Skip to content

Commit

Permalink
Moving a bunch of unit tests to pytest. (#4264)
Browse files Browse the repository at this point in the history
* Moving a bunch of unit tests to pytest

Signed-off-by: Pradyot Ranjan <[email protected]>

* style: pre-commit fixes

* style fix

Signed-off-by: Pradyot Ranjan <[email protected]>

* Update tests/unit/test_models/test_full_battery_models/test_lithium_ion/test_mpm_half_cell.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* Update tests/unit/test_models/test_full_battery_models/test_lithium_ion/test_spm.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* Update tests/unit/test_models/test_full_battery_models/test_lithium_ion/test_spme.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* Update tests/unit/test_parameters/test_parameter_sets_class.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* Update tests/unit/test_parameters/test_parameter_sets_class.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* Update tests/unit/test_plotting/test_plot.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* adding skips

Signed-off-by: Pradyot Ranjan <[email protected]>

* Update tests/unit/test_plotting/test_plot.py

Co-authored-by: Agriya Khetarpal <[email protected]>

* adding reason for skips

Signed-off-by: Pradyot Ranjan <[email protected]>

---------

Signed-off-by: Pradyot Ranjan <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Agriya Khetarpal <[email protected]>
  • Loading branch information
3 people authored Jul 16, 2024
1 parent 6c1a559 commit 4796ba9
Show file tree
Hide file tree
Showing 52 changed files with 423 additions and 1,022 deletions.
25 changes: 6 additions & 19 deletions tests/unit/test_doc_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
# is generated, but rather that the docstrings are correctly modified
#

import pybamm
import unittest
from tests import TestCase
from inspect import getmro
from pybamm.doc_utils import copy_parameter_doc_from_parent, doc_extend_parent


class TestDocUtils(TestCase):
class TestDocUtils:
def test_copy_parameter_doc_from_parent(self):
"""Test if parameters from the parent class are copied to
child class docstring"""
Expand Down Expand Up @@ -38,7 +35,7 @@ def __init__(self, foo, bar):
base_parameters = "".join(Base.__doc__.partition("Parameters")[1:])
derived_parameters = "".join(Derived.__doc__.partition("Parameters")[1:])
# check that the parameters section is in the docstring
self.assertMultiLineEqual(base_parameters, derived_parameters)
assert base_parameters == derived_parameters

def test_doc_extend_parent(self):
"""Test if the child class has the Extends directive in its docstring"""
Expand All @@ -57,21 +54,11 @@ def __init__(self, param):
super().__init__(param)

# check that the Extends directive is in the docstring
self.assertIn("**Extends:**", Derived.__doc__)
assert "**Extends:**" in Derived.__doc__

# check that the Extends directive maps to the correct base class
base_cls_name = f"{getmro(Derived)[1].__module__}.{getmro(Derived)[1].__name__}"
self.assertEqual(
Derived.__doc__.partition("**Extends:**")[2].strip(),
f":class:`{base_cls_name}`",
assert (
Derived.__doc__.partition("**Extends:**")[2].strip()
== f":class:`{base_cls_name}`"
)


if __name__ == "__main__":
print("Add -v for more debug output")
import sys

if "-v" in sys.argv:
debug = True
pybamm.settings.debug_mode = True
unittest.main()
31 changes: 8 additions & 23 deletions tests/unit/test_expression_tree/test_array.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
#
# Tests for the Array class
#
from tests import TestCase
import unittest
import unittest.mock as mock


import numpy as np
import sympy

import pybamm


class TestArray(TestCase):
class TestArray:
def test_name(self):
arr = pybamm.Array(np.array([1, 2, 3]))
self.assertEqual(arr.name, "Array of shape (3, 1)")
assert arr.name == "Array of shape (3, 1)"

def test_list_entries(self):
vect = pybamm.Array([1, 2, 3])
Expand All @@ -38,16 +35,14 @@ def test_meshgrid(self):
np.testing.assert_array_equal(B, D.entries)

def test_to_equation(self):
self.assertEqual(
pybamm.Array([1, 2]).to_equation(), sympy.Array([[1.0], [2.0]])
)
assert pybamm.Array([1, 2]).to_equation() == sympy.Array([[1.0], [2.0]])

def test_to_from_json(self):
def test_to_from_json(self, mocker):
arr = pybamm.Array(np.array([1, 2, 3]))

json_dict = {
"name": "Array of shape (3, 1)",
"id": mock.ANY,
"id": mocker.ANY,
"domains": {
"primary": [],
"secondary": [],
Expand All @@ -59,17 +54,7 @@ def test_to_from_json(self):

# array to json conversion
created_json = arr.to_json()
self.assertEqual(created_json, json_dict)
assert created_json == json_dict

# json to array conversion
self.assertEqual(pybamm.Array._from_json(created_json), arr)


if __name__ == "__main__":
print("Add -v for more debug output")
import sys

if "-v" in sys.argv:
debug = True
pybamm.settings.debug_mode = True
unittest.main()
assert pybamm.Array._from_json(created_json) == arr
47 changes: 18 additions & 29 deletions tests/unit/test_expression_tree/test_d_dt.py
Original file line number Diff line number Diff line change
@@ -1,65 +1,54 @@
#
# Tests for the Scalar class
#
from tests import TestCase
import pytest
import pybamm

import unittest
import numpy as np


class TestDDT(TestCase):
class TestDDT:
def test_time_derivative(self):
a = pybamm.Scalar(5).diff(pybamm.t)
self.assertIsInstance(a, pybamm.Scalar)
self.assertEqual(a.value, 0)
assert isinstance(a, pybamm.Scalar)
assert a.value == 0

a = pybamm.t.diff(pybamm.t)
self.assertIsInstance(a, pybamm.Scalar)
self.assertEqual(a.value, 1)
assert isinstance(a, pybamm.Scalar)
assert a.value == 1

a = (pybamm.t**2).diff(pybamm.t)
self.assertEqual(a, (2 * pybamm.t**1 * 1))
self.assertEqual(a.evaluate(t=1), 2)
assert a == (2 * pybamm.t**1 * 1)
assert a.evaluate(t=1) == 2

a = (2 + pybamm.t**2).diff(pybamm.t)
self.assertEqual(a.evaluate(t=1), 2)
assert a.evaluate(t=1) == 2

def test_time_derivative_of_variable(self):
a = (pybamm.Variable("a")).diff(pybamm.t)
self.assertIsInstance(a, pybamm.VariableDot)
self.assertEqual(a.name, "a'")
assert isinstance(a, pybamm.VariableDot)
assert a.name == "a'"

p = pybamm.Parameter("p")
a = 1 + p * pybamm.Variable("a")
diff_a = a.diff(pybamm.t)
self.assertIsInstance(diff_a, pybamm.Multiplication)
self.assertEqual(diff_a.children[0].name, "p")
self.assertEqual(diff_a.children[1].name, "a'")
assert isinstance(diff_a, pybamm.Multiplication)
assert diff_a.children[0].name == "p"
assert diff_a.children[1].name == "a'"

with self.assertRaises(pybamm.ModelError):
with pytest.raises(pybamm.ModelError):
a = (pybamm.Variable("a")).diff(pybamm.t).diff(pybamm.t)

def test_time_derivative_of_state_vector(self):
sv = pybamm.StateVector(slice(0, 10))
y_dot = np.linspace(0, 2, 19)

a = sv.diff(pybamm.t)
self.assertIsInstance(a, pybamm.StateVectorDot)
self.assertEqual(a.name[-1], "'")
assert isinstance(a, pybamm.StateVectorDot)
assert a.name[-1] == "'"
np.testing.assert_array_equal(
a.evaluate(y_dot=y_dot), np.linspace(0, 1, 10)[:, np.newaxis]
)

with self.assertRaises(pybamm.ModelError):
with pytest.raises(pybamm.ModelError):
a = (sv).diff(pybamm.t).diff(pybamm.t)


if __name__ == "__main__":
print("Add -v for more debug output")
import sys

if "-v" in sys.argv:
debug = True
pybamm.settings.debug_mode = True
unittest.main()
72 changes: 29 additions & 43 deletions tests/unit/test_expression_tree/test_independent_variable.py
Original file line number Diff line number Diff line change
@@ -1,87 +1,73 @@
#
# Tests for the Parameter class
#
from tests import TestCase
import unittest

import pytest

import pybamm
import sympy


class TestIndependentVariable(TestCase):
class TestIndependentVariable:
def test_variable_init(self):
a = pybamm.IndependentVariable("a")
self.assertEqual(a.name, "a")
self.assertEqual(a.domain, [])
assert a.name == "a"
assert a.domain == []
a = pybamm.IndependentVariable("a", domain=["test"])
self.assertEqual(a.domain[0], "test")
assert a.domain[0] == "test"
a = pybamm.IndependentVariable("a", domain="test")
self.assertEqual(a.domain[0], "test")
with self.assertRaises(TypeError):
assert a.domain[0] == "test"
with pytest.raises(TypeError):
pybamm.IndependentVariable("a", domain=1)

def test_time(self):
t = pybamm.Time()
self.assertEqual(t.name, "time")
self.assertEqual(t.evaluate(4), 4)
with self.assertRaises(ValueError):
assert t.name == "time"
assert t.evaluate(4) == 4
with pytest.raises(ValueError):
t.evaluate(None)

t = pybamm.t
self.assertEqual(t.name, "time")
self.assertEqual(t.evaluate(4), 4)
with self.assertRaises(ValueError):
assert t.name == "time"
assert t.evaluate(4) == 4
with pytest.raises(ValueError):
t.evaluate(None)

self.assertEqual(t.evaluate_for_shape(), 0)
assert t.evaluate_for_shape() == 0

def test_spatial_variable(self):
x = pybamm.SpatialVariable("x", "negative electrode")
self.assertEqual(x.name, "x")
self.assertFalse(x.evaluates_on_edges("primary"))
assert x.name == "x"
assert not x.evaluates_on_edges("primary")
y = pybamm.SpatialVariable("y", "separator")
self.assertEqual(y.name, "y")
assert y.name == "y"
z = pybamm.SpatialVariable("z", "positive electrode")
self.assertEqual(z.name, "z")
assert z.name == "z"
r = pybamm.SpatialVariable("r", "negative particle")
self.assertEqual(r.name, "r")
with self.assertRaises(NotImplementedError):
assert r.name == "r"
with pytest.raises(NotImplementedError):
x.evaluate()

with self.assertRaisesRegex(ValueError, "domain must be"):
with pytest.raises(ValueError, match="domain must be"):
pybamm.SpatialVariable("x", [])
with self.assertRaises(pybamm.DomainError):
with pytest.raises(pybamm.DomainError):
pybamm.SpatialVariable("r_n", ["positive particle"])
with self.assertRaises(pybamm.DomainError):
with pytest.raises(pybamm.DomainError):
pybamm.SpatialVariable("r_p", ["negative particle"])
with self.assertRaises(pybamm.DomainError):
with pytest.raises(pybamm.DomainError):
pybamm.SpatialVariable("x", ["negative particle"])

def test_spatial_variable_edge(self):
x = pybamm.SpatialVariableEdge("x", "negative electrode")
self.assertEqual(x.name, "x")
self.assertTrue(x.evaluates_on_edges("primary"))
assert x.name == "x"
assert x.evaluates_on_edges("primary")

def test_to_equation(self):
# Test print_name
func = pybamm.IndependentVariable("a")
func.print_name = "test"
self.assertEqual(func.to_equation(), sympy.Symbol("test"))
assert func.to_equation() == sympy.Symbol("test")

self.assertEqual(
pybamm.IndependentVariable("a").to_equation(), sympy.Symbol("a")
)
assert pybamm.IndependentVariable("a").to_equation() == sympy.Symbol("a")

# Test time
self.assertEqual(pybamm.t.to_equation(), sympy.Symbol("t"))


if __name__ == "__main__":
print("Add -v for more debug output")
import sys

if "-v" in sys.argv:
debug = True
pybamm.settings.debug_mode = True
unittest.main()
assert pybamm.t.to_equation() == sympy.Symbol("t")
Loading

0 comments on commit 4796ba9

Please sign in to comment.