test_table.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Jun 25 11:08:22 2014
  4. @author: pietro
  5. """
  6. import os
  7. import sqlite3
  8. import sys
  9. import tempfile as tmp
  10. from string import ascii_letters, digits
  11. from random import choice
  12. import numpy as np
  13. from grass.gunittest.case import TestCase
  14. from grass.gunittest.main import test
  15. from grass.pygrass.vector.table import Table, get_path
  16. if sys.version_info.major >= 3:
  17. long = int
  18. # dictionary that generate random data
  19. COL2VALS = {
  20. "INT": lambda n: np.random.randint(9, size=n),
  21. "INTEGER": lambda n: np.random.randint(9, size=n),
  22. "INTEGER PRIMARY KEY": lambda n: np.arange(1, n + 1, dtype=long),
  23. "REAL": lambda n: np.random.rand(n),
  24. "TEXT": lambda n: np.array([randstr() for _ in range(n)]),
  25. }
  26. def randstr(prefix="", suffix="", size=6, chars=ascii_letters + digits):
  27. """Return a random string of characters.
  28. :param prefix: string prefix, default: ''
  29. :type prefix: str
  30. :param suffix: string suffix, default: ''
  31. :type suffix: str
  32. :param size: number of random characters
  33. :type size: int
  34. :param chars: string containing the characters that will be used
  35. :type chars: str
  36. :returns: string
  37. """
  38. return prefix + "".join(choice(chars) for _ in range(size)) + suffix
  39. def get_table_random_values(nrows, columns):
  40. """Generate a random recarray respecting the columns definition.
  41. :param nrows: number of rows of the generated array
  42. :type nrows: int
  43. :param columns: list of tuple containing column name and type.
  44. :type columns: list of tuple
  45. :returns: numpy recarray
  46. """
  47. vals, dtype = [], []
  48. for cname, ctype in columns:
  49. if ctype not in COL2VALS:
  50. raise TypeError("Unknown column type %s for: %s" % (ctype, cname))
  51. vals.append(COL2VALS[ctype](nrows))
  52. dtype.append((cname, vals[-1].dtype.str))
  53. return np.array([v for v in zip(*vals)], dtype=dtype)
  54. class DBconnection(object):
  55. """Define a class to share common methods between TestCase."""
  56. path = os.path.join(tmp.gettempdir(), randstr(prefix="temp", suffix=".db"))
  57. connection = sqlite3.connect(get_path(path))
  58. for t in (
  59. np.int8,
  60. np.int16,
  61. np.int32,
  62. np.int64,
  63. np.uint8,
  64. np.uint16,
  65. np.uint32,
  66. np.uint64,
  67. ):
  68. sqlite3.register_adapter(t, int)
  69. columns = [
  70. ("cat", "INTEGER PRIMARY KEY"),
  71. ("cint", "INT"),
  72. ("creal", "REAL"),
  73. ("ctxt", "TEXT"),
  74. ]
  75. def create_table_instance(self, **kw):
  76. """Return a Table class instance
  77. :param **kw: keyword arguments of Table class
  78. without name and connection.
  79. :type **kw: key-word arguments
  80. :returns: Table instance
  81. """
  82. self.tname = randstr(prefix="temp")
  83. return Table(name=self.tname, connection=self.connection, **kw)
  84. def create_empty_table(self, columns=None, **kw):
  85. """Create an empty table in the database and return Table class
  86. instance.
  87. :param columns: list of tuple containing the column names and types.
  88. :type columns: list of tuple
  89. :param **kw: keyword arguments of Table class
  90. without name and connection.
  91. :type **kw: key-word arguments
  92. :returns: Table instance
  93. """
  94. columns = self.columns if columns is None else columns
  95. table = self.create_table_instance(**kw)
  96. table.create(columns)
  97. return table
  98. def create_not_empty_table(self, nrows=None, values=None, columns=None, **kw):
  99. """Create a not empty table in the database and return Table class
  100. instance.
  101. :param nrows: number of rows.
  102. :type nrows: list of tuple
  103. :param values: list of tuple containing the values for each row.
  104. :type values: list of tuple
  105. :param columns: list of tuple containing the column names and types.
  106. :type columns: list of tuple
  107. :param **kw: keyword arguments of Table class
  108. without name and connection.
  109. :type **kw: key-word arguments
  110. :returns: Table instance
  111. """
  112. if nrows is None and values is None:
  113. msg = "Both parameters ``nrows`` ``values`` are empty"
  114. raise RuntimeError(msg)
  115. columns = self.columns if columns is None else columns
  116. values = get_table_random_values(nrows, columns) if values is None else values
  117. table = self.create_empty_table(columns=columns, **kw)
  118. table.insert(values, many=True)
  119. return table
  120. def setUp(self):
  121. """Create a not empty table instance"""
  122. self.table = self.create_not_empty_table(10)
  123. self.cols = self.table.columns
  124. def tearDown(self):
  125. """Remove the generated vector map, if exist"""
  126. self.table.drop(force=True)
  127. self.table = None
  128. self.cols = None
  129. class ColumnsTestCase(DBconnection, TestCase):
  130. def test_check_insert_update_str(self):
  131. """Check insert_str and update_str attribute of Columns are correct"""
  132. insert = "INSERT INTO %s VALUES (?,?,?,?)"
  133. self.assertEqual(self.cols.insert_str, insert % self.tname)
  134. update = "UPDATE %s SET cint=?,creal=?,ctxt=? WHERE cat=?;"
  135. self.assertEqual(self.cols.update_str, update % self.tname)
  136. class TableInsertTestCase(DBconnection, TestCase):
  137. def setUp(self):
  138. """Create a not empty table instance"""
  139. self.table = self.create_empty_table()
  140. self.cols = self.table.columns
  141. def tearDown(self):
  142. """Remove the generated vector map, if exist"""
  143. self.table.drop(force=True)
  144. self.table = None
  145. self.cols = None
  146. def test_insert(self):
  147. """Test Table.insert method"""
  148. cat = 1
  149. vals = (cat, 1111, 0.1111, "test")
  150. cur = self.connection.cursor()
  151. self.table.insert(vals, cursor=cur)
  152. sqlquery = "SELECT cat, cint, creal, ctxt FROM %s WHERE cat=%d"
  153. cur.execute(sqlquery % (self.tname, cat))
  154. self.assertTupleEqual(vals, cur.fetchone())
  155. def test_insert_many(self):
  156. """Test Table.insert method using many==True"""
  157. vals = [
  158. (1, 1111, 0.1111, "test1"),
  159. (2, 2222, 0.2222, "test2"),
  160. (3, 3333, 0.3333, "test3"),
  161. ]
  162. cur = self.connection.cursor()
  163. self.table.insert(vals, cursor=cur, many=True)
  164. sqlquery = "SELECT cat, cint, creal, ctxt FROM %s"
  165. cur.execute(sqlquery % self.tname)
  166. self.assertListEqual(vals, cur.fetchall())
  167. class TableUpdateTestCase(DBconnection, TestCase):
  168. def test_update(self):
  169. """Test Table.update method"""
  170. vals = (1122, 0.1122, "test")
  171. cat = 1
  172. cur = self.connection.cursor()
  173. self.table.update(cat, list(vals), cursor=cur)
  174. self.connection.commit()
  175. sqlquery = "SELECT cint, creal, ctxt FROM %s WHERE cat=%d"
  176. cur.execute(sqlquery % (self.tname, cat))
  177. self.assertTupleEqual(vals, cur.fetchone())
  178. if __name__ == "__main__":
  179. test()