Skip to content

Commit

Permalink
Add very basic json validation.
Browse files Browse the repository at this point in the history
  • Loading branch information
bloodearnest committed Oct 16, 2023
1 parent afd022d commit d81b3f6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
17 changes: 17 additions & 0 deletions sacro/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ def load_from_path(path):
class ACROOutputs(dict):
"""An ACRO json output file"""

class InvalidFile(Exception):
pass

path: Path
version: str = None
config: dict = field(default_factory=dict)
Expand All @@ -30,6 +33,20 @@ def __post_init__(self):
if config_path.exists():
self.config = json.loads(config_path.read_text())

# super basic structural validation
try:
assert "version" in self.raw_metadata
assert "results" in self.raw_metadata
assert len(self.raw_metadata["results"]) > 0
for result in self.raw_metadata["results"].values():
assert "files" in result
assert len(result["files"]) > 0
for filedata in result["files"]:
assert "name" in filedata

except AssertionError as exc:
raise self.InvalidFile(f"{self.path} is not a valid ACRO json file: {exc}")

self.version = self.raw_metadata["version"]
self.update(self.raw_metadata["results"])
self.annotate()
Expand Down
24 changes: 24 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import json

import pytest

from sacro import models


def test_outputs_annotation(test_outputs):
assert test_outputs.version == "0.4.0"
for metadata in test_outputs.values():
Expand Down Expand Up @@ -30,3 +37,20 @@ def test_outputs_annotation_checksum_failed(test_outputs):

assert test_outputs[first_output]["files"][0]["checksum"] == "bad checksum"
assert test_outputs[first_output]["files"][0]["checksum_valid"] is False


@pytest.mark.parametrize(
"data",
[
{},
{"version": "1"},
{"version": "1", "results": {}},
{"version": "1", "results": {"name": {"files": []}}},
{"version": "1", "results": {"name": {"notfiles": "foo"}}},
],
)
def test_validation(data, tmp_path):
bad_json = tmp_path / "bad.json"
bad_json.write_text(json.dumps(data))
with pytest.raises(models.ACROOutputs.InvalidFile):
models.ACROOutputs(bad_json)

0 comments on commit d81b3f6

Please sign in to comment.