test_table.py 7.0 KB

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