| 1 |
import warnings |
| 2 |
|
| 3 |
import asdf |
| 4 |
import pytest |
| 5 |
from asdf.testing import helpers |
| 6 |
from astropy import units |
| 7 |
|
| 8 |
|
| 9 |
def vounit_compatible(unit): |
| 10 |
with warnings.catch_warnings(): |
| 11 |
warnings.simplefilter("ignore", category=units.UnitsWarning) |
| 12 |
try: |
| 13 |
unit.to_string(format="vounit") |
| 14 |
except Exception: # noqa: BLE001 |
| 15 |
return False |
| 16 |
|
| 17 |
return True |
| 18 |
|
| 19 |
|
| 20 |
def create_vounits(): |
| 21 |
return sorted( |
| 22 |
{u for u in list(units.__dict__.values()) if isinstance(u, units.UnitBase) and vounit_compatible(u)}, |
| 23 |
key=str, |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
def create_non_vounits(): |
| 28 |
return sorted( |
| 29 |
{u for u in list(units.__dict__.values()) if isinstance(u, units.UnitBase) and not vounit_compatible(u)}, |
| 30 |
key=str, |
| 31 |
) |
| 32 |
|
| 33 |
|
| 34 |
@pytest.mark.parametrize("unit", create_vounits()) |
| 35 |
def test_vounit_serialization(unit, tmp_path): |
| 36 |
file_path = tmp_path / "test.asdf" |
| 37 |
with asdf.AsdfFile() as af: |
| 38 |
af["unit"] = unit |
| 39 |
af.write_to(file_path) |
| 40 |
|
| 41 |
with asdf.open(file_path) as af: |
| 42 |
assert af["unit"].is_equivalent(unit) |
| 43 |
|
| 44 |
with file_path.open() as f: |
| 45 |
assert "!unit/unit-" in f.read() |
| 46 |
|
| 47 |
|
| 48 |
@pytest.mark.parametrize("unit", create_non_vounits()) |
| 49 |
def test_non_vounit_serialization(unit, tmp_path): |
| 50 |
file_path = tmp_path / "test.asdf" |
| 51 |
with asdf.AsdfFile() as af: |
| 52 |
af["unit"] = unit |
| 53 |
af.write_to(file_path) |
| 54 |
|
| 55 |
with asdf.open(file_path) as af: |
| 56 |
assert af["unit"].is_equivalent(unit) |
| 57 |
|
| 58 |
with file_path.open() as f: |
| 59 |
assert "tag:astropy.org:astropy/units/unit-" in f.read() |
| 60 |
|
| 61 |
|
| 62 |
def test_read(): |
| 63 |
yaml = """ |
| 64 |
unit: !unit/unit-1.0.0 "2.1798721 10-18kg m2 s-2" |
| 65 |
""" |
| 66 |
buff = helpers.yaml_to_asdf(yaml) |
| 67 |
with asdf.open(buff) as af: |
| 68 |
assert af["unit"].is_equivalent(units.Ry) |