Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dbapi20.py 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. #!/usr/bin/env python
  2. """ Python DB API 2.0 driver compliance unit test suite.
  3. This software is Public Domain and may be used without restrictions.
  4. "Now we have booze and barflies entering the discussion, plus rumours of
  5. DBAs on drugs... and I won't tell you what flashes through my mind each
  6. time I read the subject line with 'Anal Compliance' in it. All around
  7. this is turning out to be a thoroughly unwholesome unit test."
  8. -- Ian Bicking
  9. """
  10. __version__ = "$Revision: 1.15.0 $"[11:-2]
  11. __author__ = "Stuart Bishop <stuart@stuartbishop.net>"
  12. import sys
  13. import time
  14. import unittest
  15. if sys.version[0] >= "3": # python 3.x
  16. _BaseException = Exception
  17. def _failUnless(self, expr, msg=None):
  18. self.assertTrue(expr, msg)
  19. else: # python 2.x
  20. from exceptions import Exception as _BaseException
  21. def _failUnless(self, expr, msg=None):
  22. self.failUnless(expr, msg) ## deprecated since Python 2.6
  23. # set this to "True" to follow API 2.0 to the letter
  24. TEST_FOR_NON_IDEMPOTENT_CLOSE = False
  25. # Revision 1.15 2019/11/22 00:50:00 kf7xm
  26. # Make Turn off IDEMPOTENT_CLOSE a proper skipTest
  27. # Revision 1.14 2013/05/20 11:02:05 kf7xm
  28. # Add a literal string to the format insertion test to catch trivial re-format algorithms
  29. # Revision 1.13 2013/05/08 14:31:50 kf7xm
  30. # Quick switch to Turn off IDEMPOTENT_CLOSE test. Also: Silence teardown failure
  31. # Revision 1.12 2009/02/06 03:35:11 kf7xm
  32. # Tested okay with Python 3.0, includes last minute patches from Mark H.
  33. #
  34. # Revision 1.1.1.1.2.1 2008/09/20 19:54:59 rupole
  35. # Include latest changes from main branch
  36. # Updates for py3k
  37. #
  38. # Revision 1.11 2005/01/02 02:41:01 zenzen
  39. # Update author email address
  40. #
  41. # Revision 1.10 2003/10/09 03:14:14 zenzen
  42. # Add test for DB API 2.0 optional extension, where database exceptions
  43. # are exposed as attributes on the Connection object.
  44. #
  45. # Revision 1.9 2003/08/13 01:16:36 zenzen
  46. # Minor tweak from Stefan Fleiter
  47. #
  48. # Revision 1.8 2003/04/10 00:13:25 zenzen
  49. # Changes, as per suggestions by M.-A. Lemburg
  50. # - Add a table prefix, to ensure namespace collisions can always be avoided
  51. #
  52. # Revision 1.7 2003/02/26 23:33:37 zenzen
  53. # Break out DDL into helper functions, as per request by David Rushby
  54. #
  55. # Revision 1.6 2003/02/21 03:04:33 zenzen
  56. # Stuff from Henrik Ekelund:
  57. # added test_None
  58. # added test_nextset & hooks
  59. #
  60. # Revision 1.5 2003/02/17 22:08:43 zenzen
  61. # Implement suggestions and code from Henrik Eklund - test that cursor.arraysize
  62. # defaults to 1 & generic cursor.callproc test added
  63. #
  64. # Revision 1.4 2003/02/15 00:16:33 zenzen
  65. # Changes, as per suggestions and bug reports by M.-A. Lemburg,
  66. # Matthew T. Kromer, Federico Di Gregorio and Daniel Dittmar
  67. # - Class renamed
  68. # - Now a subclass of TestCase, to avoid requiring the driver stub
  69. # to use multiple inheritance
  70. # - Reversed the polarity of buggy test in test_description
  71. # - Test exception heirarchy correctly
  72. # - self.populate is now self._populate(), so if a driver stub
  73. # overrides self.ddl1 this change propogates
  74. # - VARCHAR columns now have a width, which will hopefully make the
  75. # DDL even more portible (this will be reversed if it causes more problems)
  76. # - cursor.rowcount being checked after various execute and fetchXXX methods
  77. # - Check for fetchall and fetchmany returning empty lists after results
  78. # are exhausted (already checking for empty lists if select retrieved
  79. # nothing
  80. # - Fix bugs in test_setoutputsize_basic and test_setinputsizes
  81. #
  82. def str2bytes(sval):
  83. if sys.version_info < (3, 0) and isinstance(sval, str):
  84. sval = sval.decode("latin1")
  85. return sval.encode("latin1") # python 3 make unicode into bytes
  86. class DatabaseAPI20Test(unittest.TestCase):
  87. """Test a database self.driver for DB API 2.0 compatibility.
  88. This implementation tests Gadfly, but the TestCase
  89. is structured so that other self.drivers can subclass this
  90. test case to ensure compiliance with the DB-API. It is
  91. expected that this TestCase may be expanded in the future
  92. if ambiguities or edge conditions are discovered.
  93. The 'Optional Extensions' are not yet being tested.
  94. self.drivers should subclass this test, overriding setUp, tearDown,
  95. self.driver, connect_args and connect_kw_args. Class specification
  96. should be as follows:
  97. import dbapi20
  98. class mytest(dbapi20.DatabaseAPI20Test):
  99. [...]
  100. Don't 'import DatabaseAPI20Test from dbapi20', or you will
  101. confuse the unit tester - just 'import dbapi20'.
  102. """
  103. # The self.driver module. This should be the module where the 'connect'
  104. # method is to be found
  105. driver = None
  106. connect_args = () # List of arguments to pass to connect
  107. connect_kw_args = {} # Keyword arguments for connect
  108. table_prefix = "dbapi20test_" # If you need to specify a prefix for tables
  109. ddl1 = "create table %sbooze (name varchar(20))" % table_prefix
  110. ddl2 = "create table %sbarflys (name varchar(20), drink varchar(30))" % table_prefix
  111. xddl1 = "drop table %sbooze" % table_prefix
  112. xddl2 = "drop table %sbarflys" % table_prefix
  113. lowerfunc = "lower" # Name of stored procedure to convert string->lowercase
  114. # Some drivers may need to override these helpers, for example adding
  115. # a 'commit' after the execute.
  116. def executeDDL1(self, cursor):
  117. cursor.execute(self.ddl1)
  118. def executeDDL2(self, cursor):
  119. cursor.execute(self.ddl2)
  120. def setUp(self):
  121. """self.drivers should override this method to perform required setup
  122. if any is necessary, such as creating the database.
  123. """
  124. pass
  125. def tearDown(self):
  126. """self.drivers should override this method to perform required cleanup
  127. if any is necessary, such as deleting the test database.
  128. The default drops the tables that may be created.
  129. """
  130. try:
  131. con = self._connect()
  132. try:
  133. cur = con.cursor()
  134. for ddl in (self.xddl1, self.xddl2):
  135. try:
  136. cur.execute(ddl)
  137. con.commit()
  138. except self.driver.Error:
  139. # Assume table didn't exist. Other tests will check if
  140. # execute is busted.
  141. pass
  142. finally:
  143. con.close()
  144. except _BaseException:
  145. pass
  146. def _connect(self):
  147. try:
  148. r = self.driver.connect(*self.connect_args, **self.connect_kw_args)
  149. except AttributeError:
  150. self.fail("No connect method found in self.driver module")
  151. return r
  152. def test_connect(self):
  153. con = self._connect()
  154. con.close()
  155. def test_apilevel(self):
  156. try:
  157. # Must exist
  158. apilevel = self.driver.apilevel
  159. # Must equal 2.0
  160. self.assertEqual(apilevel, "2.0")
  161. except AttributeError:
  162. self.fail("Driver doesn't define apilevel")
  163. def test_threadsafety(self):
  164. try:
  165. # Must exist
  166. threadsafety = self.driver.threadsafety
  167. # Must be a valid value
  168. _failUnless(self, threadsafety in (0, 1, 2, 3))
  169. except AttributeError:
  170. self.fail("Driver doesn't define threadsafety")
  171. def test_paramstyle(self):
  172. try:
  173. # Must exist
  174. paramstyle = self.driver.paramstyle
  175. # Must be a valid value
  176. _failUnless(
  177. self, paramstyle in ("qmark", "numeric", "named", "format", "pyformat")
  178. )
  179. except AttributeError:
  180. self.fail("Driver doesn't define paramstyle")
  181. def test_Exceptions(self):
  182. # Make sure required exceptions exist, and are in the
  183. # defined heirarchy.
  184. if sys.version[0] == "3": # under Python 3 StardardError no longer exists
  185. self.assertTrue(issubclass(self.driver.Warning, Exception))
  186. self.assertTrue(issubclass(self.driver.Error, Exception))
  187. else:
  188. self.failUnless(issubclass(self.driver.Warning, Exception))
  189. self.failUnless(issubclass(self.driver.Error, Exception))
  190. _failUnless(self, issubclass(self.driver.InterfaceError, self.driver.Error))
  191. _failUnless(self, issubclass(self.driver.DatabaseError, self.driver.Error))
  192. _failUnless(self, issubclass(self.driver.OperationalError, self.driver.Error))
  193. _failUnless(self, issubclass(self.driver.IntegrityError, self.driver.Error))
  194. _failUnless(self, issubclass(self.driver.InternalError, self.driver.Error))
  195. _failUnless(self, issubclass(self.driver.ProgrammingError, self.driver.Error))
  196. _failUnless(self, issubclass(self.driver.NotSupportedError, self.driver.Error))
  197. def test_ExceptionsAsConnectionAttributes(self):
  198. # OPTIONAL EXTENSION
  199. # Test for the optional DB API 2.0 extension, where the exceptions
  200. # are exposed as attributes on the Connection object
  201. # I figure this optional extension will be implemented by any
  202. # driver author who is using this test suite, so it is enabled
  203. # by default.
  204. con = self._connect()
  205. drv = self.driver
  206. _failUnless(self, con.Warning is drv.Warning)
  207. _failUnless(self, con.Error is drv.Error)
  208. _failUnless(self, con.InterfaceError is drv.InterfaceError)
  209. _failUnless(self, con.DatabaseError is drv.DatabaseError)
  210. _failUnless(self, con.OperationalError is drv.OperationalError)
  211. _failUnless(self, con.IntegrityError is drv.IntegrityError)
  212. _failUnless(self, con.InternalError is drv.InternalError)
  213. _failUnless(self, con.ProgrammingError is drv.ProgrammingError)
  214. _failUnless(self, con.NotSupportedError is drv.NotSupportedError)
  215. def test_commit(self):
  216. con = self._connect()
  217. try:
  218. # Commit must work, even if it doesn't do anything
  219. con.commit()
  220. finally:
  221. con.close()
  222. def test_rollback(self):
  223. con = self._connect()
  224. # If rollback is defined, it should either work or throw
  225. # the documented exception
  226. if hasattr(con, "rollback"):
  227. try:
  228. con.rollback()
  229. except self.driver.NotSupportedError:
  230. pass
  231. def test_cursor(self):
  232. con = self._connect()
  233. try:
  234. cur = con.cursor()
  235. finally:
  236. con.close()
  237. def test_cursor_isolation(self):
  238. con = self._connect()
  239. try:
  240. # Make sure cursors created from the same connection have
  241. # the documented transaction isolation level
  242. cur1 = con.cursor()
  243. cur2 = con.cursor()
  244. self.executeDDL1(cur1)
  245. cur1.execute(
  246. "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix)
  247. )
  248. cur2.execute("select name from %sbooze" % self.table_prefix)
  249. booze = cur2.fetchall()
  250. self.assertEqual(len(booze), 1)
  251. self.assertEqual(len(booze[0]), 1)
  252. self.assertEqual(booze[0][0], "Victoria Bitter")
  253. finally:
  254. con.close()
  255. def test_description(self):
  256. con = self._connect()
  257. try:
  258. cur = con.cursor()
  259. self.executeDDL1(cur)
  260. self.assertEqual(
  261. cur.description,
  262. None,
  263. "cursor.description should be none after executing a "
  264. "statement that can return no rows (such as DDL)",
  265. )
  266. cur.execute("select name from %sbooze" % self.table_prefix)
  267. self.assertEqual(
  268. len(cur.description), 1, "cursor.description describes too many columns"
  269. )
  270. self.assertEqual(
  271. len(cur.description[0]),
  272. 7,
  273. "cursor.description[x] tuples must have 7 elements",
  274. )
  275. self.assertEqual(
  276. cur.description[0][0].lower(),
  277. "name",
  278. "cursor.description[x][0] must return column name",
  279. )
  280. self.assertEqual(
  281. cur.description[0][1],
  282. self.driver.STRING,
  283. "cursor.description[x][1] must return column type. Got %r"
  284. % cur.description[0][1],
  285. )
  286. # Make sure self.description gets reset
  287. self.executeDDL2(cur)
  288. self.assertEqual(
  289. cur.description,
  290. None,
  291. "cursor.description not being set to None when executing "
  292. "no-result statements (eg. DDL)",
  293. )
  294. finally:
  295. con.close()
  296. def test_rowcount(self):
  297. con = self._connect()
  298. try:
  299. cur = con.cursor()
  300. self.executeDDL1(cur)
  301. _failUnless(
  302. self,
  303. cur.rowcount in (-1, 0), # Bug #543885
  304. "cursor.rowcount should be -1 or 0 after executing no-result "
  305. "statements",
  306. )
  307. cur.execute(
  308. "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix)
  309. )
  310. _failUnless(
  311. self,
  312. cur.rowcount in (-1, 1),
  313. "cursor.rowcount should == number or rows inserted, or "
  314. "set to -1 after executing an insert statement",
  315. )
  316. cur.execute("select name from %sbooze" % self.table_prefix)
  317. _failUnless(
  318. self,
  319. cur.rowcount in (-1, 1),
  320. "cursor.rowcount should == number of rows returned, or "
  321. "set to -1 after executing a select statement",
  322. )
  323. self.executeDDL2(cur)
  324. self.assertEqual(
  325. cur.rowcount,
  326. -1,
  327. "cursor.rowcount not being reset to -1 after executing "
  328. "no-result statements",
  329. )
  330. finally:
  331. con.close()
  332. lower_func = "lower"
  333. def test_callproc(self):
  334. con = self._connect()
  335. try:
  336. cur = con.cursor()
  337. if self.lower_func and hasattr(cur, "callproc"):
  338. r = cur.callproc(self.lower_func, ("FOO",))
  339. self.assertEqual(len(r), 1)
  340. self.assertEqual(r[0], "FOO")
  341. r = cur.fetchall()
  342. self.assertEqual(len(r), 1, "callproc produced no result set")
  343. self.assertEqual(len(r[0]), 1, "callproc produced invalid result set")
  344. self.assertEqual(r[0][0], "foo", "callproc produced invalid results")
  345. finally:
  346. con.close()
  347. def test_close(self):
  348. con = self._connect()
  349. try:
  350. cur = con.cursor()
  351. finally:
  352. con.close()
  353. # cursor.execute should raise an Error if called after connection
  354. # closed
  355. self.assertRaises(self.driver.Error, self.executeDDL1, cur)
  356. # connection.commit should raise an Error if called after connection'
  357. # closed.'
  358. self.assertRaises(self.driver.Error, con.commit)
  359. # connection.close should raise an Error if called more than once
  360. #!!! reasonable persons differ about the usefulness of this test and this feature !!!
  361. if TEST_FOR_NON_IDEMPOTENT_CLOSE:
  362. self.assertRaises(self.driver.Error, con.close)
  363. else:
  364. self.skipTest(
  365. "Non-idempotent close is considered a bad thing by some people."
  366. )
  367. def test_execute(self):
  368. con = self._connect()
  369. try:
  370. cur = con.cursor()
  371. self._paraminsert(cur)
  372. finally:
  373. con.close()
  374. def _paraminsert(self, cur):
  375. self.executeDDL2(cur)
  376. cur.execute(
  377. "insert into %sbarflys values ('Victoria Bitter', 'thi%%s :may ca%%(u)se? troub:1e')"
  378. % (self.table_prefix)
  379. )
  380. _failUnless(self, cur.rowcount in (-1, 1))
  381. if self.driver.paramstyle == "qmark":
  382. cur.execute(
  383. "insert into %sbarflys values (?, 'thi%%s :may ca%%(u)se? troub:1e')"
  384. % self.table_prefix,
  385. ("Cooper's",),
  386. )
  387. elif self.driver.paramstyle == "numeric":
  388. cur.execute(
  389. "insert into %sbarflys values (:1, 'thi%%s :may ca%%(u)se? troub:1e')"
  390. % self.table_prefix,
  391. ("Cooper's",),
  392. )
  393. elif self.driver.paramstyle == "named":
  394. cur.execute(
  395. "insert into %sbarflys values (:beer, 'thi%%s :may ca%%(u)se? troub:1e')"
  396. % self.table_prefix,
  397. {"beer": "Cooper's"},
  398. )
  399. elif self.driver.paramstyle == "format":
  400. cur.execute(
  401. "insert into %sbarflys values (%%s, 'thi%%s :may ca%%(u)se? troub:1e')"
  402. % self.table_prefix,
  403. ("Cooper's",),
  404. )
  405. elif self.driver.paramstyle == "pyformat":
  406. cur.execute(
  407. "insert into %sbarflys values (%%(beer)s, 'thi%%s :may ca%%(u)se? troub:1e')"
  408. % self.table_prefix,
  409. {"beer": "Cooper's"},
  410. )
  411. else:
  412. self.fail("Invalid paramstyle")
  413. _failUnless(self, cur.rowcount in (-1, 1))
  414. cur.execute("select name, drink from %sbarflys" % self.table_prefix)
  415. res = cur.fetchall()
  416. self.assertEqual(len(res), 2, "cursor.fetchall returned too few rows")
  417. beers = [res[0][0], res[1][0]]
  418. beers.sort()
  419. self.assertEqual(
  420. beers[0],
  421. "Cooper's",
  422. "cursor.fetchall retrieved incorrect data, or data inserted " "incorrectly",
  423. )
  424. self.assertEqual(
  425. beers[1],
  426. "Victoria Bitter",
  427. "cursor.fetchall retrieved incorrect data, or data inserted " "incorrectly",
  428. )
  429. trouble = "thi%s :may ca%(u)se? troub:1e"
  430. self.assertEqual(
  431. res[0][1],
  432. trouble,
  433. "cursor.fetchall retrieved incorrect data, or data inserted "
  434. "incorrectly. Got=%s, Expected=%s" % (repr(res[0][1]), repr(trouble)),
  435. )
  436. self.assertEqual(
  437. res[1][1],
  438. trouble,
  439. "cursor.fetchall retrieved incorrect data, or data inserted "
  440. "incorrectly. Got=%s, Expected=%s" % (repr(res[1][1]), repr(trouble)),
  441. )
  442. def test_executemany(self):
  443. con = self._connect()
  444. try:
  445. cur = con.cursor()
  446. self.executeDDL1(cur)
  447. largs = [("Cooper's",), ("Boag's",)]
  448. margs = [{"beer": "Cooper's"}, {"beer": "Boag's"}]
  449. if self.driver.paramstyle == "qmark":
  450. cur.executemany(
  451. "insert into %sbooze values (?)" % self.table_prefix, largs
  452. )
  453. elif self.driver.paramstyle == "numeric":
  454. cur.executemany(
  455. "insert into %sbooze values (:1)" % self.table_prefix, largs
  456. )
  457. elif self.driver.paramstyle == "named":
  458. cur.executemany(
  459. "insert into %sbooze values (:beer)" % self.table_prefix, margs
  460. )
  461. elif self.driver.paramstyle == "format":
  462. cur.executemany(
  463. "insert into %sbooze values (%%s)" % self.table_prefix, largs
  464. )
  465. elif self.driver.paramstyle == "pyformat":
  466. cur.executemany(
  467. "insert into %sbooze values (%%(beer)s)" % (self.table_prefix),
  468. margs,
  469. )
  470. else:
  471. self.fail("Unknown paramstyle")
  472. _failUnless(
  473. self,
  474. cur.rowcount in (-1, 2),
  475. "insert using cursor.executemany set cursor.rowcount to "
  476. "incorrect value %r" % cur.rowcount,
  477. )
  478. cur.execute("select name from %sbooze" % self.table_prefix)
  479. res = cur.fetchall()
  480. self.assertEqual(
  481. len(res), 2, "cursor.fetchall retrieved incorrect number of rows"
  482. )
  483. beers = [res[0][0], res[1][0]]
  484. beers.sort()
  485. self.assertEqual(
  486. beers[0], "Boag's", 'incorrect data "%s" retrieved' % beers[0]
  487. )
  488. self.assertEqual(beers[1], "Cooper's", "incorrect data retrieved")
  489. finally:
  490. con.close()
  491. def test_fetchone(self):
  492. con = self._connect()
  493. try:
  494. cur = con.cursor()
  495. # cursor.fetchone should raise an Error if called before
  496. # executing a select-type query
  497. self.assertRaises(self.driver.Error, cur.fetchone)
  498. # cursor.fetchone should raise an Error if called after
  499. # executing a query that cannnot return rows
  500. self.executeDDL1(cur)
  501. self.assertRaises(self.driver.Error, cur.fetchone)
  502. cur.execute("select name from %sbooze" % self.table_prefix)
  503. self.assertEqual(
  504. cur.fetchone(),
  505. None,
  506. "cursor.fetchone should return None if a query retrieves " "no rows",
  507. )
  508. _failUnless(self, cur.rowcount in (-1, 0))
  509. # cursor.fetchone should raise an Error if called after
  510. # executing a query that cannnot return rows
  511. cur.execute(
  512. "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix)
  513. )
  514. self.assertRaises(self.driver.Error, cur.fetchone)
  515. cur.execute("select name from %sbooze" % self.table_prefix)
  516. r = cur.fetchone()
  517. self.assertEqual(
  518. len(r), 1, "cursor.fetchone should have retrieved a single row"
  519. )
  520. self.assertEqual(
  521. r[0], "Victoria Bitter", "cursor.fetchone retrieved incorrect data"
  522. )
  523. self.assertEqual(
  524. cur.fetchone(),
  525. None,
  526. "cursor.fetchone should return None if no more rows available",
  527. )
  528. _failUnless(self, cur.rowcount in (-1, 1))
  529. finally:
  530. con.close()
  531. samples = [
  532. "Carlton Cold",
  533. "Carlton Draft",
  534. "Mountain Goat",
  535. "Redback",
  536. "Victoria Bitter",
  537. "XXXX",
  538. ]
  539. def _populate(self):
  540. """Return a list of sql commands to setup the DB for the fetch
  541. tests.
  542. """
  543. populate = [
  544. "insert into %sbooze values ('%s')" % (self.table_prefix, s)
  545. for s in self.samples
  546. ]
  547. return populate
  548. def test_fetchmany(self):
  549. con = self._connect()
  550. try:
  551. cur = con.cursor()
  552. # cursor.fetchmany should raise an Error if called without
  553. # issuing a query
  554. self.assertRaises(self.driver.Error, cur.fetchmany, 4)
  555. self.executeDDL1(cur)
  556. for sql in self._populate():
  557. cur.execute(sql)
  558. cur.execute("select name from %sbooze" % self.table_prefix)
  559. r = cur.fetchmany()
  560. self.assertEqual(
  561. len(r),
  562. 1,
  563. "cursor.fetchmany retrieved incorrect number of rows, "
  564. "default of arraysize is one.",
  565. )
  566. cur.arraysize = 10
  567. r = cur.fetchmany(3) # Should get 3 rows
  568. self.assertEqual(
  569. len(r), 3, "cursor.fetchmany retrieved incorrect number of rows"
  570. )
  571. r = cur.fetchmany(4) # Should get 2 more
  572. self.assertEqual(
  573. len(r), 2, "cursor.fetchmany retrieved incorrect number of rows"
  574. )
  575. r = cur.fetchmany(4) # Should be an empty sequence
  576. self.assertEqual(
  577. len(r),
  578. 0,
  579. "cursor.fetchmany should return an empty sequence after "
  580. "results are exhausted",
  581. )
  582. _failUnless(self, cur.rowcount in (-1, 6))
  583. # Same as above, using cursor.arraysize
  584. cur.arraysize = 4
  585. cur.execute("select name from %sbooze" % self.table_prefix)
  586. r = cur.fetchmany() # Should get 4 rows
  587. self.assertEqual(
  588. len(r), 4, "cursor.arraysize not being honoured by fetchmany"
  589. )
  590. r = cur.fetchmany() # Should get 2 more
  591. self.assertEqual(len(r), 2)
  592. r = cur.fetchmany() # Should be an empty sequence
  593. self.assertEqual(len(r), 0)
  594. _failUnless(self, cur.rowcount in (-1, 6))
  595. cur.arraysize = 6
  596. cur.execute("select name from %sbooze" % self.table_prefix)
  597. rows = cur.fetchmany() # Should get all rows
  598. _failUnless(self, cur.rowcount in (-1, 6))
  599. self.assertEqual(len(rows), 6)
  600. self.assertEqual(len(rows), 6)
  601. rows = [r[0] for r in rows]
  602. rows.sort()
  603. # Make sure we get the right data back out
  604. for i in range(0, 6):
  605. self.assertEqual(
  606. rows[i],
  607. self.samples[i],
  608. "incorrect data retrieved by cursor.fetchmany",
  609. )
  610. rows = cur.fetchmany() # Should return an empty list
  611. self.assertEqual(
  612. len(rows),
  613. 0,
  614. "cursor.fetchmany should return an empty sequence if "
  615. "called after the whole result set has been fetched",
  616. )
  617. _failUnless(self, cur.rowcount in (-1, 6))
  618. self.executeDDL2(cur)
  619. cur.execute("select name from %sbarflys" % self.table_prefix)
  620. r = cur.fetchmany() # Should get empty sequence
  621. self.assertEqual(
  622. len(r),
  623. 0,
  624. "cursor.fetchmany should return an empty sequence if "
  625. "query retrieved no rows",
  626. )
  627. _failUnless(self, cur.rowcount in (-1, 0))
  628. finally:
  629. con.close()
  630. def test_fetchall(self):
  631. con = self._connect()
  632. try:
  633. cur = con.cursor()
  634. # cursor.fetchall should raise an Error if called
  635. # without executing a query that may return rows (such
  636. # as a select)
  637. self.assertRaises(self.driver.Error, cur.fetchall)
  638. self.executeDDL1(cur)
  639. for sql in self._populate():
  640. cur.execute(sql)
  641. # cursor.fetchall should raise an Error if called
  642. # after executing a a statement that cannot return rows
  643. self.assertRaises(self.driver.Error, cur.fetchall)
  644. cur.execute("select name from %sbooze" % self.table_prefix)
  645. rows = cur.fetchall()
  646. _failUnless(self, cur.rowcount in (-1, len(self.samples)))
  647. self.assertEqual(
  648. len(rows),
  649. len(self.samples),
  650. "cursor.fetchall did not retrieve all rows",
  651. )
  652. rows = [r[0] for r in rows]
  653. rows.sort()
  654. for i in range(0, len(self.samples)):
  655. self.assertEqual(
  656. rows[i], self.samples[i], "cursor.fetchall retrieved incorrect rows"
  657. )
  658. rows = cur.fetchall()
  659. self.assertEqual(
  660. len(rows),
  661. 0,
  662. "cursor.fetchall should return an empty list if called "
  663. "after the whole result set has been fetched",
  664. )
  665. _failUnless(self, cur.rowcount in (-1, len(self.samples)))
  666. self.executeDDL2(cur)
  667. cur.execute("select name from %sbarflys" % self.table_prefix)
  668. rows = cur.fetchall()
  669. _failUnless(self, cur.rowcount in (-1, 0))
  670. self.assertEqual(
  671. len(rows),
  672. 0,
  673. "cursor.fetchall should return an empty list if "
  674. "a select query returns no rows",
  675. )
  676. finally:
  677. con.close()
  678. def test_mixedfetch(self):
  679. con = self._connect()
  680. try:
  681. cur = con.cursor()
  682. self.executeDDL1(cur)
  683. for sql in self._populate():
  684. cur.execute(sql)
  685. cur.execute("select name from %sbooze" % self.table_prefix)
  686. rows1 = cur.fetchone()
  687. rows23 = cur.fetchmany(2)
  688. rows4 = cur.fetchone()
  689. rows56 = cur.fetchall()
  690. _failUnless(self, cur.rowcount in (-1, 6))
  691. self.assertEqual(
  692. len(rows23), 2, "fetchmany returned incorrect number of rows"
  693. )
  694. self.assertEqual(
  695. len(rows56), 2, "fetchall returned incorrect number of rows"
  696. )
  697. rows = [rows1[0]]
  698. rows.extend([rows23[0][0], rows23[1][0]])
  699. rows.append(rows4[0])
  700. rows.extend([rows56[0][0], rows56[1][0]])
  701. rows.sort()
  702. for i in range(0, len(self.samples)):
  703. self.assertEqual(
  704. rows[i], self.samples[i], "incorrect data retrieved or inserted"
  705. )
  706. finally:
  707. con.close()
  708. def help_nextset_setUp(self, cur):
  709. """Should create a procedure called deleteme
  710. that returns two result sets, first the
  711. number of rows in booze then "name from booze"
  712. """
  713. raise NotImplementedError("Helper not implemented")
  714. # sql="""
  715. # create procedure deleteme as
  716. # begin
  717. # select count(*) from booze
  718. # select name from booze
  719. # end
  720. # """
  721. # cur.execute(sql)
  722. def help_nextset_tearDown(self, cur):
  723. "If cleaning up is needed after nextSetTest"
  724. raise NotImplementedError("Helper not implemented")
  725. # cur.execute("drop procedure deleteme")
  726. def test_nextset(self):
  727. con = self._connect()
  728. try:
  729. cur = con.cursor()
  730. if not hasattr(cur, "nextset"):
  731. return
  732. try:
  733. self.executeDDL1(cur)
  734. sql = self._populate()
  735. for sql in self._populate():
  736. cur.execute(sql)
  737. self.help_nextset_setUp(cur)
  738. cur.callproc("deleteme")
  739. numberofrows = cur.fetchone()
  740. assert numberofrows[0] == len(self.samples)
  741. assert cur.nextset()
  742. names = cur.fetchall()
  743. assert len(names) == len(self.samples)
  744. s = cur.nextset()
  745. assert s == None, "No more return sets, should return None"
  746. finally:
  747. self.help_nextset_tearDown(cur)
  748. finally:
  749. con.close()
  750. def test_nextset(self):
  751. raise NotImplementedError("Drivers need to override this test")
  752. def test_arraysize(self):
  753. # Not much here - rest of the tests for this are in test_fetchmany
  754. con = self._connect()
  755. try:
  756. cur = con.cursor()
  757. _failUnless(
  758. self, hasattr(cur, "arraysize"), "cursor.arraysize must be defined"
  759. )
  760. finally:
  761. con.close()
  762. def test_setinputsizes(self):
  763. con = self._connect()
  764. try:
  765. cur = con.cursor()
  766. cur.setinputsizes((25,))
  767. self._paraminsert(cur) # Make sure cursor still works
  768. finally:
  769. con.close()
  770. def test_setoutputsize_basic(self):
  771. # Basic test is to make sure setoutputsize doesn't blow up
  772. con = self._connect()
  773. try:
  774. cur = con.cursor()
  775. cur.setoutputsize(1000)
  776. cur.setoutputsize(2000, 0)
  777. self._paraminsert(cur) # Make sure the cursor still works
  778. finally:
  779. con.close()
  780. def test_setoutputsize(self):
  781. # Real test for setoutputsize is driver dependant
  782. raise NotImplementedError("Driver needed to override this test")
  783. def test_None(self):
  784. con = self._connect()
  785. try:
  786. cur = con.cursor()
  787. self.executeDDL1(cur)
  788. cur.execute("insert into %sbooze values (NULL)" % self.table_prefix)
  789. cur.execute("select name from %sbooze" % self.table_prefix)
  790. r = cur.fetchall()
  791. self.assertEqual(len(r), 1)
  792. self.assertEqual(len(r[0]), 1)
  793. self.assertEqual(r[0][0], None, "NULL value not returned as None")
  794. finally:
  795. con.close()
  796. def test_Date(self):
  797. d1 = self.driver.Date(2002, 12, 25)
  798. d2 = self.driver.DateFromTicks(time.mktime((2002, 12, 25, 0, 0, 0, 0, 0, 0)))
  799. # Can we assume this? API doesn't specify, but it seems implied
  800. # self.assertEqual(str(d1),str(d2))
  801. def test_Time(self):
  802. t1 = self.driver.Time(13, 45, 30)
  803. t2 = self.driver.TimeFromTicks(time.mktime((2001, 1, 1, 13, 45, 30, 0, 0, 0)))
  804. # Can we assume this? API doesn't specify, but it seems implied
  805. # self.assertEqual(str(t1),str(t2))
  806. def test_Timestamp(self):
  807. t1 = self.driver.Timestamp(2002, 12, 25, 13, 45, 30)
  808. t2 = self.driver.TimestampFromTicks(
  809. time.mktime((2002, 12, 25, 13, 45, 30, 0, 0, 0))
  810. )
  811. # Can we assume this? API doesn't specify, but it seems implied
  812. # self.assertEqual(str(t1),str(t2))
  813. def test_Binary(self):
  814. b = self.driver.Binary(str2bytes("Something"))
  815. b = self.driver.Binary(str2bytes(""))
  816. def test_STRING(self):
  817. _failUnless(
  818. self, hasattr(self.driver, "STRING"), "module.STRING must be defined"
  819. )
  820. def test_BINARY(self):
  821. _failUnless(
  822. self, hasattr(self.driver, "BINARY"), "module.BINARY must be defined."
  823. )
  824. def test_NUMBER(self):
  825. _failUnless(
  826. self, hasattr(self.driver, "NUMBER"), "module.NUMBER must be defined."
  827. )
  828. def test_DATETIME(self):
  829. _failUnless(
  830. self, hasattr(self.driver, "DATETIME"), "module.DATETIME must be defined."
  831. )
  832. def test_ROWID(self):
  833. _failUnless(
  834. self, hasattr(self.driver, "ROWID"), "module.ROWID must be defined."
  835. )