How python uses Mock in testing

  • 2021-09-12 01:44:30
  • OfStack

Directory Mock Concept
Mock class
Simple example experience the functional characteristics of Mock a relatively formal example of Mock
1 complete test example assertion method

Mock Concept

mock means simulation, that is, simulating the information returned by the interface, replacing the information it needs to return with the existing information, from the implementation to the test of the dependent module.

1 There are two scenarios:

mock of front-end to back-end interface, The mock involved in testing between back-end services often occurs during unit testing.

The front-end mock can be accomplished with one tool:

It is realized by Fiddler and Charles, and the test of various scenarios is realized by modifying the data returned by the agent. Use some API management tools to simulate, such as yapi, Easy, Mock, etc Of course, if you have coding ability, you can also use fastAPI of node. js and python to simulate it

The back-end Mock is from the interface point of view. If the data returned by one interface A needs to depend on another interface B, Mock will be needed when the B interface is not fully developed in agile development.

For testers, when testing interfaces, some interfaces have not been developed. After the interface definition is agreed, Mock can also be used to simulate.

In python3. X, the Mock module has been integrated into the unittest.

Class Mock

class Mock(spec=None,side_effect=None,return_value=DEFAULT,name=None)

spec: Defines the attribute value of an Mock object, which can be a list, a string, and an instance of an object side_effect: Can be used to throw exceptions or dynamically change the return value, and can override return_value return_value: Defines the return value of mock name: The identity of the mock object can be seen at print

Experience the functional characteristics of Mock under simple examples


from unittest import mock
def add(num1,num2):
 return num1 + num2 # pass
 
add = mock.Mock(return_value=200) #  Create mock Object 
 
print( add(10,20) )

You will find that no matter what the input parameters are, the output result is 200. Equal to the method being intercepted by Mock.

A relatively formal example of Mock

Normal conditions:


import requests
def request_scm():
 # res = requests.get('http://www.mysx-scm.com')
 res = requests.get('http://baidu.com')
 return res.status_code

import unittest
from unittest import mock
class TestScmApi(unittest.TestCase):
 
 def testUrl(self):
  # request_scm = mock.Mock(return_value=200)
  self.assertEqual(request_scm(), 200, msg='testUrl  An error occurred ')

if __name__ == '__main__':
 unittest.main()

You can try moving two # comments to the next sentence respectively.

1 complete test example


import requests

class scmapi():
 def request_scm():
  res = requests.get('http://www.mysx-scm.com')
  # res = requests.get('http://baidu.com')
  return res.status_code

 def pay_alipay():
  '''
   To be implemented 
  return 200
  '''
  return 0
 

import unittest
from unittest import mock

class TestScmApi(unittest.TestCase):
 
 needmock = True
 def setUpClass():
  print("setUpClass(): Execute before all methods ")

 def tearDownClass():
  print("tearDownClass(): Execute after all methods ")
  
 def setUp(self):
  self.scmapi = scmapi()
  print("setUp(): Execute before each method ")

 def tearDown(self):
  print("teardown(): Execute after each method ")
 
 def test_request_scm(self):
  if self.needmock:
   scmapi.request_scm = mock.Mock(return_value=200)
  self.assertEqual(scmapi.request_scm(), 200, msg='test_request_scm  An error occurred ')

 def test_pay_alipay(self):
  if self.needmock:
   scmapi.pay_alipay = mock.Mock(return_value=200)
  self.assertEqual(scmapi.pay_alipay(), 200, msg='test_pay_alipay  An error occurred ')

if __name__ == '__main__':
 unittest.main()

Assertion method

The basic assertion method provides whether the test result is True or False. All assertion methods have one msg parameter, and if the value of the msg parameter is specified, this information is returned as a failure error message.

序号 断言方法 断言描述
1 assertEqual(arg1, arg2, msg=None) 验证arg1=arg2,不等则fail
2 assertNotEqual(arg1, arg2, msg=None) 验证arg1 != arg2, 相等则fail
3 assertTrue(expr, msg=None) 验证expr是true,如果为false,则fail
4 assertFalse(expr,msg=None) 验证expr是false,如果为true,则fail
5 assertIs(arg1, arg2, msg=None) 验证arg1、arg2是同1个对象,不是则fail
6 assertIsNot(arg1, arg2, msg=None) 验证arg1、arg2不是同1个对象,是则fail
7 assertIsNone(expr, msg=None) 验证expr是None,不是则fail
8 assertIsNotNone(expr, msg=None) 验证expr不是None,是则fail
9 assertIn(arg1, arg2, msg=None) 验证arg1是arg2的子串,不是则fail
10 assertNotIn(arg1, arg2, msg=None) 验证arg1不是arg2的子串,是则fail
11 assertIsInstance(obj, cls, msg=None) 验证obj是cls的实例,不是则fail
12 assertNotIsInstance(obj, cls, msg=None) 验证obj不是cls的实例,是则fail

That's how python uses Mock in testing. For more information about using Mock in python testing, please pay attention to other related articles on this site!


Related articles: