def test_post_files(flask_apm_client):
    with open(os.path.abspath(__file__), mode="rb") as f:
        response = flask_apm_client.app.test_client().post(
            "/an-error/",
            data={
                "foo": ["bar", "baz"],
                "f1": (compat.BytesIO(compat.b("1")), "bla"),
                "f2": [(f, "flask_tests.py"),
                       (compat.BytesIO(compat.b("1")), "blub")],
            },
        )
    assert response.status_code == 500
    assert len(flask_apm_client.client.events) == 1

    event = flask_apm_client.client.events[ERROR][0]
    if flask_apm_client.client.config.capture_body in ("errors", "all"):
        assert event["context"]["request"]["body"] == {
            "foo": ["bar", "baz"],
            "_files": {
                "f1": "bla",
                "f2": ["flask_tests.py", "blub"]
            },
        }
    else:
        assert event["context"]["request"]["body"] == "[REDACTED]"
Beispiel #2
0
def test_post_files(flask_apm_client):
    with open(os.path.abspath(__file__), mode='rb') as f:
        response = flask_apm_client.app.test_client().post(
            '/an-error/',
            data={
                'foo': ['bar', 'baz'],
                'f1': (compat.BytesIO(compat.b('1')), 'bla'),
                'f2': [(f, 'flask_tests.py'),
                       (compat.BytesIO(compat.b('1')), 'blub')],
            })
    assert response.status_code == 500
    assert len(flask_apm_client.client.events) == 1

    event = flask_apm_client.client.events.pop(0)['errors'][0]
    print(flask_apm_client.client.config.capture_body)
    if flask_apm_client.client.config.capture_body in ('errors', 'all'):
        assert event['context']['request']['body'] == {
            'foo': ['bar', 'baz'],
            '_files': {
                'f1': 'bla',
                'f2': ['flask_tests.py', 'blub'],
            }
        }
    else:
        assert event['context']['request']['body'] == '[REDACTED]'
def test_request_capture(django_elasticapm_client):
    request = WSGIRequest(environ={
        'wsgi.input': compat.BytesIO(),
        'REQUEST_METHOD': 'POST',
        'SERVER_NAME': 'testserver',
        'SERVER_PORT': '80',
        'CONTENT_TYPE': 'text/html',
        'ACCEPT': 'text/html',
    })
    request.read(1)

    django_elasticapm_client.capture('Message', message='foo', request=request)

    assert len(django_elasticapm_client.events) == 1
    event = django_elasticapm_client.events.pop(0)['errors'][0]

    assert 'request' in event['context']
    request = event['context']['request']
    assert request['method'] == 'POST'
    assert request['body'] == '<unavailable>'
    assert 'headers' in request
    headers = request['headers']
    assert 'content-type' in headers, headers.keys()
    assert headers['content-type'] == 'text/html'
    env = request['env']
    assert 'SERVER_NAME' in env, env.keys()
    assert env['SERVER_NAME'] == 'testserver'
    assert 'SERVER_PORT' in env, env.keys()
    assert env['SERVER_PORT'] == '80'
Beispiel #4
0
 def __call__(self, environ, start_response):
     content = self.content
     request = Request(environ)
     self.requests.append(request)
     data = request.data
     if request.content_encoding == "deflate":
         data = zlib.decompress(data)
     elif request.content_encoding == "gzip":
         with gzip.GzipFile(fileobj=compat.BytesIO(data)) as f:
             data = f.read()
     data = data.decode(request.charset)
     if request.content_type == "application/x-ndjson":
         data = [json.loads(line) for line in data.split("\n") if line]
     self.payloads.append(data)
     code = 202
     success = 0
     fail = 0
     if not self.skip_validate:
         for line in data:
             item_type, item = list(line.items())[0]
             validator = VALIDATORS[item_type]
             try:
                 validator.validate(item)
                 success += 1
             except jsonschema.ValidationError as e:
                 fail += 1
                 content += "/".join(map(compat.text_type, e.absolute_schema_path)) + ": " + e.message + "\n"
         code = 202 if not fail else 400
     response = Response(status=code)
     response.headers.clear()
     response.headers.extend(self.headers)
     response.data = content
     self.responses.append({"code": code, "content": content})
     return response(environ, start_response)
 def init_buffer():
     buffer = gzip.GzipFile(fileobj=compat.BytesIO(),
                            mode="w",
                            compresslevel=self._compress_level)
     data = (self._json_serializer({"metadata": self._metadata}) +
             "\n").encode("utf-8")
     buffer.write(data)
     return buffer
