Skip to content

Commit

Permalink
Add more checks for the Compendium JSON data
Browse files Browse the repository at this point in the history
  • Loading branch information
markbandstra committed Mar 28, 2022
1 parent ea2f026 commit bdf9281
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
13 changes: 12 additions & 1 deletion becquerel/tools/materials_compendium.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import warnings
import numpy as np
import pandas as pd
from .materials_error import MaterialsWarning
from .materials_error import MaterialsWarning, MaterialsError

FNAME = os.path.join(os.path.split(__file__)[0], "MaterialsCompendium.json")

Expand Down Expand Up @@ -64,8 +64,19 @@ def fetch_compendium_data():
print("Pre-March 2022 JSON detected")
elif isinstance(data, dict):
print("Post-March 2022 JSON detected")
if "siteVersion" not in data.keys() or "data" not in data.keys():
raise MaterialsError(
"Attempt to read Compendium JSON failed; "
"dictionary must have keys 'siteVersion' "
"and 'data' but have keys " + str(list(data.keys()))
)
print(f"Compendium data - site version: {data['siteVersion']}")
data = data["data"]
else:
raise MaterialsError(
"Attempt to read Compendium JSON failed; "
"object must be a list or dict but is a " + str(type(data))
)
names = [datum["Name"] for datum in data]
formulae = [datum["Formula"] if "Formula" in datum else "-" for datum in data]
densities = [datum["Density"] for datum in data]
Expand Down
25 changes: 25 additions & 0 deletions tests/materials_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,31 @@ def test_materials_dummy_compendium_2022():
with pytest.warns(None) as record:
materials._load_and_compile_materials()
assert len(record) == 0, "Expected no MaterialsWarnings to be raised"
# remove siteVersion and make sure there is an error raised
del data["siteVersion"]
with open(materials_compendium.FNAME, "w") as f:
json.dump(data, f, indent=4)
with pytest.raises(MaterialsError):
materials._load_and_compile_materials()
# remove the dummy file and point back to original
os.remove(materials_compendium.FNAME)
materials_compendium.FNAME = fname_orig


@pytest.mark.webtest
def test_materials_dummy_compendium_error():
"""Test fetch_materials with a dummy Compendium JSON file.
The dummy JSON file returns something that is not a list or dict.
"""
# point to an generate a dummy JSON file
fname_orig = materials_compendium.FNAME
materials_compendium.FNAME = fname_orig[:-5] + "_dummy.json"
data = None
with open(materials_compendium.FNAME, "w") as f:
json.dump(data, f, indent=4)
with pytest.raises(MaterialsError):
materials._load_and_compile_materials()
# remove the dummy file and point back to original
os.remove(materials_compendium.FNAME)
materials_compendium.FNAME = fname_orig
Expand Down

0 comments on commit bdf9281

Please sign in to comment.