Writing unit tests presupposes that you isolate the unit of code that is being tested. Tests usually feed the function or method with some data and verify its return value and/or the side effects of its execution. This is mainly to make sure the tests include the following:
- They are concerning with an atomic part of the application, which can be a function, method, class, or interface
- They provide deterministic, reproducible results
Sometimes, the proper isolation of the program component is not obvious. For instance, if the code sends emails, it will probably call Python's smtplib module, which will work with the SMTP server through a network connection. If we want our tests to be reproducible and are just testing if emails have the desired content, then probably no real network connection needs to happen. Ideally, unit tests should run on any computer with no external dependencies and side effects.
Thanks to Python's dynamic nature, it is possible to use the monkey patching technique to modify the runtime code from the test fixture (that is, modify software dynamically at runtime without touching the source code), in order to fake the behavior of a third-party code or library. In the following sections, we will learn how to build such objects.