Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模拟函数_Python_Django_Python 3.x_Unit Testing - Fatal编程技术网

Python 模拟函数

Python 模拟函数,python,django,python-3.x,unit-testing,Python,Django,Python 3.x,Unit Testing,我试图弄清楚如何在helper.py中模拟用于单元测试的几种方法中的函数 我尝试使用patch,@patch('project.helpers.function_0',new=lambda:True),但没有成功 正确的方法是什么 多谢各位 更新 我有一个函数和一个装饰器,我需要覆盖所有测试集 helpers.py def myfunction(asd): # ... return asd 装饰师 def mydecorator(func): @wraps(func)

我试图弄清楚如何在helper.py中模拟用于单元测试的几种方法中的函数

我尝试使用patch,@patch('project.helpers.function_0',new=lambda:True),但没有成功

正确的方法是什么

多谢各位


更新 我有一个函数和一个装饰器,我需要覆盖所有测试集

helpers.py

def myfunction(asd):
    # ...
    return asd
装饰师

def mydecorator(func):
    @wraps(func)
    def _wrapped_func(asd, *args, **kwargs):
        # ...
        return func(asd, *args, **kwargs)
    return _wrapped_func
我是怎么决定的 我想知道mock是如何做到这一点的,谢谢

test_base.py

import project.decorators
import project.helpers

def myfunction_mock(asd):
   # ...
   return asd
helpers.myfunction = myfunction_mock

def mydecorator_mock(func):
   # ...
decorators.mydecorator = mydecorator_mock

这里发生了一些关键的事情

  • 如果可能,您应该使用
    unittest.mock
    (或通过
    pip
    安装的
    mock
  • 您可能在错误的位置进行了修补
  • 使用
    mock.patch
    时,您可能希望使用
    new\u callable
    关键字参数,而不是
    new
  • 假设您的生产代码如下所示

    #production_module.py
    from helpers import myfunction
    
    def some_function(a):
        result = myfunction(a) + 1
        return result
    
    如果您想测试生产代码中的
    某些函数
    ,模拟
    myfunction
    您的测试代码应该修补
    production\u模块.myfunction
    而不是
    helpers.myfunction

    因此,您的测试代码可能如下所示

    import mock
    from production_module import some_function
    
    def mock_myfunction(*args, **kwargs):
        return 1
    
    @mock.patch('production_module.myfunction', new_callable=mock_myfunction)
    def test_some_function(mock_func):
        result = some_function(1) # call the production function
        assert mock_func.called # make sure the mock was actually used
        assert result == 2
    
    另一种使用
    mock.patch
    的方法是作为上下文管理器。因此,修补程序将仅适用于该上下文

    with mock.patch(...) as mock_func:
        some_function(1) # mock_func is called here
    
    some_function(1) # the mock is no longer in place here
    

    您要查找的关键字参数是
    new\u callable
    ,而不是
    new
    。看,这对我不起作用,这样在测试中给和额外的arg,我需要覆盖所有测试的函数。函数_0在我调用的其他方法中被调用…到底是什么不起作用?请使用测试用例代码更新您的问题,并描述意外行为和期望的行为。@sytech使用更多数据更新问题,谢谢您的回答。