diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 303bebbfa..a98962d83 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,9 @@ * When making changes, write code that is consistent with the surrounding code (see the [Cantera style guidelines](https://cantera.org/dev/develop/style-guidelines.html)) * Add tests for any new features that you are implementing to either the - GoogleTest-based test suite or the Python test suite. + GoogleTest-based test suite or the Python test suite. See + [Writing Tests](https://cantera.org/dev/develop/writing-tests.html) for more + information. * Add examples that highlight new capabilities, or update existing examples to make use of new features. * Cantera is licensed under a [BSD diff --git a/doc/sphinx/develop/index.md b/doc/sphinx/develop/index.md index c13f826f2..70ffeccc5 100644 --- a/doc/sphinx/develop/index.md +++ b/doc/sphinx/develop/index.md @@ -53,6 +53,7 @@ This section is a work in progress. - [](CONTRIBUTING) - [](style-guidelines) +- [](writing-tests) - [](doc-formatting) ```{toctree} @@ -61,5 +62,6 @@ This section is a work in progress. CONTRIBUTING style-guidelines +writing-tests doc-formatting ``` diff --git a/doc/sphinx/develop/writing-tests.md b/doc/sphinx/develop/writing-tests.md new file mode 100644 index 000000000..20b4f85e4 --- /dev/null +++ b/doc/sphinx/develop/writing-tests.md @@ -0,0 +1,41 @@ +# Writing Tests + +## Python Tests + +- To allow use of deprecated methods in Python tests, use the decorator: + ```python + @pytest.mark.usefixtures("allow_deprecated") + ``` + +### Transition from `unittest` to `pytest` + +Starting in Cantera 2.6, we transitioned from using the built-in `unittest` module to +run Cantera's Python test suite to using the `pytest` framework. However, many of the +existing tests are still written in the `unittest` style (which is also supported by +`pytest`). The following recommendations apply to new tests and tests that are being +significantly modified: + +- Use `pytest`-style asserts instead of `unittest` member functions like + `assertWhatever`. Examples: + ```python + assert 0 <= idom < len(self.domains) + assert gas.n_species == N + 1 + assert "X_H2" in header.split(",") + ``` + +- Use `pytest.approx` in preference to `assertAlmostEqual`. Add + `from pytest import approx` to any test file that doesn't already contain it. + Examples: + ```python + assert q1.T == approx(T1) # scalar + assert sl_mole == approx(sl_mass, rel=0.1) # specific relative tolerance + assert list(jet.X[k, :]) == approx(list(self.sim.X[k, :]), tol_X) # arrays + assert X == approx([0.07748481, 0.048165072, 0.01446654]) + ``` + +- Use `with pytest.raises` instead of `unittest`'s method of handling "assert raises". + Example: + ```python + with pytest.raises(ct.CanteraError, match="No component named 'spam'"): + self.r1.set_advance_limit("spam", 0.1) + ```