blob: 1013755b9cfd7da02db67868f32ef5e2c5a3e244 [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
26
27class MyConnection(sqlite.Connection):
28 def __init__(self, *args, **kwargs):
29 sqlite.Connection.__init__(self, *args, **kwargs)
30
31def dict_factory(cursor, row):
32 d = {}
33 for idx, col in enumerate(cursor.description):
34 d[col[0]] = row[idx]
35 return d
36
37class MyCursor(sqlite.Cursor):
38 def __init__(self, *args, **kwargs):
39 sqlite.Cursor.__init__(self, *args, **kwargs)
40 self.row_factory = dict_factory
41
42class ConnectionFactoryTests(unittest.TestCase):
43 def setUp(self):
44 self.con = sqlite.connect(":memory:", factory=MyConnection)
45
46 def tearDown(self):
47 self.con.close()
48
49 def CheckIsInstance(self):
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020050 self.assertIsInstance(self.con, MyConnection)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051
52class CursorFactoryTests(unittest.TestCase):
53 def setUp(self):
54 self.con = sqlite.connect(":memory:")
55
56 def tearDown(self):
57 self.con.close()
58
59 def CheckIsInstance(self):
60 cur = self.con.cursor(factory=MyCursor)
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020061 self.assertIsInstance(cur, MyCursor)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062
63class RowFactoryTestsBackwardsCompat(unittest.TestCase):
64 def setUp(self):
65 self.con = sqlite.connect(":memory:")
66
67 def CheckIsProducedByFactory(self):
68 cur = self.con.cursor(factory=MyCursor)
69 cur.execute("select 4+5 as foo")
70 row = cur.fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020071 self.assertIsInstance(row, dict)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000072 cur.close()
73
74 def tearDown(self):
75 self.con.close()
76
77class RowFactoryTests(unittest.TestCase):
78 def setUp(self):
79 self.con = sqlite.connect(":memory:")
80
81 def CheckCustomFactory(self):
82 self.con.row_factory = lambda cur, row: list(row)
83 row = self.con.execute("select 1, 2").fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020084 self.assertIsInstance(row, list)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000085
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000086 def CheckSqliteRowIndex(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087 self.con.row_factory = sqlite.Row
88 row = self.con.execute("select 1 as a, 2 as b").fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020089 self.assertIsInstance(row, sqlite.Row)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000090
91 col1, col2 = row["a"], row["b"]
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020092 self.assertEqual(col1, 1, "by name: wrong result for column 'a'")
93 self.assertEqual(col2, 2, "by name: wrong result for column 'a'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094
95 col1, col2 = row["A"], row["B"]
Serhiy Storchaka78ee0782013-11-17 00:39:12 +020096 self.assertEqual(col1, 1, "by name: wrong result for column 'A'")
97 self.assertEqual(col2, 2, "by name: wrong result for column 'B'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098
99 col1, col2 = row[0], row[1]
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200100 self.assertEqual(col1, 1, "by index: wrong result for column 0")
101 self.assertEqual(col2, 2, "by index: wrong result for column 1")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000102
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000103 def CheckSqliteRowIter(self):
104 """Checks if the row object is iterable"""
105 self.con.row_factory = sqlite.Row
106 row = self.con.execute("select 1 as a, 2 as b").fetchone()
107 for col in row:
108 pass
109
110 def CheckSqliteRowAsTuple(self):
111 """Checks if the row object can be converted to a tuple"""
112 self.con.row_factory = sqlite.Row
113 row = self.con.execute("select 1 as a, 2 as b").fetchone()
114 t = tuple(row)
Benjamin Peterson29352c42014-02-15 13:19:59 -0500115 self.assertEqual(t, (row['a'], row['b']))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000116
117 def CheckSqliteRowAsDict(self):
118 """Checks if the row object can be correctly converted to a dictionary"""
119 self.con.row_factory = sqlite.Row
120 row = self.con.execute("select 1 as a, 2 as b").fetchone()
121 d = dict(row)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000122 self.assertEqual(d["a"], row["a"])
123 self.assertEqual(d["b"], row["b"])
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000124
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000125 def CheckSqliteRowHashCmp(self):
126 """Checks if the row object compares and hashes correctly"""
127 self.con.row_factory = sqlite.Row
128 row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
129 row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
130 row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
131
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200132 self.assertEqual(row_1, row_1)
133 self.assertEqual(row_1, row_2)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000134 self.assertTrue(row_2 != row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000135
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000136 self.assertFalse(row_1 != row_1)
137 self.assertFalse(row_1 != row_2)
138 self.assertFalse(row_2 == row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000139
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000140 self.assertEqual(row_1, row_2)
141 self.assertEqual(hash(row_1), hash(row_2))
142 self.assertNotEqual(row_1, row_3)
143 self.assertNotEqual(hash(row_1), hash(row_3))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000144
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000145 def tearDown(self):
146 self.con.close()
147
148class TextFactoryTests(unittest.TestCase):
149 def setUp(self):
150 self.con = sqlite.connect(":memory:")
151
152 def CheckUnicode(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000153 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200155 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156
157 def CheckString(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000158 self.con.text_factory = bytes
159 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200161 self.assertEqual(type(row[0]), bytes, "type of row[0] must be bytes")
162 self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163
164 def CheckCustom(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000165 self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
Gerhard Häring6d214562007-08-10 18:15:11 +0000166 austria = "Österreich"
167 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200168 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000169 self.assertTrue(row[0].endswith("reich"), "column must contain original data")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000170
171 def CheckOptimizedUnicode(self):
Petri Lehtinenbc35beb2012-02-09 21:09:03 +0200172 # In py3k, str objects are always returned when text_factory
173 # is OptimizedUnicode
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174 self.con.text_factory = sqlite.OptimizedUnicode
Gerhard Häring6d214562007-08-10 18:15:11 +0000175 austria = "Österreich"
176 germany = "Deutchland"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000177 a_row = self.con.execute("select ?", (austria,)).fetchone()
178 d_row = self.con.execute("select ?", (germany,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200179 self.assertEqual(type(a_row[0]), str, "type of non-ASCII row must be str")
180 self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181
182 def tearDown(self):
183 self.con.close()
184
Petri Lehtinen023fe332012-02-01 22:18:19 +0200185class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
186 def setUp(self):
187 self.con = sqlite.connect(":memory:")
188 self.con.execute("create table test (value text)")
189 self.con.execute("insert into test (value) values (?)", ("a\x00b",))
190
191 def CheckString(self):
192 # text_factory defaults to str
193 row = self.con.execute("select value from test").fetchone()
194 self.assertIs(type(row[0]), str)
195 self.assertEqual(row[0], "a\x00b")
196
197 def CheckBytes(self):
198 self.con.text_factory = bytes
199 row = self.con.execute("select value from test").fetchone()
200 self.assertIs(type(row[0]), bytes)
201 self.assertEqual(row[0], b"a\x00b")
202
203 def CheckBytearray(self):
204 self.con.text_factory = bytearray
205 row = self.con.execute("select value from test").fetchone()
206 self.assertIs(type(row[0]), bytearray)
207 self.assertEqual(row[0], b"a\x00b")
208
209 def CheckCustom(self):
210 # A custom factory should receive a bytes argument
211 self.con.text_factory = lambda x: x
212 row = self.con.execute("select value from test").fetchone()
213 self.assertIs(type(row[0]), bytes)
214 self.assertEqual(row[0], b"a\x00b")
215
216 def tearDown(self):
217 self.con.close()
218
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000219def suite():
220 connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
221 cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
222 row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
223 row_suite = unittest.makeSuite(RowFactoryTests, "Check")
224 text_suite = unittest.makeSuite(TextFactoryTests, "Check")
Petri Lehtinen023fe332012-02-01 22:18:19 +0200225 text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
226 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 +0000227
228def test():
229 runner = unittest.TextTestRunner()
230 runner.run(suite())
231
232if __name__ == "__main__":
233 test()