Unit tests and test cases
- unit test – verifies that one specific aspect of a function’s behavior is correct
- test case – a collection of unit tests that together prove that function behaves as it’s supposed to, within the full range of situations you expect it to handle
- full coverage – includes a full range of unit tests covering all the possible ways you can use a function
- prioritize gearing your tests for critical behavior before aiming for full coverage
A passing test
- write a test function that will call the function we’re testing
- we’ll make an assertion about the value that’s returned
- if our assertion is correct, the test will pass
- first test of the function get_formatted_name()
test_name_function.py
from name_function import get_formatted_name
.
def test_first_last_name():
….”””Do names like ‘Hanis Joplin’ work?”””
formatted_name = get_formatted_name(‘janis’, ‘joplin’)
assert formatted_name == ‘Janis Joplin’
- name of the test file must start with test_ so pytest can discover it and run its tests in the file
- we import the function we want to test: get_formatted_name()
- test names should be longer and more descriptive
- never call function itself, that falls within the scope of pytest
- next, we call the function we’re testing, here we call get_formatted_name() with the arguments ‘janis’ and ‘joplin’, like we used when we ran names.py
- assign return value fo this function to formatted_name
- make an assertion
- assertion – a claim about a condition
- claim the value of formatted_name should be ‘Janis Joplin’
End of study session.