[英]How to mock the default value of a method in python?
I have one class with a method that instantiates an element of a second class:我有一个 class,其方法可以实例化第二个 class 的元素:
class FirstClass:
def method_one():
second_class = SecondClass()
the second class has a method with a default argument:第二个 class 有一个带有默认参数的方法:
class SecondClass:
def method_two(important_date: datetime.date = get_today())
and a function get_today
in a different file date_service
:和一个 function get_today
在不同的文件date_service
:
def get_today() -> datetime.date:
return datetime.date.today()
I am testing method_one
in a test_first_class.py
and I don't manage to mock the value of get_today()
.我正在method_one
中测试 method_one , test_first_class.py
我无法模拟get_today()
的值。
I looked at several pages and solutions in SO and I couldn't fix it.我查看了 SO 中的几个页面和解决方案,但无法修复。 Some of the ideas:一些想法:
with patch.object(build_url, 'func_defaults', ('domain',)):
I don't know what I have to put at build_url
.我不知道我必须在build_url
放什么。 I tried something like SecondClass.method_two
and it doesn't work.我尝试了SecondClass.method_two
之类的方法,但它不起作用。
REMARK: I know that a good unit test should test FirstClass
and SecondClass
independently, and mock method_two
in test_first_class.py
but for some reasons I can't do that:-(备注:我知道一个好的单元测试应该独立测试FirstClass
和SecondClass
,并在test_first_class.py
method_two
由于某些原因我不能这样做:-(
I finally solved the problem doing the following:我终于解决了以下问题:
@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 (...)
where second_class
and first_class
contain SecondClass
and FirstClass
, respectively;其中second_class
和first_class
分别包含SecondClass
和FirstClass
; and mock_today is the date I use to mock today.而 mock_today 是我今天用来模拟的日期。
Attention: you need to reload BOTH classes, and in this very order, otherwise, it doesn't work.注意:您需要重新加载两个类,并且按照这个顺序,否则,它不起作用。
Remark: as per @Klaus D. comment, I finally couldn't use get_today()
as a default optional argument and I didn't have to use all this mess, but I give the answer in case anyone needs it...备注:根据@Klaus D. 的评论,我终于不能使用get_today()
作为默认的可选参数,我也不必使用所有这些乱七八糟的东西,但我会给出答案以防万一有人需要它......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.