| """ |
| Invariant tests for cterdam/region dataset. |
| |
| Run from dataset root after cloning: |
| pip install datasets pytest |
| pytest test/test_invariants.py -v |
| |
| Verifies: |
| - name field matches lang selection (name_en/ru/zh) |
| - lang matches region-based language rule |
| - code format and uniqueness |
| - region prefix matches code |
| - all name fields in correct script (en=Latin, zh=CJK, ru=Cyrillic) |
| - no typographic quotes in name_ru |
| - balanced parentheses in all name fields and alt lists |
| - no whitespace anomalies |
| - name_en starts uppercase, not all-caps, no trailing punctuation |
| - no duplicate values across all name fields within a row |
| - alt lists: primary not duplicated, no non-Latin in names_en_alt |
| - links are valid URLs with no duplicates per row |
| - no empty lists (use None instead of []) |
| - parent/children hierarchy integrity |
| """ |
|
|
| import re |
| import unicodedata |
| import pytest |
| from collections import Counter |
| from datasets import load_dataset |
|
|
| SLAVIC_REGIONS = { |
| 'RU', 'UA', 'BY', 'KZ', 'UZ', 'TJ', 'KG', 'TM', 'GE', 'AZ', 'AM', 'MD', |
| 'LT', 'LV', 'EE', 'RS', 'ME', 'BA', 'HR', 'SI', 'SK', 'CZ', 'PL', 'BG', 'MK', 'FI' |
| } |
|
|
| SINOPHONE_REGIONS = { |
| 'CN', 'TW', 'HK', 'MO', 'JP', 'KR', 'KP', 'MN', 'SG', 'VN', 'LA', 'TH', 'MM', 'KH', 'MY', 'BN' |
| } |
|
|
|
|
| def determine_expected_lang(region_code: str) -> str: |
| if region_code in SINOPHONE_REGIONS: |
| return 'zh' |
| elif region_code in SLAVIC_REGIONS: |
| return 'ru' |
| else: |
| return 'en' |
|
|
|
|
| @pytest.fixture(scope="session") |
| def dataset(): |
| return load_dataset('cterdam/region', split='train') |
|
|
|
|
| @pytest.fixture(scope="session") |
| def dataset_index(dataset): |
| return {e['code']: dict(e) for e in dataset} |
|
|
|
|
| |
| |
| |
|
|
| def test_lang_values_valid(dataset): |
| """lang field must be one of: en, ru, zh.""" |
| invalid = [(e['code'], e['lang']) for e in dataset if e.get('lang') not in ('en', 'ru', 'zh')] |
| assert invalid == [], f"Invalid lang values: {invalid[:5]}" |
|
|
|
|
| def test_name_matches_lang_field(dataset): |
| """name field must equal name_en/ru/zh based on lang.""" |
| lang_to_field = {'en': 'name_en', 'ru': 'name_ru', 'zh': 'name_zh'} |
| mismatches = [] |
| for e in dataset: |
| name = e.get('name') |
| lang = e.get('lang') |
| if not name or not lang: |
| continue |
| lang_val = e.get(lang_to_field.get(lang, '')) |
| if name != lang_val: |
| mismatches.append((e['code'], lang, name[:30], (lang_val or '')[:30])) |
| assert mismatches == [], f"Name/lang field mismatches: {mismatches[:5]}" |
|
|
|
|
| def test_lang_matches_parent_region(dataset): |
| """lang field must match parent region's language rule.""" |
| mismatches = [(e['code'], e.get('region'), e.get('lang'), determine_expected_lang(e.get('region', ''))) |
| for e in dataset |
| if e.get('lang') != determine_expected_lang(e.get('region', ''))] |
| assert mismatches == [], f"Lang mismatches: {mismatches[:5]}" |
|
|
|
|
| |
| |
| |
|
|
| def _is_cjk(c): |
| cp = ord(c) |
| return ( |
| 0x3400 <= cp <= 0x9FFF |
| or 0xF900 <= cp <= 0xFAFF |
| or 0x20000 <= cp <= 0x2A6DF |
| or 0x2A700 <= cp <= 0x2EBEF |
| or 0x30000 <= cp <= 0x323AF |
| ) |
|
|
|
|
| def _non_latin_alpha(s): |
| """Return list of non-Latin alphabetic characters in s. |
| |
| Allows: ASCII Latin, Latin Extended (ā ẓ etc.), modifier letters |
| (ʻ ʿ ʾ etc.), superscript/subscript Latin letters (ⁿ etc.). |
| Flags: Arabic, Hebrew, Bengali, Myanmar, Tifinagh, Greek, etc. |
| """ |
| out = [] |
| for c in (s or ''): |
| if not c.isalpha(): |
| continue |
| name = unicodedata.name(c, '') |
| if not ( |
| 'A' <= c <= 'Z' or 'a' <= c <= 'z' |
| or name.startswith('LATIN') |
| or name.startswith('MODIFIER') |
| or name.startswith('COMBINING') |
| or 'SUPERSCRIPT' in name |
| or 'SUBSCRIPT' in name |
| ): |
| out.append(c) |
| return out |
|
|
|
|
| def test_name_zh_only_cjk_letters(dataset): |
| """All letter chars in name_zh and names_zh_alt must be CJK.""" |
| bad = [] |
| for e in dataset: |
| for v in [e.get('name_zh')] + list(e.get('names_zh_alt') or []): |
| if not v: |
| continue |
| foreign = [c for c in v if c.isalpha() and not _is_cjk(c)] |
| if foreign: |
| bad.append((e['code'], v, foreign)) |
| assert bad == [], f"name_zh/alts with non-CJK letters: {bad[:10]}" |
|
|
|
|
| def test_name_ru_only_cyrillic_letters(dataset): |
| """All letter chars in name_ru and names_ru_alt must be Cyrillic.""" |
| bad = [] |
| for e in dataset: |
| for v in [e.get('name_ru')] + list(e.get('names_ru_alt') or []): |
| if not v: |
| continue |
| foreign = [c for c in v if c.isalpha() and not ('Ѐ' <= c <= 'ӿ')] |
| if foreign: |
| bad.append((e['code'], v, foreign)) |
| assert bad == [], f"name_ru/alts with non-Cyrillic letters: {bad[:10]}" |
|
|
|
|
| def test_name_en_only_latin(dataset): |
| """All letter chars in name_en and names_en_alt must be Latin.""" |
| bad = [] |
| for e in dataset: |
| for v in [e.get('name_en')] + list(e.get('names_en_alt') or []): |
| if not v: |
| continue |
| non_latin = _non_latin_alpha(v) |
| if non_latin: |
| bad.append((e['code'], v, non_latin)) |
| assert bad == [], f"name_en/alts with non-Latin letters: {bad[:10]}" |
|
|
|
|
| |
| |
| |
|
|
| def test_code_format(dataset): |
| """code must match ^[A-Z]{2}-[A-Z0-9]{1,6}$.""" |
| bad = [(e['code'],) for e in dataset |
| if not re.match(r'^[A-Z]{2}-[A-Z0-9]{1,6}$', e.get('code', ''))] |
| assert bad == [], f"Malformed codes: {bad[:10]}" |
|
|
|
|
| def test_code_unique(dataset): |
| """Each code must be unique across the dataset.""" |
| counts = Counter(e['code'] for e in dataset) |
| dups = [(c, n) for c, n in counts.items() if n > 1] |
| assert dups == [], f"Duplicate codes: {dups[:10]}" |
|
|
|
|
| def test_region_matches_code_prefix(dataset): |
| """region must equal the country prefix of the code (e.g. AD-02 → region=AD).""" |
| bad = [(e['code'], e.get('region')) for e in dataset |
| if e.get('region') != (e.get('code', '') or '')[:2]] |
| assert bad == [], f"region != code prefix: {bad[:10]}" |
|
|
|
|
| |
| |
| |
|
|
| def test_no_typographic_quotes_in_ru(dataset): |
| """name_ru must not contain typographic quotes «».""" |
| bad = [(e['code'], e['name_ru']) for e in dataset |
| if e.get('name_ru') and re.search(r'[«»]', e['name_ru'])] |
| assert bad == [], f"name_ru with «» quotes: {bad[:10]}" |
|
|
|
|
| def test_balanced_parentheses(dataset): |
| """All name fields and alt lists must have balanced ASCII and fullwidth parentheses.""" |
| bad = [] |
| for e in dataset: |
| for f in ('name_en', 'name_ru', 'name_zh'): |
| v = e.get(f) or '' |
| if v.count('(') != v.count(')') or v.count('(') != v.count(')'): |
| bad.append((e['code'], f, v)) |
| for lst in ('names_en_alt', 'names_ru_alt', 'names_zh_alt'): |
| for v in (e.get(lst) or []): |
| if v.count('(') != v.count(')') or v.count('(') != v.count(')'): |
| bad.append((e['code'], lst, v)) |
| assert bad == [], f"Unbalanced parens: {bad[:10]}" |
|
|
|
|
| def test_no_whitespace_in_names(dataset): |
| """Name fields must not have leading or trailing whitespace.""" |
| bad = [(e['code'], f) for e in dataset for f in ('name_en', 'name_ru', 'name_zh') |
| if e.get(f) and e[f] != e[f].strip()] |
| assert bad == [], f"Leading/trailing whitespace: {bad[:10]}" |
|
|
|
|
| def test_no_double_spaces_in_names(dataset): |
| """Name fields must not contain consecutive spaces.""" |
| bad = [(e['code'], f) for e in dataset for f in ('name_en', 'name_ru', 'name_zh') |
| if e.get(f) and ' ' in e[f]] |
| assert bad == [], f"Double spaces: {bad[:10]}" |
|
|
|
|
| def test_no_newlines_in_names(dataset): |
| """Name fields must not contain newline or tab characters.""" |
| bad = [(e['code'], f) for e in dataset for f in ('name_en', 'name_ru', 'name_zh') |
| if any(c in (e.get(f) or '') for c in '\n\t\r')] |
| assert bad == [], f"Newline/tab in names: {bad[:10]}" |
|
|
|
|
| def test_no_ideographic_space(dataset): |
| """Name fields and alt lists must not contain ideographic space U+3000.""" |
| bad = [] |
| for e in dataset: |
| for f in ('name_en', 'name_ru', 'name_zh'): |
| if ' ' in (e.get(f) or ''): |
| bad.append((e['code'], f)) |
| for lst in ('names_en_alt', 'names_ru_alt', 'names_zh_alt'): |
| for v in (e.get(lst) or []): |
| if ' ' in v: |
| bad.append((e['code'], lst)) |
| assert bad == [], f"Ideographic space: {bad[:10]}" |
|
|
|
|
| def test_name_en_starts_uppercase(dataset): |
| """name_en first alphabetic character must be uppercase.""" |
| bad = [(e['code'], e['name_en']) for e in dataset |
| if e.get('name_en') and any(c.isalpha() for c in e['name_en']) |
| and next(c for c in e['name_en'] if c.isalpha()).islower()] |
| assert bad == [], f"name_en starts lowercase: {bad[:10]}" |
|
|
|
|
| def test_name_en_not_allcaps(dataset): |
| """name_en must not be entirely uppercase.""" |
| bad = [(e['code'], e['name_en']) for e in dataset |
| if e.get('name_en') |
| and e['name_en'] == e['name_en'].upper() |
| and e['name_en'].replace(' ', '').replace('-', '').isalpha()] |
| assert bad == [], f"name_en all-caps: {bad[:10]}" |
|
|
|
|
| def test_name_en_no_trailing_punctuation(dataset): |
| """name_en must not end with ., ,, ;, :, !, ?.""" |
| bad = [(e['code'], e['name_en']) for e in dataset |
| if e.get('name_en') and e['name_en'][-1] in '.,:;!?'] |
| assert bad == [], f"name_en trailing punctuation: {bad[:10]}" |
|
|
|
|
| |
| |
| |
|
|
| def test_no_duplicate_names_within_entry(dataset): |
| """No value may appear twice across all name fields (including names_other).""" |
| bad = [] |
| for e in dataset: |
| vals = [] |
| for f in ('name_en', 'name_ru', 'name_zh'): |
| if e.get(f): |
| vals.append(e[f]) |
| for lst in ('names_en_alt', 'names_ru_alt', 'names_zh_alt', 'names_other'): |
| vals += (e.get(lst) or []) |
| seen = set() |
| duped = set() |
| for v in vals: |
| if v in seen: |
| duped.add(v) |
| seen.add(v) |
| if duped: |
| bad.append((e['code'], sorted(duped))) |
| assert bad == [], f"Duplicate values within entry: {bad[:10]}" |
|
|
|
|
| def test_no_empty_alt_lists(dataset): |
| """Alt list fields must be None when empty, not [].""" |
| bad = [(e['code'], lst) |
| for e in dataset |
| for lst in ('names_en_alt', 'names_ru_alt', 'names_zh_alt', 'names_other') |
| if e.get(lst) == []] |
| assert bad == [], f"Empty list instead of None: {bad[:10]}" |
|
|
|
|
| |
| |
| |
|
|
| def test_links_are_urls(dataset): |
| """Every link must start with http:// or https://.""" |
| bad = [(e['code'], l) for e in dataset for l in (e.get('links') or []) |
| if not l.startswith(('http://', 'https://'))] |
| assert bad == [], f"Bad links: {bad[:10]}" |
|
|
|
|
| def test_no_duplicate_links(dataset): |
| """No duplicate URLs within a row's link list.""" |
| bad = [(e['code'],) for e in dataset |
| if len(e.get('links') or []) != len(set(e.get('links') or []))] |
| assert bad == [], f"Duplicate links: {bad[:10]}" |
|
|
|
|
| |
| |
| |
|
|
| def test_parent_is_valid_code(dataset, dataset_index): |
| """parent, when set, must be a code present in the dataset.""" |
| bad = [(e['code'], e['parent']) for e in dataset |
| if e.get('parent') and e['parent'] not in dataset_index] |
| assert bad == [], f"Invalid parent codes: {bad[:10]}" |
|
|
|
|
| def test_children_are_valid_codes(dataset, dataset_index): |
| """All children codes must be present in the dataset.""" |
| bad = [(e['code'], c) for e in dataset |
| for c in (e.get('children') or []) |
| if c not in dataset_index] |
| assert bad == [], f"Invalid children codes: {bad[:10]}" |
|
|
|
|
| def test_no_self_referential_parent(dataset): |
| """parent must not equal code.""" |
| bad = [(e['code'],) for e in dataset if e.get('parent') == e.get('code')] |
| assert bad == [], f"Self-referential parent: {bad[:10]}" |
|
|
|
|
| def test_parent_in_children(dataset, dataset_index): |
| """If A.parent = B, then B.children must contain A.""" |
| bad = [(e['code'], e['parent']) for e in dataset |
| if e.get('parent') and e['parent'] in dataset_index |
| and e['code'] not in (dataset_index[e['parent']].get('children') or [])] |
| assert bad == [], f"A.parent=B but B.children missing A: {bad[:10]}" |
|
|
|
|
| def test_children_have_back_reference(dataset, dataset_index): |
| """If B.children contains A, then A.parent must equal B.""" |
| bad = [(e['code'], c, (dataset_index[c].get('parent') if c in dataset_index else None)) |
| for e in dataset |
| for c in (e.get('children') or []) |
| if c in dataset_index and dataset_index[c].get('parent') != e['code']] |
| assert bad == [], f"B.children contains A but A.parent != B: {bad[:10]}" |
|
|
|
|
| def test_parent_region_matches(dataset, dataset_index): |
| """parent's region must match this entry's region.""" |
| bad = [(e['code'], e['region'], e['parent'], dataset_index[e['parent']]['region']) |
| for e in dataset |
| if e.get('parent') and e['parent'] in dataset_index |
| and dataset_index[e['parent']]['region'] != e['region']] |
| assert bad == [], f"parent.region != entry.region: {bad[:10]}" |
|
|