Debian Codegraph @

tests/test_metadata_eq_.py

raw
1 # Copyright New York University and the TUF contributors
2 # SPDX-License-Identifier: MIT OR Apache-2.0
3
4 """Test __eq__ implementations of classes inside tuf/api/metadata.py."""
5
6 from __future__ import annotations
7
8 import copy
9 import os
10 import sys
11 import unittest
12 from typing import Any, ClassVar
13
14 from securesystemslib.signer import SSlibKey
15
16 from tests import utils
17 from tuf.api.metadata import (
18 TOP_LEVEL_ROLE_NAMES,
19 DelegatedRole,
20 Delegations,
21 Metadata,
22 MetaFile,
23 Role,
24 Signature,
25 SuccinctRoles,
26 TargetFile,
27 )
28
29
30 class TestMetadataComparisons(unittest.TestCase):
31 """Test __eq__ for all classes inside tuf/api/metadata.py."""
32
33 metadata: ClassVar[dict[str, bytes]]
34
35 @classmethod
36 def setUpClass(cls) -> None:
37 cls.repo_dir = os.path.join(
38 utils.TESTS_DIR, "repository_data", "repository", "metadata"
39 )
40
41 # Store class instances in this dict instead of creating them inside the
42 # test function in order to escape the need for reinitialization of the
43 # instances on each run of the test function.
44 cls.objects = {}
45 for md in TOP_LEVEL_ROLE_NAMES:
46 with open(os.path.join(cls.repo_dir, f"{md}.json"), "rb") as f:
47 data = f.read()
48 cls.objects[md.capitalize()] = Metadata.from_bytes(data).signed
49
50 cls.objects["Metadata"] = Metadata(cls.objects["Timestamp"], {})
51 cls.objects["Signed"] = cls.objects["Timestamp"]
52 cls.objects["Key"] = SSlibKey(
53 "id", "rsa", "rsassa-pss-sha256", {"public": "foo"}
54 )
55 cls.objects["Role"] = Role(["keyid1", "keyid2"], 3)
56 cls.objects["MetaFile"] = MetaFile(1, 12, {"sha256": "abc"})
57 cls.objects["DelegatedRole"] = DelegatedRole("a", [], 1, False, ["d"])
58 cls.objects["SuccinctRoles"] = SuccinctRoles(["keyid"], 1, 8, "foo")
59 cls.objects["Delegations"] = Delegations(
60 {"keyid": cls.objects["Key"]}, {"a": cls.objects["DelegatedRole"]}
61 )
62 cls.objects["TargetFile"] = TargetFile(
63 1, {"sha256": "abc"}, "file1.txt"
64 )
65
66 # Keys are class names.
67 # Values are dictionaries containing attribute names and their new values.
68 classes_attributes_modifications = {
69 "Metadata": {"signed": None, "signatures": None},
70 "Signed": {"version": -1, "spec_version": "0.0.0"},
71 "Key": {"keyid": "a", "keytype": "foo", "scheme": "b", "keyval": "b"},
72 "Role": {"keyids": [], "threshold": 10},
73 "Root": {"consistent_snapshot": None, "keys": {}},
74 "MetaFile": {"version": None, "length": None, "hashes": {}},
75 "Timestamp": {"snapshot_meta": None},
76 "Snapshot": {"meta": None},
77 "DelegatedRole": {
78 "name": "",
79 "terminating": None,
80 "paths": [""],
81 "path_hash_prefixes": [""],
82 },
83 "SuccinctRoles": {"bit_length": 0, "name_prefix": ""},
84 "Delegations": {"keys": {}, "roles": {}},
85 "TargetFile": {"length": 0, "hashes": {}, "path": ""},
86 "Targets": {"targets": {}, "delegations": []},
87 }
88
89 @utils.run_sub_tests_with_dataset(classes_attributes_modifications)
90 def test_classes_eq_(self, test_case_data: dict[str, Any]) -> None:
91 obj = self.objects[self.case_name]
92
93 # Assert that obj is not equal to an object from another type
94 self.assertNotEqual(obj, "")
95 obj_2 = copy.deepcopy(obj)
96 # Assert that __eq__ works for equal objects.
97 self.assertEqual(obj, obj_2)
98
99 for attr, value in test_case_data.items():
100 original_value = getattr(obj_2, attr)
101 setattr(obj_2, attr, value)
102 # Assert that the original object != modified one.
103 self.assertNotEqual(obj, obj_2, f"Failed case: {attr}")
104 # Restore the old value of the attribute.
105 setattr(obj_2, attr, original_value)
106
107 def test_md_eq_signatures_reversed_order(self) -> None:
108 # Test comparing objects with same signatures but different order.
109
110 # Remove all signatures and create new ones.
111 md: Metadata = self.objects["Metadata"]
112 md.signatures = {"a": Signature("a", "a"), "b": Signature("b", "b")}
113 md_2 = copy.deepcopy(md)
114 # Reverse signatures order in md_2.
115 md_2.signatures = dict(reversed(md_2.signatures.items()))
116 # Assert that both objects are not the same because of signatures order.
117 self.assertNotEqual(md, md_2)
118
119 # but if we fix the signatures order they will be equal
120 md_2.signatures = {"a": Signature("a", "a"), "b": Signature("b", "b")}
121 self.assertEqual(md, md_2)
122
123 def test_md_eq_special_signatures_tests(self) -> None:
124 # Test that metadata objects with different signatures are not equal.
125 md: Metadata = self.objects["Metadata"]
126 md_2 = copy.deepcopy(md)
127 md_2.signatures = {}
128 self.assertNotEqual(md, md_2)
129
130 # Test that metadata objects with empty signatures are equal
131 md.signatures = {}
132 self.assertEqual(md, md_2)
133
134 # Metadata objects with different signatures types are not equal.
135 md_2.signatures = "" # type: ignore[assignment]
136 self.assertNotEqual(md, md_2)
137
138 def test_delegations_eq_roles_reversed_order(self) -> None:
139 # Test comparing objects with same delegated roles but different order.
140 role_one_dict = {
141 "keyids": ["keyid1"],
142 "name": "a",
143 "terminating": False,
144 "paths": ["fn1"],
145 "threshold": 1,
146 }
147 role_two_dict = {
148 "keyids": ["keyid2"],
149 "name": "b",
150 "terminating": True,
151 "paths": ["fn2"],
152 "threshold": 4,
153 }
154
155 delegations_dict = {
156 "keys": {
157 "keyid2": {
158 "keytype": "ed25519",
159 "scheme": "ed25519",
160 "keyval": {"public": "bar"},
161 }
162 },
163 "roles": [role_one_dict, role_two_dict],
164 }
165 delegations = Delegations.from_dict(copy.deepcopy(delegations_dict))
166
167 # Create a second delegations obj with reversed roles order
168 delegations_2 = copy.deepcopy(delegations)
169 assert isinstance(delegations.roles, dict)
170 delegations_2.roles = dict(reversed(delegations.roles.items()))
171
172 # Both objects are not the equal because of delegated roles order.
173 self.assertNotEqual(delegations, delegations_2)
174
175 # but if we fix the delegated roles order they will be equal
176 delegations_2.roles = delegations.roles
177
178 self.assertEqual(delegations, delegations_2)
179
180
181 # Run unit test.
182 if __name__ == "__main__":
183 utils.configure_test_logging(sys.argv)
184 unittest.main()