blob: f587596f644880cab5b3d11f0e228014937319b6 [file] [log] [blame]
Petri Lehtinenf8547992012-02-02 17:17:36 +02001#-*- coding: iso-8859-1 -*-
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002# pysqlite2/test/factory.py: tests for the various factories in pysqlite
3#
Gerhard Häringe7ea7452008-03-29 00:45:29 +00004# Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005#
6# This file is part of pysqlite.
7#
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.
11#
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:
15#
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.
23
24import unittest
25import sqlite3 as sqlite
Serhiy Storchaka47a98132014-05-28 12:58:34 +030026from collections.abc import Sequence
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027
28class MyConnection(sqlite.Connection):
29 def __init__(self, *args, **kwargs):
30 sqlite.Connection.__init__(self, *args, **kwargs)
31
32def dict_factory(cursor, row):
33 d = {}
34 for idx, col in enumerate(cursor.description):
35 d[col[0]] = row[idx]
36 return d
37
38class MyCursor(sqlite.Cursor):
39 def __init__(self, *args, **kwargs):
40 sqlite.Cursor.__init__(self, *args, **kwargs)
41 self.row_factory = dict_factory
42
43class ConnectionFactoryTests(unittest.TestCase):
44 def setUp(self):
45 self.con = sqlite.connect(":memory:", factory=MyConnection)
46
47 def tearDown(self):
48 self.con.close()
49
50 def CheckIsInstance(self):
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020051 self.assertIsInstance(self.con, MyConnection)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052
53class CursorFactoryTests(unittest.TestCase):
54 def setUp(self):
55 self.con = sqlite.connect(":memory:")
56
57 def tearDown(self):
58 self.con.close()
59
60 def CheckIsInstance(self):
61 cur = self.con.cursor(factory=MyCursor)
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020062 self.assertIsInstance(cur, MyCursor)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64class RowFactoryTestsBackwardsCompat(unittest.TestCase):
65 def setUp(self):
66 self.con = sqlite.connect(":memory:")
67
68 def CheckIsProducedByFactory(self):
69 cur = self.con.cursor(factory=MyCursor)
70 cur.execute("select 4+5 as foo")
71 row = cur.fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020072 self.assertIsInstance(row, dict)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000073 cur.close()
74
75 def tearDown(self):
76 self.con.close()
77
78class RowFactoryTests(unittest.TestCase):
79 def setUp(self):
80 self.con = sqlite.connect(":memory:")
81
82 def CheckCustomFactory(self):
83 self.con.row_factory = lambda cur, row: list(row)
84 row = self.con.execute("select 1, 2").fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020085 self.assertIsInstance(row, list)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000086
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000087 def CheckSqliteRowIndex(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088 self.con.row_factory = sqlite.Row
89 row = self.con.execute("select 1 as a, 2 as b").fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020090 self.assertIsInstance(row, sqlite.Row)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091
92 col1, col2 = row["a"], row["b"]
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020093 self.assertEqual(col1, 1, "by name: wrong result for column 'a'")
94 self.assertEqual(col2, 2, "by name: wrong result for column 'a'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000095
96 col1, col2 = row["A"], row["B"]
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020097 self.assertEqual(col1, 1, "by name: wrong result for column 'A'")
98 self.assertEqual(col2, 2, "by name: wrong result for column 'B'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000099
Serhiy Storchaka47a98132014-05-28 12:58:34 +0300100 self.assertEqual(row[0], 1, "by index: wrong result for column 0")
101 self.assertEqual(row[1], 2, "by index: wrong result for column 1")
102 self.assertEqual(row[-1], 2, "by index: wrong result for column -1")
103 self.assertEqual(row[-2], 1, "by index: wrong result for column -2")
104
105 with self.assertRaises(IndexError):
106 row['c']
107 with self.assertRaises(IndexError):
108 row[2]
109 with self.assertRaises(IndexError):
110 row[-3]
111 with self.assertRaises(IndexError):
112 row[2**1000]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300114 def CheckSqliteRowSlice(self):
115 # A sqlite.Row can be sliced like a list.
116 self.con.row_factory = sqlite.Row
117 row = self.con.execute("select 1, 2, 3, 4").fetchone()
118 self.assertEqual(row[0:0], ())
119 self.assertEqual(row[0:1], (1,))
120 self.assertEqual(row[1:3], (2, 3))
121 self.assertEqual(row[3:1], ())
122 # Explicit bounds are optional.
123 self.assertEqual(row[1:], (2, 3, 4))
124 self.assertEqual(row[:3], (1, 2, 3))
125 # Slices can use negative indices.
126 self.assertEqual(row[-2:-1], (3,))
127 self.assertEqual(row[-2:], (3, 4))
128 # Slicing supports steps.
129 self.assertEqual(row[0:4:2], (1, 3))
130 self.assertEqual(row[3:0:-2], (4, 2))
131
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000132 def CheckSqliteRowIter(self):
133 """Checks if the row object is iterable"""
134 self.con.row_factory = sqlite.Row
135 row = self.con.execute("select 1 as a, 2 as b").fetchone()
136 for col in row:
137 pass
138
139 def CheckSqliteRowAsTuple(self):
140 """Checks if the row object can be converted to a tuple"""
141 self.con.row_factory = sqlite.Row
142 row = self.con.execute("select 1 as a, 2 as b").fetchone()
143 t = tuple(row)
Benjamin Peterson29352c42014-02-15 13:19:59 -0500144 self.assertEqual(t, (row['a'], row['b']))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000145
146 def CheckSqliteRowAsDict(self):
147 """Checks if the row object can be correctly converted to a dictionary"""
148 self.con.row_factory = sqlite.Row
149 row = self.con.execute("select 1 as a, 2 as b").fetchone()
150 d = dict(row)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000151 self.assertEqual(d["a"], row["a"])
152 self.assertEqual(d["b"], row["b"])
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000153
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000154 def CheckSqliteRowHashCmp(self):
155 """Checks if the row object compares and hashes correctly"""
156 self.con.row_factory = sqlite.Row
157 row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
158 row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
159 row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
160
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200161 self.assertEqual(row_1, row_1)
162 self.assertEqual(row_1, row_2)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000163 self.assertTrue(row_2 != row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000164
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000165 self.assertFalse(row_1 != row_1)
166 self.assertFalse(row_1 != row_2)
167 self.assertFalse(row_2 == row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000168
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000169 self.assertEqual(row_1, row_2)
170 self.assertEqual(hash(row_1), hash(row_2))
171 self.assertNotEqual(row_1, row_3)
172 self.assertNotEqual(hash(row_1), hash(row_3))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000173
Serhiy Storchaka47a98132014-05-28 12:58:34 +0300174 def CheckSqliteRowAsSequence(self):
175 """ Checks if the row object can act like a sequence """
176 self.con.row_factory = sqlite.Row
177 row = self.con.execute("select 1 as a, 2 as b").fetchone()
178
179 as_tuple = tuple(row)
180 self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))
181 self.assertIsInstance(row, Sequence)
182
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300183 def CheckFakeCursorClass(self):
184 # Issue #24257: Incorrect use of PyObject_IsInstance() caused
185 # segmentation fault.
186 class FakeCursor(str):
187 __class__ = sqlite.Cursor
188 cur = self.con.cursor(factory=FakeCursor)
189 self.assertRaises(TypeError, sqlite.Row, cur, ())
190
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191 def tearDown(self):
192 self.con.close()
193
194class TextFactoryTests(unittest.TestCase):
195 def setUp(self):
196 self.con = sqlite.connect(":memory:")
197
198 def CheckUnicode(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000199 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200201 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000202
203 def CheckString(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000204 self.con.text_factory = bytes
205 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200207 self.assertEqual(type(row[0]), bytes, "type of row[0] must be bytes")
208 self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209
210 def CheckCustom(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000211 self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
Gerhard Häring6d214562007-08-10 18:15:11 +0000212 austria = "Österreich"
213 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200214 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000215 self.assertTrue(row[0].endswith("reich"), "column must contain original data")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216
217 def CheckOptimizedUnicode(self):
Petri Lehtinenbc35beb2012-02-09 21:09:03 +0200218 # In py3k, str objects are always returned when text_factory
219 # is OptimizedUnicode
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220 self.con.text_factory = sqlite.OptimizedUnicode
Gerhard Häring6d214562007-08-10 18:15:11 +0000221 austria = "Österreich"
222 germany = "Deutchland"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000223 a_row = self.con.execute("select ?", (austria,)).fetchone()
224 d_row = self.con.execute("select ?", (germany,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200225 self.assertEqual(type(a_row[0]), str, "type of non-ASCII row must be str")
226 self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227
228 def tearDown(self):
229 self.con.close()
230
Petri Lehtinen023fe332012-02-01 22:18:19 +0200231class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
232 def setUp(self):
233 self.con = sqlite.connect(":memory:")
234 self.con.execute("create table test (value text)")
235 self.con.execute("insert into test (value) values (?)", ("a\x00b",))
236
237 def CheckString(self):
238 # text_factory defaults to str
239 row = self.con.execute("select value from test").fetchone()
240 self.assertIs(type(row[0]), str)
241 self.assertEqual(row[0], "a\x00b")
242
243 def CheckBytes(self):
244 self.con.text_factory = bytes
245 row = self.con.execute("select value from test").fetchone()
246 self.assertIs(type(row[0]), bytes)
247 self.assertEqual(row[0], b"a\x00b")
248
249 def CheckBytearray(self):
250 self.con.text_factory = bytearray
251 row = self.con.execute("select value from test").fetchone()
252 self.assertIs(type(row[0]), bytearray)
253 self.assertEqual(row[0], b"a\x00b")
254
255 def CheckCustom(self):
256 # A custom factory should receive a bytes argument
257 self.con.text_factory = lambda x: x
258 row = self.con.execute("select value from test").fetchone()
259 self.assertIs(type(row[0]), bytes)
260 self.assertEqual(row[0], b"a\x00b")
261
262 def tearDown(self):
263 self.con.close()
264
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000265def suite():
266 connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
267 cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
268 row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
269 row_suite = unittest.makeSuite(RowFactoryTests, "Check")
270 text_suite = unittest.makeSuite(TextFactoryTests, "Check")
Petri Lehtinen023fe332012-02-01 22:18:19 +0200271 text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
272 return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite, text_zero_bytes_suite))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000273
274def test():
275 runner = unittest.TextTestRunner()
276 runner.run(suite())
277
278if __name__ == "__main__":
279 test()