High Five Solution¶
Solution 1¶
test_highfive.py
from highfive import is_highfive
def test_105():
assert is_highfive(105)
def test_100():
assert not is_highfive(100)
def test_106():
assert not is_highfive(106)
Explanation¶
How to run these tests
Shell / Terminal
cd path/to/highfive/
pytest
(You should see three green dots indicating that each test passed.)
What about this?
def test_is_highfive():
assert is_highfive(105)
assert not is_highfive(100)
assert not is_highfive(106)
When you put multiple assertions in one test function, if one of the assertions fails, the function stops executing and none of the remaining assertions are tested. In other words, test functions pass or fail "as a whole". Sometimes this is desirable, but in this example we wanted each test to run, regardless of whether one of them fails.
Solution 2¶
test_highfive.py
import pytest
from highfive import is_highfive
@pytest.mark.parametrize(
"test_input, expected",
[(105, True), (100, False), (106, False)]
)
def test_is_highfive(test_input, expected):
assert is_highfive(test_input) == expected
Explanation¶
This is equivalent to Solution 1 but less wordy.
-
Define a generic test function with two parameters:
test_input
andexpected
.from highfive import is_highfive def test_is_highfive(test_input, expected): assert is_highfive(test_input) == expected
-
Decorate the function with the
@pytest.mark.parametrize
decorator, passing in- a string representation of the input parameters
- a list of (a, b) tuples representing each (
test_input
,expected
) pair
import pytest from highfive import is_highfive @pytest.mark.parametrize( "test_input, expected", [(105, True), (100, False), (106, False)] ) def test_is_highfive(test_input, expected): assert is_highfive(test_input) == expected
Note that using the parametrize decorator requires us to
import pytest
.