zoukankan      html  css  js  c++  java
  • Mock an function to modify partial return value by special arguments on Python

    Mock an function to modify partial return value by special arguments on Python

    python mock一个带参数的方法,修改指定参数的返回值,大家直接看代码就能懂。

    want mock code:

    import requests
    
    
    def get_value(arg):
        resp = requests.get('https://httpbin.org/get', params={'k': arg})
        return resp.json()['args']
    
    def main():
        # just mock while arg == 'bad'
        print(get_value('bad'))
        print(get_value('good'))
    
    if __name__ == '__main__':
        main()
    

    mock code:

    import unittest.mock
    import mock_func
    
    
    class TestMockFunc(unittest.TestCase):
        def test_main(self):
            '''style 1: using with statement and nested function'''
            print('test_main')
    
            # backup original function for normal call
            orig_func = mock_func.get_value
    
            # nested function for mock side_effect
            def fake_get_value(arg):
                if arg == 'bad':
                    return {'k': 'mock_value'}
                else:
                    return orig_func(arg)
    
            # patch function
            with unittest.mock.patch('mock_func.get_value') as mock_get_value:
                mock_get_value.side_effect = fake_get_value
                mock_func.main()
    
        # backup original function for normal call at class or global
        orig_func = mock_func.get_value
    
        # patch using decorator
        @unittest.mock.patch('mock_func.get_value')
        def test_main_other(self, mock_get_value):
            '''style 2: using with statement and nested function'''
            print('test_main_other')
    
            # using lambda instead of nested function
            mock_get_value.side_effect = lambda arg: 
                {'k': 'mock_value'} 
                if arg == 'bad' 
                else TestMockFunc.orig_func(arg)
    
            mock_func.main()
    
    if __name__ == '__main__':
        unittest.main()
    
  • 相关阅读:
    最佳调度问题_分支限界法
    运动员最佳配对问题
    最小重量机器设计问题
    实现银行家算法和先进先出算法_对文件读写数据
    n皇后问题_回溯法
    0-1背包_回溯法
    根据前序、中序、后序遍历还原二叉树
    矩阵连乘问题_动态规划
    最长公共子序列_动态规划
    最优二叉查找树_动态规划
  • 原文地址:https://www.cnblogs.com/eshizhan/p/7629084.html
Copyright © 2011-2022 走看看