Skip to content

Commit

Permalink
[test] moved to test_data_path fixture where possible and changed sma…
Browse files Browse the repository at this point in the history
…ll test classes to pytest-style tests
  • Loading branch information
wandadars committed Oct 8, 2024
1 parent 98a1eb6 commit f905236
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 67 deletions.
2 changes: 0 additions & 2 deletions test/python/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,6 @@ def test_work_path(request, cantera_setup):
# Assign to the test class
request.cls.test_work_path = work_path
request.cls.using_tempfile = using_tempfile
request.cls.test_data_path = TEST_DATA_PATH
request.cls.cantera_data_path = CANTERA_DATA_PATH

yield

Expand Down
46 changes: 18 additions & 28 deletions test/python/test_composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,27 +163,23 @@ def test_pickle_interface(self):
pickle.dump(interface, pkl)


class TestEmptyThermoPhase:
""" Test empty Solution object """

@pytest.fixture
def empty_thermo_phase(self):
return ct.ThermoPhase()

def test_empty_report(self, empty_thermo_phase):
with pytest.raises(NotImplementedError):
empty_thermo_phase()
@pytest.fixture(params=[ct.ThermoPhase(), ct.Solution()])
def empty_object(request):
return request.param

def test_empty_TP(self, empty_thermo_phase):
def test_empty_report(empty_object):
with pytest.raises(NotImplementedError):
empty_thermo_phase.TP = 300, ct.one_atm
empty_object()

def test_empty_equilibrate(self, empty_thermo_phase):
with pytest.raises(NotImplementedError):
empty_thermo_phase.equilibrate("TP")
def test_empty_TP(empty_object):
with pytest.raises(NotImplementedError):
empty_object.TP = 300, ct.one_atm

def test_empty_equilibrate(empty_object):
with pytest.raises(NotImplementedError):
empty_object.equilibrate("TP")

@pytest.fixture(scope='function')
@pytest.fixture
def empty_solution():
return ct.Solution()

Expand Down Expand Up @@ -793,18 +789,15 @@ def test_legacy_hdf_multidim(self, test_data_path):
@pytest.mark.skipif("native" not in ct.hdf_support(),
reason="Cantera compiled without HDF support")
@pytest.mark.filterwarnings("ignore:.*legacy HDF.*:UserWarning")
def test_legacy_hdf(self):
self.run_legacy_hdf()

def run_legacy_hdf(self, legacy=False):
def test_legacy_hdf(self, test_data_path, legacy=False):
# recreate states used to create legacy HDF file (valid portion)
extra = {'foo': range(7), 'bar': range(7)}
meta = {'spam': 'eggs', 'hello': 'world'}
states = ct.SolutionArray(self.gas, 7, extra=extra, meta=meta)
states.TPX = np.linspace(300, 1000, 7), 2e5, 'H2:0.5, O2:0.4'
states.equilibrate('HP')

infile = self.test_data_path / f"solutionarray_fancy_legacy.h5"
infile = test_data_path / f"solutionarray_fancy_legacy.h5"
b = ct.SolutionArray(self.gas)
attr = b.restore(infile, "group0")
assert states.T == approx(b.T)
Expand All @@ -819,15 +812,12 @@ def run_legacy_hdf(self, legacy=False):
@pytest.mark.skipif("native" not in ct.hdf_support(),
reason="Cantera compiled without HDF support")
@pytest.mark.filterwarnings("ignore:.*legacy HDF.*:UserWarning")
def test_read_legacy_hdf_no_norm(self):
self.run_read_legacy_hdf_no_norm()

def run_read_legacy_hdf_no_norm(self, legacy=False):
def test_read_legacy_hdf_no_norm(self, test_data_path, legacy=False):
# recreate states used to create legacy HDF file
self.gas.set_unnormalized_mole_fractions(np.full(self.gas.n_species, 0.3))
states = ct.SolutionArray(self.gas, 5)

infile = self.test_data_path / "solutionarray_no_norm_legacy.h5"
infile = test_data_path / "solutionarray_no_norm_legacy.h5"

