Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Validate workspace specification before accessing parts of it #1953

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/pyhf/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,14 +300,15 @@ def __init__(self, spec, validate: bool = True, **config_kwargs):

"""
spec = copy.deepcopy(spec)
super().__init__(spec, channels=spec['channels'])
self.schema = config_kwargs.pop('schema', 'workspace.json')
self.version = config_kwargs.pop('version', spec.get('version', None))

# run jsonschema validation of input specification against the (provided) schema
if validate:
log.info(f"Validating spec against schema: {self.schema}")
schema.validate(self, self.schema, version=self.version)
schema.validate(spec, self.schema, version=self.version)

super().__init__(spec, channels=spec['channels'])

self.measurement_names = []
for measurement in self.get('measurements', []):
Expand Down
8 changes: 8 additions & 0 deletions tests/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -910,3 +910,11 @@ def test_workspace_without_validation(mocker, simplemodels_model_data):

pyhf.Workspace(dict(ws), validate=False)
assert pyhf.schema.validate.called is False


def test_workspace_invalid_specification():
spec = {"channels": [{"name": "SR", "samples_wrong_name": []}]}
# Ensure that an invalid specifications gets caught as such
# before a KeyError: 'samples' could be reached.
with pytest.raises(pyhf.exceptions.InvalidSpecification):
pyhf.Workspace(spec)
kratsg marked this conversation as resolved.
Show resolved Hide resolved