db.test.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: db.test
  5. # AUTHOR(S): Radim Blazek
  6. # Converted to Python by Glynn Clements
  7. # PURPOSE: Test database driver
  8. # COPYRIGHT: (C) 2004-2014 by the GRASS Development Team
  9. #
  10. # This program is free software under the GNU General Public
  11. # License (version 2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. #
  14. #############################################################################
  15. #%module
  16. #% description: Test database driver, database must exist and set by db.connect.
  17. #% keyword: database
  18. #% keyword: attribute table
  19. #%end
  20. #%option
  21. #% key: test
  22. #% type: string
  23. #% description: Test name
  24. #% required: yes
  25. #% options: test1
  26. #%end
  27. import sys
  28. import os
  29. from grass.script import core as gcore
  30. from grass.script import db as grassdb
  31. from grass.exceptions import CalledModuleError
  32. # i18N
  33. import gettext
  34. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  35. def main():
  36. test_file = options['test']
  37. expected = gcore.tempfile()
  38. result = gcore.tempfile()
  39. dbconn = grassdb.db_connection()
  40. gcore.message(_("Using DB driver: %s") % dbconn['driver'])
  41. infile = os.path.join(os.environ['GISBASE'], 'etc', 'db.test', test_file)
  42. inf = file(infile)
  43. while True:
  44. type = inf.readline()
  45. if not type:
  46. break
  47. type = type.rstrip('\r\n')
  48. sql = inf.readline().rstrip('\r\n')
  49. sys.stdout.write(sql + '\n')
  50. # Copy expected result to temp file
  51. try:
  52. if type == 'X':
  53. gcore.write_command('db.execute', input='-', stdin=sql + '\n')
  54. else:
  55. resf = file(result, 'w')
  56. gcore.write_command('db.select', input='-', flags='c',
  57. stdin=sql + '\n', stdout=resf)
  58. resf.close()
  59. except CalledModuleError:
  60. gcore.error("EXECUTE: ******** ERROR ********")
  61. else:
  62. gcore.message(_("EXECUTE: OK"))
  63. expf = file(expected, 'w')
  64. while True:
  65. res = inf.readline().rstrip('\r\n')
  66. if not res:
  67. break
  68. expf.write(res + '\n')
  69. expf.close()
  70. if type == 'S':
  71. if gcore.call(['diff', result, expected]) != 0:
  72. gcore.error("RESULT: ******** ERROR ********")
  73. else:
  74. gcore.message(_("RESULT: OK"))
  75. if __name__ == "__main__":
  76. options, flags = gcore.parser()
  77. main()