Introductory on Unit Testing Python Functions with Pytest, Visual Studio Code, Command-line
- Overview
- Testing module setup
- Setting up a pytest Test module
- Setting up pytest functions
- How to run pytest
- Test-driven development
- Testing steps
- Important note
- This repository shows an example of how to implement unit testing for total function
- Total function - sums the elements of the list and returns the float type number
- To install requirements use:
python3 -m pip install -r requirements.txt
To setup testing module in pytest
in the same directory with your source files add the following suffix [filename]_test.py
.
For example test module for my_program.py
will be my_program_test.py
To test the definitions of a module, first create a sibling module with the same name, but ending in _test
For example: module name --> files.my_module
, test module will be --> files.my_module_test
Add tests which are functions whose names begin with test_
For example: test_total_empty
- To run from any directory use:
python3 -m pytest -v [path_to_the_test_module.py]
- In VSCode you can use GUI version for Python unit testing. Install Python extension from Microsoft - Python
- Before you implement a function, write tests
- Keep in this mind when writing tests:
- What are some usual arguments? (Use cases)
- What are some valid but unusual arguments (Edge cases)
- Given those arguments, what is your expected return value for each set of inputs?
- Write "dummy" function that satisfies the function definition (input parameters, return values)
- Write test cases
- Run tests first time. They must fail
- Modify your dummy function, so that it passes the test
- Re-run the tests, check results. If failed go back to step 4
- Testing is no substitute for critical thinking ...
- Passing your own tests doesn't ensure your function is correct! Your tests must cover a useful range of cases
- Rule of Thumb:
- Test 2+ use cases and 1+ edge cases
- When a function has if-else statements, try to write a test that reaches each branch