Debian Codegraph @

Lib/test/test_sqlite3/test_factory.py

raw
1 # pysqlite2/test/factory.py: tests for the various factories in pysqlite
2 #
3 # Copyright (C) 2005-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 unittest
24 import sqlite3 as sqlite
25 from collections.abc import Sequence
26
27 from .util import memory_database
28 from .util import MemoryDatabaseMixin
29
30
31 def dict_factory(cursor, row):
32 d = {}
33 for idx, col in enumerate(cursor.description):
34 d[col[0]] = row[idx]
35 return d
36
37 class MyCursor(sqlite.Cursor):
38 def __init__(self, *args, **kwargs):
39 sqlite.Cursor.__init__(self, *args, **kwargs)
40 self.row_factory = dict_factory
41
42 class ConnectionFactoryTests(unittest.TestCase):
43 def test_connection_factories(self):
44 class DefectFactory(sqlite.Connection):
45 def __init__(self, *args, **kwargs):
46 return None
47 class OkFactory(sqlite.Connection):
48 def __init__(self, *args, **kwargs):
49 sqlite.Connection.__init__(self, *args, **kwargs)
50
51 with memory_database(factory=OkFactory) as con:
52 self.assertIsInstance(con, OkFactory)
53 regex = "Base Connection.__init__ not called."
54 with self.assertRaisesRegex(sqlite.ProgrammingError, regex):
55 with memory_database(factory=DefectFactory) as con:
56 self.assertIsInstance(con, DefectFactory)
57
58 def test_connection_factory_relayed_call(self):
59 # gh-95132: keyword args must not be passed as positional args
60 class Factory(sqlite.Connection):
61 def __init__(self, *args, **kwargs):
62 kwargs["isolation_level"] = None
63 super(Factory, self).__init__(*args, **kwargs)
64
65 with memory_database(factory=Factory) as con:
66 self.assertIsNone(con.isolation_level)
67 self.assertIsInstance(con, Factory)
68
69 def test_connection_factory_as_positional_arg(self):
70 class Factory(sqlite.Connection):
71 def __init__(self, *args, **kwargs):
72 super(Factory, self).__init__(*args, **kwargs)
73
74 regex = (
75 r"Passing more than 1 positional argument to _sqlite3.Connection\(\) "
76 r"is deprecated. Parameters 'timeout', 'detect_types', "
77 r"'isolation_level', 'check_same_thread', 'factory', "
78 r"'cached_statements' and 'uri' will become keyword-only "
79 r"parameters in Python 3.15."
80 )
81 with self.assertWarnsRegex(DeprecationWarning, regex) as cm:
82 with memory_database(5.0, 0, None, True, Factory) as con:
83 self.assertIsNone(con.isolation_level)
84 self.assertIsInstance(con, Factory)
85 self.assertEqual(cm.filename, __file__)
86
87
88 class CursorFactoryTests(MemoryDatabaseMixin, unittest.TestCase):
89
90 def test_is_instance(self):
91 cur = self.con.cursor()
92 self.assertIsInstance(cur, sqlite.Cursor)
93 cur = self.con.cursor(MyCursor)
94 self.assertIsInstance(cur, MyCursor)
95 cur = self.con.cursor(factory=lambda con: MyCursor(con))
96 self.assertIsInstance(cur, MyCursor)
97
98 def test_invalid_factory(self):
99 # not a callable at all
100 self.assertRaises(TypeError, self.con.cursor, None)
101 # invalid callable with not exact one argument
102 self.assertRaises(TypeError, self.con.cursor, lambda: None)
103 # invalid callable returning non-cursor
104 self.assertRaises(TypeError, self.con.cursor, lambda con: None)
105
106
107 class RowFactoryTestsBackwardsCompat(MemoryDatabaseMixin, unittest.TestCase):
108
109 def test_is_produced_by_factory(self):
110 cur = self.con.cursor(factory=MyCursor)
111 cur.execute("select 4+5 as foo")
112 row = cur.fetchone()
113 self.assertIsInstance(row, dict)
114 cur.close()
115
116
117 class RowFactoryTests(MemoryDatabaseMixin, unittest.TestCase):
118
119 def setUp(self):
120 super().setUp()
121 self.con.row_factory = sqlite.Row
122
123 def test_custom_factory(self):
124 self.con.row_factory = lambda cur, row: list(row)
125 row = self.con.execute("select 1, 2").fetchone()
126 self.assertIsInstance(row, list)
127
128 def test_sqlite_row_index(self):
129 row = self.con.execute("select 1 as a_1, 2 as b").fetchone()
130 self.assertIsInstance(row, sqlite.Row)
131
132 self.assertEqual(row["a_1"], 1, "by name: wrong result for column 'a_1'")
133 self.assertEqual(row["b"], 2, "by name: wrong result for column 'b'")
134
135 self.assertEqual(row["A_1"], 1, "by name: wrong result for column 'A_1'")
136 self.assertEqual(row["B"], 2, "by name: wrong result for column 'B'")
137
138 self.assertEqual(row[0], 1, "by index: wrong result for column 0")
139 self.assertEqual(row[1], 2, "by index: wrong result for column 1")
140 self.assertEqual(row[-1], 2, "by index: wrong result for column -1")
141 self.assertEqual(row[-2], 1, "by index: wrong result for column -2")
142
143 with self.assertRaises(IndexError):
144 row['c']
145 with self.assertRaises(IndexError):
146 row['a_\x11']
147 with self.assertRaises(IndexError):
148 row['a\x7f1']
149 with self.assertRaises(IndexError):
150 row[2]
151 with self.assertRaises(IndexError):
152 row[-3]
153 with self.assertRaises(IndexError):
154 row[2**1000]
155 with self.assertRaises(IndexError):
156 row[complex()] # index must be int or string
157
158 def test_sqlite_row_index_unicode(self):
159 row = self.con.execute("select 1 as \xff").fetchone()
160 self.assertEqual(row["\xff"], 1)
161 with self.assertRaises(IndexError):
162 row['\u0178']
163 with self.assertRaises(IndexError):
164 row['\xdf']
165
166 def test_sqlite_row_slice(self):
167 # A sqlite.Row can be sliced like a list.
168 row = self.con.execute("select 1, 2, 3, 4").fetchone()
169 self.assertEqual(row[0:0], ())
170 self.assertEqual(row[0:1], (1,))
171 self.assertEqual(row[1:3], (2, 3))
172 self.assertEqual(row[3:1], ())
173 # Explicit bounds are optional.
174 self.assertEqual(row[1:], (2, 3, 4))
175 self.assertEqual(row[:3], (1, 2, 3))
176 # Slices can use negative indices.
177 self.assertEqual(row[-2:-1], (3,))
178 self.assertEqual(row[-2:], (3, 4))
179 # Slicing supports steps.
180 self.assertEqual(row[0:4:2], (1, 3))
181 self.assertEqual(row[3:0:-2], (4, 2))
182
183 def test_sqlite_row_iter(self):
184 # Checks if the row object is iterable.
185 row = self.con.execute("select 1 as a, 2 as b").fetchone()
186
187 # Is iterable in correct order and produces valid results:
188 items = [col for col in row]
189 self.assertEqual(items, [1, 2])
190
191 # Is iterable the second time:
192 items = [col for col in row]
193 self.assertEqual(items, [1, 2])
194
195 def test_sqlite_row_as_tuple(self):
196 # Checks if the row object can be converted to a tuple.
197 row = self.con.execute("select 1 as a, 2 as b").fetchone()
198 t = tuple(row)
199 self.assertEqual(t, (row['a'], row['b']))
200
201 def test_sqlite_row_as_dict(self):
202 # Checks if the row object can be correctly converted to a dictionary.
203 row = self.con.execute("select 1 as a, 2 as b").fetchone()
204 d = dict(row)
205 self.assertEqual(d["a"], row["a"])
206 self.assertEqual(d["b"], row["b"])
207
208 def test_sqlite_row_hash_cmp(self):
209 # Checks if the row object compares and hashes correctly.
210 row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
211 row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
212 row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
213 row_4 = self.con.execute("select 1 as b, 2 as a").fetchone()
214 row_5 = self.con.execute("select 2 as b, 1 as a").fetchone()
215
216 self.assertTrue(row_1 == row_1)
217 self.assertTrue(row_1 == row_2)
218 self.assertFalse(row_1 == row_3)
219 self.assertFalse(row_1 == row_4)
220 self.assertFalse(row_1 == row_5)
221 self.assertFalse(row_1 == object())
222
223 self.assertFalse(row_1 != row_1)
224 self.assertFalse(row_1 != row_2)
225 self.assertTrue(row_1 != row_3)
226 self.assertTrue(row_1 != row_4)
227 self.assertTrue(row_1 != row_5)
228 self.assertTrue(row_1 != object())
229
230 with self.assertRaises(TypeError):
231 row_1 > row_2
232 with self.assertRaises(TypeError):
233 row_1 < row_2
234 with self.assertRaises(TypeError):
235 row_1 >= row_2
236 with self.assertRaises(TypeError):
237 row_1 <= row_2
238
239 self.assertEqual(hash(row_1), hash(row_2))
240
241 def test_sqlite_row_as_sequence(self):
242 # Checks if the row object can act like a sequence.
243 row = self.con.execute("select 1 as a, 2 as b").fetchone()
244
245 as_tuple = tuple(row)
246 self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))
247 self.assertIsInstance(row, Sequence)
248
249 def test_sqlite_row_keys(self):
250 # Checks if the row object can return a list of columns as strings.
251 row = self.con.execute("select 1 as a, 2 as b").fetchone()
252 self.assertEqual(row.keys(), ['a', 'b'])
253
254 def test_fake_cursor_class(self):
255 # Issue #24257: Incorrect use of PyObject_IsInstance() caused
256 # segmentation fault.
257 # Issue #27861: Also applies for cursor factory.
258 class FakeCursor(str):
259 __class__ = sqlite.Cursor
260 self.assertRaises(TypeError, self.con.cursor, FakeCursor)
261 self.assertRaises(TypeError, sqlite.Row, FakeCursor(), ())
262
263
264 class TextFactoryTests(MemoryDatabaseMixin, unittest.TestCase):
265
266 def test_unicode(self):
267 austria = "Österreich"
268 row = self.con.execute("select ?", (austria,)).fetchone()
269 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
270
271 def test_string(self):
272 self.con.text_factory = bytes
273 austria = "Österreich"
274 row = self.con.execute("select ?", (austria,)).fetchone()
275 self.assertEqual(type(row[0]), bytes, "type of row[0] must be bytes")
276 self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")
277
278 def test_custom(self):
279 self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
280 austria = "Österreich"
281 row = self.con.execute("select ?", (austria,)).fetchone()
282 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
283 self.assertEndsWith(row[0], "reich", "column must contain original data")
284
285
286 class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
287
288 def setUp(self):
289 self.con = sqlite.connect(":memory:")
290 self.con.execute("create table test (value text)")
291 self.con.execute("insert into test (value) values (?)", ("a\x00b",))
292
293 def tearDown(self):
294 self.con.close()
295
296 def test_string(self):
297 # text_factory defaults to str
298 row = self.con.execute("select value from test").fetchone()
299 self.assertIs(type(row[0]), str)
300 self.assertEqual(row[0], "a\x00b")
301
302 def test_bytes(self):
303 self.con.text_factory = bytes
304 row = self.con.execute("select value from test").fetchone()
305 self.assertIs(type(row[0]), bytes)
306 self.assertEqual(row[0], b"a\x00b")
307
308 def test_bytearray(self):
309 self.con.text_factory = bytearray
310 row = self.con.execute("select value from test").fetchone()
311 self.assertIs(type(row[0]), bytearray)
312 self.assertEqual(row[0], b"a\x00b")
313
314 def test_custom(self):
315 # A custom factory should receive a bytes argument
316 self.con.text_factory = lambda x: x
317 row = self.con.execute("select value from test").fetchone()
318 self.assertIs(type(row[0]), bytes)
319 self.assertEqual(row[0], b"a\x00b")
320
321
322 if __name__ == "__main__":
323 unittest.main()