Search code examples
google-app-enginepytestmonkeypatching

pytest monkeypatch fails second time is called


Hi I'm trying ot use pytest to test some methods from an appengine app. Both methods use google.appengine.api.users.get_current_user to access current logged in 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

I've created a pytest fixture to provide it:

@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

It works fine for the first test but when executing ght second i thows an error like:

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

I can't find why. Any suggestions?


Solution

  • I've managed to solve this by importing users locally on the test file

    from google.appengine.api import users
    

    and then monkeypatch this way:

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