Skip to content

Trying to mock, but not working

Can anyone tell me why this isn’t working?

>>> import mock
>>> @mock.patch('')
... def today(cls):
...  return date(2010, 1, 1)
>>> from datetime import date
>>>, 12, 19)

Perhaps someone could suggest a better way?



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, with a Mock object only within the decorated function. So, only within your today() will be a different function, which doesn’t appear to be what you want.

What you really want seems to be more like this:

def test(): = date(2010, 1, 1)

Unfortunately, this won’t work:

>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "build/bdist.macosx-10.6-universal/egg/", line 557, in patched
  File "build/bdist.macosx-10.6-universal/egg/", line 620, in __enter__
TypeError: can't set attributes of built-in/extension type ''

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

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

import datetime
class NewDate(
    def today(cls):
        return cls(2010, 1, 1) = NewDate

And now you could do:

NewDate(2010, 1, 1)
9 People found this is helpful