""" Bidirectional interoperability tests against the original implementation. These tests load ``chaoscrypt/legacy/chaoscrypt_legacy.py`` and prove that: * ciphertext produced by the original script decrypts with the packaged library, and * ciphertext produced by the packaged library decrypts with the original script. They are the regression guard for the promise that the algorithm itself was ported without any behavioural change. """ import importlib.util import os import pytest from chaoscrypt import ChaosCrypt KEY_PWD = "legacy-key-password" USER_PWD = "legacy-user-password" SAMPLES = [ "legacy compatibility", "兼容性检查", "x" * 300, "emoji test 🎉", "multi\nline\ttabbed", ] def _load_legacy(): """Import the legacy single-file implementation, or skip if absent.""" here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) legacy = os.path.join(here, "legacy", "chaoscrypt_legacy.py") if not os.path.exists(legacy): pytest.skip("legacy implementation not present") spec = importlib.util.spec_from_file_location("cc_legacy", legacy) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod class TestLegacyInterop: def test_library_decrypts_legacy_ciphertext(self, tmp_path): legacy_mod = _load_legacy() kf = str(tmp_path / "legacy.key") old = legacy_mod.EncryptionSystem() old.generate_keys(kf, KEY_PWD) pairs = [(tx, old.encrypt(tx, USER_PWD)) for tx in SAMPLES] new = ChaosCrypt() new.load(kf, KEY_PWD) for tx, ct in pairs: assert new.decrypt(ct, USER_PWD) == tx def test_legacy_decrypts_library_ciphertext(self, tmp_path): legacy_mod = _load_legacy() kf = str(tmp_path / "legacy2.key") new = ChaosCrypt() new.create_key(KEY_PWD, kf) old = legacy_mod.EncryptionSystem() old._load_keys(kf, KEY_PWD) for tx in SAMPLES: ct = new.encrypt(tx, USER_PWD) assert old.decrypt(ct, USER_PWD) == tx def test_key_files_are_identical_in_format(self, tmp_path): """A library key file must load in the original implementation.""" legacy_mod = _load_legacy() kf = str(tmp_path / "fmt.key") ChaosCrypt().create_key(KEY_PWD, kf) old = legacy_mod.EncryptionSystem() old._load_keys(kf, KEY_PWD) assert old.keys_loaded