Python mock module Use (i)

Source: Internet
Author: User

What is a mock

Unittest.mock is a library for unit testing in Python, a mock translation is the meaning of the simulation, as the name implies, the main function of this library is to simulate something.
Its main function is to use mock objects instead of the specified Python object to achieve the behavior of the simulated object.

Learning Python automation is not unfamiliar to unittest, UnitTest is actually a unit testing framework,
But for unit testing, it is estimated that many small partners do not understand, unit testing is the highest level of automated testing, where the mock is the unit test of the spinal cord

What a mock can do:
    • 1. Before and after the end of the joint, if you are a front-end page development, now you need to develop a feature:
      The next order, Payment page interface, according to payment results, payment success, show payment success page, payment failure, show payment failure page.
      To accomplish this, you need to invoke the backend interface and display the different pages based on the results returned to you. At this point, the backend interface has not been developed.
      As a front-end development can not wait for others to develop, you re-development, then you only have to work overtime life.
      In order to synchronize the development of the task, at this time, you can according to the interface documentation, the interface of the address and access to the past, and then mock the interface of the different return interface, to complete the front-end development tasks

    • 2. Unit testing, the purpose of unit testing is to test the function of a small unit, but the actual development of functions or methods are dependent, such as the parameters of the B function, you need to call a function return results, but I have already tested a function
      In this case, you do not need to test a function again, you can use the mock module to simulate the invocation of this part of the content, and give the results of the return

    • 3. Third-party interface dependencies, in the interface automation, sometimes need to call the third-party interface, but the other company's interface services are not under your control, it is possible to provide a test environment for you to open today, others turned off,
      A lot of trouble for the Automation interface test, you can write a mock-server to simulate the interface return data

Mock environment preparation

1.python2.x version, mock is a standalone module that needs to be installed with PIP

Pip Install-u Mock

3. The version of the mock from Python 3.3 has been incorporated into the UnitTest module, which is part of the UnitTest unit test and is directly imported.

From unittest import mock

Dependent relationships

1. The following scenario: The payment is a separate interface, provided by other development, based on the payment of the interface return status to show failure, or success, this is the function you need to implement

That is to say you write a B function, your colleague writes a function, your B function needs to judge according to the result of a function, then realizes the corresponding function. This is the existence of dependencies, the progress of your colleague's development is beyond your control.
If you wait for him to develop, and you develop again, you should wait for overtime.

2. The following is the function of the zhifu_statues () function which is written by oneself, it is probably designed as follows, save as temple.py file

# Save As Temple.py# Coding:utf-8# SHANGHAI-long QQ Exchange Group: 588402570DefZhifu():"' Suppose here is a paid function that has not been developed to complete the payment successfully returned: {" result ":" Success "," Reason ":" Null "} Payment failed to return: {" result ":" Fail "," reason ":" Insufficient Balance "} Reason return failure reason ' 'PassDefZhifu_statues(): " success or fail according to the result of the payment, the judgment jumps to the corresponding page" "result = Zhifu () print (result) try: if result[" result "] = = "Success": return "Payment succeeded" elif result["result"] = = "fail": Print ("Reason for failure:%s"% result[" Reason "]) return " Payment failed " else: return " Unknown error exception " except: return " error, the service side returned an exception! "  

3. Unit Test Case Design

# Coding:utf-8From UnitTestImport mockImport UnitTestImport Temple# SHANGHAI-long QQ Exchange Group: 588402570ClassTest_zhifu_statues(UnitTest. TestCase):' Unit test case 'DefTest_01(self):"Test Payment Success Scenario"# Mock a paid success data Temple.zhifu = mock. Mock (return_value={"Result":"Success", "reason":  "null"}) # according to the Payment results test page Jump statues = temple.zhifu_statues () print (statues) self.assertequal (statues, Span class= "hljs-string" > "payment success") def test_02 "Test payment failure Scenario" # mock a payment successful data Temple.zhifu = mock. Mock (Return_value={ "result":  "fail",  "reason":  "insufficient Balance"}) # based on payment results test page Jump statues = temple.zhifu_statues () self.assertequal (statues, " payment failure ") if __name__ = " __main__ ": Unittest.main ( ) 

4. Unit testing is to ensure that each branch of the function is measured, the above zhifu_statues () function has four branches, that is to write four cases, here I only write 2, and 2 cases, you can practice

Python mock module Use (i)

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.