Skip to content

Commit bb82c74

Browse files
committed
♻️ Move further instances of module imports within test functions
1 parent c97d009 commit bb82c74

4 files changed

Lines changed: 30 additions & 29 deletions

File tree

_episodes/21-automatically-testing-software.md

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -355,10 +355,10 @@ Look at `tests/test_models.py`:
355355
import numpy as np
356356
import numpy.testing as npt
357357
358+
from inflammation.models import daily_mean
358359
359360
def test_daily_mean_zeros():
360361
"""Test that mean function works for an array of zeros."""
361-
from inflammation.models import daily_mean
362362
363363
test_input = np.array([[0, 0],
364364
[0, 0],
@@ -371,7 +371,6 @@ def test_daily_mean_zeros():
371371
372372
def test_daily_mean_integers():
373373
"""Test that mean function works for an array of positive integers."""
374-
from inflammation.models import daily_mean
375374
376375
test_input = np.array([[1, 2],
377376
[3, 4],
@@ -544,14 +543,14 @@ do we think these results are easy to understand?
544543
> Once added, run all the tests again with `python -m pytest tests/test_models.py`,
545544
> and you should also see your new tests pass.
546545
>
547-
>
546+
>
548547
> > ## Solution
549548
> >
550549
> > ~~~
550+
> > from inflammation.models import daily_max, daily_mean, daily_min
551551
> > ...
552552
> > def test_daily_max():
553553
> > """Test that max function works for an array of positive integers."""
554-
> > from inflammation.models import daily_max
555554
> >
556555
> > test_input = np.array([[4, 2, 5],
557556
> > [1, 6, 2],
@@ -563,7 +562,6 @@ do we think these results are easy to understand?
563562
> >
564563
> > def test_daily_min():
565564
> > """Test that min function works for an array of positive and negative integers."""
566-
> > from inflammation.models import daily_min
567565
> >
568566
> > test_input = np.array([[ 4, -2, 5],
569567
> > [ 1, -6, 2],
@@ -593,10 +591,10 @@ Add this test in `tests/test_models.py`:
593591
594592
~~~
595593
import pytest
594+
from inflammation.models import daily_min
596595
...
597596
def test_daily_min_string():
598597
"""Test for TypeError when passing strings"""
599-
from inflammation.models import daily_min
600598

601599
with pytest.raises(TypeError):
602600
error_expected = daily_min([['Hello', 'there'], ['General', 'Kenobi']])

_episodes/24-diagnosing-issues-improving-robustness.md

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ Let us now add a new test in `tests/test_models.py`
113113
to check that the normalisation function is correct for some test data.
114114

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

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

@@ -467,9 +470,12 @@ def patient_normalise(data):
467470
> and add them to the parametrised tests.
468471
> After you have finished remember to commit your changes.
469472
>
470-
>
473+
>
471474
> > ## Possible Solution
475+
> >
472476
> > ~~~
477+
> > from inflammation.models import patient_normalise
478+
> >
473479
> > @pytest.mark.parametrize(
474480
> > "test, expected",
475481
> > [
@@ -500,7 +506,7 @@ def patient_normalise(data):
500506
> > ])
501507
> > def test_patient_normalise(test, expected):
502508
> > """Test normalisation works for arrays of one and positive integers."""
503-
> > from inflammation.models import patient_normalise
509+
> >
504510
> > result = patient_normalise(np.array(test))
505511
> > npt.assert_allclose(result, np.array(expected), rtol=1e-2, atol=1e-2)
506512
> > ...
@@ -563,6 +569,8 @@ and is used to indicate that the function received an argument of the right type
563569
but of an inappropriate value.
564570
565571
~~~
572+
from inflammation.models import patient_normalise
573+
566574
@pytest.mark.parametrize(
567575
"test, expected, expect_raises",
568576
[
@@ -581,7 +589,6 @@ but of an inappropriate value.
581589
])
582590
def test_patient_normalise(test, expected, expect_raises):
583591
"""Test normalisation works for arrays of one and positive integers."""
584-
from inflammation.models import patient_normalise
585592

586593
if expect_raises is not None:
587594
with pytest.raises(expect_raises):
@@ -639,6 +646,7 @@ Be sure to commit your changes so far and push them to GitHub.
639646
> > In `test/test_models.py`:
640647
> >
641648
> > ~~~
649+
> > from inflammation.models import patient_normalise
642650
> > ...
643651
> > @pytest.mark.parametrize(
644652
> > "test, expected, expect_raises",
@@ -662,7 +670,6 @@ Be sure to commit your changes so far and push them to GitHub.
662670
> > ])
663671
> > def test_patient_normalise(test, expected, expect_raises):
664672
> > """Test normalisation works for arrays of one and positive integers."""
665-
> > from inflammation.models import patient_normalise
666673
> > if isinstance(test, list):
667674
> > test = np.array(test)
668675
> > if expect_raises is not None:

_extras/databases.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -169,11 +169,12 @@ but it allows us not to worry about **migrations**.
169169
from sqlalchemy import create_engine
170170
from sqlalchemy.orm import sessionmaker
171171
172+
from inflammation.models import Base, Patient
173+
172174
...
173175
174176
def test_sqlalchemy_patient_search():
175177
"""Test that we can save and retrieve patient data from a database."""
176-
from inflammation.models import Base, Patient
177178
178179
# Setup a database connection - we're using a database stored in memory here
179180
engine = create_engine('sqlite:///:memory:', echo=True)
@@ -273,11 +274,11 @@ We then test that we can get the observations from a patient we've searched for.
273274
~~~
274275
# file: tests/test_models.py
275276
277+
from inflammation.models import Base, Observation, Patient
276278
...
277279
278280
def test_sqlalchemy_observations():
279281
"""Test that we can save and retrieve inflammation observations from a database."""
280-
from inflammation.models import Base, Observation, Patient
281282
282283
# Setup a database connection - we're using a database stored in memory here
283284
engine = create_engine('sqlite:///:memory:', echo=True)
@@ -342,10 +343,10 @@ and test that we can turn them into a Numpy array.
342343

343344
~~~
344345
# file: tests/test_models.py
345-
346+
from inflammation.models import Base, Observation, Patient
347+
...
346348
def test_sqlalchemy_observations_to_array():
347349
"""Test that we can save and retrieve inflammation observations from a database."""
348-
from inflammation.models import Base, Observation, Patient
349350
350351
# Setup a database connection - we're using a database stored in memory here
351352
engine = create_engine('sqlite:///:memory:')

_extras/object-oriented-programming.md

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -803,44 +803,40 @@ before we can properly initialise a `Patient` model with their inflammation data
803803
> explain them and how you implemented them to your neighbour.
804804
> Would they have implemented that feature in the same way?
805805
>
806-
>
806+
>
807807
> > ## Solution
808808
> > One example solution is shown below.
809809
> > You may start by writing some tests (that will initially fail),
810810
> > and then develop the code to satisfy the new requirements and pass the tests.
811811
> > ~~~
812812
> > # file: tests/test_patient.py
813813
> > """Tests for the Patient model."""
814+
> > from inflammation.models import Doctor, Patient, Person
814815
> >
815816
> > def test_create_patient():
816817
> > """Check a patient is created correctly given a name."""
817-
> > from inflammation.models import Patient
818818
> > name = 'Alice'
819819
> > p = Patient(name=name)
820820
> > assert p.name == name
821821
> >
822822
> > def test_create_doctor():
823823
> > """Check a doctor is created correctly given a name."""
824-
> > from inflammation.models import Doctor
825824
> > name = 'Sheila Wheels'
826825
> > doc = Doctor(name=name)
827826
> > assert doc.name == name
828827
> >
829828
> > def test_doctor_is_person():
830829
> > """Check if a doctor is a person."""
831-
> > from inflammation.models import Doctor, Person
832830
> > doc = Doctor("Sheila Wheels")
833831
> > assert isinstance(doc, Person)
834832
> >
835833
> > def test_patient_is_person():
836834
> > """Check if a patient is a person. """
837-
> > from inflammation.models import Patient, Person
838835
> > alice = Patient("Alice")
839836
> > assert isinstance(alice, Person)
840837
> >
841838
> > def test_patients_added_correctly():
842839
> > """Check patients are being added correctly by a doctor. """
843-
> > from inflammation.models import Doctor, Patient
844840
> > doc = Doctor("Sheila Wheels")
845841
> > alice = Patient("Alice")
846842
> > doc.add_patient(alice)
@@ -849,7 +845,6 @@ before we can properly initialise a `Patient` model with their inflammation data
849845
> >
850846
> > def test_no_duplicate_patients():
851847
> > """Check adding the same patient to the same doctor twice does not result in duplicates. """
852-
> > from inflammation.models import Doctor, Patient
853848
> > doc = Doctor("Sheila Wheels")
854849
> > alice = Patient("Alice")
855850
> > doc.add_patient(alice)

0 commit comments

Comments
 (0)