Skip to content

Commit

Permalink
Metadata API: Don't do equality comparisons on containers
Browse files Browse the repository at this point in the history
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 and ValueErrors if file format structure is incorrect.

Signed-off-by: Jussi Kukkonen <[email protected]>
  • Loading branch information
Jussi Kukkonen committed May 14, 2021
1 parent aa480b1 commit 73a8f24
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
8 changes: 8 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,14 @@ def test_delegation_class(self):
delegations = Delegations.from_dict(copy.deepcopy(delegations_dict))
self.assertEqual(delegations_dict, delegations.to_dict())

# Test some basic missing data
invalid_delegations_dicts = [
{},
{"keys":{}, "roles":[]},
]
for d in invalid_delegations_dicts:
with self.assertRaises(KeyError):
Targets.from_dict(d)

def test_metadata_targets(self):
targets_path = os.path.join(
Expand Down
11 changes: 7 additions & 4 deletions tuf/api/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -909,17 +909,20 @@ def from_dict(cls, targets_dict: Dict[str, Any]) -> "Targets":
"""Creates Targets object from its dict representation."""
common_args = cls._common_fields_from_dict(targets_dict)
targets = targets_dict.pop("targets")
delegations = targets_dict.pop("delegations", None)
if delegations:
delegations = Delegations.from_dict(delegations)
try:
delegations_dict = targets_dict.pop("delegations")
except KeyError:
delegations = None
else:
delegations = Delegations.from_dict(delegations_dict)
# All fields left in the targets_dict are unrecognized.
return cls(*common_args, targets, delegations, targets_dict)

def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
targets_dict = self._common_fields_to_dict()
targets_dict["targets"] = self.targets
if self.delegations:
if self.delegations is not None:
targets_dict["delegations"] = self.delegations.to_dict()
return targets_dict

Expand Down

0 comments on commit 73a8f24

Please sign in to comment.