PageRenderTime 78ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/sqlite3/test/types.py

https://bitbucket.org/rokujyouhitoma/pypy/
Python | 418 lines | 338 code | 42 blank | 38 comment | 19 complexity | 5224d49f2756690d7ebe718d16f392e1 MD5 | raw file
  1. #-*- coding: ISO-8859-1 -*-
  2. # pysqlite2/test/types.py: tests for type conversion and detection
  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 datetime
  24. import unittest
  25. import sqlite3 as sqlite
  26. try:
  27. import zlib
  28. except ImportError:
  29. zlib = None
  30. class SqliteTypeTests(unittest.TestCase):
  31. def setUp(self):
  32. self.con = sqlite.connect(":memory:")
  33. self.cur = self.con.cursor()
  34. self.cur.execute("create table test(i integer, s varchar, f number, b blob)")
  35. def tearDown(self):
  36. self.cur.close()
  37. self.con.close()
  38. def CheckString(self):
  39. self.cur.execute("insert into test(s) values (?)", (u"Österreich",))
  40. self.cur.execute("select s from test")
  41. row = self.cur.fetchone()
  42. self.assertEqual(row[0], u"Österreich")
  43. def CheckSmallInt(self):
  44. self.cur.execute("insert into test(i) values (?)", (42,))
  45. self.cur.execute("select i from test")
  46. row = self.cur.fetchone()
  47. self.assertEqual(row[0], 42)
  48. def CheckLargeInt(self):
  49. num = 2**40
  50. self.cur.execute("insert into test(i) values (?)", (num,))
  51. self.cur.execute("select i from test")
  52. row = self.cur.fetchone()
  53. self.assertEqual(row[0], num)
  54. def CheckFloat(self):
  55. val = 3.14
  56. self.cur.execute("insert into test(f) values (?)", (val,))
  57. self.cur.execute("select f from test")
  58. row = self.cur.fetchone()
  59. self.assertEqual(row[0], val)
  60. def CheckBlob(self):
  61. val = buffer("Guglhupf")
  62. self.cur.execute("insert into test(b) values (?)", (val,))
  63. self.cur.execute("select b from test")
  64. row = self.cur.fetchone()
  65. self.assertEqual(row[0], val)
  66. def CheckUnicodeExecute(self):
  67. self.cur.execute(u"select 'Österreich'")
  68. row = self.cur.fetchone()
  69. self.assertEqual(row[0], u"Österreich")
  70. def CheckNonUtf8_Default(self):
  71. try:
  72. self.cur.execute("select ?", (chr(150),))
  73. self.fail("should have raised a ProgrammingError")
  74. except sqlite.ProgrammingError:
  75. pass
  76. def CheckNonUtf8_TextFactoryString(self):
  77. orig_text_factory = self.con.text_factory
  78. try:
  79. self.con.text_factory = str
  80. self.cur.execute("select ?", (chr(150),))
  81. finally:
  82. self.con.text_factory = orig_text_factory
  83. def CheckNonUtf8_TextFactoryOptimizedUnicode(self):
  84. orig_text_factory = self.con.text_factory
  85. try:
  86. try:
  87. self.con.text_factory = sqlite.OptimizedUnicode
  88. self.cur.execute("select ?", (chr(150),))
  89. self.fail("should have raised a ProgrammingError")
  90. except sqlite.ProgrammingError:
  91. pass
  92. finally:
  93. self.con.text_factory = orig_text_factory
  94. class DeclTypesTests(unittest.TestCase):
  95. class Foo:
  96. def __init__(self, _val):
  97. self.val = _val
  98. def __cmp__(self, other):
  99. if not isinstance(other, DeclTypesTests.Foo):
  100. raise ValueError
  101. if self.val == other.val:
  102. return 0
  103. else:
  104. return 1
  105. def __conform__(self, protocol):
  106. if protocol is sqlite.PrepareProtocol:
  107. return self.val
  108. else:
  109. return None
  110. def __str__(self):
  111. return "<%s>" % self.val
  112. def setUp(self):
  113. self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
  114. self.cur = self.con.cursor()
  115. self.cur.execute("create table test(i int, s str, f float, b bool, u unicode, foo foo, bin blob, n1 number, n2 number(5))")
  116. # override float, make them always return the same number
  117. sqlite.converters["FLOAT"] = lambda x: 47.2
  118. # and implement two custom ones
  119. sqlite.converters["BOOL"] = lambda x: bool(int(x))
  120. sqlite.converters["FOO"] = DeclTypesTests.Foo
  121. sqlite.converters["WRONG"] = lambda x: "WRONG"
  122. sqlite.converters["NUMBER"] = float
  123. def tearDown(self):
  124. del sqlite.converters["FLOAT"]
  125. del sqlite.converters["BOOL"]
  126. del sqlite.converters["FOO"]
  127. del sqlite.converters["NUMBER"]
  128. self.cur.close()
  129. self.con.close()
  130. def CheckString(self):
  131. # default
  132. self.cur.execute("insert into test(s) values (?)", ("foo",))
  133. self.cur.execute('select s as "s [WRONG]" from test')
  134. row = self.cur.fetchone()
  135. self.assertEqual(row[0], "foo")
  136. def CheckSmallInt(self):
  137. # default
  138. self.cur.execute("insert into test(i) values (?)", (42,))
  139. self.cur.execute("select i from test")
  140. row = self.cur.fetchone()
  141. self.assertEqual(row[0], 42)
  142. def CheckLargeInt(self):
  143. # default
  144. num = 2**40
  145. self.cur.execute("insert into test(i) values (?)", (num,))
  146. self.cur.execute("select i from test")
  147. row = self.cur.fetchone()
  148. self.assertEqual(row[0], num)
  149. def CheckFloat(self):
  150. # custom
  151. val = 3.14
  152. self.cur.execute("insert into test(f) values (?)", (val,))
  153. self.cur.execute("select f from test")
  154. row = self.cur.fetchone()
  155. self.assertEqual(row[0], 47.2)
  156. def CheckBool(self):
  157. # custom
  158. self.cur.execute("insert into test(b) values (?)", (False,))
  159. self.cur.execute("select b from test")
  160. row = self.cur.fetchone()
  161. self.assertEqual(row[0], False)
  162. self.cur.execute("delete from test")
  163. self.cur.execute("insert into test(b) values (?)", (True,))
  164. self.cur.execute("select b from test")
  165. row = self.cur.fetchone()
  166. self.assertEqual(row[0], True)
  167. def CheckUnicode(self):
  168. # default
  169. val = u"\xd6sterreich"
  170. self.cur.execute("insert into test(u) values (?)", (val,))
  171. self.cur.execute("select u from test")
  172. row = self.cur.fetchone()
  173. self.assertEqual(row[0], val)
  174. def CheckFoo(self):
  175. val = DeclTypesTests.Foo("bla")
  176. self.cur.execute("insert into test(foo) values (?)", (val,))
  177. self.cur.execute("select foo from test")
  178. row = self.cur.fetchone()
  179. self.assertEqual(row[0], val)
  180. def CheckUnsupportedSeq(self):
  181. class Bar: pass
  182. val = Bar()
  183. try:
  184. self.cur.execute("insert into test(f) values (?)", (val,))
  185. self.fail("should have raised an InterfaceError")
  186. except sqlite.InterfaceError:
  187. pass
  188. except:
  189. self.fail("should have raised an InterfaceError")
  190. def CheckUnsupportedDict(self):
  191. class Bar: pass
  192. val = Bar()
  193. try:
  194. self.cur.execute("insert into test(f) values (:val)", {"val": val})
  195. self.fail("should have raised an InterfaceError")
  196. except sqlite.InterfaceError:
  197. pass
  198. except:
  199. self.fail("should have raised an InterfaceError")
  200. def CheckBlob(self):
  201. # default
  202. val = buffer("Guglhupf")
  203. self.cur.execute("insert into test(bin) values (?)", (val,))
  204. self.cur.execute("select bin from test")
  205. row = self.cur.fetchone()
  206. self.assertEqual(row[0], val)
  207. def CheckNumber1(self):
  208. self.cur.execute("insert into test(n1) values (5)")
  209. value = self.cur.execute("select n1 from test").fetchone()[0]
  210. # if the converter is not used, it's an int instead of a float
  211. self.assertEqual(type(value), float)
  212. def CheckNumber2(self):
  213. """Checks wether converter names are cut off at '(' characters"""
  214. self.cur.execute("insert into test(n2) values (5)")
  215. value = self.cur.execute("select n2 from test").fetchone()[0]
  216. # if the converter is not used, it's an int instead of a float
  217. self.assertEqual(type(value), float)
  218. class ColNamesTests(unittest.TestCase):
  219. def setUp(self):
  220. self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
  221. self.cur = self.con.cursor()
  222. self.cur.execute("create table test(x foo)")
  223. sqlite.converters["FOO"] = lambda x: "[%s]" % x
  224. sqlite.converters["BAR"] = lambda x: "<%s>" % x
  225. sqlite.converters["EXC"] = lambda x: 5 // 0
  226. sqlite.converters["B1B1"] = lambda x: "MARKER"
  227. def tearDown(self):
  228. del sqlite.converters["FOO"]
  229. del sqlite.converters["BAR"]
  230. del sqlite.converters["EXC"]
  231. del sqlite.converters["B1B1"]
  232. self.cur.close()
  233. self.con.close()
  234. def CheckDeclTypeNotUsed(self):
  235. """
  236. Assures that the declared type is not used when PARSE_DECLTYPES
  237. is not set.
  238. """
  239. self.cur.execute("insert into test(x) values (?)", ("xxx",))
  240. self.cur.execute("select x from test")
  241. val = self.cur.fetchone()[0]
  242. self.assertEqual(val, "xxx")
  243. def CheckNone(self):
  244. self.cur.execute("insert into test(x) values (?)", (None,))
  245. self.cur.execute("select x from test")
  246. val = self.cur.fetchone()[0]
  247. self.assertEqual(val, None)
  248. def CheckColName(self):
  249. self.cur.execute("insert into test(x) values (?)", ("xxx",))
  250. self.cur.execute('select x as "x [bar]" from test')
  251. val = self.cur.fetchone()[0]
  252. self.assertEqual(val, "<xxx>")
  253. # Check if the stripping of colnames works. Everything after the first
  254. # whitespace should be stripped.
  255. self.assertEqual(self.cur.description[0][0], "x")
  256. def CheckCaseInConverterName(self):
  257. self.cur.execute("""select 'other' as "x [b1b1]\"""")
  258. val = self.cur.fetchone()[0]
  259. self.assertEqual(val, "MARKER")
  260. def CheckCursorDescriptionNoRow(self):
  261. """
  262. cursor.description should at least provide the column name(s), even if
  263. no row returned.
  264. """
  265. self.cur.execute("select * from test where 0 = 1")
  266. self.assertEqual(self.cur.description[0][0], "x")
  267. class ObjectAdaptationTests(unittest.TestCase):
  268. def cast(obj):
  269. return float(obj)
  270. cast = staticmethod(cast)
  271. def setUp(self):
  272. self.con = sqlite.connect(":memory:")
  273. try:
  274. del sqlite.adapters[int]
  275. except:
  276. pass
  277. sqlite.register_adapter(int, ObjectAdaptationTests.cast)
  278. self.cur = self.con.cursor()
  279. def tearDown(self):
  280. del sqlite.adapters[(int, sqlite.PrepareProtocol)]
  281. self.cur.close()
  282. self.con.close()
  283. def CheckCasterIsUsed(self):
  284. self.cur.execute("select ?", (4,))
  285. val = self.cur.fetchone()[0]
  286. self.assertEqual(type(val), float)
  287. @unittest.skipUnless(zlib, "requires zlib")
  288. class BinaryConverterTests(unittest.TestCase):
  289. def convert(s):
  290. return zlib.decompress(s)
  291. convert = staticmethod(convert)
  292. def setUp(self):
  293. self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
  294. sqlite.register_converter("bin", BinaryConverterTests.convert)
  295. def tearDown(self):
  296. self.con.close()
  297. def CheckBinaryInputForConverter(self):
  298. testdata = "abcdefg" * 10
  299. result = self.con.execute('select ? as "x [bin]"', (buffer(zlib.compress(testdata)),)).fetchone()[0]
  300. self.assertEqual(testdata, result)
  301. class DateTimeTests(unittest.TestCase):
  302. def setUp(self):
  303. self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
  304. self.cur = self.con.cursor()
  305. self.cur.execute("create table test(d date, ts timestamp)")
  306. def tearDown(self):
  307. self.cur.close()
  308. self.con.close()
  309. def CheckSqliteDate(self):
  310. d = sqlite.Date(2004, 2, 14)
  311. self.cur.execute("insert into test(d) values (?)", (d,))
  312. self.cur.execute("select d from test")
  313. d2 = self.cur.fetchone()[0]
  314. self.assertEqual(d, d2)
  315. def CheckSqliteTimestamp(self):
  316. ts = sqlite.Timestamp(2004, 2, 14, 7, 15, 0)
  317. self.cur.execute("insert into test(ts) values (?)", (ts,))
  318. self.cur.execute("select ts from test")
  319. ts2 = self.cur.fetchone()[0]
  320. self.assertEqual(ts, ts2)
  321. def CheckSqlTimestamp(self):
  322. # The date functions are only available in SQLite version 3.1 or later
  323. if sqlite.sqlite_version_info < (3, 1):
  324. return
  325. # SQLite's current_timestamp uses UTC time, while datetime.datetime.now() uses local time.
  326. now = datetime.datetime.now()
  327. self.cur.execute("insert into test(ts) values (current_timestamp)")
  328. self.cur.execute("select ts from test")
  329. ts = self.cur.fetchone()[0]
  330. self.assertEqual(type(ts), datetime.datetime)
  331. self.assertEqual(ts.year, now.year)
  332. def CheckDateTimeSubSeconds(self):
  333. ts = sqlite.Timestamp(2004, 2, 14, 7, 15, 0, 500000)
  334. self.cur.execute("insert into test(ts) values (?)", (ts,))
  335. self.cur.execute("select ts from test")
  336. ts2 = self.cur.fetchone()[0]
  337. self.assertEqual(ts, ts2)
  338. def CheckDateTimeSubSecondsFloatingPoint(self):
  339. ts = sqlite.Timestamp(2004, 2, 14, 7, 15, 0, 510241)
  340. self.cur.execute("insert into test(ts) values (?)", (ts,))
  341. self.cur.execute("select ts from test")
  342. ts2 = self.cur.fetchone()[0]
  343. self.assertEqual(ts, ts2)
  344. def suite():
  345. sqlite_type_suite = unittest.makeSuite(SqliteTypeTests, "Check")
  346. decltypes_type_suite = unittest.makeSuite(DeclTypesTests, "Check")
  347. colnames_type_suite = unittest.makeSuite(ColNamesTests, "Check")
  348. adaptation_suite = unittest.makeSuite(ObjectAdaptationTests, "Check")
  349. bin_suite = unittest.makeSuite(BinaryConverterTests, "Check")
  350. date_suite = unittest.makeSuite(DateTimeTests, "Check")
  351. return unittest.TestSuite((sqlite_type_suite, decltypes_type_suite, colnames_type_suite, adaptation_suite, bin_suite, date_suite))
  352. def test():
  353. runner = unittest.TextTestRunner()
  354. runner.run(suite())
  355. if __name__ == "__main__":
  356. test()