python Mock basic usage

Posted by blinks on Tue, 02 Nov 2021 22:22:28 +0100

Introduction to mock

Mock was originally a third-party library of Python. After Python 3, mock modules have been integrated into the unittest testing framework, so there is no need to install them separately. The word mock means simulation in English, so we can guess that the main function of this library is to simulate something. To be exact, mock is a library used to support unit testing in Python. Its main function is to use mock objects instead of specified Python objects to simulate the behavior of objects. Since mock has been integrated into the unittest unit testing framework, it can be imagined that the purpose of mock is to make us better test

 

mock action

1. Solve dependency problem: when we test an interface or function module, if the interface or function module depends on other interfaces or modules, if the dependent interface or function module has not been developed, we can use mock to simulate the dependent interface and complete the test of the target interface

2. Unit test: if a function has not been developed, we have to write the code of the test case. We can also simulate the function for test first

3. Simulate the interface of complex business: in actual work, if we test an interface function and the interface depends on a very complex interface business, we can use mock to simulate the complex business interface. In fact, this is the same principle as solving the interface dependence

4. Front and back end joint debugging: if you are developing a front-end page, you need to develop a function: display different pages according to the status returned by the background, then you need to call the background interface, but the background interface has not been developed yet. Will you stop this part of work? The answer is No. you can use mock to simulate the background interface to return the data you want

 

Payment case: use mock to complete the test when the third-party payment interface cannot be called at present

Payment function: payment.py

import requests
from unittest import mock

def request_lemonfix():
    """

    :return:
    """
    res = requests.get('http://www.lemonfix.com')
    return res.status_code.encode('utf-8')


if __name__ == '__main__':
    request_lemonfix = mock.Mock(return_value="The forum home page is displayed")
    print(request_lemonfix())
Then there is another practical example: the third-party payment interface can not be used at present mock Complete the test

import requests


class Payment:
    """
    Define third party payment category
    """
    def authe(self, card_num, amount):
        """
        Request the third-party payment interface and return the response code
        :param card_num: Card number
        :param amount: amount of money
        :return: The returned status code 200 represents successful payment and 500 represents abnormal payment
        """
        url = "https://www.dd.com"  # Third party url
        data = {"card_num": card_num, "amount": amount}
        response = requests.post(url, data=data)
        return response.status_code

    def pay(self, user_id, card_num, amount):
        """
        payment
        :param user_id: user id
        :param card_num: Card number
        :param amount: amount of money
        :return:
        """
        try:
            status_code = self.authe(card_num, amount)
        except TimeoutError:
            status_code = self.authe(card_num, amount)

        if status_code == 200:
            print("Payment successful")
            return "success"
        if status_code == 500:
            print("Payment failed")
            return "fail"

Test Case function: Mock_demo

# -*- coding: utf-8 -*-
#@Time :  2021/11/2 20:16
#@Auth :  Ann
#@File : modular.py
#@IDE : PyCharm
import requests

class Payment:
    """
    Define third party payment category
    """
    def authe(self, card_num, amount):
        """
        Request the third-party payment interface and return the response code
        :param card_num: Card number
        :param amount: amount of money
        :return: The returned status code 200 represents successful payment and 500 represents abnormal payment
        """
        url = "https://www.dd.com"  # Third party url
        data = {"card_num": card_num, "amount": amount}
        response = requests.post(url, data=data)
        return response.status_code

    def pay(self, user_id, card_num, amount):
        """
        payment
        :param user_id: user id
        :param card_num: Card number
        :param amount: amount of money
        :return:
        """
        try:
            status_code = self.authe(card_num, amount)
        except TimeoutError:
            status_code = self.authe(card_num, amount)

        if status_code == 200:
            print("Payment successful")
            return "success"
        if status_code == 500:
            print("Payment failed")
            return "fail"