예제 #1
0
    def testGroupingFunctionValidationWhenExtraFields(self):
        # Extra fields included in the grouping function response
        # should be stripped from the payload
        config = self.mockMiddlewareConfig(
            grouping_function=lambda req: {
                "id": "spam",
                "email": "*****@*****.**",
                "label": "Spam Musubi",
                "telephone": "(939) 555-0113",
            })

        responseObjectString = "{ 'responseObject': 'value' }"
        environ = Environ.MockEnviron().getEnvironForRequest(b"", "POST")
        app = MockApplication(responseObjectString)
        metrics = MetricsCoreMock()
        middleware = MetricsMiddleware(app, config)
        middleware.metrics_core = metrics
        next(middleware(environ, app.mockStartResponse))
        payload = self.createPayload(config)
        data = payload(metrics.req, metrics.res)
        assert isinstance(data, dict)
        assert "group" in data
        group = data["group"]

        expected_group = {
            "id": "spam",
            "email": "*****@*****.**",
            "label": "Spam Musubi",
        }
        assert group == expected_group
예제 #2
0
 def testUuid(self):
     config = self.mockMiddlewareConfig(development_mode=True)
     responseObjectString = "{ 'responseObject': 'value' }"
     environ = Environ.MockEnviron().getEnvironForRequest(b"", "POST")
     app = MockApplication(responseObjectString)
     metrics = MetricsCoreMock()
     middleware = MetricsMiddleware(app, config)
     middleware.metrics_core = metrics
     next(middleware(environ, app.mockStartResponse))
     payload = self.createPayload(config)
     data = payload(metrics.req, metrics.res)
     assert data["_id"] == str(uuid.UUID(data["_id"], version=4))
예제 #3
0
 def testEmptyPostRequest(self):
     jsonString = b""
     responseObjectString = "{ responseObject: 'value' }"
     environ = Environ.MockEnviron().getEnvironForRequest(
         jsonString, "POST")
     app = MockApplication(responseObjectString)
     metrics = MetricsCoreMock()
     middleware = MetricsMiddleware(app, mockMiddlewareConfig())
     middleware.metrics_core = metrics
     next(middleware(environ, app.mockStartResponse))
     assert metrics.req.data == jsonString
     assert metrics.req.method == "POST"
     assert metrics.res.body == responseObjectString
예제 #4
0
    def testGroupingFunctionNone(self):
        # PayloadBuilder should return None if the grouping_function returns
        # None (which means not to log the request).
        config = self.mockMiddlewareConfig(grouping_function=lambda req: None)

        responseObjectString = "{ 'responseObject': 'value' }"
        environ = Environ.MockEnviron().getEnvironForRequest(b"", "POST")
        app = MockApplication(responseObjectString)
        metrics = MetricsCoreMock()
        middleware = MetricsMiddleware(app, config)
        middleware.metrics_core = metrics
        next(middleware(environ, app.mockStartResponse))
        payload_builder = self.createPayload(config)
        payload = payload_builder(metrics.req, metrics.res)
        assert payload is None
예제 #5
0
    def testDeprecatedWhiteListed(self):
        config = self.mockMiddlewareConfig(whitelist=["ok"])

        jsonString = json.dumps({"ok": 123, "password": 456}).encode()
        responseObjectString = "{ 'responseObject': 'value' }"
        environ = Environ.MockEnviron().getEnvironForRequest(
            jsonString, "POST")
        app = MockApplication(responseObjectString)
        metrics = MetricsCoreMock()
        middleware = MetricsMiddleware(app, config)
        middleware.metrics_core = metrics
        next(middleware(environ, app.mockStartResponse))
        payload = self.createPayload(config)
        data = payload(metrics.req, metrics.res)
        text = data["request"]["log"]["entries"][0]["request"]["text"]

        assert "ok" in text
        assert not "password" in text
예제 #6
0
    def testGroupingFunctionValidationWhenMissingId(self):
        config = self.mockMiddlewareConfig(grouping_function=lambda req: {
            "email": "*****@*****.**",
            "label": "Spam Musubi",
        })

        responseObjectString = "{ 'responseObject': 'value' }"
        environ = Environ.MockEnviron().getEnvironForRequest(b"", "POST")
        app = MockApplication(responseObjectString)
        metrics = MetricsCoreMock()
        middleware = MetricsMiddleware(app, config)
        middleware.metrics_core = metrics
        next(middleware(environ, app.mockStartResponse))
        payload = self.createPayload(config)
        data = payload(metrics.req, metrics.res)

        # When the "id" and "api_key" fields are both missing,
        # the payload should be None
        assert data is None
예제 #7
0
    def testDeprecatedIDField(self):
        config = self.mockMiddlewareConfig(grouping_function=lambda req: {
            "id": "spam",
            "email": "*****@*****.**",
            "label": "Spam Musubi",
        })

        responseObjectString = "{ 'responseObject': 'value' }"
        environ = Environ.MockEnviron().getEnvironForRequest(b"", "POST")
        app = MockApplication(responseObjectString)
        metrics = MetricsCoreMock()
        middleware = MetricsMiddleware(app, config)
        middleware.metrics_core = metrics
        next(middleware(environ, app.mockStartResponse))
        payload = self.createPayload(config)
        data = payload(metrics.req, metrics.res)
        group = data["group"]

        assert group["id"] == "spam"
        assert group["email"] == "*****@*****.**"
        assert group["label"] == "Spam Musubi"
예제 #8
0
from flask import Flask
from readme_metrics import MetricsApiConfig, MetricsMiddleware

app = Flask(__name__)

# Docs: https://docs.readme.com/developers/docs/authentication#api-key-quick-start
README_API_KEY = "YOUR_API_KEY"

app.wsgi_app = MetricsMiddleware(
    app.wsgi_app,
    MetricsApiConfig(
        README_API_KEY,
        lambda req: {
            'id': 'owlbert',
            'label': 'Owlbert',
            'email': '*****@*****.**'
        },
        buffer_length=
        1,  # makes it so logs show up after each request, rather than after each batch of 10
    ))


@app.route('/', methods=['GET', 'POST'])
def hello_world():
    return 'Hello, World!'
예제 #9
0
"""
WSGI config for django_metrics_test project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

from readme_metrics import MetricsApiConfig, MetricsMiddleware

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_metrics_test.settings')

application = get_wsgi_application()

application = MetricsMiddleware(
    application,
    MetricsApiConfig("YOUR_API_KEY",
                     lambda req: {
                         'id': '123',
                         'label': 'testuser',
                         'email': '*****@*****.**'
                     },
                     buffer_length=1))