test_table.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Jun 25 11:08:22 2014
  4. @author: pietro
  5. """
  6. try:
  7. from builtins import long
  8. except ImportError:
  9. # python3
  10. long = int
  11. import os
  12. import sqlite3
  13. import tempfile as tmp
  14. from string import ascii_letters, digits
  15. from random import choice
  16. import numpy as np
  17. from grass.gunittest.case import TestCase
  18. from grass.gunittest.main import test
  19. from grass.pygrass.vector.table import Table, get_path
  20. # dictionary that generate random data
  21. COL2VALS = {'INT': lambda n: np.random.randint(9, size=n),
  22. 'INTEGER': lambda n: np.random.randint(9, size=n),
  23. 'INTEGER PRIMARY KEY': lambda n: np.arange(1, n+1, dtype=long),
  24. 'REAL': lambda n: np.random.rand(n),
  25. 'TEXT': lambda n: np.array([randstr() for _ in range(n)])}
  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("Unkown 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. columns = [('cat', 'INTEGER PRIMARY KEY'),
  59. ('cint', 'INT'),
  60. ('creal', 'REAL'),
  61. ('ctxt', 'TEXT')]
  62. def create_table_instance(self, **kw):
  63. """Return a Table class instance
  64. :param **kw: keyword arguments of Table class
  65. without name and connection.
  66. :type **kw: key-word arguments
  67. :returns: Table instance
  68. """
  69. self.tname = randstr(prefix='temp')
  70. return Table(name=self.tname,
  71. connection=self.connection, **kw)
  72. def create_empty_table(self, columns=None, **kw):
  73. """Create an empty table in the database and return Table class
  74. instance.
  75. :param columns: list of tuple containing the column names and types.
  76. :type columns: list of tuple
  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. columns = self.columns if columns is None else columns
  83. table = self.create_table_instance(**kw)
  84. table.create(columns)
  85. return table
  86. def create_not_empty_table(self, nrows=None, values=None,
  87. columns=None, **kw):
  88. """Create a not empty table in the database and return Table class
  89. instance.
  90. :param nrows: number of rows.
  91. :type nrows: list of tuple
  92. :param values: list of tuple containing the values for each row.
  93. :type values: list of tuple
  94. :param columns: list of tuple containing the column names and types.
  95. :type columns: list of tuple
  96. :param **kw: keyword arguments of Table class
  97. without name and connection.
  98. :type **kw: key-word arguments
  99. :returns: Table instance
  100. """
  101. if nrows is None and values is None:
  102. msg = "Both parameters ``nrows`` ``values`` are empty"
  103. raise RuntimeError(msg)
  104. columns = self.columns if columns is None else columns
  105. values = (get_table_random_values(nrows, columns) if values is None
  106. else values)
  107. table = self.create_empty_table(columns=columns, **kw)
  108. table.insert(values, many=True)
  109. return table
  110. def setUp(self):
  111. """Create a not empty table instance"""
  112. self.table = self.create_not_empty_table(10)
  113. self.cols = self.table.columns
  114. def tearDown(self):
  115. """Remove the generated vector map, if exist"""
  116. self.table.drop(force=True)
  117. self.table = None
  118. self.cols = None
  119. class ColumnsTestCase(DBconnection, TestCase):
  120. def test_check_insert_update_str(self):
  121. """Check insert_str and update_str attribute of Columns are correct"""
  122. insert = 'INSERT INTO %s VALUES (?,?,?,?)'
  123. self.assertEqual(self.cols.insert_str, insert % self.tname)
  124. update = 'UPDATE %s SET cint=?,creal=?,ctxt=? WHERE cat=?;'
  125. self.assertEqual(self.cols.update_str, update % self.tname)
  126. class TableInsertTestCase(DBconnection, TestCase):
  127. def setUp(self):
  128. """Create a not empty table instance"""
  129. self.table = self.create_empty_table()
  130. self.cols = self.table.columns
  131. def tearDown(self):
  132. """Remove the generated vector map, if exist"""
  133. self.table.drop(force=True)
  134. self.table = None
  135. self.cols = None
  136. def test_insert(self):
  137. """Test Table.insert method"""
  138. cat = 1
  139. vals = (cat, 1111, 0.1111, 'test')
  140. cur = self.connection.cursor()
  141. self.table.insert(vals, cursor=cur)
  142. sqlquery = "SELECT cat, cint, creal, ctxt FROM %s WHERE cat=%d"
  143. cur.execute(sqlquery % (self.tname, cat))
  144. self.assertTupleEqual(vals, cur.fetchone())
  145. def test_insert_many(self):
  146. """Test Table.insert method using many==True"""
  147. vals = [(1, 1111, 0.1111, 'test1'),
  148. (2, 2222, 0.2222, 'test2'),
  149. (3, 3333, 0.3333, 'test3')]
  150. cur = self.connection.cursor()
  151. self.table.insert(vals, cursor=cur, many=True)
  152. sqlquery = "SELECT cat, cint, creal, ctxt FROM %s"
  153. cur.execute(sqlquery % self.tname)
  154. self.assertListEqual(vals, cur.fetchall())
  155. class TableUpdateTestCase(DBconnection, TestCase):
  156. def test_update(self):
  157. """Test Table.update method"""
  158. vals = (1122, 0.1122, 'test')
  159. cat = 1
  160. cur = self.connection.cursor()
  161. self.table.update(cat, list(vals), cursor=cur)
  162. self.connection.commit()
  163. sqlquery = "SELECT cint, creal, ctxt FROM %s WHERE cat=%d"
  164. cur.execute(sqlquery % (self.tname, cat))
  165. self.assertTupleEqual(vals, cur.fetchone())
  166. if __name__ == '__main__':
  167. test()