What is Mock?
The word Mock has the meaning of simulation in English, so we can guess that the main function of this library is to simulate something. To be precise, Mock is a library in Python that supports unit testing. Its main function is to replace the specified Python object with a mock object to achieve the behavior of the mock object. Simply put, the mock library is used in the following scenarios:
Suppose the project you are developing is called a, which contains a module b. A function c (also known as abc) in module b needs to call to send a request to a specific server to get a JSON return value when working, and then return according to this. Value to do. What if you want to write a unit test for the abc function?
An easy way is to set up a test server, and let the abc function interact with the test server during unit testing. But this approach has two problems:
The test server may be very difficult to set up, or the build efficiency is very low.
The test server you set up may not be able to return all possible values, or it may take a lot of work to get there.
So how do you perform unit tests for this situation without a test server? The Mock module is the answer. As mentioned above, the mock module can replace Python objects. Let's assume that the code for abc is as follows:
Import requests
Defc(url):
Resp = requests.get(url)
# further process with resp
If you use the mock module, you can achieve this effect: replace the request.get function with a mock object, and then execute the function c, the return value of the call to requests.get can be determined by our mock object. No need for server involvement. To put it simply, we replace the process of interacting with the c function and the server with a mock object. You must be curious as to how this function is implemented. This is the internal implementation mechanism of the mock module and is beyond the scope of this article. This article focuses on how to use the mock module to solve the unit test scenario mentioned above.
Mock installation and import
In versions prior to Python 3.3, an additional mock module was required, which can be installed using the pip command:
$sudo pip install mock
Then you can import directly in the code:
Import mock
Starting with Python 3.3, the mock module has been merged into the standard library and is named unittest.mock, which can be imported directly into use:
From unittest import mock
Mock object
Basic usage
The Mock object is the most important concept in the mock module. The Mock object is an instance of a class in the mock module. An instance of this class can be used to replace other Python objects to achieve the simulated effect. The Mock class is defined as follows:
classMock(spec=None,side_effect=None,return_value=DEFAULT,wraps=None,name=None,spec_set=None, **kwargs)
The definition given here is just to show that the Mock object is actually a Python class. Of course, its internal implementation is very clever. If you are interested, you can look at the code of the mock module.
The general usage of Mock objects is this:
Find the object you want to replace. This object can be a class, a function, or an instance of a class.
Then instantiate the Mock class to get a mock object, and set the behavior of the mock object, such as what value is returned when called, what value is returned when the member is accessed, and so on.
Use this mock object to replace the object we want to replace, which is the object identified in step 1.
After that, you can start writing test code. At this time, we can guarantee that the object we replaced will behave the same as we preset in the execution of the test case.
For example: We have a simple client implementation that is used to access a URL. When the access is normal, we need to return a status code of 200. If it is not normal, we need to return a status code of 404. First, our client code is implemented as follows:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Import requests
Def send_request(url):
r = requests.get(url)
Returnr.status_code
Def visit_ustack():
Returnsend_request('http://')
The external module calls visit_ustack() to access the official website of UnitedStack. Below we use the mock object to test the normal access and abnormal access in the unit test.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Import unittest
Import mock
Import client
classTestClient(unittest.TestCase):
Def test_success_request(self):
Success_send = mock.Mock(return_value='200')
Client.send_request = success_send
self.assertEqual(client.visit_ustack(), '200')
Def test_fail_request(self):
Fail_send = mock.Mock(return_value='404')
Client.send_request = fail_send
self.assertEqual(client.visit_ustack(), '404')
Find the object to replace: we need to test the visit_ustack function, then we need to replace the send_request function.
Instantiate the Mock class to get a mock object and set the behavior of this mock object. In the successful test, we set the return value of the mock object to the string "200". In the failure test, we set the return value of the mock object to the string "404".
Use this mock object to replace the object we want to replace. We replaced client.send_request
Write the test code. We call client.visit_ustack() and expect its return value to be the same as our default.
The above is the basic step of using a mock object. In the above example, we replaced the object of the module we wrote. In fact, we can replace the object of the standard library and the third-party module. The method is the same: first import and then replace the specified object.
Slightly advanced point usage
Class Mock parameters
The above is the most basic usage of the mock object. Let's take a look at the slightly advanced usage of the mock object (not very advanced, the most complete and advanced to go directly to the mock documentation, given later).
Let's take a look at the parameters of the Mock class. In the class definitions seen above, we know that it has several parameters. Here are the main ones:
Name: This is used to name a mock object, just to identify it. When you print a mock object, you can see its name.
Return_value: This we have just used, this field can specify a value (or object), when the mock object is called, if the side_effect function returns DEFAULT, the call to the mock object will return the value specified by return_value.
Side_effect: This parameter points to a callable object, which is usually a function. When the mock object is called, if the return value of the function is not DEFAULT, then the return value of the function is used as the return value of the mock object call.
Please refer to the official documentation for other parameters.
Automatic creation of mock objects
When accessing a property that does not exist in a mock object, the mock automatically creates a child mock object and points the property being accessed to it. This function is convenient for implementing a multi-level property mock.
Client = mock.Mock()
Client.v2_client.get.return_value = '200'
At this time, you get a mock client instance, and the v2_client.get() method that calls the instance will get a return value of "200".
As you can see from the above example, the return_value of the specified mock object can also use the method of attribute assignment.
Check the method call
The mock object has methods that can be used to check if the object has been called, what parameters were called, how many times it was called, and so on. To implement these functions, you can call the method of the mock object. You can view the mock documentation specifically. Here we give an example.
Still using the above code, this time we need to check if the parameter type passed by the visit_ustack() function calls the send_request() function. We can use the mock object like this.
classTestClient(unittest.TestCase):
Def test_call_send_request_with_right_arguments(self):
Client.send_request = mock.Mock()
Client.visit_ustack()
self.assertEqual(client.send_request.called,True)
Call_args = client.send_request.call_args
self.assertIsInstance(call_args[0][0], str)
The called property of the Mock object indicates whether the mock object has been called.
The call_args of the Mock object represents the tuple that the mock object is called, and each member of the tuple is a mock.call object. The mock.call object represents a call to a mock object whose content is a tuple with two elements, the first element is the positional argument (*args) when the mock object is called, and the second element is the call to the mock object. Keyword parameters (**kwargs).
Now to analyze the above use case, we have two items to check:
Visit_ustack() calls send_request()
The parameter called is a string
Patch and patch.object
After learning about the mock object, let's look at two functions that are easy to test: patch and patch.object. Both of these functions return a class instance inside the mock, which is class _patch. The returned class instance can be used as a decorator for a function, as a decorator for a class, or as a context manager. The purpose of using patch or patch.object is to control the scope of the mock, meaning to mock an object within a function scope, or within the scope of a class, or within the scope of a with statement. Let's look at a code example:
classTestClient(unittest.TestCase):
Def test_success_request(self):
Status_code = '200'
Success_send = mock.Mock(return_value=status_code)
With mock.patch('client.send_request',success_send):
From client import visit_ustack
self.assertEqual(visit_ustack(),status_code)
Def test_fail_request(self):
Status_code = '404'
Fail_send = mock.Mock(return_value=status_code)
With mock.patch('client.send_request',fail_send):
From client import visit_ustack
self.assertEqual(visit_ustack(),status_code)
This test class, like the first test class we just wrote, contains two tests, but this time instead of showing the creation of a mock object and replacing it, we use the patch function (used as a context manager).
The effect of patch.object and patch is the same, but the usage is a bit different. For example, the same example above, replaced with patch.object is this:
Def test_fail_request(self):
Status_code = '404'
Fail_send = mock.Mock(return_value=status_code)
With mock.patch.object(client,'send_request',fail_send):
From client import visit_ustack
self.assertEqual(visit_ustack(),status_code)
Is to replace the attribute of a specified name of an object, the usage is similar to setattr.
How to learn to use the mock?
You must be very strange, this article is not to teach people to use the mock? Actually not, I found that the main difficulty I encountered in learning the mock is that I don't know what the mock can do, not what the mock object actually has. So the main purpose of writing this article is to illustrate what the mock can do.
When you know what a mock can do, how do you learn and master the mock? The best way is to read the official documentation and use it in your own unit tests.
Finally, to learn the mock skills you should be able to feel the thrill of control, that is, you can enjoy the joy of controlling external services. When you feel this pleasure, your mock should reach the level of proficiency.
Neck bluetooth headset - a bluetooth headset with headphone cables or accessories running from the neck to the ear when wearing. It is a product developed in recent years.
Born: in order to solve the boring when running or control the exercise rhythm, many people choose to listen to music,however, experienced people all know that because of the swing in the process of exercise, the earphones are easy to fall off, which makes it difficult to run coherently and constantly ,under this circumstance, the bluetooth neckband headphones was designed.
Features:
1: There is no restrained from headphone cables.
2: In line with the development trend of headphones: From the perspective of the development trend of consumer headphones, bluetooth neckband headphones should be regarded as the general trend. Whether it is sports headset or head-worn headset, many manufacturers are vigorously developing bluetooth headset to occupy the market.
3: Not affected by audio interface
More and more flagship mobile phones are also trying to cancel the audio interface, which is the important reason for the generation of bluetooth neckband headset. As long as the device that supports bluetooth music play is ok, the audio interface will not be considered.
4: No burden when running
Sports neck hanging bluetooth headset is light and easy to wear, more convenient and fast storage, no knot, more relaxed entertainment sports, let you run zero burden.
5: Waterproof and sweat-proof are very important
When exercising, people will sweat a lot, which may cause some damage to the ears. The bluetooth neckband headphones adopts the IPX5 waterproof design, which is more suitable for sports scenes. Especially in summer, when sweat is easy to happen, it is necessary to use the bluetooth neckband headphones.
Wireless Headphone,Bluetooth Headphones Wireless,Bluetooth Headphone Neckband,Neckband Bluetooth Headphones
Shenzhen Linx Technology Co., Ltd. , https://www.linxheadphone.com