def test_disallowed_hosts_error_django_18(django_elasticapm_client):
    request = WSGIRequest(environ={
        'wsgi.input': compat.BytesIO(),
        'wsgi.url_scheme': 'http',
        'REQUEST_METHOD': 'POST',
        'SERVER_NAME': 'testserver',
        'SERVER_PORT': '80',
        'CONTENT_TYPE': 'application/json',
        'ACCEPT': 'application/json',
    })
    with override_settings(ALLOWED_HOSTS=['example.com']):
        # this should not raise a DisallowedHost exception
        django_elasticapm_client.capture('Message', message='foo', request=request)
    event = django_elasticapm_client.events.pop(0)['errors'][0]
    assert event['context']['request']['url'] == {'full': 'DisallowedHost'}
def test_capture_files(client, django_elasticapm_client):
    with pytest.raises(MyException), open(os.path.abspath(__file__)) as f:
        client.post(reverse('elasticapm-raise-exc'), data={
            'a': 'b',
            'f1': compat.BytesIO(100*compat.b('1')),
            'f2': f,
        },)
    error = django_elasticapm_client.events[0]
    if django_elasticapm_client.config.capture_body in ('errors', 'all'):
        assert error['errors'][0]['context']['request']['body'] == {
            'a': 'b',
            '_files': {
                'f1': 'f1',
                'f2': 'django_tests.py',
            }
        }
    else:
        assert error['errors'][0]['context']['request']['body'] == '[REDACTED]'
def test_post_data(django_elasticapm_client):
    request = WSGIRequest(environ={
        'wsgi.input': compat.BytesIO(),
        'REQUEST_METHOD': 'POST',
        'SERVER_NAME': 'testserver',
        'SERVER_PORT': '80',
        'CONTENT_TYPE': 'application/json',
        'ACCEPT': 'application/json',
    })
    request.POST = QueryDict("x=1&y=2")
    django_elasticapm_client.capture('Message', message='foo', request=request)

    assert len(django_elasticapm_client.events) == 1
    event = django_elasticapm_client.events.pop(0)['errors'][0]

    assert 'request' in event['context']
    request = event['context']['request']
    assert request['method'] == 'POST'
    assert request['body'] == {'x': '1', 'y': '2'}
def test_post_raw_data(django_elasticapm_client):
    request = WSGIRequest(environ={
        'wsgi.input': compat.BytesIO(compat.b('foobar')),
        'wsgi.url_scheme': 'http',
        'REQUEST_METHOD': 'POST',
        'SERVER_NAME': 'testserver',
        'SERVER_PORT': '80',
        'CONTENT_TYPE': 'application/json',
        'ACCEPT': 'application/json',
        'CONTENT_LENGTH': '6',
    })
    django_elasticapm_client.capture('Message', message='foo', request=request)

    assert len(django_elasticapm_client.events) == 1
    event = django_elasticapm_client.events.pop(0)['errors'][0]

    assert 'request' in event['context']
    request = event['context']['request']
    assert request['method'] == 'POST'
    assert request['body'] == compat.b('foobar')
Beispiel #10
0
def test_raw_post_data_partial_read(django_elasticapm_client):
    v = compat.b('{"foo": "bar"}')
    request = WSGIRequest(environ={
        'wsgi.input': compat.BytesIO(v + compat.b('\r\n\r\n')),
        'REQUEST_METHOD': 'POST',
        'SERVER_NAME': 'testserver',
        'SERVER_PORT': '80',
        'CONTENT_TYPE': 'application/json',
        'CONTENT_LENGTH': len(v),
        'ACCEPT': 'application/json',
    })
    request.read(1)

    django_elasticapm_client.capture('Message', message='foo', request=request)

    assert len(django_elasticapm_client.events) == 1
    event = django_elasticapm_client.events.pop(0)['errors'][0]

    assert 'request' in event['context']
    request = event['context']['request']
    assert request['method'] == 'POST'
    assert request['body'] == '<unavailable>'
Beispiel #11
0
 def _init_buffer(self):
     buffer = gzip.GzipFile(fileobj=compat.BytesIO(),
                            mode="w",
                            compresslevel=self._compress_level)
     return buffer