blob: 98dcae5d6c4a88609ae842f062f767c427421e14 [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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000165 def tearDown(self):
166 self.con.close()
167
168class TextFactoryTests(unittest.TestCase):
169 def setUp(self):
170 self.con = sqlite.connect(":memory:")
171
172 def CheckUnicode(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000173 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200175 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000176
177 def CheckString(self):
Gerhard Häring6d214562007-08-10 18:15:11 +0000178 self.con.text_factory = bytes
179 austria = "Österreich"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000180 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200181 self.assertEqual(type(row[0]), bytes, "type of row[0] must be bytes")
182 self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183
184 def CheckCustom(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000185 self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
Gerhard Häring6d214562007-08-10 18:15:11 +0000186 austria = "Österreich"
187 row = self.con.execute("select ?", (austria,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200188 self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000189 self.assertTrue(row[0].endswith("reich"), "column must contain original data")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190
191 def CheckOptimizedUnicode(self):
Petri Lehtinenbc35beb2012-02-09 21:09:03 +0200192 # In py3k, str objects are always returned when text_factory
193 # is OptimizedUnicode
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194 self.con.text_factory = sqlite.OptimizedUnicode
Gerhard Häring6d214562007-08-10 18:15:11 +0000195 austria = "Österreich"
196 germany = "Deutchland"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000197 a_row = self.con.execute("select ?", (austria,)).fetchone()
198 d_row = self.con.execute("select ?", (germany,)).fetchone()
Serhiy Storchaka78ee0782013-11-17 00:39:12 +0200199 self.assertEqual(type(a_row[0]), str, "type of non-ASCII row must be str")
200 self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000201
202 def tearDown(self):
203 self.con.close()
204
Petri Lehtinen023fe332012-02-01 22:18:19 +0200205class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
206 def setUp(self):
207 self.con = sqlite.connect(":memory:")
208 self.con.execute("create table test (value text)")
209 self.con.execute("insert into test (value) values (?)", ("a\x00b",))
210
211 def CheckString(self):
212 # text_factory defaults to str
213 row = self.con.execute("select value from test").fetchone()
214 self.assertIs(type(row[0]), str)
215 self.assertEqual(row[0], "a\x00b")
216
217 def CheckBytes(self):
218 self.con.text_factory = bytes
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 CheckBytearray(self):
224 self.con.text_factory = bytearray
225 row = self.con.execute("select value from test").fetchone()
226 self.assertIs(type(row[0]), bytearray)
227 self.assertEqual(row[0], b"a\x00b")
228
229 def CheckCustom(self):
230 # A custom factory should receive a bytes argument
231 self.con.text_factory = lambda x: x
232 row = self.con.execute("select value from test").fetchone()
233 self.assertIs(type(row[0]), bytes)
234 self.assertEqual(row[0], b"a\x00b")
235
236 def tearDown(self):
237 self.con.close()
238
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000239def suite():
240 connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
241 cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
242 row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
243 row_suite = unittest.makeSuite(RowFactoryTests, "Check")
244 text_suite = unittest.makeSuite(TextFactoryTests, "Check")
Petri Lehtinen023fe332012-02-01 22:18:19 +0200245 text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
246 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 +0000247
248def test():
249 runner = unittest.TextTestRunner()
250 runner.run(suite())
251
252if __name__ == "__main__":
253 test()