Repository: mercadona/rele
Pull request #127 (2019-11-26 10:28:48)

Rele flask
### :tophat: What?

Adds middleware for easy integration with Flask and fixes issue with logging Middleware not expecting kwargs.

hobochild: For some reason `TestPublish.test_creates_global_publisher_when_published_called` test case was failing I didn't touch it so assume it was something to do with my local setup ? will wait for the CI to tell me :)
hobochild: Not sure whats up with the tests - but it appears that calling `rele.config.setup()` in the new middleware test causes the `test_creates_global_publisher_when_published_called` to fail. So must have some shared state between the tests somehow. :/
andrewgy8: This looks great! After playing around on your fork, the issue was indeed the global publisher. And this snippet should solve the issue:

```
import pytest

import rele
from unittest.mock import patch


class TestMiddleware:

    @pytest.fixture
    def mock_init_global_publisher(self):
        with patch("rele.config.init_global_publisher", autospec=True) as m:
            yield m

    @pytest.mark.usefixtures('mock_init_global_publisher')
    @patch("rele.contrib.FlaskMiddleware.setup", autospec=True)
    def test_setup_fn_is_called_with_kwargs(
        self, mock_middleware_setup, project_id, credentials
    ):

        settings = {
            "GC_PROJECT_ID": project_id,
            "GC_CREDENTIALS": credentials,
            "MIDDLEWARE": ["rele.contrib.FlaskMiddleware"],
        }

        rele.setup(settings, foo="bar")
        assert mock_middleware_setup.called
        mock_middleware_setup.call_args_list[0][-1] == {"foo": "bar"}

```
andrewgy8: Also dont forget to add yourself to the contributors file. 

Patch:
diff --git a/AUTHORS.md b/AUTHORS.md
index 35ad7a4..fda3f98 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -3,10 +3,11 @@ Thank you to all the contributors to Relé!
 * Andrew Graham-Yooll (@andrewgy8)
 * Miquel Torres Barcelo (@tobami)
 * Edgar Latorre (@edgarlatorre)
-* Lluis Guirado (@LluisGuiVi) 
-* Daniel Ruiz (@dani-ruiz) 
+* Lluis Guirado (@LluisGuiVi)
+* Daniel Ruiz (@dani-ruiz)
 * Juanjo Ponz (@jjponz)
 * Jose Antonio Navarro (@jonasae)
 * Antonio Bustos Rodriguez (@antoniobusrod)
 * David de la Iglesia (@ddelaiglesia) for the Logo!
 * Santiago Lanús (@sanntt)
+* Craig Mulligan (@hobochild)
diff --git a/rele/contrib/__init__.py b/rele/contrib/__init__.py
index f7a1a53..808ebea 100644
--- a/rele/contrib/__init__.py
+++ b/rele/contrib/__init__.py
@@ -1,4 +1,5 @@
 from .logging_middleware import LoggingMiddleware  # noqa
+from .flask_middleware import FlaskMiddleware  # noqa
 
 try:
     from .django_db_middleware import DjangoDBMiddleware  # noqa
diff --git a/rele/contrib/flask_middleware.py b/rele/contrib/flask_middleware.py
new file mode 100644
index 0000000..b5ae141
--- /dev/null
+++ b/rele/contrib/flask_middleware.py
@@ -0,0 +1,13 @@
+from rele.middleware import BaseMiddleware
+
+
+class FlaskMiddleware(BaseMiddleware):
+    def setup(self, config, **kwargs):
+        self.app = kwargs["flask_app"]
+
+    def pre_process_message(self, subscription, message):
+        self.ctx = self.app.app_context()
+        self.ctx.push()
+
+    def post_process_message(self):
+        self.ctx.pop()
diff --git a/rele/contrib/logging_middleware.py b/rele/contrib/logging_middleware.py
index c964371..1d824e5 100644
--- a/rele/contrib/logging_middleware.py
+++ b/rele/contrib/logging_middleware.py
@@ -13,7 +13,7 @@ class LoggingMiddleware(BaseMiddleware):
     def __init__(self):
         self._logger = None
 
-    def setup(self, config):
+    def setup(self, config, **kwargs):
         self._logger = logging.getLogger(__name__)
         self._app_name = config.app_name
 


Test patch:
diff --git a/tests/test_middleware.py b/tests/test_middleware.py
new file mode 100644
index 0000000..0b4c634
--- /dev/null
+++ b/tests/test_middleware.py
@@ -0,0 +1,26 @@
+import pytest
+import rele
+from unittest.mock import patch
+
+
+class TestMiddleware:
+    @pytest.fixture
+    def mock_init_global_publisher(self):
+        with patch("rele.config.init_global_publisher", autospec=True) as m:
+            yield m
+
+    @pytest.mark.usefixtures("mock_init_global_publisher")
+    @patch("rele.contrib.FlaskMiddleware.setup", autospec=True)
+    def test_setup_fn_is_called_with_kwargs(
+        self, mock_middleware_setup, project_id, credentials
+    ):
+
+        settings = {
+            "GC_PROJECT_ID": project_id,
+            "GC_CREDENTIALS": credentials,
+            "MIDDLEWARE": ["rele.contrib.FlaskMiddleware"],
+        }
+
+        rele.setup(settings, foo="bar")
+        assert mock_middleware_setup.called
+        mock_middleware_setup.call_args_list[0][-1] == {"foo": "bar"}