current position:Home>How to implement mockserver [Python version]

How to implement mockserver [Python version]

2022-01-31 23:10:18 Mr. forgets his name

「 This is my participation 11 The fourth of the yuegengwen challenge 1 God , Check out the activity details :2021 One last more challenge 」.

mock Definition

  • What is? mock test ?
 Online Baidu Encyclopedia found such an interpretation , you 're right , What it says is mock test :
mock Testing is in the process of testing , For some objects that are not easy to construct or get , Use a virtual object to create test methods for testing .
 Copy code 
  • No mock, What will happen ?
 I think in the era of rapid development of the Internet , And it is an era of rapid response to the market , Products want to live 、 To get more users , Then it has to update iterations quickly ;
 At the Internet company , Generally, it takes half a month to iterate , The faster is to iterate in a few days , If the development mode , Is a full stack Development Engineer , That is, one person at the front and back , Not afraid of < die > I'll be right there ;
 I don't know whether it's good or bad , In short, time is indispensable , Testing is also essential ; So here comes the question , Separation of front and rear development , After the requirements review , Start breaking down tasks !!!
 Copy code 
    • 1、 Back end students began to develop interfaces , Get the front end UI The design draft starts the layout screen , But the interface didn't come out at this time ?
excuse me? Go to the front and watch the students at the back ? Urge every day , Is there an interface , Waiting for joint commissioning ? You deserve to work overtime !!!
 Then the time difference between them is the loss , Finally, the joint debugging and testing will not be started until the back-end development is completed , At this time, there is not much time left for the test students , The cycle is compact , The quality is also worrying ?
 Copy code 
    • 2、 situation 2: Back end A The development interface must rely on the back end B The interface developed by students , So is he waiting, too ?
 You think the iteration time is too long , Want to work overtime ?
 Copy code 
    • 3、 situation 3: About third party services , If it's a performance scenario , You can't press other people's servers , What to do with your own test ?
 When there is no need to pay special attention to the third-party business , What should our side do ?

No, The iteration cycle is much shorter than you think ,QA/ project manager / Technology Manager / operating / Customers are following the progress of the project , Don't wait to be hunted down , This taste will affect the quality of the project , It will also disgust people .
 Copy code 
  • How to solve this problem ?
 such , This mock The meaning of comes out , The front end is no longer dependent on the back end , Back end A No longer rely on the back end B, It's parallel development , When we reach a point when all tasks are completed ,
 Re integration testing < Front and rear end joint debugging test >, At least before the last plot can be tested , Although not absolutely early ; But it is also a good collaborative office mode .

 How can we not rely on it ?
 After the requirements review , Confirm demand , Develop and identify what needs to be done , The front and back end agree on the data structure , Give the interface document , And then start fire, I don't think there is a more comfortable way to work .
 Copy code 
  • Having finished the interpretation, problems and solutions , Next, let's look at the practical application

unittest The test framework

  • The author is used to using python, Take the standard library unittest Framework for example
 Need to have python Basics ;mock stay python2 There is a separate library in ,python3 Directly integrated in unittest The framework .
 Copy code 
  • scene 1: Interface B Dependent interface A, Then only in the interface A The interface can only be requested normally when the request is normal B
class Demo():
    def pay(self):
        """  This is a result of B Payment interface developed by students , Hang in the air ;  He will return to two states : success or Failure  {"msg":"success","code":0,"reason":None} {"msg":"failed","code":-1,"reason":" Wrong payment account or password "} reason: Return the failure reason  """
        pass
    
    
    def get_status(self):
        """ According to the status of payment results """
        res=self.pay()
        try:
            if res["msg"]=="success":
                return " Successful payment "
            elif res["msg"]=="failed":
                return " Failure to pay "
            else:
                return " Unknown exception "
        except:
            return "Error, Server exception "
 Copy code 
  • according to Demo Module design unit test case
import unittest
from unittest import mock

class TestPayStatus(unittest.TestCase):
    """ Unit Test Case """
    
    #  Instantiate objects 
    demo=Demo()
    
    def test_success(self):
        """ Test payment success scenarios """
        #  Simulate successful payment response 
        self.demo.pay=mock.Mock(return_value={"msg":"success","code":0,"reason":None})
        status=self.demo.get_status()
        #  Assertion 
        self.assertEqual(status, " Successful payment ")
        
    def test_failed(self):
        """ Test payment failure scenarios """
        #  Simulate payment failure response 
        self.demo.pay=mock.Mock(return_value={"msg":"failed","code":-1,"reason":" Wrong payment account or password "})
        status=self.demo.get_status()
        #  Assertion 
        self.assertEqual(status, " Failure to pay ")
    
    def test_error(self):
        """ Test exception scenarios """
        #  Simulate payment failure response 
        self.demo.pay=mock.Mock(return_value={"msg":"error","code":-2,"reason":" Unknown exception "})
        status=self.demo.get_status()
        #  Assertion 
        self.assertEqual(status, " Unknown exception ")
    
    def test_error2(self):
        """ Test the server exception scenario """
        #  Simulate payment failure response 
        self.demo.pay=mock.Mock(return_value={})
        status=self.demo.get_status()
        #  Assertion 
        self.assertEqual(status, "Error, Server exception ")
 Copy code 
  • The above case , Is it simple , And the use case coverage reaches 100%

copyright notice
author[Mr. forgets his name],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312310141334.html

Random recommended