Debian Codegraph @

Lib/test/test_sqlite3/util.py

raw
1 import contextlib
2 import functools
3 import io
4 import re
5 import sqlite3
6 import test.support
7 import unittest
8
9
10 # Helper for temporary memory databases
11 def memory_database(*args, **kwargs):
12 cx = sqlite3.connect(":memory:", *args, **kwargs)
13 return contextlib.closing(cx)
14
15
16 # Temporarily limit a database connection parameter
17 @contextlib.contextmanager
18 def cx_limit(cx, category=sqlite3.SQLITE_LIMIT_SQL_LENGTH, limit=128):
19 try:
20 _prev = cx.setlimit(category, limit)
21 yield limit
22 finally:
23 cx.setlimit(category, _prev)
24
25
26 def with_tracebacks(exc, regex="", name=""):
27 """Convenience decorator for testing callback tracebacks."""
28 def decorator(func):
29 _regex = re.compile(regex) if regex else None
30 @functools.wraps(func)
31 def wrapper(self, *args, **kwargs):
32 with test.support.catch_unraisable_exception() as cm:
33 # First, run the test with traceback enabled.
34 with check_tracebacks(self, cm, exc, _regex, name):
35 func(self, *args, **kwargs)
36
37 # Then run the test with traceback disabled.
38 func(self, *args, **kwargs)
39 return wrapper
40 return decorator
41
42
43 @contextlib.contextmanager
44 def check_tracebacks(self, cm, exc, regex, obj_name):
45 """Convenience context manager for testing callback tracebacks."""
46 sqlite3.enable_callback_tracebacks(True)
47 try:
48 buf = io.StringIO()
49 with contextlib.redirect_stderr(buf):
50 yield
51
52 self.assertEqual(cm.unraisable.exc_type, exc)
53 if regex:
54 msg = str(cm.unraisable.exc_value)
55 self.assertIsNotNone(regex.search(msg))
56 if obj_name:
57 self.assertEqual(cm.unraisable.object.__name__, obj_name)
58 finally:
59 sqlite3.enable_callback_tracebacks(False)
60
61
62 class MemoryDatabaseMixin:
63
64 def setUp(self):
65 self.con = sqlite3.connect(":memory:")
66 self.cur = self.con.cursor()
67
68 def tearDown(self):
69 self.cur.close()
70 self.con.close()
71
72 @property
73 def cx(self):
74 return self.con
75
76 @property
77 def cu(self):
78 return self.cur
79
80
81 def requires_virtual_table(module):
82 with memory_database() as cx:
83 supported = (module,) in list(cx.execute("PRAGMA module_list"))
84 reason = f"Requires {module!r} virtual table support"
85 return unittest.skipUnless(supported, reason)