“功能"对象没有属性"assert_drawn_once_with" [英] 'function' object has no attribute 'assert_called_once_with'

查看:67
本文介绍了“功能"对象没有属性"assert_drawn_once_with"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pytest和pytest_mock运行以下测试

I'm trying to run the following test using pytest and pytest_mock

def rm(filename):
    helper(filename, 5)

def helper(filename):
    pass

def test_unix_fs(mocker):
    mocker.patch('module.helper')
    rm('file')
    helper.assert_called_once_with('file', 5)

但是我得到了异常AttributeError: 'function' object has no attribute 'assert_called_once_with'

我在做什么错了?

推荐答案

您无法在 vanilla 函数上执行.assert_called_once_with函数:首先需要用 mock.create_autospec 装饰器.例如:

You can not perform a .assert_called_once_with function on a vanilla function: you first need to wrap it with the mock.create_autospec decorator. So for instance:

import unittest.mock as mock

def rm(filename):
    helper(filename, 5)

def helper(filename):
    pass

helper = mock.create_autospec(helper)

def test_unix_fs(mocker):
    mocker.patch('module.helper')
    rm('file')
    helper.assert_called_once_with('file', 5)

或更优雅:

import unittest.mock as mock

def rm(filename):
    helper(filename, 5)

@mock.create_autospec
def helper(filename):
    pass

def test_unix_fs(mocker):
    mocker.patch('module.helper')
    rm('file')
    helper.assert_called_once_with('file', 5)

请注意,断言将失败,因为您只能使用'file'进行调用.因此有效的测试应该是:

Note that the assertion will fail, since you call it only with 'file'. So a valid test would be:

import unittest.mock as mock

def rm(filename):
    helper(filename, 5)

@mock.create_autospec
def helper(filename):
    pass

def test_unix_fs(mocker):
    mocker.patch('module.helper')
    rm('file')
    helper.assert_called_once_with('file')

编辑:如果该功能在某个模块中定义,则可以将其包装在本地的装饰器中.例如:

EDIT: In case the function is defined in some module, you can wrap it in a decorator locally. For example:

import unittest.mock as mock
from some_module import some_function

some_function = mock.create_autospec(some_function)

def test_unix_fs(mocker):
    some_function('file')
    some_function.assert_called_once_with('file')

这篇关于“功能"对象没有属性"assert_drawn_once_with"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