繁体   English   中英

Python:如何模拟设置类变量的函数调用

[英]Python: How do I mock a function call that sets a class variable

说我在module.py有类

class A():
    INPUTS = {}

    def __init__():
        self.inputs = do_something(self.INPUTS)

class B(A):
    INPUTS = function_with_external_API_call()

    def something_to_test():
        pass # do stuff

在我的单元测试中(使用pytest),我想要一个B的实例,以便可以测试B.something_to_test() 但是,导入类B会触发function_with_external_API_call()

此解决方案有效,但似乎是一个不好的解决方案。

with requests_mock.mock() as m:
    m.get(
        'https://url.com',
        json={'data': [{'id': '1'}]}
    )
    from module import B

如何模拟函数调用,以便可以导入类B并将INPUTS替换为模拟值?

我不太理解你打算做什么,但是INPUTS在你看来是一个类属性 如果您想修改和调用INPUTS ,我认为这样做会更简单:

class A(object):
    def __init__(self, mookup=None):
        self.INPUTS = mookup

class B(A):
    def __init__(self):
        super().__init__(self.function_to_call)
    def function_to_call(self):
        pass

如果这样不能回答您的问题,能否请您为问题添加更多的精度?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM