Debian Codegraph @

Lib/test/test_sqlite3/test_hooks.py

raw
1 # pysqlite2/test/hooks.py: tests for various SQLite-specific hooks
2 #
3 # Copyright (C) 2006-2007 Gerhard Häring <[email protected]>
4 #
5 # This file is part of pysqlite.
6 #
7 # This software is provided 'as-is', without any express or implied
8 # warranty. In no event will the authors be held liable for any damages
9 # arising from the use of this software.
10 #
11 # Permission is granted to anyone to use this software for any purpose,
12 # including commercial applications, and to alter it and redistribute it
13 # freely, subject to the following restrictions:
14 #
15 # 1. The origin of this software must not be misrepresented; you must not
16 # claim that you wrote the original software. If you use this software
17 # in a product, an acknowledgment in the product documentation would be
18 # appreciated but is not required.
19 # 2. Altered source versions must be plainly marked as such, and must not be
20 # misrepresented as being the original software.
21 # 3. This notice may not be removed or altered from any source distribution.
22
23 import contextlib
24 import sqlite3 as sqlite
25 import unittest
26
27 from test.support import import_helper
28 from test.support.os_helper import TESTFN, unlink
29
30 from .util import memory_database, cx_limit, with_tracebacks
31 from .util import MemoryDatabaseMixin
32
33 # TODO(picnixz): increase test coverage for other callbacks
34 # such as 'func', 'step', 'finalize', and 'collation'.
35
36
37 class CollationTests(MemoryDatabaseMixin, unittest.TestCase):
38
39 def test_create_collation_not_string(self):
40 with self.assertRaises(TypeError):
41 self.con.create_collation(None, lambda x, y: (x > y) - (x < y))
42
43 def test_create_collation_not_callable(self):
44 with self.assertRaises(TypeError) as cm:
45 self.con.create_collation("X", 42)
46 self.assertEqual(str(cm.exception), 'parameter must be callable')
47
48 def test_create_collation_not_ascii(self):
49 self.con.create_collation("collä", lambda x, y: (x > y) - (x < y))
50
51 def test_create_collation_bad_upper(self):
52 class BadUpperStr(str):
53 def upper(self):
54 return None
55 mycoll = lambda x, y: -((x > y) - (x < y))
56 self.con.create_collation(BadUpperStr("mycoll"), mycoll)
57 result = self.con.execute("""
58 select x from (
59 select 'a' as x
60 union
61 select 'b' as x
62 ) order by x collate mycoll
63 """).fetchall()
64 self.assertEqual(result[0][0], 'b')
65 self.assertEqual(result[1][0], 'a')
66
67 def test_collation_is_used(self):
68 def mycoll(x, y):
69 # reverse order
70 return -((x > y) - (x < y))
71
72 self.con.create_collation("mycoll", mycoll)
73 sql = """
74 select x from (
75 select 'a' as x
76 union
77 select 'b' as x
78 union
79 select 'c' as x
80 ) order by x collate mycoll
81 """
82 result = self.con.execute(sql).fetchall()
83 self.assertEqual(result, [('c',), ('b',), ('a',)],
84 msg='the expected order was not returned')
85
86 self.con.create_collation("mycoll", None)
87 with self.assertRaises(sqlite.OperationalError) as cm:
88 result = self.con.execute(sql).fetchall()
89 self.assertEqual(str(cm.exception), 'no such collation sequence: mycoll')
90
91 def test_collation_returns_large_integer(self):
92 def mycoll(x, y):
93 # reverse order
94 return -((x > y) - (x < y)) * 2**32
95 self.con.create_collation("mycoll", mycoll)
96 sql = """
97 select x from (
98 select 'a' as x
99 union
100 select 'b' as x
101 union
102 select 'c' as x
103 ) order by x collate mycoll
104 """
105 result = self.con.execute(sql).fetchall()
106 self.assertEqual(result, [('c',), ('b',), ('a',)],
107 msg="the expected order was not returned")
108
109 def test_collation_register_twice(self):
110 """
111 Register two different collation functions under the same name.
112 Verify that the last one is actually used.
113 """
114 con = self.con
115 con.create_collation("mycoll", lambda x, y: (x > y) - (x < y))
116 con.create_collation("mycoll", lambda x, y: -((x > y) - (x < y)))
117 result = con.execute("""
118 select x from (select 'a' as x union select 'b' as x) order by x collate mycoll
119 """).fetchall()
120 self.assertEqual(result[0][0], 'b')
121 self.assertEqual(result[1][0], 'a')
122
123 def test_deregister_collation(self):
124 """
125 Register a collation, then deregister it. Make sure an error is raised if we try
126 to use it.
127 """
128 con = self.con
129 con.create_collation("mycoll", lambda x, y: (x > y) - (x < y))
130 con.create_collation("mycoll", None)
131 with self.assertRaises(sqlite.OperationalError) as cm:
132 con.execute("select 'a' as x union select 'b' as x order by x collate mycoll")
133 self.assertEqual(str(cm.exception), 'no such collation sequence: mycoll')
134
135
136 class AuthorizerTests(MemoryDatabaseMixin, unittest.TestCase):
137
138 def assert_not_authorized(self, func, /, *args, **kwargs):
139 with self.assertRaisesRegex(sqlite.DatabaseError, "not authorized"):
140 func(*args, **kwargs)
141
142 # When a handler has an invalid signature, the exception raised is
143 # the same that would be raised if the handler "negatively" replied.
144
145 def test_authorizer_invalid_signature(self):
146 self.cx.execute("create table if not exists test(a number)")
147 self.cx.set_authorizer(lambda: None)
148 self.assert_not_authorized(self.cx.execute, "select * from test")
149
150 # Tests for checking that callback context mutations do not crash.
151 # Regression tests for https://github.com/python/cpython/issues/142830.
152
153 @with_tracebacks(ZeroDivisionError, regex="hello world")
154 def test_authorizer_concurrent_mutation_in_call(self):
155 self.cx.execute("create table if not exists test(a number)")
156
157 def handler(*a, **kw):
158 self.cx.set_authorizer(None)
159 raise ZeroDivisionError("hello world")
160
161 self.cx.set_authorizer(handler)
162 self.assert_not_authorized(self.cx.execute, "select * from test")
163
164 @with_tracebacks(OverflowError)
165 def test_authorizer_concurrent_mutation_with_overflown_value(self):
166 _testcapi = import_helper.import_module("_testcapi")
167 self.cx.execute("create table if not exists test(a number)")
168
169 def handler(*a, **kw):
170 self.cx.set_authorizer(None)
171 # We expect 'int' at the C level, so this one will raise
172 # when converting via PyLong_Int().
173 return _testcapi.INT_MAX + 1
174
175 self.cx.set_authorizer(handler)
176 self.assert_not_authorized(self.cx.execute, "select * from test")
177
178
179 class ProgressTests(MemoryDatabaseMixin, unittest.TestCase):
180
181 def assert_interrupted(self, func, /, *args, **kwargs):
182 with self.assertRaisesRegex(sqlite.OperationalError, "interrupted"):
183 func(*args, **kwargs)
184
185 def test_progress_handler_used(self):
186 """
187 Test that the progress handler is invoked once it is set.
188 """
189 progress_calls = []
190 def progress():
191 progress_calls.append(None)
192 return 0
193 self.con.set_progress_handler(progress, 1)
194 self.con.execute("""
195 create table foo(a, b)
196 """)
197 self.assertTrue(progress_calls)
198
199 def test_opcode_count(self):
200 """
201 Test that the opcode argument is respected.
202 """
203 con = self.con
204 progress_calls = []
205 def progress():
206 progress_calls.append(None)
207 return 0
208 con.set_progress_handler(progress, 1)
209 curs = con.cursor()
210 curs.execute("""
211 create table foo (a, b)
212 """)
213 first_count = len(progress_calls)
214 progress_calls = []
215 con.set_progress_handler(progress, 2)
216 curs.execute("""
217 create table bar (a, b)
218 """)
219 second_count = len(progress_calls)
220 self.assertGreaterEqual(first_count, second_count)
221
222 def test_cancel_operation(self):
223 """
224 Test that returning a non-zero value stops the operation in progress.
225 """
226 def progress():
227 return 1
228 self.con.set_progress_handler(progress, 1)
229 curs = self.con.cursor()
230 self.assertRaises(
231 sqlite.OperationalError,
232 curs.execute,
233 "create table bar (a, b)")
234
235 def test_clear_handler(self):
236 """
237 Test that setting the progress handler to None clears the previously set handler.
238 """
239 con = self.con
240 action = 0
241 def progress():
242 nonlocal action
243 action = 1
244 return 0
245 con.set_progress_handler(progress, 1)
246 con.set_progress_handler(None, 1)
247 con.execute("select 1 union select 2 union select 3").fetchall()
248 self.assertEqual(action, 0, "progress handler was not cleared")
249
250 @with_tracebacks(ZeroDivisionError, name="bad_progress")
251 def test_error_in_progress_handler(self):
252 def bad_progress():
253 1 / 0
254 self.con.set_progress_handler(bad_progress, 1)
255 with self.assertRaises(sqlite.OperationalError):
256 self.con.execute("""
257 create table foo(a, b)
258 """)
259
260 @with_tracebacks(ZeroDivisionError, name="bad_progress")
261 def test_error_in_progress_handler_result(self):
262 class BadBool:
263 def __bool__(self):
264 1 / 0
265 def bad_progress():
266 return BadBool()
267 self.con.set_progress_handler(bad_progress, 1)
268 with self.assertRaises(sqlite.OperationalError):
269 self.con.execute("""
270 create table foo(a, b)
271 """)
272
273 def test_set_progress_handler_keyword_args(self):
274 regex = (
275 r"Passing keyword argument 'progress_handler' to "
276 r"_sqlite3.Connection.set_progress_handler\(\) is deprecated. "
277 r"Parameter 'progress_handler' will become positional-only in "
278 r"Python 3.15."
279 )
280
281 with self.assertWarnsRegex(DeprecationWarning, regex) as cm:
282 self.con.set_progress_handler(progress_handler=lambda: None, n=1)
283 self.assertEqual(cm.filename, __file__)
284
285 # When a handler has an invalid signature, the exception raised is
286 # the same that would be raised if the handler "negatively" replied.
287
288 def test_progress_handler_invalid_signature(self):
289 self.cx.execute("create table if not exists test(a number)")
290 self.cx.set_progress_handler(lambda x: None, 1)
291 self.assert_interrupted(self.cx.execute, "select * from test")
292
293 # Tests for checking that callback context mutations do not crash.
294 # Regression tests for https://github.com/python/cpython/issues/142830.
295
296 @with_tracebacks(ZeroDivisionError, regex="hello world")
297 def test_progress_handler_concurrent_mutation_in_call(self):
298 self.cx.execute("create table if not exists test(a number)")
299
300 def handler(*a, **kw):
301 self.cx.set_progress_handler(None, 1)
302 raise ZeroDivisionError("hello world")
303
304 self.cx.set_progress_handler(handler, 1)
305 self.assert_interrupted(self.cx.execute, "select * from test")
306
307 def test_progress_handler_concurrent_mutation_in_conversion(self):
308 self.cx.execute("create table if not exists test(a number)")
309
310 class Handler:
311 def __bool__(_):
312 # clear the progress handler
313 self.cx.set_progress_handler(None, 1)
314 raise ValueError # force PyObject_True() to fail
315
316 self.cx.set_progress_handler(Handler.__init__, 1)
317 self.assert_interrupted(self.cx.execute, "select * from test")
318
319 # Running with tracebacks makes the second execution of this
320 # function raise another exception because of a database change.
321
322
323 class TraceCallbackTests(MemoryDatabaseMixin, unittest.TestCase):
324
325 @contextlib.contextmanager
326 def check_stmt_trace(self, cx, expected):
327 try:
328 traced = []
329 cx.set_trace_callback(lambda stmt: traced.append(stmt))
330 yield
331 finally:
332 self.assertEqual(traced, expected)
333 cx.set_trace_callback(None)
334
335 def test_trace_callback_used(self):
336 """
337 Test that the trace callback is invoked once it is set.
338 """
339 traced_statements = []
340 def trace(statement):
341 traced_statements.append(statement)
342 self.con.set_trace_callback(trace)
343 self.con.execute("create table foo(a, b)")
344 self.assertTrue(traced_statements)
345 self.assertTrue(any("create table foo" in stmt for stmt in traced_statements))
346
347 def test_clear_trace_callback(self):
348 """
349 Test that setting the trace callback to None clears the previously set callback.
350 """
351 con = self.con
352 traced_statements = []
353 def trace(statement):
354 traced_statements.append(statement)
355 con.set_trace_callback(trace)
356 con.set_trace_callback(None)
357 con.execute("create table foo(a, b)")
358 self.assertFalse(traced_statements, "trace callback was not cleared")
359
360 def test_unicode_content(self):
361 """
362 Test that the statement can contain unicode literals.
363 """
364 unicode_value = '\xf6\xe4\xfc\xd6\xc4\xdc\xdf\u20ac'
365 con = self.con
366 traced_statements = []
367 def trace(statement):
368 traced_statements.append(statement)
369 con.set_trace_callback(trace)
370 con.execute("create table foo(x)")
371 con.execute("insert into foo(x) values ('%s')" % unicode_value)
372 con.commit()
373 self.assertTrue(any(unicode_value in stmt for stmt in traced_statements),
374 "Unicode data %s garbled in trace callback: %s"
375 % (ascii(unicode_value), ', '.join(map(ascii, traced_statements))))
376
377 def test_trace_callback_content(self):
378 # set_trace_callback() shouldn't produce duplicate content (bpo-26187)
379 traced_statements = []
380 def trace(statement):
381 traced_statements.append(statement)
382
383 queries = ["create table foo(x)",
384 "insert into foo(x) values(1)"]
385 self.addCleanup(unlink, TESTFN)
386 con1 = sqlite.connect(TESTFN, isolation_level=None)
387 con2 = sqlite.connect(TESTFN)
388 try:
389 con1.set_trace_callback(trace)
390 cur = con1.cursor()
391 cur.execute(queries[0])
392 con2.execute("create table bar(x)")
393 cur.execute(queries[1])
394 finally:
395 con1.close()
396 con2.close()
397 self.assertEqual(traced_statements, queries)
398
399 def test_trace_expanded_sql(self):
400 expected = [
401 "create table t(t)",
402 "BEGIN ",
403 "insert into t values(0)",
404 "insert into t values(1)",
405 "insert into t values(2)",
406 "COMMIT",
407 ]
408 with memory_database() as cx, self.check_stmt_trace(cx, expected):
409 with cx:
410 cx.execute("create table t(t)")
411 cx.executemany("insert into t values(?)", ((v,) for v in range(3)))
412
413 @with_tracebacks(
414 sqlite.DataError,
415 regex="Expanded SQL string exceeds the maximum string length"
416 )
417 def test_trace_too_much_expanded_sql(self):
418 # If the expanded string is too large, we'll fall back to the
419 # unexpanded SQL statement.
420 # The resulting string length is limited by the runtime limit
421 # SQLITE_LIMIT_LENGTH.
422 template = "select 1 as a where a="
423 category = sqlite.SQLITE_LIMIT_LENGTH
424 with memory_database() as cx, cx_limit(cx, category=category) as lim:
425 ok_param = "a"
426 bad_param = "a" * lim
427
428 unexpanded_query = template + "?"
429 expected = [unexpanded_query]
430 with self.check_stmt_trace(cx, expected):
431 cx.execute(unexpanded_query, (bad_param,))
432
433 expanded_query = f"{template}'{ok_param}'"
434 with self.check_stmt_trace(cx, [expanded_query]):
435 cx.execute(unexpanded_query, (ok_param,))
436
437 @with_tracebacks(ZeroDivisionError, regex="division by zero")
438 def test_trace_bad_handler(self):
439 with memory_database() as cx:
440 cx.set_trace_callback(lambda stmt: 5/0)
441 cx.execute("select 1")
442
443 def test_set_trace_callback_keyword_args(self):
444 regex = (
445 r"Passing keyword argument 'trace_callback' to "
446 r"_sqlite3.Connection.set_trace_callback\(\) is deprecated. "
447 r"Parameter 'trace_callback' will become positional-only in "
448 r"Python 3.15."
449 )
450
451 with self.assertWarnsRegex(DeprecationWarning, regex) as cm:
452 self.con.set_trace_callback(trace_callback=lambda: None)
453 self.assertEqual(cm.filename, __file__)
454
455 # When a handler has an invalid signature, the exception raised is
456 # the same that would be raised if the handler "negatively" replied,
457 # but for the trace handler, exceptions are never re-raised (only
458 # printed when needed).
459
460 @with_tracebacks(
461 TypeError,
462 regex=r".*<lambda>\(\) missing 6 required positional arguments",
463 )
464 def test_trace_handler_invalid_signature(self):
465 self.cx.execute("create table if not exists test(a number)")
466 self.cx.set_trace_callback(lambda x, y, z, t, a, b, c: None)
467 self.cx.execute("select * from test")
468
469 # Tests for checking that callback context mutations do not crash.
470 # Regression tests for https://github.com/python/cpython/issues/142830.
471
472 @with_tracebacks(ZeroDivisionError, regex="hello world")
473 def test_trace_callback_concurrent_mutation_in_call(self):
474 self.cx.execute("create table if not exists test(a number)")
475
476 def handler(statement):
477 # clear the progress handler
478 self.cx.set_trace_callback(None)
479 raise ZeroDivisionError("hello world")
480
481 self.cx.set_trace_callback(handler)
482 self.cx.execute("select * from test")
483
484
485 if __name__ == "__main__":
486 unittest.main()