If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best practice here?
A unit test is a test that checks a single component of code, usually modularized as a function, and ensures that it performs as expected. Unit tests are an important part of regression testing to ensure that the code still functions as expected after making changes to the code and helps ensure code stability.
Who performs Unit Testing? Unit testing is the first software testing phase in SDLC and it is usually taken up during the development of the application. These unit test cases are written and executed by software developers.
Note that the order in which the various test cases will be run is determined by sorting the test function names with respect to the built-in ordering for strings.
An exception object is created when a Python script raises an exception. If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.
For a file module.py
, the unit test should normally be called test_module.py
, following Pythonic naming conventions.
There are several commonly accepted places to put test_module.py
:
module.py
.../tests/test_module.py
(at the same level as the code directory).tests/test_module.py
(one level under the code directory).I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with test_
. Actually, the default unittest
pattern used for test discovery is test*.py
.
If there has only 1 test files, putting it in a top-level directory is recommended:
module/ lib/ __init__.py module.py test.py
Run the test in CLI
python test.py
If has many test files, put it in a tests
folder:
module/ lib/ __init__.py module.py tests/ test_module.py test_module_function.py
# test_module.py import unittest from lib import module class TestModule(unittest.TestCase): def test_module(self): pass if __name__ == '__main__': unittest.main()
Run the test in CLI
# In top-level /module/ folder python -m tests.test_module python -m tests.test_module_function
unittest discovery
unittest discovery
will find all test in package folder.
Create a __init__.py
in tests/
folder
module/ lib/ __init__.py module.py tests/ __init__.py test_module.py test_module_function.py
Run the test in CLI
# In top-level /module/ folder # -s, --start-directory (default current directory) # -p, --pattern (default test*.py) python -m unittest discover
pytest
Good Practices for test layoutunittest
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With