diff --git a/p3analysis/data/_validation.py b/p3analysis/data/_validation.py index 51c403c..7f5c181 100644 --- a/p3analysis/data/_validation.py +++ b/p3analysis/data/_validation.py @@ -3,36 +3,34 @@ import json import pkgutil +from typing import Any import jsonschema -def _validate_coverage_json(json_string: str) -> object: +def _validate_coverage_json(json_data: Any) -> object: """ - Validate coverage JSON string against schema. + Validate coverage JSON against schema. Parameters ---------- - json_string : String - The JSON string to validate. + json_data : Any + The JSON string or object to validate. Returns ------- Object - A Python object corresponding to the JSON string. + A Python object corresponding to the JSON provided. Raises ------ ValueError - If the JSON string fails to validate. - - TypeError - If the JSON string is not a string. + If the JSON fails to validate. """ - if not isinstance(json_string, str): - raise TypeError("Coverage must be a JSON string.") - - instance = json.loads(json_string) + if isinstance(json_data, str): + instance = json.loads(json_data) + else: + instance = json_data schema_string = pkgutil.get_data(__name__, "coverage-0.3.0.schema") if not schema_string: @@ -44,7 +42,7 @@ def _validate_coverage_json(json_string: str) -> object: try: jsonschema.validate(instance=instance, schema=schema) except jsonschema.exceptions.ValidationError: - msg = "Coverage string failed schema validation" + msg = "Coverage data failed schema validation" raise ValueError(msg) except jsonschema.exceptions.SchemaError: msg = "coverage-0.3.0.schema is not a valid schema" diff --git a/tests/data/test_validation.py b/tests/data/test_validation.py index f266512..39b17ee 100644 --- a/tests/data/test_validation.py +++ b/tests/data/test_validation.py @@ -13,9 +13,14 @@ class TestValidation(unittest.TestCase): def test_coverage_json_valid(self): """p3analysis.data.validation.coverage_json_valid""" + expected_object = [{"file": "path", "id": "sha", "lines": [1, 2, [3, 5]]}] + json_string = '[{"file": "path", "id": "sha", "lines": [1, 2, [3, 5]]}]' result_object = _validate_coverage_json(json_string) - expected_object = [{"file": "path", "id": "sha", "lines": [1, 2, [3, 5]]}] + self.assertTrue(result_object == expected_object) + + json_object = expected_object + result_object = _validate_coverage_json(json_object) self.assertTrue(result_object == expected_object) def test_coverage_json_invalid(self): @@ -24,7 +29,7 @@ def test_coverage_json_invalid(self): with self.assertRaises(ValueError): _validate_coverage_json(json_string) - with self.assertRaises(TypeError): + with self.assertRaises(ValueError): json_object = [{"file": "path", "id": "sha", "lines": [["1"]]}] _validate_coverage_json(json_object)