![](/img/trans.png)
[英]How do I mock a function with no parameters that sets a class attribute for Python unit tests?
[英]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.