【问题标题】:Python: How do I mock a function call that sets a class variablePython:如何模拟设置类变量的函数调用
【发布时间】:2018-01-11 16:23:12
【问题描述】:

假设我在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

【问题讨论】:

    标签: python mocking pytest


    【解决方案1】:

    我并不完全理解您尝试做什么,但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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      相关资源
      最近更新 更多