meteogate / scripts /test-slugify-cross-layer.mjs
alexdum's picture
Sync current state to Hugging Face
3fee36c
Raw History Blame Contribute Delete
8.92 kB
#!/usr/bin/env node
/**
* Cross-layer slugify test β€” EuroMeteo
*
* Verifies that the R (eurometeo_slugify) and JS (eurometeoSlugify)
* implementations produce identical slugs for a comprehensive set of
* station and country names covering all transliteration edge cases.
*
* Usage:
* node scripts/test-slugify-cross-layer.mjs
*
* Requirements:
* - Rscript in PATH
* - Run from meteogate/ root
*/
import { eurometeoSlugify } from './lib/eurometeo-slugify.mjs';
import { execSync } from 'child_process';
import { writeFileSync, unlinkSync } from 'fs';
import { join } from 'path';
// ═══════════════════════════════════════════════════════════════
// Test cases: [input, expected_slug]
// Covers all transliteration table entries + edge cases
// ═══════════════════════════════════════════════════════════════
const TEST_CASES = [
// --- Basic ---
['OSLO-BLINDERN', 'oslo-blindern'],
['oslo-blindern', 'oslo-blindern'],
['Berlin', 'berlin'],
// --- German umlauts (ΓΌβ†’ue, ΓΆβ†’oe, Γ€β†’ae, ΓŸβ†’ss) ---
['MÜNCHEN', 'muenchen'],
['MUENCHEN-STADT', 'muenchen-stadt'], // already transliterated
['DΓΌsseldorf', 'duesseldorf'],
['GROß-GERAU', 'gross-gerau'],
['Γ–sterreich', 'oesterreich'],
['GΓ€ufelden', 'gaeufelden'], // Γ€β†’ae explicit: G+ae+ufelden
// --- Norwegian/Danish (ΓΈβ†’o, Γ¦β†’ae) ---
['OSLO - ØSTENSJØ', 'oslo-ostensjo'],
['KVITØYA', 'kvitoya'],
['EDGEØYA - KAPP HEUGLIN', 'edgeoya-kapp-heuglin'],
['ANDØYA', 'andoya'],
['Γ†RØSKØBING', 'aeroskobing'],
// --- Icelandic (ΓΎβ†’th, Γ°β†’d) ---
['ÞórshΓΆfn', 'thorshoefn'], // ΓΎβ†’th + ΓΆβ†’oe explicit
['Akureyri', 'akureyri'],
['ReykjavΓ­k', 'reykjavik'], // Γ­β†’i via NFD
// --- Polish (Ε‚β†’l) ---
['ŁódΕΊ', 'lodz'], // Ε‚β†’l + Γ³β†’o via NFD + ΕΊβ†’z via NFD
['WrocΕ‚aw', 'wroclaw'],
// --- Turkish (Δ±β†’i) ---
['Istanbul', 'istanbul'],
['GazΔ±antep', 'gaziantep'], // Δ±β†’i (dotless i)
// --- Swedish ---
['BJΓ–RNEBORG', 'bjoerneborg'], // ΓΆβ†’oe explicit table
['UmeΓ₯', 'umea'], // Γ₯β†’a via NFD
// --- French accents (via NFD) ---
['SAINT-CLEMENT-DES-BA', 'saint-clement-des-ba'],
['BΓ©ziers', 'beziers'],
['Île-de-France', 'ile-de-france'],
// --- Hungarian (via NFD) ---
['Budapest LΓ‘gymΓ‘nyos', 'budapest-lagymanyos'],
// --- Spacing/special chars ---
['SAARBRUECKEN-BURBACH (SECONDARY)', 'saarbruecken-burbach-secondary'],
['RV36 SELJORD', 'rv36-seljord'],
['ST_FLORENT_VIEI', 'st-florent-viei'], // underscore β†’ hyphen
[' leading trailing ', 'leading-trailing'],
// --- Country names ---
['Norway', 'norway'],
['United Kingdom', 'united-kingdom'],
['Czechia', 'czechia'],
['Bosnia and Herzegovina', 'bosnia-and-herzegovina'],
['Falkland Islands (Malvinas)', 'falkland-islands-malvinas'],
['South Georgia and the South Sandwich Islands', 'south-georgia-and-the-south-sandwich-islands'],
// --- Empty/null ---
['', ''],
[null, ''],
[undefined, ''],
];
// ═══════════════════════════════════════════════════════════════
// Run JS tests
// ═══════════════════════════════════════════════════════════════
console.log('╔═══════════════════════════════════════════════════════╗');
console.log('β•‘ EuroMeteo Slugify β€” Cross-Layer Test β•‘');
console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n');
let jsPass = 0;
let jsFail = 0;
const jsResults = {};
for (const [input, expected] of TEST_CASES) {
const actual = eurometeoSlugify(input);
jsResults[input ?? 'null'] = actual;
if (actual === expected) {
jsPass++;
} else {
jsFail++;
console.log(` βœ— JS FAIL: "${input}" β†’ "${actual}" (expected "${expected}")`);
}
}
console.log(`JS: ${jsPass} passed, ${jsFail} failed out of ${TEST_CASES.length}\n`);
// ═══════════════════════════════════════════════════════════════
// Run R tests via Rscript
// ═══════════════════════════════════════════════════════════════
// Build an R script that sources slugify.R and tests the same inputs
// Write test inputs to a temp file to avoid shell encoding issues
const rTestInputs = TEST_CASES
.filter(([input]) => input != null && input !== undefined && input !== '')
.map(([input]) => input);
const inputFile = join(process.cwd(), 'scripts', '_test_slugify_inputs.txt');
writeFileSync(inputFile, rTestInputs.join('\n'), 'utf-8');
const rScript = `
source("funs/slugify.R")
inputs <- readLines("scripts/_test_slugify_inputs.txt", encoding = "UTF-8")
cat("R_RESULTS_START\\n")
for (inp in inputs) {
slug <- eurometeo_slugify(inp)
cat(paste0(inp, "\\t", slug, "\\n"))
}
cat("R_RESULTS_END\\n")
`;
const rScriptFile = join(process.cwd(), 'scripts', '_test_slugify.R');
writeFileSync(rScriptFile, rScript, 'utf-8');
let rOutput;
try {
rOutput = execSync('Rscript scripts/_test_slugify.R', {
cwd: process.cwd(),
encoding: 'utf-8',
timeout: 30000,
env: { ...process.env, LC_ALL: 'en_US.UTF-8' },
});
} catch (e) {
console.error(' βœ— Failed to run Rscript:', e.message);
process.exit(1);
} finally {
try { unlinkSync(inputFile); unlinkSync(rScriptFile); } catch(e) {}
}
// Parse R results
const rLines = rOutput.split('\n');
const startIdx = rLines.indexOf('R_RESULTS_START');
const endIdx = rLines.indexOf('R_RESULTS_END');
if (startIdx === -1 || endIdx === -1) {
console.error(' βœ— Could not parse R output');
console.error(rOutput);
process.exit(1);
}
const rResults = {};
for (let i = startIdx + 1; i < endIdx; i++) {
const parts = rLines[i].split('\t');
if (parts.length === 2) {
rResults[parts[0]] = parts[1];
}
}
let rPass = 0;
let rFail = 0;
for (const [input, expected] of TEST_CASES) {
if (input == null || input === undefined || input === '') continue;
const rSlug = rResults[input];
if (rSlug === expected) {
rPass++;
} else {
rFail++;
console.log(` βœ— R FAIL: "${input}" β†’ "${rSlug}" (expected "${expected}")`);
}
}
console.log(`R: ${rPass} passed, ${rFail} failed out of ${rTestInputs.length} (excl null/undefined/empty)\n`);
// ═══════════════════════════════════════════════════════════════
// Cross-layer comparison: R vs JS
// ═══════════════════════════════════════════════════════════════
let crossPass = 0;
let crossFail = 0;
for (const [input] of TEST_CASES) {
if (input == null || input === undefined || input === '') continue;
const jsSlug = jsResults[input];
const rSlug = rResults[input];
if (jsSlug === rSlug) {
crossPass++;
} else {
crossFail++;
console.log(` βœ— MISMATCH: "${input}"\n JS: "${jsSlug}"\n R: "${rSlug}"`);
}
}
console.log(`Cross-layer (R↔JS): ${crossPass} matched, ${crossFail} mismatched\n`);
// ═══════════════════════════════════════════════════════════════
// Summary
// ═══════════════════════════════════════════════════════════════
const totalFail = jsFail + rFail + crossFail;
if (totalFail > 0) {
console.log(`\n❌ ${totalFail} total failures`);
process.exit(1);
} else {
console.log('βœ… All tests passed β€” R and JS produce identical slugs');
process.exit(0);
}