Unit testing with Python
Testing your Python libraries is a great idea! Here is a simple example of how you could implement unit tests for a business logic library written in Python.
See Unit testing with Robot Framework if you want to use Robot Framework for testing your libraries.
The business logic library
The Python library implements a function for calculating net income based on revenues and expenses.
accounting.py
:
See How to write your own Robot Framework libraries in Python for more information.
Import pytest
framework as a dependency
pytest is the de facto standard framework for testing Python code.
Create a test_conda.yaml
configuration file and add pytest
as a dependency:
See Adding packages to your robot for more information.
Create a configuration file for running the tests
Create a test_robot.yaml
configuration file for running the pytest
command:
See Robot YAML configuration format for more information.
Implement tests for the business logic library
Create a test_accounting.py
file for implementing the tests for the business logic:
pytest will run all files of the form
test_*.py
or*_test.py
in the current directory and its subdirectories.
test_accounting.py
:
Run the tests with RCC
See RCC toolchain for more information.
More complex use cases
"Sometimes tests need to invoke functionality that depends on global settings or invokes code that cannot be easily tested, such as network access." - pytest.org
pytest supports mocking or monkeypatching. Read the full pytest documentation to learn about all the supported features.