logxpy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. logxpy/__init__.py +126 -0
  2. logxpy/_action.py +958 -0
  3. logxpy/_async.py +186 -0
  4. logxpy/_base.py +80 -0
  5. logxpy/_compat.py +71 -0
  6. logxpy/_config.py +45 -0
  7. logxpy/_dest.py +88 -0
  8. logxpy/_errors.py +58 -0
  9. logxpy/_fmt.py +68 -0
  10. logxpy/_generators.py +136 -0
  11. logxpy/_mask.py +23 -0
  12. logxpy/_message.py +195 -0
  13. logxpy/_output.py +517 -0
  14. logxpy/_pool.py +93 -0
  15. logxpy/_traceback.py +126 -0
  16. logxpy/_types.py +71 -0
  17. logxpy/_util.py +56 -0
  18. logxpy/_validation.py +486 -0
  19. logxpy/_version.py +21 -0
  20. logxpy/cli.py +61 -0
  21. logxpy/dask.py +172 -0
  22. logxpy/decorators.py +268 -0
  23. logxpy/filter.py +124 -0
  24. logxpy/journald.py +88 -0
  25. logxpy/json.py +149 -0
  26. logxpy/loggerx.py +253 -0
  27. logxpy/logwriter.py +84 -0
  28. logxpy/parse.py +191 -0
  29. logxpy/prettyprint.py +173 -0
  30. logxpy/serializers.py +36 -0
  31. logxpy/stdlib.py +23 -0
  32. logxpy/tai64n.py +45 -0
  33. logxpy/testing.py +472 -0
  34. logxpy/tests/__init__.py +9 -0
  35. logxpy/tests/common.py +36 -0
  36. logxpy/tests/strategies.py +231 -0
  37. logxpy/tests/test_action.py +1751 -0
  38. logxpy/tests/test_api.py +86 -0
  39. logxpy/tests/test_async.py +67 -0
  40. logxpy/tests/test_compat.py +13 -0
  41. logxpy/tests/test_config.py +21 -0
  42. logxpy/tests/test_coroutines.py +105 -0
  43. logxpy/tests/test_dask.py +211 -0
  44. logxpy/tests/test_decorators.py +54 -0
  45. logxpy/tests/test_filter.py +122 -0
  46. logxpy/tests/test_fmt.py +42 -0
  47. logxpy/tests/test_generators.py +292 -0
  48. logxpy/tests/test_journald.py +246 -0
  49. logxpy/tests/test_json.py +208 -0
  50. logxpy/tests/test_loggerx.py +44 -0
  51. logxpy/tests/test_logwriter.py +262 -0
  52. logxpy/tests/test_message.py +334 -0
  53. logxpy/tests/test_output.py +921 -0
  54. logxpy/tests/test_parse.py +309 -0
  55. logxpy/tests/test_pool.py +55 -0
  56. logxpy/tests/test_prettyprint.py +303 -0
  57. logxpy/tests/test_pyinstaller.py +35 -0
  58. logxpy/tests/test_serializers.py +36 -0
  59. logxpy/tests/test_stdlib.py +73 -0
  60. logxpy/tests/test_tai64n.py +66 -0
  61. logxpy/tests/test_testing.py +1051 -0
  62. logxpy/tests/test_traceback.py +251 -0
  63. logxpy/tests/test_twisted.py +814 -0
  64. logxpy/tests/test_util.py +45 -0
  65. logxpy/tests/test_validation.py +989 -0
  66. logxpy/twisted.py +265 -0
  67. logxpy-0.1.0.dist-info/METADATA +100 -0
  68. logxpy-0.1.0.dist-info/RECORD +72 -0
  69. logxpy-0.1.0.dist-info/WHEEL +5 -0
  70. logxpy-0.1.0.dist-info/entry_points.txt +2 -0
  71. logxpy-0.1.0.dist-info/licenses/LICENSE +201 -0
  72. logxpy-0.1.0.dist-info/top_level.txt +1 -0