b = ct.SolutionArray(self.gas)
if legacy:
Expand All @@ -841,14 +831,14 @@ def run_read_legacy_hdf_no_norm(self, legacy=False):
@pytest.mark.skipif("native" not in ct.hdf_support(),
reason="Cantera compiled without HDF support")
@pytest.mark.filterwarnings("ignore:.*legacy HDF.*:UserWarning")
def test_import_no_norm_water(self):
def test_import_no_norm_water(self, test_data_path):
# recreate states used to create legacy HDF file
w = ct.Water()
w.TQ = 300, 0.5
states = ct.SolutionArray(w, 5)

w_new = ct.Water()
infile = self.test_data_path / "solutionarray_water_legacy.h5"
infile = test_data_path / "solutionarray_water_legacy.h5"
c = ct.SolutionArray(w_new)
c.restore(infile, "group0")
assert states.T == approx(c.T, rel=1e-7)
Expand Down
24 changes: 22 additions & 2 deletions test/python/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
import pytest
from pytest import approx


import cantera as ct
from cantera import ck2yaml, cti2yaml, ctml2yaml, yaml2ck, lxcat2yaml
from utilities import load_yaml


class Testck2yaml:
@pytest.fixture(autouse=True)
def inject_fixtures(self, capsys):
def inject_fixtures(self, capsys, test_data_path):
self._capsys = capsys
self.test_data_path = test_data_path

def convert(self, inputFile, thermo=None, transport=None,
surface=None, output=None, quiet=True, extra=None, **kwargs):
Expand Down Expand Up @@ -780,6 +781,10 @@ class Testyaml2ck:
"""Test yaml2ck by converting to CK then back to YAML to read with Cantera."""
ext: str = "-from-yaml2ck.yaml"

@pytest.fixture(autouse=True)
def inject_fixtures(self, test_data_path):
self.test_data_path = test_data_path

