The mock python unittest


1. What is the mock
unittest.mock is a library for unit testing in Python, Mock translates analog means, as the name suggests the main feature of this library is to simulate something.
Its main function is to replace the use of mock objects out of the specified Python objects, simulate the behavior in order to achieve the object.
Learned python unittest is no stranger to automate, actually unittest unit testing framework,
but unit testing, estimated that many small partners do not understand, unit testing is the highest level of automated testing, unit testing in which mock the spinal cord is located
2 What .mock do:
    end 1. FBI before and after, if you are a front page development, now need to develop a feature: the next order, payment page interface, based on the result of the payment, the payment success, demonstrated successful payment page, failure to pay , failed to show payment page. To accomplish this function, you need to call back-end interface, based on the results back to you, to show different pages. At this point the back-end interfaces have not developed well,
    as a front-end developer can not wait for someone else to develop well, and then you develop, you only overtime fate. In order to synchronize the development to complete the task, then, you can in accordance with interface documentation, and the address of the interface and the parameters passed in the past, and then return to their own different mock interface screens to complete the front-end development tasks 2. unit testing, unit testing the purpose is to test the function of a small unit, but the function or method developed in reality there are dependencies, such as parameter b function, you need to call a function returns a value, but I have already tested a function of this case, do not need to test a function of time, this time can be used to simulate the call module mock this section, and returns the result given third party interface 3. dependent, making the interface when automated, and sometimes need to call third-party interface, but other people's interface services beyond your control, there may be others provide testing services to the environment you are driving today, others will turn off,
    Automated interface testing to bring a lot of trouble, then you can write your own mock-server data interface to simulate the return of
3.mock environment ready
version of 1.python2.x, mock is an independent module, you need to install with pip
    the install -U mock PIP
3. Python 3.3 have been merged from mock to future versions of the unittest module is part unittest unit testing, come directly into the line
    from unittest import mock
dependencies
1. the following scenario: the payment is a separate interface by other development provides the interface to the payment of the return status display failure or success, you need to implement this function in accordance with
that is you write a function b, you write a colleague a function, you need to a function of b result of the function to judge, then implement a corresponding function. That's dependencies, the progress of the development of your colleagues that you can not control
if you wait for him to develop over, and then you develop, that you sit and so on overtime it.
2. The following is his writing zhifu_statues () function function, probably designed as follows save the file as temple.py
# saved as temple.py
# Coding: UTF-8

