forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_logger.py
254 lines (188 loc) · 6.76 KB
/
test_logger.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for L{twisted.logger._logger}.
"""
from twisted.trial import unittest
from .._levels import InvalidLogLevelError
from .._levels import LogLevel
from .._format import formatEvent
from .._logger import Logger
from .._global import globalLogPublisher
class TestLogger(Logger):
"""
L{Logger} with an overridden C{emit} method that keeps track of received
events.
"""
def emit(self, level, format=None, **kwargs):
def observer(event):
self.event = event
globalLogPublisher.addObserver(observer)
try:
Logger.emit(self, level, format, **kwargs)
finally:
globalLogPublisher.removeObserver(observer)
self.emitted = {
"level": level,
"format": format,
"kwargs": kwargs,
}
class LogComposedObject(object):
"""
A regular object, with a logger attached.
"""
log = TestLogger()
def __init__(self, state=None):
self.state = state
def __str__(self):
return "<LogComposedObject {state}>".format(state=self.state)
class LoggerTests(unittest.TestCase):
"""
Tests for L{Logger}.
"""
def test_repr(self):
"""
repr() on Logger
"""
namespace = "bleargh"
log = Logger(namespace)
self.assertEqual(repr(log), "<Logger {0}>".format(repr(namespace)))
def test_namespaceDefault(self):
"""
Default namespace is module name.
"""
log = Logger()
self.assertEqual(log.namespace, __name__)
def test_namespaceAttribute(self):
"""
Default namespace for classes using L{Logger} as a descriptor is the
class name they were retrieved from.
"""
obj = LogComposedObject()
expectedNamespace = "{0}.{1}".format(
obj.__module__,
obj.__class__.__name__,
)
self.assertEqual(obj.log.namespace, expectedNamespace)
self.assertEqual(LogComposedObject.log.namespace, expectedNamespace)
self.assertIs(LogComposedObject.log.source, LogComposedObject)
self.assertIs(obj.log.source, obj)
self.assertIsNone(Logger().source)
def test_descriptorObserver(self):
"""
When used as a descriptor, the observer is propagated.
"""
observed = []
class MyObject(object):
log = Logger(observer=observed.append)
MyObject.log.info("hello")
self.assertEqual(len(observed), 1)
self.assertEqual(observed[0]['log_format'], "hello")
def test_sourceAvailableForFormatting(self):
"""
On instances that have a L{Logger} class attribute, the C{log_source}
key is available to format strings.
"""
obj = LogComposedObject("hello")
log = obj.log
log.error("Hello, {log_source}.")
self.assertIn("log_source", log.event)
self.assertEqual(log.event["log_source"], obj)
stuff = formatEvent(log.event)
self.assertIn("Hello, <LogComposedObject hello>.", stuff)
def test_basicLogger(self):
"""
Test that log levels and messages are emitted correctly for
Logger.
"""
log = TestLogger()
for level in LogLevel.iterconstants():
format = "This is a {level_name} message"
message = format.format(level_name=level.name)
logMethod = getattr(log, level.name)
logMethod(format, junk=message, level_name=level.name)
# Ensure that test_emit got called with expected arguments
self.assertEqual(log.emitted["level"], level)
self.assertEqual(log.emitted["format"], format)
self.assertEqual(log.emitted["kwargs"]["junk"], message)
self.assertTrue(hasattr(log, "event"), "No event observed.")
self.assertEqual(log.event["log_format"], format)
self.assertEqual(log.event["log_level"], level)
self.assertEqual(log.event["log_namespace"], __name__)
self.assertIsNone(log.event["log_source"])
self.assertEqual(log.event["junk"], message)
self.assertEqual(formatEvent(log.event), message)
def test_sourceOnClass(self):
"""
C{log_source} event key refers to the class.
"""
def observer(event):
self.assertEqual(event["log_source"], Thingo)
class Thingo(object):
log = TestLogger(observer=observer)
Thingo.log.info()
def test_sourceOnInstance(self):
"""
C{log_source} event key refers to the instance.
"""
def observer(event):
self.assertEqual(event["log_source"], thingo)
class Thingo(object):
log = TestLogger(observer=observer)
thingo = Thingo()
thingo.log.info()
def test_sourceUnbound(self):
"""
C{log_source} event key is L{None}.
"""
def observer(event):
self.assertIsNone(event["log_source"])
log = TestLogger(observer=observer)
log.info()
def test_defaultFailure(self):
"""
Test that log.failure() emits the right data.
"""
log = TestLogger()
try:
raise RuntimeError("baloney!")
except RuntimeError:
log.failure("Whoops")
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(len(errors), 1)
self.assertEqual(log.emitted["level"], LogLevel.critical)
self.assertEqual(log.emitted["format"], "Whoops")
def test_conflictingKwargs(self):
"""
Make sure that kwargs conflicting with args don't pass through.
"""
log = TestLogger()
log.warn(
u"*",
log_format="#",
log_level=LogLevel.error,
log_namespace="*namespace*",
log_source="*source*",
)
self.assertEqual(log.event["log_format"], u"*")
self.assertEqual(log.event["log_level"], LogLevel.warn)
self.assertEqual(log.event["log_namespace"], log.namespace)
self.assertIsNone(log.event["log_source"])
def test_logInvalidLogLevel(self):
"""
Test passing in a bogus log level to C{emit()}.
"""
log = TestLogger()
log.emit("*bogus*")
errors = self.flushLoggedErrors(InvalidLogLevelError)
self.assertEqual(len(errors), 1)
def test_trace(self):
"""
Tracing keeps track of forwarding to the publisher.
"""
def publisher(event):
observer(event)
def observer(event):
self.assertEqual(event["log_trace"], [(log, publisher)])
log = TestLogger(observer=publisher)
log.info("Hello.", log_trace=[])