PyCon UK 2019

Mock Object Library: Common Pitfalls and Best Practices
09-15, 14:30–15:00 (Europe/London), Room D

This talk is an introduction to the mock object library along with a detailed discussion on common pitfalls associated with patching objects with mocks and the best practices for it. The talk would present code examples, common pitfalls, and best practices to demonstrate how to use mocks effectively.

Unit testing is an integral part of any matured software development process. Python comes with the unittest package that provides a very comprehensive unit testing framework for writing unit tests. Often, the functionality being tested depends on complex external objects that are unnecessary and/or impractical to create in unit tests. That's when we need to use mock objects to partially simulate the behaviour of the external objects in order to write the unit tests and invoke the functionality being tested. Sometimes we also need to validate whether the functionality being tested exercised the mock objects in certain ways. Python comes with a quite comprehensive mock object library in the form of unittest.mock module that fulfills these requirements of mocking objects.

This talk would discuss how to use the unittest.mock library to create mock objects, patch modules and classes, record method calls on mock objects, and make assertions about which mock methods or attributes are exercised during tests, and the arguments they are called with. Additionally, this talk would also discuss how to construct mock objects that simulate specific expected behaviour such as returning specific values, mocking a chain of method calls, asserting that a chain of methods are called, etc.

Further, this talk would dive into common pitfalls that one encounters while using unittest.mock, e.g., how patching an object at the wrong place leads to test errors, how to write good test code to verify whether a chained call was made, etc. These examples are drawn from the speaker's experience while working on Python projects.

The goal of this talk is to help Python developers with a basic knowledge of unit testing to effectively use mock objects in order to avoid common pitfalls as well as write better, simpler, and robust unit tests.

Is your proposal suitable for beginners? – yes

Sunaina Pai is a senior big data software developer from Bangalore, India. She has 9 years of experience in developing software using big data technologies in organizations such as RSA Security and Intel Security. She develops solutions using Elasticsearch, Spark, Storm, and Kafka at work. In her free time, she enjoys working on her open source projects.