Django Unit Test
Why unit test?
Tests can let us avoid breaking things when doing the refactoring.
Why mocking?
We only care about the functionality of a single fuction. For other functions that are called within this function, that’s the responsibilities for other functions.
Mock vs MagicMock
Both MagicMock and Mock allow you to mock a object. MagicMock is the subclass of Mock that provides some default implementaions for magic methods like __iter__
, __iter__
.
In this case, if you need to mock a object with a list as the attribute, then you need to use MagicMock.
- return_value
This attribute set as a single fixed vaue. You get this fixed return value every time you call the mock object.
- side_effect
This attribute usually set as a list of vaues, then every time the mock object is called, it will return one value from the list in sequence.
- patch
patch() usually works as a decorator or context manager. Note that you patch where an object is looked up, which is not necessarily the same place as where it is defined.
- factory boy (for mocking Django models or other ORM objects)
allow to declare the test-specific fields (especially for foreignkey related fields). It is supper useful when you wanna mock some foreign key related fields and you don’t bother creating an instance for the foreign key related model. This class is ususlly used to test model related functionalities
1 | # no need to create an Author instance |
- Client (for mocking http request client, Django-rest-framework)
This class acts like a “client” to make request to the server. It contains methods like login()
, get()
, post()
, patch()
, delete()
. This class is ususlly used to test API related functionalities.
TestCase:
- setUpData()
this is a classmethod, it implementes only one time for the whole test class and provides public initial data for every test cases. Therefore, don’t execute some actions that affect the these public data like deletion.
- setUp()
this is a instance method, it implements once before each test case. It is ok to execute deletion for the public data, since it is isolated for each test case and execute one time for each test case function.