blob: 9d7b27639a47244684bf872acd4453952a37deb3 [file] [log] [blame]
Petri Lehtinenf8547992012-02-02 17:17:36 +02001#-*- coding: iso-8859-1 -*-
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002# pysqlite2/test/regression.py: pysqlite regression tests
3#
Gerhard Häringf9cee222010-03-05 15:20:03 +00004# Copyright (C) 2006-2010 Gerhard Häring <gh@ghaering.de>
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005#
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
Gerhard Häringe7ea7452008-03-29 00:45:29 +000024import datetime
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025import unittest
Thomas Wouters477c8d52006-05-27 19:21:47 +000026import sqlite3 as sqlite
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027
28class RegressionTests(unittest.TestCase):
29 def setUp(self):
30 self.con = sqlite.connect(":memory:")
31
32 def tearDown(self):
33 self.con.close()
34
35 def CheckPragmaUserVersion(self):
36 # This used to crash pysqlite because this pragma command returns NULL for the column name
37 cur = self.con.cursor()
38 cur.execute("pragma user_version")
39
Thomas Wouters477c8d52006-05-27 19:21:47 +000040 def CheckPragmaSchemaVersion(self):
41 # This still crashed pysqlite <= 2.2.1
42 con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
43 try:
44 cur = self.con.cursor()
45 cur.execute("pragma schema_version")
46 finally:
47 cur.close()
48 con.close()
49
50 def CheckStatementReset(self):
51 # pysqlite 2.1.0 to 2.2.0 have the problem that not all statements are
52 # reset before a rollback, but only those that are still in the
53 # statement cache. The others are not accessible from the connection object.
54 con = sqlite.connect(":memory:", cached_statements=5)
Guido van Rossum805365e2007-05-07 22:24:25 +000055 cursors = [con.cursor() for x in range(5)]
Thomas Wouters477c8d52006-05-27 19:21:47 +000056 cursors[0].execute("create table test(x)")
57 for i in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +000058 cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in range(10)])
Thomas Wouters477c8d52006-05-27 19:21:47 +000059
60 for i in range(5):
61 cursors[i].execute(" " * i + "select x from test")
62
63 con.rollback()
64
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065 def CheckColumnNameWithSpaces(self):
66 cur = self.con.cursor()
67 cur.execute('select 1 as "foo bar [datetime]"')
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000068 self.assertEqual(cur.description[0][0], "foo bar")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
70 cur.execute('select 1 as "foo baz"')
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000071 self.assertEqual(cur.description[0][0], "foo baz")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
Gerhard Häringe7ea7452008-03-29 00:45:29 +000073 def CheckStatementFinalizationOnCloseDb(self):
74 # pysqlite versions <= 2.3.3 only finalized statements in the statement
75 # cache when closing the database. statements that were still
76 # referenced in cursors weren't closed an could provoke "
77 # "OperationalError: Unable to close due to unfinalised statements".
78 con = sqlite.connect(":memory:")
79 cursors = []
80 # default statement cache size is 100
81 for i in range(105):
82 cur = con.cursor()
83 cursors.append(cur)
84 cur.execute("select 1 x union select " + str(i))
85 con.close()
86
87 def CheckOnConflictRollback(self):
88 if sqlite.sqlite_version_info < (3, 2, 2):
89 return
90 con = sqlite.connect(":memory:")
91 con.execute("create table foo(x, unique(x) on conflict rollback)")
92 con.execute("insert into foo(x) values (1)")
93 try:
94 con.execute("insert into foo(x) values (1)")
95 except sqlite.DatabaseError:
96 pass
97 con.execute("insert into foo(x) values (2)")
98 try:
99 con.commit()
100 except sqlite.OperationalError:
101 self.fail("pysqlite knew nothing about the implicit ROLLBACK")
102
103 def CheckWorkaroundForBuggySqliteTransferBindings(self):
104 """
105 pysqlite would crash with older SQLite versions unless
106 a workaround is implemented.
107 """
108 self.con.execute("create table foo(bar)")
109 self.con.execute("drop table foo")
110 self.con.execute("create table foo(bar)")
111
112 def CheckEmptyStatement(self):
113 """
114 pysqlite used to segfault with SQLite versions 3.5.x. These return NULL
115 for "no-operation" statements
116 """
117 self.con.execute("")
118
119 def CheckTypeMapUsage(self):
120 """
121 pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling
122 a statement. This test exhibits the problem.
123 """
124 SELECT = "select * from foo"
125 con = sqlite.connect(":memory:",detect_types=sqlite.PARSE_DECLTYPES)
126 con.execute("create table foo(bar timestamp)")
127 con.execute("insert into foo(bar) values (?)", (datetime.datetime.now(),))
128 con.execute(SELECT)
129 con.execute("drop table foo")
130 con.execute("create table foo(bar integer)")
131 con.execute("insert into foo(bar) values (5)")
132 con.execute(SELECT)
133
Gerhard Häring873d9ff2008-02-29 22:22:09 +0000134 def CheckErrorMsgDecodeError(self):
135 # When porting the module to Python 3.0, the error message about
136 # decoding errors disappeared. This verifies they're back again.
137 failure = None
138 try:
Georg Brandl3dbca812008-07-23 16:10:53 +0000139 self.con.execute("select 'xxx' || ? || 'yyy' colname",
140 (bytes(bytearray([250])),)).fetchone()
Gerhard Häring873d9ff2008-02-29 22:22:09 +0000141 failure = "should have raised an OperationalError with detailed description"
142 except sqlite.OperationalError as e:
143 msg = e.args[0]
144 if not msg.startswith("Could not decode to UTF-8 column 'colname' with text 'xxx"):
145 failure = "OperationalError did not have expected description text"
146 if failure:
147 self.fail(failure)
148
Georg Brandl3dbca812008-07-23 16:10:53 +0000149 def CheckRegisterAdapter(self):
150 """
151 See issue 3312.
152 """
153 self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
154
155 def CheckSetIsolationLevel(self):
156 """
157 See issue 3312.
158 """
159 con = sqlite.connect(":memory:")
160 setattr(con, "isolation_level", "\xe9")
161
Gerhard Häringf9cee222010-03-05 15:20:03 +0000162 def CheckCursorConstructorCallCheck(self):
163 """
164 Verifies that cursor methods check wether base class __init__ was called.
165 """
166 class Cursor(sqlite.Cursor):
167 def __init__(self, con):
168 pass
169
170 con = sqlite.connect(":memory:")
171 cur = Cursor(con)
172 try:
173 cur.execute("select 4+5").fetchall()
174 self.fail("should have raised ProgrammingError")
175 except sqlite.ProgrammingError:
176 pass
177 except:
178 self.fail("should have raised ProgrammingError")
179
180
Gerhard Häring6117f422008-09-22 06:04:51 +0000181 def CheckStrSubclass(self):
182 """
183 The Python 3.0 port of the module didn't cope with values of subclasses of str.
184 """
185 class MyStr(str): pass
186 self.con.execute("select ?", (MyStr("abc"),))
Georg Brandl3dbca812008-07-23 16:10:53 +0000187
Gerhard Häringf9cee222010-03-05 15:20:03 +0000188 def CheckConnectionConstructorCallCheck(self):
189 """
190 Verifies that connection methods check wether base class __init__ was called.
191 """
192 class Connection(sqlite.Connection):
193 def __init__(self, name):
194 pass
195
196 con = Connection(":memory:")
197 try:
198 cur = con.cursor()
199 self.fail("should have raised ProgrammingError")
200 except sqlite.ProgrammingError:
201 pass
202 except:
203 self.fail("should have raised ProgrammingError")
204
205 def CheckCursorRegistration(self):
206 """
207 Verifies that subclassed cursor classes are correctly registered with
208 the connection object, too. (fetch-across-rollback problem)
209 """
210 class Connection(sqlite.Connection):
211 def cursor(self):
212 return Cursor(self)
213
214 class Cursor(sqlite.Cursor):
215 def __init__(self, con):
216 sqlite.Cursor.__init__(self, con)
217
218 con = Connection(":memory:")
219 cur = con.cursor()
220 cur.execute("create table foo(x)")
221 cur.executemany("insert into foo(x) values (?)", [(3,), (4,), (5,)])
222 cur.execute("select x from foo")
223 con.rollback()
224 try:
225 cur.fetchall()
226 self.fail("should have raised InterfaceError")
227 except sqlite.InterfaceError:
228 pass
229 except:
230 self.fail("should have raised InterfaceError")
231
232 def CheckAutoCommit(self):
233 """
234 Verifies that creating a connection in autocommit mode works.
235 2.5.3 introduced a regression so that these could no longer
236 be created.
237 """
238 con = sqlite.connect(":memory:", isolation_level=None)
239
240 def CheckPragmaAutocommit(self):
241 """
242 Verifies that running a PRAGMA statement that does an autocommit does
243 work. This did not work in 2.5.3/2.5.4.
244 """
Victor Stinner0201f442010-03-13 03:28:34 +0000245 cur = self.con.cursor()
Gerhard Häringf9cee222010-03-05 15:20:03 +0000246 cur.execute("create table foo(bar)")
247 cur.execute("insert into foo(bar) values (5)")
248
249 cur.execute("pragma page_size")
250 row = cur.fetchone()
251
252 def CheckSetDict(self):
253 """
254 See http://bugs.python.org/issue7478
255
256 It was possible to successfully register callbacks that could not be
257 hashed. Return codes of PyDict_SetItem were not checked properly.
258 """
259 class NotHashable:
260 def __call__(self, *args, **kw):
261 pass
262 def __hash__(self):
263 raise TypeError()
264 var = NotHashable()
Victor Stinner0201f442010-03-13 03:28:34 +0000265 self.assertRaises(TypeError, self.con.create_function, var)
266 self.assertRaises(TypeError, self.con.create_aggregate, var)
267 self.assertRaises(TypeError, self.con.set_authorizer, var)
268 self.assertRaises(TypeError, self.con.set_progress_handler, var)
269
270 def CheckConnectionCall(self):
271 """
272 Call a connection with a non-string SQL request: check error handling
273 of the statement constructor.
274 """
275 self.assertRaises(sqlite.Warning, self.con, 1)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000276
Victor Stinner35466c52010-04-22 11:23:23 +0000277 def CheckCollation(self):
278 def collation_cb(a, b):
279 return 1
280 self.assertRaises(sqlite.ProgrammingError, self.con.create_collation,
281 # Lone surrogate cannot be encoded to the default encoding (utf8)
282 "\uDC80", collation_cb)
283
Gerhard Haering936d5182011-05-09 12:24:09 +0200284 def CheckRecursiveCursorUse(self):
285 """
286 http://bugs.python.org/issue10811
287
288 Recursively using a cursor, such as when reusing it from a generator led to segfaults.
289 Now we catch recursive cursor usage and raise a ProgrammingError.
290 """
291 con = sqlite.connect(":memory:")
292
293 cur = con.cursor()
294 cur.execute("create table a (bar)")
295 cur.execute("create table b (baz)")
296
297 def foo():
298 cur.execute("insert into a (bar) values (?)", (1,))
299 yield 1
300
Victor Stinner502ff6c2011-05-09 12:50:41 +0200301 with self.assertRaises(sqlite.ProgrammingError):
302 cur.executemany("insert into b (baz) values (?)",
303 ((i,) for i in foo()))
304
Gerhard Haering936d5182011-05-09 12:24:09 +0200305
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306def suite():
307 regression_suite = unittest.makeSuite(RegressionTests, "Check")
308 return unittest.TestSuite((regression_suite,))
309
310def test():
311 runner = unittest.TextTestRunner()
312 runner.run(suite())
313
314if __name__ == "__main__":
315 test()