对类中使用的 Monkeypatching 外部函数进行故障排除[重复]

问题描述 投票:0回答:1

我已经编写了如下所示的测试代码,我正在尝试使用我的测试代码中的

subtract_f
来对
util.math.py
中的
patch_wrong_subtract_f()
函数进行猴子补丁。但是,我遇到了一个问题,它似乎没有按预期工作。如果您能在识别和解决问题方面获得一些帮助,我将不胜感激。

这是我的测试代码:

test_disney.py

from util import math
from disney.calculator import Calculator

def patch_wrong_subtract_f(a:int, b:int)->int:
    return 1000

def test_calculator(monkeypatch):

    monkeypatch.setattr(math, "subtract_f", patch_wrong_subtract_f)

    cal = Calculator()
    assert cal.sum(2, 4) == 6
    assert cal.subtract(6 ,2) == 4  # I expect this assert must be broken by monkeypatch.

迪士尼/计算器.py

from util.math import sum_f, subtract_f

class Calculator:
    def sum(self,a:int, b:int)->int:
        return sum_f(a, b)
    def subtract(self, a:int,b:int)->int:
        return subtract_f(a, b)

util.math.py

def sum_f(a:int, b:int)->int:
    return a+b

def subtract_f(a:int, b:int)->int:
    return a-b

您能否帮助我了解可能导致此问题的原因以及如何使用

subtract_f
成功进行 Monkeypatch
patch_wrong_subtract_f()

谢谢你。

python pytest monkeypatching
1个回答
0
投票

我解决了如下问题。


from util import math #1

def test_calculator(monkeypatch):

    def patch_wrong_subtract_f(a:int, b:int)->int:
        return 1000
    
    monkeypatch.setattr(math, "subtract_f", patch_wrong_subtract_f) #2
    from disney.calculator import Calculator #3

    cal = Calculator()
    assert cal.sum(2, 4) == 6
    assert cal.subtract(6 ,2) == 4  # Broken case by monkeypatch!!

要解决的关键想法是

  1. 导入具有打补丁功能的上层模块
  2. 拨打 1. 在
    monkeypatch.setattr() as 1st positional parameter.
  3. 在 2 之后导入带有猴子补丁模块的类。

谢谢@danzel。

© www.soinside.com 2019 - 2024. All rights reserved.