To create a valid unittest test suite there are a few things you need to keep in mind. In the following sections, you'll step through creating tests following a small example. Later, you'll apply the same process to add tests to your web scraper code that you wrote in one of the previous sections of the course.
Useful TDD Guidelines
You'll start with a couple of high-level guidelines that you should apply to all of your test suites when using the unittest package.
Use test_ in File Names
The files containing your unittest tests should all be prefixed with the word test_. This is important for the test module to run correctly.
Give Descriptive File Names
Name your testing files in a way so it is crystal clear what code the test file refers to. For example, a descriptive file name for your test suite could be test_your_package_name.py.
Info: Tests are not the place to get creative! You've got other parts of your coding projects to do that. Tests are there to keep your creative explorations in check, which is why you should approach them with the appropriate dryness.
Keep Test and Code Files Together
Keep your test files together with your other code files. That allows you to quickly see code files and test files side-by-side.
Inherit From unittest.TestCase
The unittest module relies on a lot of pre-built functionality. By inheriting from unittest.TestCase when you create your test class, you make sure that you'll be able to utilize that pre-built functionality.
Use a Descriptive Test Class Name
Similar to naming your files descriptively, you'll want to do the same for your test functions. For example, if you are testing whether a number will always be above zero, your test file name could be test_number_always_above_zero().
Basic Code Structure
The code that you could come up with if you apply the guidelines mentioned above could be saved in a file structure like this:
├── your_package_name.py
└── test_your_package_name.py
The general structure of your test file, test_your_package_name.py, could then look like below:
import unittest
import your_package_name
class TestYourPackageName(unittest.TestCase):
def test_your_package_name_function_does_what_it_says(self):
# Write your specific test case in here
pass
As you might see, both the file naming and the code you're writing try to be as specific and descriptive as possible.
In the next lesson, you'll learn more about the structure of a test case method, and you'll apply all these concepts in practice by building tests that can check the correct functionality of Python's math module.
Summary: Test-Driven Development Best Practices
- Tests make code more stable
- The
unittestframework is a popular Python testing framework
Useful TDD Guidelines
- Use
test_in file names - Give descriptive file names
- Keep your test and code files together
- Inherit from
unittest.TestCase() - Use a descriptive test class name