recently, i started to write unittest for python applications. because what i did is data pipeline, i will use a lot of mocking and patching. this post is for recording purposes.
unittest framework is MUCH MORE POWERFUL than I expected. so let me talked about a little bit about unittest framework itself first.
Mock
Link to heading
this is one powerful object that unittest provides. basically, one can use mock = Mock() to ‘fake’ any object that you want to replace.
for example, i personally use it to replace bigquery client, and furthermore define a lot more methods for this mocked object.
return_value is one attribute that i use often, basically it will define what will be returned.
another attribute i often use is side_effect. sometimes, side_effect and return_value can accomplish the same.
patch
Link to heading
patch on import Link to heading
The main way to use unittest.mock is to patch imports in the module under test using the patch function.
if we use patch like that, we simply ‘replace’ that module.
if we use patch as decorator and not using new keyword as signature param, then it will create a new MagicMock object and pass it to function.
patch in mocking context managers Link to heading
this is another senario that I found patch is really helpful. it will ‘replace’ with open('file path') as if python really read a file.
to sum up Link to heading
currently, i am using these two things in unittest, and they already give me powerful weapon to deal with my tests. if anything come up, I will keep posting.