At Solid GEAR, we don’t understand development without creating unit tests. They are essential in order to satisfy the new functionality will be working as expected and we have not modified the current functionality.
TDD (Test-Driven Development) is part of our philosophy when we develop. In brief, it consists in thinking all possible test cases, code them and develop the necessary code to satisfy them all. Carrying out this methodology, we get a simple code, with the minimum amount of lines of possible code, and avoiding a lot of possible bugs. As you can see, great advantages.
ISSUES CREATING TESTS
Sometimes, when we start to code test cases, we realize that we don’t have enough data in the current database, or it is very difficult to introduce the necessary conditions to follow with the test or even, we just need to make sure that a method is called. So, we wish to have the possibility of faking data or assuming a particular method is called.
Is it possible to fulfill these wishes of mocking code in Python? Yes, it is with MOCK, a python library designed for testing.
There are different ways to use this library, but I will explain just one in this article: how to use patch method as decorator, in particular, I will explain the patch.object alternative.
HOW CAN WE USE THIS LIBRARY?
The first step, obviously, is to install the library.
pip install mock
Secondly, import the library patch method from mock library to the source file.
from mock import patch
And finally, the way of using that method is including it to above the definition of the method as decorator. What this decorator does is to replace the object with a mock at the beginning of the execution of the test and restore it when the test is ended.
@patch.object(SomeClass, “some_class_method”) def test_a (mock_class_method):
In this example, the some_class_method of SomeClass will be replaced by the mock object given as param:mock_class_method.
You can patch multiple methods, what only you need to do is to nest as many patch decorators you need and pass mock objects and in the same order they are applied in the decorated function. This means from the bottom up. For example, mocking 2 methods from different classes will be as well as following:
@patch.object(SomeClassA, “some_class_a_method”) @patch.object(SomeClassB, “some_class_b_method”) def test_b (mock_class_b_method, mock_class_a_method):
WHAT CAN WE DO WITH THIS LIBRARY?
Basically, replace some pieces of code in order to:
- Return always the same value.
- Not run methods but making sure they are called.
- Perform side effects, including raising exceptions.
I will explain these cases in later articles, but if you are not patient, check out the mock library documentation.