logxpy/testing.py ADDED
@@ -0,0 +1,472 @@
1
+ """
2
+ Utilities to aid unit testing L{eliot} and code that uses it.
3
+ """
4
+
5
+ from unittest import SkipTest
6
+ from functools import wraps
7
+
8
+ from pyrsistent import PClass, field
9
+
10
+ from ._action import (
11
+ ACTION_STATUS_FIELD,
12
+ ACTION_TYPE_FIELD,
13
+ STARTED_STATUS,
14
+ FAILED_STATUS,
15
+ SUCCEEDED_STATUS,
16
+ )
17
+ from ._message import MESSAGE_TYPE_FIELD, TASK_LEVEL_FIELD, TASK_UUID_FIELD
18
+ from ._output import MemoryLogger
19
+ from . import _output
20
+ from .json import EliotJSONEncoder
21
+
22
+ COMPLETED_STATUSES = (FAILED_STATUS, SUCCEEDED_STATUS)
23
+
24
+
25
+ def issuperset(a, b):
26
+ """
27
+ Use L{assertContainsFields} instead.
28
+
29
+ @type a: C{dict}
30
+
31
+ @type b: C{dict}
32
+
33
+ @return: Boolean indicating whether C{a} has all key/value pairs that C{b}
34
+ does.
35
+ """
36
+ aItems = a.items()
37
+ return all(pair in aItems for pair in b.items())
38
+
39
+
40
+ def assertContainsFields(test, message, fields):
41
+ """
42
+ Assert that the given message contains the given fields.
43
+
44
+ @param test: L{unittest.TestCase} being run.
45
+
46
+ @param message: C{dict}, the message we are checking.
47
+
48
+ @param fields: C{dict}, the fields we expect the message to have.
49
+
50
+ @raises AssertionError: If the message doesn't contain the fields.
51
+ """
52
+ messageSubset = dict(
53
+ [(key, value) for key, value in message.items() if key in fields]
54
+ )
55
+ test.assertEqual(messageSubset, fields)
56
+
57
+
58
+ class LoggedAction(PClass):
59
+ """
60
+ An action whose start and finish messages have been logged.
61
+
62
+ @ivar startMessage: A C{dict}, the start message contents. Also
63
+ available as C{start_message}.
64
+
65
+ @ivar endMessage: A C{dict}, the end message contents (in both success and
66
+ failure cases). Also available as C{end_message}.
67
+
68
+ @ivar children: A C{list} of direct child L{LoggedMessage} and
69
+ L{LoggedAction} instances.
70
+ """
71
+
72
+ startMessage = field(mandatory=True)
73
+ endMessage = field(mandatory=True)
74
+ children = field(mandatory=True)
75
+
76
+ def __new__(cls, startMessage, endMessage, children):
77
+ return PClass.__new__(
78
+ cls, startMessage=startMessage, endMessage=endMessage, children=children
79
+ )
80
+
81
+ @property
82
+ def start_message(self):
83
+ return self.startMessage
84
+
85
+ @property
86
+ def end_message(self):
87
+ return self.endMessage
88
+
89
+ @classmethod
90
+ def fromMessages(klass, uuid, level, messages):
91
+ """
92
+ Given a task uuid and level (identifying an action) and a list of
93
+ dictionaries, create a L{LoggedAction}.
94
+
95
+ All child messages and actions will be added as L{LoggedAction} or
96
+ L{LoggedMessage} children. Note that some descendant messages may be
97
+ missing if you end up logging to two or more different ILogger
98
+ providers.
99
+
100
+ @param uuid: The uuid of the task (C{unicode}).
101
+
102
+ @param level: The C{task_level} of the action's start message,
103
+ e.g. C{"/1/2/1"}.
104
+
105
+ @param messages: A list of message C{dict}s.
106
+
107
+ @return: L{LoggedAction} constructed from start and finish messages for
108
+ this specific action.
109
+
110
+ @raises: L{ValueError} if one or both of the action's messages cannot be
111
+ found.
112
+ """
113
+ startMessage = None
114
+ endMessage = None
115
+ children = []
116
+ levelPrefix = level[:-1]
117
+
118
+ for message in messages:
119
+ if message[TASK_UUID_FIELD] != uuid:
120
+ # Different task altogether:
121
+ continue
122
+
123
+ messageLevel = message[TASK_LEVEL_FIELD]
124
+
125
+ if messageLevel[:-1] == levelPrefix:
126
+ status = message.get(ACTION_STATUS_FIELD)
127
+ if status == STARTED_STATUS:
128
+ startMessage = message
129
+ elif status in COMPLETED_STATUSES:
130
+ endMessage = message
131
+ else:
132
+ # Presumably a message in this action:
133
+ children.append(LoggedMessage(message))
134
+ elif (
135
+ len(messageLevel) == len(levelPrefix) + 2
136
+ and messageLevel[:-2] == levelPrefix
137
+ and messageLevel[-1] == 1
138
+ ):
139
+ # If start message level is [1], [1, 2, 1] implies first
140
+ # message of a direct child.
141
+ child = klass.fromMessages(uuid, message[TASK_LEVEL_FIELD], messages)
142
+ children.append(child)
143
+ if startMessage is None:
144
+ raise ValueError("Missing start message")
145
+ if endMessage is None:
146
+ raise ValueError(
147
+ "Missing end message of type "
148
+ + message.get(ACTION_TYPE_FIELD, "unknown")
149
+ )
150
+ return klass(startMessage, endMessage, children)
151
+
152
+ # PEP 8 variant:
153
+ from_messages = fromMessages
154
+
155
+ @classmethod
156
+ def of_type(klass, messages, actionType):
157
+ """
158
+ Find all L{LoggedAction} of the specified type.
159
+
160
+ @param messages: A list of message C{dict}s.
161
+
162
+ @param actionType: A L{eliot.ActionType}, the type of the actions to
163
+ find, or the type as a C{str}.
164
+
165
+ @return: A C{list} of L{LoggedAction}.
166
+ """
167
+ if not isinstance(actionType, str):
168
+ actionType = actionType.action_type
169
+ result = []
170
+ for message in messages:
171
+ if (
172
+ message.get(ACTION_TYPE_FIELD) == actionType
173
+ and message[ACTION_STATUS_FIELD] == STARTED_STATUS
174
+ ):
175
+ result.append(
176
+ klass.fromMessages(
177
+ message[TASK_UUID_FIELD], message[TASK_LEVEL_FIELD], messages
178
+ )
179
+ )
180
+ return result
181
+
182
+ # Backwards compat:
183
+ ofType = of_type
184
+
185
+ def descendants(self):
186
+ """
187
+ Find all descendant L{LoggedAction} or L{LoggedMessage} of this
188
+ instance.
189
+
190
+ @return: An iterable of L{LoggedAction} and L{LoggedMessage} instances.
191
+ """
192
+ for child in self.children:
193
+ yield child
194
+ if isinstance(child, LoggedAction):
195
+ for descendant in child.descendants():
196
+ yield descendant
197
+
198
+ @property
199
+ def succeeded(self):
200
+ """
201
+ Indicate whether this action succeeded.
202
+
203
+ @return: C{bool} indicating whether the action succeeded.
204
+ """
205
+ return self.endMessage[ACTION_STATUS_FIELD] == SUCCEEDED_STATUS
206
+
207
+ def type_tree(self):
208
+ """Return dictionary of all child action and message types.
209
+
210
+ Actions become dictionaries that look like
211
+ C{{<action_type>: [<child_message_type>, <child_action_dict>]}}
212
+
213
+ @return: C{dict} where key is action type, and value is list of child
214
+ types: either strings for messages, or dicts for actions.
215
+ """
216
+ children = []
217
+ for child in self.children:
218
+ if isinstance(child, LoggedAction):
219
+ children.append(child.type_tree())
220
+ else:
221
+ children.append(child.message[MESSAGE_TYPE_FIELD])
222
+ return {self.startMessage[ACTION_TYPE_FIELD]: children}
223
+
224
+
225
+ class LoggedMessage(PClass):
226
+ """
227
+ A message that has been logged.
228
+
229
+ @ivar message: A C{dict}, the message contents.
230
+ """
231
+
232
+ message = field(mandatory=True)
233
+
234
+ def __new__(cls, message):
235
+ return PClass.__new__(cls, message=message)
236
+
237
+ @classmethod
238
+ def of_type(klass, messages, messageType):
239
+ """
240
+ Find all L{LoggedMessage} of the specified type.
241
+
242
+ @param messages: A list of message C{dict}s.
243
+
244
+ @param messageType: A L{eliot.MessageType}, the type of the messages
245
+ to find, or the type as a L{str}.
246
+
247
+ @return: A C{list} of L{LoggedMessage}.
248
+ """
249
+ result = []
250
+ if not isinstance(messageType, str):
251
+ messageType = messageType.message_type
252
+ for message in messages:
253
+ if message.get(MESSAGE_TYPE_FIELD) == messageType:
254
+ result.append(klass(message))
255
+ return result
256
+
257
+ # Backwards compat:
258
+ ofType = of_type
259
+
260
+
261
+ class UnflushedTracebacks(Exception):
262
+ """
263
+ The L{MemoryLogger} had some tracebacks logged which were not flushed.
264
+
265
+ This means either your code has a bug and logged an unexpected
266
+ traceback. If you expected the traceback then you will need to flush it
267
+ using L{MemoryLogger.flushTracebacks}.
268
+ """
269
+
270
+
271
+ def check_for_errors(logger):
272
+ """
273
+ Raise exception if logger has unflushed tracebacks or validation errors.
274
+
275
+ @param logger: A L{MemoryLogger}.
276
+
277
+ @raise L{UnflushedTracebacks}: If any tracebacks were unflushed.
278
+ """
279
+ # Check for unexpected tracebacks first, since that indicates business
280
+ # logic errors:
281
+ if logger.tracebackMessages:
282
+ raise UnflushedTracebacks(logger.tracebackMessages)
283
+ # If those are fine, validate the logging:
284
+ logger.validate()
285
+
286
+
287
+ def swap_logger(logger):
288
+ """Swap out the global logging sink.
289
+
290
+ @param logger: An C{ILogger}.
291
+
292
+ @return: The current C{ILogger}.
293
+ """
294
+ previous_logger = _output._DEFAULT_LOGGER
295
+ _output._DEFAULT_LOGGER = logger
296
+ return previous_logger
297
+
298
+
299
+ def validateLogging(
300
+ assertion, *assertionArgs, encoder_=EliotJSONEncoder, **assertionKwargs
301
+ ):
302
+ """
303
+ Decorator factory for L{unittest.TestCase} methods to add logging
304
+ validation.
305
+
306
+ 1. The decorated test method gets a C{logger} keyword argument, a
307
+ L{MemoryLogger}.
308
+ 2. All messages logged to this logger will be validated at the end of
309
+ the test.
310
+ 3. Any unflushed logged tracebacks will cause the test to fail.
311
+
312
+ For example:
313
+
314
+ from unittest import TestCase
315
+ from eliot.testing import assertContainsFields, validateLogging
316
+
317
+ class MyTests(TestCase):
318
+ def assertFooLogging(self, logger):
319
+ assertContainsFields(self, logger.messages[0], {"key": 123})
320
+
321
+
322
+ @param assertion: A callable that will be called with the
323
+ L{unittest.TestCase} instance, the logger and C{assertionArgs} and
324
+ C{assertionKwargs} once the actual test has run, allowing for extra
325
+ logging-related assertions on the effects of the test. Use L{None} if you
326
+ want the cleanup assertions registered but no custom assertions.
327
+
328
+ @param assertionArgs: Additional positional arguments to pass to
329
+ C{assertion}.
330
+
331
+ @param assertionKwargs: Additional keyword arguments to pass to
332
+ C{assertion}.
333
+
334
+ @param encoder_: C{json.JSONEncoder} subclass to use when validating JSON.
335
+ """
336
+
337
+ def decorator(function):
338
+ @wraps(function)
339
+ def wrapper(self, *args, **kwargs):
340
+ skipped = False
341
+
342
+ kwargs["logger"] = logger = MemoryLogger(encoder=encoder_)
343
+ self.addCleanup(check_for_errors, logger)
344
+ # TestCase runs cleanups in reverse order, and we want this to
345
+ # run *before* tracebacks are checked:
346
+ if assertion is not None:
347
+ self.addCleanup(
348
+ lambda: skipped
349
+ or assertion(self, logger, *assertionArgs, **assertionKwargs)
350
+ )
351
+ try:
352
+ return function(self, *args, **kwargs)
353
+ except SkipTest:
354
+ skipped = True
355
+ raise
356
+
357
+ return wrapper
358
+
359
+ return decorator
360
+
361
+
362
+ # PEP 8 variant:
363
+ validate_logging = validateLogging
364
+
365
+
366
+ def capture_logging(
367
+ assertion, *assertionArgs, encoder_=EliotJSONEncoder, **assertionKwargs
368
+ ):
369
+ """
370
+ Capture and validate all logging that doesn't specify a L{Logger}.
371
+
372
+ See L{validate_logging} for details on the rest of its behavior.
373
+ """
374
+
375
+ def decorator(function):
376
+ @validate_logging(
377
+ assertion, *assertionArgs, encoder_=encoder_, **assertionKwargs
378
+ )
379
+ @wraps(function)
380
+ def wrapper(self, *args, **kwargs):
381
+ logger = kwargs["logger"]
382
+ previous_logger = swap_logger(logger)
383
+
384
+ def cleanup():
385
+ swap_logger(previous_logger)
386
+
387
+ self.addCleanup(cleanup)
388
+ return function(self, *args, **kwargs)
389
+
390
+ return wrapper
391
+
392
+ return decorator
393
+
394
+
395
+ def assertHasMessage(testCase, logger, messageType, fields=None):
396
+ """
397
+ Assert that the given logger has a message of the given type, and the first
398
+ message found of this type has the given fields.
399
+
400
+ This can be used as the assertion function passed to L{validateLogging} or
401
+ as part of a unit test.
402
+
403
+ @param testCase: L{unittest.TestCase} instance.
404
+
405
+ @param logger: L{eliot.MemoryLogger} whose messages will be checked.
406
+
407
+ @param messageType: L{eliot.MessageType} indicating which message we're
408
+ looking for.
409
+
410
+ @param fields: The first message of the given type found must have a
411
+ superset of the given C{dict} as its fields. If C{None} then fields are
412
+ not checked.
413
+
414
+ @return: The first found L{LoggedMessage} of the given type, if field
415
+ validation succeeded.
416
+
417
+ @raises AssertionError: No message was found, or the fields were not
418
+ superset of given fields.
419
+ """
420
+ if fields is None:
421
+ fields = {}
422
+ messages = LoggedMessage.ofType(logger.messages, messageType)
423
+ testCase.assertTrue(messages, "No messages of type %s" % (messageType,))
424
+ loggedMessage = messages[0]
425
+ assertContainsFields(testCase, loggedMessage.message, fields)
426
+ return loggedMessage
427
+
428
+
429
+ def assertHasAction(
430
+ testCase, logger, actionType, succeeded, startFields=None, endFields=None
431
+ ):
432
+ """
433
+ Assert that the given logger has an action of the given type, and the first
434
+ action found of this type has the given fields and success status.
435
+
436
+ This can be used as the assertion function passed to L{validateLogging} or
437
+ as part of a unit test.
438
+
439
+ @param testCase: L{unittest.TestCase} instance.
440
+
441
+ @param logger: L{eliot.MemoryLogger} whose messages will be checked.
442
+
443
+ @param actionType: L{eliot.ActionType} or C{str} indicating which message
444
+ we're looking for.
445
+
446
+ @param succeeded: Expected success status of the action, a C{bool}.
447
+
448
+ @param startFields: The first action of the given type found must have a
449
+ superset of the given C{dict} as its start fields. If C{None} then
450
+ fields are not checked.
451
+
452
+ @param endFields: The first action of the given type found must have a
453
+ superset of the given C{dict} as its end fields. If C{None} then
454
+ fields are not checked.
455
+
456
+ @return: The first found L{LoggedAction} of the given type, if field
457
+ validation succeeded.
458
+
459
+ @raises AssertionError: No action was found, or the fields were not
460
+ superset of given fields.
461
+ """
462
+ if startFields is None:
463
+ startFields = {}
464
+ if endFields is None:
465
+ endFields = {}
466
+ actions = LoggedAction.ofType(logger.messages, actionType)
467
+ testCase.assertTrue(actions, "No actions of type %s" % (actionType,))
468
+ action = actions[0]
469
+ testCase.assertEqual(action.succeeded, succeeded)
470
+ assertContainsFields(testCase, action.startMessage, startFields)
471
+ assertContainsFields(testCase, action.endMessage, endFields)
472
+ return action
@@ -0,0 +1,9 @@
1
+ """
2
+ Tests for the logxpy package.
3
+ """
4
+
5
+ # Increase hypothesis deadline so we don't time out on PyPy:
6
+ from hypothesis import settings
7
+
8
+ settings.register_profile("eliot", deadline=1000)
9
+ settings.load_profile("eliot")
logxpy/tests/common.py ADDED
@@ -0,0 +1,36 @@
1
+ """
2
+ Common testing infrastructure.
3
+ """
4
+
5
+ from io import StringIO
6
+ from json import JSONEncoder
7
+
8
+
9
+ class CustomObject(object):
10
+ """Gets encoded to JSON."""
11
+
12
+
13
+ class CustomJSONEncoder(JSONEncoder):
14
+ """JSONEncoder that knows about L{CustomObject}."""
15
+
16
+ def default(self, o):
17
+ if isinstance(o, CustomObject):
18
+ return "CUSTOM!"
19
+ return JSONEncoder.default(self, o)
20
+
21
+
22
+ class FakeSys(object):
23
+ """
24
+ A fake L{sys} module.
25
+ """
26
+
27
+ def __init__(self, argv, stdinStr):
28
+ """
29
+ @param argv: List of command-line arguments.
30
+
31
+ @param stdinStr: C{str} that are readable from stdin.
32
+ """
33
+ self.argv = argv
34
+ self.stdin = StringIO(stdinStr)
35
+ self.stdout = StringIO()
36
+ self.stderr = StringIO()