如何模拟 python 中方法的默认值?
How to mock the default value of a method in python?
我有一个 class 有一个实例化第二个元素的方法 class:
class FirstClass:
def method_one():
second_class = SecondClass()
第二个 class 有一个带有默认参数的方法:
class SecondClass:
def method_two(important_date: datetime.date = get_today())
和另一个文件中的函数 get_today
date_service
:
def get_today() -> datetime.date:
return datetime.date.today()
我正在 test_first_class.py
中测试 method_one
,但我无法模拟 get_today()
的值。
我查看了 SO 中的几个页面和解决方案,但无法修复它。一些想法:
- 我试过that但是在行
with patch.object(build_url, 'func_defaults', ('domain',)):
我不知道我要在 build_url
上放什么。我尝试了类似 SecondClass.method_two
的方法,但它不起作用。
备注:我知道一个好的单元测试应该独立测试 FirstClass
和 SecondClass
,并在 test_first_class.py
中模拟 method_two
但由于某些原因我不能这样做:-(
我终于解决了以下问题:
@staticmethod
@patch('date_service.get_today', Mock(return_value=mock_today))
def test_something():
importlib.reload(second_class)
importlib.reload(first_class)
first_class_element = FirstClass()
whatever = first_class_element.method_one()
assert (...)
其中second_class
和first_class
分别包含SecondClass
和FirstClass
; mock_today 是我今天用来模拟的日期。
注意:您需要重新加载两个 类,并且按照这个顺序,否则,它将不起作用。
备注:根据@Klaus D. 评论,我终于不能使用 get_today()
作为默认的可选参数,我也不必使用所有这些乱七八糟的东西,但我给出了答案以防万一任何人都需要它...
我有一个 class 有一个实例化第二个元素的方法 class:
class FirstClass:
def method_one():
second_class = SecondClass()
第二个 class 有一个带有默认参数的方法:
class SecondClass:
def method_two(important_date: datetime.date = get_today())
和另一个文件中的函数 get_today
date_service
:
def get_today() -> datetime.date:
return datetime.date.today()
我正在 test_first_class.py
中测试 method_one
,但我无法模拟 get_today()
的值。
我查看了 SO 中的几个页面和解决方案,但无法修复它。一些想法:
- 我试过that但是在行
with patch.object(build_url, 'func_defaults', ('domain',)):
我不知道我要在 build_url
上放什么。我尝试了类似 SecondClass.method_two
的方法,但它不起作用。
备注:我知道一个好的单元测试应该独立测试 FirstClass
和 SecondClass
,并在 test_first_class.py
中模拟 method_two
但由于某些原因我不能这样做:-(
我终于解决了以下问题:
@staticmethod
@patch('date_service.get_today', Mock(return_value=mock_today))
def test_something():
importlib.reload(second_class)
importlib.reload(first_class)
first_class_element = FirstClass()
whatever = first_class_element.method_one()
assert (...)
其中second_class
和first_class
分别包含SecondClass
和FirstClass
; mock_today 是我今天用来模拟的日期。
注意:您需要重新加载两个 类,并且按照这个顺序,否则,它将不起作用。
备注:根据@Klaus D. 评论,我终于不能使用 get_today()
作为默认的可选参数,我也不必使用所有这些乱七八糟的东西,但我给出了答案以防万一任何人都需要它...