test02_transliteration.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import logging
  2. from unittest import TestCase, TestSuite, TextTestRunner
  3. from csv import reader
  4. from glob import glob
  5. from os import environ, path
  6. from tests import TEST_DATA_DIR, reload_tables
  7. from scriptshifter.trans import transliterate
  8. import scriptshifter.tables
  9. logger = logging.getLogger(__name__)
  10. class TestTrans(TestCase):
  11. """
  12. Test S2R transliteration.
  13. Modified test case class to run independent tests for each CSV row.
  14. TODO use a comprehensive sample table and report errors for unsupported
  15. languages.
  16. """
  17. maxDiff = None
  18. def sample_s2r(self):
  19. """
  20. Test S2R transliteration for one CSV sample.
  21. This function name won't start with `test_` otherwise will be
  22. automatically run without parameters.
  23. """
  24. config = scriptshifter.tables.load_table(self.tbl)
  25. if "script_to_roman" in config:
  26. txl = transliterate(self.script, self.tbl, capitalize="first")[0]
  27. self.assertEqual(
  28. txl, self.roman,
  29. f"S2R transliteration error for {self.tbl}!\n"
  30. f"Original: {self.script}")
  31. def sample_r2s(self):
  32. """
  33. Test R2S transliteration for one CSV sample.
  34. This function name won't start with `test_` otherwise will be
  35. automatically run without parameters.
  36. """
  37. config = scriptshifter.tables.load_table(self.tbl)
  38. if "roman_to_script" in config:
  39. txl = transliterate(
  40. self.roman, self.tbl, r2s=True, capitalize="first")[0]
  41. self.assertEqual(
  42. txl, self.script,
  43. f"R2S transliteration error for {self.tbl}!\n"
  44. f"Original: {self.roman}")
  45. def make_suite():
  46. """
  47. Build parametrized test cases.
  48. """
  49. if "TXL_CONFIG_TABLE_DIR" in environ:
  50. del environ["TXL_CONFIG_TABLE_DIR"]
  51. reload_tables()
  52. suite = TestSuite()
  53. for fpath in glob(path.join(TEST_DATA_DIR, "script_samples", "*.csv")):
  54. with open(fpath, newline="") as fh:
  55. csv = reader(fh)
  56. # csv.__next__() # Discard header row.
  57. for row in csv:
  58. if len(row[0]):
  59. # Inject transliteration info in the test case.
  60. for tname in ("sample_s2r", "sample_r2s"):
  61. tcase = TestTrans(tname)
  62. tcase.tbl = row[0]
  63. tcase.script = row[1].strip()
  64. tcase.roman = row[2].strip()
  65. suite.addTest(tcase)
  66. return suite
  67. TextTestRunner().run(make_suite())