dbapi20.py 31 KB

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