blob: a8348b4626f89691fd84ca2b395685a41f7207a8 [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
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000114 def CheckSqliteRowIter(self):
115 """Checks if the row object is iterable"""
116 self.con.row_factory = sqlite.Row
117 row = self.con.execute("select 1 as a, 2 as b").fetchone()
118 for col in row:
119 pass
120
121 def CheckSqliteRowAsTuple(self):
122 """Checks if the row object can be converted to a tuple"""
123 self.con.row_factory = sqlite.Row
124 row = self.con.execute("select 1 as a, 2 as b").fetchone()
125 t = tuple(row)
Benjamin Peterson29352c42014-02-15 13:19:59 -0500126 self.assertEqual(t, (row['a'], row['b']))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000127
128 def CheckSqliteRowAsDict(self):
129 """Checks if the row object can be correctly converted to a dictionary"""
130 self.con.row_factory = sqlite.Row
131 row = self.con.execute("select 1 as a, 2 as b").fetchone()
132 d = dict(row)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000133 self.assertEqual(d["a"], row["a"])
134 self.assertEqual(d["b"], row["b"])
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000135
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000136 def CheckSqliteRowHashCmp(self):
137 """Checks if the row object compares and hashes correctly"""
138 self.con.row_factory = sqlite.Row
139 row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
140 row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
141 row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
142
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200143 self.assertEqual(row_1, row_1)
144 self.assertEqual(row_1, row_2)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000145 self.assertTrue(row_2 != row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000146
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000147 self.assertFalse(row_1 != row_1)
148 self.assertFalse(row_1 != row_2)
149 self.assertFalse(row_2 == row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000150
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000151 self.assertEqual(row_1, row_2)
152 self.assertEqual(hash(row_1), hash(row_2))
153 self.assertNotEqual(row_1, row_3)
154 self.assertNotEqual(hash(row_1), hash(row_3))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000155
Serhiy Storchaka47a98132014-05-28 12:58:34 +0300156 def CheckSqliteRowAsSequence(self):
157 """ Checks if the row object can act like a sequence """
158 self.con.row_factory = sqlite.Row
159 row = self.con.execute("select 1 as a, 2 as b").fetchone()
160
161 as_tuple = tuple(row)
162 self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))
163 self.assertIsInstance(row, Sequence)
164
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300165 def CheckFakeCursorClass(self):
166 # Issue #24257: Incorrect use of PyObject_IsInstance() caused
167 # segmentation fault.
168 class FakeCursor(str):
169 __class__ = sqlite.Cursor
170 cur = self.con.cursor(factory=FakeCursor)
171 self.assertRaises(TypeError, sqlite.Row, cur, ())
172
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173 def tearDown(self):
174 self.con.close()
175
176class TextFactoryTests(unittest.TestCase):
177 def setUp(self):
178 self.con = sqlite.connect(":memory:")
179
180 def CheckUnicode(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000181 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200183 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184
185 def CheckString(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000186 self.con.text_factory = bytes
187 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200189 self.assertEqual(type(row[0]), bytes, "type of row[0] must be bytes")
190 self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191
192 def CheckCustom(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000193 self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
Gerhard Häring6d214562007-08-10 18:15:11 +0000194 austria = "Österreich"
195 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200196 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000197 self.assertTrue(row[0].endswith("reich"), "column must contain original data")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198
199 def CheckOptimizedUnicode(self):
Petri Lehtinenbc35beb2012-02-09 21:09:03 +0200200 # In py3k, str objects are always returned when text_factory
201 # is OptimizedUnicode
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000202 self.con.text_factory = sqlite.OptimizedUnicode
Gerhard Häring6d214562007-08-10 18:15:11 +0000203 austria = "Österreich"
204 germany = "Deutchland"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000205 a_row = self.con.execute("select ?", (austria,)).fetchone()
206 d_row = self.con.execute("select ?", (germany,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200207 self.assertEqual(type(a_row[0]), str, "type of non-ASCII row must be str")
208 self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209
210 def tearDown(self):
211 self.con.close()
212
Petri Lehtinen023fe332012-02-01 22:18:19 +0200213class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
214 def setUp(self):
215 self.con = sqlite.connect(":memory:")
216 self.con.execute("create table test (value text)")
217 self.con.execute("insert into test (value) values (?)", ("a\x00b",))
218
219 def CheckString(self):
220 # text_factory defaults to str
221 row = self.con.execute("select value from test").fetchone()
222 self.assertIs(type(row[0]), str)
223 self.assertEqual(row[0], "a\x00b")
224
225 def CheckBytes(self):
226 self.con.text_factory = bytes
227 row = self.con.execute("select value from test").fetchone()
228 self.assertIs(type(row[0]), bytes)
229 self.assertEqual(row[0], b"a\x00b")
230
231 def CheckBytearray(self):
232 self.con.text_factory = bytearray
233 row = self.con.execute("select value from test").fetchone()
234 self.assertIs(type(row[0]), bytearray)
235 self.assertEqual(row[0], b"a\x00b")
236
237 def CheckCustom(self):
238 # A custom factory should receive a bytes argument
239 self.con.text_factory = lambda x: x
240 row = self.con.execute("select value from test").fetchone()
241 self.assertIs(type(row[0]), bytes)
242 self.assertEqual(row[0], b"a\x00b")
243
244 def tearDown(self):
245 self.con.close()
246
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247def suite():
248 connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
249 cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
250 row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
251 row_suite = unittest.makeSuite(RowFactoryTests, "Check")
252 text_suite = unittest.makeSuite(TextFactoryTests, "Check")
Petri Lehtinen023fe332012-02-01 22:18:19 +0200253 text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
254 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 +0000255
256def test():
257 runner = unittest.TextTestRunner()
258 runner.run(suite())
259
260if __name__ == "__main__":
261 test()