么在导入类而不是模块时python的monkeypatch不起作

么在导入类而不是模块时python的monkeypatch不起作

本文介绍了为什么在导入类而不是模块时python的monkeypatch不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用接受的答案的代码时遇到问题.

I was having issues while using the code of the accepted answer here.

代码的工作方式取决于我如何导入日期时间.这是为什么?是否有可能对其进行模拟,使其同时起作用?

The code works depending on how I do the import of datetime. Why is that? Is it possible to mock it so it works both ways?

我正在使用Python 3.4.以下代码说明了该问题:

I am using Python 3.4. The following code illustrates the problem:

import pytest
from datetime import datetime

mockdate = datetime(2000, 1, 1, 0, 0, 0)

@pytest.fixture(autouse=True)
def patch_datetime_now(monkeypatch):
    class mydatetime:
        @classmethod
        def now(cls):
            return mockdate

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

def test_doesnt_work():
    assert datetime.now() == mockdate

def test_works():
    import datetime
    assert datetime.datetime.now() == mockdate

推荐答案

即使您没有使用 mock 框架,您应该查看 哪里打补丁 一章.通过写

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

from datetime import datetime

您正在测试模块中创建对datetime.datetime的新引用,并将其称为datetime.这就是您在test_doesnt_work()测试中使用的参考.

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.

通过写作

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

您要在datetime模块中修补datetime的绝对引用:test_works()中使用的那个.

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

这篇关于为什么在导入类而不是模块时python的monkeypatch不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:26