This repository has been archived by the owner on Jan 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
210 lines (168 loc) · 6.75 KB
/
tests.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
import unittest
import logging
import json
from wsgiref.util import setup_testing_defaults
import statsd
class MockStatist(statsd.StatsClient):
def __init__(self, test_case):
self._prefix = None
self.test_case = test_case
def _send(self, data):
if not hasattr(self.test_case, 'stats'):
self.test_case.stats = []
self.test_case.stats.append(data)
class LogCapturingHandler(logging.Handler):
def __init__(self, test_case, level=logging.NOTSET):
self.test_case = test_case
super(LogCapturingHandler, self).__init__(level)
def emit(self, record):
if not hasattr(self.test_case, 'logged'):
self.test_case.logged = []
self.test_case.logged.append(record)
class StatistCase(unittest.TestCase):
def test_creation_of_statsd_client(self):
settings = {
'statsd.host': 'example.com',
'statsd.port': '8125',
'statsd.prefix': '',
}
from cnxlogging import make_statist
statist = make_statist(settings)
import statsd
self.assertTrue(isinstance(statist, statsd.StatsClient))
def test_creation_degrades_to_logging(self):
settings = {}
from cnxlogging import make_statist
statist = make_statist(settings)
from cnxlogging import _StatsLoggingClient
self.assertTrue(isinstance(statist, _StatsLoggingClient))
class ApplicationTestCase(unittest.TestCase):
def setUp(self):
self.statist = MockStatist(self)
logger = logging.getLogger(self.__class__.__name__)
logger.setLevel(logging.INFO)
self.log_handler = LogCapturingHandler(self)
logger.addHandler(self.log_handler)
from cnxlogging import Application
self.app = Application(self.statist, logger)
def start_response(self, *args, **kwargs):
self.resp_args = args
self.resp_kwargs = kwargs
def test_metric_acceptance(self):
metric_data = {
'type': 'incr',
'label': 'i.haz.clikd.cheezburgr',
##'value': None, # Tests that missing value or `None' becomes 1.
}
environ = {
'PATH_INFO': '/metric',
'REQUEST_METHOD': 'POST',
}
setup_testing_defaults(environ)
# Assign the posted message.
environ['wsgi.input'].write(json.dumps(metric_data))
environ['wsgi.input'].seek(0)
resp_body = self.app(environ, self.start_response)
# Check response, smoke test.
self.assertEqual(resp_body, [])
self.assertEqual(self.resp_args[0].upper(), '200 OK')
self.assertEqual(self.resp_args[1], [])
# Check the metric was accepted.
self.assertEqual(self.stats, [u'i.haz.clikd.cheezburgr:1|c'])
def test_log_acceptance(self):
message = 'Smoo clikd on a cheezburgr'
metric_data = {
'message': message,
}
environ = {
'PATH_INFO': '/log',
'REQUEST_METHOD': 'POST',
}
setup_testing_defaults(environ)
# Assign the posted message.
environ['wsgi.input'].write(json.dumps(metric_data))
environ['wsgi.input'].seek(0)
resp_body = self.app(environ, self.start_response)
# Check response, smoke test.
self.assertEqual(resp_body, [])
self.assertEqual(self.resp_args[0], '200 OK')
self.assertEqual(self.resp_args[1], [])
# Check the metric was accepted.
self.assertEqual([x.msg for x in self.logged], [message])
def test_only_accepts_post(self):
environ = {'REQUEST_METHOD': 'GET'}
setup_testing_defaults(environ)
resp_body = self.app(environ, self.start_response)
# Check response, smoke test.
self.assertEqual(resp_body, [])
self.assertEqual(self.resp_args[0].upper(), '404 NOT FOUND')
self.assertEqual(self.resp_args[1], [])
def test_invalid_metric_type(self):
metric_data = {
'type': 'smudge',
'label': 'doo.be.doo.be.do',
'value': None,
}
environ = {
'PATH_INFO': '/metric',
'REQUEST_METHOD': 'POST',
}
setup_testing_defaults(environ)
# Assign the posted message.
environ['wsgi.input'].write(json.dumps(metric_data))
environ['wsgi.input'].seek(0)
from cnxlogging import InvalidMetricType
with self.assertRaises(InvalidMetricType):
resp_body = self.app.handle_metric(metric_data)
resp_body = self.app(environ, self.start_response)
self.assertEqual(self.resp_args[0], '500 Internal Server Error')
self.assertEqual(self.resp_args[1], [('Content-type', 'text/plain')])
self.assertEqual(resp_body,
['InvalidMetricType: Invalid metric type: smudge'])
class StatsApplicationTestCase(unittest.TestCase):
def setUp(self):
self.log_handler = LogCapturingHandler(self)
from cnxlogging import _StatsLoggingClient
self.statist = _StatsLoggingClient()
self.statist._logger.setLevel(logging.INFO)
self.statist._logger.addHandler(self.log_handler)
logger = logging.getLogger(self.__class__.__name__)
logger.setLevel(logging.INFO)
logger.addHandler(self.log_handler)
from cnxlogging import Application
self.app = Application(self.statist, logger)
def start_response(self, *args, **kwargs):
self.resp_args = args
self.resp_kwargs = kwargs
def test_stats_w_logging_client(self):
# In the case where a statsd server has not been configured,
# stats info is sent to a log using a custom class that provides
# the same interface as the statsd.StatsClient.
metric_data = {
'type': 'timing',
'label': 'i.haz.thunkd.cheezburgr',
'value': 300,
}
environ = {
'PATH_INFO': '/metric',
'REQUEST_METHOD': 'POST',
}
setup_testing_defaults(environ)
# Assign the posted message.
environ['wsgi.input'].write(json.dumps(metric_data))
environ['wsgi.input'].seek(0)
resp_body = self.app(environ, self.start_response)
# Check response, smoke test.
self.assertEqual(resp_body, [])
self.assertEqual(self.resp_args[0].upper(), '200 OK')
self.assertEqual(self.resp_args[1], [])
# Check the metric was accepted.
self.assertEqual([x.msg for x in self.logged],
['i.haz.thunkd.cheezburgr:300|ms'])