1
#-*- coding: iso-8859-1 -*-
2
# pysqlite2/test/regression.py: pysqlite regression tests
4
# Copyright (C) 2006-2010 Gerhard Hļæ½ring <gh@ghaering.de>
6
# This file is part of pysqlite.
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.
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:
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.
26
import sqlite3 as sqlite
28
class RegressionTests(unittest.TestCase):
30
self.con = sqlite.connect(":memory:")
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")
40
def CheckPragmaSchemaVersion(self):
41
# This still crashed pysqlite <= 2.2.1
42
con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
44
cur = self.con.cursor()
45
cur.execute("pragma schema_version")
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)
55
cursors = [con.cursor() for x in range(5)]
56
cursors[0].execute("create table test(x)")
58
cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in range(10)])
61
cursors[i].execute(" " * i + "select x from test")
65
def CheckColumnNameWithSpaces(self):
66
cur = self.con.cursor()
67
cur.execute('select 1 as "foo bar [datetime]"')
68
self.assertEqual(cur.description[0][0], "foo bar")
70
cur.execute('select 1 as "foo baz"')
71
self.assertEqual(cur.description[0][0], "foo baz")
73
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:")
80
# default statement cache size is 100
84
cur.execute("select 1 x union select " + str(i))
87
def CheckOnConflictRollback(self):
88
if sqlite.sqlite_version_info < (3, 2, 2):
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)")
94
con.execute("insert into foo(x) values (1)")
95
except sqlite.DatabaseError:
97
con.execute("insert into foo(x) values (2)")
100
except sqlite.OperationalError:
101
self.fail("pysqlite knew nothing about the implicit ROLLBACK")
103
def CheckWorkaroundForBuggySqliteTransferBindings(self):
105
pysqlite would crash with older SQLite versions unless
106
a workaround is implemented.
108
self.con.execute("create table foo(bar)")
109
self.con.execute("drop table foo")
110
self.con.execute("create table foo(bar)")
112
def CheckEmptyStatement(self):
114
pysqlite used to segfault with SQLite versions 3.5.x. These return NULL
115
for "no-operation" statements
119
def CheckTypeMapUsage(self):
121
pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling
122
a statement. This test exhibits the problem.
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(),))
129
con.execute("drop table foo")
130
con.execute("create table foo(bar integer)")
131
con.execute("insert into foo(bar) values (5)")
134
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.
139
self.con.execute("select 'xxx' || ? || 'yyy' colname",
140
(bytes(bytearray([250])),)).fetchone()
141
failure = "should have raised an OperationalError with detailed description"
142
except sqlite.OperationalError as e:
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"
149
def CheckRegisterAdapter(self):
153
self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
155
def CheckSetIsolationLevel(self):
159
con = sqlite.connect(":memory:")
160
setattr(con, "isolation_level", "\xe9")
162
def CheckCursorConstructorCallCheck(self):
164
Verifies that cursor methods check whether base class __init__ was
167
class Cursor(sqlite.Cursor):
168
def __init__(self, con):
171
con = sqlite.connect(":memory:")
174
cur.execute("select 4+5").fetchall()
175
self.fail("should have raised ProgrammingError")
176
except sqlite.ProgrammingError:
179
self.fail("should have raised ProgrammingError")
182
def CheckStrSubclass(self):
184
The Python 3.0 port of the module didn't cope with values of subclasses of str.
186
class MyStr(str): pass
187
self.con.execute("select ?", (MyStr("abc"),))
189
def CheckConnectionConstructorCallCheck(self):
191
Verifies that connection methods check whether base class __init__ was
194
class Connection(sqlite.Connection):
195
def __init__(self, name):
198
con = Connection(":memory:")
201
self.fail("should have raised ProgrammingError")
202
except sqlite.ProgrammingError:
205
self.fail("should have raised ProgrammingError")
207
def CheckCursorRegistration(self):
209
Verifies that subclassed cursor classes are correctly registered with
210
the connection object, too. (fetch-across-rollback problem)
212
class Connection(sqlite.Connection):
216
class Cursor(sqlite.Cursor):
217
def __init__(self, con):
218
sqlite.Cursor.__init__(self, con)
220
con = Connection(":memory:")
222
cur.execute("create table foo(x)")
223
cur.executemany("insert into foo(x) values (?)", [(3,), (4,), (5,)])
224
cur.execute("select x from foo")
228
self.fail("should have raised InterfaceError")
229
except sqlite.InterfaceError:
232
self.fail("should have raised InterfaceError")
234
def CheckAutoCommit(self):
236
Verifies that creating a connection in autocommit mode works.
237
2.5.3 introduced a regression so that these could no longer
240
con = sqlite.connect(":memory:", isolation_level=None)
242
def CheckPragmaAutocommit(self):
244
Verifies that running a PRAGMA statement that does an autocommit does
245
work. This did not work in 2.5.3/2.5.4.
247
cur = self.con.cursor()
248
cur.execute("create table foo(bar)")
249
cur.execute("insert into foo(bar) values (5)")
251
cur.execute("pragma page_size")
254
def CheckSetDict(self):
256
See http://bugs.python.org/issue7478
258
It was possible to successfully register callbacks that could not be
259
hashed. Return codes of PyDict_SetItem were not checked properly.
262
def __call__(self, *args, **kw):
267
self.assertRaises(TypeError, self.con.create_function, var)
268
self.assertRaises(TypeError, self.con.create_aggregate, var)
269
self.assertRaises(TypeError, self.con.set_authorizer, var)
270
self.assertRaises(TypeError, self.con.set_progress_handler, var)
272
def CheckConnectionCall(self):
274
Call a connection with a non-string SQL request: check error handling
275
of the statement constructor.
277
self.assertRaises(sqlite.Warning, self.con, 1)
279
def CheckCollation(self):
280
def collation_cb(a, b):
282
self.assertRaises(sqlite.ProgrammingError, self.con.create_collation,
283
# Lone surrogate cannot be encoded to the default encoding (utf8)
284
"\uDC80", collation_cb)
286
def CheckRecursiveCursorUse(self):
288
http://bugs.python.org/issue10811
290
Recursively using a cursor, such as when reusing it from a generator led to segfaults.
291
Now we catch recursive cursor usage and raise a ProgrammingError.
293
con = sqlite.connect(":memory:")
296
cur.execute("create table a (bar)")
297
cur.execute("create table b (baz)")
300
cur.execute("insert into a (bar) values (?)", (1,))
303
with self.assertRaises(sqlite.ProgrammingError):
304
cur.executemany("insert into b (baz) values (?)",
305
((i,) for i in foo()))
307
def CheckConvertTimestampMicrosecondPadding(self):
309
http://bugs.python.org/issue14720
311
The microsecond parsing of convert_timestamp() should pad with zeros,
312
since the microsecond string "456" actually represents "456000".
315
con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
317
cur.execute("CREATE TABLE t (x TIMESTAMP)")
319
# Microseconds should be 456000
320
cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.456')")
322
# Microseconds should be truncated to 123456
323
cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.123456789')")
325
cur.execute("SELECT * FROM t")
326
values = [x[0] for x in cur.fetchall()]
328
self.assertEqual(values, [
329
datetime.datetime(2012, 4, 4, 15, 6, 0, 456000),
330
datetime.datetime(2012, 4, 4, 15, 6, 0, 123456),
335
regression_suite = unittest.makeSuite(RegressionTests, "Check")
336
return unittest.TestSuite((regression_suite,))
339
runner = unittest.TextTestRunner()
342
if __name__ == "__main__":