Skip to content

Commit

Permalink
Merge pull request #379 from johnnonweiler/266-remove-imports-from-wi…
Browse files Browse the repository at this point in the history
…thin-tests

Move imports outside of test method code
  • Loading branch information
bielsnohr authored Oct 21, 2024
2 parents 69f0b0c + bb82c74 commit 625f523
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 32 deletions.
10 changes: 4 additions & 6 deletions _episodes/21-automatically-testing-software.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,10 +355,10 @@ Look at `tests/test_models.py`:
import numpy as np
import numpy.testing as npt
from inflammation.models import daily_mean
def test_daily_mean_zeros():
"""Test that mean function works for an array of zeros."""
from inflammation.models import daily_mean
test_input = np.array([[0, 0],
[0, 0],
Expand All @@ -371,7 +371,6 @@ def test_daily_mean_zeros():
def test_daily_mean_integers():
"""Test that mean function works for an array of positive integers."""
from inflammation.models import daily_mean
test_input = np.array([[1, 2],
[3, 4],
Expand Down Expand Up @@ -544,14 +543,14 @@ do we think these results are easy to understand?
> Once added, run all the tests again with `python -m pytest tests/test_models.py`,
> and you should also see your new tests pass.
>
>
>
> > ## Solution
> >
> > ~~~
> > from inflammation.models import daily_max, daily_mean, daily_min
> > ...
> > def test_daily_max():
> > """Test that max function works for an array of positive integers."""
> > from inflammation.models import daily_max
> >
> > test_input = np.array([[4, 2, 5],
> > [1, 6, 2],
Expand All @@ -563,7 +562,6 @@ do we think these results are easy to understand?
> >
> > def test_daily_min():
> > """Test that min function works for an array of positive and negative integers."""
> > from inflammation.models import daily_min
> >
> > test_input = np.array([[ 4, -2, 5],
> > [ 1, -6, 2],
Expand Down Expand Up @@ -593,10 +591,10 @@ Add this test in `tests/test_models.py`:
~~~
import pytest
from inflammation.models import daily_min
...
def test_daily_min_string():
"""Test for TypeError when passing strings"""
from inflammation.models import daily_min

with pytest.raises(TypeError):
error_expected = daily_min([['Hello', 'there'], ['General', 'Kenobi']])
Expand Down
6 changes: 3 additions & 3 deletions _episodes/22-scaling-up-unit-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ the `test_daily_mean_zeros()` and `test_daily_mean_integers()`
into a single test function:

~~~
from inflammation.models import daily_mean
@pytest.mark.parametrize(
"test, expected",
[
Expand All @@ -46,7 +48,6 @@ into a single test function:
])
def test_daily_mean(test, expected):
"""Test mean function works for array of zeroes and positive integers."""
from inflammation.models import daily_mean
npt.assert_array_equal(daily_mean(np.array(test)), np.array(expected))
~~~
{: .language-python}
Expand Down Expand Up @@ -85,6 +86,7 @@ and adding more tests scales better as our code becomes more complex.
>
> > ## Solution
> > ~~~
> > from inflammation.models import daily_max, daily_min
> > ...
> > @pytest.mark.parametrize(
> > "test, expected",
Expand All @@ -95,7 +97,6 @@ and adding more tests scales better as our code becomes more complex.
> > ])
> > def test_daily_max(test, expected):
> > """Test max function works for zeroes, positive integers, mix of positive/negative integers."""
> > from inflammation.models import daily_max
> > npt.assert_array_equal(daily_max(np.array(test)), np.array(expected))
> >
> >
Expand All @@ -108,7 +109,6 @@ and adding more tests scales better as our code becomes more complex.
> > ])
> > def test_daily_min(test, expected):
> > """Test min function works for zeroes, positive integers, mix of positive/negative integers."""
> > from inflammation.models import daily_min
> > npt.assert_array_equal(daily_min(np.array(test)), np.array(expected))
> > ...
> > ~~~
Expand Down
31 changes: 19 additions & 12 deletions _episodes/24-diagnosing-issues-improving-robustness.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ Let us now add a new test in `tests/test_models.py`
to check that the normalisation function is correct for some test data.

~~~
from inflammation.models import patient_normalise
@pytest.mark.parametrize(
"test, expected",
[
Expand All @@ -121,7 +123,7 @@ to check that the normalisation function is correct for some test data.
def test_patient_normalise(test, expected):
"""Test normalisation works for arrays of one and positive integers.
Test with a relative and absolute tolerance of 0.01."""
from inflammation.models import patient_normalise
result = patient_normalise(np.array(test))
npt.assert_allclose(result, np.array(expected), rtol=1e-2, atol=1e-2)
~~~
Expand All @@ -135,14 +137,15 @@ and are only concerned with a certain degree of precision,
like the test case above.

> ## Relative and absolute tolerance
> **Relative tolerance** in unit testing means that the acceptable difference between the expected and actual results
> depends on the size of the expected result itself. So, if your expected result is 100,
>
> **Relative tolerance** in unit testing means that the acceptable difference between the expected and actual results
> depends on the size of the expected result itself. So, if your expected result is 100,
> a relative tolerance of 0.1 (or 10%) means the actual result can be anywhere from 90 to 110 and still be considered correct.
>
> **Absolute tolerance**, on the other hand,
> sets a fixed allowable difference regardless of the magnitude of the expected result.
> For example, if you set an absolute tolerance of 5,
> it means the actual result can be within 5 units of the expected result,
>
> **Absolute tolerance**, on the other hand,
> sets a fixed allowable difference regardless of the magnitude of the expected result.
> For example, if you set an absolute tolerance of 5,
> it means the actual result can be within 5 units of the expected result,
> regardless of whether the expected result is 10 or 1000.
{: .callout}

Expand Down Expand Up @@ -467,9 +470,12 @@ def patient_normalise(data):
> and add them to the parametrised tests.
> After you have finished remember to commit your changes.
>
>
>
> > ## Possible Solution
> >
> > ~~~
> > from inflammation.models import patient_normalise
> >
> > @pytest.mark.parametrize(
> > "test, expected",
> > [
Expand Down Expand Up @@ -500,7 +506,7 @@ def patient_normalise(data):
> > ])
> > def test_patient_normalise(test, expected):
> > """Test normalisation works for arrays of one and positive integers."""
> > from inflammation.models import patient_normalise
> >
> > result = patient_normalise(np.array(test))
> > npt.assert_allclose(result, np.array(expected), rtol=1e-2, atol=1e-2)
> > ...
Expand Down Expand Up @@ -563,6 +569,8 @@ and is used to indicate that the function received an argument of the right type
but of an inappropriate value.
~~~
from inflammation.models import patient_normalise

@pytest.mark.parametrize(
"test, expected, expect_raises",
[
Expand All @@ -581,7 +589,6 @@ but of an inappropriate value.
])
def test_patient_normalise(test, expected, expect_raises):
"""Test normalisation works for arrays of one and positive integers."""
from inflammation.models import patient_normalise

if expect_raises is not None:
with pytest.raises(expect_raises):
Expand Down Expand Up @@ -639,6 +646,7 @@ Be sure to commit your changes so far and push them to GitHub.
> > In `test/test_models.py`:
> >
> > ~~~
> > from inflammation.models import patient_normalise
> > ...
> > @pytest.mark.parametrize(
> > "test, expected, expect_raises",
Expand All @@ -662,7 +670,6 @@ Be sure to commit your changes so far and push them to GitHub.
> > ])
> > def test_patient_normalise(test, expected, expect_raises):
> > """Test normalisation works for arrays of one and positive integers."""
> > from inflammation.models import patient_normalise
> > if isinstance(test, list):
> > test = np.array(test)
> > if expect_raises is not None:
Expand Down
9 changes: 5 additions & 4 deletions _extras/databases.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,12 @@ but it allows us not to worry about **migrations**.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from inflammation.models import Base, Patient
...
def test_sqlalchemy_patient_search():
"""Test that we can save and retrieve patient data from a database."""
from inflammation.models import Base, Patient
# Setup a database connection - we are using a database stored in memory here
engine = create_engine('sqlite:///:memory:', echo=True)
Expand Down Expand Up @@ -273,11 +274,11 @@ We then test that we can get the observations from a patient we have searched fo
~~~
# file: tests/test_models.py
from inflammation.models import Base, Observation, Patient
...
def test_sqlalchemy_observations():
"""Test that we can save and retrieve inflammation observations from a database."""
from inflammation.models import Base, Observation, Patient
# Setup a database connection - we are using a database stored in memory here
engine = create_engine('sqlite:///:memory:', echo=True)
Expand Down Expand Up @@ -342,10 +343,10 @@ and test that we can turn them into a Numpy array.

~~~
# file: tests/test_models.py
from inflammation.models import Base, Observation, Patient
...
def test_sqlalchemy_observations_to_array():
"""Test that we can save and retrieve inflammation observations from a database."""
from inflammation.models import Base, Observation, Patient
# Setup a database connection - we are using a database stored in memory here
engine = create_engine('sqlite:///:memory:')
Expand Down
9 changes: 2 additions & 7 deletions _extras/object-oriented-programming.md
Original file line number Diff line number Diff line change
Expand Up @@ -803,44 +803,40 @@ before we can properly initialise a `Patient` model with their inflammation data
> explain them and how you implemented them to your neighbour.
> Would they have implemented that feature in the same way?
>
>
>
> > ## Solution
> > One example solution is shown below.
> > You may start by writing some tests (that will initially fail),
> > and then develop the code to satisfy the new requirements and pass the tests.
> > ~~~
> > # file: tests/test_patient.py
> > """Tests for the Patient model."""
> > from inflammation.models import Doctor, Patient, Person
> >
> > def test_create_patient():
> > """Check a patient is created correctly given a name."""
> > from inflammation.models import Patient
> > name = 'Alice'
> > p = Patient(name=name)
> > assert p.name == name
> >
> > def test_create_doctor():
> > """Check a doctor is created correctly given a name."""
> > from inflammation.models import Doctor
> > name = 'Sheila Wheels'
> > doc = Doctor(name=name)
> > assert doc.name == name
> >
> > def test_doctor_is_person():
> > """Check if a doctor is a person."""
> > from inflammation.models import Doctor, Person
> > doc = Doctor("Sheila Wheels")
> > assert isinstance(doc, Person)
> >
> > def test_patient_is_person():
> > """Check if a patient is a person. """
> > from inflammation.models import Patient, Person
> > alice = Patient("Alice")
> > assert isinstance(alice, Person)
> >
> > def test_patients_added_correctly():
> > """Check patients are being added correctly by a doctor. """
> > from inflammation.models import Doctor, Patient
> > doc = Doctor("Sheila Wheels")
> > alice = Patient("Alice")
> > doc.add_patient(alice)
Expand All @@ -849,7 +845,6 @@ before we can properly initialise a `Patient` model with their inflammation data
> >
> > def test_no_duplicate_patients():
> > """Check adding the same patient to the same doctor twice does not result in duplicates. """
> > from inflammation.models import Doctor, Patient
> > doc = Doctor("Sheila Wheels")
> > alice = Patient("Alice")
> > doc.add_patient(alice)
Expand Down

0 comments on commit 625f523

Please sign in to comment.