Skip to content

Commit

Permalink
refactor test_connect for new test suite
Browse files Browse the repository at this point in the history
Provides mixins for TestCosmology to test the descriptors

Signed-off-by: Nathaniel Starkman (@nstarman) <nstarkman@protonmail.com>
  • Loading branch information
nstarman committed Sep 24, 2021
1 parent d1313bb commit e1c445d
Show file tree
Hide file tree
Showing 7 changed files with 223 additions and 132 deletions.
2 changes: 1 addition & 1 deletion astropy/cosmology/core.py
Expand Up @@ -264,7 +264,7 @@ def __new__(cls, *args, **kwargs):

return self

def __init__(self, *args, name=None, meta=None, **kwargs):
def __init__(self, name=None, meta=None):
self._name = name
self.meta.update(meta or {})

Expand Down
2 changes: 1 addition & 1 deletion astropy/cosmology/io/tests/test_mapping.py
Expand Up @@ -12,7 +12,7 @@

class CosmologyWithKwargs(Cosmology):
def __init__(self, name="cosmology with kwargs", meta=None, **kwargs):
super().__init__(name=name, meta=meta, **kwargs)
super().__init__(name=name, meta=meta)


cosmo_instances = [
Expand Down
76 changes: 76 additions & 0 deletions astropy/cosmology/tests/conftest.py
Expand Up @@ -5,13 +5,89 @@
##############################################################################
# IMPORTS

# STDLIB
import json
import os

import pytest

import astropy.units as u
from astropy.cosmology import core
from astropy.cosmology.core import Cosmology
from astropy.utils.misc import isiterable

###############################################################################
# FUNCTIONS


def read_json(filename, **kwargs):
"""Read JSON.
Parameters
----------
filename : str
**kwargs
Keyword arguments into :meth:`~astropy.cosmology.Cosmology.from_format`
Returns
-------
`~astropy.cosmology.Cosmology` instance
"""
# read
if isinstance(filename, (str, bytes, os.PathLike)):
with open(filename, "r") as file:
data = file.read()
else: # file-like : this also handles errors in dumping
data = filename.read()

mapping = json.loads(data) # parse json mappable to dict

# deserialize Quantity
for k, v in mapping.items():
if isinstance(v, dict) and "value" in v and "unit" in v:
mapping[k] = u.Quantity(v["value"], v["unit"])
for k, v in mapping.get("meta", {}).items(): # also the metadata
if isinstance(v, dict) and "value" in v and "unit" in v:
mapping["meta"][k] = u.Quantity(v["value"], v["unit"])

return Cosmology.from_format(mapping, **kwargs)


def write_json(cosmology, file, *, overwrite=False):
"""Write Cosmology to JSON.
Parameters
----------
cosmology : `astropy.cosmology.Cosmology` subclass instance
file : path-like or file-like
overwrite : bool (optional, keyword-only)
"""
data = cosmology.to_format("mapping") # start by turning into dict
data["cosmology"] = data["cosmology"].__qualname__

# serialize Quantity
for k, v in data.items():
if isinstance(v, u.Quantity):
data[k] = {"value": v.value.tolist(), "unit": str(v.unit)}
for k, v in data.get("meta", {}).items(): # also serialize the metadata
if isinstance(v, u.Quantity):
data["meta"][k] = {"value": v.value.tolist(), "unit": str(v.unit)}

# check that file exists and whether to overwrite.
if os.path.exists(file) and not overwrite:
raise IOError(f"{file} exists. Set 'overwrite' to write over.")
with open(file, "w") as write_file:
json.dump(data, write_file)


def json_identify(origin, filepath, fileobj, *args, **kwargs):
return filepath is not None and filepath.endswith(".json")


###############################################################################
# FIXTURES

@pytest.fixture
def clean_registry():
# TODO! with monkeypatch instead for thread safety.
Expand Down

0 comments on commit e1c445d

Please sign in to comment.