简体   繁体   中英

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 FirstClass:

    def method_one():
        second_class = SecondClass()

the second class has a method with a default argument:

class SecondClass:
    def method_two(important_date: datetime.date = get_today())

and a function get_today in a different file 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() .

I looked at several pages and solutions in SO and I couldn't fix it. Some of the ideas:

  • I tried that but in the line
with patch.object(build_url, 'func_defaults', ('domain',)):

I don't know what I have to put at build_url . I tried something like SecondClass.method_two and it doesn't work.

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:-(

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; and mock_today is the date I use to 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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