Mock in Python
Using Mock in appropriate ways!
What is Mocking?
Mocking an object is a way to substitutes and imitates a real object/function within a testing environment. It is a powerful way for improving the quality of your tests.
Why we need Mock?
Mock is needed to control the environment so that the external services that you use are behaving as you expected. Controlled environment is the best place to test your code because anything that outside of your code base will works in a predictable way.
When to use Mock?
- Controlling your code’s behavior during testing.
- Inspecting code, such as how much a method got called, how a method got called, and is a method got called.
- Using external services that uses HTTP Requests
Mocking in Python
Python provides a package that can be utilized for testing, that is unittest. The unittest package contains a sub-package mock that can used for mocking an object. So, mocking in python is basically utilizing unittest.mock package to replace some services that outside of our application scope, such as external services.
Example
Here, I’m gonna explain how I use mock in my PPL Project. Take a look at the code below.
For context, this function act as a callback for Google’s OAuth2.
So, in Python, mocking can be done by using patch function from unittest.mock package. In the above example, I setting up Mock in setUp function of the TestCase. I mocked one function and one object in authentication/views.py, they are requests.get and Flow.
Flow and requests.get are making HTTP Requests to external services. Because of that, they have to be mocked in order to create a predictable response/output when they are called. Besides that, making HTTP Requests to external services is something that can’t be done in the inside of Django Test Environment because it is an isolated environment.
In mocked Flow, the only method that I set it’s return value is credentials because I need it’s return value to be changed as dict by credentials_to_dict function. Then, I also specify the return value of requests.get so that it’s return value will be used by the codes that come after it.
After finishing the setUp, I created test_oauth2callback_success function that will simulate HTTP GET Request into /auth/oauth2callback/ url. Then, it will check what is the response’s status code, is the from_client_secrets_file got called, and is the response’s url pattern matched with the given regex pattern.
I think, that’s all I can share about Mocking in Python. I hope that you find it useful and informative for your programming journey.
Feel free to check out my other stories! Thanks for reading until the end! See ya!