Mocking in Python Has Never Been Easier
This article assumes you already know your way around Python mocks and Pytest and that you’re familiar with the Arrange-Act-Assert pattern.
If you need a short recap, I find the following articles useful:
What the mock? A cheatsheet for mocking in Python
Arrange-Act-Assert: A Pattern for Writing Good Tests
I often struggle with Python mocks, this is why I wrote a library to assist me.
The Pytest Mock Generator library simplifies writing the ‘arrange’ and ‘assert’ sections. It generates the ‘arrange’ and ‘assert’ sections for you and allows you to focus on the ‘act’ section of your tests.
I’m sharing it with you, so it can save you time and effort.
Let’s assume you want to do some complex logic on a string and then write it to a zip file. Here is a short piece of code to do just that:
This is the function that you want to test (aka Unit Under Test or UUT). You don’t want to create a file on the hard drive and wish to mock it instead.
Here is where the mock generator (mg for short) fixture comes to play — it would generate both the arrange and assert sections for you.
An outline of the test method in an arrange-act-assert pattern looks like so:
Please note this line in particular:
mg.generate_uut_mocks_with_asserts(process_and_zip). It receives the tested function as a parameter and does a static code analysis to mock the various dependencies of the function.
When you execute the test, the following output is printed to the console and copied to the clipboard:
This generated code is ready to use and can be embedded in your test:
The arrange part is complete and we’re left with filling the assert section. Luckily for us, this line would generate the assert section:
mg.generate_asserts(mock_ZipFile, name=’mock_ZipFile’). Run the test function once more and you’ll get the asserts copied to the clipboard and printed to the console:
These asserts are the exact calls made to the mock we prepared earlier. They include the creation of the zip file, entering and exiting the context, and the call to create a file inside the zip and fill it with data.
Some of them are pretty low level, so I’m omitting them from the final version of the test function:
That’s it! We have done several great things in this article, so here is a short recap:
- We have a beautiful test method in no time.
- Most of the code was auto-generated.
- The helper library allowed us to focus on the main code sections.
- We have saved time and effort doing the above.
- Mocking in Python has never been easier 😊
To get started, visit https://pypi.org/project/pytest-mock-generator/.
Did this tool save you some time? If so, let me know.