dbapi.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. #-*- coding: ISO-8859-1 -*-
  2. # pysqlite2/test/dbapi.py: tests for DB-API compliance
  3. #
  4. # Copyright (C) 2004-2010 Gerhard Häring <gh@ghaering.de>
  5. #
  6. # This file is part of pysqlite.
  7. #
  8. # This software is provided 'as-is', without any express or implied
  9. # warranty. In no event will the authors be held liable for any damages
  10. # arising from the use of this software.
  11. #
  12. # Permission is granted to anyone to use this software for any purpose,
  13. # including commercial applications, and to alter it and redistribute it
  14. # freely, subject to the following restrictions:
  15. #
  16. # 1. The origin of this software must not be misrepresented; you must not
  17. # claim that you wrote the original software. If you use this software
  18. # in a product, an acknowledgment in the product documentation would be
  19. # appreciated but is not required.
  20. # 2. Altered source versions must be plainly marked as such, and must not be
  21. # misrepresented as being the original software.
  22. # 3. This notice may not be removed or altered from any source distribution.
  23. import unittest
  24. import sys
  25. import sqlite3 as sqlite
  26. from test import test_support
  27. try:
  28. import threading
  29. except ImportError:
  30. threading = None
  31. class ModuleTests(unittest.TestCase):
  32. def CheckAPILevel(self):
  33. self.assertEqual(sqlite.apilevel, "2.0",
  34. "apilevel is %s, should be 2.0" % sqlite.apilevel)
  35. def CheckThreadSafety(self):
  36. self.assertEqual(sqlite.threadsafety, 1,
  37. "threadsafety is %d, should be 1" % sqlite.threadsafety)
  38. def CheckParamStyle(self):
  39. self.assertEqual(sqlite.paramstyle, "qmark",
  40. "paramstyle is '%s', should be 'qmark'" %
  41. sqlite.paramstyle)
  42. def CheckWarning(self):
  43. self.assertTrue(issubclass(sqlite.Warning, StandardError),
  44. "Warning is not a subclass of StandardError")
  45. def CheckError(self):
  46. self.assertTrue(issubclass(sqlite.Error, StandardError),
  47. "Error is not a subclass of StandardError")
  48. def CheckInterfaceError(self):
  49. self.assertTrue(issubclass(sqlite.InterfaceError, sqlite.Error),
  50. "InterfaceError is not a subclass of Error")
  51. def CheckDatabaseError(self):
  52. self.assertTrue(issubclass(sqlite.DatabaseError, sqlite.Error),
  53. "DatabaseError is not a subclass of Error")
  54. def CheckDataError(self):
  55. self.assertTrue(issubclass(sqlite.DataError, sqlite.DatabaseError),
  56. "DataError is not a subclass of DatabaseError")
  57. def CheckOperationalError(self):
  58. self.assertTrue(issubclass(sqlite.OperationalError, sqlite.DatabaseError),
  59. "OperationalError is not a subclass of DatabaseError")
  60. def CheckIntegrityError(self):
  61. self.assertTrue(issubclass(sqlite.IntegrityError, sqlite.DatabaseError),
  62. "IntegrityError is not a subclass of DatabaseError")
  63. def CheckInternalError(self):
  64. self.assertTrue(issubclass(sqlite.InternalError, sqlite.DatabaseError),
  65. "InternalError is not a subclass of DatabaseError")
  66. def CheckProgrammingError(self):
  67. self.assertTrue(issubclass(sqlite.ProgrammingError, sqlite.DatabaseError),
  68. "ProgrammingError is not a subclass of DatabaseError")
  69. def CheckNotSupportedError(self):
  70. self.assertTrue(issubclass(sqlite.NotSupportedError,
  71. sqlite.DatabaseError),
  72. "NotSupportedError is not a subclass of DatabaseError")
  73. class ConnectionTests(unittest.TestCase):
  74. def setUp(self):
  75. self.cx = sqlite.connect(":memory:")
  76. cu = self.cx.cursor()
  77. cu.execute("create table test(id integer primary key, name text)")
  78. cu.execute("insert into test(name) values (?)", ("foo",))
  79. def tearDown(self):
  80. self.cx.close()
  81. def CheckCommit(self):
  82. self.cx.commit()
  83. def CheckCommitAfterNoChanges(self):
  84. """
  85. A commit should also work when no changes were made to the database.
  86. """
  87. self.cx.commit()
  88. self.cx.commit()
  89. def CheckRollback(self):
  90. self.cx.rollback()
  91. def CheckRollbackAfterNoChanges(self):
  92. """
  93. A rollback should also work when no changes were made to the database.
  94. """
  95. self.cx.rollback()
  96. self.cx.rollback()
  97. def CheckCursor(self):
  98. cu = self.cx.cursor()
  99. def CheckFailedOpen(self):
  100. YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
  101. try:
  102. con = sqlite.connect(YOU_CANNOT_OPEN_THIS)
  103. except sqlite.OperationalError:
  104. return
  105. self.fail("should have raised an OperationalError")
  106. def CheckClose(self):
  107. self.cx.close()
  108. def CheckExceptions(self):
  109. # Optional DB-API extension.
  110. self.assertEqual(self.cx.Warning, sqlite.Warning)
  111. self.assertEqual(self.cx.Error, sqlite.Error)
  112. self.assertEqual(self.cx.InterfaceError, sqlite.InterfaceError)
  113. self.assertEqual(self.cx.DatabaseError, sqlite.DatabaseError)
  114. self.assertEqual(self.cx.DataError, sqlite.DataError)
  115. self.assertEqual(self.cx.OperationalError, sqlite.OperationalError)
  116. self.assertEqual(self.cx.IntegrityError, sqlite.IntegrityError)
  117. self.assertEqual(self.cx.InternalError, sqlite.InternalError)
  118. self.assertEqual(self.cx.ProgrammingError, sqlite.ProgrammingError)
  119. self.assertEqual(self.cx.NotSupportedError, sqlite.NotSupportedError)
  120. class CursorTests(unittest.TestCase):
  121. def setUp(self):
  122. self.cx = sqlite.connect(":memory:")
  123. self.cu = self.cx.cursor()
  124. self.cu.execute("create table test(id integer primary key, name text, income number)")
  125. self.cu.execute("insert into test(name) values (?)", ("foo",))
  126. def tearDown(self):
  127. self.cu.close()
  128. self.cx.close()
  129. def CheckExecuteNoArgs(self):
  130. self.cu.execute("delete from test")
  131. def CheckExecuteIllegalSql(self):
  132. try:
  133. self.cu.execute("select asdf")
  134. self.fail("should have raised an OperationalError")
  135. except sqlite.OperationalError:
  136. return
  137. except:
  138. self.fail("raised wrong exception")
  139. def CheckExecuteTooMuchSql(self):
  140. try:
  141. self.cu.execute("select 5+4; select 4+5")
  142. self.fail("should have raised a Warning")
  143. except sqlite.Warning:
  144. return
  145. except:
  146. self.fail("raised wrong exception")
  147. def CheckExecuteTooMuchSql2(self):
  148. self.cu.execute("select 5+4; -- foo bar")
  149. def CheckExecuteTooMuchSql3(self):
  150. self.cu.execute("""
  151. select 5+4;
  152. /*
  153. foo
  154. */
  155. """)
  156. def CheckExecuteWrongSqlArg(self):
  157. try:
  158. self.cu.execute(42)
  159. self.fail("should have raised a ValueError")
  160. except ValueError:
  161. return
  162. except:
  163. self.fail("raised wrong exception.")
  164. def CheckExecuteArgInt(self):
  165. self.cu.execute("insert into test(id) values (?)", (42,))
  166. def CheckExecuteArgFloat(self):
  167. self.cu.execute("insert into test(income) values (?)", (2500.32,))
  168. def CheckExecuteArgString(self):
  169. self.cu.execute("insert into test(name) values (?)", ("Hugo",))
  170. def CheckExecuteArgStringWithZeroByte(self):
  171. self.cu.execute("insert into test(name) values (?)", ("Hu\x00go",))
  172. self.cu.execute("select name from test where id=?", (self.cu.lastrowid,))
  173. row = self.cu.fetchone()
  174. self.assertEqual(row[0], "Hu\x00go")
  175. def CheckExecuteWrongNoOfArgs1(self):
  176. # too many parameters
  177. try:
  178. self.cu.execute("insert into test(id) values (?)", (17, "Egon"))
  179. self.fail("should have raised ProgrammingError")
  180. except sqlite.ProgrammingError:
  181. pass
  182. def CheckExecuteWrongNoOfArgs2(self):
  183. # too little parameters
  184. try:
  185. self.cu.execute("insert into test(id) values (?)")
  186. self.fail("should have raised ProgrammingError")
  187. except sqlite.ProgrammingError:
  188. pass
  189. def CheckExecuteWrongNoOfArgs3(self):
  190. # no parameters, parameters are needed
  191. try:
  192. self.cu.execute("insert into test(id) values (?)")
  193. self.fail("should have raised ProgrammingError")
  194. except sqlite.ProgrammingError:
  195. pass
  196. def CheckExecuteParamList(self):
  197. self.cu.execute("insert into test(name) values ('foo')")
  198. self.cu.execute("select name from test where name=?", ["foo"])
  199. row = self.cu.fetchone()
  200. self.assertEqual(row[0], "foo")
  201. def CheckExecuteParamSequence(self):
  202. class L(object):
  203. def __len__(self):
  204. return 1
  205. def __getitem__(self, x):
  206. assert x == 0
  207. return "foo"
  208. self.cu.execute("insert into test(name) values ('foo')")
  209. self.cu.execute("select name from test where name=?", L())
  210. row = self.cu.fetchone()
  211. self.assertEqual(row[0], "foo")
  212. def CheckExecuteDictMapping(self):
  213. self.cu.execute("insert into test(name) values ('foo')")
  214. self.cu.execute("select name from test where name=:name", {"name": "foo"})
  215. row = self.cu.fetchone()
  216. self.assertEqual(row[0], "foo")
  217. def CheckExecuteDictMapping_Mapping(self):
  218. # Test only works with Python 2.5 or later
  219. if sys.version_info < (2, 5, 0):
  220. return
  221. class D(dict):
  222. def __missing__(self, key):
  223. return "foo"
  224. self.cu.execute("insert into test(name) values ('foo')")
  225. self.cu.execute("select name from test where name=:name", D())
  226. row = self.cu.fetchone()
  227. self.assertEqual(row[0], "foo")
  228. def CheckExecuteDictMappingTooLittleArgs(self):
  229. self.cu.execute("insert into test(name) values ('foo')")
  230. try:
  231. self.cu.execute("select name from test where name=:name and id=:id", {"name": "foo"})
  232. self.fail("should have raised ProgrammingError")
  233. except sqlite.ProgrammingError:
  234. pass
  235. def CheckExecuteDictMappingNoArgs(self):
  236. self.cu.execute("insert into test(name) values ('foo')")
  237. try:
  238. self.cu.execute("select name from test where name=:name")
  239. self.fail("should have raised ProgrammingError")
  240. except sqlite.ProgrammingError:
  241. pass
  242. def CheckExecuteDictMappingUnnamed(self):
  243. self.cu.execute("insert into test(name) values ('foo')")
  244. try:
  245. self.cu.execute("select name from test where name=?", {"name": "foo"})
  246. self.fail("should have raised ProgrammingError")
  247. except sqlite.ProgrammingError:
  248. pass
  249. def CheckClose(self):
  250. self.cu.close()
  251. def CheckRowcountExecute(self):
  252. self.cu.execute("delete from test")
  253. self.cu.execute("insert into test(name) values ('foo')")
  254. self.cu.execute("insert into test(name) values ('foo')")
  255. self.cu.execute("update test set name='bar'")
  256. self.assertEqual(self.cu.rowcount, 2)
  257. def CheckRowcountSelect(self):
  258. """
  259. pysqlite does not know the rowcount of SELECT statements, because we
  260. don't fetch all rows after executing the select statement. The rowcount
  261. has thus to be -1.
  262. """
  263. self.cu.execute("select 5 union select 6")
  264. self.assertEqual(self.cu.rowcount, -1)
  265. def CheckRowcountExecutemany(self):
  266. self.cu.execute("delete from test")
  267. self.cu.executemany("insert into test(name) values (?)", [(1,), (2,), (3,)])
  268. self.assertEqual(self.cu.rowcount, 3)
  269. def CheckTotalChanges(self):
  270. self.cu.execute("insert into test(name) values ('foo')")
  271. self.cu.execute("insert into test(name) values ('foo')")
  272. if self.cx.total_changes < 2:
  273. self.fail("total changes reported wrong value")
  274. # Checks for executemany:
  275. # Sequences are required by the DB-API, iterators
  276. # enhancements in pysqlite.
  277. def CheckExecuteManySequence(self):
  278. self.cu.executemany("insert into test(income) values (?)", [(x,) for x in range(100, 110)])
  279. def CheckExecuteManyIterator(self):
  280. class MyIter:
  281. def __init__(self):
  282. self.value = 5
  283. def next(self):
  284. if self.value == 10:
  285. raise StopIteration
  286. else:
  287. self.value += 1
  288. return (self.value,)
  289. self.cu.executemany("insert into test(income) values (?)", MyIter())
  290. def CheckExecuteManyGenerator(self):
  291. def mygen():
  292. for i in range(5):
  293. yield (i,)
  294. self.cu.executemany("insert into test(income) values (?)", mygen())
  295. def CheckExecuteManyWrongSqlArg(self):
  296. try:
  297. self.cu.executemany(42, [(3,)])
  298. self.fail("should have raised a ValueError")
  299. except ValueError:
  300. return
  301. except:
  302. self.fail("raised wrong exception.")
  303. def CheckExecuteManySelect(self):
  304. try:
  305. self.cu.executemany("select ?", [(3,)])
  306. self.fail("should have raised a ProgrammingError")
  307. except sqlite.ProgrammingError:
  308. return
  309. except:
  310. self.fail("raised wrong exception.")
  311. def CheckExecuteManyNotIterable(self):
  312. try:
  313. self.cu.executemany("insert into test(income) values (?)", 42)
  314. self.fail("should have raised a TypeError")
  315. except TypeError:
  316. return
  317. except Exception, e:
  318. print "raised", e.__class__
  319. self.fail("raised wrong exception.")
  320. def CheckFetchIter(self):
  321. # Optional DB-API extension.
  322. self.cu.execute("delete from test")
  323. self.cu.execute("insert into test(id) values (?)", (5,))
  324. self.cu.execute("insert into test(id) values (?)", (6,))
  325. self.cu.execute("select id from test order by id")
  326. lst = []
  327. for row in self.cu:
  328. lst.append(row[0])
  329. self.assertEqual(lst[0], 5)
  330. self.assertEqual(lst[1], 6)
  331. def CheckFetchone(self):
  332. self.cu.execute("select name from test")
  333. row = self.cu.fetchone()
  334. self.assertEqual(row[0], "foo")
  335. row = self.cu.fetchone()
  336. self.assertEqual(row, None)
  337. def CheckFetchoneNoStatement(self):
  338. cur = self.cx.cursor()
  339. row = cur.fetchone()
  340. self.assertEqual(row, None)
  341. def CheckArraySize(self):
  342. # must default ot 1
  343. self.assertEqual(self.cu.arraysize, 1)
  344. # now set to 2
  345. self.cu.arraysize = 2
  346. # now make the query return 3 rows
  347. self.cu.execute("delete from test")
  348. self.cu.execute("insert into test(name) values ('A')")
  349. self.cu.execute("insert into test(name) values ('B')")
  350. self.cu.execute("insert into test(name) values ('C')")
  351. self.cu.execute("select name from test")
  352. res = self.cu.fetchmany()
  353. self.assertEqual(len(res), 2)
  354. def CheckFetchmany(self):
  355. self.cu.execute("select name from test")
  356. res = self.cu.fetchmany(100)
  357. self.assertEqual(len(res), 1)
  358. res = self.cu.fetchmany(100)
  359. self.assertEqual(res, [])
  360. def CheckFetchmanyKwArg(self):
  361. """Checks if fetchmany works with keyword arguments"""
  362. self.cu.execute("select name from test")
  363. res = self.cu.fetchmany(size=100)
  364. self.assertEqual(len(res), 1)
  365. def CheckFetchall(self):
  366. self.cu.execute("select name from test")
  367. res = self.cu.fetchall()
  368. self.assertEqual(len(res), 1)
  369. res = self.cu.fetchall()
  370. self.assertEqual(res, [])
  371. def CheckSetinputsizes(self):
  372. self.cu.setinputsizes([3, 4, 5])
  373. def CheckSetoutputsize(self):
  374. self.cu.setoutputsize(5, 0)
  375. def CheckSetoutputsizeNoColumn(self):
  376. self.cu.setoutputsize(42)
  377. def CheckCursorConnection(self):
  378. # Optional DB-API extension.
  379. self.assertEqual(self.cu.connection, self.cx)
  380. def CheckWrongCursorCallable(self):
  381. try:
  382. def f(): pass
  383. cur = self.cx.cursor(f)
  384. self.fail("should have raised a TypeError")
  385. except TypeError:
  386. return
  387. self.fail("should have raised a ValueError")
  388. def CheckCursorWrongClass(self):
  389. class Foo: pass
  390. foo = Foo()
  391. try:
  392. cur = sqlite.Cursor(foo)
  393. self.fail("should have raised a ValueError")
  394. except TypeError:
  395. pass
  396. @unittest.skipUnless(threading, 'This test requires threading.')
  397. class ThreadTests(unittest.TestCase):
  398. def setUp(self):
  399. self.con = sqlite.connect(":memory:")
  400. self.cur = self.con.cursor()
  401. self.cur.execute("create table test(id integer primary key, name text, bin binary, ratio number, ts timestamp)")
  402. def tearDown(self):
  403. self.cur.close()
  404. self.con.close()
  405. def CheckConCursor(self):
  406. def run(con, errors):
  407. try:
  408. cur = con.cursor()
  409. errors.append("did not raise ProgrammingError")
  410. return
  411. except sqlite.ProgrammingError:
  412. return
  413. except:
  414. errors.append("raised wrong exception")
  415. errors = []
  416. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  417. t.start()
  418. t.join()
  419. if len(errors) > 0:
  420. self.fail("\n".join(errors))
  421. def CheckConCommit(self):
  422. def run(con, errors):
  423. try:
  424. con.commit()
  425. errors.append("did not raise ProgrammingError")
  426. return
  427. except sqlite.ProgrammingError:
  428. return
  429. except:
  430. errors.append("raised wrong exception")
  431. errors = []
  432. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  433. t.start()
  434. t.join()
  435. if len(errors) > 0:
  436. self.fail("\n".join(errors))
  437. def CheckConRollback(self):
  438. def run(con, errors):
  439. try:
  440. con.rollback()
  441. errors.append("did not raise ProgrammingError")
  442. return
  443. except sqlite.ProgrammingError:
  444. return
  445. except:
  446. errors.append("raised wrong exception")
  447. errors = []
  448. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  449. t.start()
  450. t.join()
  451. if len(errors) > 0:
  452. self.fail("\n".join(errors))
  453. def CheckConClose(self):
  454. def run(con, errors):
  455. try:
  456. con.close()
  457. errors.append("did not raise ProgrammingError")
  458. return
  459. except sqlite.ProgrammingError:
  460. return
  461. except:
  462. errors.append("raised wrong exception")
  463. errors = []
  464. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  465. t.start()
  466. t.join()
  467. if len(errors) > 0:
  468. self.fail("\n".join(errors))
  469. def CheckCurImplicitBegin(self):
  470. def run(cur, errors):
  471. try:
  472. cur.execute("insert into test(name) values ('a')")
  473. errors.append("did not raise ProgrammingError")
  474. return
  475. except sqlite.ProgrammingError:
  476. return
  477. except:
  478. errors.append("raised wrong exception")
  479. errors = []
  480. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  481. t.start()
  482. t.join()
  483. if len(errors) > 0:
  484. self.fail("\n".join(errors))
  485. def CheckCurClose(self):
  486. def run(cur, errors):
  487. try:
  488. cur.close()
  489. errors.append("did not raise ProgrammingError")
  490. return
  491. except sqlite.ProgrammingError:
  492. return
  493. except:
  494. errors.append("raised wrong exception")
  495. errors = []
  496. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  497. t.start()
  498. t.join()
  499. if len(errors) > 0:
  500. self.fail("\n".join(errors))
  501. def CheckCurExecute(self):
  502. def run(cur, errors):
  503. try:
  504. cur.execute("select name from test")
  505. errors.append("did not raise ProgrammingError")
  506. return
  507. except sqlite.ProgrammingError:
  508. return
  509. except:
  510. errors.append("raised wrong exception")
  511. errors = []
  512. self.cur.execute("insert into test(name) values ('a')")
  513. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  514. t.start()
  515. t.join()
  516. if len(errors) > 0:
  517. self.fail("\n".join(errors))
  518. def CheckCurIterNext(self):
  519. def run(cur, errors):
  520. try:
  521. row = cur.fetchone()
  522. errors.append("did not raise ProgrammingError")
  523. return
  524. except sqlite.ProgrammingError:
  525. return
  526. except:
  527. errors.append("raised wrong exception")
  528. errors = []
  529. self.cur.execute("insert into test(name) values ('a')")
  530. self.cur.execute("select name from test")
  531. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  532. t.start()
  533. t.join()
  534. if len(errors) > 0:
  535. self.fail("\n".join(errors))
  536. class ConstructorTests(unittest.TestCase):
  537. def CheckDate(self):
  538. d = sqlite.Date(2004, 10, 28)
  539. def CheckTime(self):
  540. t = sqlite.Time(12, 39, 35)
  541. def CheckTimestamp(self):
  542. ts = sqlite.Timestamp(2004, 10, 28, 12, 39, 35)
  543. def CheckDateFromTicks(self):
  544. d = sqlite.DateFromTicks(42)
  545. def CheckTimeFromTicks(self):
  546. t = sqlite.TimeFromTicks(42)
  547. def CheckTimestampFromTicks(self):
  548. ts = sqlite.TimestampFromTicks(42)
  549. def CheckBinary(self):
  550. with test_support.check_py3k_warnings():
  551. b = sqlite.Binary(chr(0) + "'")
  552. class ExtensionTests(unittest.TestCase):
  553. def CheckScriptStringSql(self):
  554. con = sqlite.connect(":memory:")
  555. cur = con.cursor()
  556. cur.executescript("""
  557. -- bla bla
  558. /* a stupid comment */
  559. create table a(i);
  560. insert into a(i) values (5);
  561. """)
  562. cur.execute("select i from a")
  563. res = cur.fetchone()[0]
  564. self.assertEqual(res, 5)
  565. def CheckScriptStringUnicode(self):
  566. con = sqlite.connect(":memory:")
  567. cur = con.cursor()
  568. cur.executescript(u"""
  569. create table a(i);
  570. insert into a(i) values (5);
  571. select i from a;
  572. delete from a;
  573. insert into a(i) values (6);
  574. """)
  575. cur.execute("select i from a")
  576. res = cur.fetchone()[0]
  577. self.assertEqual(res, 6)
  578. def CheckScriptSyntaxError(self):
  579. con = sqlite.connect(":memory:")
  580. cur = con.cursor()
  581. raised = False
  582. try:
  583. cur.executescript("create table test(x); asdf; create table test2(x)")
  584. except sqlite.OperationalError:
  585. raised = True
  586. self.assertEqual(raised, True, "should have raised an exception")
  587. def CheckScriptErrorNormal(self):
  588. con = sqlite.connect(":memory:")
  589. cur = con.cursor()
  590. raised = False
  591. try:
  592. cur.executescript("create table test(sadfsadfdsa); select foo from hurz;")
  593. except sqlite.OperationalError:
  594. raised = True
  595. self.assertEqual(raised, True, "should have raised an exception")
  596. def CheckConnectionExecute(self):
  597. con = sqlite.connect(":memory:")
  598. result = con.execute("select 5").fetchone()[0]
  599. self.assertEqual(result, 5, "Basic test of Connection.execute")
  600. def CheckConnectionExecutemany(self):
  601. con = sqlite.connect(":memory:")
  602. con.execute("create table test(foo)")
  603. con.executemany("insert into test(foo) values (?)", [(3,), (4,)])
  604. result = con.execute("select foo from test order by foo").fetchall()
  605. self.assertEqual(result[0][0], 3, "Basic test of Connection.executemany")
  606. self.assertEqual(result[1][0], 4, "Basic test of Connection.executemany")
  607. def CheckConnectionExecutescript(self):
  608. con = sqlite.connect(":memory:")
  609. con.executescript("create table test(foo); insert into test(foo) values (5);")
  610. result = con.execute("select foo from test").fetchone()[0]
  611. self.assertEqual(result, 5, "Basic test of Connection.executescript")
  612. class ClosedConTests(unittest.TestCase):
  613. def setUp(self):
  614. pass
  615. def tearDown(self):
  616. pass
  617. def CheckClosedConCursor(self):
  618. con = sqlite.connect(":memory:")
  619. con.close()
  620. try:
  621. cur = con.cursor()
  622. self.fail("Should have raised a ProgrammingError")
  623. except sqlite.ProgrammingError:
  624. pass
  625. except:
  626. self.fail("Should have raised a ProgrammingError")
  627. def CheckClosedConCommit(self):
  628. con = sqlite.connect(":memory:")
  629. con.close()
  630. try:
  631. con.commit()
  632. self.fail("Should have raised a ProgrammingError")
  633. except sqlite.ProgrammingError:
  634. pass
  635. except:
  636. self.fail("Should have raised a ProgrammingError")
  637. def CheckClosedConRollback(self):
  638. con = sqlite.connect(":memory:")
  639. con.close()
  640. try:
  641. con.rollback()
  642. self.fail("Should have raised a ProgrammingError")
  643. except sqlite.ProgrammingError:
  644. pass
  645. except:
  646. self.fail("Should have raised a ProgrammingError")
  647. def CheckClosedCurExecute(self):
  648. con = sqlite.connect(":memory:")
  649. cur = con.cursor()
  650. con.close()
  651. try:
  652. cur.execute("select 4")
  653. self.fail("Should have raised a ProgrammingError")
  654. except sqlite.ProgrammingError:
  655. pass
  656. except:
  657. self.fail("Should have raised a ProgrammingError")
  658. def CheckClosedCreateFunction(self):
  659. con = sqlite.connect(":memory:")
  660. con.close()
  661. def f(x): return 17
  662. try:
  663. con.create_function("foo", 1, f)
  664. self.fail("Should have raised a ProgrammingError")
  665. except sqlite.ProgrammingError:
  666. pass
  667. except:
  668. self.fail("Should have raised a ProgrammingError")
  669. def CheckClosedCreateAggregate(self):
  670. con = sqlite.connect(":memory:")
  671. con.close()
  672. class Agg:
  673. def __init__(self):
  674. pass
  675. def step(self, x):
  676. pass
  677. def finalize(self):
  678. return 17
  679. try:
  680. con.create_aggregate("foo", 1, Agg)
  681. self.fail("Should have raised a ProgrammingError")
  682. except sqlite.ProgrammingError:
  683. pass
  684. except:
  685. self.fail("Should have raised a ProgrammingError")
  686. def CheckClosedSetAuthorizer(self):
  687. con = sqlite.connect(":memory:")
  688. con.close()
  689. def authorizer(*args):
  690. return sqlite.DENY
  691. try:
  692. con.set_authorizer(authorizer)
  693. self.fail("Should have raised a ProgrammingError")
  694. except sqlite.ProgrammingError:
  695. pass
  696. except:
  697. self.fail("Should have raised a ProgrammingError")
  698. def CheckClosedSetProgressCallback(self):
  699. con = sqlite.connect(":memory:")
  700. con.close()
  701. def progress(): pass
  702. try:
  703. con.set_progress_handler(progress, 100)
  704. self.fail("Should have raised a ProgrammingError")
  705. except sqlite.ProgrammingError:
  706. pass
  707. except:
  708. self.fail("Should have raised a ProgrammingError")
  709. def CheckClosedCall(self):
  710. con = sqlite.connect(":memory:")
  711. con.close()
  712. try:
  713. con()
  714. self.fail("Should have raised a ProgrammingError")
  715. except sqlite.ProgrammingError:
  716. pass
  717. except:
  718. self.fail("Should have raised a ProgrammingError")
  719. class ClosedCurTests(unittest.TestCase):
  720. def setUp(self):
  721. pass
  722. def tearDown(self):
  723. pass
  724. def CheckClosed(self):
  725. con = sqlite.connect(":memory:")
  726. cur = con.cursor()
  727. cur.close()
  728. for method_name in ("execute", "executemany", "executescript", "fetchall", "fetchmany", "fetchone"):
  729. if method_name in ("execute", "executescript"):
  730. params = ("select 4 union select 5",)
  731. elif method_name == "executemany":
  732. params = ("insert into foo(bar) values (?)", [(3,), (4,)])
  733. else:
  734. params = []
  735. try:
  736. method = getattr(cur, method_name)
  737. method(*params)
  738. self.fail("Should have raised a ProgrammingError: method " + method_name)
  739. except sqlite.ProgrammingError:
  740. pass
  741. except:
  742. self.fail("Should have raised a ProgrammingError: " + method_name)
  743. def suite():
  744. module_suite = unittest.makeSuite(ModuleTests, "Check")
  745. connection_suite = unittest.makeSuite(ConnectionTests, "Check")
  746. cursor_suite = unittest.makeSuite(CursorTests, "Check")
  747. thread_suite = unittest.makeSuite(ThreadTests, "Check")
  748. constructor_suite = unittest.makeSuite(ConstructorTests, "Check")
  749. ext_suite = unittest.makeSuite(ExtensionTests, "Check")
  750. closed_con_suite = unittest.makeSuite(ClosedConTests, "Check")
  751. closed_cur_suite = unittest.makeSuite(ClosedCurTests, "Check")
  752. return unittest.TestSuite((module_suite, connection_suite, cursor_suite, thread_suite, constructor_suite, ext_suite, closed_con_suite, closed_cur_suite))
  753. def test():
  754. runner = unittest.TextTestRunner()
  755. runner.run(suite())
  756. if __name__ == "__main__":
  757. test()