factory.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #-*- coding: iso-8859-1 -*-
  2. # pysqlite2/test/factory.py: tests for the various factories in pysqlite
  3. #
  4. # Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>
  5. #
  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. import unittest
  24. import sqlite3 as sqlite
  25. from collections.abc import Sequence
  26. class MyConnection(sqlite.Connection):
  27. def __init__(self, *args, **kwargs):
  28. sqlite.Connection.__init__(self, *args, **kwargs)
  29. def dict_factory(cursor, row):
  30. d = {}
  31. for idx, col in enumerate(cursor.description):
  32. d[col[0]] = row[idx]
  33. return d
  34. class MyCursor(sqlite.Cursor):
  35. def __init__(self, *args, **kwargs):
  36. sqlite.Cursor.__init__(self, *args, **kwargs)
  37. self.row_factory = dict_factory
  38. class ConnectionFactoryTests(unittest.TestCase):
  39. def setUp(self):
  40. self.con = sqlite.connect(":memory:", factory=MyConnection)
  41. def tearDown(self):
  42. self.con.close()
  43. def CheckIsInstance(self):
  44. self.assertIsInstance(self.con, MyConnection)
  45. class CursorFactoryTests(unittest.TestCase):
  46. def setUp(self):
  47. self.con = sqlite.connect(":memory:")
  48. def tearDown(self):
  49. self.con.close()
  50. def CheckIsInstance(self):
  51. cur = self.con.cursor()
  52. self.assertIsInstance(cur, sqlite.Cursor)
  53. cur = self.con.cursor(MyCursor)
  54. self.assertIsInstance(cur, MyCursor)
  55. cur = self.con.cursor(factory=lambda con: MyCursor(con))
  56. self.assertIsInstance(cur, MyCursor)
  57. def CheckInvalidFactory(self):
  58. # not a callable at all
  59. self.assertRaises(TypeError, self.con.cursor, None)
  60. # invalid callable with not exact one argument
  61. self.assertRaises(TypeError, self.con.cursor, lambda: None)
  62. # invalid callable returning non-cursor
  63. self.assertRaises(TypeError, self.con.cursor, lambda con: None)
  64. class RowFactoryTestsBackwardsCompat(unittest.TestCase):
  65. def setUp(self):
  66. self.con = sqlite.connect(":memory:")
  67. def CheckIsProducedByFactory(self):
  68. cur = self.con.cursor(factory=MyCursor)
  69. cur.execute("select 4+5 as foo")
  70. row = cur.fetchone()
  71. self.assertIsInstance(row, dict)
  72. cur.close()
  73. def tearDown(self):
  74. self.con.close()
  75. class RowFactoryTests(unittest.TestCase):
  76. def setUp(self):
  77. self.con = sqlite.connect(":memory:")
  78. def CheckCustomFactory(self):
  79. self.con.row_factory = lambda cur, row: list(row)
  80. row = self.con.execute("select 1, 2").fetchone()
  81. self.assertIsInstance(row, list)
  82. def CheckSqliteRowIndex(self):
  83. self.con.row_factory = sqlite.Row
  84. row = self.con.execute("select 1 as a_1, 2 as b").fetchone()
  85. self.assertIsInstance(row, sqlite.Row)
  86. self.assertEqual(row["a_1"], 1, "by name: wrong result for column 'a_1'")
  87. self.assertEqual(row["b"], 2, "by name: wrong result for column 'b'")
  88. self.assertEqual(row["A_1"], 1, "by name: wrong result for column 'A_1'")
  89. self.assertEqual(row["B"], 2, "by name: wrong result for column 'B'")
  90. self.assertEqual(row[0], 1, "by index: wrong result for column 0")
  91. self.assertEqual(row[1], 2, "by index: wrong result for column 1")
  92. self.assertEqual(row[-1], 2, "by index: wrong result for column -1")
  93. self.assertEqual(row[-2], 1, "by index: wrong result for column -2")
  94. with self.assertRaises(IndexError):
  95. row['c']
  96. with self.assertRaises(IndexError):
  97. row['a_\x11']
  98. with self.assertRaises(IndexError):
  99. row['a\x7f1']
  100. with self.assertRaises(IndexError):
  101. row[2]
  102. with self.assertRaises(IndexError):
  103. row[-3]
  104. with self.assertRaises(IndexError):
  105. row[2**1000]
  106. def CheckSqliteRowIndexUnicode(self):
  107. self.con.row_factory = sqlite.Row
  108. row = self.con.execute("select 1 as \xff").fetchone()
  109. self.assertEqual(row["\xff"], 1)
  110. with self.assertRaises(IndexError):
  111. row['\u0178']
  112. with self.assertRaises(IndexError):
  113. row['\xdf']
  114. def CheckSqliteRowSlice(self):
  115. # A sqlite.Row can be sliced like a list.
  116. self.con.row_factory = sqlite.Row
  117. row = self.con.execute("select 1, 2, 3, 4").fetchone()
  118. self.assertEqual(row[0:0], ())
  119. self.assertEqual(row[0:1], (1,))
  120. self.assertEqual(row[1:3], (2, 3))
  121. self.assertEqual(row[3:1], ())
  122. # Explicit bounds are optional.
  123. self.assertEqual(row[1:], (2, 3, 4))
  124. self.assertEqual(row[:3], (1, 2, 3))
  125. # Slices can use negative indices.
  126. self.assertEqual(row[-2:-1], (3,))
  127. self.assertEqual(row[-2:], (3, 4))
  128. # Slicing supports steps.
  129. self.assertEqual(row[0:4:2], (1, 3))
  130. self.assertEqual(row[3:0:-2], (4, 2))
  131. def CheckSqliteRowIter(self):
  132. """Checks if the row object is iterable"""
  133. self.con.row_factory = sqlite.Row
  134. row = self.con.execute("select 1 as a, 2 as b").fetchone()
  135. for col in row:
  136. pass
  137. def CheckSqliteRowAsTuple(self):
  138. """Checks if the row object can be converted to a tuple"""
  139. self.con.row_factory = sqlite.Row
  140. row = self.con.execute("select 1 as a, 2 as b").fetchone()
  141. t = tuple(row)
  142. self.assertEqual(t, (row['a'], row['b']))
  143. def CheckSqliteRowAsDict(self):
  144. """Checks if the row object can be correctly converted to a dictionary"""
  145. self.con.row_factory = sqlite.Row
  146. row = self.con.execute("select 1 as a, 2 as b").fetchone()
  147. d = dict(row)
  148. self.assertEqual(d["a"], row["a"])
  149. self.assertEqual(d["b"], row["b"])
  150. def CheckSqliteRowHashCmp(self):
  151. """Checks if the row object compares and hashes correctly"""
  152. self.con.row_factory = sqlite.Row
  153. row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
  154. row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
  155. row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
  156. row_4 = self.con.execute("select 1 as b, 2 as a").fetchone()
  157. row_5 = self.con.execute("select 2 as b, 1 as a").fetchone()
  158. self.assertTrue(row_1 == row_1)
  159. self.assertTrue(row_1 == row_2)
  160. self.assertFalse(row_1 == row_3)
  161. self.assertFalse(row_1 == row_4)
  162. self.assertFalse(row_1 == row_5)
  163. self.assertFalse(row_1 == object())
  164. self.assertFalse(row_1 != row_1)
  165. self.assertFalse(row_1 != row_2)
  166. self.assertTrue(row_1 != row_3)
  167. self.assertTrue(row_1 != row_4)
  168. self.assertTrue(row_1 != row_5)
  169. self.assertTrue(row_1 != object())
  170. with self.assertRaises(TypeError):
  171. row_1 > row_2
  172. with self.assertRaises(TypeError):
  173. row_1 < row_2
  174. with self.assertRaises(TypeError):
  175. row_1 >= row_2
  176. with self.assertRaises(TypeError):
  177. row_1 <= row_2
  178. self.assertEqual(hash(row_1), hash(row_2))
  179. def CheckSqliteRowAsSequence(self):
  180. """ Checks if the row object can act like a sequence """
  181. self.con.row_factory = sqlite.Row
  182. row = self.con.execute("select 1 as a, 2 as b").fetchone()
  183. as_tuple = tuple(row)
  184. self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))
  185. self.assertIsInstance(row, Sequence)
  186. def CheckFakeCursorClass(self):
  187. # Issue #24257: Incorrect use of PyObject_IsInstance() caused
  188. # segmentation fault.
  189. # Issue #27861: Also applies for cursor factory.
  190. class FakeCursor(str):
  191. __class__ = sqlite.Cursor
  192. self.con.row_factory = sqlite.Row
  193. self.assertRaises(TypeError, self.con.cursor, FakeCursor)
  194. self.assertRaises(TypeError, sqlite.Row, FakeCursor(), ())
  195. def tearDown(self):
  196. self.con.close()
  197. class TextFactoryTests(unittest.TestCase):
  198. def setUp(self):
  199. self.con = sqlite.connect(":memory:")
  200. def CheckUnicode(self):
  201. austria = "Österreich"
  202. row = self.con.execute("select ?", (austria,)).fetchone()
  203. self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
  204. def CheckString(self):
  205. self.con.text_factory = bytes
  206. austria = "Österreich"
  207. row = self.con.execute("select ?", (austria,)).fetchone()
  208. self.assertEqual(type(row[0]), bytes, "type of row[0] must be bytes")
  209. self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")
  210. def CheckCustom(self):
  211. self.con.text_factory = lambda x: str(x, "utf-8", "ignore")
  212. austria = "Österreich"
  213. row = self.con.execute("select ?", (austria,)).fetchone()
  214. self.assertEqual(type(row[0]), str, "type of row[0] must be unicode")
  215. self.assertTrue(row[0].endswith("reich"), "column must contain original data")
  216. def CheckOptimizedUnicode(self):
  217. # In py3k, str objects are always returned when text_factory
  218. # is OptimizedUnicode
  219. self.con.text_factory = sqlite.OptimizedUnicode
  220. austria = "Österreich"
  221. germany = "Deutchland"
  222. a_row = self.con.execute("select ?", (austria,)).fetchone()
  223. d_row = self.con.execute("select ?", (germany,)).fetchone()
  224. self.assertEqual(type(a_row[0]), str, "type of non-ASCII row must be str")
  225. self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str")
  226. def tearDown(self):
  227. self.con.close()
  228. class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
  229. def setUp(self):
  230. self.con = sqlite.connect(":memory:")
  231. self.con.execute("create table test (value text)")
  232. self.con.execute("insert into test (value) values (?)", ("a\x00b",))
  233. def CheckString(self):
  234. # text_factory defaults to str
  235. row = self.con.execute("select value from test").fetchone()
  236. self.assertIs(type(row[0]), str)
  237. self.assertEqual(row[0], "a\x00b")
  238. def CheckBytes(self):
  239. self.con.text_factory = bytes
  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. def CheckBytearray(self):
  244. self.con.text_factory = bytearray
  245. row = self.con.execute("select value from test").fetchone()
  246. self.assertIs(type(row[0]), bytearray)
  247. self.assertEqual(row[0], b"a\x00b")
  248. def CheckCustom(self):
  249. # A custom factory should receive a bytes argument
  250. self.con.text_factory = lambda x: x
  251. row = self.con.execute("select value from test").fetchone()
  252. self.assertIs(type(row[0]), bytes)
  253. self.assertEqual(row[0], b"a\x00b")
  254. def tearDown(self):
  255. self.con.close()
  256. def suite():
  257. connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
  258. cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
  259. row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
  260. row_suite = unittest.makeSuite(RowFactoryTests, "Check")
  261. text_suite = unittest.makeSuite(TextFactoryTests, "Check")
  262. text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
  263. return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite, text_zero_bytes_suite))
  264. def test():
  265. runner = unittest.TextTestRunner()
  266. runner.run(suite())
  267. if __name__ == "__main__":
  268. test()