pytest monkeypatch 第二次失败被调用

pytest monkeypatch fails second time is called

您好,我正在尝试使用 pytest 来测试应用引擎应用程序中的某些方法。这两种方法都使用 google.appengine.api.users.get_current_user 来访问当前登录的用户:

@pytest.fixture
def api_client():
    tb = testbed.Testbed()
    tb.activate()
    tb.init_datastore_v3_stub()
    tb.init_memcache_stub()
    tb.init_user_stub()
    ndb.get_context().clear_cache()
    api.api_app.testing = True
    yield api.api_app.test_client()
    tb.deactivate()

def test_get_pipelines(api_client, mocked_google_user):
    pips = _insert_pipelines()
    user = LUser(user_id=mocked_google_user.user_id(), pipelines=[p.key for p in pips])
    user.put()

    r = api_client.get('/api/v1/pipelines')

    assert r.status_code == 200

    expected_result = {
        'own': [
            pips[0].to_dic(),
            pips[1].to_dic(),
        ]
    }
    assert json.loads(r.data) == expected_result

def test_get_pipelines_no_pipelines(api_client, mocked_google_user):
    r = api_client.get('/api/v1/pipelines')

    assert r.status_code == 200

    expected_result = {
        'own': []
    }
    assert json.loads(r.data) == expected_result

我创建了一个 pytest fixture 来提供它:

@pytest.fixture(autouse=True)
def mocked_google_user(monkeypatch):
    google_user = MockGoogleUser()
    monkeypatch.setattr('google.appengine.api.users.get_current_user', lambda: google_user)
    return google_user

它在第一次测试时工作正常,但在第二次执行时我抛出了一个错误,如:

obj = <module 'google' from 'C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\__init__.pyc'>
name = 'appengine', ann = 'google.appengine'

    def annotated_getattr(obj, name, ann):
        try:
            obj = getattr(obj, name)
        except AttributeError:
            raise AttributeError(
                '%r object at %s has no attribute %r' % (
>                   type(obj).__name__, ann, name
                )
            )
E           AttributeError: 'module' object at google.appengine has no attribute 'appengine'

winvevn\lib\site-packages\_pytest\monkeypatch.py:75: AttributeError

我找不到原因。有什么建议吗?

我已经设法通过在测试文件上本地导入 users 解决了这个问题

from google.appengine.api import users

然后用这种方式进行 monkeypatch:

@pytest.fixture(autouse=True)
def mocked_google_user(monkeypatch):
    google_user = MockGoogleUser('test@example.com', 'test user', '193934')
    monkeypatch.setattr(users, 'get_current_user', lambda: google_user)
    return google_user