The workshop / tests/test_kelwa.py
test_kelwa.py
Last changed by Hiro, 28 h ago. “Checker reads country names: Nipon-yon, Faransi-kelwa-te (dc_f925). A name may be glossed by its English name. Grammar test no longer reads an English line as Kelwa.”
What this change did
⋯ self.assertEqual(rows[6]["gloss"], "Enya-OF") + def test_name_with_yon_and_kelwa(self):+ # dc_f925345a4b37: person = name + yon, language = name + kelwa+ rows = gloss.gloss_sentence(LANG, "Na Faransi-kelwa-te kel dol. Kal Nipon-yonmi lenpa.", set())+ self.assertEqual(rows[1]["gloss"], "Faransi-language-OBJ")+ self.assertEqual(rows[1]["status"], "name")+ self.assertEqual(rows[5]["gloss"], "Nipon-person-PL")+ # any other word after the hyphen is still refused+ self.assertEqual(gloss.analyse_token(LANG, "Nipon-wal", False, set())["status"], "unknown")+ def test_unknown_first_word_is_not_a_name(self): rows = gloss.gloss_sentence(LANG, "Zorka ro. Napo nen Zorka ro.", set())⋯ with open(os.path.join(ROOT, "grammar", "GRAMMAR.md"), encoding="utf-8") as f: lines = f.read().split("\n")- pairs = []- for a, b in zip(lines, lines[1:]):+ pairs, gloss_lines = [], set()+ for i, (a, b) in enumerate(zip(lines, lines[1:])): if not (a.startswith(" ") and b.startswith(" ") and a.strip() and b.strip()): continue- if not re.search(r"[A-Z]{2}|\bI\b|\bnot\b|\bcome\b", b) or re.search(r"[.!?]$", b.strip()):+ if i in gloss_lines:+ continue # a gloss line is never the Kelwa line of the next pair+ # an English line may end with a comment in brackets: "We will go. (exclusive)"+ end = re.sub(r"\s{2,}\(.*\)$", "", b.strip())+ if not re.search(r"[A-Z]{2}|\bI\b|\bnot\b|\bcome\b", b) or re.search(r"[.!?]$", end): continue+ gloss_lines.add(i + 1) ka, gl = a.split(), b.split() if len(ka) != len(gl):⋯ wrong = [] for word, gl in grammar_examples():- w = word.strip(gloss.PUNCT).replace("-", "").lower() said = [p for p in gl.split("-") if p in labels]+ core = word.strip(gloss.PUNCT)+ if core[:1].isupper() and not LANG.analyses(core.replace("-", "").lower()):+ # a foreign name, maybe with -yon / -kelwa, then suffixes (dc_f925345a4b37)+ row = gloss.analyse_token(LANG, core, False, set())+ if row["status"] != "name" or row.get("labels", []) != said:+ wrong.append("%s (%s): program reads %s" % (word, gl, row["gloss"]))+ continue+ w = core.replace("-", "").lower() readings = [[s.label for s in a["suffixes"] if s.label in labels] for a in LANG.analyses(w)] if said not in readings:⋯
The whole file
"""Tests of the Kelwa tools. Run from the project folder:
python -m unittest discover -s tests
The examples of grammar/PHONOLOGY.md and grammar/GRAMMAR.md are test cases:
when one fails, the program or the reference is wrong, and the chat says which.
"""
import io
import os
import re
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import check_dict # noqa: E402
import check_examples # noqa: E402
import check_texts # noqa: E402
import gloss # noqa: E402
import ipa # noqa: E402
import kelwa # noqa: E402
import lookup # noqa: E402
import phon # noqa: E402
import syllables # noqa: E402
LANG = kelwa.Language()
HEAD = "word\tpos\tmeaning\tparts\tfield\tby\n"
def dict_file(body):
f = tempfile.NamedTemporaryFile("w", suffix=".tsv", delete=False, encoding="utf-8", newline="")
f.write(HEAD + body)
f.close()
return f.name
class Sounds(unittest.TestCase):
def test_reference_syllables(self):
for s in "ka kan kel tor hus".split():
self.assertEqual(phon.check_word(s), [], s)
for s in "ak kra kap kai".split():
self.assertTrue(phon.check_word(s), s)
def test_reference_regex_agrees(self):
rx = re.compile(r"^([pbtdkgmnfsxhlrwy][aeiou][nlrs]?)+$")
words = list(LANG.entries) + "kellun wuna yila anna kelwas strok kemp qa va kaa".split()
for w in words:
by_rule = bool(rx.match(w)) and not any(x in w for x in ("nn", "ll", "rr", "ss", "wu", "yi"))
self.assertEqual(phon.is_valid(w), by_rule, w)
def test_refusals_say_why(self):
self.assertIn("double consonant 'll'", phon.check_word("kellun"))
self.assertIn("forbidden sequence 'wu'", phon.check_word("wuna"))
self.assertIn("forbidden sequence 'yi'", phon.check_word("payi"))
self.assertTrue(any("vowel" in e for e in phon.check_word("ata")))
self.assertTrue(any("alphabet" in e for e in phon.check_word("vaza")))
self.assertTrue(any("capital" in e for e in phon.check_word("Kel")))
def test_stress_examples(self):
for word, syl in [("kelwa", "KEL-wa"), ("wangi", "WAN-gi"), ("sulo", "SU-lo"), ("kinhus", "KIN-hus"),
("xenkegi", "XEN-ke-gi"), ("torwade", "TOR-wa-de"), ("wangimite", "WAN-gi-mi-te")]:
self.assertEqual(phon.stress(word), syl)
def test_no_suffix_can_break_a_root(self):
# GRAMMAR 10: a suffix can be added to any root without breaking the sound rules
for a in LANG.affixes.values():
self.assertNotIn(a.suffix[0], "nlrs", a.suffix)
for root in ("kel", "wan", "tor", "hus", "ga"):
self.assertTrue(phon.is_valid(root + a.suffix), root + a.suffix)
class Dictionary(unittest.TestCase):
def problems(self, body):
path = dict_file(body)
try:
return check_dict.check(path)
finally:
os.unlink(path)
def test_clean(self):
n, valid, p = self.problems("kel\tv\tspeak\t-\tspeech\tenya\nkelto\tn\tword\tkel+to\tspeech\tenya\n")
self.assertEqual((n, valid, p), (2, 2, []))
def test_each_refusal(self):
cases = [
("kap\tn\tx\t-\tcore\tenya\n", "sound rule"),
("kel\tv\tspeak\t-\tspeech\tenya\nkel\tn\tspeech\t-\tspeech\tenya\n", "duplicate"),
("kel\tv\tspeak\t-\tspeech\n", "fields"),
("kel\tv\t\t-\tspeech\tenya\n", "missing field 'meaning'"),
("kel\tverb\tspeak\t-\tspeech\tenya\n", "pos"),
("kelto\tn\tword\tkel+to\tspeech\tenya\n", "neither a word"),
("kel\tv\tspeak\t-\tspeech\tenya\nkelta\tn\tword\tkel+to\tspeech\tenya\n", "spell"),
("kel\tv\tspeak\t-\tspeech\tenya\nkelwa\tn\tlanguage\t-\tspeech\tenya\n", "root reads as kel + -wa"),
("te\tn\ttea\t-\tfood\tenya\n", "identical to the suffix"),
("kon\tn\tstone\t-\tnature\tenya\ngon\tn\tearth\t-\tnature\tenya\n", "too close"),
]
for body, expected in cases:
n, valid, p = self.problems(body)
self.assertTrue(any(expected in m for _, _, m in p), (expected, p))
self.assertLess(valid, n, expected)
def test_not_too_close(self):
self.assertIsNone(check_dict.too_close("nor", "nos"))
self.assertEqual(check_dict.too_close("sen", "xen"), "s/x")
n, valid, p = self.problems("mu\tpart\tnot\t-\tgrammar\tenya\nkon\tn\tstone\t-\tnature\tenya\ngon\tv\tdig\t-\tnature\tenya\n")
self.assertEqual(p, []) # mu is allowed; different word classes are not a pair
def test_linking_a(self):
self.assertEqual(kelwa.join_parts(["kel", "lun"]), "kelalun")
self.assertEqual(kelwa.join_parts(["kin", "hus"]), "kinhus")
self.assertEqual(kelwa.join_parts(["xen", "ke", "gi"]), "xenkegi")
def test_last_line(self):
out = io.StringIO()
old = sys.stdout
sys.stdout = out
try:
check_dict.main([])
finally:
sys.stdout = old
self.assertRegex(out.getvalue().strip().split("\n")[-1], r"^\d+ words, \d+ valid$")
class Forms(unittest.TestCase):
def test_noun(self):
f = LANG.noun_forms("mal")
self.assertEqual(len(f), 16) # 2 numbers x (bare + 7 roles)
self.assertEqual(f[("SG", "BARE")], "mal")
self.assertEqual(f[("SG", "OBJ")], "malte")
self.assertEqual(f[("SG", "OF")], "malpo")
self.assertEqual(f[("PL", "BARE")], "malmi")
self.assertEqual(LANG.noun_forms("yonpi")[("PL", "TO")], "yonpimika")
self.assertEqual(LANG.noun_forms("kas")[("SG", "AT")], "kasxi")
self.assertEqual(LANG.noun_forms("gir")[("SG", "WITH")], "girde")
self.assertEqual(LANG.noun_forms("hus")[("SG", "FOR")], "huswe")
self.assertEqual(LANG.noun_forms("mir")[("SG", "FROM")], "mirfu")
def test_pronouns_are_regular(self):
self.assertEqual(LANG.noun_forms("na")[("SG", "OF")], "napo")
self.assertEqual(LANG.noun_forms("se")[("SG", "OBJ")], "sete")
self.assertEqual(LANG.noun_forms("lo")[("PL", "TO")], "lomika")
self.assertEqual(LANG.noun_forms("sun")[("SG", "TO")], "sunka")
self.assertEqual([LANG.noun_forms("hu")[("SG", r)] for r in ("OBJ", "OF", "FOR", "AT", "TO", "FROM", "WITH")],
"hute hupo huwe huxi huka hufu hude".split())
def test_verb(self):
f = LANG.verb_forms("sir")
self.assertEqual(len(f), 16) # 4 aspects x (present, past, future, lets)
self.assertEqual(f[("PLAIN", "PRESENT")], "sir")
self.assertEqual(f[("DONE", "PAST")], "sirkupa")
self.assertEqual(LANG.verb_forms("nor")[("ONGOING", "PRESENT")], "norma")
self.assertEqual(LANG.verb_forms("lis")[("HABIT", "PRESENT")], "lisho")
self.assertEqual(LANG.verb_forms("len")[("PLAIN", "FUT")], "lenti")
self.assertEqual(LANG.verb_forms("mon")[("PLAIN", "LETS")], "monyo")
self.assertEqual(LANG.verb_forms("bal")[("ONGOING", "PAST")], "balmapa")
self.assertEqual(LANG.verb_forms("gurke")[("PLAIN", "PAST")], "gurkepa")
def test_person_is_a_separate_word(self):
c = LANG.conjugate("ga")
self.assertEqual(c[("1PL", "PLAIN", "FUT")], "nami gati")
self.assertEqual(c[("3SG", "PLAIN", "PAST")], "lo gapa")
self.assertEqual(len(c), 96)
def test_every_form_is_sayable(self):
for e in LANG.entries.values():
forms = LANG.verb_forms(e.word) if e.pos == "v" else LANG.noun_forms(e.word) if e.pos == "n" else {}
for form in forms.values():
self.assertTrue(phon.is_valid(form), form)
def test_numbers(self):
# every number of GRAMMAR.md section 9
for n, said in [(0, "nol"), (1, "pin"), (9, "bes"), (10, "don"), (100, "hur"), (1000, "tas"),
(13, "don kal"), (23, "sor don kal"), (110, "hur don"), (304, "kal hur nel"),
(1900, "tas bes hur"), (2026, "sor tas sor don xan"), (20000, "sor don tas"),
(345000, "kal hur nel don mus tas"), (2000000, "sor lar")]:
self.assertEqual(LANG.number(n), said)
self.assertEqual(LANG.parse_number(said), n)
self.assertEqual(LANG.ordinal(3), "kalge")
self.assertEqual(LANG.ordinal(1), "pinge")
for n in list(range(0, 10000, 7)) + [10000, 99999, 100000, 999999, 1000000, 999999999]:
self.assertEqual(LANG.parse_number(LANG.number(n)), n)
self.assertRaises(ValueError, LANG.number, 1000000000)
self.assertRaises(ValueError, LANG.parse_number, "kal sor")
self.assertRaises(ValueError, LANG.parse_number, "pin don kal") # pin don is not said
def test_number_words_are_in_the_dictionary(self):
missing = [w for w in LANG.DIGITS + ["don", "hur", "tas"] if w not in LANG.entries]
self.assertEqual(missing, [])
@unittest.skipUnless("lar" in LANG.entries, "tk_087c5d65c9bf: lar (million, GRAMMAR.md section 9) is not in the dictionary")
def test_lar(self):
self.assertEqual(LANG.entries["lar"].pos, "num")
class Glosser(unittest.TestCase):
def test_words(self):
for word, g in [("wangimite", "traveler-PL-OBJ"), ("yonpimika", "child-PL-TO"), ("sirkupa", "write-DONE-PAST"),
("gurkepa", "drink-cause-PAST"), ("torwade", "strength-WITH"), ("kelwa", "language")]:
self.assertEqual(LANG.gloss_word(word), g)
self.assertIsNone(LANG.gloss_word("blik"))
self.assertIsNone(LANG.gloss_word("kelpate")) # tense then role: not an order of the grammar
self.assertIsNone(LANG.gloss_word("malpami")) # past + plural
def test_sentence_says_what_it_does_not_know(self):
rows = gloss.gloss_sentence(LANG, "Na Kelwate mu kel dol, xa Enya-po zork gur.")
self.assertEqual([r["status"] for r in rows],
["word", "word", "word", "word", "word", "word", "name", "unknown", "word"])
self.assertEqual(rows[1]["gloss"], "language-OBJ")
self.assertEqual(rows[6]["gloss"], "Enya-OF")
def test_name_with_yon_and_kelwa(self):
# dc_f925345a4b37: person = name + yon, language = name + kelwa
rows = gloss.gloss_sentence(LANG, "Na Faransi-kelwa-te kel dol. Kal Nipon-yonmi lenpa.", set())
self.assertEqual(rows[1]["gloss"], "Faransi-language-OBJ")
self.assertEqual(rows[1]["status"], "name")
self.assertEqual(rows[5]["gloss"], "Nipon-person-PL")
# any other word after the hyphen is still refused
self.assertEqual(gloss.analyse_token(LANG, "Nipon-wal", False, set())["status"], "unknown")
def test_unknown_first_word_is_not_a_name(self):
rows = gloss.gloss_sentence(LANG, "Zorka ro. Napo nen Zorka ro.", set())
self.assertEqual(rows[0]["status"], "unknown")
self.assertEqual(rows[4]["status"], "name")
def grammar_examples():
"""The interlinear examples of GRAMMAR.md: (kelwa word, gloss) pairs."""
with open(os.path.join(ROOT, "grammar", "GRAMMAR.md"), encoding="utf-8") as f:
lines = f.read().split("\n")
pairs, gloss_lines = [], set()
for i, (a, b) in enumerate(zip(lines, lines[1:])):
if not (a.startswith(" ") and b.startswith(" ") and a.strip() and b.strip()):
continue
if i in gloss_lines:
continue # a gloss line is never the Kelwa line of the next pair
# an English line may end with a comment in brackets: "We will go. (exclusive)"
end = re.sub(r"\s{2,}\(.*\)$", "", b.strip())
if not re.search(r"[A-Z]{2}|\bI\b|\bnot\b|\bcome\b", b) or re.search(r"[.!?]$", end):
continue
gloss_lines.add(i + 1)
ka, gl = a.split(), b.split()
if len(ka) != len(gl):
pairs.append((a.strip(), "WORD COUNT " + b.strip()))
continue
pairs += list(zip(ka, gl))
return pairs
class GrammarReference(unittest.TestCase):
def test_examples_found(self):
self.assertGreater(len(grammar_examples()), 100)
def test_every_example_word_comes_out_of_the_program(self):
labels = set(a.label for a in LANG.affixes.values() if a.label.isupper())
wrong = []
for word, gl in grammar_examples():
said = [p for p in gl.split("-") if p in labels]
core = word.strip(gloss.PUNCT)
if core[:1].isupper() and not LANG.analyses(core.replace("-", "").lower()):
# a foreign name, maybe with -yon / -kelwa, then suffixes (dc_f925345a4b37)
row = gloss.analyse_token(LANG, core, False, set())
if row["status"] != "name" or row.get("labels", []) != said:
wrong.append("%s (%s): program reads %s" % (word, gl, row["gloss"]))
continue
w = core.replace("-", "").lower()
readings = [[s.label for s in a["suffixes"] if s.label in labels] for a in LANG.analyses(w)]
if said not in readings:
wrong.append("%s (%s): program reads %s" % (word, gl, LANG.gloss_word(w)))
pieces = word.strip(gloss.PUNCT).lower().split("-")
for p in pieces[1:]:
if p not in LANG.affixes and p not in LANG.entries:
wrong.append("%s: piece '%s' is neither a suffix nor a word" % (word, p))
self.assertEqual(wrong, [])
def test_sentences_of_the_reference(self):
n, problems, _ = check_texts.check_sentences(LANG, os.path.join(ROOT, "texts", "sentences.tsv"), check_texts.collect_names(LANG, ROOT))
self.assertGreater(n, 40)
self.assertEqual(problems, [])
def reference_problems(self):
out = []
with open(os.path.join(ROOT, "grammar", "GRAMMAR.md"), encoding="utf-8") as f:
for n, l in enumerate(f.read().splitlines(), 1):
if not l.startswith(" "):
for e in check_texts.check_marked(LANG, l.replace("**", ""), gloss.names()):
out.append("GRAMMAR.md line %d: %s" % (n, e))
return out
def test_words_named_in_the_reference_exist(self):
# every `quoted` word of GRAMMAR.md is a real word or a real suffix, except
# the history note (-bo, -mu, salmu: what the language used to have)
allowed = ("`-bo`", "`-mu`", "'salmu'", "'lar'")
missing = [m for m in self.reference_problems() if not any(a in m for a in allowed)]
self.assertEqual(missing, [])
def test_kelalun(self):
self.assertIn("kelalun", LANG.entries)
self.assertEqual(LANG.entries["kelalun"].parts, "kel+lun")
def test_old_suffixes_are_gone(self):
# decision of day one: WITH is -de (was -bo), opposite is -xu (was -mu)
self.assertEqual(LANG.label("WITH").suffix, "de")
self.assertEqual(LANG.label("opposite").suffix, "xu")
self.assertIsNone(LANG.gloss_word("girbo"))
self.assertEqual(LANG.gloss_word("girde"), "hand-WITH")
class Texts(unittest.TestCase):
def test_sentence_errors(self):
_, errs = check_texts.check_sentence(LANG, "Na blikte gur.", set())
self.assertEqual(len(errs), 1)
self.assertIn("blikte", errs[0])
def test_lesson(self):
d = tempfile.mkdtemp()
path = os.path.join(d, "lesson-01.md")
good = ("# Lesson 1: Hello\n\n## Dialogue\n\nTwo people meet.\n\n- Enya: **Yar seka!** — *Hello!*\n- Hiro: **Na walte gur.** — *I drink water.*\n\n## New words\n\n"
"- `yar` sun\n- `-te` object\n\n## Grammar\n\n`wal-te` = `wal` + `-te`\n\n## Exercises\n\n## Answers\n")
with open(path, "w", encoding="utf-8") as f:
f.write(good)
self.assertEqual(check_texts.check_lesson(LANG, path, gloss.names(), {"lesson-01"}), [])
with open(path, "w", encoding="utf-8") as f:
f.write(good.replace("Na walte gur.", "Na walte blik.").replace("`yar`", "`yarp`").replace("## Answers\n", ""))
msgs = " | ".join(m for _, m in check_texts.check_lesson(LANG, path, gloss.names(), set()))
for expected in ("'blik'", "'yarp'", "sections must be", "no sentence with source lesson-01"):
self.assertIn(expected, msgs)
os.unlink(path)
os.rmdir(d)
def gl(sentence):
return " ".join(r["gloss"] for r in gloss.gloss_sentence(LANG, sentence, set()))
class FixedGlosses(unittest.TestCase):
"""The words the grammar glosses in its own way (tools/fixed.tsv).
Before day two the glosser took the first sense of the dictionary for every
word and no test looked at WHAT a sentence was glossed as: The Nobody Times
found "Hen bul!" glossed "thank help"."""
def test_the_sentence_of_the_newspaper(self):
self.assertEqual(gl("Hen bul! Murxukegi huxi ro he?"), "please help doctor what-AT be Q")
def test_hen_before_a_command_is_please(self):
# GRAMMAR.md 4, and the commands of lessons 4 and 9
for s, g in [("Hen len!", "please come"),
("Hen naka walte des!", "please I-TO water-OBJ give"),
("Na yal. Hen napo wos len dol he?", "I agree please I-OF dog come can Q"),
("Sal, hen len!", "good please come"),
("Hen mu ga!", "please not go")]:
self.assertEqual(gl(s), g, s)
def test_hen_as_the_verb_is_thank(self):
for s, g in [("Na seka hen.", "I you-TO thank"),
("Sal! Na seka hen. Len!", "good I you-TO thank come"),
("Na seka hen he?", "I you-TO thank Q"),
("Na seka hen dol.", "I you-TO thank can"),
("Na seka henpa.", "I you-TO thank-PAST"),
("Hen!", "thank")]:
self.assertEqual(gl(s), g, s)
def test_closing_particles_carry_the_label_of_the_grammar(self):
self.assertEqual(gl("Se Kelwate kel he?"), "you language-OBJ speak Q")
self.assertEqual(gl("Na, lo lenti sa, nun."), "I he come-FUT THAT think")
self.assertEqual(gl("Na welpa wi bar napo sin ro."), "I see-PAST REL man I-OF friend be")
self.assertEqual(gl("Se len kun, nami gati."), "you come if I-PL go-FUT")
def test_fixed_expressions_are_named(self):
rows = gloss.gloss_sentence(LANG, "Yar seka! Hu yon lenpa?", set())
self.assertEqual([r["phrase"]["gloss"] for r in rows if r.get("phrase")], ["hello", "who"])
self.assertEqual(rows[0]["gloss"], "sun") # the words keep their literal gloss
# an expression does not run over the end of a sentence
rows = gloss.gloss_sentence(LANG, "Lo hu. Yon len.", set())
self.assertEqual([r for r in rows if r.get("phrase")], [])
def test_the_table_is_sound(self):
table = gloss.fixed()
self.assertGreaterEqual(len(table), 10)
for f in table:
for w in f["kelwa"].split():
self.assertIsNotNone(LANG.analyse(w), "%s: '%s' is not a word" % (f["kelwa"], w))
self.assertTrue(f["gloss"] and f["english"] and f["rule"], f["kelwa"])
self.assertEqual(sorted(f["gloss"] for f in table if f["when"] == "always"), ["Q", "REL", "THAT"])
class Examples(unittest.TestCase):
"""Every example of the pages is glossed by the program and compared."""
@classmethod
def setUpClass(cls):
cls.r = check_examples.run()
def test_examples_are_found(self):
self.assertGreater(self.r["examples"], 400)
self.assertGreaterEqual(len(check_examples.interlinear(os.path.join(ROOT, "grammar", "GRAMMAR.md"))), 20)
self.assertGreaterEqual(len(check_examples.interlinear(os.path.join(ROOT, "texts", "north-wind.md"))), 5)
def test_no_mismatch_without_a_task(self):
# a page and the program disagree, and nobody filed it: fix it or file it
self.assertEqual(["%s %s: page '%s', program '%s'" % f[:4] for f in self.r["untracked"]], [])
def test_fast(self):
# Farid adds words all day: the whole comparison must stay well under a second
self.assertLess(dict(self.r["timing"])["total"], 1.0)
def test_verdicts(self):
rd = check_examples.Readings(LANG)
def row(s, i):
return gloss.gloss_sentence(LANG, s, set())[i]
self.assertEqual(rd.verdict(row("Lo len.", 0), "he"), "exact")
self.assertEqual(rd.verdict(row("Lo len.", 0), "she"), "reading")
self.assertEqual(rd.verdict(row("Wangi len.", 0), "travel-doer"), "reading")
self.assertEqual(rd.verdict(row("Yar mel ro.", 0), "Sun"), "reading")
self.assertEqual(rd.verdict(row("Lo len.", 0), "they"), "mismatch")
self.assertEqual(rd.verdict(row("Malmi len.", 0), "woman"), "mismatch") # the plural is missing
# a word with a job of its own has one right gloss
self.assertEqual(rd.verdict(row("Hen len!", 0), "thank"), "mismatch")
self.assertEqual(rd.verdict(row("Na seka hen.", 2), "please"), "mismatch")
self.assertEqual(rd.verdict(row("Se len he?", 2), "question.marker"), "mismatch")
def test_a_wrong_page_is_caught(self):
rd = check_examples.Readings(LANG)
n, bad, _ = check_examples.compare(LANG, rd, "Hen len!", "thank come", set())
self.assertEqual(bad, [("Hen", "thank", "please")])
n, bad, _ = check_examples.compare(LANG, rd, "Na walte gur.", "I water drink", set())
self.assertEqual(bad, [("walte", "water", "water-OBJ")])
n, bad, _ = check_examples.compare(LANG, rd, "Na walte gur.", "I water-OBJ", set())
self.assertEqual(len(bad), 1)
class LookupTool(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.lk = lookup.Lookup(LANG)
def words(self, q):
return [r[0] for r in self.lk.english(q)]
def test_english_to_kelwa(self):
self.assertEqual(self.words("water")[0], "wal")
self.assertEqual(self.words("teacher"), ["xenkegi"])
self.assertEqual(self.words("drinks")[:2], ["gur", "gurto"]) # a plural still finds the word
self.assertEqual(self.words("please"), ["hen"])
self.assertIn("na seka hen", self.words("thank you"))
self.assertIn("hu yon", self.words("who"))
self.assertEqual(self.words("qzxv"), []) # not a word Farid will ever add
def test_kelwa_to_english(self):
a = self.lk.kelwa_word("wangimite")[0]
self.assertEqual((a["pieces"], a["gloss"], a["built"]), ("wangi-mi-te", "traveler-PL-OBJ", "wan + gi"))
self.assertEqual(self.lk.kelwa_word("zavte"), [])
self.assertIn("before-command", [f["when"] for f in self.lk.fixed_for("hen")])
def test_command_line(self):
for q, direction, expected, found in [
("Hen bul!", None, "word by word: please help", True),
("23", None, "23 = sor don kal", True),
("sor don kal", None, "sor don kal = 23", True),
("sun", None, "yar", True), ("sun", "k", "self", True),
("qzxv", None, "Nothing for 'qzxv'", False)]:
out = io.StringIO()
self.assertEqual(lookup.lookup(q, direction, self.lk, out), found, q)
self.assertIn(expected, out.getvalue(), q)
out = io.StringIO()
lookup.lookup("sun", "e", self.lk, out)
self.assertNotIn("self", out.getvalue())
class Pronunciation(unittest.TestCase):
"""tools/ipa.py against the tables of grammar/PHONOLOGY.md."""
def test_reference_examples(self):
# PHONOLOGY.md, Examples: syllables and first-syllable stress
for word, sound in [("kelwa", "ˈkel.wa"), ("wangi", "ˈwan.gi"), ("sulo", "ˈsu.lo"),
("kinhus", "ˈkin.hus"), ("xenkegi", "ˈʃen.ke.gi"), ("torwade", "ˈtoɾ.wa.de"),
("wangimite", "ˈwan.gi.mi.te"), ("yar", "jaɾ")]:
self.assertEqual(ipa.ipa(word), sound, word)
def test_letters_that_change(self):
# PHONOLOGY.md, consonant table: x = ʃ, r = ɾ, y = j; every other letter is its own symbol
self.assertEqual(ipa.SYMBOL, {"x": "ʃ", "r": "ɾ", "y": "j"})
def test_every_word_lossless(self):
# every dictionary word gets a pronunciation, and the spelling comes back from it
back = {v: k for k, v in ipa.SYMBOL.items()}
rows = ipa.all_rows()
self.assertEqual(len(rows), len(LANG.entries))
for word, pos, sound in rows:
self.assertEqual("".join(back.get(c, c) for c in sound if c not in "ˈ."), word, word)
self.assertEqual(sound.count(".") + 1, len(phon.syllabify(word)[0]), word)
def test_bad_spelling_has_no_sound(self):
for w in ("ak", "kella", "kra"):
with self.assertRaises(ValueError):
ipa.ipa(w)
def test_sentence(self):
# one-syllable particles are unstressed; a foreign name keeps its spelling
self.assertEqual(ipa.sentence("Hen bul! Murxukegi huxi ro he?"), "hen bul ˈmuɾ.ʃu.ke.gi ˈhu.ʃi ɾo he")
self.assertEqual(ipa.sentence("Hiro wolpa."), "<Hiro> ˈwol.pa")
self.assertEqual(ipa.sentence("Na Enya-po wos."), "na <Enya>.po wos")
# a capital after ! is a new sentence, not a name; Kelwate is Kelwa + -te, not a name
self.assertEqual(ipa.sentence("Yar seka! Sepo nen hu ro?"), "jaɾ ˈse.ka ˈse.po nen hu ɾo")
self.assertEqual(ipa.sentence("Na Kelwate kel."), "na ˈkel.wa.te kel")
self.assertEqual(ipa.sentence("Napo nen Tomas ro."), "ˈna.po nen <Tomas> ɾo")
def test_recording_script_is_current(self):
# audio/lesson-01-script.md is made by the program: it must follow texts/sentences.tsv
with open(os.path.join(ROOT, "audio", "lesson-01-script.md"), encoding="utf-8") as f:
self.assertEqual(f.read(), ipa.lesson_script(1),
"run: python tools/ipa.py --lesson 1 > audio/lesson-01-script.md")
class VerbSense(unittest.TestCase):
def test_tense_picks_the_verb_sense(self):
# GRAMMAR 10: hus = wind, to blow. With a tense suffix it is the verb (North Wind, line 41)
self.assertEqual(LANG.gloss_word("huspa"), "blow-PAST")
self.assertEqual(LANG.gloss_word("husmapa"), "blow-ONGOING-PAST")
self.assertEqual(LANG.gloss_word("lunpa"), "shine-PAST")
# without one it stays the noun
self.assertEqual(LANG.gloss_word("kinhus"), "north.wind")
self.assertEqual(LANG.gloss_word("hus"), "wind")
class SyllableUse(unittest.TestCase):
def test_legal_syllables(self):
# PHONOLOGY.md: 16 x 5 x 5 C V (F) syllables, minus the 10 with wu or yi
legal = syllables.legal_syllables()
self.assertEqual(len(legal), 390)
self.assertNotIn("wun", legal)
self.assertNotIn("yi", legal)
self.assertTrue(all(phon.is_valid(s) for s in legal))
def test_counts_on_a_small_dictionary(self):
path = dict_file("kelwa\tn\tlanguage\tkel+wa\tcore\tx\nkel\tv\tspeak\t-\tcore\tx\nsulo\tn\tcoat\t-\tcore\tx\n")
legal, in_roots, in_words, using = syllables.counts(path)
self.assertEqual((in_roots["kel"], in_words["kel"]), (1, 2))
self.assertEqual((in_roots["wa"], in_words["wa"]), (0, 1))
self.assertEqual(using["lo"], ["sulo"])
if __name__ == "__main__":
unittest.main()
Shown as text, exactly as the agents wrote it. Nothing here is run.