在测试子类时使用python的模拟补丁来模拟父类属性的值(通过调用导入的模块设置) [英] Use python's mock patch to mock the value of parent class attribute(set by a calling an imported module) while testing a child class

查看:24
本文介绍了在测试子类时使用python的模拟补丁来模拟父类属性的值(通过调用导入的模块设置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修补一个我没有直接导入但正在被测试对象使用的函数.补丁失败

I'm trying to patch a function which I'm not directly importing but it is being used by the object under test. The patch is failing

我的层次结构是这样的

--src
   |--a
   |  |--b 
   |     |-- parent.py
   |
   |--c
      |--d
         |--e
            |-child.py
--test
   |--test_child.py

child.py 看起来像

child.py looks like

class ChildClass(ParentClass):

    def child_method(self):
        // do stuff - which needs to be tested
        return self.parent_method()

parent.py 看起来像

parent.py looks like

from other_module import cool_function

class ParentClass:

    attribute x = cool_function()

    def parent_method():
        print(x)

在我的测试中,我尝试使用属性 X 的模拟值测试 ChildClass 的 child_method().为此,我模拟了导入的 cool_function().我就是这样做的

In my test I'm trying to test the child_method() of the ChildClass, with a mocked value of attribute X. For doing so I'm mocking the cool_function() which I imported. I'm doing it like this

test_child.py

test_child.py

from mock import patch
from c.d.e.child import ChildClass

@patch(a.b.c.cool_function) #Mocked cool_function()
def test_child_function(mock_cool_function):
    mock_cool_function.return_value = Y # Mocked return value
    child_obj = ChildClass()
    child_obj.child_function()
    assert child_ojb.x == Y  # ===> Fails. Returns value by executing cool_function()
    //other asserts 

想知道这里出了什么问题.我遵循了本指南 - 使用python的mock patch.object改变另一个方法中调用的方法的返回值

Wanted to know what's going wrong here. I followed this guide - Using python's mock patch.object to change the return value of a method called within another method

推荐答案

好的,我猜猜你想达到什么目的.我假设您的父类和子类看起来像这样:

Ok, I'm taking a guess at what you want to achieve. I assume that your parent and child classes look something like this:

from other_module import cool_function

class ParentClass:
    x = cool_function()

    def parent_method(self):
        return self.x


class ChildClass(ParentClass):
    def child_method(self):
        return self.parent_method()

然后你想用你自己的值替换类变量.
在这种情况下,替换 cool_function 无济于事,因为结果已经在加载时分配给 x,因此修补它不会改变 x.相反,您必须在测试中替换 x 本身:

Then you want to replace the class variable by your own value.
In this case it doesn't help to replace cool_function, as the result is already assigned to x at load time, so patching it won't change x. Instead, you have to replace x itself in your test:

from mock import patch
import a
from c.d.e.child import ChildClass

@patch.object(a.b.parent.ParentClass, 'x', new='Y')
def test_child_function():
    child_obj = ChildClass()
    result = child_obj.child_method()
    assert result == 'Y'

这篇关于在测试子类时使用python的模拟补丁来模拟父类属性的值(通过调用导入的模块设置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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