blob: 55695851f113b21f7f0beb367e42d929f17c69e8 [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):
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000050 self.assertTrue(isinstance(self.con,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051 MyConnection),
52 "connection is not instance of MyConnection")
53
54class CursorFactoryTests(unittest.TestCase):
55 def setUp(self):
56 self.con = sqlite.connect(":memory:")
57
58 def tearDown(self):
59 self.con.close()
60
61 def CheckIsInstance(self):
62 cur = self.con.cursor(factory=MyCursor)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000063 self.assertTrue(isinstance(cur,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064 MyCursor),
65 "cursor is not instance of MyCursor")
66
67class RowFactoryTestsBackwardsCompat(unittest.TestCase):
68 def setUp(self):
69 self.con = sqlite.connect(":memory:")
70
71 def CheckIsProducedByFactory(self):
72 cur = self.con.cursor(factory=MyCursor)
73 cur.execute("select 4+5 as foo")
74 row = cur.fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000075 self.assertTrue(isinstance(row,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076 dict),
77 "row is not instance of dict")
78 cur.close()
79
80 def tearDown(self):
81 self.con.close()
82
83class RowFactoryTests(unittest.TestCase):
84 def setUp(self):
85 self.con = sqlite.connect(":memory:")
86
87 def CheckCustomFactory(self):
88 self.con.row_factory = lambda cur, row: list(row)
89 row = self.con.execute("select 1, 2").fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000090 self.assertTrue(isinstance(row,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091 list),
92 "row is not instance of list")
93
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000094 def CheckSqliteRowIndex(self):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000095 self.con.row_factory = sqlite.Row
96 row = self.con.execute("select 1 as a, 2 as b").fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000097 self.assertTrue(isinstance(row,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098 sqlite.Row),
99 "row is not instance of sqlite.Row")
100
101 col1, col2 = row["a"], row["b"]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000102 self.assertTrue(col1 == 1, "by name: wrong result for column 'a'")
103 self.assertTrue(col2 == 2, "by name: wrong result for column 'a'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000104
105 col1, col2 = row["A"], row["B"]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000106 self.assertTrue(col1 == 1, "by name: wrong result for column 'A'")
107 self.assertTrue(col2 == 2, "by name: wrong result for column 'B'")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000108
109 col1, col2 = row[0], row[1]
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000110 self.assertTrue(col1 == 1, "by index: wrong result for column 0")
111 self.assertTrue(col2 == 2, "by index: wrong result for column 1")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000113 def CheckSqliteRowIter(self):
114 """Checks if the row object is iterable"""
115 self.con.row_factory = sqlite.Row
116 row = self.con.execute("select 1 as a, 2 as b").fetchone()
117 for col in row:
118 pass
119
120 def CheckSqliteRowAsTuple(self):
121 """Checks if the row object can be converted to a tuple"""
122 self.con.row_factory = sqlite.Row
123 row = self.con.execute("select 1 as a, 2 as b").fetchone()
124 t = tuple(row)
125
126 def CheckSqliteRowAsDict(self):
127 """Checks if the row object can be correctly converted to a dictionary"""
128 self.con.row_factory = sqlite.Row
129 row = self.con.execute("select 1 as a, 2 as b").fetchone()
130 d = dict(row)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000131 self.assertEqual(d["a"], row["a"])
132 self.assertEqual(d["b"], row["b"])
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000133
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000134 def CheckSqliteRowHashCmp(self):
135 """Checks if the row object compares and hashes correctly"""
136 self.con.row_factory = sqlite.Row
137 row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
138 row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
139 row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
140
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000141 self.assertTrue(row_1 == row_1)
142 self.assertTrue(row_1 == row_2)
143 self.assertTrue(row_2 != row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000144
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000145 self.assertFalse(row_1 != row_1)
146 self.assertFalse(row_1 != row_2)
147 self.assertFalse(row_2 == row_3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000148
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000149 self.assertEqual(row_1, row_2)
150 self.assertEqual(hash(row_1), hash(row_2))
151 self.assertNotEqual(row_1, row_3)
152 self.assertNotEqual(hash(row_1), hash(row_3))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000153
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154 def tearDown(self):
155 self.con.close()
156
157class TextFactoryTests(unittest.TestCase):
158 def setUp(self):
159 self.con = sqlite.connect(":memory:")
160
161 def CheckUnicode(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000162 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163 row = self.con.execute("select ?", (austria,)).fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000164 self.assertTrue(type(row[0]) == str, "type of row[0] must be unicode")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000165
166 def CheckString(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000167 self.con.text_factory = bytes
168 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000169 row = self.con.execute("select ?", (austria,)).fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000170 self.assertTrue(type(row[0]) == bytes, "type of row[0] must be bytes")
171 self.assertTrue(row[0] == austria.encode("utf-8"), "column must equal original data in UTF-8")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172
173 def CheckCustom(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000174 self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
Gerhard Häring6d214562007-08-10 18:15:11 +0000175 austria = "Österreich"
176 row = self.con.execute("select ?", (austria,)).fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000177 self.assertTrue(type(row[0]) == str, "type of row[0] must be unicode")
178 self.assertTrue(row[0].endswith("reich"), "column must contain original data")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000179
180 def CheckOptimizedUnicode(self):
181 self.con.text_factory = sqlite.OptimizedUnicode
Gerhard Häring6d214562007-08-10 18:15:11 +0000182 austria = "Österreich"
183 germany = "Deutchland"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184 a_row = self.con.execute("select ?", (austria,)).fetchone()
185 d_row = self.con.execute("select ?", (germany,)).fetchone()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000186 self.assertTrue(type(a_row[0]) == str, "type of non-ASCII row must be str")
187 self.assertTrue(type(d_row[0]) == str, "type of ASCII-only row must be str")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188
189 def tearDown(self):
190 self.con.close()
191
Petri Lehtinen023fe332012-02-01 22:18:19 +0200192class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
193 def setUp(self):
194 self.con = sqlite.connect(":memory:")
195 self.con.execute("create table test (value text)")
196 self.con.execute("insert into test (value) values (?)", ("a\x00b",))
197
198 def CheckString(self):
199 # text_factory defaults to str
200 row = self.con.execute("select value from test").fetchone()
201 self.assertIs(type(row[0]), str)
202 self.assertEqual(row[0], "a\x00b")
203
204 def CheckBytes(self):
205 self.con.text_factory = bytes
206 row = self.con.execute("select value from test").fetchone()
207 self.assertIs(type(row[0]), bytes)
208 self.assertEqual(row[0], b"a\x00b")
209
210 def CheckBytearray(self):
211 self.con.text_factory = bytearray
212 row = self.con.execute("select value from test").fetchone()
213 self.assertIs(type(row[0]), bytearray)
214 self.assertEqual(row[0], b"a\x00b")
215
216 def CheckCustom(self):
217 # A custom factory should receive a bytes argument
218 self.con.text_factory = lambda x: x
219 row = self.con.execute("select value from test").fetchone()
220 self.assertIs(type(row[0]), bytes)
221 self.assertEqual(row[0], b"a\x00b")
222
223 def tearDown(self):
224 self.con.close()
225
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000226def suite():
227 connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
228 cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
229 row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
230 row_suite = unittest.makeSuite(RowFactoryTests, "Check")
231 text_suite = unittest.makeSuite(TextFactoryTests, "Check")
Petri Lehtinen023fe332012-02-01 22:18:19 +0200232 text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
233 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 +0000234
235def test():
236 runner = unittest.TextTestRunner()
237 runner.run(suite())
238
239if __name__ == "__main__":
240 test()