Use the mock library in Python to simulate and test the Python code.
How to test without patience
Usually, the software we write interacts directly with services that we call "dirty. In layman's terms, services are crucial to our applications, and the interaction between them is well designed, but this will bring us undesirable side effects-those features that we don't want to test on our own.
For example, we may be writing a social software program and trying to test the function of publishing to Facebook, but we do not want to publish it to Facebook every time we run the test set.
There is a sub-package named unittest in the unittest library of Python. mock -- or you can declare it as a dependency and simplify it to mock -- this module provides very powerful and useful methods through which we can simulate or screen away these undesirable aspects.
Note: mock is recently included in the Python 3.3 standard library. previously released versions must download the Mock library through PyPI.
Fear system call
For another example, considering system calls, we will discuss them in the remaining articles. It is not hard to find that you can consider using simulation: Whether you want to write a script to pop up a cddriver or a web service to delete the cache files under the/tmp directory, or a socket service to bind a TCP port. These calls are not expected during unit testing.
As a developer, you are more concerned about whether your library has successfully called the system function to pop up the CD instead of opening the CD tray during each test.
As a developer, you are more concerned about whether your library has successfully called the system function to pop up CD (with correct parameters, etc ). Instead of opening the CD tray during each test (or worse, many times, when a unit test runs, many test points involve pop-up code ).
Similarly, keeping your unit test efficiency and performance means retaining "Slow code" Beyond automated testing, such as file system and network access.
For our first example, We Need To refactor a standard Python test case from the original to using mock. We will demonstrate how to use mock to write a test case to make our test smarter, faster, and exposed