Running a test
- if you run test_name_function.py directly, you won’t get an output because we never called the test function
- instead, have pytest run the test file for us
- open a terminal and navigate to the folder that contains the test file
- with VS Code, you can open the folder containing the test file and use the terminal embedded in the editor window
- in the terminal window, enter the command pytest
$ pytest
========================test session starts===================
==========
platform darwin — Python 3.x.x, pytest-8 .x.x, pluggy-1.x.x
rootdir: /…/python_work/chapter_11
collected 1 item
.
test_name_function.py .
======================== 1 passed in 0.00s ===================
==========
- can see which versions of Python, pytest, and other packages being used
- see directory where the test is being run, python_work/chapter_11
- see pytest found one test to run
- see the test file being run, single dot after the name tells us that a single test passed
- output tells us get_formatted_name() will always work for names that have a first and last name, unless we modify the function
- can test again after modifying the function
A failing test
- what does a failing test look like?
- modify get_formatted_name() so it can handle middle names, but we’ll break the function for names with just a first and last name, like Janis Joplin
name_function.py
def get_formatted_name(first, middle, last):
….”””Generate a neatly formatted full name.”””
….full_name = f”{first} {middle} {last}”
….return full_name.title()
- this version only works for people with middle names
- running pytest gives the following output
$ pytest
======================== test session starts=============
==========
–snip–
test_name_function.py F [100%]
================================= FAILURES ============
=================
________________________ test_first_last_name__________________
___
….def test_first_last_name():
……..”””Do names like ‘Janis Joplin’ work?”””
>……..formatted_name = get_formatted_name(‘janis’, ‘joplin’)
E……..TypeError: get_formatted_name() missing 1 required positional
………….argument: ‘last’
Error message continues.
- F tells us that one test has failed
- section for FAILURES because failed tests are important
- see test_first_last_name() failed
- angle bracket (>) indicates the line of code that caused the test to fail
- E shows the actual error that caused the failure: a TypeError due to a missing required positional argument, last
- most important info is repeated in a shorter summary at the end
End of study session.