"""Fixture for flask.g.""" from functools import partial from unittest.mock import MagicMock import uuid from flask import g from owsrequest import flask_request DELETE_ATTRIBUTE_VALUE = uuid.uuid1() def mock(monkeypatch, **kwargs): """Fix the flask global object. The ā€œgā€ object on flask is throwing exception whenever you try to access properties on it (based on the fact that an application context is not yet available). Since we use the logger across our application, we don't want to write tests that have dependencies on flask. This fixture fixes this. Args: monkeypatch (MonkeyPatch): pytest monkeypatch. kwargs (dict): additional properties to mock. """ ows = flask_request.Ows() ows.log = MagicMock() ows.correlation_id = uuid.uuid1() ows.request_counter = 0 storage = dict( ows=ows, **kwargs, ) get_attribute = partial(mock_flask_global_get_attribute, storage) def set_attribute(self, name, value): setattr(storage.get('ows'), name, value) def delete_attribute(self, name): delattr(storage.get('ows'), name) monkeypatch.setattr(g.__class__, '__getattr__', get_attribute) monkeypatch.setattr(g.__class__, '__setattr__', set_attribute) monkeypatch.setattr(g.__class__, '__delattr__', delete_attribute) def mock_flask_global_get_attribute(storage, name): """Get a specific attribute. Args: storage (dict): properties to mock. name (str): the name of the attribute. """ if name in storage: if name == 'ows': return storage.get('ows') value = getattr(storage.get('ows'), name) return value return MagicMock()