test_table.py 6.7 KB

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