File: dbextstest.py

package info (click to toggle)
jython 2.1.0-20
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 9,388 kB
  • ctags: 12,215
  • sloc: java: 48,499; python: 16,220; xml: 403; makefile: 189; perl: 103; ansic: 24; sh: 14
file content (248 lines) | stat: -rw-r--r-- 7,944 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

# Jython Database Specification API 2.0
#
# $Id: dbextstest.py,v 1.2 2001/12/29 07:16:55 bzimmer Exp $
#
# Copyright (c) 2001 brian zimmer <bzimmer@ziclix.com>

import dbexts, runner, tempfile, os
from random import random

class dbextsTestCase(runner.SQLTestCase):

	def setUp(self):
		template = """
			[default]
			name=dbexts_test

			[jdbc]
			name=dbexts_test
			url=%s
			user=%s
			pwd=%s
			driver=%s
		"""

		args = {}
		for arg in self.factory.arguments:
			args[arg[0]] = arg[1]

		template = template % (args["url"], args["usr"], args["pwd"], args["driver"])
		if hasattr(self, "datahandler"):
			template += "\tdatahandler=%s" % (self.datahandler.__name__)
		template = os.linesep.join(template.split())

		try:
			fp = open(tempfile.mktemp(), "w")
			fp.write(template)
			fp.close()
			self.db = dbexts.dbexts(cfg=fp.name)
			self.db.verbose = 0
			self.db.raw("create table one (a int, b int, c varchar(32))")
			self.db.raw("create table two (a int, b int, c varchar(32))")
		finally:
			try:
				os.remove(fp.name)
			except:
				pass

	def tearDown(self):
		self.db.raw("drop table one")
		self.db.raw("drop table two")
		self.db.close()

	def testChoose(self):
		"""testing choose()"""
		r = dbexts.choose(1, 4, 5)
		assert r == 4, "choose failed, expected 4, got %d" % r

	def _insertInto(self, table, num):
		for i in range(0, num):
			self.db.raw("insert into %s (a, b, c) values (?, ?, ?)" % (table), [(i, random()*100+i, "%s" % (random()*100+i))])

	def testSqlFailure(self):
		"""testing isql with sql exception"""
		try:
			self.db.isql("select * from __garbage__")
			self.fail("expected SQL exception")
		except:
			pass

	def testSqlFailureWithBeginCommit(self):
		"""testing failure with begin/commit"""
		failed = 0
		c = self.db.begin()
		try:
			try:
				c.execute("select * from __garbage__")
			except:
				failed = 1
		finally:
			self.db.commit(c)
			c.close()

		if not failed:
			self.fail("expected SQL exception")

	def testSqlWithBeginCommit(self):
		"""testing begin/commit"""
		self._insertInto("two", 30)
		c = self.db.begin()
		c.execute("select * from two")
		f = c.fetchall()
		c.close()
		self.db.commit()
		assert len(f) == 30, "expected [30], got [%d]" % (len(f))

	def testQueryMultipleReturnSets(self):
		"""testing multiple return sets"""
		self._insertInto("two", 30)
		h, r = self.db.raw("select * from two where a = ?", [(0,), (3,)])
		assert len(r) == 2, "expected [2], got [%d]" % (len(r))

	def testUpdateCount(self):
		"""testing update count"""

		self._insertInto("one", 45)
		self.db.raw("delete from one where a > ?", [(12,)])
		self.assertEquals(32, self.db.updatecount)

	def testQueryWithMaxRows(self):
		"""testing query with max rows"""

		self._insertInto("one", 45)
		self.db.raw("select * from one where a > ?", [(12,)], maxrows=3)
		assert len(self.db.results) == 3, "failed to query set number of max rows, got [%d], expected [%d]" % (len(self.db.results), 3)

	def testBulkcopy(self):
		"""testing bcp"""

		self._insertInto("two", 3)

		bcp = self.db.bulkcopy("dbexts_test", "two", include=['a'])
		assert len(bcp.columns) == 1, "one column should be specified, [%d] found" % (len(bcp.columns))

		bcp = self.db.bulkcopy("dbexts_test", "two", include=['a', 'b', 'c'], exclude=['a'])
		assert len(bcp.columns) == 2, "expected two columns, found [%d]" % (len(bcp.columns))
		a = filter(lambda x, c=bcp.columns: x in c, ['b', 'c'])
		assert a, "expecting ['b', 'c'], found %s" % (str(a))

		class _executor:
			def __init__(self, table, cols):
				self.cols = cols
				if cols:
					self.sql = "insert into %s (%s) values (%s)" % (table, ",".join(self.cols), ",".join(("?",) * len(self.cols)))
				else:
					self.sql = "insert into %s values (%%s)" % (table)
			def execute(self, db, rows, bindings):
				assert len(rows) > 0, "must have at least one row"
				if self.cols:
					sql = self.sql
				else:
					sql = self.sql % (",".join(("?",) * len(rows[0])))

		bcp = self.db.bulkcopy("dbexts_test", "two", include=['a'], executor=_executor)
		done = bcp.transfer(self.db)
		assert done == 3, "expecting three rows to be handled but not inserted, found [%d]" % (done)

		bcp = self.db.bulkcopy("dbexts_test", "two", include=['a'])
		done = bcp.transfer(self.db)
		assert done == 3, "expecting three rows to be inserted, found [%d]" % (done)

		bcp = self.db.bulkcopy("dbexts_test", "two", include=['a'])
		bcp.rowxfer([200])
		bcp.rowxfer([201])
		bcp.rowxfer([202])
		bcp.rowxfer([203])
		done = bcp.batch()
		assert done == 4, "expecting four rows to be inserted, found [%d]" % (done)
		bcp.rowxfer([300])
		bcp.rowxfer([401])
		bcp.rowxfer([502])
		bcp.rowxfer([603])
		done = bcp.batch()
		assert done == 4, "expecting four rows to be inserted, found [%d]" % (done)
		bcp.rowxfer([205])
		bcp.rowxfer([210])
		done = bcp.done()
		assert done == 2, "expecting two rows to be inserted, found [%d]" % (done)
		assert bcp.total == 10, "expecting 10 rows to be inserted, found [%d]" % (bcp.total)

		bcp = self.db.bulkcopy("dbexts_test", "two", include=['a'])
		done = bcp.transfer(self.db)
		assert done == 16, "expecting sixteen rows to be inserted, found [%d]" % (done)

	def testTable(self):
		"""testing dbexts.table(tabname)"""
		self.db.table("one")
		assert not self.db.results == None, "results were None"
		self.assertEquals(3, len(self.db.results))

	def testOut(self):
		"""testing dbexts.out"""
		self.db.verbose = 1
		fp = open(tempfile.mktemp(), "w")
		try:
			self.db.out = fp
			self.db.raw("insert into one (a, b) values (?, ?)", [(1, 2), (3, 4)])
			self.db.isql("select * from one")
			self.db.verbose = 0
			fp.close()
			fp = open(fp.name, "r")
			data = fp.read()
			assert len(data), "expected file to contain output"
		finally:
			fp.close()
			os.remove(fp.name)

	def testResultSetWrapper(self):
		"""testing result set wrapper"""
		from dbexts import ResultSet
		self._insertInto("two", 30)
		h, r = self.db.raw("select * from two where a in (?, ?, ?, ?) order by a", [(12,15,17,8)])
		assert len(r) == 4, "expected [4], got [%d]" % (len(r))
		rs = ResultSet(map(lambda x: x[0], h), r)
		assert len(rs[0]) == 3, "expected [3], got [%d]" % (len(rs[0]))
		assert rs[0]['a'] == 8, "expected [8], got [%s]" % (rs[0]['a'])
		assert rs[0]['A'] == 8, "expected [8], got [%s]" % (rs[0]['A'])
		assert len(rs[0]['b':]) == 2, "expected [2], got [%s]" % (len(rs[0]['b':]))
		assert len(rs[0]['a':'b']) == 1, "expected [1], got [%s]" % (len(rs[0]['a':'b']))

	def testMultipleResultSetConcatentation(self):
		"""testing multiple result sets with some resulting in None"""
		self._insertInto("two", 30)
		# first is non None
		h, r = self.db.raw("select * from two where a = ?", [(12,),(8001,),(15,),(17,),(8,),(9001,)])
		assert len(r) == 4, "expected [4], got [%d]" % (len(r))
		# first is None
		h, r = self.db.raw("select * from two where a = ?", [(1200,),(8001,),(15,),(17,),(8,),(9001,)])
		assert len(r) == 3, "expected [3], got [%d]" % (len(r))

	def testBulkcopyWithDynamicColumns(self):
		"""testing bcp with dynamic column names"""

		self.testBulkcopy()

		bcp = self.db.bulkcopy("dbexts_test", "two", exclude=['a'])
		assert len(bcp.columns) == 2, "expected two columns, found [%d]" % (len(bcp.columns))
		a = filter(lambda x, c=bcp.columns: x in c, ['b', 'c'])
		assert a == ['b', 'c'], "expecting ['b', 'c'], found %s" % (str(a))

		bcp = self.db.bulkcopy("dbexts_test", "two")
		done = bcp.transfer(self.db)
		assert done == 32, "expecting thirty two rows to be inserted, found [%d]" % (done)

	def testAutocommit(self):
		"""testing the autocommit functionality"""
		for u in (0, 1):
			self.db.autocommit = u
			try:
				self.db.isql("select * from one")
			except Exception, e:
				fail("failed autocommit query with u=[%d], v=[%d]" % (u, v))
			for v in (0, 1):
				self.db.db.autocommit = v
				try:
					self.db.isql("select * from one")
				except Exception, e:
					fail("failed autocommit query with u=[%d], v=[%d]" % (u, v))