»Core Development>Code coverage>Lib/sqlite3/test/regression.py

Python code coverage for Lib/sqlite3/test/regression.py

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