test02_transliteration.py 2.9 KB

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