PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/sqlite3/test/dbapi.py

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