|
| 1 | +import numpy as np |
| 2 | +import pytest |
| 3 | + |
| 4 | +import asdf |
| 5 | +from asdf._commands import main |
| 6 | + |
| 7 | + |
| 8 | +@pytest.fixture() |
| 9 | +def valid_file_path(tmp_path): |
| 10 | + path = tmp_path / "valid_file.asdf" |
| 11 | + asdf.dump({"foo": 42, "arr": np.arange(42)}, path) |
| 12 | + return path |
| 13 | + |
| 14 | + |
| 15 | +@pytest.fixture() |
| 16 | +def invalid_file_path(tmp_path): |
| 17 | + # don't use asdf as we're intentionally making an invalid file |
| 18 | + contents = b"""#ASDF 1.0.0 |
| 19 | +#ASDF_STANDARD 1.6.0 |
| 20 | +%YAML 1.1 |
| 21 | +%TAG ! tag:stsci.edu:asdf/ |
| 22 | +--- !core/asdf-1.1.0 |
| 23 | +arr: !core/ndarray-1.1.0 |
| 24 | + data: |
| 25 | + nested: error |
| 26 | +...""" |
| 27 | + path = tmp_path / "invalid_file.asdf" |
| 28 | + with path.open("wb") as f: |
| 29 | + f.write(contents) |
| 30 | + return path |
| 31 | + |
| 32 | + |
| 33 | +@pytest.fixture() |
| 34 | +def custom_schema_path(tmp_path): |
| 35 | + contents = """%YAML 1.1 |
| 36 | +--- |
| 37 | +id: "http://example.com/schemas/your-custom-schema" |
| 38 | +$schema: "http://stsci.edu/schemas/yaml-schema/draft-01" |
| 39 | +type: object |
| 40 | +properties: |
| 41 | + foo: |
| 42 | + type: string""" |
| 43 | + path = tmp_path / "custom_schema.yaml" |
| 44 | + with path.open("w") as f: |
| 45 | + f.write(contents) |
| 46 | + return path |
| 47 | + |
| 48 | + |
| 49 | +@pytest.fixture() |
| 50 | +def bad_blocks_file_path(tmp_path): |
| 51 | + to_replace = b"REPLACE" |
| 52 | + replacement = b"ABCDEFG" |
| 53 | + buff = asdf.dumps({"arr": np.frombuffer(to_replace, np.uint8)}) |
| 54 | + buff = buff.replace(to_replace, replacement) |
| 55 | + path = tmp_path / "bad_block.asdf" |
| 56 | + with path.open("wb") as f: |
| 57 | + f.write(buff) |
| 58 | + return path |
| 59 | + |
| 60 | + |
| 61 | +def test_valid(capsys, valid_file_path): |
| 62 | + assert main.main_from_args(["validate", str(valid_file_path)]) == 0 |
| 63 | + |
| 64 | + captured = capsys.readouterr() |
| 65 | + assert "valid" in captured.out |
| 66 | + |
| 67 | + |
| 68 | +def test_invalid(invalid_file_path): |
| 69 | + with pytest.raises(asdf.ValidationError): |
| 70 | + main.main_from_args(["validate", str(invalid_file_path)]) |
| 71 | + |
| 72 | + |
| 73 | +def test_custom_schema(valid_file_path, custom_schema_path): |
| 74 | + with pytest.raises(asdf.ValidationError): |
| 75 | + main.main_from_args(["validate", str(valid_file_path), "--custom-schema", str(custom_schema_path)]) |
| 76 | + |
| 77 | + |
| 78 | +def test_block_checksum(bad_blocks_file_path): |
| 79 | + with pytest.raises(ValueError, match="does not match given checksum"): |
| 80 | + main.main_from_args(["validate", str(bad_blocks_file_path)]) |
| 81 | + |
| 82 | + |
| 83 | +def test_skip_block_validation(bad_blocks_file_path): |
| 84 | + assert main.main_from_args(["validate", str(bad_blocks_file_path), "--skip-block-validation"]) == 0 |
0 commit comments