Test Driven
Development Demo with PyTest
TDD
Discussed in hpr4075
Write a new test and run it. It should fail.
Write the minimal code that will pass the test
Optionally - refactor the code while ensure the tests continue to
pass
PyTest
Framework for writing software tests with python
Normally used to test python projects, but could test any software
that python can launch return input.
if you can write python, you can write tests in PyTest.
python assert - check that something is true
Test Discovery
Files named test*
Functions named test*
Demo Project
Trivial app as a demo
Print a summary of the latest HPR Episode
Title, Host, Date, Audio File
How do we get the latest show data
RSS feed
Feed parser
Feed URL
The pytest setup
The python script we want to test will be named
hpr_info.py
The test will be in a file will be named
test_hpr_info.py
test_hpr_info.py
import hpr_info
Run pytest
ModuleNotFoundError: No module named 'hpr_info'
We have written our first failing test.
The minimum code to get pytest to pass is to create an empty
file
touch hpr_info.py
Run pytest again
pytest
============================= test session starts ==============================
platform linux -- Python 3.11.8, pytest-7.4.4, pluggy-1.4.0
rootdir: /tmp/Demo
collected 0 items
What just happened
We created a file named test_hpr_info.py with a single
line to import hpr_info
We ran pytest and it failed because hpr_info.py did not exist
We created hpr_info.py and pytest ran without an
error.
This means we confirmed:
Pytest found the file named test_hpr_info.py and tried
to execute its tests
The import line is looking for a file named
hpr_info.py
Python Assert
In python, assert tests if a statement is true
For example
asert 1==1
In pytest, we can use assert to check a function returns a specific
value
assert module.function() == "Desired Output"
Without doing a comparison operator, we can also use assert to check
if something exists without specifying a specific value
assert dictionary.key
Adding a Test
Import hpr_info will allow us to test functions inside
hpr_info.py
We can reference functions inside hpr_info.py by
prepending the name with hpr_info. for example
hpr_info.HPR_FEED
The first step in finding the latest HPR episode is fetching a copy
of the feed.
Lets add a test to make sure the HPR feed is defined
import hpr_info
def test_hpr_feed_url():
assert hpr_info.HPR_FEED == "https://hackerpublicradio.org/hpr_ogg_rss.php"
pytest again
Lets run pytest again and we get the error
AttributeError: module 'hpr_info' has no attribute 'HPR_FEED'
So lets add the just enough code hpr_info.py to get the
test to pass
HPR_FEED = "https://hackerpublicradio.