test02_transliteration.py 2.8 KB

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