PageRenderTime 67ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/sqlite3/test/dbapi.py

https://bitbucket.org/mirror/cpython/
Python | 839 lines | 771 code | 38 blank | 30 comment | 16 complexity | 1327d5eba618da0783d510f0e1cbf90a MD5 | raw file
Possible License(s): Unlicense, 0BSD, BSD-3-Clause
  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 sqlite3 as sqlite
  25. try:
  26. import threading
  27. except ImportError:
  28. threading = None
  29. from test.support import TESTFN, unlink
  30. class ModuleTests(unittest.TestCase):
  31. def CheckAPILevel(self):
  32. self.assertEqual(sqlite.apilevel, "2.0",
  33. "apilevel is %s, should be 2.0" % sqlite.apilevel)
  34. def CheckThreadSafety(self):
  35. self.assertEqual(sqlite.threadsafety, 1,
  36. "threadsafety is %d, should be 1" % sqlite.threadsafety)
  37. def CheckParamStyle(self):
  38. self.assertEqual(sqlite.paramstyle, "qmark",
  39. "paramstyle is '%s', should be 'qmark'" %
  40. sqlite.paramstyle)
  41. def CheckWarning(self):
  42. self.assertTrue(issubclass(sqlite.Warning, Exception),
  43. "Warning is not a subclass of Exception")
  44. def CheckError(self):
  45. self.assertTrue(issubclass(sqlite.Error, Exception),
  46. "Error is not a subclass of Exception")
  47. def CheckInterfaceError(self):
  48. self.assertTrue(issubclass(sqlite.InterfaceError, sqlite.Error),
  49. "InterfaceError is not a subclass of Error")
  50. def CheckDatabaseError(self):
  51. self.assertTrue(issubclass(sqlite.DatabaseError, sqlite.Error),
  52. "DatabaseError is not a subclass of Error")
  53. def CheckDataError(self):
  54. self.assertTrue(issubclass(sqlite.DataError, sqlite.DatabaseError),
  55. "DataError is not a subclass of DatabaseError")
  56. def CheckOperationalError(self):
  57. self.assertTrue(issubclass(sqlite.OperationalError, sqlite.DatabaseError),
  58. "OperationalError is not a subclass of DatabaseError")
  59. def CheckIntegrityError(self):
  60. self.assertTrue(issubclass(sqlite.IntegrityError, sqlite.DatabaseError),
  61. "IntegrityError is not a subclass of DatabaseError")
  62. def CheckInternalError(self):
  63. self.assertTrue(issubclass(sqlite.InternalError, sqlite.DatabaseError),
  64. "InternalError is not a subclass of DatabaseError")
  65. def CheckProgrammingError(self):
  66. self.assertTrue(issubclass(sqlite.ProgrammingError, sqlite.DatabaseError),
  67. "ProgrammingError is not a subclass of DatabaseError")
  68. def CheckNotSupportedError(self):
  69. self.assertTrue(issubclass(sqlite.NotSupportedError,
  70. sqlite.DatabaseError),
  71. "NotSupportedError is not a subclass of DatabaseError")
  72. class ConnectionTests(unittest.TestCase):
  73. def setUp(self):
  74. self.cx = sqlite.connect(":memory:")
  75. cu = self.cx.cursor()
  76. cu.execute("create table test(id integer primary key, name text)")
  77. cu.execute("insert into test(name) values (?)", ("foo",))
  78. def tearDown(self):
  79. self.cx.close()
  80. def CheckCommit(self):
  81. self.cx.commit()
  82. def CheckCommitAfterNoChanges(self):
  83. """
  84. A commit should also work when no changes were made to the database.
  85. """
  86. self.cx.commit()
  87. self.cx.commit()
  88. def CheckRollback(self):
  89. self.cx.rollback()
  90. def CheckRollbackAfterNoChanges(self):
  91. """
  92. A rollback should also work when no changes were made to the database.
  93. """
  94. self.cx.rollback()
  95. self.cx.rollback()
  96. def CheckCursor(self):
  97. cu = self.cx.cursor()
  98. def CheckFailedOpen(self):
  99. YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
  100. with self.assertRaises(sqlite.OperationalError):
  101. con = sqlite.connect(YOU_CANNOT_OPEN_THIS)
  102. def CheckClose(self):
  103. self.cx.close()
  104. def CheckExceptions(self):
  105. # Optional DB-API extension.
  106. self.assertEqual(self.cx.Warning, sqlite.Warning)
  107. self.assertEqual(self.cx.Error, sqlite.Error)
  108. self.assertEqual(self.cx.InterfaceError, sqlite.InterfaceError)
  109. self.assertEqual(self.cx.DatabaseError, sqlite.DatabaseError)
  110. self.assertEqual(self.cx.DataError, sqlite.DataError)
  111. self.assertEqual(self.cx.OperationalError, sqlite.OperationalError)
  112. self.assertEqual(self.cx.IntegrityError, sqlite.IntegrityError)
  113. self.assertEqual(self.cx.InternalError, sqlite.InternalError)
  114. self.assertEqual(self.cx.ProgrammingError, sqlite.ProgrammingError)
  115. self.assertEqual(self.cx.NotSupportedError, sqlite.NotSupportedError)
  116. def CheckInTransaction(self):
  117. # Can't use db from setUp because we want to test initial state.
  118. cx = sqlite.connect(":memory:")
  119. cu = cx.cursor()
  120. self.assertEqual(cx.in_transaction, False)
  121. cu.execute("create table transactiontest(id integer primary key, name text)")
  122. self.assertEqual(cx.in_transaction, False)
  123. cu.execute("insert into transactiontest(name) values (?)", ("foo",))
  124. self.assertEqual(cx.in_transaction, True)
  125. cu.execute("select name from transactiontest where name=?", ["foo"])
  126. row = cu.fetchone()
  127. self.assertEqual(cx.in_transaction, True)
  128. cx.commit()
  129. self.assertEqual(cx.in_transaction, False)
  130. cu.execute("select name from transactiontest where name=?", ["foo"])
  131. row = cu.fetchone()
  132. self.assertEqual(cx.in_transaction, False)
  133. def CheckInTransactionRO(self):
  134. with self.assertRaises(AttributeError):
  135. self.cx.in_transaction = True
  136. def CheckOpenUri(self):
  137. if sqlite.sqlite_version_info < (3, 7, 7):
  138. with self.assertRaises(sqlite.NotSupportedError):
  139. sqlite.connect(':memory:', uri=True)
  140. return
  141. self.addCleanup(unlink, TESTFN)
  142. with sqlite.connect(TESTFN) as cx:
  143. cx.execute('create table test(id integer)')
  144. with sqlite.connect('file:' + TESTFN, uri=True) as cx:
  145. cx.execute('insert into test(id) values(0)')
  146. with sqlite.connect('file:' + TESTFN + '?mode=ro', uri=True) as cx:
  147. with self.assertRaises(sqlite.OperationalError):
  148. cx.execute('insert into test(id) values(1)')
  149. @unittest.skipIf(sqlite.sqlite_version_info >= (3, 3, 1),
  150. 'needs sqlite versions older than 3.3.1')
  151. def CheckSameThreadErrorOnOldVersion(self):
  152. with self.assertRaises(sqlite.NotSupportedError) as cm:
  153. sqlite.connect(':memory:', check_same_thread=False)
  154. self.assertEqual(str(cm.exception), 'shared connections not available')
  155. class CursorTests(unittest.TestCase):
  156. def setUp(self):
  157. self.cx = sqlite.connect(":memory:")
  158. self.cu = self.cx.cursor()
  159. self.cu.execute(
  160. "create table test(id integer primary key, name text, "
  161. "income number, unique_test text unique)"
  162. )
  163. self.cu.execute("insert into test(name) values (?)", ("foo",))
  164. def tearDown(self):
  165. self.cu.close()
  166. self.cx.close()
  167. def CheckExecuteNoArgs(self):
  168. self.cu.execute("delete from test")
  169. def CheckExecuteIllegalSql(self):
  170. with self.assertRaises(sqlite.OperationalError):
  171. self.cu.execute("select asdf")
  172. def CheckExecuteTooMuchSql(self):
  173. with self.assertRaises(sqlite.Warning):
  174. self.cu.execute("select 5+4; select 4+5")
  175. def CheckExecuteTooMuchSql2(self):
  176. self.cu.execute("select 5+4; -- foo bar")
  177. def CheckExecuteTooMuchSql3(self):
  178. self.cu.execute("""
  179. select 5+4;
  180. /*
  181. foo
  182. */
  183. """)
  184. def CheckExecuteWrongSqlArg(self):
  185. with self.assertRaises(ValueError):
  186. self.cu.execute(42)
  187. def CheckExecuteArgInt(self):
  188. self.cu.execute("insert into test(id) values (?)", (42,))
  189. def CheckExecuteArgFloat(self):
  190. self.cu.execute("insert into test(income) values (?)", (2500.32,))
  191. def CheckExecuteArgString(self):
  192. self.cu.execute("insert into test(name) values (?)", ("Hugo",))
  193. def CheckExecuteArgStringWithZeroByte(self):
  194. self.cu.execute("insert into test(name) values (?)", ("Hu\x00go",))
  195. self.cu.execute("select name from test where id=?", (self.cu.lastrowid,))
  196. row = self.cu.fetchone()
  197. self.assertEqual(row[0], "Hu\x00go")
  198. def CheckExecuteNonIterable(self):
  199. with self.assertRaises(ValueError) as cm:
  200. self.cu.execute("insert into test(id) values (?)", 42)
  201. self.assertEqual(str(cm.exception), 'parameters are of unsupported type')
  202. def CheckExecuteWrongNoOfArgs1(self):
  203. # too many parameters
  204. with self.assertRaises(sqlite.ProgrammingError):
  205. self.cu.execute("insert into test(id) values (?)", (17, "Egon"))
  206. def CheckExecuteWrongNoOfArgs2(self):
  207. # too little parameters
  208. with self.assertRaises(sqlite.ProgrammingError):
  209. self.cu.execute("insert into test(id) values (?)")
  210. def CheckExecuteWrongNoOfArgs3(self):
  211. # no parameters, parameters are needed
  212. with self.assertRaises(sqlite.ProgrammingError):
  213. self.cu.execute("insert into test(id) values (?)")
  214. def CheckExecuteParamList(self):
  215. self.cu.execute("insert into test(name) values ('foo')")
  216. self.cu.execute("select name from test where name=?", ["foo"])
  217. row = self.cu.fetchone()
  218. self.assertEqual(row[0], "foo")
  219. def CheckExecuteParamSequence(self):
  220. class L(object):
  221. def __len__(self):
  222. return 1
  223. def __getitem__(self, x):
  224. assert x == 0
  225. return "foo"
  226. self.cu.execute("insert into test(name) values ('foo')")
  227. self.cu.execute("select name from test where name=?", L())
  228. row = self.cu.fetchone()
  229. self.assertEqual(row[0], "foo")
  230. def CheckExecuteDictMapping(self):
  231. self.cu.execute("insert into test(name) values ('foo')")
  232. self.cu.execute("select name from test where name=:name", {"name": "foo"})
  233. row = self.cu.fetchone()
  234. self.assertEqual(row[0], "foo")
  235. def CheckExecuteDictMapping_Mapping(self):
  236. class D(dict):
  237. def __missing__(self, key):
  238. return "foo"
  239. self.cu.execute("insert into test(name) values ('foo')")
  240. self.cu.execute("select name from test where name=:name", D())
  241. row = self.cu.fetchone()
  242. self.assertEqual(row[0], "foo")
  243. def CheckExecuteDictMappingTooLittleArgs(self):
  244. self.cu.execute("insert into test(name) values ('foo')")
  245. with self.assertRaises(sqlite.ProgrammingError):
  246. self.cu.execute("select name from test where name=:name and id=:id", {"name": "foo"})
  247. def CheckExecuteDictMappingNoArgs(self):
  248. self.cu.execute("insert into test(name) values ('foo')")
  249. with self.assertRaises(sqlite.ProgrammingError):
  250. self.cu.execute("select name from test where name=:name")
  251. def CheckExecuteDictMappingUnnamed(self):
  252. self.cu.execute("insert into test(name) values ('foo')")
  253. with self.assertRaises(sqlite.ProgrammingError):
  254. self.cu.execute("select name from test where name=?", {"name": "foo"})
  255. def CheckClose(self):
  256. self.cu.close()
  257. def CheckRowcountExecute(self):
  258. self.cu.execute("delete from test")
  259. self.cu.execute("insert into test(name) values ('foo')")
  260. self.cu.execute("insert into test(name) values ('foo')")
  261. self.cu.execute("update test set name='bar'")
  262. self.assertEqual(self.cu.rowcount, 2)
  263. def CheckRowcountSelect(self):
  264. """
  265. pysqlite does not know the rowcount of SELECT statements, because we
  266. don't fetch all rows after executing the select statement. The rowcount
  267. has thus to be -1.
  268. """
  269. self.cu.execute("select 5 union select 6")
  270. self.assertEqual(self.cu.rowcount, -1)
  271. def CheckRowcountExecutemany(self):
  272. self.cu.execute("delete from test")
  273. self.cu.executemany("insert into test(name) values (?)", [(1,), (2,), (3,)])
  274. self.assertEqual(self.cu.rowcount, 3)
  275. def CheckTotalChanges(self):
  276. self.cu.execute("insert into test(name) values ('foo')")
  277. self.cu.execute("insert into test(name) values ('foo')")
  278. self.assertLess(2, self.cx.total_changes, msg='total changes reported wrong value')
  279. # Checks for executemany:
  280. # Sequences are required by the DB-API, iterators
  281. # enhancements in pysqlite.
  282. def CheckExecuteManySequence(self):
  283. self.cu.executemany("insert into test(income) values (?)", [(x,) for x in range(100, 110)])
  284. def CheckExecuteManyIterator(self):
  285. class MyIter:
  286. def __init__(self):
  287. self.value = 5
  288. def __next__(self):
  289. if self.value == 10:
  290. raise StopIteration
  291. else:
  292. self.value += 1
  293. return (self.value,)
  294. self.cu.executemany("insert into test(income) values (?)", MyIter())
  295. def CheckExecuteManyGenerator(self):
  296. def mygen():
  297. for i in range(5):
  298. yield (i,)
  299. self.cu.executemany("insert into test(income) values (?)", mygen())
  300. def CheckExecuteManyWrongSqlArg(self):
  301. with self.assertRaises(ValueError):
  302. self.cu.executemany(42, [(3,)])
  303. def CheckExecuteManySelect(self):
  304. with self.assertRaises(sqlite.ProgrammingError):
  305. self.cu.executemany("select ?", [(3,)])
  306. def CheckExecuteManyNotIterable(self):
  307. with self.assertRaises(TypeError):
  308. self.cu.executemany("insert into test(income) values (?)", 42)
  309. def CheckFetchIter(self):
  310. # Optional DB-API extension.
  311. self.cu.execute("delete from test")
  312. self.cu.execute("insert into test(id) values (?)", (5,))
  313. self.cu.execute("insert into test(id) values (?)", (6,))
  314. self.cu.execute("select id from test order by id")
  315. lst = []
  316. for row in self.cu:
  317. lst.append(row[0])
  318. self.assertEqual(lst[0], 5)
  319. self.assertEqual(lst[1], 6)
  320. def CheckFetchone(self):
  321. self.cu.execute("select name from test")
  322. row = self.cu.fetchone()
  323. self.assertEqual(row[0], "foo")
  324. row = self.cu.fetchone()
  325. self.assertEqual(row, None)
  326. def CheckFetchoneNoStatement(self):
  327. cur = self.cx.cursor()
  328. row = cur.fetchone()
  329. self.assertEqual(row, None)
  330. def CheckArraySize(self):
  331. # must default ot 1
  332. self.assertEqual(self.cu.arraysize, 1)
  333. # now set to 2
  334. self.cu.arraysize = 2
  335. # now make the query return 3 rows
  336. self.cu.execute("delete from test")
  337. self.cu.execute("insert into test(name) values ('A')")
  338. self.cu.execute("insert into test(name) values ('B')")
  339. self.cu.execute("insert into test(name) values ('C')")
  340. self.cu.execute("select name from test")
  341. res = self.cu.fetchmany()
  342. self.assertEqual(len(res), 2)
  343. def CheckFetchmany(self):
  344. self.cu.execute("select name from test")
  345. res = self.cu.fetchmany(100)
  346. self.assertEqual(len(res), 1)
  347. res = self.cu.fetchmany(100)
  348. self.assertEqual(res, [])
  349. def CheckFetchmanyKwArg(self):
  350. """Checks if fetchmany works with keyword arguments"""
  351. self.cu.execute("select name from test")
  352. res = self.cu.fetchmany(size=100)
  353. self.assertEqual(len(res), 1)
  354. def CheckFetchall(self):
  355. self.cu.execute("select name from test")
  356. res = self.cu.fetchall()
  357. self.assertEqual(len(res), 1)
  358. res = self.cu.fetchall()
  359. self.assertEqual(res, [])
  360. def CheckSetinputsizes(self):
  361. self.cu.setinputsizes([3, 4, 5])
  362. def CheckSetoutputsize(self):
  363. self.cu.setoutputsize(5, 0)
  364. def CheckSetoutputsizeNoColumn(self):
  365. self.cu.setoutputsize(42)
  366. def CheckCursorConnection(self):
  367. # Optional DB-API extension.
  368. self.assertEqual(self.cu.connection, self.cx)
  369. def CheckWrongCursorCallable(self):
  370. with self.assertRaises(TypeError):
  371. def f(): pass
  372. cur = self.cx.cursor(f)
  373. def CheckCursorWrongClass(self):
  374. class Foo: pass
  375. foo = Foo()
  376. with self.assertRaises(TypeError):
  377. cur = sqlite.Cursor(foo)
  378. def CheckLastRowIDOnReplace(self):
  379. """
  380. INSERT OR REPLACE and REPLACE INTO should produce the same behavior.
  381. """
  382. sql = '{} INTO test(id, unique_test) VALUES (?, ?)'
  383. for statement in ('INSERT OR REPLACE', 'REPLACE'):
  384. with self.subTest(statement=statement):
  385. self.cu.execute(sql.format(statement), (1, 'foo'))
  386. self.assertEqual(self.cu.lastrowid, 1)
  387. def CheckLastRowIDOnIgnore(self):
  388. self.cu.execute(
  389. "insert or ignore into test(unique_test) values (?)",
  390. ('test',))
  391. self.assertEqual(self.cu.lastrowid, 2)
  392. self.cu.execute(
  393. "insert or ignore into test(unique_test) values (?)",
  394. ('test',))
  395. self.assertEqual(self.cu.lastrowid, 2)
  396. def CheckLastRowIDInsertOR(self):
  397. results = []
  398. for statement in ('FAIL', 'ABORT', 'ROLLBACK'):
  399. sql = 'INSERT OR {} INTO test(unique_test) VALUES (?)'
  400. with self.subTest(statement='INSERT OR {}'.format(statement)):
  401. self.cu.execute(sql.format(statement), (statement,))
  402. results.append((statement, self.cu.lastrowid))
  403. with self.assertRaises(sqlite.IntegrityError):
  404. self.cu.execute(sql.format(statement), (statement,))
  405. results.append((statement, self.cu.lastrowid))
  406. expected = [
  407. ('FAIL', 2), ('FAIL', 2),
  408. ('ABORT', 3), ('ABORT', 3),
  409. ('ROLLBACK', 4), ('ROLLBACK', 4),
  410. ]
  411. self.assertEqual(results, expected)
  412. @unittest.skipUnless(threading, 'This test requires threading.')
  413. class ThreadTests(unittest.TestCase):
  414. def setUp(self):
  415. self.con = sqlite.connect(":memory:")
  416. self.cur = self.con.cursor()
  417. self.cur.execute("create table test(id integer primary key, name text, bin binary, ratio number, ts timestamp)")
  418. def tearDown(self):
  419. self.cur.close()
  420. self.con.close()
  421. def CheckConCursor(self):
  422. def run(con, errors):
  423. try:
  424. cur = con.cursor()
  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 CheckConCommit(self):
  438. def run(con, errors):
  439. try:
  440. con.commit()
  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 CheckConRollback(self):
  454. def run(con, errors):
  455. try:
  456. con.rollback()
  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 CheckConClose(self):
  470. def run(con, errors):
  471. try:
  472. con.close()
  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={"con": self.con, "errors": errors})
  481. t.start()
  482. t.join()
  483. if len(errors) > 0:
  484. self.fail("\n".join(errors))
  485. def CheckCurImplicitBegin(self):
  486. def run(cur, errors):
  487. try:
  488. cur.execute("insert into test(name) values ('a')")
  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 CheckCurClose(self):
  502. def run(cur, errors):
  503. try:
  504. cur.close()
  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. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  513. t.start()
  514. t.join()
  515. if len(errors) > 0:
  516. self.fail("\n".join(errors))
  517. def CheckCurExecute(self):
  518. def run(cur, errors):
  519. try:
  520. cur.execute("select name from test")
  521. errors.append("did not raise ProgrammingError")
  522. return
  523. except sqlite.ProgrammingError:
  524. return
  525. except:
  526. errors.append("raised wrong exception")
  527. errors = []
  528. self.cur.execute("insert into test(name) values ('a')")
  529. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  530. t.start()
  531. t.join()
  532. if len(errors) > 0:
  533. self.fail("\n".join(errors))
  534. def CheckCurIterNext(self):
  535. def run(cur, errors):
  536. try:
  537. row = cur.fetchone()
  538. errors.append("did not raise ProgrammingError")
  539. return
  540. except sqlite.ProgrammingError:
  541. return
  542. except:
  543. errors.append("raised wrong exception")
  544. errors = []
  545. self.cur.execute("insert into test(name) values ('a')")
  546. self.cur.execute("select name from test")
  547. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  548. t.start()
  549. t.join()
  550. if len(errors) > 0:
  551. self.fail("\n".join(errors))
  552. class ConstructorTests(unittest.TestCase):
  553. def CheckDate(self):
  554. d = sqlite.Date(2004, 10, 28)
  555. def CheckTime(self):
  556. t = sqlite.Time(12, 39, 35)
  557. def CheckTimestamp(self):
  558. ts = sqlite.Timestamp(2004, 10, 28, 12, 39, 35)
  559. def CheckDateFromTicks(self):
  560. d = sqlite.DateFromTicks(42)
  561. def CheckTimeFromTicks(self):
  562. t = sqlite.TimeFromTicks(42)
  563. def CheckTimestampFromTicks(self):
  564. ts = sqlite.TimestampFromTicks(42)
  565. def CheckBinary(self):
  566. b = sqlite.Binary(b"\0'")
  567. class ExtensionTests(unittest.TestCase):
  568. def CheckScriptStringSql(self):
  569. con = sqlite.connect(":memory:")
  570. cur = con.cursor()
  571. cur.executescript("""
  572. -- bla bla
  573. /* a stupid comment */
  574. create table a(i);
  575. insert into a(i) values (5);
  576. """)
  577. cur.execute("select i from a")
  578. res = cur.fetchone()[0]
  579. self.assertEqual(res, 5)
  580. def CheckScriptSyntaxError(self):
  581. con = sqlite.connect(":memory:")
  582. cur = con.cursor()
  583. with self.assertRaises(sqlite.OperationalError):
  584. cur.executescript("create table test(x); asdf; create table test2(x)")
  585. def CheckScriptErrorNormal(self):
  586. con = sqlite.connect(":memory:")
  587. cur = con.cursor()
  588. with self.assertRaises(sqlite.OperationalError):
  589. cur.executescript("create table test(sadfsadfdsa); select foo from hurz;")
  590. def CheckCursorExecutescriptAsBytes(self):
  591. con = sqlite.connect(":memory:")
  592. cur = con.cursor()
  593. with self.assertRaises(ValueError) as cm:
  594. cur.executescript(b"create table test(foo); insert into test(foo) values (5);")
  595. self.assertEqual(str(cm.exception), 'script argument must be unicode.')
  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 CheckClosedConCursor(self):
  614. con = sqlite.connect(":memory:")
  615. con.close()
  616. with self.assertRaises(sqlite.ProgrammingError):
  617. cur = con.cursor()
  618. def CheckClosedConCommit(self):
  619. con = sqlite.connect(":memory:")
  620. con.close()
  621. with self.assertRaises(sqlite.ProgrammingError):
  622. con.commit()
  623. def CheckClosedConRollback(self):
  624. con = sqlite.connect(":memory:")
  625. con.close()
  626. with self.assertRaises(sqlite.ProgrammingError):
  627. con.rollback()
  628. def CheckClosedCurExecute(self):
  629. con = sqlite.connect(":memory:")
  630. cur = con.cursor()
  631. con.close()
  632. with self.assertRaises(sqlite.ProgrammingError):
  633. cur.execute("select 4")
  634. def CheckClosedCreateFunction(self):
  635. con = sqlite.connect(":memory:")
  636. con.close()
  637. def f(x): return 17
  638. with self.assertRaises(sqlite.ProgrammingError):
  639. con.create_function("foo", 1, f)
  640. def CheckClosedCreateAggregate(self):
  641. con = sqlite.connect(":memory:")
  642. con.close()
  643. class Agg:
  644. def __init__(self):
  645. pass
  646. def step(self, x):
  647. pass
  648. def finalize(self):
  649. return 17
  650. with self.assertRaises(sqlite.ProgrammingError):
  651. con.create_aggregate("foo", 1, Agg)
  652. def CheckClosedSetAuthorizer(self):
  653. con = sqlite.connect(":memory:")
  654. con.close()
  655. def authorizer(*args):
  656. return sqlite.DENY
  657. with self.assertRaises(sqlite.ProgrammingError):
  658. con.set_authorizer(authorizer)
  659. def CheckClosedSetProgressCallback(self):
  660. con = sqlite.connect(":memory:")
  661. con.close()
  662. def progress(): pass
  663. with self.assertRaises(sqlite.ProgrammingError):
  664. con.set_progress_handler(progress, 100)
  665. def CheckClosedCall(self):
  666. con = sqlite.connect(":memory:")
  667. con.close()
  668. with self.assertRaises(sqlite.ProgrammingError):
  669. con()
  670. class ClosedCurTests(unittest.TestCase):
  671. def CheckClosed(self):
  672. con = sqlite.connect(":memory:")
  673. cur = con.cursor()
  674. cur.close()
  675. for method_name in ("execute", "executemany", "executescript", "fetchall", "fetchmany", "fetchone"):
  676. if method_name in ("execute", "executescript"):
  677. params = ("select 4 union select 5",)
  678. elif method_name == "executemany":
  679. params = ("insert into foo(bar) values (?)", [(3,), (4,)])
  680. else:
  681. params = []
  682. with self.assertRaises(sqlite.ProgrammingError):
  683. method = getattr(cur, method_name)
  684. method(*params)
  685. def suite():
  686. module_suite = unittest.makeSuite(ModuleTests, "Check")
  687. connection_suite = unittest.makeSuite(ConnectionTests, "Check")
  688. cursor_suite = unittest.makeSuite(CursorTests, "Check")
  689. thread_suite = unittest.makeSuite(ThreadTests, "Check")
  690. constructor_suite = unittest.makeSuite(ConstructorTests, "Check")
  691. ext_suite = unittest.makeSuite(ExtensionTests, "Check")
  692. closed_con_suite = unittest.makeSuite(ClosedConTests, "Check")
  693. closed_cur_suite = unittest.makeSuite(ClosedCurTests, "Check")
  694. return unittest.TestSuite((module_suite, connection_suite, cursor_suite, thread_suite, constructor_suite, ext_suite, closed_con_suite, closed_cur_suite))
  695. def test():
  696. runner = unittest.TextTestRunner()
  697. runner.run(suite())
  698. if __name__ == "__main__":
  699. test()