Why python's monkeypatch doesn't work when importing a class instead of a module?

耗尽温柔 提交于 2019-12-03 23:23:09
Michele d'Amico

Even if you aren't using mock framework you should take a look to where to patch chapter. By writing

from datetime import datetime

You are creating a new reference to datetime.datetime in your test module and call it datetime. That is the reference that you use in test_doesnt_work() test.

By writing

monkeypatch.setattr('datetime.datetime', mydatetime)

You are patching datetime's absolute reference in datetime module: the one used in test_works().

@Michele d'Amico's answer explains why it doesn't work. This is how to make it work if you want to use "from datetime import datetime" instead of just "import datetime"

monkeypatch.setattr(__name__ + '.datetime', mydatetime)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!