PageRenderTime 63ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/rokujyouhitoma/pypy/
Python | 885 lines | 825 code | 31 blank | 29 comment | 9 complexity | a0185ae8355e070afd7d1bb7fb72742c 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 __iter__(self):
  278. return self
  279. def next(self):
  280. if self.value == 10:
  281. raise StopIteration
  282. else:
  283. self.value += 1
  284. return (self.value,)
  285. self.cu.executemany("insert into test(income) values (?)", MyIter())
  286. def CheckExecuteManyGenerator(self):
  287. def mygen():
  288. for i in range(5):
  289. yield (i,)
  290. self.cu.executemany("insert into test(income) values (?)", mygen())
  291. def CheckExecuteManyWrongSqlArg(self):
  292. try:
  293. self.cu.executemany(42, [(3,)])
  294. self.fail("should have raised a ValueError")
  295. except ValueError:
  296. return
  297. except:
  298. self.fail("raised wrong exception.")
  299. def CheckExecuteManySelect(self):
  300. try:
  301. self.cu.executemany("select ?", [(3,)])
  302. self.fail("should have raised a ProgrammingError")
  303. except sqlite.ProgrammingError:
  304. return
  305. except:
  306. self.fail("raised wrong exception.")
  307. def CheckExecuteManyNotIterable(self):
  308. try:
  309. self.cu.executemany("insert into test(income) values (?)", 42)
  310. self.fail("should have raised a TypeError")
  311. except TypeError:
  312. return
  313. except Exception, e:
  314. print "raised", e.__class__
  315. self.fail("raised wrong exception.")
  316. def CheckFetchIter(self):
  317. # Optional DB-API extension.
  318. self.cu.execute("delete from test")
  319. self.cu.execute("insert into test(id) values (?)", (5,))
  320. self.cu.execute("insert into test(id) values (?)", (6,))
  321. self.cu.execute("select id from test order by id")
  322. lst = []
  323. for row in self.cu:
  324. lst.append(row[0])
  325. self.assertEqual(lst[0], 5)
  326. self.assertEqual(lst[1], 6)
  327. def CheckFetchone(self):
  328. self.cu.execute("select name from test")
  329. row = self.cu.fetchone()
  330. self.assertEqual(row[0], "foo")
  331. row = self.cu.fetchone()
  332. self.assertEqual(row, None)
  333. def CheckFetchoneNoStatement(self):
  334. cur = self.cx.cursor()
  335. row = cur.fetchone()
  336. self.assertEqual(row, None)
  337. def CheckArraySize(self):
  338. # must default ot 1
  339. self.assertEqual(self.cu.arraysize, 1)
  340. # now set to 2
  341. self.cu.arraysize = 2
  342. # now make the query return 3 rows
  343. self.cu.execute("delete from test")
  344. self.cu.execute("insert into test(name) values ('A')")
  345. self.cu.execute("insert into test(name) values ('B')")
  346. self.cu.execute("insert into test(name) values ('C')")
  347. self.cu.execute("select name from test")
  348. res = self.cu.fetchmany()
  349. self.assertEqual(len(res), 2)
  350. def CheckFetchmany(self):
  351. self.cu.execute("select name from test")
  352. res = self.cu.fetchmany(100)
  353. self.assertEqual(len(res), 1)
  354. res = self.cu.fetchmany(100)
  355. self.assertEqual(res, [])
  356. def CheckFetchmanyKwArg(self):
  357. """Checks if fetchmany works with keyword arguments"""
  358. self.cu.execute("select name from test")
  359. res = self.cu.fetchmany(size=100)
  360. self.assertEqual(len(res), 1)
  361. def CheckFetchall(self):
  362. self.cu.execute("select name from test")
  363. res = self.cu.fetchall()
  364. self.assertEqual(len(res), 1)
  365. res = self.cu.fetchall()
  366. self.assertEqual(res, [])
  367. def CheckSetinputsizes(self):
  368. self.cu.setinputsizes([3, 4, 5])
  369. def CheckSetoutputsize(self):
  370. self.cu.setoutputsize(5, 0)
  371. def CheckSetoutputsizeNoColumn(self):
  372. self.cu.setoutputsize(42)
  373. def CheckCursorConnection(self):
  374. # Optional DB-API extension.
  375. self.assertEqual(self.cu.connection, self.cx)
  376. def CheckWrongCursorCallable(self):
  377. try:
  378. def f(): pass
  379. cur = self.cx.cursor(f)
  380. self.fail("should have raised a TypeError")
  381. except TypeError:
  382. return
  383. self.fail("should have raised a ValueError")
  384. def CheckCursorWrongClass(self):
  385. class Foo: pass
  386. foo = Foo()
  387. try:
  388. cur = sqlite.Cursor(foo)
  389. self.fail("should have raised a ValueError")
  390. except TypeError:
  391. pass
  392. @unittest.skipUnless(threading, 'This test requires threading.')
  393. class ThreadTests(unittest.TestCase):
  394. def setUp(self):
  395. self.con = sqlite.connect(":memory:")
  396. self.cur = self.con.cursor()
  397. self.cur.execute("create table test(id integer primary key, name text, bin binary, ratio number, ts timestamp)")
  398. def tearDown(self):
  399. self.cur.close()
  400. self.con.close()
  401. def CheckConCursor(self):
  402. def run(con, errors):
  403. try:
  404. cur = con.cursor()
  405. errors.append("did not raise ProgrammingError")
  406. return
  407. except sqlite.ProgrammingError:
  408. return
  409. except:
  410. errors.append("raised wrong exception")
  411. errors = []
  412. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  413. t.start()
  414. t.join()
  415. if len(errors) > 0:
  416. self.fail("\n".join(errors))
  417. def CheckConCommit(self):
  418. def run(con, errors):
  419. try:
  420. con.commit()
  421. errors.append("did not raise ProgrammingError")
  422. return
  423. except sqlite.ProgrammingError:
  424. return
  425. except:
  426. errors.append("raised wrong exception")
  427. errors = []
  428. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  429. t.start()
  430. t.join()
  431. if len(errors) > 0:
  432. self.fail("\n".join(errors))
  433. def CheckConRollback(self):
  434. def run(con, errors):
  435. try:
  436. con.rollback()
  437. errors.append("did not raise ProgrammingError")
  438. return
  439. except sqlite.ProgrammingError:
  440. return
  441. except:
  442. errors.append("raised wrong exception")
  443. errors = []
  444. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  445. t.start()
  446. t.join()
  447. if len(errors) > 0:
  448. self.fail("\n".join(errors))
  449. def CheckConClose(self):
  450. def run(con, errors):
  451. try:
  452. con.close()
  453. errors.append("did not raise ProgrammingError")
  454. return
  455. except sqlite.ProgrammingError:
  456. return
  457. except:
  458. errors.append("raised wrong exception")
  459. errors = []
  460. t = threading.Thread(target=run, kwargs={"con": self.con, "errors": errors})
  461. t.start()
  462. t.join()
  463. if len(errors) > 0:
  464. self.fail("\n".join(errors))
  465. def CheckCurImplicitBegin(self):
  466. def run(cur, errors):
  467. try:
  468. cur.execute("insert into test(name) values ('a')")
  469. errors.append("did not raise ProgrammingError")
  470. return
  471. except sqlite.ProgrammingError:
  472. return
  473. except:
  474. errors.append("raised wrong exception")
  475. errors = []
  476. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  477. t.start()
  478. t.join()
  479. if len(errors) > 0:
  480. self.fail("\n".join(errors))
  481. def CheckCurClose(self):
  482. def run(cur, errors):
  483. try:
  484. cur.close()
  485. errors.append("did not raise ProgrammingError")
  486. return
  487. except sqlite.ProgrammingError:
  488. return
  489. except:
  490. errors.append("raised wrong exception")
  491. errors = []
  492. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  493. t.start()
  494. t.join()
  495. if len(errors) > 0:
  496. self.fail("\n".join(errors))
  497. def CheckCurExecute(self):
  498. def run(cur, errors):
  499. try:
  500. cur.execute("select name from test")
  501. errors.append("did not raise ProgrammingError")
  502. return
  503. except sqlite.ProgrammingError:
  504. return
  505. except:
  506. errors.append("raised wrong exception")
  507. errors = []
  508. self.cur.execute("insert into test(name) values ('a')")
  509. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  510. t.start()
  511. t.join()
  512. if len(errors) > 0:
  513. self.fail("\n".join(errors))
  514. def CheckCurIterNext(self):
  515. def run(cur, errors):
  516. try:
  517. row = cur.fetchone()
  518. errors.append("did not raise ProgrammingError")
  519. return
  520. except sqlite.ProgrammingError:
  521. return
  522. except:
  523. errors.append("raised wrong exception")
  524. errors = []
  525. self.cur.execute("insert into test(name) values ('a')")
  526. self.cur.execute("select name from test")
  527. t = threading.Thread(target=run, kwargs={"cur": self.cur, "errors": errors})
  528. t.start()
  529. t.join()
  530. if len(errors) > 0:
  531. self.fail("\n".join(errors))
  532. class ConstructorTests(unittest.TestCase):
  533. def CheckDate(self):
  534. d = sqlite.Date(2004, 10, 28)
  535. def CheckTime(self):
  536. t = sqlite.Time(12, 39, 35)
  537. def CheckTimestamp(self):
  538. ts = sqlite.Timestamp(2004, 10, 28, 12, 39, 35)
  539. def CheckDateFromTicks(self):
  540. d = sqlite.DateFromTicks(42)
  541. def CheckTimeFromTicks(self):
  542. t = sqlite.TimeFromTicks(42)
  543. def CheckTimestampFromTicks(self):
  544. ts = sqlite.TimestampFromTicks(42)
  545. def CheckBinary(self):
  546. b = sqlite.Binary(chr(0) + "'")
  547. class ExtensionTests(unittest.TestCase):
  548. def CheckScriptStringSql(self):
  549. con = sqlite.connect(":memory:")
  550. cur = con.cursor()
  551. cur.executescript("""
  552. -- bla bla
  553. /* a stupid comment */
  554. create table a(i);
  555. insert into a(i) values (5);
  556. """)
  557. cur.execute("select i from a")
  558. res = cur.fetchone()[0]
  559. self.assertEqual(res, 5)
  560. def CheckScriptStringUnicode(self):
  561. con = sqlite.connect(":memory:")
  562. cur = con.cursor()
  563. cur.executescript(u"""
  564. create table a(i);
  565. insert into a(i) values (5);
  566. select i from a;
  567. delete from a;
  568. insert into a(i) values (6);
  569. """)
  570. cur.execute("select i from a")
  571. res = cur.fetchone()[0]
  572. self.assertEqual(res, 6)
  573. def CheckScriptSyntaxError(self):
  574. con = sqlite.connect(":memory:")
  575. cur = con.cursor()
  576. raised = False
  577. try:
  578. cur.executescript("create table test(x); asdf; create table test2(x)")
  579. except sqlite.OperationalError:
  580. raised = True
  581. self.assertEqual(raised, True, "should have raised an exception")
  582. def CheckScriptErrorNormal(self):
  583. con = sqlite.connect(":memory:")
  584. cur = con.cursor()
  585. raised = False
  586. try:
  587. cur.executescript("create table test(sadfsadfdsa); select foo from hurz;")
  588. except sqlite.OperationalError:
  589. raised = True
  590. self.assertEqual(raised, True, "should have raised an exception")
  591. def CheckConnectionExecute(self):
  592. con = sqlite.connect(":memory:")
  593. result = con.execute("select 5").fetchone()[0]
  594. self.assertEqual(result, 5, "Basic test of Connection.execute")
  595. def CheckConnectionExecutemany(self):
  596. con = sqlite.connect(":memory:")
  597. con.execute("create table test(foo)")
  598. con.executemany("insert into test(foo) values (?)", [(3,), (4,)])
  599. result = con.execute("select foo from test order by foo").fetchall()
  600. self.assertEqual(result[0][0], 3, "Basic test of Connection.executemany")
  601. self.assertEqual(result[1][0], 4, "Basic test of Connection.executemany")
  602. def CheckConnectionExecutescript(self):
  603. con = sqlite.connect(":memory:")
  604. con.executescript("create table test(foo); insert into test(foo) values (5);")
  605. result = con.execute("select foo from test").fetchone()[0]
  606. self.assertEqual(result, 5, "Basic test of Connection.executescript")
  607. class ClosedConTests(unittest.TestCase):
  608. def setUp(self):
  609. pass
  610. def tearDown(self):
  611. pass
  612. def CheckClosedConCursor(self):
  613. con = sqlite.connect(":memory:")
  614. con.close()
  615. try:
  616. cur = con.cursor()
  617. self.fail("Should have raised a ProgrammingError")
  618. except sqlite.ProgrammingError:
  619. pass
  620. except:
  621. self.fail("Should have raised a ProgrammingError")
  622. def CheckClosedConCommit(self):
  623. con = sqlite.connect(":memory:")
  624. con.close()
  625. try:
  626. con.commit()
  627. self.fail("Should have raised a ProgrammingError")
  628. except sqlite.ProgrammingError:
  629. pass
  630. except:
  631. self.fail("Should have raised a ProgrammingError")
  632. def CheckClosedConRollback(self):
  633. con = sqlite.connect(":memory:")
  634. con.close()
  635. try:
  636. con.rollback()
  637. self.fail("Should have raised a ProgrammingError")
  638. except sqlite.ProgrammingError:
  639. pass
  640. except:
  641. self.fail("Should have raised a ProgrammingError")
  642. def CheckClosedCurExecute(self):
  643. con = sqlite.connect(":memory:")
  644. cur = con.cursor()
  645. con.close()
  646. try:
  647. cur.execute("select 4")
  648. self.fail("Should have raised a ProgrammingError")
  649. except sqlite.ProgrammingError:
  650. pass
  651. except:
  652. self.fail("Should have raised a ProgrammingError")
  653. def CheckClosedCreateFunction(self):
  654. con = sqlite.connect(":memory:")
  655. con.close()
  656. def f(x): return 17
  657. try:
  658. con.create_function("foo", 1, f)
  659. self.fail("Should have raised a ProgrammingError")
  660. except sqlite.ProgrammingError:
  661. pass
  662. except:
  663. self.fail("Should have raised a ProgrammingError")
  664. def CheckClosedCreateAggregate(self):
  665. con = sqlite.connect(":memory:")
  666. con.close()
  667. class Agg:
  668. def __init__(self):
  669. pass
  670. def step(self, x):
  671. pass
  672. def finalize(self):
  673. return 17
  674. try:
  675. con.create_aggregate("foo", 1, Agg)
  676. self.fail("Should have raised a ProgrammingError")
  677. except sqlite.ProgrammingError:
  678. pass
  679. except:
  680. self.fail("Should have raised a ProgrammingError")
  681. def CheckClosedSetAuthorizer(self):
  682. con = sqlite.connect(":memory:")
  683. con.close()
  684. def authorizer(*args):
  685. return sqlite.DENY
  686. try:
  687. con.set_authorizer(authorizer)
  688. self.fail("Should have raised a ProgrammingError")
  689. except sqlite.ProgrammingError:
  690. pass
  691. except:
  692. self.fail("Should have raised a ProgrammingError")
  693. def CheckClosedSetProgressCallback(self):
  694. con = sqlite.connect(":memory:")
  695. con.close()
  696. def progress(): pass
  697. try:
  698. con.set_progress_handler(progress, 100)
  699. self.fail("Should have raised a ProgrammingError")
  700. except sqlite.ProgrammingError:
  701. pass
  702. except:
  703. self.fail("Should have raised a ProgrammingError")
  704. def CheckClosedCall(self):
  705. con = sqlite.connect(":memory:")
  706. con.close()
  707. try:
  708. con("select 1")
  709. self.fail("Should have raised a ProgrammingError")
  710. except sqlite.ProgrammingError:
  711. pass
  712. except:
  713. self.fail("Should have raised a ProgrammingError")
  714. class ClosedCurTests(unittest.TestCase):
  715. def setUp(self):
  716. pass
  717. def tearDown(self):
  718. pass
  719. def CheckClosed(self):
  720. con = sqlite.connect(":memory:")
  721. cur = con.cursor()
  722. cur.close()
  723. for method_name in ("execute", "executemany", "executescript", "fetchall", "fetchmany", "fetchone"):
  724. if method_name in ("execute", "executescript"):
  725. params = ("select 4 union select 5",)
  726. elif method_name == "executemany":
  727. params = ("insert into foo(bar) values (?)", [(3,), (4,)])
  728. else:
  729. params = []
  730. try:
  731. method = getattr(cur, method_name)
  732. method(*params)
  733. self.fail("Should have raised a ProgrammingError: method " + method_name)
  734. except sqlite.ProgrammingError:
  735. pass
  736. except:
  737. self.fail("Should have raised a ProgrammingError: " + method_name)
  738. def suite():
  739. module_suite = unittest.makeSuite(ModuleTests, "Check")
  740. connection_suite = unittest.makeSuite(ConnectionTests, "Check")
  741. cursor_suite = unittest.makeSuite(CursorTests, "Check")
  742. thread_suite = unittest.makeSuite(ThreadTests, "Check")
  743. constructor_suite = unittest.makeSuite(ConstructorTests, "Check")
  744. ext_suite = unittest.makeSuite(ExtensionTests, "Check")
  745. closed_con_suite = unittest.makeSuite(ClosedConTests, "Check")
  746. closed_cur_suite = unittest.makeSuite(ClosedCurTests, "Check")
  747. return unittest.TestSuite((module_suite, connection_suite, cursor_suite, thread_suite, constructor_suite, ext_suite, closed_con_suite, closed_cur_suite))
  748. def test():
  749. runner = unittest.TextTestRunner()
  750. runner.run(suite())
  751. if __name__ == "__main__":
  752. test()