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()
    
  • 相关阅读:
    Ajax
    Linux安装SmartSVN及破解
    JQuery异步提交
    动画效果
    事件
    表单选择器
    DOM操作
    JQuery基础
    PHP环境配置
    DP--钢条切割
  • 原文地址:https://www.cnblogs.com/eshizhan/p/7629084.html
Copyright © 2011-2022 走看看