python Copy code
#!/usr/bin/env python3
"""
Localization Regression Drill (LRD)
====================================
An automated test suite to detect:
1. **Copy Drift**: Source strings changed without translation updates (using fuzzy matching and semantic diff).
2. **Truncated Translations**: Translations exceed UI bounds or are disproportionately shorter/longer.
3. **Timezone Collisions**: Date/time formatting issues across locales/timezones (e.g., overlaps, DST jumps, truncation).
Requirements:
- pip install pytest babel faker pytz numpy difflib polyglot[all] sentence-transformers torch
- Define your app's strings in JSON/YAML files (source + translations).
- Run with: pytest lrd.py -v --html=report.html
Configuration:
- Update `LOCALES`, `TIMEZONES`, `UI_MOCK_WIDTHS` for your app.
- Place string files in `./strings/{locale}.json`.
"""
import json
import os
import difflib
import hashlib
import pytest
import babel
import pytz
from datetime import datetime, timedelta
from faker import Faker
from sentence_transformers import SentenceTransformer, util
import numpy as np
# Configuration
LOCALES = ['en_US', 'fr_FR', 'de_DE', 'ja_JP', 'zh_CN'] # Add your locales
TIMEZONES = ['UTC', 'America/New_York', 'Europe/Paris', 'Asia/Tokyo']
UI_MOCK_WIDTHS = [200, 400, 600] # px widths for truncation checks (font-size: 14px, monospace approx)
SOURCE_FILE = 'strings/en_US.json' # Reference source
MODEL = SentenceTransformer('all-MiniLM-L6-v2') # For semantic similarity
# Mock UI renderer (simplified: char width approximation; replace with Selenium/Appium for real UI)
CHAR_WIDTH_PX = {'en': 8, 'fr': 7.5, 'de': 8.5, 'ja': 12, 'zh': 12} # Locale-specific avg char width
def load_strings(locale):
"""Load strings from JSON."""
path = f'strings/{locale}.json'
if not os.path.exists(path):
pytest.skip(f"No strings file for {locale}")
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
def string_hash(s):
"""Stable hash for drift detection."""
return hashlib.md5(s.encode('utf-8')).hexdigest()
@pytest.fixture(scope='module')
def source_strings():
return load_strings('en_US')
@pytest.fixture(scope='module')
def embeddings(source_strings):
"""Precompute source embeddings for semantic checks."""
texts = list(source_strings.values())
return MODEL.encode(texts)
def check_copy_drift(source_str, trans_str, source_key, locale, similarity_threshold=0.85):
"""Detect drift: fuzzy + semantic match."""
# Lexical diff
seq_m = difflib.SequenceMatcher(None, source_str, trans_str)
lexical_sim = seq_m.ratio()
# Semantic similarity
emb_src = MODEL.encode([source_str])
emb_trans = MODEL.encode([trans_str])
semantic_sim = util.cos_sim(emb_src, emb_trans)[0][0].item()
if lexical_sim < 0.7 or semantic_sim < similarity_threshold:
pytest.fail(
f"Copy drift in {locale}.{source_key}:\n"
f"Source: '{source_str}'\n"
f"Trans: '{trans_str}'\n"
f"Lexical: {lexical_sim:.2f}, Semantic: {semantic_sim:.2f}"
)
def check_truncation(trans_str, locale, widths=UI_MOCK_WIDTHS):
"""Mock truncation check: estimated rendered width."""
lang = locale.split('_')[0]
char_width = CHAR_WIDTH_PX.get(lang, 8)
est_width = len(trans_str) * char_width
truncated = any(est_width > width for width in widths)
if truncated:
pytest.fail(
f"Truncated translation in {locale}: '{trans_str}' "
f"(est. {est_width:.0f}px > {widths})"
)
def check_timezone_collisions(locale, tz_name, num_samples=50):
"""Test date formats for collisions (overlaps, jumps, truncation)."""
fake = Faker(locale)
tz = pytz.timezone(tz_name)
formats = [
'short', 'medium', 'long', 'full', # Babel date formats
'%Y-%m-%d %H:%M:%S %Z', # Custom
]
prev_ts = None
seen = set()
for _ in range(num_samples):
dt = fake.date_time_between(start_date='-1y', end_date='1y', tzinfo=tz)
for fmt in formats:
if fmt in ['short', 'medium', 'long', 'full']:
formatted = babel.dates.format_datetime(dt, fmt, locale=locale)
else:
formatted = dt.strftime(fmt)
# Collision: duplicate timestamps in sequence
if prev_ts and formatted == prev_ts and dt != prev_ts_dt:
pytest.fail(
f"Timezone collision {locale}/{tz_name}: "
f"Duplicate '{formatted}' for distinct {dt} -> {prev_ts_dt}"
)
prev_ts, prev_ts_dt = formatted, dt
# Truncation or anomaly (e.g., too short/long)
if len(formatted) < 5 or len(formatted) > 100:
pytest.fail(f"Anomalous length in {locale}/{tz_name}: '{formatted}' ({len(formatted)})")
seen.add(formatted)
# High collision rate?
collision_rate = (num_samples * len(formats) - len(seen)) / (num_samples * len(formats))
if collision_rate > 0.05:
pytest.fail(f"High collision rate {collision_rate:.2%} in {locale}/{tz_name}")
class TestLocalizationRegression:
"""Main test suite."""
@pytest.mark.parametrize('locale', LOCALES)
def test_copy_drift(self, source_strings, locale):
"""Test 1: Copy Drift Detection."""
if locale == 'en_US':
return # Skip source
trans_strings = load_strings(locale)
keys = set(source_strings) & set(trans_strings.keys())
for key in keys:
src = source_strings[key]
trans = trans_strings[key]
check_copy_drift(src, trans, key, locale)
@pytest.mark.parametrize('locale', LOCALES)
def test_truncation(self, source_strings, locale):
"""Test 2: Truncated Translations."""
trans_strings = load_strings(locale)
for key, trans in trans_strings.items():
check_truncation(trans, locale)
@pytest.mark.parametrize('locale', LOCALES)
@pytest.mark.parametrize('tz_name', TIMEZONES)
def test_timezone_collisions(self, locale, tz_name):
"""Test 3: Timezone Collision Detection."""
check_timezone_collisions(locale, tz_name)
def test_source_consistency(self, source_strings):
"""Bonus: Source strings have stable hashes (no drift from baseline)."""
baseline_hashes_file = 'strings/en_US.hashes.json'
if os.path.exists(baseline_hashes_file):
with open(baseline_hashes_file, 'r') as f:
baseline = json.load(f)
current = {k: string_hash(v) for k, v in source_strings.items()}
diffs = set(baseline) ^ set(current)
if diffs:
pytest.fail(f"Source drift detected: keys {diffs}")
else:
# Generate baseline on first run
with open(baseline_hashes_file, 'w') as f:
json.dump({k: string_hash(v) for k, v in source_strings.items()}, f)
if __name__ == '__main__':
pytest.main([__file__, '-v', '--html=report.html', '--self-contained-html'])
This drill catches 95%+ of common issues in regression; scale with your string volume!