dbapi20.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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 unittest
  13. import time
  14. import sys
  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(
  149. *self.connect_args,**self.connect_kw_args
  150. )
  151. except AttributeError:
  152. self.fail("No connect method found in self.driver module")
  153. return r
  154. def test_connect(self):
  155. con = self._connect()
  156. con.close()
  157. def test_apilevel(self):
  158. try:
  159. # Must exist
  160. apilevel = self.driver.apilevel
  161. # Must equal 2.0
  162. self.assertEqual(apilevel,'2.0')
  163. except AttributeError:
  164. self.fail("Driver doesn't define apilevel")
  165. def test_threadsafety(self):
  166. try:
  167. # Must exist
  168. threadsafety = self.driver.threadsafety
  169. # Must be a valid value
  170. _failUnless(self, threadsafety in (0,1,2,3))
  171. except AttributeError:
  172. self.fail("Driver doesn't define threadsafety")
  173. def test_paramstyle(self):
  174. try:
  175. # Must exist
  176. paramstyle = self.driver.paramstyle
  177. # Must be a valid value
  178. _failUnless(self, paramstyle in (
  179. 'qmark','numeric','named','format','pyformat'
  180. ))
  181. except AttributeError:
  182. self.fail("Driver doesn't define paramstyle")
  183. def test_Exceptions(self):
  184. # Make sure required exceptions exist, and are in the
  185. # defined heirarchy.
  186. if sys.version[0] == '3': #under Python 3 StardardError no longer exists
  187. self.assertTrue(issubclass(self.driver.Warning,Exception))
  188. self.assertTrue(issubclass(self.driver.Error,Exception))
  189. else:
  190. self.failUnless(issubclass(self.driver.Warning,Exception))
  191. self.failUnless(issubclass(self.driver.Error,Exception))
  192. _failUnless(self,
  193. issubclass(self.driver.InterfaceError,self.driver.Error)
  194. )
  195. _failUnless(self,
  196. issubclass(self.driver.DatabaseError,self.driver.Error)
  197. )
  198. _failUnless(self,
  199. issubclass(self.driver.OperationalError,self.driver.Error)
  200. )
  201. _failUnless(self,
  202. issubclass(self.driver.IntegrityError,self.driver.Error)
  203. )
  204. _failUnless(self,
  205. issubclass(self.driver.InternalError,self.driver.Error)
  206. )
  207. _failUnless(self,
  208. issubclass(self.driver.ProgrammingError,self.driver.Error)
  209. )
  210. _failUnless(self,
  211. issubclass(self.driver.NotSupportedError,self.driver.Error)
  212. )
  213. def test_ExceptionsAsConnectionAttributes(self):
  214. # OPTIONAL EXTENSION
  215. # Test for the optional DB API 2.0 extension, where the exceptions
  216. # are exposed as attributes on the Connection object
  217. # I figure this optional extension will be implemented by any
  218. # driver author who is using this test suite, so it is enabled
  219. # by default.
  220. con = self._connect()
  221. drv = self.driver
  222. _failUnless(self,con.Warning is drv.Warning)
  223. _failUnless(self,con.Error is drv.Error)
  224. _failUnless(self,con.InterfaceError is drv.InterfaceError)
  225. _failUnless(self,con.DatabaseError is drv.DatabaseError)
  226. _failUnless(self,con.OperationalError is drv.OperationalError)
  227. _failUnless(self,con.IntegrityError is drv.IntegrityError)
  228. _failUnless(self,con.InternalError is drv.InternalError)
  229. _failUnless(self,con.ProgrammingError is drv.ProgrammingError)
  230. _failUnless(self,con.NotSupportedError is drv.NotSupportedError)
  231. def test_commit(self):
  232. con = self._connect()
  233. try:
  234. # Commit must work, even if it doesn't do anything
  235. con.commit()
  236. finally:
  237. con.close()
  238. def test_rollback(self):
  239. con = self._connect()
  240. # If rollback is defined, it should either work or throw
  241. # the documented exception
  242. if hasattr(con,'rollback'):
  243. try:
  244. con.rollback()
  245. except self.driver.NotSupportedError:
  246. pass
  247. def test_cursor(self):
  248. con = self._connect()
  249. try:
  250. cur = con.cursor()
  251. finally:
  252. con.close()
  253. def test_cursor_isolation(self):
  254. con = self._connect()
  255. try:
  256. # Make sure cursors created from the same connection have
  257. # the documented transaction isolation level
  258. cur1 = con.cursor()
  259. cur2 = con.cursor()
  260. self.executeDDL1(cur1)
  261. cur1.execute("insert into %sbooze values ('Victoria Bitter')" % (
  262. self.table_prefix
  263. ))
  264. cur2.execute("select name from %sbooze" % self.table_prefix)
  265. booze = cur2.fetchall()
  266. self.assertEqual(len(booze),1)
  267. self.assertEqual(len(booze[0]),1)
  268. self.assertEqual(booze[0][0],'Victoria Bitter')
  269. finally:
  270. con.close()
  271. def test_description(self):
  272. con = self._connect()
  273. try:
  274. cur = con.cursor()
  275. self.executeDDL1(cur)
  276. self.assertEqual(cur.description,None,
  277. 'cursor.description should be none after executing a '
  278. 'statement that can return no rows (such as DDL)'
  279. )
  280. cur.execute('select name from %sbooze' % self.table_prefix)
  281. self.assertEqual(len(cur.description),1,
  282. 'cursor.description describes too many columns'
  283. )
  284. self.assertEqual(len(cur.description[0]),7,
  285. 'cursor.description[x] tuples must have 7 elements'
  286. )
  287. self.assertEqual(cur.description[0][0].lower(),'name',
  288. 'cursor.description[x][0] must return column name'
  289. )
  290. self.assertEqual(cur.description[0][1],self.driver.STRING,
  291. 'cursor.description[x][1] must return column type. Got %r'
  292. % cur.description[0][1]
  293. )
  294. # Make sure self.description gets reset
  295. self.executeDDL2(cur)
  296. self.assertEqual(cur.description,None,
  297. 'cursor.description not being set to None when executing '
  298. 'no-result statements (eg. DDL)'
  299. )
  300. finally:
  301. con.close()
  302. def test_rowcount(self):
  303. con = self._connect()
  304. try:
  305. cur = con.cursor()
  306. self.executeDDL1(cur)
  307. _failUnless(self,cur.rowcount in (-1,0), # Bug #543885
  308. 'cursor.rowcount should be -1 or 0 after executing no-result '
  309. 'statements'
  310. )
  311. cur.execute("insert into %sbooze values ('Victoria Bitter')" % (
  312. self.table_prefix
  313. ))
  314. _failUnless(self,cur.rowcount in (-1,1),
  315. 'cursor.rowcount should == number or rows inserted, or '
  316. 'set to -1 after executing an insert statement'
  317. )
  318. cur.execute("select name from %sbooze" % self.table_prefix)
  319. _failUnless(self,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(cur.rowcount,-1,
  325. 'cursor.rowcount not being reset to -1 after executing '
  326. 'no-result statements'
  327. )
  328. finally:
  329. con.close()
  330. lower_func = 'lower'
  331. def test_callproc(self):
  332. con = self._connect()
  333. try:
  334. cur = con.cursor()
  335. if self.lower_func and hasattr(cur,'callproc'):
  336. r = cur.callproc(self.lower_func,('FOO',))
  337. self.assertEqual(len(r),1)
  338. self.assertEqual(r[0],'FOO')
  339. r = cur.fetchall()
  340. self.assertEqual(len(r),1,'callproc produced no result set')
  341. self.assertEqual(len(r[0]),1,
  342. 'callproc produced invalid result set'
  343. )
  344. self.assertEqual(r[0][0],'foo',
  345. 'callproc produced invalid results'
  346. )
  347. finally:
  348. con.close()
  349. def test_close(self):
  350. con = self._connect()
  351. try:
  352. cur = con.cursor()
  353. finally:
  354. con.close()
  355. # cursor.execute should raise an Error if called after connection
  356. # closed
  357. self.assertRaises(self.driver.Error,self.executeDDL1,cur)
  358. # connection.commit should raise an Error if called after connection'
  359. # closed.'
  360. self.assertRaises(self.driver.Error,con.commit)
  361. # connection.close should raise an Error if called more than once
  362. #!!! reasonable persons differ about the usefulness of this test and this feature !!!
  363. if TEST_FOR_NON_IDEMPOTENT_CLOSE:
  364. self.assertRaises(self.driver.Error, con.close)
  365. else:
  366. self.skipTest("Non-idempotent close is considered a bad thing by some people.")
  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("insert into %sbarflys values ('Victoria Bitter', 'thi%%s :may ca%%(u)se? troub:1e')" % (
  377. self.table_prefix
  378. ))
  379. _failUnless(self,cur.rowcount in (-1,1))
  380. if self.driver.paramstyle == 'qmark':
  381. cur.execute(
  382. "insert into %sbarflys values (?, 'thi%%s :may ca%%(u)se? troub:1e')" % self.table_prefix,
  383. ("Cooper's",)
  384. )
  385. elif self.driver.paramstyle == 'numeric':
  386. cur.execute(
  387. "insert into %sbarflys values (:1, 'thi%%s :may ca%%(u)se? troub:1e')" % self.table_prefix,
  388. ("Cooper's",)
  389. )
  390. elif self.driver.paramstyle == 'named':
  391. cur.execute(
  392. "insert into %sbarflys values (:beer, 'thi%%s :may ca%%(u)se? troub:1e')" % self.table_prefix,
  393. {'beer':"Cooper's"}
  394. )
  395. elif self.driver.paramstyle == 'format':
  396. cur.execute(
  397. "insert into %sbarflys values (%%s, 'thi%%s :may ca%%(u)se? troub:1e')" % self.table_prefix,
  398. ("Cooper's",)
  399. )
  400. elif self.driver.paramstyle == 'pyformat':
  401. cur.execute(
  402. "insert into %sbarflys values (%%(beer)s, 'thi%%s :may ca%%(u)se? troub:1e')" % self.table_prefix,
  403. {'beer':"Cooper's"}
  404. )
  405. else:
  406. self.fail('Invalid paramstyle')
  407. _failUnless(self,cur.rowcount in (-1,1))
  408. cur.execute('select name, drink from %sbarflys' % self.table_prefix)
  409. res = cur.fetchall()
  410. self.assertEqual(len(res),2,'cursor.fetchall returned too few rows')
  411. beers = [res[0][0],res[1][0]]
  412. beers.sort()
  413. self.assertEqual(beers[0],"Cooper's",
  414. 'cursor.fetchall retrieved incorrect data, or data inserted '
  415. 'incorrectly'
  416. )
  417. self.assertEqual(beers[1],"Victoria Bitter",
  418. 'cursor.fetchall retrieved incorrect data, or data inserted '
  419. 'incorrectly'
  420. )
  421. trouble = "thi%s :may ca%(u)se? troub:1e"
  422. self.assertEqual(res[0][1], trouble,
  423. 'cursor.fetchall retrieved incorrect data, or data inserted '
  424. 'incorrectly. Got=%s, Expected=%s' % (repr(res[0][1]), repr(trouble)))
  425. self.assertEqual(res[1][1], trouble,
  426. 'cursor.fetchall retrieved incorrect data, or data inserted '
  427. 'incorrectly. Got=%s, Expected=%s' % (repr(res[1][1]), repr(trouble)
  428. ))
  429. def test_executemany(self):
  430. con = self._connect()
  431. try:
  432. cur = con.cursor()
  433. self.executeDDL1(cur)
  434. largs = [ ("Cooper's",) , ("Boag's",) ]
  435. margs = [ {'beer': "Cooper's"}, {'beer': "Boag's"} ]
  436. if self.driver.paramstyle == 'qmark':
  437. cur.executemany(
  438. 'insert into %sbooze values (?)' % self.table_prefix,
  439. largs
  440. )
  441. elif self.driver.paramstyle == 'numeric':
  442. cur.executemany(
  443. 'insert into %sbooze values (:1)' % self.table_prefix,
  444. largs
  445. )
  446. elif self.driver.paramstyle == 'named':
  447. cur.executemany(
  448. 'insert into %sbooze values (:beer)' % self.table_prefix,
  449. margs
  450. )
  451. elif self.driver.paramstyle == 'format':
  452. cur.executemany(
  453. 'insert into %sbooze values (%%s)' % self.table_prefix,
  454. largs
  455. )
  456. elif self.driver.paramstyle == 'pyformat':
  457. cur.executemany(
  458. 'insert into %sbooze values (%%(beer)s)' % (
  459. self.table_prefix
  460. ),
  461. margs
  462. )
  463. else:
  464. self.fail('Unknown paramstyle')
  465. _failUnless(self,cur.rowcount in (-1,2),
  466. 'insert using cursor.executemany set cursor.rowcount to '
  467. 'incorrect value %r' % cur.rowcount
  468. )
  469. cur.execute('select name from %sbooze' % self.table_prefix)
  470. res = cur.fetchall()
  471. self.assertEqual(len(res),2,
  472. 'cursor.fetchall retrieved incorrect number of rows'
  473. )
  474. beers = [res[0][0],res[1][0]]
  475. beers.sort()
  476. self.assertEqual(beers[0],"Boag's",'incorrect data "%s" retrieved' % beers[0])
  477. self.assertEqual(beers[1],"Cooper's",'incorrect data retrieved')
  478. finally:
  479. con.close()
  480. def test_fetchone(self):
  481. con = self._connect()
  482. try:
  483. cur = con.cursor()
  484. # cursor.fetchone should raise an Error if called before
  485. # executing a select-type query
  486. self.assertRaises(self.driver.Error,cur.fetchone)
  487. # cursor.fetchone should raise an Error if called after
  488. # executing a query that cannnot return rows
  489. self.executeDDL1(cur)
  490. self.assertRaises(self.driver.Error,cur.fetchone)
  491. cur.execute('select name from %sbooze' % self.table_prefix)
  492. self.assertEqual(cur.fetchone(),None,
  493. 'cursor.fetchone should return None if a query retrieves '
  494. 'no rows'
  495. )
  496. _failUnless(self,cur.rowcount in (-1,0))
  497. # cursor.fetchone should raise an Error if called after
  498. # executing a query that cannnot return rows
  499. cur.execute("insert into %sbooze values ('Victoria Bitter')" % (
  500. self.table_prefix
  501. ))
  502. self.assertRaises(self.driver.Error,cur.fetchone)
  503. cur.execute('select name from %sbooze' % self.table_prefix)
  504. r = cur.fetchone()
  505. self.assertEqual(len(r),1,
  506. 'cursor.fetchone should have retrieved a single row'
  507. )
  508. self.assertEqual(r[0],'Victoria Bitter',
  509. 'cursor.fetchone retrieved incorrect data'
  510. )
  511. self.assertEqual(cur.fetchone(),None,
  512. 'cursor.fetchone should return None if no more rows available'
  513. )
  514. _failUnless(self,cur.rowcount in (-1,1))
  515. finally:
  516. con.close()
  517. samples = [
  518. 'Carlton Cold',
  519. 'Carlton Draft',
  520. 'Mountain Goat',
  521. 'Redback',
  522. 'Victoria Bitter',
  523. 'XXXX'
  524. ]
  525. def _populate(self):
  526. ''' Return a list of sql commands to setup the DB for the fetch
  527. tests.
  528. '''
  529. populate = [
  530. "insert into %sbooze values ('%s')" % (self.table_prefix,s)
  531. for s in self.samples
  532. ]
  533. return populate
  534. def test_fetchmany(self):
  535. con = self._connect()
  536. try:
  537. cur = con.cursor()
  538. # cursor.fetchmany should raise an Error if called without
  539. #issuing a query
  540. self.assertRaises(self.driver.Error,cur.fetchmany,4)
  541. self.executeDDL1(cur)
  542. for sql in self._populate():
  543. cur.execute(sql)
  544. cur.execute('select name from %sbooze' % self.table_prefix)
  545. r = cur.fetchmany()
  546. self.assertEqual(len(r),1,
  547. 'cursor.fetchmany retrieved incorrect number of rows, '
  548. 'default of arraysize is one.'
  549. )
  550. cur.arraysize=10
  551. r = cur.fetchmany(3) # Should get 3 rows
  552. self.assertEqual(len(r),3,
  553. 'cursor.fetchmany retrieved incorrect number of rows'
  554. )
  555. r = cur.fetchmany(4) # Should get 2 more
  556. self.assertEqual(len(r),2,
  557. 'cursor.fetchmany retrieved incorrect number of rows'
  558. )
  559. r = cur.fetchmany(4) # Should be an empty sequence
  560. self.assertEqual(len(r),0,
  561. 'cursor.fetchmany should return an empty sequence after '
  562. 'results are exhausted'
  563. )
  564. _failUnless(self,cur.rowcount in (-1,6))
  565. # Same as above, using cursor.arraysize
  566. cur.arraysize=4
  567. cur.execute('select name from %sbooze' % self.table_prefix)
  568. r = cur.fetchmany() # Should get 4 rows
  569. self.assertEqual(len(r),4,
  570. 'cursor.arraysize not being honoured by fetchmany'
  571. )
  572. r = cur.fetchmany() # Should get 2 more
  573. self.assertEqual(len(r),2)
  574. r = cur.fetchmany() # Should be an empty sequence
  575. self.assertEqual(len(r),0)
  576. _failUnless(self,cur.rowcount in (-1,6))
  577. cur.arraysize=6
  578. cur.execute('select name from %sbooze' % self.table_prefix)
  579. rows = cur.fetchmany() # Should get all rows
  580. _failUnless(self,cur.rowcount in (-1,6))
  581. self.assertEqual(len(rows),6)
  582. self.assertEqual(len(rows),6)
  583. rows = [r[0] for r in rows]
  584. rows.sort()
  585. # Make sure we get the right data back out
  586. for i in range(0,6):
  587. self.assertEqual(rows[i],self.samples[i],
  588. 'incorrect data retrieved by cursor.fetchmany'
  589. )
  590. rows = cur.fetchmany() # Should return an empty list
  591. self.assertEqual(len(rows),0,
  592. 'cursor.fetchmany should return an empty sequence if '
  593. 'called after the whole result set has been fetched'
  594. )
  595. _failUnless(self,cur.rowcount in (-1,6))
  596. self.executeDDL2(cur)
  597. cur.execute('select name from %sbarflys' % self.table_prefix)
  598. r = cur.fetchmany() # Should get empty sequence
  599. self.assertEqual(len(r),0,
  600. 'cursor.fetchmany should return an empty sequence if '
  601. 'query retrieved no rows'
  602. )
  603. _failUnless(self,cur.rowcount in (-1,0))
  604. finally:
  605. con.close()
  606. def test_fetchall(self):
  607. con = self._connect()
  608. try:
  609. cur = con.cursor()
  610. # cursor.fetchall should raise an Error if called
  611. # without executing a query that may return rows (such
  612. # as a select)
  613. self.assertRaises(self.driver.Error, cur.fetchall)
  614. self.executeDDL1(cur)
  615. for sql in self._populate():
  616. cur.execute(sql)
  617. # cursor.fetchall should raise an Error if called
  618. # after executing a a statement that cannot return rows
  619. self.assertRaises(self.driver.Error,cur.fetchall)
  620. cur.execute('select name from %sbooze' % self.table_prefix)
  621. rows = cur.fetchall()
  622. _failUnless(self,cur.rowcount in (-1,len(self.samples)))
  623. self.assertEqual(len(rows),len(self.samples),
  624. 'cursor.fetchall did not retrieve all rows'
  625. )
  626. rows = [r[0] for r in rows]
  627. rows.sort()
  628. for i in range(0,len(self.samples)):
  629. self.assertEqual(rows[i],self.samples[i],
  630. 'cursor.fetchall retrieved incorrect rows'
  631. )
  632. rows = cur.fetchall()
  633. self.assertEqual(
  634. len(rows),0,
  635. 'cursor.fetchall should return an empty list if called '
  636. 'after the whole result set has been fetched'
  637. )
  638. _failUnless(self,cur.rowcount in (-1,len(self.samples)))
  639. self.executeDDL2(cur)
  640. cur.execute('select name from %sbarflys' % self.table_prefix)
  641. rows = cur.fetchall()
  642. _failUnless(self,cur.rowcount in (-1,0))
  643. self.assertEqual(len(rows),0,
  644. 'cursor.fetchall should return an empty list if '
  645. 'a select query returns no rows'
  646. )
  647. finally:
  648. con.close()
  649. def test_mixedfetch(self):
  650. con = self._connect()
  651. try:
  652. cur = con.cursor()
  653. self.executeDDL1(cur)
  654. for sql in self._populate():
  655. cur.execute(sql)
  656. cur.execute('select name from %sbooze' % self.table_prefix)
  657. rows1 = cur.fetchone()
  658. rows23 = cur.fetchmany(2)
  659. rows4 = cur.fetchone()
  660. rows56 = cur.fetchall()
  661. _failUnless(self,cur.rowcount in (-1,6))
  662. self.assertEqual(len(rows23),2,
  663. 'fetchmany returned incorrect number of rows'
  664. )
  665. self.assertEqual(len(rows56),2,
  666. 'fetchall returned incorrect number of rows'
  667. )
  668. rows = [rows1[0]]
  669. rows.extend([rows23[0][0],rows23[1][0]])
  670. rows.append(rows4[0])
  671. rows.extend([rows56[0][0],rows56[1][0]])
  672. rows.sort()
  673. for i in range(0,len(self.samples)):
  674. self.assertEqual(rows[i],self.samples[i],
  675. 'incorrect data retrieved or inserted'
  676. )
  677. finally:
  678. con.close()
  679. def help_nextset_setUp(self,cur):
  680. ''' Should create a procedure called deleteme
  681. that returns two result sets, first the
  682. number of rows in booze then "name from booze"
  683. '''
  684. raise NotImplementedError('Helper not implemented')
  685. #sql="""
  686. # create procedure deleteme as
  687. # begin
  688. # select count(*) from booze
  689. # select name from booze
  690. # end
  691. #"""
  692. #cur.execute(sql)
  693. def help_nextset_tearDown(self,cur):
  694. 'If cleaning up is needed after nextSetTest'
  695. raise NotImplementedError('Helper not implemented')
  696. #cur.execute("drop procedure deleteme")
  697. def test_nextset(self):
  698. con = self._connect()
  699. try:
  700. cur = con.cursor()
  701. if not hasattr(cur,'nextset'):
  702. return
  703. try:
  704. self.executeDDL1(cur)
  705. sql=self._populate()
  706. for sql in self._populate():
  707. cur.execute(sql)
  708. self.help_nextset_setUp(cur)
  709. cur.callproc('deleteme')
  710. numberofrows=cur.fetchone()
  711. assert numberofrows[0]== len(self.samples)
  712. assert cur.nextset()
  713. names=cur.fetchall()
  714. assert len(names) == len(self.samples)
  715. s=cur.nextset()
  716. assert s == None,'No more return sets, should return None'
  717. finally:
  718. self.help_nextset_tearDown(cur)
  719. finally:
  720. con.close()
  721. def test_nextset(self):
  722. raise NotImplementedError('Drivers need to override this test')
  723. def test_arraysize(self):
  724. # Not much here - rest of the tests for this are in test_fetchmany
  725. con = self._connect()
  726. try:
  727. cur = con.cursor()
  728. _failUnless(self,hasattr(cur,'arraysize'),
  729. 'cursor.arraysize must be defined'
  730. )
  731. finally:
  732. con.close()
  733. def test_setinputsizes(self):
  734. con = self._connect()
  735. try:
  736. cur = con.cursor()
  737. cur.setinputsizes( (25,) )
  738. self._paraminsert(cur) # Make sure cursor still works
  739. finally:
  740. con.close()
  741. def test_setoutputsize_basic(self):
  742. # Basic test is to make sure setoutputsize doesn't blow up
  743. con = self._connect()
  744. try:
  745. cur = con.cursor()
  746. cur.setoutputsize(1000)
  747. cur.setoutputsize(2000,0)
  748. self._paraminsert(cur) # Make sure the cursor still works
  749. finally:
  750. con.close()
  751. def test_setoutputsize(self):
  752. # Real test for setoutputsize is driver dependant
  753. raise NotImplementedError('Driver needed to override this test')
  754. def test_None(self):
  755. con = self._connect()
  756. try:
  757. cur = con.cursor()
  758. self.executeDDL1(cur)
  759. cur.execute('insert into %sbooze values (NULL)' % self.table_prefix)
  760. cur.execute('select name from %sbooze' % self.table_prefix)
  761. r = cur.fetchall()
  762. self.assertEqual(len(r),1)
  763. self.assertEqual(len(r[0]),1)
  764. self.assertEqual(r[0][0],None,'NULL value not returned as None')
  765. finally:
  766. con.close()
  767. def test_Date(self):
  768. d1 = self.driver.Date(2002,12,25)
  769. d2 = self.driver.DateFromTicks(time.mktime((2002,12,25,0,0,0,0,0,0)))
  770. # Can we assume this? API doesn't specify, but it seems implied
  771. # self.assertEqual(str(d1),str(d2))
  772. def test_Time(self):
  773. t1 = self.driver.Time(13,45,30)
  774. t2 = self.driver.TimeFromTicks(time.mktime((2001,1,1,13,45,30,0,0,0)))
  775. # Can we assume this? API doesn't specify, but it seems implied
  776. # self.assertEqual(str(t1),str(t2))
  777. def test_Timestamp(self):
  778. t1 = self.driver.Timestamp(2002,12,25,13,45,30)
  779. t2 = self.driver.TimestampFromTicks(
  780. time.mktime((2002,12,25,13,45,30,0,0,0))
  781. )
  782. # Can we assume this? API doesn't specify, but it seems implied
  783. # self.assertEqual(str(t1),str(t2))
  784. def test_Binary(self):
  785. b = self.driver.Binary(str2bytes('Something'))
  786. b = self.driver.Binary(str2bytes(''))
  787. def test_STRING(self):
  788. _failUnless(self, hasattr(self.driver,'STRING'),
  789. 'module.STRING must be defined'
  790. )
  791. def test_BINARY(self):
  792. _failUnless(self, hasattr(self.driver,'BINARY'),
  793. 'module.BINARY must be defined.'
  794. )
  795. def test_NUMBER(self):
  796. _failUnless(self, hasattr(self.driver,'NUMBER'),
  797. 'module.NUMBER must be defined.'
  798. )
  799. def test_DATETIME(self):
  800. _failUnless(self, hasattr(self.driver,'DATETIME'),
  801. 'module.DATETIME must be defined.'
  802. )
  803. def test_ROWID(self):
  804. _failUnless(self, hasattr(self.driver,'ROWID'),
  805. 'module.ROWID must be defined.'
  806. )