DEF Zhifu ():
    '' 'the assumption here is the function of a payment, not completely developed
    successful payment is returned: { "result": "success " , "reason": "null" }
    payment fails returns: { "result": "fail ", "reason": "


    Pass

DEF zhifu_statues ():
    '' 'according to a result of the success or fail to pay, jump to the corresponding page is determined' ''
    Result = Zhifu ()
    Print (Result)
    the try:
        IF Result [ "Result"] == "Success":
            return "pay for success"
        elif the Result [ "the Result"] == "fail":
            Print ( "failed reason:% S"% the Result [ "reason"])
            return "failure to pay"
        the else:
            return "unknown error exception"
    the except:
        return "Error, the server returns an exception!"

3. test design unit
# Coding: UTF-. 8
from the unittest the mock Import
Import the unittest
Import Temple

class Test_zhifu_statues (of unittest.TestCase):
    '' 'Unit test' ''
    DEF test_01 (Self):
        '' 'Test of successful payment scenario' ''
        # the mock data a successful payment
        temple.zhifu = mock.Mock (the return_value = { "Result": "Success", "reason": "null"})
        # payment according to the test results page jump
        Statues = temple.zhifu_statues ()
        Print (Statues)
        self.assertEqual (Statues, "pay for success")

    DEF test_02 (Self):
        '' 'paid test failure scenarios' ''
        # mock a successful payment data
        temple. zhifu = mock.Mock (return_value = { " result": "fail", "reason": " lack of balance"})
        # Jump paid according to the results of the test page
        Statues = temple.zhifu_statues ()
        self.assertEqual (Statues, "pay failure ")

IF __name__ ==" __main__ ":
    unittest.main ()

two,
the mock inside another implementation, using the patch decorators, patch () as a function of decorator, and passes it to create a simulated decor function you
Official documents address
patch Profile

1.unittest.mock.patch (target, the DEFAULT = new new, spec = None, the Create = False, spec_set = None, Autospec = None, new_callable = None, ** kwargs)
    target parameter must be a str, format 'package.module.ClassName', pay attention to the format here must write right, if you write a function or class name is a case in pakege, b.py script, there is a c function (or class), then this parameter write "abc"
    new new parameter, if I did not write, the default specified is MagicMock
    spec = True or spec_set = True, this will lead to pass patch to the object is modeled as a spec / spec_set of new_callable lets you specify will be called to create a new different class or callable objects. MagicMock use by default.

Function to explain the case

1. Subsequently, a new temple.py, the following code is written
# saved as temple.py
# Coding: UTF. 8-

DEF Zhifu ():
    '' 'is here assumed that a pay function, incompletely developed
    successful payment returns: { "result": "success ", "reason": "null"}
    payment fails returns: { "result": "fail ", "reason": "


    Pass

DEF zhifu_statues ():
    '' 'according to a result of the success or fail to pay, jump to the corresponding page is determined' ''
    Result = Zhifu ()
    Print (Result)
    the try:
        IF Result [ "Result"] == "Success":
            return "pay for success"
        elif the Result [ "the Result"] == "fail":
            Print ( "failed reason:% S"% the Result [ "reason"])
            return "failure to pay"
        the else:
            return "unknown error exception"
    the except:
        return "Error, the server returns an exception!"

2. mock.patch implemented as follows:
# Coding: UTF-. 8
from the unittest the mock Import
Import the unittest
Import Temple

class Test_zhifu_statues (the unittest.TestCase):
    '' 'unit test' ''

    @ mock.patch ( "temple.zhifu")
    test_01 DEF (Self, mock_zhifu):
        '' 'test of successful payment scenario' ''
        # Method a: mock a successful payment data
        # temple.zhifu = mock.Mock (return_value = { "result": "success", "reason ":" null "})

        # method two: mock.path decorative analog return results
        mock_zhifu.return_value = {" result ":" Success "," reason ":" null "}
        # The result of payment jump test page
        statues = temple.zhifu_statues ()
        Print (Statues)
        self.assertEqual (Statues, "pay for success")

    @ mock.patch ( "temple.zhifu")
    DEF test_02 (Self, mock_zhifu):
        '' 'paid test failure scenarios' ''
        # mock a successful payment data

        mock_zhifu.return_value = { "result": " fail", "reason": " lack of balance"}
        # payment according to the results of the test page jump
        = temple.zhifu_statues Statues ()
        self.assertEqual (Statues, "failure to pay")

IF __name__ == "__main__":
    unittest.main ()

classes and methods Case
1. If the previous temple.py which is not a function, is written classes and methods, how to use mock?
# saved as temple.py
# Coding: UTF-8
class Zhifu ():
    DEF Zhifu (Self):
        '' 'the assumption here is the function of a payment, not completely developed
        successful payment returns: { "result": "success" , "reason": "null"}
        payment fails returns: { "result": "fail ", "reason": " insufficient balance"}
        reason return failure Cause
        '' '
        Pass
class Statues ( ):
    DEF zhifu_statues (Self):
        '' 'according to a result of the success or fail to pay, jump to the corresponding page is determined''
        result = Zhifu().zhifu()
        print(result)
        try:
            the Result IF [ "the Result"] == "Success":
                return "pay for success"
            elif the Result [ "the Result"] == "Fail":
                Print ( "reason for the failure:% S"% the Result [ "reason"])
                return " payment fails, "
            the else:
                return" unknown error exception "
        the except:
            return" error, the server returns an exception "!

2 case design as

# Coding: UTF-8
from unittest Import mock
Import unittest
from temple_class Import Zhifu, Statues

class Test_zhifu_statues (unittest .TestCase):
    '' 'unit test' ''

    @ mock.patch ( "temple_class.Zhifu")
    DEF test_01 (Self,mock_Zhifu):
        '' 'paid test success scenario' ''
        a = mock_Zhifu.return_value # returned first instance, to replace the name of the class
        # instance method call, then the return value of the method alternative
        a.zhifu.return_value = { "result": " success", "reason": "null"}
        # payment according to the results of the test page jump
        Statues Statues = (). zhifu_statues ()
        Print (Statues)
        self.assertEqual (Statues, "pay for success")

    @ mock.patch ( "temple_class.Zhifu")
    DEF test_02 (Self, mock_Zhifu) :
        '' 'payment fails the test scenarios' ''
        B # = mock_Zhifu.return_value returned first instance, to replace the name of the class
        # calling method by way of example, and then the return value replacement
        b.zhifu.return_value = { "result": " fail "," reason ":" lack of balance "}
        # Jump paid according to the results of the test page
        statues = Statues ().zhifu_statues()
        print(statues)
        self.assertEqual (statues, "failure to pay")

IF __name__ == "__main__":
    unittest.main ()

3. equivalent function, here is the main multi-step, first name of the class to be a mock "a = mock_Zhifu .return_value ", and then to call the method by example.


Guess you like

Origin www.cnblogs.com/lisa2016/p/12069243.html