def _convert_to_ck(
self,
input_file: Path,
Expand Down Expand Up @@ -1079,6 +1084,11 @@ def test_multi_line_notes(self):


class Testcti2yaml:

@pytest.fixture(autouse=True)
def inject_fixtures(self, test_data_path):
self.test_data_path = test_data_path

def convert(self, basename, src_dir=None, encoding=None):
if src_dir is None:
src_dir = self.test_data_path
Expand Down Expand Up @@ -1301,6 +1311,11 @@ def test_nonreactant_orders(self):


class Testctml2yaml:

@pytest.fixture(autouse=True)
def inject_fixtures(self, test_data_path):
self.test_data_path = test_data_path

def convert(self, basename, src_dir=None):
if src_dir is None:
src_dir = self.test_data_path
Expand Down Expand Up @@ -1658,6 +1673,11 @@ def test_duplicate_section_ids(self):
self.convert("duplicate-reactionData-ids")

class Testlxcat2yaml:

@pytest.fixture(autouse=True)
def inject_fixtures(self, test_data_path):
self.test_data_path = test_data_path

def convert(self, inputFile=None, database=None, mechFile=None, phase=None,
insert=True, output=None):
if inputFile is not None:
Expand Down
12 changes: 8 additions & 4 deletions test/python/test_equilibrium.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ class TestKOH_Equil:
Test roughly based on examples/multiphase/plasma_equilibrium.py
"""

def test_equil_TP(self):
def test_equil_TP(self, test_data_path):
temperatures = range(350, 5000, 300)
data = np.zeros((len(temperatures), self.mix.n_species+1))
data[:,0] = temperatures
Expand All @@ -184,10 +184,10 @@ def test_equil_TP(self):
# VCS solver extrapolating thermo polynomials outside of their valid range. See
# https://github.com/Cantera/cantera/issues/270. The results show ice at
# temperatures of over 1000 K, and liquid water for temperatures of 2000-5000 K.
compare(data, self.test_data_path / "koh-equil-TP.csv")
compare(data, test_data_path / "koh-equil-TP.csv")

@pytest.mark.slow_test
def test_equil_HP(self):
def test_equil_HP(self, test_data_path):
temperatures = range(350, 5000, 300)
data = np.zeros((len(temperatures), self.mix.n_species+2))
data[:,0] = temperatures
Expand All @@ -208,7 +208,7 @@ def test_equil_HP(self):
data[i,1] = self.mix.T # equilibrated temperature
data[i,2:] = self.mix.species_moles

compare(data, self.test_data_path / "koh-equil-HP.csv")
compare(data, test_data_path / "koh-equil-HP.csv")


@pytest.fixture(scope='function')
Expand All @@ -223,6 +223,10 @@ def carbon_equil(request):
class TestEquil_GasCarbon:
"Test roughly based on examples/multiphase/adiabatic.py"

@pytest.fixture(autouse=True)
def inject_fixtures(self, test_data_path):
self.test_data_path = test_data_path

def solve(self, solver, **kwargs):
n_points = 12
T = 300
Expand Down
8 changes: 4 additions & 4 deletions test/python/test_kinetics.py
Original file line number Diff line number Diff line change
Expand Up @@ -912,7 +912,7 @@ class TestSofcKinetics:
""" Test based on sofc.py """
_mech = "sofc.yaml"

def test_sofc(self):
def test_sofc(self, test_data_path):
mech = self._mech
T = 1073.15 # T in K
P = ct.one_atm
Expand Down Expand Up @@ -1010,14 +1010,14 @@ def cathode_curr(E):
cathode_bulk.electric_potential -
anode_bulk.electric_potential])

compare(data, self.test_data_path / "sofc-test.csv", rtol=1e-7)
compare(data, test_data_path / "sofc-test.csv", rtol=1e-7)


class TestLithiumIonBatteryKinetics:
""" Test based on lithium_ion_battery.py """
_mech = "lithium_ion_battery.yaml"

def test_lithium_ion_battery(self):
def test_lithium_ion_battery(self, test_data_path):
mech = self._mech
samples = 11
soc = np.linspace(0., 1., samples) # [-] Input state of charge (0...1)
Expand Down Expand Up @@ -1103,7 +1103,7 @@ def cathode_current(phi_s, phi_l, X_Li_cathode):
data.append(phi_s_cathode - phi_s_anode)

data = np.array(data).ravel()
ref = np.genfromtxt(self.test_data_path / "lithium-ion-battery-test.csv")
ref = np.genfromtxt(test_data_path / "lithium-ion-battery-test.csv")
assert data == approx(ref, rel=1e-7)

def test_interface_current(self):
Expand Down
28 changes: 14 additions & 14 deletions test/python/test_onedim.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,10 +807,10 @@ def test_write_csv(self):
@pytest.mark.filterwarnings("ignore:.*legacy HDF.*:UserWarning")
@pytest.mark.skipif("native" not in ct.hdf_support(),
reason="Cantera compiled without HDF support")
def test_restore_legacy_hdf(self):
def test_restore_legacy_hdf(self, test_data_path):
# Legacy input file was created using the Cantera 2.6 Python test suite:
# - restore_legacy.h5 -> test_onedim.py::TestFreeFlame::test_write_hdf
filename = self.test_data_path / f"freeflame_legacy.h5"
filename = test_data_path / f"freeflame_legacy.h5"

self.run_mix(phi=1.1, T=350, width=2.0, p=2.0, refine=False)
desc = 'mixture-averaged simulation'
Expand Down Expand Up @@ -976,7 +976,7 @@ def solve_mix(self, ratio=3.0, slope=0.1, curve=0.12, prune=0.0):
assert self.sim.transport_model == 'mixture-averaged'

@pytest.mark.slow_test
def test_mixture_averaged(self, saveReference=False):
def test_mixture_averaged(self, test_data_path, saveReference=False):
referenceFile = "DiffusionFlameTest-h2-mix.csv"
self.create_sim(p=ct.one_atm)
self.sim.set_initial_guess()
Expand All @@ -998,11 +998,11 @@ def test_mixture_averaged(self, saveReference=False):
if saveReference:
np.savetxt(referenceFile, data, '%11.6e', ', ')
else:
bad = compareProfiles(self.test_data_path / referenceFile, data,
bad = compareProfiles(test_data_path / referenceFile, data,
rtol=1e-2, atol=1e-8, xtol=1e-2)
assert not bad, bad

def test_auto(self, saveReference=False):
def test_auto(self, test_data_path, saveReference=False):
referenceFile = "DiffusionFlameTest-h2-auto.csv"
self.create_sim(p=ct.one_atm, mdot_fuel=2, mdot_ox=3)

Expand Down Expand Up @@ -1037,7 +1037,7 @@ def time_step_func(dt):
if saveReference:
np.savetxt(referenceFile, data, '%11.6e', ', ')
else:
bad = compareProfiles(self.test_data_path / referenceFile, data,
bad = compareProfiles(test_data_path / referenceFile, data,
rtol=1e-2, atol=1e-8, xtol=1e-2)
assert not bad, bad

Expand Down Expand Up @@ -1091,7 +1091,7 @@ def test_restart(self):
assert self.sim.T[0] == approx(self.sim.fuel_inlet.T, rel=1e-4)
assert mdot[-1] == approx(-self.sim.oxidizer_inlet.mdot, rel=1e-4)

def test_mixture_averaged_rad(self, saveReference=False):
def test_mixture_averaged_rad(self, test_data_path, saveReference=False):
referenceFile = "DiffusionFlameTest-h2-mix-rad.csv"
self.create_sim(p=ct.one_atm)
self.sim.set_initial_guess()
Expand Down Expand Up @@ -1120,7 +1120,7 @@ def test_mixture_averaged_rad(self, saveReference=False):
if saveReference:
np.savetxt(referenceFile, data, '%11.6e', ', ')
else:
bad = compareProfiles(self.test_data_path / referenceFile, data,
bad = compareProfiles(test_data_path / referenceFile, data,
rtol=1e-2, atol=1e-8, xtol=1e-2)
assert not bad, bad

Expand Down Expand Up @@ -1368,7 +1368,7 @@ class TestCounterflowPremixedFlame:
the ones in test/data and replace them if needed.
"""

def test_mixture_averaged(self, saveReference=False):
def test_mixture_averaged(self, test_data_path, saveReference=False):
T_in = 373.0 # inlet temperature
comp = 'H2:1.6, O2:1, AR:7' # premixed gas composition

Expand Down Expand Up @@ -1407,7 +1407,7 @@ def test_mixture_averaged(self, saveReference=False):
if saveReference:
np.savetxt(referenceFile, data, '%11.6e', ', ')
else:
bad = compareProfiles(self.test_data_path / referenceFile, data,
bad = compareProfiles(test_data_path / referenceFile, data,
rtol=1e-2, atol=1e-8, xtol=1e-2)
assert not bad, bad

Expand Down Expand Up @@ -1487,7 +1487,7 @@ class TestCounterflowPremixedFlameNonIdeal:
the ones in test/data and replace them if needed.
"""

def test_mixture_averaged(self, saveReference=False):
def test_mixture_averaged(self, test_data_path, saveReference=False):
T_in = 373.0 # inlet temperature
comp = 'H2:1.6, O2:1, AR:7' # premixed gas composition

Expand Down Expand Up @@ -1526,7 +1526,7 @@ def test_mixture_averaged(self, saveReference=False):
if saveReference:
np.savetxt(referenceFile, data, '%11.6e', ', ')
else:
bad = compareProfiles(self.test_data_path / referenceFile, data,
bad = compareProfiles(test_data_path / referenceFile, data,
rtol=1e-2, atol=1e-8, xtol=1e-2)
assert not bad, bad

Expand Down Expand Up @@ -1807,10 +1807,10 @@ def test_reacting_surface_case3(self):
@pytest.mark.skipif("native" not in ct.hdf_support(),
reason="Cantera compiled without HDF support")
@pytest.mark.filterwarnings("ignore:.*legacy HDF.*:UserWarning")
def test_restore_legacy_hdf(self):
def test_restore_legacy_hdf(self, test_data_path):
# Legacy input file was created using the Cantera 2.6 Python test suite:
# - restore_legacy.h5 -> test_onedim.py::TestImpingingJet::test_write_hdf
filename = self.test_data_path / f"impingingjet_legacy.h5"
filename = test_data_path / f"impingingjet_legacy.h5"

self.run_reacting_surface(xch4=0.095, tsurf=900.0, mdot=0.06, width=0.1)
jet = ct.ImpingingJet(gas=self.gas, surface=self.surf_phase)
Expand Down
Loading

0 comments on commit f905236

Please sign in to comment.