PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/sqlite3/test/dbapi.py

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