from __future__ import annotations import copy import importlib.util import sys import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SPEC = importlib.util.spec_from_file_location( "abi_contract", ROOT / "scripts" / "abi_contract.py" ) assert SPEC is not None and SPEC.loader is not None ABI = importlib.util.module_from_spec(SPEC) sys.modules[SPEC.name] = ABI SPEC.loader.exec_module(ABI) class AbiContractTests(unittest.TestCase): def setUp(self) -> None: self.contract = ABI.load_contract( ROOT / "abi" / "echoion-module-v1.json" ) def classify(self, updated: object, old: str = "a", new: str = "b") -> str: return ABI.classify(self.contract, updated, old, new, "module") def test_canonical_hash_is_stable(self) -> None: reordered = { key: self.contract[key] for key in reversed(self.contract.keys()) } self.assertEqual( ABI.contract_hash(self.contract), ABI.contract_hash(reordered) ) def test_unchanged_source_reuses_version_and_artifact(self) -> None: self.assertEqual( ABI.classify( self.contract, copy.deepcopy(self.contract), "same", "same", "module" ), "unchanged", ) self.assertEqual(ABI.derive_version("2.0.0", "unchanged"), "2.0.0") def test_implementation_only_change_increments_patch(self) -> None: self.assertEqual(self.classify(copy.deepcopy(self.contract)), "patch") self.assertEqual(ABI.derive_version("2.0.0", "patch"), "2.0.1") def test_append_only_change_increments_minor(self) -> None: updated = copy.deepcopy(self.contract) updated["types"][0]["fields"].append( { "name": "future_field", "type": "uint64_t", "ownership": "value", } ) self.assertEqual(self.classify(updated), "minor") self.assertEqual(ABI.derive_version("2.3.9", "minor"), "2.4.0") def test_reordered_retyped_and_renamed_fields_are_breaking(self) -> None: for mutate in ( lambda fields: fields.reverse(), lambda fields: fields[0].update(type="uint64_t"), lambda fields: fields[0].update(name="renamed"), ): with self.subTest(mutate=mutate): updated = copy.deepcopy(self.contract) mutate(updated["types"][0]["fields"]) self.assertEqual(self.classify(updated), "major") self.assertEqual(ABI.derive_version("2.3.9", "major"), "3.0.0") def test_contract_change_without_source_change_is_rejected(self) -> None: updated = copy.deepcopy(self.contract) updated["types"].append({"name": "future", "fields": []}) with self.assertRaisesRegex( ValueError, "without a source SHA change" ): self.classify(updated, "same", "same") def test_executable_and_assets_changes_increment_patch(self) -> None: incompatible = {"schemaVersion": 1} for kind in ("executable", "assets"): with self.subTest(kind=kind): self.assertEqual( ABI.classify( self.contract, incompatible, "old", "new", kind ), "patch", ) if __name__ == "__main__": unittest.main()