blob: 087edb03df345598d6ed2664f6c8cd60efe03329 [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/hooks.py: tests for various SQLite-specific hooks
3#
Gerhard Häringe7ea7452008-03-29 00:45:29 +00004# Copyright (C) 2006-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
Christian Heimes05e8be12008-02-23 18:30:17 +000024import unittest
Thomas Wouters477c8d52006-05-27 19:21:47 +000025import sqlite3 as sqlite
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026
27class CollationTests(unittest.TestCase):
28 def setUp(self):
29 pass
30
31 def tearDown(self):
32 pass
33
34 def CheckCreateCollationNotCallable(self):
35 con = sqlite.connect(":memory:")
36 try:
37 con.create_collation("X", 42)
38 self.fail("should have raised a TypeError")
Guido van Rossumb940e112007-01-10 16:19:56 +000039 except TypeError as e:
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000040 self.assertEqual(e.args[0], "parameter must be callable")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041
42 def CheckCreateCollationNotAscii(self):
43 con = sqlite.connect(":memory:")
44 try:
Mark Dickinsona56c4672009-01-27 18:17:45 +000045 con.create_collation("collä", lambda x, y: (x > y) - (x < y))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000046 self.fail("should have raised a ProgrammingError")
Guido van Rossumb940e112007-01-10 16:19:56 +000047 except sqlite.ProgrammingError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048 pass
49
R David Murray3f7beb92013-01-10 20:18:21 -050050 @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 1),
51 'old SQLite versions crash on this test')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052 def CheckCollationIsUsed(self):
53 def mycoll(x, y):
54 # reverse order
Mark Dickinsona56c4672009-01-27 18:17:45 +000055 return -((x > y) - (x < y))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056
57 con = sqlite.connect(":memory:")
58 con.create_collation("mycoll", mycoll)
59 sql = """
60 select x from (
61 select 'a' as x
62 union
63 select 'b' as x
64 union
65 select 'c' as x
66 ) order by x collate mycoll
67 """
68 result = con.execute(sql).fetchall()
69 if result[0][0] != "c" or result[1][0] != "b" or result[2][0] != "a":
70 self.fail("the expected order was not returned")
71
72 con.create_collation("mycoll", None)
73 try:
74 result = con.execute(sql).fetchall()
75 self.fail("should have raised an OperationalError")
Guido van Rossumb940e112007-01-10 16:19:56 +000076 except sqlite.OperationalError as e:
Gregory P. Smith04cecaf2009-07-04 08:32:15 +000077 self.assertEqual(e.args[0].lower(), "no such collation sequence: mycoll")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +020079 def CheckCollationReturnsLargeInteger(self):
80 def mycoll(x, y):
81 # reverse order
82 return -((x > y) - (x < y)) * 2**32
83 con = sqlite.connect(":memory:")
84 con.create_collation("mycoll", mycoll)
85 sql = """
86 select x from (
87 select 'a' as x
88 union
89 select 'b' as x
90 union
91 select 'c' as x
92 ) order by x collate mycoll
93 """
94 result = con.execute(sql).fetchall()
95 self.assertEqual(result, [('c',), ('b',), ('a',)],
96 msg="the expected order was not returned")
97
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098 def CheckCollationRegisterTwice(self):
99 """
100 Register two different collation functions under the same name.
101 Verify that the last one is actually used.
102 """
103 con = sqlite.connect(":memory:")
Mark Dickinsona56c4672009-01-27 18:17:45 +0000104 con.create_collation("mycoll", lambda x, y: (x > y) - (x < y))
105 con.create_collation("mycoll", lambda x, y: -((x > y) - (x < y)))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000106 result = con.execute("""
107 select x from (select 'a' as x union select 'b' as x) order by x collate mycoll
108 """).fetchall()
109 if result[0][0] != 'b' or result[1][0] != 'a':
110 self.fail("wrong collation function is used")
111
112 def CheckDeregisterCollation(self):
113 """
114 Register a collation, then deregister it. Make sure an error is raised if we try
115 to use it.
116 """
117 con = sqlite.connect(":memory:")
Mark Dickinsona56c4672009-01-27 18:17:45 +0000118 con.create_collation("mycoll", lambda x, y: (x > y) - (x < y))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000119 con.create_collation("mycoll", None)
120 try:
121 con.execute("select 'a' as x union select 'b' as x order by x collate mycoll")
122 self.fail("should have raised an OperationalError")
Guido van Rossumb940e112007-01-10 16:19:56 +0000123 except sqlite.OperationalError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000124 if not e.args[0].startswith("no such collation sequence"):
125 self.fail("wrong OperationalError raised")
126
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000127class ProgressTests(unittest.TestCase):
128 def CheckProgressHandlerUsed(self):
129 """
130 Test that the progress handler is invoked once it is set.
131 """
132 con = sqlite.connect(":memory:")
133 progress_calls = []
134 def progress():
135 progress_calls.append(None)
136 return 0
137 con.set_progress_handler(progress, 1)
138 con.execute("""
139 create table foo(a, b)
140 """)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000141 self.assertTrue(progress_calls)
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000142
143
144 def CheckOpcodeCount(self):
145 """
146 Test that the opcode argument is respected.
147 """
148 con = sqlite.connect(":memory:")
149 progress_calls = []
150 def progress():
151 progress_calls.append(None)
152 return 0
153 con.set_progress_handler(progress, 1)
154 curs = con.cursor()
155 curs.execute("""
156 create table foo (a, b)
157 """)
158 first_count = len(progress_calls)
159 progress_calls = []
160 con.set_progress_handler(progress, 2)
161 curs.execute("""
162 create table bar (a, b)
163 """)
164 second_count = len(progress_calls)
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000165 self.assertTrue(first_count > second_count)
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000166
167 def CheckCancelOperation(self):
168 """
169 Test that returning a non-zero value stops the operation in progress.
170 """
171 con = sqlite.connect(":memory:")
172 progress_calls = []
173 def progress():
174 progress_calls.append(None)
175 return 1
176 con.set_progress_handler(progress, 1)
177 curs = con.cursor()
178 self.assertRaises(
179 sqlite.OperationalError,
180 curs.execute,
181 "create table bar (a, b)")
182
183 def CheckClearHandler(self):
184 """
185 Test that setting the progress handler to None clears the previously set handler.
186 """
187 con = sqlite.connect(":memory:")
188 action = 0
189 def progress():
Petri Lehtinenc86d9e22012-02-17 21:30:55 +0200190 nonlocal action
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000191 action = 1
192 return 0
193 con.set_progress_handler(progress, 1)
194 con.set_progress_handler(None, 1)
195 con.execute("select 1 union select 2 union select 3").fetchall()
Gregory P. Smith04cecaf2009-07-04 08:32:15 +0000196 self.assertEqual(action, 0, "progress handler was not cleared")
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000197
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200198class TraceCallbackTests(unittest.TestCase):
199 def CheckTraceCallbackUsed(self):
200 """
201 Test that the trace callback is invoked once it is set.
202 """
203 con = sqlite.connect(":memory:")
204 traced_statements = []
205 def trace(statement):
206 traced_statements.append(statement)
207 con.set_trace_callback(trace)
208 con.execute("create table foo(a, b)")
209 self.assertTrue(traced_statements)
210 self.assertTrue(any("create table foo" in stmt for stmt in traced_statements))
211
212 def CheckClearTraceCallback(self):
213 """
214 Test that setting the trace callback to None clears the previously set callback.
215 """
216 con = sqlite.connect(":memory:")
217 traced_statements = []
218 def trace(statement):
219 traced_statements.append(statement)
220 con.set_trace_callback(trace)
221 con.set_trace_callback(None)
222 con.execute("create table foo(a, b)")
223 self.assertFalse(traced_statements, "trace callback was not cleared")
224
225 def CheckUnicodeContent(self):
226 """
227 Test that the statement can contain unicode literals.
228 """
229 unicode_value = '\xf6\xe4\xfc\xd6\xc4\xdc\xdf\u20ac'
230 con = sqlite.connect(":memory:")
231 traced_statements = []
232 def trace(statement):
233 traced_statements.append(statement)
234 con.set_trace_callback(trace)
235 con.execute("create table foo(x)")
Antoine Pitrouf4e18102011-04-04 01:50:50 +0200236 # Can't execute bound parameters as their values don't appear
237 # in traced statements before SQLite 3.6.21
238 # (cf. http://www.sqlite.org/draft/releaselog/3_6_21.html)
239 con.execute('insert into foo(x) values ("%s")' % unicode_value)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200240 con.commit()
241 self.assertTrue(any(unicode_value in stmt for stmt in traced_statements),
Antoine Pitrou43b21682011-04-04 00:50:01 +0200242 "Unicode data %s garbled in trace callback: %s"
243 % (ascii(unicode_value), ', '.join(map(ascii, traced_statements))))
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200244
245
246
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247def suite():
248 collation_suite = unittest.makeSuite(CollationTests, "Check")
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000249 progress_suite = unittest.makeSuite(ProgressTests, "Check")
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200250 trace_suite = unittest.makeSuite(TraceCallbackTests, "Check")
251 return unittest.TestSuite((collation_suite, progress_suite, trace_suite))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000252
253def test():
254 runner = unittest.TextTestRunner()
255 runner.run(suite())
256
257if __name__ == "__main__":
258 test()