您好我正在尝试使用pytest从appengine应用程序测试一些方法。两种方法都使用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
我找不到原因。有什么建议吗?
答案 0 :(得分:0)
我设法通过在测试文件
上本地导入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