Python Mock interface Return data (reprint)

Source: Internet
Author: User

In the test process, in order to better expand the unit test, mock some data and objects are unavoidable, the following is the simple use of Python mock.

About Python mock, there are a lot of information on the Internet, here will not speak particularly deep, but it will be practical, after reading, at least you can let you know how the mock is used.

Return data in 1.mock object methods:

We often need such a scenario, a system with B system, B system developers slow progress, some a need to call B system API return data can not get, this time, do not change the original code, but the United needs to ensure that a system side function fully OK

Scene can be used to mock this module.

Here we assume that the B system is done the following way

system_b.py

#!/usr/bin/env python#-*-coding:utf-8-*-import jsonimport requestsdef send_request (URL):    r = requests.get (URL) C1/>return Json.loads (R.text) def visit_ustack ():    return send_request (' http://api.kanzhihu.com/getposts ') if __ name__ = = ' __main__ ':    content = Visit_ustack ()    print content

We can get the JSON data returned by http://api.kanzhihu.com/getposts this interface by calling Visit_ustack (). In the ideal test case, the test code for the A system is this way

system_a.py

#!/usr/bin/env python#-*-coding:utf-8-*-import system_bdef system_b_test ():    if System_b.visit_ustack () [' Count ' ] = =:        print "System b OK, test failed"    else:        print "System B exception, test failure" system_b_test ()

The result is obvious.

/system/library/frameworks/python.framework/versions/2.7/bin/python/users/lsf/pycharmprojects/py_pattern/ Test.pysystem b Normal, test through process finished with exit code 0

But now the bad thing is, System B's main function send_request has not been developed, we can not get the JSON format of data, of course, there are many other ways to solve the reality, but in order to maximize the simulation of B system, now can be done by mock to do this work.

A system that is not completed in reality

system_a.py

#!/usr/bin/env python#-*-coding:utf-8-*-def send_request (URL):    passdef visit_ustack ():    return Send_request (' http://api.kanzhihu.com/getposts ') if __name__ = = ' __main__ ':    content = Visit_ustack ()    print content

system_b.py

#!/usr/bin/env python#-*-coding:utf-8-*-import mockimport system_bdef system_b_test ():    = {u ' count ' : +, U ' publishtime ': U ' 1470798000 ', U ' date ': U ' 2016-08-10 ', U ' id ': U ' 2375 '}], U ' ERROR ': U '}    system_b.send_ Request = mock. Mock (return_value=mock_result)    if System_b.visit_ustack () [' count '] = =:        print "System b OK, test passed"    Else:        print "System B exception, test Failed" system_b_test ()

The result is

/system/library/frameworks/python.framework/versions/2.7/bin/python/applications/pycharm.app/contents/helpers/ pycharm/utrunner.py/users/lsf/pycharmprojects/py_pattern/test.py truetesting started at 15:24 ... system B is OK, Test through process finished with exit Code 0Empty test suite.

Here, we directly mock a JSON data to achieve the purpose of the B system return data, even we call the system is still the interface of B, the difference has been marked in red font, this is the operation of the mock.

(1) Mock_result: Prepare the required mock data

(2) Use a mock. Mock (Return_value=mock_result) sets the mock object to the return method corresponding to system B

It is worth noting that the mock. A mock (Return_value=mock_result) is an object, but why system_b.send_request = mock. The mock (return_value=mock_result) returns the data instead of the object's other properties and methods, here, because there is a side_effect attribute in the mock object, and if this property is None, it will Return_ Value is set to return.

Methods in 2.mock objects: Mock.patch and Mock.patch.object

#!/usr/bin/env python#-*-coding:utf-8-*-import Mockclass by (object):    def add (self, A, b):        return a + B + self. Multiply (b)    def multiply (self, A, b):        passb  = by () class Mockdemo (object):    def __init__ (self):        self.b  = b    @mock. Patch.object (b, ' multiply ')    def test_add (self,mock_multiply):        a = 3        b = 5        Mock_multiply.return_value =        Self.b.add (A, b) = =:            print "mock success"        else:            print " Mock Failed "if __name__ = = ' __main__ ':    Mockdemo (). Test_add ()

If the mock is a function, it can be implemented with @mock.patch (target= ' Module.func ').

Python Mock interface Return data (reprint)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.