owned this note
owned this note
Published
Linked with GitHub
---
title: Python Testing Guide
tags: resources
---
# Python Testing Guide
## Testing
1. All functions (including helper functions and testing functions) require examples/test cases
2. Examples/test cases should reflect various input scenarios so that you exercise the possible main behaviors of your function. You do not need to test every input or every input combination, but rather enough to be confident that your function works with various inputs.
3. Test the "edge cases" of functions. For example, functions that take in numeric inputs and work differently depending on the range that number is in should test the boundaries of those ranges.
4. Even if your function does not work as expected, you can still write examples/test cases for it and receive full testing credit.
6. If a function has a side effect (like modifying a list), **test that side effect**.
7. If a function both has a side effect *and* returns information, test **both the main return and the side effect**.
8. If a function *fails* in certain cases, test that failure (see below example on how to test errors).
9. If a function modifies (or mutates) data, set up testing data rather than working on a global piece of data/dataset.
### Setting up `pytest`
* To use pytest, you need to install the package first:
* Install the pytest package in your terminal by running `pip3 install pytest`
* Then, put `import pytest` at the top of your Python test file.
* All of your tests must be contained within functions that begin with `test_`
* **Example of good testing:**
```python=
import pytest
def test_rem_if_gt_3(lst: list, numb: int):
""" given a list and a number, remove that
number from the list if it is greater than 3
do nothing if the numb is <= 3. raise an error
if numb is not in the list """
if numb not in lst:
raise ValueError('numb must be in list')
if numb > 3:
lst.remove(numb)
def test_rem():
""" tests the rem_if_gt_3 function """
test_list = [0, 4, 5, 3]
rem_if_gt_3(test_list, 4)
assert test_list == [0, 5, 3]
assert rem_if_gt_3(test_list, 0) is None
# testing errors:
with pytest.raises(ValueError):
rem_if_gt_3(test_list, 6)
with pytest.raises(ValueError):
rem_if_gt_3(test_list, 2)
```
<!-- ## Specific -->
---
*Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS200 document by filling out the [anonymous feedback form](https://forms.gle/JipS5Y32eRUdZcSZ6)!* *(you do have to sign in but we don't see it)*