-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_logging_plugins.py
190 lines (150 loc) · 5.42 KB
/
test_logging_plugins.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import os
import pathlib
from typing import Any, Dict, Type, Tuple, Iterable
import pytest
import requests
from flask import Flask
from routemaster_sentry import SentryLogger
from routemaster_statsd import StatsDLogger
from prometheus_client.core import Sample
from routemaster_prometheus import PrometheusLogger
from prometheus_client.parser import text_string_to_metric_families
from routemaster.logging import BaseLogger, SplitLogger
SENTRY_KWARGS = {
'dsn': 'https://xxxxxxx:xxxxxxx@sentry.io/xxxxxxx',
'enabled': False,
}
PROMETHEUS_KWARGS = {
'path': '/metrics',
}
STATSD_KWARGS = {
'tags': {
'env': 'testing',
},
}
TEST_CASES: Iterable[Tuple[Type[BaseLogger], Dict[str, Any]]] = [
(SentryLogger, SENTRY_KWARGS),
(PrometheusLogger, PROMETHEUS_KWARGS),
(StatsDLogger, STATSD_KWARGS),
(SplitLogger, {'loggers': [
SentryLogger(None, **SENTRY_KWARGS),
PrometheusLogger(None, **PROMETHEUS_KWARGS),
]}),
]
@pytest.mark.parametrize('klass, kwargs', TEST_CASES)
def test_logger(app, klass, kwargs):
logger = klass(app.config, **kwargs)
state_machine = app.config.state_machines['test_machine']
state = state_machine.states[0]
feed_url = 'https://localhost'
server = Flask('test_server')
@server.route('/')
def root():
return 'Ok', 200
logger.init_flask(server)
with logger.process_cron(state_machine, state, 'test_cron'):
pass
with pytest.raises(RuntimeError):
with logger.process_cron(state_machine, state, 'test_cron'):
raise RuntimeError("Error must propagate")
with logger.process_feed(state_machine, state, feed_url):
pass
with pytest.raises(RuntimeError):
with logger.process_feed(state_machine, state, feed_url):
raise RuntimeError("Error must propagate")
with logger.process_webhook(state_machine, state):
pass
with pytest.raises(RuntimeError):
with logger.process_webhook(state_machine, state):
raise RuntimeError("Error must propagate")
# Test valid request
wsgi_environ = {
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/',
}
logger.process_request_started(wsgi_environ)
logger.process_request_finished(
wsgi_environ,
status=200,
headers={},
exc_info=None,
)
# Test failed request
wsgi_environ_failed = {
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/',
}
logger.process_request_started(wsgi_environ_failed)
logger.process_request_finished(
wsgi_environ_failed,
status=200,
headers={},
exc_info=(RuntimeError, RuntimeError('Test exception'), None),
)
# Test with invalid path
wsgi_environ_invalid_path = {
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/non-existent',
}
logger.process_request_started(wsgi_environ_invalid_path)
logger.process_request_finished(
wsgi_environ_invalid_path,
status=404,
headers={},
exc_info=None,
)
logger.debug("test")
logger.info("test")
logger.warning("test")
logger.error("test")
logger.critical("test")
try:
raise ValueError("Test Exception")
except ValueError:
logger.exception("test")
with pytest.raises(AttributeError):
logger.non_existent_logging_fn("test")
response = requests.Response()
logger.webhook_response(state_machine, state, response)
logger.feed_response(state_machine, state, feed_url, response)
def test_prometheus_logger_wipes_directory_on_startup(app):
tmp = pathlib.Path(os.environ['PROMETHEUS_MULTIPROC_DIR'])
tmp.mkdir(parents=True, exist_ok=True)
filepath = tmp / 'foo.txt'
dirpath = tmp / 'subdir'
dirpath.mkdir(parents=True, exist_ok=True)
with filepath.open('w') as f:
f.write('Hello, world')
PrometheusLogger(app.config)
assert not filepath.exists()
assert not dirpath.exists()
def test_prometheus_logger_metrics(routemaster_serve_subprocess):
with routemaster_serve_subprocess(
wait_for_output=b'Booting worker',
) as (proc, port):
# Populate metrics with a request
requests.get(f'http://127.0.0.1:{port}/')
metrics_response = requests.get(f'http://127.0.0.1:{port}/metrics')
metric_families = list(text_string_to_metric_families(metrics_response.text))
samples = [y for x in metric_families for y in x.samples]
assert Sample(
name='routemaster_api_request_duration_seconds_count',
labels={'method': 'GET', 'status': '200', 'endpoint': '/'},
value=1.0,
) in samples
def test_prometheus_logger_ignores_metrics_path(routemaster_serve_subprocess):
with routemaster_serve_subprocess(
wait_for_output=b'Booting worker',
) as (proc, port):
# This should _not_ populate the metrics with any samples
requests.get(f'http://127.0.0.1:{port}/metrics')
metrics_response = requests.get(f'http://127.0.0.1:{port}/metrics')
metric_families = list(text_string_to_metric_families(metrics_response.text))
samples = [y for x in metric_families for y in x.samples]
assert samples == []
def test_prometheus_logger_validates_metrics_path(app):
orig = os.environ['PROMETHEUS_MULTIPROC_DIR']
os.environ['PROMETHEUS_MULTIPROC_DIR'] = ''
with pytest.raises(ValueError):
PrometheusLogger(app.config)
os.environ['PROMETHEUS_MULTIPROC_DIR'] = orig