【问题标题】:setattr in monkeypatching of a function throws attribute error函数的monkeypatching中的setattr抛出属性错误
【发布时间】:2020-05-07 08:37:23
【问题描述】:

我有以下代码

/tests/test_fixme.py

def make_my_patch():
    name = "Dinesh"
    return name


def test_make_patch(monkeypatch):

    monkeypatch.setattr(make_my_patch,"name","DineshKumar")

使用setattr 设置name 会引发属性错误。

注意:我已经将这两个函数放在同一个文件中作为权宜之计,以避免模块/导入错误。

这是回溯。

================================================================== FAILURES ==================================================================
______________________________________________________________ test_make_patch _______________________________________________________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7fddd5675630>

    def test_make_patch(monkeypatch):

>       monkeypatch.setattr(make_my_patch,"name","DineshKumar")
E       AttributeError: <function make_my_patch at 0x7fddd5676048> has no attribute 'name'

tests/test_fixme.py:16: AttributeError
========================================================== short test summary info ===========================================================
FAILED tests/test_fixme.py::test_make_patch - AttributeError: <function make_my_patch at 0x7fddd5676048> has no attribute 'name'
============================================================= 1 failed in 0.02s ==============================================================
(testenv) user@user:~/MyGitHub/MyLearning/Python/MyUnitTests/Testing10$ 

如何正确修补 name 属性?但是,如果我将代码放在一个类中,类变量的 setattr 就可以正常工作吗?你能解释一下为什么它不适用于函数吗?

【问题讨论】:

  • 请注意,即使您要猴子修补name 属性,该函数使用的是name 局部变量
  • @MisterMiyagi :那么我如何真正对name 变量进行猴子补丁并强制它使用更新后的值?您能否解释一下为什么这对课程有效,以及为什么在这种情况下无效。在过去的 2 天里,我一直在努力理解这一点。
  • 需要更改该函数,使其不使用局部变量。我只能假设你的类使用了一个属性。
  • 是的,你是对的。我在使用类时将 name 设置为类变量。理想情况下,由于 python 函数是一流的对象,setattr(make_my_patch,"name","DineshKumar") 工作正常。所以我假设 @ monkeypatch 的 987654331@ 也应该可以工作。 :(

标签: python python-3.x pytest monkeypatching


【解决方案1】:

万一有人在这里结束。

你需要返回一个有返回值的mock对象 所以你的代码会是这样的:

from unittest.mock import Mock

def make_my_patch():
    name = "Dinesh"
    return name


def test_make_patch(monkeypatch):
    monkeypatch.setattr(
        make_my_patch,
        Mock(return_value="DineshKumar")
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多