test02_transliteration.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import logging
  2. from unittest import TestCase, TestSuite, TextTestRunner
  3. from csv import reader
  4. from json import loads as jloads
  5. from os import environ, path, unlink
  6. from scriptshifter.trans import transliterate
  7. from scriptshifter.tables import get_language, init_db
  8. from test import TEST_DATA_DIR
  9. logger = logging.getLogger(__name__)
  10. def setUpModule():
  11. init_db()
  12. def tearDownModule():
  13. unlink(environ["TXL_DB_PATH"])
  14. class TestTrans(TestCase):
  15. """
  16. Test S2R transliteration.
  17. Modified test case class to run independent tests for each CSV row.
  18. TODO use a comprehensive sample table and report errors for unsupported
  19. languages.
  20. """
  21. def sample(self):
  22. """
  23. Test transliteration for one CSV row.
  24. This function name won't start with `test_` otherwise will be
  25. automatically run without parameters.
  26. """
  27. config = get_language(self.tbl)
  28. t_dir = self.options.get("t_dir", "s2r")
  29. if (
  30. t_dir == "s2r" and config["has_s2r"]
  31. or t_dir == "r2s" and config["has_r2s"]):
  32. txl = transliterate(
  33. self.script, self.tbl,
  34. t_dir=t_dir,
  35. capitalize=self.options.get("capitalize", False),
  36. options=self.options)[0]
  37. self.assertEqual(
  38. txl, self.roman,
  39. f"S2R transliteration error for {self.tbl}!\n"
  40. f"Original: {self.script}")
  41. def make_suite():
  42. """
  43. Build parametrized test cases.
  44. """
  45. suite = TestSuite()
  46. with open(path.join(
  47. TEST_DATA_DIR, "script_samples", "unittest.csv"
  48. ), newline="") as fh:
  49. csv = reader(fh)
  50. for row in csv:
  51. if len(row[0]):
  52. # Inject transliteration info in the test case.
  53. tcase = TestTrans("sample")
  54. tcase.tbl = row[0]
  55. tcase.script = row[1].strip()
  56. tcase.roman = row[2].strip()
  57. tcase.options = jloads(row[3]) if len(row[3]) else {}
  58. suite.addTest(tcase)
  59. return suite
  60. TextTestRunner().run(make_suite())