Skip to content

Commit a7a33ce

Browse files
committed
Add from_json metadata convenience wrapper
Add convenience wrapper that takes a json string and passes it to from_dict to create a Metadata object. Signed-off-by: Lukas Puehringer <[email protected]>
1 parent 1cdae24 commit a7a33ce

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

tests/test_api.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,25 @@ def test_generic_read(self):
8989
('timestamp', Timestamp),
9090
('targets', Targets)]:
9191

92+
# Load JSON-formatted metdata of each supported type from file
93+
# and from out-of-band read JSON string
9294
path = os.path.join(self.repo_dir, 'metadata', metadata + '.json')
9395
metadata_obj = Metadata.from_json_file(path)
96+
with open(path, 'rb') as f:
97+
metadata_str = f.read()
98+
metadata_obj2 = Metadata.from_json(metadata_str)
9499

95-
# Assert that generic method instantiates the right inner class for
96-
# each metadata type
100+
# Assert that both methods instantiate the right inner class for
101+
# each metadata type and ...
97102
self.assertTrue(
98103
isinstance(metadata_obj.signed, inner_metadata_cls))
104+
self.assertTrue(
105+
isinstance(metadata_obj2.signed, inner_metadata_cls))
106+
107+
# ... and return the same object (compared by dict representation)
108+
self.assertDictEqual(
109+
metadata_obj.to_dict(), metadata_obj2.to_dict())
110+
99111

100112
# Assert that it chokes correctly on an unknown metadata type
101113
bad_metadata_path = 'bad-metadata.json'

tuf/api/metadata.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@
2929
import tempfile
3030

3131
from securesystemslib.formats import encode_canonical
32-
from securesystemslib.util import load_json_file, persist_temp_file
32+
from securesystemslib.util import (
33+
load_json_file,
34+
load_json_string,
35+
persist_temp_file
36+
)
3337
from securesystemslib.storage import StorageBackendInterface
3438
from securesystemslib.keys import create_signature, verify_signature
3539
from tuf.repository_lib import (
@@ -80,6 +84,24 @@ def to_dict(self) -> JsonDict:
8084
'signed': self.signed.to_dict()
8185
}
8286

87+
@classmethod
88+
def from_json(cls, metadata_json: str) -> 'Metadata':
89+
"""Loads JSON-formatted TUF metadata from a string.
90+
91+
Arguments:
92+
metadata_json: TUF metadata in JSON-string representation.
93+
94+
Raises:
95+
securesystemslib.exceptions.Error, ValueError, KeyError: The
96+
metadata cannot be parsed.
97+
98+
Returns:
99+
A TUF Metadata object.
100+
101+
"""
102+
return cls.from_dict(load_json_string(metadata_json))
103+
104+
83105
def to_json(self, compact: bool = False) -> None:
84106
"""Returns the optionally compacted JSON representation of self. """
85107
return json.dumps(

0 commit comments

Comments
 (0)