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
@@ -0,0 +1,921 @@
1
+ """
2
+ Tests for L{eliot._output}.
3
+ """
4
+
5
+ from sys import stdout
6
+ from unittest import TestCase, skipUnless
7
+
8
+ # Make sure to use StringIO that only accepts unicode:
9
+ from io import BytesIO, StringIO
10
+ import json as pyjson
11
+ from tempfile import mktemp
12
+ from time import time
13
+ from uuid import UUID
14
+ from threading import Thread
15
+
16
+ try:
17
+ import numpy as np
18
+ except ImportError:
19
+ np = None
20
+ from zope.interface.verify import verifyClass
21
+
22
+ from .._output import (
23
+ MemoryLogger,
24
+ ILogger,
25
+ Destinations,
26
+ Logger,
27
+ to_file,
28
+ FileDestination,
29
+ _safe_unicode_dictionary,
30
+ )
31
+ from .._action import start_action
32
+ from .._validation import ValidationError, Field, _MessageSerializer
33
+ from .._traceback import write_traceback
34
+ from ..testing import assertContainsFields
35
+ from .common import CustomObject, CustomJSONEncoder
36
+
37
+
38
+ class MemoryLoggerTests(TestCase):
39
+ """
40
+ Tests for L{MemoryLogger}.
41
+ """
42
+
43
+ def test_interface(self):
44
+ """
45
+ L{MemoryLogger} implements L{ILogger}.
46
+ """
47
+ verifyClass(ILogger, MemoryLogger)
48
+
49
+ def test_write(self):
50
+ """
51
+ Dictionaries written with L{MemoryLogger.write} are stored on a list.
52
+ """
53
+ logger = MemoryLogger()
54
+ logger.write({"a": "b"})
55
+ logger.write({"c": 1})
56
+ self.assertEqual(logger.messages, [{"a": "b"}, {"c": 1}])
57
+ logger.validate()
58
+
59
+ def test_notStringFieldKeys(self):
60
+ """
61
+ Field keys must be unicode or bytes; if not L{MemoryLogger.validate}
62
+ raises a C{TypeError}.
63
+ """
64
+ logger = MemoryLogger()
65
+ logger.write({123: "b"})
66
+ self.assertRaises(TypeError, logger.validate)
67
+
68
+ def test_bytesMustBeUTF8(self):
69
+ """
70
+ Field keys can be bytes, but only if they're UTF-8 encoded Unicode.
71
+ """
72
+ logger = MemoryLogger()
73
+ logger.write({"\u1234".encode("utf-16"): "b"})
74
+ self.assertRaises(UnicodeDecodeError, logger.validate)
75
+
76
+ def test_serializer(self):
77
+ """
78
+ L{MemoryLogger.validate} calls the given serializer's C{validate()}
79
+ method with the message, as does L{MemoryLogger.write}.
80
+ """
81
+
82
+ class FakeValidator(list):
83
+ def validate(self, message):
84
+ self.append(message)
85
+
86
+ def serialize(self, obj):
87
+ return obj
88
+
89
+ validator = FakeValidator()
90
+ logger = MemoryLogger()
91
+ message = {"message_type": "mymessage", "X": 1}
92
+ logger.write(message, validator)
93
+ self.assertEqual(validator, [message])
94
+ logger.validate()
95
+ self.assertEqual(validator, [message, message])
96
+
97
+ def test_failedValidation(self):
98
+ """
99
+ L{MemoryLogger.validate} will allow exceptions raised by the serializer
100
+ to pass through.
101
+ """
102
+ serializer = _MessageSerializer(
103
+ [Field.forValue("message_type", "mymessage", "The type")]
104
+ )
105
+ logger = MemoryLogger()
106
+ logger.write({"message_type": "wrongtype"}, serializer)
107
+ self.assertRaises(ValidationError, logger.validate)
108
+
109
+ def test_JSON(self):
110
+ """
111
+ L{MemoryLogger.validate} will encode the output of serialization to
112
+ JSON.
113
+ """
114
+ serializer = _MessageSerializer(
115
+ [
116
+ Field.forValue("message_type", "type", "The type"),
117
+ Field("foo", lambda value: object(), "The type"),
118
+ ]
119
+ )
120
+ logger = MemoryLogger()
121
+ logger.write(
122
+ {"message_type": "type", "foo": "will become object()"}, serializer
123
+ )
124
+ self.assertRaises(TypeError, logger.validate)
125
+
126
+ @skipUnless(np, "NumPy is not installed.")
127
+ def test_EliotJSONEncoder(self):
128
+ """
129
+ L{MemoryLogger.validate} uses the EliotJSONEncoder by default to do
130
+ encoding testing.
131
+ """
132
+ logger = MemoryLogger()
133
+ logger.write({"message_type": "type", "foo": np.uint64(12)}, None)
134
+ logger.validate()
135
+
136
+ def test_JSON_custom_encoder(self):
137
+ """
138
+ L{MemoryLogger.validate} will use a custom JSON encoder if one was given.
139
+ """
140
+ logger = MemoryLogger(encoder=CustomJSONEncoder)
141
+ logger.write(
142
+ {"message_type": "type", "custom": CustomObject()},
143
+ None,
144
+ )
145
+ logger.validate()
146
+
147
+ def test_serialize(self):
148
+ """
149
+ L{MemoryLogger.serialize} returns a list of serialized versions of the
150
+ logged messages.
151
+ """
152
+ serializer = _MessageSerializer(
153
+ [
154
+ Field.forValue("message_type", "mymessage", "The type"),
155
+ Field("length", len, "The length"),
156
+ ]
157
+ )
158
+ messages = [
159
+ {"message_type": "mymessage", "length": "abc"},
160
+ {"message_type": "mymessage", "length": "abcd"},
161
+ ]
162
+ logger = MemoryLogger()
163
+ for message in messages:
164
+ logger.write(message, serializer)
165
+ self.assertEqual(
166
+ logger.serialize(),
167
+ [
168
+ {"message_type": "mymessage", "length": 3},
169
+ {"message_type": "mymessage", "length": 4},
170
+ ],
171
+ )
172
+
173
+ def test_serializeCopies(self):
174
+ """
175
+ L{MemoryLogger.serialize} does not mutate the original logged messages.
176
+ """
177
+ serializer = _MessageSerializer(
178
+ [
179
+ Field.forValue("message_type", "mymessage", "The type"),
180
+ Field("length", len, "The length"),
181
+ ]
182
+ )
183
+ message = {"message_type": "mymessage", "length": "abc"}
184
+ logger = MemoryLogger()
185
+ logger.write(message, serializer)
186
+ logger.serialize()
187
+ self.assertEqual(logger.messages[0]["length"], "abc")
188
+
189
+ def write_traceback(self, logger, exception):
190
+ """
191
+ Write an exception as a traceback to the logger.
192
+ """
193
+ try:
194
+ raise exception
195
+ except:
196
+ write_traceback(logger)
197
+
198
+ def test_tracebacksCauseTestFailure(self):
199
+ """
200
+ Logging a traceback to L{MemoryLogger} will add its exception to
201
+ L{MemoryLogger.tracebackMessages}.
202
+ """
203
+ logger = MemoryLogger()
204
+ exception = Exception()
205
+ self.write_traceback(logger, exception)
206
+ self.assertEqual(logger.tracebackMessages[0]["reason"], exception)
207
+
208
+ def test_flushTracebacksNoTestFailure(self):
209
+ """
210
+ Any tracebacks cleared by L{MemoryLogger.flushTracebacks} (as specified
211
+ by exception type) are removed from
212
+ L{MemoryLogger.tracebackMessages}.
213
+ """
214
+ logger = MemoryLogger()
215
+ exception = RuntimeError()
216
+ self.write_traceback(logger, exception)
217
+ logger.flushTracebacks(RuntimeError)
218
+ self.assertEqual(logger.tracebackMessages, [])
219
+
220
+ def test_flushTracebacksReturnsExceptions(self):
221
+ """
222
+ L{MemoryLogger.flushTracebacks} returns the traceback messages.
223
+ """
224
+ exceptions = [ZeroDivisionError(), ZeroDivisionError()]
225
+ logger = MemoryLogger()
226
+ logger.write({"x": 1})
227
+ for exc in exceptions:
228
+ self.write_traceback(logger, exc)
229
+ logger.write({"x": 1})
230
+ flushed = logger.flushTracebacks(ZeroDivisionError)
231
+ self.assertEqual(flushed, logger.messages[1:3])
232
+
233
+ def test_flushTracebacksUnflushedTestFailure(self):
234
+ """
235
+ Any tracebacks uncleared by L{MemoryLogger.flushTracebacks} (because
236
+ they are of a different type) are still listed in
237
+ L{MemoryLogger.tracebackMessages}.
238
+ """
239
+ logger = MemoryLogger()
240
+ exception = RuntimeError()
241
+ self.write_traceback(logger, exception)
242
+ logger.flushTracebacks(KeyError)
243
+ self.assertEqual(logger.tracebackMessages[0]["reason"], exception)
244
+
245
+ def test_flushTracebacksUnflushedUnreturned(self):
246
+ """
247
+ Any tracebacks uncleared by L{MemoryLogger.flushTracebacks} (because
248
+ they are of a different type) are not returned.
249
+ """
250
+ logger = MemoryLogger()
251
+ exception = RuntimeError()
252
+ self.write_traceback(logger, exception)
253
+ self.assertEqual(logger.flushTracebacks(KeyError), [])
254
+
255
+ def test_reset(self):
256
+ """
257
+ L{MemoryLogger.reset} clears all logged messages and tracebacks.
258
+ """
259
+ logger = MemoryLogger()
260
+ logger.write({"key": "value"}, None)
261
+ logger.reset()
262
+ self.assertEqual(
263
+ (logger.messages, logger.serializers, logger.tracebackMessages),
264
+ ([], [], []),
265
+ )
266
+
267
+ def test_threadSafeWrite(self):
268
+ """
269
+ L{MemoryLogger.write} can be called from multiple threads concurrently.
270
+ """
271
+ # Some threads will log some messages
272
+ thread_count = 10
273
+
274
+ # A lot of messages. This will keep the threads running long enough
275
+ # to give them a chance to (try to) interfere with each other.
276
+ write_count = 10000
277
+
278
+ # They'll all use the same MemoryLogger instance.
279
+ logger = MemoryLogger()
280
+
281
+ # Each thread will have its own message and serializer that it writes
282
+ # to the log over and over again.
283
+ def write(msg, serializer):
284
+ for i in range(write_count):
285
+ logger.write(msg, serializer)
286
+
287
+ # Generate a single distinct message for each thread to log.
288
+ msgs = list({"i": i} for i in range(thread_count))
289
+
290
+ # Generate a single distinct serializer for each thread to log.
291
+ serializers = list(object() for i in range(thread_count))
292
+
293
+ # Pair them all up. This gives us a simple invariant we can check
294
+ # later on.
295
+ write_args = zip(msgs, serializers)
296
+
297
+ # Create the threads.
298
+ threads = list(Thread(target=write, args=args) for args in write_args)
299
+
300
+ # Run them all. Note threads early in this list will start writing to
301
+ # the log before later threads in the list even get a chance to start.
302
+ # That's part of why we have each thread write so many messages.
303
+ for t in threads:
304
+ t.start()
305
+ # Wait for them all to finish.
306
+ for t in threads:
307
+ t.join()
308
+
309
+ # Check that we got the correct number of messages in the log.
310
+ expected_count = thread_count * write_count
311
+ self.assertEqual(len(logger.messages), expected_count)
312
+ self.assertEqual(len(logger.serializers), expected_count)
313
+
314
+ # Check the simple invariant we created above. Every logged message
315
+ # must be paired with the correct serializer, where "correct" is
316
+ # defined by ``write_args`` above.
317
+ for position, (msg, serializer) in enumerate(
318
+ zip(logger.messages, logger.serializers)
319
+ ):
320
+ # The indexes must match because the objects are paired using
321
+ # zip() above.
322
+ msg_index = msgs.index(msg)
323
+ serializer_index = serializers.index(serializer)
324
+ self.assertEqual(
325
+ msg_index,
326
+ serializer_index,
327
+ "Found message #{} with serializer #{} at position {}".format(
328
+ msg_index, serializer_index, position
329
+ ),
330
+ )
331
+
332
+
333
+ class MyException(Exception):
334
+ """
335
+ Custom exception.
336
+ """
337
+
338
+
339
+ class BadDestination(list):
340
+ """
341
+ A destination that throws an exception the first time it is called.
342
+ """
343
+
344
+ called = 0
345
+
346
+ def __call__(self, msg):
347
+ if not self.called:
348
+ self.called = True
349
+ raise MyException("ono")
350
+ self.append(msg)
351
+
352
+
353
+ class DestinationsTests(TestCase):
354
+ """
355
+ Tests for L{Destinations}.
356
+ """
357
+
358
+ def test_send(self):
359
+ """
360
+ L{Destinations.send} calls all destinations added with
361
+ L{Destinations.add} with the given dictionary.
362
+ """
363
+ destinations = Destinations()
364
+ message = {"hoorj": "blargh"}
365
+ dest = []
366
+ dest2 = []
367
+ dest3 = []
368
+ destinations.add(dest.append, dest2.append)
369
+ destinations.add(dest3.append)
370
+ destinations.send(message)
371
+ self.assertEqual(dest, [message])
372
+ self.assertEqual(dest2, [message])
373
+ self.assertEqual(dest3, [message])
374
+
375
+ def test_destination_exception_multiple_destinations(self):
376
+ """
377
+ If one destination throws an exception, other destinations still
378
+ get the message.
379
+ """
380
+ destinations = Destinations()
381
+ dest = []
382
+ dest2 = BadDestination()
383
+ dest3 = []
384
+ destinations.add(dest.append)
385
+ destinations.add(dest2)
386
+ destinations.add(dest3.append)
387
+
388
+ message = {"hello": 123}
389
+ destinations.send(message)
390
+ self.assertIn(message, dest)
391
+ self.assertIn(message, dest3)
392
+
393
+ def test_destination_exception_continue(self):
394
+ """
395
+ If a destination throws an exception, future messages are still
396
+ sent to it.
397
+ """
398
+ destinations = Destinations()
399
+ dest = BadDestination()
400
+ destinations.add(dest)
401
+
402
+ msg1 = {"hello": 123}
403
+ msg2 = {"world": 456}
404
+ destinations.send(msg1)
405
+ self.assertNotIn(msg1, dest)
406
+ destinations.send(msg2)
407
+ self.assertIn(msg2, dest)
408
+
409
+ def test_remove(self):
410
+ """
411
+ A destination removed with L{Destinations.remove} will no longer
412
+ receive messages from L{Destionations.add} calls.
413
+ """
414
+ destinations = Destinations()
415
+ message = {"hello": 123}
416
+ dest = []
417
+ destinations.add(dest.append)
418
+ destinations.remove(dest.append)
419
+ destinations.send(message)
420
+ self.assertEqual(dest, [])
421
+
422
+ def test_removeNonExistent(self):
423
+ """
424
+ Removing a destination that has not previously been added with result
425
+ in a C{ValueError} being thrown.
426
+ """
427
+ destinations = Destinations()
428
+ self.assertRaises(ValueError, destinations.remove, [].append)
429
+
430
+ def test_addGlobalFields(self):
431
+ """
432
+ L{Destinations.addGlobalFields} adds the given fields and values to
433
+ the messages being passed in.
434
+ """
435
+ destinations = Destinations()
436
+ dest = []
437
+ destinations.add(dest.append)
438
+ destinations.addGlobalFields(x=123, y="hello")
439
+ destinations.send({"z": 456})
440
+ self.assertEqual(dest, [{"x": 123, "y": "hello", "z": 456}])
441
+
442
+ def test_addGlobalFieldsCumulative(self):
443
+ """
444
+ L{Destinations.addGlobalFields} adds the given fields to those set by
445
+ previous calls.
446
+ """
447
+ destinations = Destinations()
448
+ dest = []
449
+ destinations.add(dest.append)
450
+ destinations.addGlobalFields(x=123, y="hello")
451
+ destinations.addGlobalFields(x=456, z=456)
452
+ destinations.send({"msg": "X"})
453
+ self.assertEqual(dest, [{"x": 456, "y": "hello", "z": 456, "msg": "X"}])
454
+
455
+ def test_buffering(self):
456
+ """
457
+ Before any destinations are set up to 1000 messages are buffered, and
458
+ then delivered to the first registered destinations.
459
+ """
460
+ destinations = Destinations()
461
+ messages = [{"k": i} for i in range(1050)]
462
+ for m in messages:
463
+ destinations.send(m)
464
+ dest, dest2 = [], []
465
+ destinations.add(dest.append, dest2.append)
466
+ self.assertEqual((dest, dest2), (messages[-1000:], messages[-1000:]))
467
+
468
+ def test_buffering_second_batch(self):
469
+ """
470
+ The second batch of added destination don't get the buffered messages.
471
+ """
472
+ destinations = Destinations()
473
+ message = {"m": 1}
474
+ message2 = {"m": 2}
475
+ destinations.send(message)
476
+ dest = []
477
+ dest2 = []
478
+ destinations.add(dest.append)
479
+ destinations.add(dest2.append)
480
+ destinations.send(message2)
481
+ self.assertEqual((dest, dest2), ([message, message2], [message2]))
482
+
483
+ def test_global_fields_buffering(self):
484
+ """
485
+ Global fields are added to buffered messages, when possible.
486
+ """
487
+ destinations = Destinations()
488
+ message = {"m": 1}
489
+ destinations.send(message)
490
+ destinations.addGlobalFields(k=123)
491
+ dest = []
492
+ destinations.add(dest.append)
493
+ self.assertEqual(dest, [{"m": 1, "k": 123}])
494
+
495
+
496
+ def makeLogger():
497
+ """
498
+ Return a tuple (L{Logger} instance, C{list} of written messages).
499
+ """
500
+ logger = Logger()
501
+ logger._destinations = Destinations()
502
+ written = []
503
+ logger._destinations.add(written.append)
504
+ return logger, written
505
+
506
+
507
+ class LoggerTests(TestCase):
508
+ """
509
+ Tests for L{Logger}.
510
+ """
511
+
512
+ def test_interface(self):
513
+ """
514
+ L{Logger} implements L{ILogger}.
515
+ """
516
+ verifyClass(ILogger, Logger)
517
+
518
+ def test_global(self):
519
+ """
520
+ A global L{Destinations} is used by the L{Logger} class.
521
+ """
522
+ self.assertIsInstance(Logger._destinations, Destinations)
523
+
524
+ def test_write(self):
525
+ """
526
+ L{Logger.write} sends the given dictionary L{Destinations} object.
527
+ """
528
+ logger, written = makeLogger()
529
+
530
+ d = {"hello": 1}
531
+ logger.write(d)
532
+ self.assertEqual(written, [d])
533
+
534
+ def test_serializer(self):
535
+ """
536
+ If a L{_MessageSerializer} is passed to L{Logger.write}, it is used to
537
+ serialize the message before it is passed to the destination.
538
+ """
539
+ logger, written = makeLogger()
540
+
541
+ serializer = _MessageSerializer(
542
+ [
543
+ Field.forValue("message_type", "mymessage", "The type"),
544
+ Field("length", len, "The length of a thing"),
545
+ ]
546
+ )
547
+ logger.write({"message_type": "mymessage", "length": "thething"}, serializer)
548
+ self.assertEqual(written, [{"message_type": "mymessage", "length": 8}])
549
+
550
+ def test_passedInDictionaryUnmodified(self):
551
+ """
552
+ The dictionary passed in to L{Logger.write} is not modified.
553
+ """
554
+ logger, written = makeLogger()
555
+
556
+ serializer = _MessageSerializer(
557
+ [
558
+ Field.forValue("message_type", "mymessage", "The type"),
559
+ Field("length", len, "The length of a thing"),
560
+ ]
561
+ )
562
+ d = {"message_type": "mymessage", "length": "thething"}
563
+ original = d.copy()
564
+ logger.write(d, serializer)
565
+ self.assertEqual(d, original)
566
+
567
+ def test_safe_unicode_dictionary(self):
568
+ """
569
+ L{_safe_unicode_dictionary} converts the given dictionary's
570
+ values and keys to unicode using C{safeunicode}.
571
+ """
572
+
573
+ class badobject(object):
574
+ def __repr__(self):
575
+ raise TypeError()
576
+
577
+ dictionary = {badobject(): 123, 123: badobject()}
578
+ badMessage = "eliot: unknown, str() raised exception"
579
+ self.assertEqual(
580
+ eval(_safe_unicode_dictionary(dictionary)),
581
+ {badMessage: "123", "123": badMessage},
582
+ )
583
+
584
+ def test_safe_unicode_dictionary_fallback(self):
585
+ """
586
+ If converting the dictionary failed for some reason,
587
+ L{_safe_unicode_dictionary} runs C{repr} on the object.
588
+ """
589
+ self.assertEqual(_safe_unicode_dictionary(None), "None")
590
+
591
+ def test_safe_unicode_dictionary_fallback_failure(self):
592
+ """
593
+ If all else fails, L{_safe_unicode_dictionary} just gives up.
594
+ """
595
+
596
+ class badobject(object):
597
+ def __repr__(self):
598
+ raise TypeError()
599
+
600
+ self.assertEqual(
601
+ _safe_unicode_dictionary(badobject()),
602
+ "eliot: unknown, str() raised exception",
603
+ )
604
+
605
+ def test_serializationErrorTraceback(self):
606
+ """
607
+ If serialization fails in L{Logger.write}, a traceback is logged,
608
+ along with a C{eliot:serialization_failure} message for debugging
609
+ purposes.
610
+ """
611
+ logger, written = makeLogger()
612
+
613
+ def raiser(i):
614
+ raise RuntimeError("oops")
615
+
616
+ serializer = _MessageSerializer(
617
+ [
618
+ Field.forValue("message_type", "mymessage", "The type"),
619
+ Field("fail", raiser, "Serialization fail"),
620
+ ]
621
+ )
622
+ message = {"message_type": "mymessage", "fail": "will"}
623
+ logger.write(message, serializer)
624
+ self.assertEqual(len(written), 2)
625
+ tracebackMessage = written[0]
626
+ assertContainsFields(
627
+ self,
628
+ tracebackMessage,
629
+ {
630
+ "exception": "%s.RuntimeError" % (RuntimeError.__module__,),
631
+ "message_type": "eliot:traceback",
632
+ },
633
+ )
634
+ self.assertIn("RuntimeError: oops", tracebackMessage["traceback"])
635
+ # Calling _safe_unicode_dictionary multiple times leads to
636
+ # inconsistent results due to hash ordering, so compare contents:
637
+ assertContainsFields(
638
+ self, written[1], {"message_type": "eliot:serialization_failure"}
639
+ )
640
+ self.assertEqual(
641
+ eval(written[1]["message"]),
642
+ dict((repr(key), repr(value)) for (key, value) in message.items()),
643
+ )
644
+
645
+ def test_destination_exception_caught(self):
646
+ """
647
+ If a destination throws an exception, an appropriate error is
648
+ logged.
649
+ """
650
+ logger = Logger()
651
+ logger._destinations = Destinations()
652
+ dest = BadDestination()
653
+ logger._destinations.add(dest)
654
+
655
+ message = {"hello": 123}
656
+ logger.write({"hello": 123})
657
+ assertContainsFields(
658
+ self,
659
+ dest[0],
660
+ {
661
+ "message_type": "eliot:destination_failure",
662
+ "message": _safe_unicode_dictionary(message),
663
+ "reason": "ono",
664
+ "exception": "eliot.tests.test_output.MyException",
665
+ },
666
+ )
667
+
668
+ def test_destination_multiple_exceptions_caught(self):
669
+ """
670
+ If multiple destinations throw an exception, an appropriate error is
671
+ logged for each.
672
+ """
673
+ logger = Logger()
674
+ logger._destinations = Destinations()
675
+ logger._destinations.add(BadDestination())
676
+ logger._destinations.add(lambda msg: 1 / 0)
677
+ messages = []
678
+ logger._destinations.add(messages.append)
679
+
680
+ try:
681
+ 1 / 0
682
+ except ZeroDivisionError as e:
683
+ zero_divide = str(e)
684
+ zero_type = ZeroDivisionError.__module__ + ".ZeroDivisionError"
685
+
686
+ message = {"hello": 123}
687
+ logger.write({"hello": 123})
688
+
689
+ def remove(key):
690
+ return [message.pop(key) for message in messages[1:]]
691
+
692
+ # Make sure we have task_level & task_uuid in exception messages.
693
+ task_levels = remove("task_level")
694
+ task_uuids = remove("task_uuid")
695
+ timestamps = remove("timestamp")
696
+
697
+ self.assertEqual(
698
+ (
699
+ abs(timestamps[0] + timestamps[1] - 2 * time()) < 1,
700
+ task_levels == [[1], [1]],
701
+ len([UUID(uuid) for uuid in task_uuids]) == 2,
702
+ messages,
703
+ ),
704
+ (
705
+ True,
706
+ True,
707
+ True,
708
+ [
709
+ message,
710
+ {
711
+ "message_type": "eliot:destination_failure",
712
+ "message": _safe_unicode_dictionary(message),
713
+ "reason": "ono",
714
+ "exception": "eliot.tests.test_output.MyException",
715
+ },
716
+ {
717
+ "message_type": "eliot:destination_failure",
718
+ "message": _safe_unicode_dictionary(message),
719
+ "reason": zero_divide,
720
+ "exception": zero_type,
721
+ },
722
+ ],
723
+ ),
724
+ )
725
+
726
+ def test_destination_exception_caught_twice(self):
727
+ """
728
+ If a destination throws an exception, and the logged error about
729
+ it also causes an exception, then just drop that exception on the
730
+ floor, since there's nothing we can do with it.
731
+ """
732
+ logger = Logger()
733
+ logger._destinations = Destinations()
734
+
735
+ def always_raise(message):
736
+ raise ZeroDivisionError()
737
+
738
+ logger._destinations.add(always_raise)
739
+
740
+ # Just a message. No exception raised; since everything is dropped no
741
+ # other assertions to be made.
742
+ logger.write({"hello": 123})
743
+
744
+ # With an action. No exception raised; since everything is dropped no
745
+ # other assertions to be made.
746
+ with start_action(logger, "sys:do"):
747
+ logger.write({"hello": 123})
748
+
749
+
750
+ class PEP8Tests(TestCase):
751
+ """
752
+ Tests for PEP 8 method compatibility.
753
+ """
754
+
755
+ def test_flush_tracebacks(self):
756
+ """
757
+ L{MemoryLogger.flush_tracebacks} is the same as
758
+ L{MemoryLogger.flushTracebacks}
759
+ """
760
+ self.assertEqual(MemoryLogger.flush_tracebacks, MemoryLogger.flushTracebacks)
761
+
762
+
763
+ class ToFileTests(TestCase):
764
+ """
765
+ Tests for L{to_file}.
766
+ """
767
+
768
+ def test_to_file_adds_destination(self):
769
+ """
770
+ L{to_file} adds a L{FileDestination} destination with the given file.
771
+ """
772
+ f = BytesIO()
773
+ to_file(f)
774
+ expected = FileDestination(file=f)
775
+ self.addCleanup(Logger._destinations.remove, expected)
776
+ self.assertIn(expected, Logger._destinations._destinations)
777
+
778
+ def test_to_file_custom_encoder(self):
779
+ """
780
+ L{to_file} accepts a custom encoder, and sets it on the resulting
781
+ L{FileDestination}.
782
+ """
783
+ from json import JSONEncoder
784
+
785
+ f = stdout
786
+
787
+ class MyEncoder(JSONEncoder):
788
+ def default(self, o):
789
+ return 17
790
+
791
+ to_file(f, encoder=MyEncoder)
792
+ added = Logger._destinations._destinations[-1]
793
+ self.addCleanup(Logger._destinations.remove, added)
794
+ self.assertEqual(added._json_default(object()), 17)
795
+
796
+ def test_to_file_custom_json_default(self):
797
+ """
798
+ L{to_file} accepts a custom JSON default object, and sets it on the resulting
799
+ L{FileDestination}.
800
+ """
801
+ f = BytesIO()
802
+
803
+ def default(o):
804
+ return 23
805
+
806
+ to_file(f, json_default=default)
807
+ added = Logger._destinations._destinations[-1]
808
+ self.addCleanup(Logger._destinations.remove, added)
809
+ self.assertEqual(added._json_default(object()), 23)
810
+
811
+ @skipUnless(np, "NumPy is not installed.")
812
+ def test_default_encoder_supports_numpy(self):
813
+ """The default encoder can encode NumPy objects."""
814
+ message = {"x": np.int64(3)}
815
+ f = StringIO()
816
+ destination = FileDestination(file=f)
817
+ destination(message)
818
+ self.assertEqual(
819
+ [pyjson.loads(line) for line in f.getvalue().splitlines()], [{"x": 3}]
820
+ )
821
+
822
+ def test_filedestination_writes_json_bytes(self):
823
+ """
824
+ L{FileDestination} writes JSON-encoded messages to a file that accepts
825
+ bytes.
826
+ """
827
+ message1 = {"x": 123}
828
+ message2 = {"y": None, "x": "abc"}
829
+ bytes_f = BytesIO()
830
+ destination = FileDestination(file=bytes_f)
831
+ destination(message1)
832
+ destination(message2)
833
+ self.assertEqual(
834
+ [pyjson.loads(line) for line in bytes_f.getvalue().splitlines()],
835
+ [message1, message2],
836
+ )
837
+
838
+ def test_filedestination_custom_encoder(self):
839
+ """
840
+ L{FileDestionation} can use a custom encoder.
841
+ """
842
+ custom = object()
843
+
844
+ class CustomEncoder(pyjson.JSONEncoder):
845
+ def default(self, o):
846
+ if o is custom:
847
+ return "CUSTOM!"
848
+ else:
849
+ return pyjson.JSONEncoder.default(self, o)
850
+
851
+ message = {"x": 123, "z": custom}
852
+ f = BytesIO()
853
+ destination = FileDestination(file=f, encoder=CustomEncoder)
854
+ destination(message)
855
+ self.assertEqual(
856
+ pyjson.loads(f.getvalue().splitlines()[0]), {"x": 123, "z": "CUSTOM!"}
857
+ )
858
+
859
+ def test_filedestination_custom_json_default(self):
860
+ """
861
+ L{FileDestination} accepts a custom JSON default callable.
862
+ """
863
+ custom = object()
864
+
865
+ def default(o):
866
+ if o is custom:
867
+ return "CUSTOM!"
868
+ else:
869
+ raise TypeError
870
+
871
+ message = {"x": 123, "z": custom}
872
+ f = BytesIO()
873
+ destination = FileDestination(file=f, json_default=default)
874
+ destination(message)
875
+ self.assertEqual(
876
+ pyjson.loads(f.getvalue().splitlines()[0]), {"x": 123, "z": "CUSTOM!"}
877
+ )
878
+
879
+ def test_filedestination_flushes(self):
880
+ """
881
+ L{FileDestination} flushes after every write, to ensure logs get
882
+ written out even if the local buffer hasn't filled up.
883
+ """
884
+ path = mktemp()
885
+ # File with large buffer:
886
+ f = open(path, "wb", 1024 * 1024 * 10)
887
+ # and a small message that won't fill the buffer:
888
+ message1 = {"x": 123}
889
+
890
+ destination = FileDestination(file=f)
891
+ destination(message1)
892
+
893
+ # Message got written even though buffer wasn't filled:
894
+ self.assertEqual(
895
+ [
896
+ pyjson.loads(line.decode("utf-8"))
897
+ for line in open(path, "rb").read().splitlines()
898
+ ],
899
+ [message1],
900
+ )
901
+
902
+ def test_filedestination_writes_json_unicode(self):
903
+ """
904
+ L{FileDestination} writes JSON-encoded messages to file that only
905
+ accepts Unicode.
906
+ """
907
+ message = {"x": "\u1234"}
908
+ unicode_f = StringIO()
909
+ destination = FileDestination(file=unicode_f)
910
+ destination(message)
911
+ self.assertEqual(pyjson.loads(unicode_f.getvalue()), message)
912
+
913
+ def test_filedestination_unwriteable_file(self):
914
+ """
915
+ L{FileDestination} raises a runtime error if the given file isn't writeable.
916
+ """
917
+ path = mktemp()
918
+ open(path, "w").close()
919
+ f = open(path, "r")
920
+ with self.assertRaises(RuntimeError):
921
+ FileDestination(f)