| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
import argparse |
| 20 |
import difflib |
| 21 |
import os |
| 22 |
from pathlib import Path |
| 23 |
import shutil |
| 24 |
import subprocess |
| 25 |
import tempfile |
| 26 |
import unittest |
| 27 |
from unittest import mock |
| 28 |
|
| 29 |
|
| 30 |
CONFIGS = [ |
| 31 |
"s2hk", |
| 32 |
"s2hk_jieba", |
| 33 |
"s2hkp", |
| 34 |
"s2hkp_jieba", |
| 35 |
"s2t", |
| 36 |
"s2t_jieba", |
| 37 |
"s2tw", |
| 38 |
"s2tw_jieba", |
| 39 |
"s2twp", |
| 40 |
"s2twp_jieba", |
| 41 |
] |
| 42 |
|
| 43 |
INPUTS = [ |
| 44 |
"us_constitution_zhs.txt", |
| 45 |
] |
| 46 |
|
| 47 |
|
| 48 |
def _workspace_root() -> Path: |
| 49 |
return Path(__file__).resolve().parents[2] |
| 50 |
|
| 51 |
|
| 52 |
class Runfiles: |
| 53 |
def __init__(self) -> None: |
| 54 |
self.manifest = {} |
| 55 |
manifest_path = os.environ.get("RUNFILES_MANIFEST_FILE") |
| 56 |
if manifest_path and Path(manifest_path).is_file(): |
| 57 |
with open(manifest_path, encoding="utf-8") as manifest: |
| 58 |
for line in manifest: |
| 59 |
line = line.rstrip("\n") |
| 60 |
if not line: |
| 61 |
continue |
| 62 |
key, value = self._parse_manifest_line(line) |
| 63 |
if key: |
| 64 |
self.manifest[key] = value |
| 65 |
|
| 66 |
self.runfiles_dirs = [ |
| 67 |
Path(value) |
| 68 |
for value in ( |
| 69 |
os.environ.get("TEST_SRCDIR"), |
| 70 |
os.environ.get("RUNFILES_DIR"), |
| 71 |
) |
| 72 |
if value |
| 73 |
] |
| 74 |
self.workspace_names = [ |
| 75 |
name |
| 76 |
for name in ( |
| 77 |
os.environ.get("TEST_WORKSPACE"), |
| 78 |
"_main", |
| 79 |
"opencc", |
| 80 |
) |
| 81 |
if name |
| 82 |
] |
| 83 |
|
| 84 |
@staticmethod |
| 85 |
def _parse_manifest_line(line: str) -> tuple[str, str]: |
| 86 |
if not line.startswith(" "): |
| 87 |
key, _, value = line.partition(" ") |
| 88 |
return key, value or key |
| 89 |
|
| 90 |
parts = [] |
| 91 |
current = [] |
| 92 |
escaped = False |
| 93 |
for char in line[1:]: |
| 94 |
if escaped: |
| 95 |
current.append("\\" + char) |
| 96 |
escaped = False |
| 97 |
continue |
| 98 |
if char == "\\": |
| 99 |
escaped = True |
| 100 |
continue |
| 101 |
if char == " " and len(parts) == 0: |
| 102 |
parts.append("".join(current)) |
| 103 |
current = [] |
| 104 |
continue |
| 105 |
current.append(char) |
| 106 |
parts.append("".join(current)) |
| 107 |
|
| 108 |
if len(parts) != 2: |
| 109 |
return "", "" |
| 110 |
return tuple(Runfiles._unescape_manifest_field(part) for part in parts) |
| 111 |
|
| 112 |
@staticmethod |
| 113 |
def _unescape_manifest_field(value: str) -> str: |
| 114 |
return ( |
| 115 |
value.replace("\\s", " ") |
| 116 |
.replace("\\n", "\n") |
| 117 |
.replace("\\b", "\\") |
| 118 |
) |
| 119 |
|
| 120 |
def rlocation(self, relative_path: str) -> Path: |
| 121 |
candidates = [] |
| 122 |
for workspace in self.workspace_names: |
| 123 |
candidates.append(f"{workspace}/{relative_path}") |
| 124 |
candidates.append(relative_path) |
| 125 |
|
| 126 |
for candidate in candidates: |
| 127 |
if candidate in self.manifest: |
| 128 |
return Path(self.manifest[candidate]) |
| 129 |
path = self._lookup_manifest_prefix(candidate) |
| 130 |
if path is not None: |
| 131 |
return path |
| 132 |
|
| 133 |
for runfiles_dir in self.runfiles_dirs: |
| 134 |
for candidate in candidates: |
| 135 |
path = runfiles_dir / candidate |
| 136 |
if path.exists(): |
| 137 |
return path |
| 138 |
|
| 139 |
source_path = _workspace_root() / relative_path |
| 140 |
if source_path.exists(): |
| 141 |
return source_path |
| 142 |
|
| 143 |
raise FileNotFoundError(f"Could not locate runfile: {relative_path}") |
| 144 |
|
| 145 |
def _lookup_manifest_prefix(self, candidate: str) -> Path | None: |
| 146 |
current = candidate |
| 147 |
suffix_parts = [] |
| 148 |
while "/" in current: |
| 149 |
current, _, suffix = current.rpartition("/") |
| 150 |
suffix_parts.append(suffix) |
| 151 |
if current in self.manifest: |
| 152 |
return Path(self.manifest[current]).joinpath(*reversed(suffix_parts)) |
| 153 |
return None |
| 154 |
|
| 155 |
|
| 156 |
def _default_opencc_command(runfiles: Runfiles) -> Path: |
| 157 |
env_value = os.environ.get("OPENCC_COMMAND") |
| 158 |
if env_value: |
| 159 |
return Path(env_value) |
| 160 |
|
| 161 |
for candidate in [ |
| 162 |
"src/tools/command_line.exe", |
| 163 |
"src/tools/command_line", |
| 164 |
]: |
| 165 |
try: |
| 166 |
command = runfiles.rlocation(candidate) |
| 167 |
except FileNotFoundError: |
| 168 |
continue |
| 169 |
if command.is_file(): |
| 170 |
return command |
| 171 |
|
| 172 |
for command in [ |
| 173 |
_workspace_root() / "bazel-bin/src/tools/command_line.exe", |
| 174 |
_workspace_root() / "bazel-bin/src/tools/command_line", |
| 175 |
]: |
| 176 |
if command.exists(): |
| 177 |
return command |
| 178 |
|
| 179 |
raise FileNotFoundError("Could not locate command_line executable") |
| 180 |
|
| 181 |
|
| 182 |
def _default_dict_dir(runfiles: Runfiles) -> Path: |
| 183 |
env_value = os.environ.get("OPENCC_DICT_DIR") |
| 184 |
if env_value: |
| 185 |
return Path(env_value) |
| 186 |
try: |
| 187 |
return runfiles.rlocation("data/dictionary/STCharacters.ocd2").parent |
| 188 |
except FileNotFoundError: |
| 189 |
dict_file = _workspace_root() / "bazel-bin/data/dictionary/STCharacters.ocd2" |
| 190 |
if dict_file.exists(): |
| 191 |
return dict_file.parent |
| 192 |
raise |
| 193 |
|
| 194 |
|
| 195 |
def _default_config_dir(runfiles: Runfiles) -> Path: |
| 196 |
env_value = os.environ.get("OPENCC_CONFIG_DIR") |
| 197 |
if env_value: |
| 198 |
return Path(env_value) |
| 199 |
return runfiles.rlocation("data/config/s2t.json").parent |
| 200 |
|
| 201 |
|
| 202 |
def _default_jieba_config_dir(runfiles: Runfiles) -> Path: |
| 203 |
env_value = os.environ.get("OPENCC_JIEBA_CONFIG_DIR") |
| 204 |
if env_value: |
| 205 |
return Path(env_value) |
| 206 |
return runfiles.rlocation("plugins/jieba/data/config/s2twp_jieba.json").parent |
| 207 |
|
| 208 |
|
| 209 |
def _default_jieba_plugin_dir(runfiles: Runfiles) -> Path: |
| 210 |
env_value = os.environ.get("OPENCC_JIEBA_PLUGIN_DIR") |
| 211 |
if env_value: |
| 212 |
return Path(env_value) |
| 213 |
|
| 214 |
candidates = [ |
| 215 |
"plugins/jieba/libopencc-jieba.dylib", |
| 216 |
"plugins/jieba/libopencc-jieba.so", |
| 217 |
"plugins/jieba/opencc-jieba.dll", |
| 218 |
"plugins/jieba/opencc-jieba", |
| 219 |
] |
| 220 |
for candidate in candidates: |
| 221 |
try: |
| 222 |
path = runfiles.rlocation(candidate) |
| 223 |
except FileNotFoundError: |
| 224 |
continue |
| 225 |
if path.is_file(): |
| 226 |
return path.parent |
| 227 |
|
| 228 |
for candidate in [ |
| 229 |
_workspace_root() / "bazel-bin/plugins/jieba/libopencc-jieba.dylib", |
| 230 |
_workspace_root() / "bazel-bin/plugins/jieba/libopencc-jieba.so", |
| 231 |
_workspace_root() / "bazel-bin/plugins/jieba/opencc-jieba.dll", |
| 232 |
_workspace_root() / "bazel-bin/plugins/jieba/opencc-jieba.exe", |
| 233 |
_workspace_root() / "bazel-bin/plugins/jieba/opencc-jieba", |
| 234 |
]: |
| 235 |
if candidate.is_file(): |
| 236 |
return candidate.parent |
| 237 |
|
| 238 |
raise FileNotFoundError("Could not locate opencc-jieba plugin") |
| 239 |
|
| 240 |
|
| 241 |
def _default_jieba_resource_dir(runfiles: Runfiles) -> Path: |
| 242 |
env_value = os.environ.get("OPENCC_JIEBA_RESOURCE_DIR") |
| 243 |
if env_value: |
| 244 |
return Path(env_value) |
| 245 |
try: |
| 246 |
return runfiles.rlocation("plugins/jieba/jieba_dict/jieba_merged.ocd2").parent.parent |
| 247 |
except FileNotFoundError: |
| 248 |
resource = _workspace_root() / "bazel-bin/plugins/jieba/jieba_dict/jieba_merged.ocd2" |
| 249 |
if resource.exists(): |
| 250 |
return resource.parent.parent |
| 251 |
raise |
| 252 |
|
| 253 |
|
| 254 |
def convert( |
| 255 |
command: Path, |
| 256 |
dict_dir: Path, |
| 257 |
input_path: Path, |
| 258 |
output_path: Path, |
| 259 |
config_path: Path, |
| 260 |
extra_paths: list[Path], |
| 261 |
plugin_dir: Path | None, |
| 262 |
) -> None: |
| 263 |
env = os.environ.copy() |
| 264 |
if plugin_dir is not None: |
| 265 |
env["OPENCC_SEGMENTATION_PLUGIN_PATH"] = str(plugin_dir) |
| 266 |
|
| 267 |
subprocess.run( |
| 268 |
[ |
| 269 |
str(command), |
| 270 |
"-i", |
| 271 |
str(input_path), |
| 272 |
"-o", |
| 273 |
str(output_path), |
| 274 |
"-c", |
| 275 |
str(config_path), |
| 276 |
"--path", |
| 277 |
str(dict_dir), |
| 278 |
] |
| 279 |
+ [ |
| 280 |
item |
| 281 |
for path in extra_paths |
| 282 |
for item in ("--path", str(path)) |
| 283 |
], |
| 284 |
check=True, |
| 285 |
env=env, |
| 286 |
) |
| 287 |
|
| 288 |
|
| 289 |
def output_name(input_name: str, config: str) -> str: |
| 290 |
return f"{Path(input_name).stem}.{config}.txt" |
| 291 |
|
| 292 |
|
| 293 |
class GoldenConvertTest(unittest.TestCase): |
| 294 |
@classmethod |
| 295 |
def setUpClass(cls) -> None: |
| 296 |
cls.runfiles = Runfiles() |
| 297 |
cls.command = _default_opencc_command(cls.runfiles) |
| 298 |
cls.config_dir = _default_config_dir(cls.runfiles) |
| 299 |
cls.dict_dir = _default_dict_dir(cls.runfiles) |
| 300 |
cls.jieba_config_dir = _default_jieba_config_dir(cls.runfiles) |
| 301 |
cls.jieba_plugin_dir = _default_jieba_plugin_dir(cls.runfiles) |
| 302 |
cls.jieba_resource_dir = _default_jieba_resource_dir(cls.runfiles) |
| 303 |
|
| 304 |
@classmethod |
| 305 |
def config_path(cls, config: str) -> Path: |
| 306 |
if config.endswith("_jieba"): |
| 307 |
return cls.jieba_config_dir / f"{config}.json" |
| 308 |
return cls.config_dir / f"{config}.json" |
| 309 |
|
| 310 |
@classmethod |
| 311 |
def extra_paths(cls, config: str) -> list[Path]: |
| 312 |
paths = [cls.config_dir] |
| 313 |
if config.endswith("_jieba"): |
| 314 |
paths.extend([cls.jieba_config_dir, cls.jieba_resource_dir]) |
| 315 |
return paths |
| 316 |
|
| 317 |
@classmethod |
| 318 |
def plugin_dir(cls, config: str) -> Path | None: |
| 319 |
if config.endswith("_jieba"): |
| 320 |
return cls.jieba_plugin_dir |
| 321 |
return None |
| 322 |
|
| 323 |
def test_golden_outputs(self) -> None: |
| 324 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 325 |
temp_path = Path(temp_dir) |
| 326 |
for input_name in INPUTS: |
| 327 |
input_path = self.runfiles.rlocation(f"test/golden/input/{input_name}") |
| 328 |
for config in CONFIGS: |
| 329 |
with self.subTest(input=input_name, config=config): |
| 330 |
actual_path = temp_path / output_name(input_name, config) |
| 331 |
expected_path = self.runfiles.rlocation( |
| 332 |
f"test/golden/output/{output_name(input_name, config)}" |
| 333 |
) |
| 334 |
convert( |
| 335 |
self.command, |
| 336 |
self.dict_dir, |
| 337 |
input_path, |
| 338 |
actual_path, |
| 339 |
self.config_path(config), |
| 340 |
self.extra_paths(config), |
| 341 |
self.plugin_dir(config), |
| 342 |
) |
| 343 |
expected = expected_path.read_text(encoding="utf-8") |
| 344 |
actual = actual_path.read_text(encoding="utf-8") |
| 345 |
if expected != actual: |
| 346 |
diff = "".join( |
| 347 |
difflib.unified_diff( |
| 348 |
expected.splitlines(keepends=True), |
| 349 |
actual.splitlines(keepends=True), |
| 350 |
fromfile=str(expected_path), |
| 351 |
tofile=str(actual_path), |
| 352 |
) |
| 353 |
) |
| 354 |
self.fail(diff) |
| 355 |
|
| 356 |
|
| 357 |
class PathResolutionTest(unittest.TestCase): |
| 358 |
def test_default_opencc_command_accepts_windows_exe_runfile(self) -> None: |
| 359 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 360 |
command = Path(temp_dir) / "command_line.exe" |
| 361 |
command.write_text("", encoding="utf-8") |
| 362 |
runfiles = Runfiles() |
| 363 |
runfiles.manifest = { |
| 364 |
"_main/src/tools/command_line.exe": str(command), |
| 365 |
} |
| 366 |
runfiles.runfiles_dirs = [] |
| 367 |
runfiles.workspace_names = ["_main"] |
| 368 |
|
| 369 |
with mock.patch.dict(os.environ, {}, clear=True): |
| 370 |
self.assertEqual(command, _default_opencc_command(runfiles)) |
| 371 |
|
| 372 |
def test_parse_manifest_line_unescapes_escaped_entries(self) -> None: |
| 373 |
key, value = Runfiles._parse_manifest_line( |
| 374 |
r" _main/src/tools/command_line.exe C:\btmp\bpath\swith\sspaces\bbin\bcommand_line.exe" |
| 375 |
) |
| 376 |
self.assertEqual("_main/src/tools/command_line.exe", key) |
| 377 |
self.assertEqual(r"C:\tmp\path with spaces\bin\command_line.exe", value) |
| 378 |
|
| 379 |
def test_parse_manifest_line_self_maps_single_token_entries(self) -> None: |
| 380 |
key, value = Runfiles._parse_manifest_line("_main/data/config") |
| 381 |
self.assertEqual("_main/data/config", key) |
| 382 |
self.assertEqual("_main/data/config", value) |
| 383 |
|
| 384 |
def test_rlocation_resolves_files_under_manifest_directory_entries(self) -> None: |
| 385 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 386 |
config_dir = Path(temp_dir) / "config" |
| 387 |
runfiles = Runfiles() |
| 388 |
runfiles.manifest = { |
| 389 |
"_main/data/config": str(config_dir), |
| 390 |
} |
| 391 |
runfiles.runfiles_dirs = [] |
| 392 |
runfiles.workspace_names = ["_main"] |
| 393 |
|
| 394 |
self.assertEqual( |
| 395 |
config_dir / "s2t.json", |
| 396 |
runfiles.rlocation("data/config/s2t.json"), |
| 397 |
) |
| 398 |
|
| 399 |
def test_default_jieba_plugin_dir_accepts_windows_bazel_bin_fallback(self) -> None: |
| 400 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 401 |
workspace = Path(temp_dir) |
| 402 |
plugin = workspace / "bazel-bin/plugins/jieba/opencc-jieba.dll" |
| 403 |
plugin.parent.mkdir(parents=True) |
| 404 |
plugin.write_text("", encoding="utf-8") |
| 405 |
runfiles = Runfiles() |
| 406 |
runfiles.manifest = {} |
| 407 |
runfiles.runfiles_dirs = [] |
| 408 |
runfiles.workspace_names = ["_main"] |
| 409 |
|
| 410 |
with mock.patch.dict(os.environ, {}, clear=True): |
| 411 |
with mock.patch( |
| 412 |
__name__ + "._workspace_root", |
| 413 |
return_value=workspace, |
| 414 |
): |
| 415 |
self.assertEqual(plugin.parent, _default_jieba_plugin_dir(runfiles)) |
| 416 |
|
| 417 |
|
| 418 |
def update_outputs() -> None: |
| 419 |
runfiles = Runfiles() |
| 420 |
command = _default_opencc_command(runfiles) |
| 421 |
config_dir = _default_config_dir(runfiles) |
| 422 |
dict_dir = _default_dict_dir(runfiles) |
| 423 |
jieba_config_dir = _default_jieba_config_dir(runfiles) |
| 424 |
jieba_plugin_dir = _default_jieba_plugin_dir(runfiles) |
| 425 |
jieba_resource_dir = _default_jieba_resource_dir(runfiles) |
| 426 |
output_dir = _workspace_root() / "test/golden/output" |
| 427 |
output_dir.mkdir(parents=True, exist_ok=True) |
| 428 |
|
| 429 |
for input_name in INPUTS: |
| 430 |
input_path = _workspace_root() / "test/golden/input" / input_name |
| 431 |
expected_names = {output_name(input_name, config) for config in CONFIGS} |
| 432 |
for stale_path in output_dir.glob(f"{input_path.stem}.*.txt"): |
| 433 |
if stale_path.name not in expected_names: |
| 434 |
stale_path.unlink() |
| 435 |
|
| 436 |
for config in CONFIGS: |
| 437 |
if config.endswith("_jieba"): |
| 438 |
config_path = jieba_config_dir / f"{config}.json" |
| 439 |
extra_paths = [config_dir, jieba_config_dir, jieba_resource_dir] |
| 440 |
plugin_dir = jieba_plugin_dir |
| 441 |
else: |
| 442 |
config_path = config_dir / f"{config}.json" |
| 443 |
extra_paths = [config_dir] |
| 444 |
plugin_dir = None |
| 445 |
output_path = output_dir / output_name(input_name, config) |
| 446 |
with tempfile.NamedTemporaryFile(delete=False) as temp_file: |
| 447 |
temp_path = Path(temp_file.name) |
| 448 |
try: |
| 449 |
convert( |
| 450 |
command, |
| 451 |
dict_dir, |
| 452 |
input_path, |
| 453 |
temp_path, |
| 454 |
config_path, |
| 455 |
extra_paths, |
| 456 |
plugin_dir, |
| 457 |
) |
| 458 |
shutil.move(str(temp_path), output_path) |
| 459 |
output_path.chmod(0o644) |
| 460 |
finally: |
| 461 |
if temp_path.exists(): |
| 462 |
temp_path.unlink() |
| 463 |
|
| 464 |
|
| 465 |
def main() -> None: |
| 466 |
parser = argparse.ArgumentParser() |
| 467 |
parser.add_argument( |
| 468 |
"--update", |
| 469 |
action="store_true", |
| 470 |
help="regenerate files under test/golden/output", |
| 471 |
) |
| 472 |
args, remaining = parser.parse_known_args() |
| 473 |
|
| 474 |
if args.update: |
| 475 |
update_outputs() |
| 476 |
else: |
| 477 |
unittest.main(argv=[parser.prog] + remaining) |
| 478 |
|
| 479 |
|
| 480 |
if __name__ == "__main__": |
| 481 |
main() |