Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ extend-select = [
# "PGH", # pygrep-hooks
# "PIE", # flake8-pie
# "PL", # pylint
# "PT", # flake8-pytest-style
"PT", # flake8-pytest-style
# "PTH", # flake8-use-pathlib
# "RET", # flake8-return
"RUF", # Ruff-specific
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def optimtest():

class TestLeadAcidFull:
@pytest.mark.parametrize(
"options, t_eval",
("options", "t_eval"),
[
({"thermal": "isothermal"}, np.linspace(0, 3600 * 17)),
(
Expand Down Expand Up @@ -76,7 +76,7 @@ def test_set_up(self):
optimtest.set_up_model(to_python=False)

@pytest.mark.parametrize(
"options, param_update",
("options", "param_update"),
[
({"thermal": "lumped"}, {"Current function [A]": 1.7}),
({"thermal": "x-full"}, None),
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_batch_study.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def test_solve(self):

# Tests for exceptions
for name in pybamm.BatchStudy.INPUT_LIST:
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Either provide no"):
pybamm.BatchStudy(
models={"SPM": spm, "SPM uniform": spm_uniform}, **{name: {None}}
)
Expand Down
4 changes: 3 additions & 1 deletion tests/unit/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ def test_write_read_uuid(self, tmp_path, write_opt_in):
else:
assert config_dict["enable_telemetry"] is False

@pytest.mark.parametrize("user_opted_in, user_input", [(True, "y"), (False, "n")])
@pytest.mark.parametrize(
("user_opted_in", "user_input"), [(True, "y"), (False, "n")]
)
def test_ask_user_opt_in(self, monkeypatch, capsys, user_opted_in, user_input):
# Mock select.select to simulate user input
def mock_select(*args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_experiments/test_base_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


@pytest.mark.parametrize(
"test_string, unit_string",
("test_string", "unit_string"),
[
("123e-1 W", "W"),
("123K", "K"),
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_expression_tree/test_coupled_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def test_setter(self):
coupled_variables = {"a": a}
model.coupled_variables = coupled_variables
assert model.coupled_variables == coupled_variables
coupled_variables = {"b": a}

with pytest.raises(ValueError, match="Coupled variable with name"):
coupled_variables = {"b": a}
model.coupled_variables = coupled_variables
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ def test_time(self):
t = pybamm.Time()
assert t.name == "time"
assert t.evaluate(4) == 4
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="t must be provided"):
t.evaluate(None)

t = pybamm.t
assert t.name == "time"
assert t.evaluate(4) == 4
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="t must be provided"):
t.evaluate(None)

assert t.evaluate_for_shape() == 0
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/test_expression_tree/test_interpolant.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ def f(x, y):
value = interp._function_evaluate(evaluated_children)

# Test evaluation fails with different child shapes
with pytest.raises(ValueError, match="All children must"):
evaluated_children = [np.array([[1, 1]]), np.array([7])]
evaluated_children = [np.array([[1, 1]]), np.array([7])]
with pytest.raises(ValueError, match="All children must have the same shape"):
value = interp._function_evaluate(evaluated_children)

# Test runs when all children are scalars
Expand Down Expand Up @@ -295,8 +295,8 @@ def f(x, y, z):
value = interp._function_evaluate(evaluated_children)

# Test evaluation fails with different child shapes
with pytest.raises(ValueError, match="All children must"):
evaluated_children = [np.array([[1, 1]]), np.ones(()) * 4, np.array([[7]])]
evaluated_children = [np.array([[1, 1]]), np.ones(()) * 4, np.array([[7]])]
with pytest.raises(ValueError, match="All children must have the same shape"):
value = interp._function_evaluate(evaluated_children)

# Test runs when all children are scalsrs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def test_interpolation(self):
# error for not recognized interpolator
with pytest.raises(ValueError, match="interpolator"):
interp = pybamm.Interpolant(x, data, y, interpolator="idonotexist")
interp_casadi = interp.to_casadi(y=casadi_y)
interp_casadi = interp.to_casadi(y=casadi_y)

# error for converted children count
y4 = (
Expand All @@ -205,7 +205,7 @@ def test_interpolation(self):
data4 = 2 * x4 # np.tile(2 * x3, (10, 1)).T
with pytest.raises(ValueError, match="Invalid dimension of x"):
interp = pybamm.Interpolant(x4_, data4, y4, interpolator="linear")
interp_casadi = interp.to_casadi(y=casadi_y)
interp_casadi = interp.to_casadi(y=casadi_y)

Comment on lines 207 to 209
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part looks off to me. If the raise value error happens in the pybamm.Interpolant() line then the to_casadi() line does nothing

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few other places with similar changes

def test_interpolation_2d(self):
x_ = [np.linspace(0, 1), np.linspace(0, 1)]
Expand Down Expand Up @@ -249,7 +249,7 @@ def test_interpolation_2d(self):
# error for pchip interpolator
with pytest.raises(ValueError, match="interpolator should be"):
interp = pybamm.Interpolant(x_, Y, y, interpolator="pchip")
interp_casadi = interp.to_casadi(y=casadi_y)
interp_casadi = interp.to_casadi(y=casadi_y)

def test_interpolation_3d(self):
def f(x, y, z):
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_expression_tree/test_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,12 @@ def test_set_input_names(self):

assert func.input_names == new_input_names

new_input_names = {"wrong": "input type"}
with pytest.raises(TypeError):
new_input_names = {"wrong": "input type"}
func.input_names = new_input_names

new_input_names = [var]
with pytest.raises(TypeError):
new_input_names = [var]
func.input_names = new_input_names

def test_print_name(self):
Expand Down
5 changes: 2 additions & 3 deletions tests/unit/test_expression_tree/test_symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def test_symbol_visualise(self, tmp_path):
sym.visualise(str(temp_file))
assert temp_file.exists()

with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Invalid file extension"):
sym.visualise(str(temp_file.with_suffix("")))

def test_has_spatial_derivatives(self):
Expand Down Expand Up @@ -559,5 +559,4 @@ def test_bool(self):
bool(a)
# if statement calls Boolean
with pytest.raises(NotImplementedError, match="Boolean"):
if a > 1:
print("a is greater than 1")
bool(a > 1)
3 changes: 3 additions & 0 deletions tests/unit/test_expression_tree/test_unary_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,8 +660,11 @@ def test_boundary_value(self):

# error if boundary value on tabs and domain is not "current collector"
var = pybamm.Variable("var", domain=["negative electrode"])

with pytest.raises(pybamm.ModelError, match="Can only take boundary"):
pybamm.boundary_value(var, "negative tab")

with pytest.raises(pybamm.ModelError, match="Can only take boundary"):
pybamm.boundary_value(var, "positive tab")

# boundary value of symbol that evaluates on edges raises error
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ def test_logger(self):
pybamm.set_logging_level("WARNING")

def test_exceptions(self):
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="filename must be specified"):
pybamm.get_new_logger("test", None)
6 changes: 3 additions & 3 deletions tests/unit/test_meshes/test_one_dimensional_submesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
import numpy as np


@pytest.fixture()
@pytest.fixture
def r():
r = pybamm.SpatialVariable(
"r", domain=["negative particle"], coord_sys="spherical polar"
)
return r


@pytest.fixture()
@pytest.fixture
def x():
return pybamm.SpatialVariable(
"x", domain=["negative electrode"], coord_sys="cartesian"
)


@pytest.fixture()
@pytest.fixture
def geometry(r):
geometry = {
"negative particle": {r: {"min": pybamm.Scalar(0), "max": pybamm.Scalar(1)}}
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_meshes/test_scikit_fem_submesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import numpy as np


@pytest.fixture()
@pytest.fixture
def param():
return pybamm.ParameterValues(
{
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_models/test_base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def test_get_parameter_info(self, symbols):
assert parameter_info["g"][1] == "Parameter"

@pytest.mark.parametrize(
"sub, key, parameter_value",
("sub", "key", "parameter_value"),
[
("sub1", "a", "InputParameter"),
("sub1", "w", "InputParameter"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,10 @@ def test_save_load_model(self):
)

# raises error if variables are saved without mesh
with pytest.raises(ValueError):
with pytest.raises(
ValueError,
match="Serialisation: Please provide the mesh if variables are required",
):
model.save_model(
filename="test_base_battery_model", variables=model.variables
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ def test_changing_number_of_rcs(self):
model = pybamm.equivalent_circuit.Thevenin(options=options)
model.check_well_posedness()

with pytest.raises(pybamm.OptionError, match="natural numbers"):
options = {"number of rc elements": -1}
options = {"number of rc elements": -1}
with pytest.raises(pybamm.OptionError, match="natural numbers"): # noqa: PT012
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is being suppressed here?

model = pybamm.equivalent_circuit.Thevenin(options=options)
model.check_well_posedness()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def test_model_well_posedness(self):
model.check_well_posedness()

@pytest.mark.parametrize(
"options, expected_solver",
("options", "expected_solver"),
[
(
{"hydrolysis": "true", "surface form": "differential"},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def test_default_geometry(self):
)

@pytest.mark.parametrize(
"dimensionality, spatial_method, submesh_type",
("dimensionality", "spatial_method", "submesh_type"),
[
(1, pybamm.FiniteVolume, pybamm.Uniform1DSubMesh),
(2, pybamm.ScikitFiniteElement, pybamm.ScikitUniform2DSubMesh),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


# Fixture for TestElectrodeSOHMSMR, TestCalculateTheoreticalEnergy and TestGetInitialOCPMSMR class.
@pytest.fixture()
@pytest.fixture
def options():
options = {
"open-circuit potential": "MSMR",
Expand Down Expand Up @@ -363,13 +363,11 @@ def test_error(self):
parameter_values, known_value="something else"
)

param_MSMR = pybamm.lithium_ion.MSMR({"number of MSMR reactions": "3"}).param
with pytest.raises(
ValueError,
match="Known value must be cell capacity or cyclable lithium capacity",
):
param_MSMR = pybamm.lithium_ion.MSMR(
{"number of MSMR reactions": "3"}
).param
pybamm.models.full_battery_models.lithium_ion.electrode_soh._ElectrodeSOHMSMR(
param=param_MSMR, known_value="something else"
)
Expand Down
13 changes: 6 additions & 7 deletions tests/unit/test_parameters/test_parameter_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,16 +325,13 @@ def test_process_symbol(self):

# not found
with pytest.raises(KeyError):
x = pybamm.Parameter("x")
parameter_values.process_symbol(x)
parameter_values.process_symbol(pybamm.Parameter("x"))

parameter_values = pybamm.ParameterValues({"x": np.nan})
with pytest.raises(ValueError, match="Parameter 'x' not found"):
x = pybamm.Parameter("x")
parameter_values.process_symbol(x)
parameter_values.process_symbol(pybamm.Parameter("x"))
with pytest.raises(ValueError, match="possibly a function"):
x = pybamm.FunctionParameter("x", {})
parameter_values.process_symbol(x)
parameter_values.process_symbol(pybamm.FunctionParameter("x", {}))

def test_process_parameter_in_parameter(self):
parameter_values = pybamm.ParameterValues(
Expand Down Expand Up @@ -1003,7 +1000,9 @@ def test_evaluate(self):
)

y = pybamm.StateVector(slice(0, 1))
with pytest.raises(ValueError):
with pytest.raises(
ValueError, match="symbol must evaluate to a constant scalar or array"
):
parameter_values.evaluate(y)

def test_exchange_current_density_plating(self):
Expand Down
4 changes: 3 additions & 1 deletion tests/unit/test_pybamm_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ def test_fetch():
)
def test_fetch_fake():
# Try to fetch a fake file not present in the registry
with pytest.raises(ValueError):
with pytest.raises(
ValueError, match="File 'NotAfile.json' is not in the registry."
):
data_loader.get_data("NotAfile.json")


Expand Down
17 changes: 9 additions & 8 deletions tests/unit/test_serialisation/test_serialisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,15 +304,16 @@ def test_get_pybamm_class(self, mocker):

assert isinstance(mesh_class, pybamm.Mesh)

unrecognised_symbol = {
"py/id": mocker.ANY,
"py/object": "pybamm.expression_tree.scalar.Scale",
"name": "5.0",
"id": mocker.ANY,
"value": 5.0,
"children": [],
}

with pytest.raises(AttributeError):
unrecognised_symbol = {
"py/id": mocker.ANY,
"py/object": "pybamm.expression_tree.scalar.Scale",
"name": "5.0",
"id": mocker.ANY,
"value": 5.0,
"children": [],
}
Serialise()._get_pybamm_class(unrecognised_symbol)

def test_reconstruct_symbol(self, mocker):
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ def test_smoothing_parameters(self):
pybamm.settings.set_smoothing_parameters("exact")

# Test errors
pybamm.settings.min_max_mode = "smooth"
with pytest.raises(ValueError, match="greater than 1"):
pybamm.settings.min_max_mode = "smooth"
pybamm.settings.min_max_smoothing = 0.9
pybamm.settings.min_max_mode = "soft"
with pytest.raises(ValueError, match="positive number"):
pybamm.settings.min_max_mode = "soft"
pybamm.settings.min_max_smoothing = -10
with pytest.raises(ValueError, match="positive number"):
pybamm.settings.heaviside_smoothing = -10
Expand Down
Loading