-
Notifications
You must be signed in to change notification settings - Fork 86
/
real.py
2220 lines (1781 loc) · 73.8 KB
/
real.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2008-2015 testtools developers. See LICENSE for details.
"""Test results and related things."""
__all__ = [
"ExtendedToOriginalDecorator",
"ExtendedToStreamDecorator",
"MultiTestResult",
"ResourcedToStreamDecorator",
"StreamFailFast",
"StreamResult",
"StreamSummary",
"StreamTagger",
"StreamToDict",
"StreamToExtendedDecorator",
"StreamToQueue",
"Tagger",
"TestControl",
"TestResult",
"TestResultDecorator",
"ThreadsafeForwardingResult",
"TimestampingStreamResult",
]
import datetime
import email.message
import math
from operator import methodcaller
import sys
import unittest
import warnings
from testtools.compat import _b
from testtools.content import (
Content,
text_content,
TracebackContent,
)
from testtools.content_type import ContentType
from testtools.tags import TagContext
# circular import
# from testtools.testcase import PlaceHolder
PlaceHolder = None
# From http://docs.python.org/library/datetime.html
_ZERO = datetime.timedelta(0)
class UTC(datetime.tzinfo):
"""UTC"""
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
utc = UTC()
class TestResult(unittest.TestResult):
"""Subclass of unittest.TestResult extending the protocol for flexibility.
This test result supports an experimental protocol for providing additional
data to in test outcomes. All the outcome methods take an optional dict
'details'. If supplied any other detail parameters like 'err' or 'reason'
should not be provided. The details dict is a mapping from names to
MIME content objects (see testtools.content). This permits attaching
tracebacks, log files, or even large objects like databases that were
part of the test fixture. Until this API is accepted into upstream
Python it is considered experimental: it may be replaced at any point
by a newer version more in line with upstream Python. Compatibility would
be aimed for in this case, but may not be possible.
:ivar skip_reasons: A dict of skip-reasons -> list of tests. See addSkip.
"""
def __init__(self, failfast=False, tb_locals=False):
# startTestRun resets all attributes, and older clients don't know to
# call startTestRun, so it is called once here.
# Because subclasses may reasonably not expect this, we call the
# specific version we want to run.
self.failfast = failfast
self.tb_locals = tb_locals
TestResult.startTestRun(self)
def addExpectedFailure(self, test, err=None, details=None):
"""Called when a test has failed in an expected manner.
Like with addSuccess and addError, testStopped should still be called.
:param test: The test that has been skipped.
:param err: The exc_info of the error that was raised.
:return: None
"""
# This is the python 2.7 implementation
self.expectedFailures.append(
(test, self._err_details_to_string(test, err, details))
)
def addError(self, test, err=None, details=None):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
:param details: Alternative way to supply details about the outcome.
see the class docstring for more information.
"""
self.errors.append((test, self._err_details_to_string(test, err, details)))
if self.failfast:
self.stop()
def addFailure(self, test, err=None, details=None):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
:param details: Alternative way to supply details about the outcome.
see the class docstring for more information.
"""
self.failures.append((test, self._err_details_to_string(test, err, details)))
if self.failfast:
self.stop()
def addSkip(self, test, reason=None, details=None):
"""Called when a test has been skipped rather than running.
Like with addSuccess and addError, testStopped should still be called.
This must be called by the TestCase. 'addError' and 'addFailure' will
not call addSkip, since they have no assumptions about the kind of
errors that a test can raise.
:param test: The test that has been skipped.
:param reason: The reason for the test being skipped. For instance,
u"pyGL is not available".
:param details: Alternative way to supply details about the outcome.
see the class docstring for more information.
:return: None
"""
if reason is None:
reason = details.get("reason")
if reason is None:
reason = "No reason given"
else:
reason = reason.as_text()
skip_list = self.skip_reasons.setdefault(reason, [])
skip_list.append(test)
def addSuccess(self, test, details=None):
"""Called when a test succeeded."""
def addUnexpectedSuccess(self, test, details=None):
"""Called when a test was expected to fail, but succeed."""
self.unexpectedSuccesses.append(test)
if self.failfast:
self.stop()
def wasSuccessful(self):
"""Has this result been successful so far?
If there have been any errors, failures or unexpected successes,
return False. Otherwise, return True.
Note: This differs from standard unittest in that we consider
unexpected successes to be equivalent to failures, rather than
successes.
"""
return not (self.errors or self.failures or self.unexpectedSuccesses)
def _err_details_to_string(self, test, err=None, details=None):
"""Convert an error in exc_info form or a contents dict to a string."""
if err is not None:
return TracebackContent(err, test, capture_locals=self.tb_locals).as_text()
return _details_to_str(details, special="traceback")
def _exc_info_to_unicode(self, err, test):
# Deprecated. Only present because subunit upcalls to it. See
# <https://bugs.launchpad.net/testtools/+bug/929063>.
return TracebackContent(err, test).as_text()
def _now(self):
"""Return the current 'test time'.
If the time() method has not been called, this is equivalent to
datetime.now(), otherwise its the last supplied datestamp given to the
time() method.
"""
if self.__now is None:
return datetime.datetime.now(utc)
else:
return self.__now
def startTestRun(self):
"""Called before a test run starts.
New in Python 2.7. The testtools version resets the result to a
pristine condition ready for use in another test run. Note that this
is different from Python 2.7's startTestRun, which does nothing.
"""
# failfast and tb_locals are reset by the super __init__, so save them.
failfast = self.failfast
tb_locals = self.tb_locals
super().__init__()
self.skip_reasons = {}
self.__now = None
self._tags = TagContext()
# -- Start: As per python 2.7 --
self.expectedFailures = []
self.unexpectedSuccesses = []
self.failfast = failfast
# -- End: As per python 2.7 --
# -- Python 3.5
self.tb_locals = tb_locals
def stopTestRun(self):
"""Called after a test run completes
New in python 2.7
"""
def startTest(self, test):
super().startTest(test)
self._tags = TagContext(self._tags)
def stopTest(self, test):
# NOTE: In Python 3.12.1 skipped tests may not call startTest()
if self._tags is not None:
self._tags = self._tags.parent
super().stopTest(test)
@property
def current_tags(self):
"""The currently set tags."""
return self._tags.get_current_tags()
def tags(self, new_tags, gone_tags):
"""Add and remove tags from the test.
:param new_tags: A set of tags to be added to the stream.
:param gone_tags: A set of tags to be removed from the stream.
"""
self._tags.change_tags(new_tags, gone_tags)
def time(self, a_datetime):
"""Provide a timestamp to represent the current time.
This is useful when test activity is time delayed, or happening
concurrently and getting the system time between API calls will not
accurately represent the duration of tests (or the whole run).
Calling time() sets the datetime used by the TestResult object.
Time is permitted to go backwards when using this call.
:param a_datetime: A datetime.datetime object with TZ information or
None to reset the TestResult to gathering time from the system.
"""
self.__now = a_datetime
def done(self):
"""Called when the test runner is done.
deprecated in favour of stopTestRun.
"""
"""Interim states:
* None - no particular status is being reported, or status being reported is
not associated with a test (e.g. when reporting on stdout / stderr chatter).
* inprogress - the test is currently running. Emitted by tests when they start
running and at any intermediary point they might choose to indicate their
continual operation.
"""
INTERIM_STATES = frozenset([None, "inprogress"])
"""Final states:
* exists - the test exists. This is used when a test is not being executed.
Typically this is when querying what tests could be run in a test run (which
is useful for selecting tests to run).
* xfail - the test failed but that was expected. This is purely informative -
the test is not considered to be a failure.
* uxsuccess - the test passed but was expected to fail. The test will be
considered a failure.
* success - the test has finished without error.
* fail - the test failed (or errored). The test will be considered a failure.
* skip - the test was selected to run but chose to be skipped. e.g. a test
dependency was missing. This is purely informative: the test is not
considered to be a failure.
* unknown - we don't know what state the test is in
"""
FINAL_STATES = frozenset(
["exists", "xfail", "uxsuccess", "success", "fail", "skip", "unknown"]
)
STATES = INTERIM_STATES | FINAL_STATES
class StreamResult:
"""A test result for reporting the activity of a test run.
Typical use
>>> result = StreamResult()
>>> result.startTestRun()
>>> try:
... case.run(result)
... finally:
... result.stopTestRun()
The case object will be either a TestCase or a TestSuite, and
generally make a sequence of calls like::
>>> result.status(self.id(), 'inprogress')
>>> result.status(self.id(), 'success')
General concepts
StreamResult is built to process events that are emitted by tests during a
test run or test enumeration. The test run may be running concurrently, and
even be spread out across multiple machines.
All events are timestamped to prevent network buffering or scheduling
latency causing false timing reports. Timestamps are datetime objects in
the UTC timezone.
A route_code is a unicode string that identifies where a particular test
run. This is optional in the API but very useful when multiplexing multiple
streams together as it allows identification of interactions between tests
that were run on the same hardware or in the same test process. Generally
actual tests never need to bother with this - it is added and processed
by StreamResult's that do multiplexing / run analysis. route_codes are
also used to route stdin back to pdb instances.
The StreamResult base class does no accounting or processing, rather it
just provides an empty implementation of every method, suitable for use
as a base class regardless of intent.
"""
def startTestRun(self):
"""Start a test run.
This will prepare the test result to process results (which might imply
connecting to a database or remote machine).
"""
def stopTestRun(self):
"""Stop a test run.
This informs the result that no more test updates will be received. At
this point any test ids that have started and not completed can be
considered failed-or-hung.
"""
def status(
self,
test_id=None,
test_status=None,
test_tags=None,
runnable=True,
file_name=None,
file_bytes=None,
eof=False,
mime_type=None,
route_code=None,
timestamp=None,
):
"""Inform the result about a test status.
:param test_id: The test whose status is being reported. None to
report status about the test run as a whole.
:param test_status: The status for the test. There are two sorts of
status - interim and final status events. As many interim events
can be generated as desired, but only one final event. After a
final status event any further file or status events from the
same test_id+route_code may be discarded or associated with a new
test by the StreamResult. (But no exception will be thrown).
Interim states:
* None - no particular status is being reported, or status being
reported is not associated with a test (e.g. when reporting on
stdout / stderr chatter).
* inprogress - the test is currently running. Emitted by tests
when they start running and at any intermediary point they
might choose to indicate their continual operation.
Final states:
* exists - the test exists. This is used when a test is not being
executed. Typically this is when querying what tests could be
run in a test run (which is useful for selecting tests to run).
* xfail - the test failed but that was expected. This is purely
informative - the test is not considered to be a failure.
* uxsuccess - the test passed but was expected to fail. The test
will be considered a failure.
* success - the test has finished without error.
* fail - the test failed (or errored). The test will be
considered a failure.
* skip - the test was selected to run but chose to be skipped.
e.g. a test dependency was missing. This is purely informative-
the test is not considered to be a failure.
:param test_tags: Optional set of tags to apply to the test. Tags
have no intrinsic meaning - that is up to the test author.
:param runnable: Allows status reports to mark that they are for
tests which are not able to be explicitly run. For instance,
subtests will report themselves as non-runnable.
:param file_name: The name for the file_bytes. Any unicode string may
be used. While there is no semantic value attached to the name
of any attachment, the names 'stdout' and 'stderr' and 'traceback'
are recommended for use only for output sent to stdout, stderr and
tracebacks of exceptions. When file_name is supplied, file_bytes
must be a bytes instance.
:param file_bytes: A bytes object containing content for the named
file. This can just be a single chunk of the file - emitting
another file event with more later. Must be None unleses a
file_name is supplied.
:param eof: True if this chunk is the last chunk of the file, any
additional chunks with the same name should be treated as an error
and discarded. Ignored unless file_name has been supplied.
:param mime_type: An optional MIME type for the file. stdout and
stderr will generally be "text/plain; charset=utf8". If None,
defaults to application/octet-stream. Ignored unless file_name
has been supplied.
"""
def domap(function, *sequences):
"""A strict version of 'map' that's guaranteed to run on all inputs.
DEPRECATED since testtools 1.8.1: Internal code should use _strict_map.
External code should look for other solutions for their strict mapping
needs.
"""
warnings.warn(
"domap deprecated since 1.8.1. Please implement your own strict map.",
DeprecationWarning,
stacklevel=2,
)
return _strict_map(function, *sequences)
def _strict_map(function, *sequences):
return list(map(function, *sequences))
class CopyStreamResult(StreamResult):
"""Copies all event it receives to multiple results.
This provides an easy facility for combining multiple StreamResults.
For TestResult the equivalent class was ``MultiTestResult``.
"""
def __init__(self, targets):
super().__init__()
self.targets = targets
def startTestRun(self):
super().startTestRun()
_strict_map(methodcaller("startTestRun"), self.targets)
def stopTestRun(self):
super().stopTestRun()
_strict_map(methodcaller("stopTestRun"), self.targets)
def status(self, *args, **kwargs):
super().status(*args, **kwargs)
_strict_map(methodcaller("status", *args, **kwargs), self.targets)
class StreamFailFast(StreamResult):
"""Call the supplied callback if an error is seen in a stream.
An example callback::
def do_something():
pass
"""
def __init__(self, on_error):
self.on_error = on_error
def status(
self,
test_id=None,
test_status=None,
test_tags=None,
runnable=True,
file_name=None,
file_bytes=None,
eof=False,
mime_type=None,
route_code=None,
timestamp=None,
):
if test_status in ("uxsuccess", "fail"):
self.on_error()
class StreamResultRouter(StreamResult):
"""A StreamResult that routes events.
StreamResultRouter forwards received events to another StreamResult object,
selected by a dynamic forwarding policy. Events where no destination is
found are forwarded to the fallback StreamResult, or an error is raised.
Typical use is to construct a router with a fallback and then either
create up front mapping rules, or create them as-needed from the fallback
handler::
>>> router = StreamResultRouter()
>>> sink = doubles.StreamResult()
>>> router.add_rule(sink, 'route_code_prefix', route_prefix='0',
... consume_route=True)
>>> router.status(
... test_id='foo', route_code='0/1', test_status='uxsuccess')
StreamResultRouter has no buffering.
When adding routes (and for the fallback) whether to call startTestRun and
stopTestRun or to not call them is controllable by passing
'do_start_stop_run'. The default is to call them for the fallback only.
If a route is added after startTestRun has been called, and
do_start_stop_run is True then startTestRun is called immediately on the
new route sink.
There is no a-priori defined lookup order for routes: if they are ambiguous
the behaviour is undefined. Only a single route is chosen for any event.
"""
_policies = {}
def __init__(self, fallback=None, do_start_stop_run=True):
"""Construct a StreamResultRouter with optional fallback.
:param fallback: A StreamResult to forward events to when no route
exists for them.
:param do_start_stop_run: If False do not pass startTestRun and
stopTestRun onto the fallback.
"""
self.fallback = fallback
self._route_code_prefixes = {}
self._test_ids = {}
# Records sinks that should have do_start_stop_run called on them.
self._sinks = []
if do_start_stop_run and fallback:
self._sinks.append(fallback)
self._in_run = False
def startTestRun(self):
super().startTestRun()
for sink in self._sinks:
sink.startTestRun()
self._in_run = True
def stopTestRun(self):
super().stopTestRun()
for sink in self._sinks:
sink.stopTestRun()
self._in_run = False
def status(self, **kwargs):
route_code = kwargs.get("route_code", None)
test_id = kwargs.get("test_id", None)
if route_code is not None:
prefix = route_code.split("/")[0]
else:
prefix = route_code
if prefix in self._route_code_prefixes:
target, consume_route = self._route_code_prefixes[prefix]
if route_code is not None and consume_route:
route_code = route_code[len(prefix) + 1 :]
if not route_code:
route_code = None
kwargs["route_code"] = route_code
elif test_id in self._test_ids:
target = self._test_ids[test_id]
else:
target = self.fallback
target.status(**kwargs)
def add_rule(self, sink, policy, do_start_stop_run=False, **policy_args):
"""Add a rule to route events to sink when they match a given policy.
:param sink: A StreamResult to receive events.
:param policy: A routing policy. Valid policies are
'route_code_prefix' and 'test_id'.
:param do_start_stop_run: If True then startTestRun and stopTestRun
events will be passed onto this sink.
:raises: ValueError if the policy is unknown
:raises: TypeError if the policy is given arguments it cannot handle.
``route_code_prefix`` routes events based on a prefix of the route
code in the event. It takes a ``route_prefix`` argument to match on
(e.g. '0') and a ``consume_route`` argument, which, if True, removes
the prefix from the ``route_code`` when forwarding events.
``test_id`` routes events based on the test id. It takes a single
argument, ``test_id``. Use ``None`` to select non-test events.
"""
policy_method = StreamResultRouter._policies.get(policy, None)
if not policy_method:
raise ValueError(f"bad policy {policy!r}")
policy_method(self, sink, **policy_args)
if do_start_stop_run:
self._sinks.append(sink)
if self._in_run:
sink.startTestRun()
def _map_route_code_prefix(self, sink, route_prefix, consume_route=False):
if "/" in route_prefix:
raise TypeError(f"{route_prefix!r} is more than one route step long")
self._route_code_prefixes[route_prefix] = (sink, consume_route)
_policies["route_code_prefix"] = _map_route_code_prefix
def _map_test_id(self, sink, test_id):
self._test_ids[test_id] = sink
_policies["test_id"] = _map_test_id
class StreamTagger(CopyStreamResult):
"""Adds or discards tags from StreamResult events."""
def __init__(self, targets, add=None, discard=None):
"""Create a StreamTagger.
:param targets: A list of targets to forward events onto.
:param add: Either None or an iterable of tags to add to each event.
:param discard: Either None or an iterable of tags to discard from each
event.
"""
super().__init__(targets)
self.add = frozenset(add or ())
self.discard = frozenset(discard or ())
def status(self, *args, **kwargs):
test_tags = kwargs.get("test_tags") or set()
test_tags.update(self.add)
test_tags.difference_update(self.discard)
kwargs["test_tags"] = test_tags or None
super().status(*args, **kwargs)
class _TestRecord:
"""Representation of a test."""
def __init__(self, id, tags, details, status, timestamps):
# The test id.
self.id = id
# Tags for the test.
self.tags = tags
# File attachments.
self.details = details
# One of the StreamResult status codes.
self.status = status
# Pair of timestamps (x, y).
# x is the first timestamp we received for this test, y is the one that
# triggered the notification. y can be None if the test hanged.
self.timestamps = timestamps
@classmethod
def create(cls, test_id, timestamp):
return cls(
id=test_id,
tags=set(),
details={},
status="unknown",
timestamps=(timestamp, None),
)
def set(self, *args, **kwargs):
if args:
setattr(self, args[0], args[1])
for key, value in kwargs.items():
setattr(self, key, value)
return self
def transform(self, data, value):
getattr(self, data[0])[data[1]] = value
return self
def to_dict(self):
"""Convert record into a "test dict".
A "test dict" is a concept used in other parts of the code-base. It
has the following keys:
* id: the test id.
* tags: The tags for the test. A set of unicode strings.
* details: A dict of file attachments - ``testtools.content.Content``
objects.
* status: One of the StreamResult status codes (including inprogress)
or 'unknown' (used if only file events for a test were received...)
* timestamps: A pair of timestamps - the first one received with this
test id, and the one in the event that triggered the notification.
Hung tests have a None for the second end event. Timestamps are not
compared - their ordering is purely order received in the stream.
"""
return {
"id": self.id,
"tags": self.tags,
"details": self.details,
"status": self.status,
"timestamps": list(self.timestamps),
}
def got_timestamp(self, timestamp):
"""Called when we receive a timestamp.
This will always update the second element of the 'timestamps' tuple.
It doesn't compare timestamps at all.
"""
return self.set(timestamps=(self.timestamps[0], timestamp))
def got_file(self, file_name, file_bytes, mime_type=None):
"""Called when we receive file information.
``mime_type`` is only used when this is the first time we've seen data
from this file.
"""
if file_name in self.details:
case = self
else:
content_type = _make_content_type(mime_type)
content_bytes = []
case = self.transform(
["details", file_name], Content(content_type, lambda: content_bytes)
)
case.details[file_name].iter_bytes().append(file_bytes)
return case
def to_test_case(self):
"""Convert into a TestCase object.
:return: A PlaceHolder test object.
"""
# Circular import.
global PlaceHolder
if PlaceHolder is None:
from testtools.testcase import PlaceHolder
outcome = _status_map[self.status]
return PlaceHolder(
self.id,
outcome=outcome,
details=self.details,
tags=self.tags,
timestamps=self.timestamps,
)
def _make_content_type(mime_type=None):
"""Return ContentType for a given mime type.
testtools was emitting a bad encoding, and this works around it.
Unfortunately, is also loses data - probably want to drop this in a few
releases.
Based on mimeparse.py by Joe Gregorio (MIT License).
https://github.com/conneg/mimeparse/blob/master/mimeparse.py
"""
# XXX: Not sure what release this was added, so "in a few releases" is
# unactionable.
if mime_type is None:
mime_type = "application/octet-stream"
msg = email.message.EmailMessage()
msg["content-type"] = mime_type
full_type, parameters = msg.get_content_type(), dict(msg["content-type"].params)
# Ensure any wildcards are valid.
if full_type == "*":
full_type = "*/*"
type_parts = full_type.split("/") if "/" in full_type else None
if not type_parts or len(type_parts) > 2:
raise Exception("Can't parse type '%s'" % full_type)
primary_type, sub_type = type_parts
primary_type = primary_type.strip()
sub_type = sub_type.strip()
if "charset" in parameters:
if "," in parameters["charset"]:
parameters["charset"] = parameters["charset"][
: parameters["charset"].find(",")
]
return ContentType(primary_type, sub_type, parameters)
_status_map = {
"inprogress": "addFailure",
"unknown": "addFailure",
"success": "addSuccess",
"skip": "addSkip",
"fail": "addFailure",
"xfail": "addExpectedFailure",
"uxsuccess": "addUnexpectedSuccess",
}
class _StreamToTestRecord(StreamResult):
"""A specialised StreamResult that emits a callback as tests complete.
Top level file attachments are simply discarded. Hung tests are detected
by stopTestRun and notified there and then.
The callback is passed a ``_TestRecord`` object.
Only the most recent tags observed in the stream are reported.
"""
def __init__(self, on_test):
"""Create a _StreamToTestRecord calling on_test on test completions.
:param on_test: A callback that accepts one parameter:
a ``_TestRecord`` object describing a test.
"""
super().__init__()
self.on_test = on_test
def startTestRun(self):
super().startTestRun()
self._inprogress = {}
def status(
self,
test_id=None,
test_status=None,
test_tags=None,
runnable=True,
file_name=None,
file_bytes=None,
eof=False,
mime_type=None,
route_code=None,
timestamp=None,
):
super().status(
test_id,
test_status,
test_tags=test_tags,
runnable=runnable,
file_name=file_name,
file_bytes=file_bytes,
eof=eof,
mime_type=mime_type,
route_code=route_code,
timestamp=timestamp,
)
key = self._ensure_key(test_id, route_code, timestamp)
if not key:
return
# update fields
self._inprogress[key] = self._update_case(
self._inprogress[key],
test_status,
test_tags,
file_name,
file_bytes,
mime_type,
timestamp,
)
# notify completed tests.
if test_status not in INTERIM_STATES:
self.on_test(self._inprogress.pop(key))
def _update_case(
self,
case,
test_status=None,
test_tags=None,
file_name=None,
file_bytes=None,
mime_type=None,
timestamp=None,
):
if test_status is not None:
case = case.set(status=test_status)
case = case.got_timestamp(timestamp)
if file_name is not None and file_bytes:
case = case.got_file(file_name, file_bytes, mime_type)
if test_tags is not None:
case = case.set("tags", test_tags)
return case
def stopTestRun(self):
super().stopTestRun()
while self._inprogress:
case = self._inprogress.popitem()[1]
self.on_test(case.got_timestamp(None))
def _ensure_key(self, test_id, route_code, timestamp):
if test_id is None:
return
key = (test_id, route_code)
if key not in self._inprogress:
self._inprogress[key] = _TestRecord.create(test_id, timestamp)
return key
class StreamToDict(StreamResult):
"""A specialised StreamResult that emits a callback as tests complete.
Top level file attachments are simply discarded. Hung tests are detected
by stopTestRun and notified there and then.
The callback is passed a dict with the following keys:
* id: the test id.
* tags: The tags for the test. A set of unicode strings.
* details: A dict of file attachments - ``testtools.content.Content``
objects.
* status: One of the StreamResult status codes (including inprogress) or
'unknown' (used if only file events for a test were received...)
* timestamps: A pair of timestamps - the first one received with this
test id, and the one in the event that triggered the notification.
Hung tests have a None for the second end event. Timestamps are not
compared - their ordering is purely order received in the stream.
Only the most recent tags observed in the stream are reported.
"""
# XXX: This could actually be replaced by a very simple function.
# Unfortunately, subclassing is a supported API.
# XXX: Alternative simplification is to extract a StreamAdapter base
# class, and have this inherit from that.
def __init__(self, on_test):
"""Create a _StreamToTestRecord calling on_test on test completions.
:param on_test: A callback that accepts one parameter:
a dictionary describing a test.
"""
super().__init__()
self._hook = _StreamToTestRecord(self._handle_test)
# XXX: Not clear whether its part of the supported interface for
# self.on_test to be the passed-in on_test. If not, we could reduce
# the boilerplate by subclassing _StreamToTestRecord.
self.on_test = on_test
def _handle_test(self, test_record):
self.on_test(test_record.to_dict())
def startTestRun(self):
super().startTestRun()
self._hook.startTestRun()
def status(self, *args, **kwargs):
super().status(*args, **kwargs)
self._hook.status(*args, **kwargs)
def stopTestRun(self):
super().stopTestRun()
self._hook.stopTestRun()
def test_dict_to_case(test_dict):
"""Convert a test dict into a TestCase object.
:param test_dict: A test dict as generated by StreamToDict.
:return: A PlaceHolder test object.
"""
return _TestRecord(
id=test_dict["id"],
tags=test_dict["tags"],
details=test_dict["details"],
status=test_dict["status"],
timestamps=tuple(test_dict["timestamps"]),
).to_test_case()