Skip to content
Advertisement

Trying to mock datetime.date.today(), but not working

Can anyone tell me why this isn’t working?

JavaScript

Perhaps someone could suggest a better way?

Advertisement

Answer

There are a few problems.

First of all, the way you’re using mock.patch isn’t quite right. When used as a decorator, it replaces the given function/class (in this case, datetime.date.today) with a Mock object only within the decorated function. So, only within your today() will datetime.date.today be a different function, which doesn’t appear to be what you want.

What you really want seems to be more like this:

JavaScript

Unfortunately, this won’t work:

JavaScript

This fails because Python built-in types are immutable – see this answer for more details.

In this case, I would subclass datetime.date myself and create the right function:

JavaScript

And now you could do:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement