regression.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #-*- coding: iso-8859-1 -*-
  2. # pysqlite2/test/regression.py: pysqlite regression tests
  3. #
  4. # Copyright (C) 2006-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 datetime
  24. import unittest
  25. import sqlite3 as sqlite
  26. import weakref
  27. from test import support
  28. class RegressionTests(unittest.TestCase):
  29. def setUp(self):
  30. self.con = sqlite.connect(":memory:")
  31. def tearDown(self):
  32. self.con.close()
  33. def CheckPragmaUserVersion(self):
  34. # This used to crash pysqlite because this pragma command returns NULL for the column name
  35. cur = self.con.cursor()
  36. cur.execute("pragma user_version")
  37. def CheckPragmaSchemaVersion(self):
  38. # This still crashed pysqlite <= 2.2.1
  39. con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
  40. try:
  41. cur = self.con.cursor()
  42. cur.execute("pragma schema_version")
  43. finally:
  44. cur.close()
  45. con.close()
  46. def CheckStatementReset(self):
  47. # pysqlite 2.1.0 to 2.2.0 have the problem that not all statements are
  48. # reset before a rollback, but only those that are still in the
  49. # statement cache. The others are not accessible from the connection object.
  50. con = sqlite.connect(":memory:", cached_statements=5)
  51. cursors = [con.cursor() for x in range(5)]
  52. cursors[0].execute("create table test(x)")
  53. for i in range(10):
  54. cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in range(10)])
  55. for i in range(5):
  56. cursors[i].execute(" " * i + "select x from test")
  57. con.rollback()
  58. def CheckColumnNameWithSpaces(self):
  59. cur = self.con.cursor()
  60. cur.execute('select 1 as "foo bar [datetime]"')
  61. self.assertEqual(cur.description[0][0], "foo bar")
  62. cur.execute('select 1 as "foo baz"')
  63. self.assertEqual(cur.description[0][0], "foo baz")
  64. def CheckStatementFinalizationOnCloseDb(self):
  65. # pysqlite versions <= 2.3.3 only finalized statements in the statement
  66. # cache when closing the database. statements that were still
  67. # referenced in cursors weren't closed and could provoke "
  68. # "OperationalError: Unable to close due to unfinalised statements".
  69. con = sqlite.connect(":memory:")
  70. cursors = []
  71. # default statement cache size is 100
  72. for i in range(105):
  73. cur = con.cursor()
  74. cursors.append(cur)
  75. cur.execute("select 1 x union select " + str(i))
  76. con.close()
  77. @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 2), 'needs sqlite 3.2.2 or newer')
  78. def CheckOnConflictRollback(self):
  79. con = sqlite.connect(":memory:")
  80. con.execute("create table foo(x, unique(x) on conflict rollback)")
  81. con.execute("insert into foo(x) values (1)")
  82. try:
  83. con.execute("insert into foo(x) values (1)")
  84. except sqlite.DatabaseError:
  85. pass
  86. con.execute("insert into foo(x) values (2)")
  87. try:
  88. con.commit()
  89. except sqlite.OperationalError:
  90. self.fail("pysqlite knew nothing about the implicit ROLLBACK")
  91. def CheckWorkaroundForBuggySqliteTransferBindings(self):
  92. """
  93. pysqlite would crash with older SQLite versions unless
  94. a workaround is implemented.
  95. """
  96. self.con.execute("create table foo(bar)")
  97. self.con.execute("drop table foo")
  98. self.con.execute("create table foo(bar)")
  99. def CheckEmptyStatement(self):
  100. """
  101. pysqlite used to segfault with SQLite versions 3.5.x. These return NULL
  102. for "no-operation" statements
  103. """
  104. self.con.execute("")
  105. def CheckTypeMapUsage(self):
  106. """
  107. pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling
  108. a statement. This test exhibits the problem.
  109. """
  110. SELECT = "select * from foo"
  111. con = sqlite.connect(":memory:",detect_types=sqlite.PARSE_DECLTYPES)
  112. con.execute("create table foo(bar timestamp)")
  113. con.execute("insert into foo(bar) values (?)", (datetime.datetime.now(),))
  114. con.execute(SELECT)
  115. con.execute("drop table foo")
  116. con.execute("create table foo(bar integer)")
  117. con.execute("insert into foo(bar) values (5)")
  118. con.execute(SELECT)
  119. def CheckErrorMsgDecodeError(self):
  120. # When porting the module to Python 3.0, the error message about
  121. # decoding errors disappeared. This verifies they're back again.
  122. with self.assertRaises(sqlite.OperationalError) as cm:
  123. self.con.execute("select 'xxx' || ? || 'yyy' colname",
  124. (bytes(bytearray([250])),)).fetchone()
  125. msg = "Could not decode to UTF-8 column 'colname' with text 'xxx"
  126. self.assertIn(msg, str(cm.exception))
  127. def CheckRegisterAdapter(self):
  128. """
  129. See issue 3312.
  130. """
  131. self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
  132. def CheckSetIsolationLevel(self):
  133. # See issue 27881.
  134. class CustomStr(str):
  135. def upper(self):
  136. return None
  137. def __del__(self):
  138. con.isolation_level = ""
  139. con = sqlite.connect(":memory:")
  140. con.isolation_level = None
  141. for level in "", "DEFERRED", "IMMEDIATE", "EXCLUSIVE":
  142. with self.subTest(level=level):
  143. con.isolation_level = level
  144. con.isolation_level = level.lower()
  145. con.isolation_level = level.capitalize()
  146. con.isolation_level = CustomStr(level)
  147. # setting isolation_level failure should not alter previous state
  148. con.isolation_level = None
  149. con.isolation_level = "DEFERRED"
  150. pairs = [
  151. (1, TypeError), (b'', TypeError), ("abc", ValueError),
  152. ("IMMEDIATE\0EXCLUSIVE", ValueError), ("\xe9", ValueError),
  153. ]
  154. for value, exc in pairs:
  155. with self.subTest(level=value):
  156. with self.assertRaises(exc):
  157. con.isolation_level = value
  158. self.assertEqual(con.isolation_level, "DEFERRED")
  159. def CheckCursorConstructorCallCheck(self):
  160. """
  161. Verifies that cursor methods check whether base class __init__ was
  162. called.
  163. """
  164. class Cursor(sqlite.Cursor):
  165. def __init__(self, con):
  166. pass
  167. con = sqlite.connect(":memory:")
  168. cur = Cursor(con)
  169. with self.assertRaises(sqlite.ProgrammingError):
  170. cur.execute("select 4+5").fetchall()
  171. with self.assertRaisesRegex(sqlite.ProgrammingError,
  172. r'^Base Cursor\.__init__ not called\.$'):
  173. cur.close()
  174. def CheckStrSubclass(self):
  175. """
  176. The Python 3.0 port of the module didn't cope with values of subclasses of str.
  177. """
  178. class MyStr(str): pass
  179. self.con.execute("select ?", (MyStr("abc"),))
  180. def CheckConnectionConstructorCallCheck(self):
  181. """
  182. Verifies that connection methods check whether base class __init__ was
  183. called.
  184. """
  185. class Connection(sqlite.Connection):
  186. def __init__(self, name):
  187. pass
  188. con = Connection(":memory:")
  189. with self.assertRaises(sqlite.ProgrammingError):
  190. cur = con.cursor()
  191. def CheckCursorRegistration(self):
  192. """
  193. Verifies that subclassed cursor classes are correctly registered with
  194. the connection object, too. (fetch-across-rollback problem)
  195. """
  196. class Connection(sqlite.Connection):
  197. def cursor(self):
  198. return Cursor(self)
  199. class Cursor(sqlite.Cursor):
  200. def __init__(self, con):
  201. sqlite.Cursor.__init__(self, con)
  202. con = Connection(":memory:")
  203. cur = con.cursor()
  204. cur.execute("create table foo(x)")
  205. cur.executemany("insert into foo(x) values (?)", [(3,), (4,), (5,)])
  206. cur.execute("select x from foo")
  207. con.rollback()
  208. with self.assertRaises(sqlite.InterfaceError):
  209. cur.fetchall()
  210. def CheckAutoCommit(self):
  211. """
  212. Verifies that creating a connection in autocommit mode works.
  213. 2.5.3 introduced a regression so that these could no longer
  214. be created.
  215. """
  216. con = sqlite.connect(":memory:", isolation_level=None)
  217. def CheckPragmaAutocommit(self):
  218. """
  219. Verifies that running a PRAGMA statement that does an autocommit does
  220. work. This did not work in 2.5.3/2.5.4.
  221. """
  222. cur = self.con.cursor()
  223. cur.execute("create table foo(bar)")
  224. cur.execute("insert into foo(bar) values (5)")
  225. cur.execute("pragma page_size")
  226. row = cur.fetchone()
  227. def CheckConnectionCall(self):
  228. """
  229. Call a connection with a non-string SQL request: check error handling
  230. of the statement constructor.
  231. """
  232. self.assertRaises(sqlite.Warning, self.con, 1)
  233. def CheckCollation(self):
  234. def collation_cb(a, b):
  235. return 1
  236. self.assertRaises(sqlite.ProgrammingError, self.con.create_collation,
  237. # Lone surrogate cannot be encoded to the default encoding (utf8)
  238. "\uDC80", collation_cb)
  239. def CheckRecursiveCursorUse(self):
  240. """
  241. http://bugs.python.org/issue10811
  242. Recursively using a cursor, such as when reusing it from a generator led to segfaults.
  243. Now we catch recursive cursor usage and raise a ProgrammingError.
  244. """
  245. con = sqlite.connect(":memory:")
  246. cur = con.cursor()
  247. cur.execute("create table a (bar)")
  248. cur.execute("create table b (baz)")
  249. def foo():
  250. cur.execute("insert into a (bar) values (?)", (1,))
  251. yield 1
  252. with self.assertRaises(sqlite.ProgrammingError):
  253. cur.executemany("insert into b (baz) values (?)",
  254. ((i,) for i in foo()))
  255. def CheckConvertTimestampMicrosecondPadding(self):
  256. """
  257. http://bugs.python.org/issue14720
  258. The microsecond parsing of convert_timestamp() should pad with zeros,
  259. since the microsecond string "456" actually represents "456000".
  260. """
  261. con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
  262. cur = con.cursor()
  263. cur.execute("CREATE TABLE t (x TIMESTAMP)")
  264. # Microseconds should be 456000
  265. cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.456')")
  266. # Microseconds should be truncated to 123456
  267. cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.123456789')")
  268. cur.execute("SELECT * FROM t")
  269. values = [x[0] for x in cur.fetchall()]
  270. self.assertEqual(values, [
  271. datetime.datetime(2012, 4, 4, 15, 6, 0, 456000),
  272. datetime.datetime(2012, 4, 4, 15, 6, 0, 123456),
  273. ])
  274. def CheckInvalidIsolationLevelType(self):
  275. # isolation level is a string, not an integer
  276. self.assertRaises(TypeError,
  277. sqlite.connect, ":memory:", isolation_level=123)
  278. def CheckNullCharacter(self):
  279. # Issue #21147
  280. con = sqlite.connect(":memory:")
  281. self.assertRaises(ValueError, con, "\0select 1")
  282. self.assertRaises(ValueError, con, "select 1\0")
  283. cur = con.cursor()
  284. self.assertRaises(ValueError, cur.execute, " \0select 2")
  285. self.assertRaises(ValueError, cur.execute, "select 2\0")
  286. def CheckCommitCursorReset(self):
  287. """
  288. Connection.commit() did reset cursors, which made sqlite3
  289. to return rows multiple times when fetched from cursors
  290. after commit. See issues 10513 and 23129 for details.
  291. """
  292. con = sqlite.connect(":memory:")
  293. con.executescript("""
  294. create table t(c);
  295. create table t2(c);
  296. insert into t values(0);
  297. insert into t values(1);
  298. insert into t values(2);
  299. """)
  300. self.assertEqual(con.isolation_level, "")
  301. counter = 0
  302. for i, row in enumerate(con.execute("select c from t")):
  303. with self.subTest(i=i, row=row):
  304. con.execute("insert into t2(c) values (?)", (i,))
  305. con.commit()
  306. if counter == 0:
  307. self.assertEqual(row[0], 0)
  308. elif counter == 1:
  309. self.assertEqual(row[0], 1)
  310. elif counter == 2:
  311. self.assertEqual(row[0], 2)
  312. counter += 1
  313. self.assertEqual(counter, 3, "should have returned exactly three rows")
  314. def CheckBpo31770(self):
  315. """
  316. The interpreter shouldn't crash in case Cursor.__init__() is called
  317. more than once.
  318. """
  319. def callback(*args):
  320. pass
  321. con = sqlite.connect(":memory:")
  322. cur = sqlite.Cursor(con)
  323. ref = weakref.ref(cur, callback)
  324. cur.__init__(con)
  325. del cur
  326. # The interpreter shouldn't crash when ref is collected.
  327. del ref
  328. support.gc_collect()
  329. def CheckDelIsolation_levelSegfault(self):
  330. with self.assertRaises(AttributeError):
  331. del self.con.isolation_level
  332. class UnhashableFunc:
  333. __hash__ = None
  334. def __init__(self, return_value=None):
  335. self.calls = 0
  336. self.return_value = return_value
  337. def __call__(self, *args, **kwargs):
  338. self.calls += 1
  339. return self.return_value
  340. class UnhashableCallbacksTestCase(unittest.TestCase):
  341. """
  342. https://bugs.python.org/issue34052
  343. Registering unhashable callbacks raises TypeError, callbacks are not
  344. registered in SQLite after such registration attempt.
  345. """
  346. def setUp(self):
  347. self.con = sqlite.connect(':memory:')
  348. def tearDown(self):
  349. self.con.close()
  350. def test_progress_handler(self):
  351. f = UnhashableFunc(return_value=0)
  352. with self.assertRaisesRegex(TypeError, 'unhashable type'):
  353. self.con.set_progress_handler(f, 1)
  354. self.con.execute('SELECT 1')
  355. self.assertFalse(f.calls)
  356. def test_func(self):
  357. func_name = 'func_name'
  358. f = UnhashableFunc()
  359. with self.assertRaisesRegex(TypeError, 'unhashable type'):
  360. self.con.create_function(func_name, 0, f)
  361. msg = 'no such function: %s' % func_name
  362. with self.assertRaisesRegex(sqlite.OperationalError, msg):
  363. self.con.execute('SELECT %s()' % func_name)
  364. self.assertFalse(f.calls)
  365. def test_authorizer(self):
  366. f = UnhashableFunc(return_value=sqlite.SQLITE_DENY)
  367. with self.assertRaisesRegex(TypeError, 'unhashable type'):
  368. self.con.set_authorizer(f)
  369. self.con.execute('SELECT 1')
  370. self.assertFalse(f.calls)
  371. def test_aggr(self):
  372. class UnhashableType(type):
  373. __hash__ = None
  374. aggr_name = 'aggr_name'
  375. with self.assertRaisesRegex(TypeError, 'unhashable type'):
  376. self.con.create_aggregate(aggr_name, 0, UnhashableType('Aggr', (), {}))
  377. msg = 'no such function: %s' % aggr_name
  378. with self.assertRaisesRegex(sqlite.OperationalError, msg):
  379. self.con.execute('SELECT %s()' % aggr_name)
  380. def suite():
  381. regression_suite = unittest.makeSuite(RegressionTests, "Check")
  382. return unittest.TestSuite((
  383. regression_suite,
  384. unittest.makeSuite(UnhashableCallbacksTestCase),
  385. ))
  386. def test():
  387. runner = unittest.TextTestRunner()
  388. runner.run(suite())
  389. if __name__ == "__main__":
  390. test()