Skip to content

Commit 14f5957

Browse files
author
Jussi Kukkonen
committed
Metadata API: Don't do equality comparisons on containers
Use either "if X is not None:" or a try-except instead of a "if X:". I believe Targets.from_dict() was not really broken with previous code but it looks suspicious and did fail the added test with a strange exception: I expect the from_dict() methods to mainly fail with KeyErrors, ValueErrors or AttributeErrors if file format structure is incorrect. Signed-off-by: Jussi Kukkonen <jkukkonen@vmware.com>
1 parent aa480b1 commit 14f5957

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

tests/test_api.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,21 @@ def test_delegation_class(self):
497497
delegations = Delegations.from_dict(copy.deepcopy(delegations_dict))
498498
self.assertEqual(delegations_dict, delegations.to_dict())
499499

500+
# empty keys and roles
501+
delegations_dict = {"keys":{}, "roles":[]}
502+
delegations = Delegations.from_dict(delegations_dict.copy())
503+
self.assertEqual(delegations_dict, delegations.to_dict())
504+
505+
# Test some basic missing or broken input
506+
invalid_delegations_dicts = [
507+
{},
508+
{"keys":None, "roles":None},
509+
{"keys":{"foo":0}, "roles":[]},
510+
{"keys":{}, "roles":["foo"]},
511+
]
512+
for d in invalid_delegations_dicts:
513+
with self.assertRaises((KeyError, AttributeError)):
514+
Delegations.from_dict(d)
500515

501516
def test_metadata_targets(self):
502517
targets_path = os.path.join(

tuf/api/metadata.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -909,17 +909,20 @@ def from_dict(cls, targets_dict: Dict[str, Any]) -> "Targets":
909909
"""Creates Targets object from its dict representation."""
910910
common_args = cls._common_fields_from_dict(targets_dict)
911911
targets = targets_dict.pop("targets")
912-
delegations = targets_dict.pop("delegations", None)
913-
if delegations:
914-
delegations = Delegations.from_dict(delegations)
912+
try:
913+
delegations_dict = targets_dict.pop("delegations")
914+
except KeyError:
915+
delegations = None
916+
else:
917+
delegations = Delegations.from_dict(delegations_dict)
915918
# All fields left in the targets_dict are unrecognized.
916919
return cls(*common_args, targets, delegations, targets_dict)
917920

918921
def to_dict(self) -> Dict[str, Any]:
919922
"""Returns the dict representation of self."""
920923
targets_dict = self._common_fields_to_dict()
921924
targets_dict["targets"] = self.targets
922-
if self.delegations:
925+
if self.delegations is not None:
923926
targets_dict["delegations"] = self.delegations.to_dict()
924927
return targets_dict
925928

0 commit comments

Comments
 (0)