-
Notifications
You must be signed in to change notification settings - Fork 86
/
test_testresult.py
3077 lines (2599 loc) · 108 KB
/
test_testresult.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-2016 testtools developers. See LICENSE for details.
"""Test TestResults and related things."""
import codecs
import datetime
import doctest
import io
from itertools import chain
from itertools import combinations
import os
import platform
from queue import Queue
import re
import shutil
import sys
import tempfile
import threading
from unittest import TestSuite
from testtools import (
CopyStreamResult,
ExtendedToOriginalDecorator,
ExtendedToStreamDecorator,
MultiTestResult,
PlaceHolder,
ResourcedToStreamDecorator,
StreamFailFast,
StreamResult,
StreamResultRouter,
StreamSummary,
StreamTagger,
StreamToDict,
StreamToExtendedDecorator,
StreamToQueue,
Tagger,
TestCase,
TestControl,
TestResult,
TestResultDecorator,
TestByTestResult,
TextTestResult,
ThreadsafeForwardingResult,
TimestampingStreamResult,
testresult,
)
from testtools.compat import (
_b,
_get_exception_encoding,
)
from testtools.content import (
Content,
content_from_stream,
text_content,
TracebackContent,
)
from testtools.content_type import ContentType, UTF8_TEXT
from testtools.helpers import try_import
from testtools.matchers import (
AllMatch,
Contains,
DocTestMatches,
Equals,
HasLength,
MatchesAny,
MatchesException,
MatchesRegex,
Raises,
)
from testtools.tests.helpers import (
an_exc_info,
FullStackRunTest,
LoggingResult,
run_with_stack_hidden,
)
from testtools.testresult.doubles import (
Python26TestResult,
Python27TestResult,
ExtendedTestResult,
StreamResult as LoggingStreamResult,
TwistedTestResult,
)
from testtools.testresult.real import (
_details_to_str,
_merge_tags,
utc,
)
testresources = try_import('testresources')
def make_erroring_test():
class Test(TestCase):
def error(self):
a = 1 # noqa: F841
1/0
return Test("error")
def make_failing_test():
class Test(TestCase):
def failed(self):
self.fail("yo!")
return Test("failed")
def make_mismatching_test():
class Test(TestCase):
def mismatch(self):
self.assertEqual(1, 2)
return Test("mismatch")
def make_unexpectedly_successful_test():
class Test(TestCase):
def succeeded(self):
self.expectFailure("yo!", lambda: None)
return Test("succeeded")
def make_test():
class Test(TestCase):
def test(self):
pass
return Test("test")
def make_exception_info(exceptionFactory, *args, **kwargs):
try:
raise exceptionFactory(*args, **kwargs)
except BaseException:
return sys.exc_info()
class TestControlContract:
"""Stopping test runs."""
def test_initially_not_shouldStop(self):
# A result is not set to stop initially.
result = self.makeResult()
self.assertFalse(result.shouldStop)
def test_stop_sets_shouldStop(self):
# Calling 'stop()' sets 'shouldStop' to True.
result = self.makeResult()
result.stop()
self.assertTrue(result.shouldStop)
class Python26Contract(TestControlContract):
def test_fresh_result_is_successful(self):
# A result is considered successful before any tests are run.
result = self.makeResult()
self.assertTrue(result.wasSuccessful())
def test_addError_is_failure(self):
# addError fails the test run.
result = self.makeResult()
result.startTest(self)
result.addError(self, an_exc_info)
result.stopTest(self)
self.assertFalse(result.wasSuccessful())
def test_addFailure_is_failure(self):
# addFailure fails the test run.
result = self.makeResult()
result.startTest(self)
result.addFailure(self, an_exc_info)
result.stopTest(self)
self.assertFalse(result.wasSuccessful())
def test_addSuccess_is_success(self):
# addSuccess does not fail the test run.
result = self.makeResult()
result.startTest(self)
result.addSuccess(self)
result.stopTest(self)
self.assertTrue(result.wasSuccessful())
class Python27Contract(Python26Contract):
def test_addExpectedFailure(self):
# Calling addExpectedFailure(test, exc_info) completes ok.
result = self.makeResult()
result.startTest(self)
result.addExpectedFailure(self, an_exc_info)
def test_addExpectedFailure_is_success(self):
# addExpectedFailure does not fail the test run.
result = self.makeResult()
result.startTest(self)
result.addExpectedFailure(self, an_exc_info)
result.stopTest(self)
self.assertTrue(result.wasSuccessful())
def test_addSkipped(self):
# Calling addSkip(test, reason) completes ok.
result = self.makeResult()
result.startTest(self)
result.addSkip(self, "Skipped for some reason")
def test_addSkip_is_success(self):
# addSkip does not fail the test run.
result = self.makeResult()
result.startTest(self)
result.addSkip(self, "Skipped for some reason")
result.stopTest(self)
self.assertTrue(result.wasSuccessful())
def test_addUnexpectedSuccess(self):
# Calling addUnexpectedSuccess(test) completes ok.
result = self.makeResult()
result.startTest(self)
result.addUnexpectedSuccess(self)
def test_addUnexpectedSuccess_was_successful(self):
# addUnexpectedSuccess does not fail the test run in Python 2.7.
result = self.makeResult()
result.startTest(self)
result.addUnexpectedSuccess(self)
result.stopTest(self)
self.assertTrue(result.wasSuccessful())
def test_startStopTestRun(self):
# Calling startTestRun completes ok.
result = self.makeResult()
result.startTestRun()
result.stopTestRun()
def test_failfast(self):
result = self.makeResult()
result.failfast = True
class Failing(TestCase):
def test_a(self):
self.fail('a')
def test_b(self):
self.fail('b')
TestSuite([Failing('test_a'), Failing('test_b')]).run(result)
self.assertEqual(1, result.testsRun)
class TagsContract(Python27Contract):
"""Tests to ensure correct tagging behaviour.
See the subunit docs for guidelines on how this is supposed to work.
"""
def test_no_tags_by_default(self):
# Results initially have no tags.
result = self.makeResult()
result.startTestRun()
self.assertEqual(frozenset(), result.current_tags)
def test_adding_tags(self):
# Tags are added using 'tags' and thus become visible in
# 'current_tags'.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
self.assertEqual({'foo'}, result.current_tags)
def test_removing_tags(self):
# Tags are removed using 'tags'.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
result.tags(set(), {'foo'})
self.assertEqual(set(), result.current_tags)
def test_startTestRun_resets_tags(self):
# startTestRun makes a new test run, and thus clears all the tags.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
result.startTestRun()
self.assertEqual(set(), result.current_tags)
def test_add_tags_within_test(self):
# Tags can be added after a test has run.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
result.startTest(self)
result.tags({'bar'}, set())
self.assertEqual({'foo', 'bar'}, result.current_tags)
def test_tags_added_in_test_are_reverted(self):
# Tags added during a test run are then reverted once that test has
# finished.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
result.startTest(self)
result.tags({'bar'}, set())
result.addSuccess(self)
result.stopTest(self)
self.assertEqual({'foo'}, result.current_tags)
def test_tags_removed_in_test(self):
# Tags can be removed during tests.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
result.startTest(self)
result.tags(set(), {'foo'})
self.assertEqual(set(), result.current_tags)
def test_tags_removed_in_test_are_restored(self):
# Tags removed during tests are restored once that test has finished.
result = self.makeResult()
result.startTestRun()
result.tags({'foo'}, set())
result.startTest(self)
result.tags(set(), {'foo'})
result.addSuccess(self)
result.stopTest(self)
self.assertEqual({'foo'}, result.current_tags)
class DetailsContract(TagsContract):
"""Tests for the details API of TestResults."""
def test_addExpectedFailure_details(self):
# Calling addExpectedFailure(test, details=xxx) completes ok.
result = self.makeResult()
result.startTest(self)
result.addExpectedFailure(self, details={})
def test_addError_details(self):
# Calling addError(test, details=xxx) completes ok.
result = self.makeResult()
result.startTest(self)
result.addError(self, details={})
def test_addFailure_details(self):
# Calling addFailure(test, details=xxx) completes ok.
result = self.makeResult()
result.startTest(self)
result.addFailure(self, details={})
def test_addSkipped_details(self):
# Calling addSkip(test, reason) completes ok.
result = self.makeResult()
result.startTest(self)
result.addSkip(self, details={})
def test_addUnexpectedSuccess_details(self):
# Calling addUnexpectedSuccess(test) completes ok.
result = self.makeResult()
result.startTest(self)
result.addUnexpectedSuccess(self, details={})
def test_addSuccess_details(self):
# Calling addSuccess(test) completes ok.
result = self.makeResult()
result.startTest(self)
result.addSuccess(self, details={})
class FallbackContract(DetailsContract):
"""When we fallback we take our policy choice to map calls.
For instance, we map unexpectedSuccess to an error code, not to success.
"""
def test_addUnexpectedSuccess_was_successful(self):
# addUnexpectedSuccess fails test run in testtools.
result = self.makeResult()
result.startTest(self)
result.addUnexpectedSuccess(self)
result.stopTest(self)
self.assertFalse(result.wasSuccessful())
class StartTestRunContract(FallbackContract):
"""Defines the contract for testtools policy choices.
That is things which are not simply extensions to unittest but choices we
have made differently.
"""
def test_startTestRun_resets_unexpected_success(self):
result = self.makeResult()
result.startTest(self)
result.addUnexpectedSuccess(self)
result.stopTest(self)
result.startTestRun()
self.assertTrue(result.wasSuccessful())
def test_startTestRun_resets_failure(self):
result = self.makeResult()
result.startTest(self)
result.addFailure(self, an_exc_info)
result.stopTest(self)
result.startTestRun()
self.assertTrue(result.wasSuccessful())
def test_startTestRun_resets_errors(self):
result = self.makeResult()
result.startTest(self)
result.addError(self, an_exc_info)
result.stopTest(self)
result.startTestRun()
self.assertTrue(result.wasSuccessful())
class TestTestResultContract(TestCase, StartTestRunContract):
run_test_with = FullStackRunTest
def makeResult(self):
return TestResult()
class TestMultiTestResultContract(TestCase, StartTestRunContract):
run_test_with = FullStackRunTest
def makeResult(self):
return MultiTestResult(TestResult(), TestResult())
class TestTextTestResultContract(TestCase, StartTestRunContract):
run_test_with = FullStackRunTest
def makeResult(self):
return TextTestResult(io.StringIO())
class TestThreadSafeForwardingResultContract(TestCase, StartTestRunContract):
run_test_with = FullStackRunTest
def makeResult(self):
result_semaphore = threading.Semaphore(1)
target = TestResult()
return ThreadsafeForwardingResult(target, result_semaphore)
class TestExtendedTestResultContract(TestCase, StartTestRunContract):
def makeResult(self):
return ExtendedTestResult()
class TestPython26TestResultContract(TestCase, Python26Contract):
def makeResult(self):
return Python26TestResult()
class TestAdaptedPython26TestResultContract(TestCase, FallbackContract):
def makeResult(self):
return ExtendedToOriginalDecorator(Python26TestResult())
class TestPython27TestResultContract(TestCase, Python27Contract):
def makeResult(self):
return Python27TestResult()
class TestAdaptedPython27TestResultContract(TestCase, DetailsContract):
def makeResult(self):
return ExtendedToOriginalDecorator(Python27TestResult())
class TestAdaptedTwistedTestResultContract(TestCase, DetailsContract):
def makeResult(self):
return ExtendedToOriginalDecorator(TwistedTestResult())
class TestAdaptedStreamResult(TestCase, DetailsContract):
def makeResult(self):
return ExtendedToStreamDecorator(StreamResult())
class TestTestResultDecoratorContract(TestCase, StartTestRunContract):
run_test_with = FullStackRunTest
def makeResult(self):
return TestResultDecorator(TestResult())
# DetailsContract because ExtendedToStreamDecorator follows Python for
# uxsuccess handling.
class TestStreamToExtendedContract(TestCase, DetailsContract):
def makeResult(self):
return ExtendedToStreamDecorator(
StreamToExtendedDecorator(ExtendedTestResult()))
class TestStreamResultContract:
def _make_result(self):
raise NotImplementedError(self._make_result)
def test_startTestRun(self):
result = self._make_result()
result.startTestRun()
result.stopTestRun()
def test_files(self):
# Test parameter combinations when files are being emitted.
result = self._make_result()
result.startTestRun()
self.addCleanup(result.stopTestRun)
now = datetime.datetime.now(utc)
inputs = list(dict(
eof=True,
mime_type="text/plain",
route_code="1234",
test_id="foo",
timestamp=now,
).items())
param_dicts = self._power_set(inputs)
for kwargs in param_dicts:
result.status(file_name="foo", file_bytes=_b(""), **kwargs)
result.status(file_name="foo", file_bytes=_b("bar"), **kwargs)
def test_test_status(self):
# Tests non-file attachment parameter combinations.
result = self._make_result()
result.startTestRun()
self.addCleanup(result.stopTestRun)
now = datetime.datetime.now(utc)
args = [["foo", s] for s in [
'exists',
'inprogress',
'xfail',
'uxsuccess',
'success',
'fail',
'skip',
]]
inputs = list(dict(
runnable=False,
test_tags={'quux'},
route_code="1234",
timestamp=now,
).items())
param_dicts = self._power_set(inputs)
for kwargs in param_dicts:
for arg in args:
result.status(test_id=arg[0], test_status=arg[1], **kwargs)
def _power_set(self, iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
param_dicts = []
combos = (combinations(s, r) for r in range(len(s) + 1))
for ss in chain.from_iterable(combos):
param_dicts.append(dict(ss))
return param_dicts
class TestBaseStreamResultContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamResult()
class TestCopyStreamResultContract(TestCase, TestStreamResultContract):
def _make_result(self):
return CopyStreamResult([StreamResult(), StreamResult()])
class TestDoubleStreamResultContract(TestCase, TestStreamResultContract):
def _make_result(self):
return LoggingStreamResult()
class TestExtendedToStreamDecoratorContract(TestCase, TestStreamResultContract):
def _make_result(self):
return ExtendedToStreamDecorator(StreamResult())
class TestResourcedToStreamDecoratorContract(TestCase, TestStreamResultContract):
def _make_result(self):
return ResourcedToStreamDecorator(StreamResult())
class TestStreamSummaryResultContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamSummary()
class TestStreamTaggerContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamTagger([StreamResult()], add=set(), discard=set())
class TestStreamToDictContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamToDict(lambda x:None)
class TestStreamToExtendedDecoratorContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamToExtendedDecorator(ExtendedTestResult())
class TestStreamToQueueContract(TestCase, TestStreamResultContract):
def _make_result(self):
queue = Queue()
return StreamToQueue(queue, "foo")
class TestStreamFailFastContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamFailFast(lambda:None)
class TestStreamResultRouterContract(TestCase, TestStreamResultContract):
def _make_result(self):
return StreamResultRouter(StreamResult())
class TestDoubleStreamResultEvents(TestCase):
def test_startTestRun(self):
result = LoggingStreamResult()
result.startTestRun()
self.assertEqual([('startTestRun',)], result._events)
def test_stopTestRun(self):
result = LoggingStreamResult()
result.startTestRun()
result.stopTestRun()
self.assertEqual([('startTestRun',), ('stopTestRun',)], result._events)
def test_file(self):
result = LoggingStreamResult()
result.startTestRun()
now = datetime.datetime.now(utc)
result.status(file_name="foo", file_bytes="bar", eof=True, mime_type="text/json",
test_id="id", route_code='abc', timestamp=now)
self.assertEqual(
[('startTestRun',),
('status', 'id', None, None, True, 'foo', 'bar', True, 'text/json', 'abc', now)],
result._events)
def test_status(self):
result = LoggingStreamResult()
result.startTestRun()
now = datetime.datetime.now(utc)
result.status("foo", "success", test_tags={'tag'},
runnable=False, route_code='abc', timestamp=now)
self.assertEqual(
[('startTestRun',),
('status', 'foo', 'success', {'tag'}, False, None, None, False, None, 'abc', now)],
result._events)
class TestCopyStreamResultCopies(TestCase):
def setUp(self):
super().setUp()
self.target1 = LoggingStreamResult()
self.target2 = LoggingStreamResult()
self.targets = [self.target1._events, self.target2._events]
self.result = CopyStreamResult([self.target1, self.target2])
def test_startTestRun(self):
self.result.startTestRun()
self.assertThat(self.targets, AllMatch(Equals([('startTestRun',)])))
def test_stopTestRun(self):
self.result.startTestRun()
self.result.stopTestRun()
self.assertThat(self.targets,
AllMatch(Equals([('startTestRun',), ('stopTestRun',)])))
def test_status(self):
self.result.startTestRun()
now = datetime.datetime.now(utc)
self.result.status("foo", "success", test_tags={'tag'},
runnable=False, file_name="foo", file_bytes=b'bar', eof=True,
mime_type="text/json", route_code='abc', timestamp=now)
self.assertThat(self.targets,
AllMatch(Equals([('startTestRun',),
('status', 'foo', 'success', {'tag'}, False, "foo",
b'bar', True, "text/json", 'abc', now)
])))
class TestStreamTagger(TestCase):
def test_adding(self):
log = LoggingStreamResult()
result = StreamTagger([log], add=['foo'])
result.startTestRun()
result.status()
result.status(test_tags={'bar'})
result.status(test_tags=None)
result.stopTestRun()
self.assertEqual([
('startTestRun',),
('status', None, None, {'foo'}, True, None, None, False, None, None, None),
('status', None, None, {'foo', 'bar'}, True, None, None, False, None, None, None),
('status', None, None, {'foo'}, True, None, None, False, None, None, None),
('stopTestRun',),
], log._events)
def test_discarding(self):
log = LoggingStreamResult()
result = StreamTagger([log], discard=['foo'])
result.startTestRun()
result.status()
result.status(test_tags=None)
result.status(test_tags={'foo'})
result.status(test_tags={'bar'})
result.status(test_tags={'foo', 'bar'})
result.stopTestRun()
self.assertEqual([
('startTestRun',),
('status', None, None, None, True, None, None, False, None, None, None),
('status', None, None, None, True, None, None, False, None, None, None),
('status', None, None, None, True, None, None, False, None, None, None),
('status', None, None, {'bar'}, True, None, None, False, None, None, None),
('status', None, None, {'bar'}, True, None, None, False, None, None, None),
('stopTestRun',),
], log._events)
class TestStreamToDict(TestCase):
def test_hung_test(self):
tests = []
result = StreamToDict(tests.append)
result.startTestRun()
result.status('foo', 'inprogress')
self.assertEqual([], tests)
result.stopTestRun()
self.assertEqual([
{'id': 'foo', 'tags': set(), 'details': {}, 'status': 'inprogress',
'timestamps': [None, None]}
], tests)
def test_all_terminal_states_reported(self):
tests = []
result = StreamToDict(tests.append)
result.startTestRun()
result.status('success', 'success')
result.status('skip', 'skip')
result.status('exists', 'exists')
result.status('fail', 'fail')
result.status('xfail', 'xfail')
result.status('uxsuccess', 'uxsuccess')
self.assertThat(tests, HasLength(6))
self.assertEqual(
['success', 'skip', 'exists', 'fail', 'xfail', 'uxsuccess'],
[test['id'] for test in tests])
result.stopTestRun()
self.assertThat(tests, HasLength(6))
def test_files_reported(self):
tests = []
result = StreamToDict(tests.append)
result.startTestRun()
result.status(file_name="some log.txt",
file_bytes=_b("1234 log message"), eof=True,
mime_type="text/plain; charset=utf8", test_id="foo.bar")
result.status(file_name="another file",
file_bytes=_b("""Traceback..."""), test_id="foo.bar")
result.stopTestRun()
self.assertThat(tests, HasLength(1))
test = tests[0]
self.assertEqual("foo.bar", test['id'])
self.assertEqual("unknown", test['status'])
details = test['details']
self.assertEqual(
"1234 log message", details['some log.txt'].as_text())
self.assertEqual(
_b("Traceback..."),
_b('').join(details['another file'].iter_bytes()))
self.assertEqual(
"application/octet-stream", repr(details['another file'].content_type))
def test_bad_mime(self):
# Testtools was making bad mime types, this tests that the specific
# corruption is catered for.
tests = []
result = StreamToDict(tests.append)
result.startTestRun()
result.status(file_name="file", file_bytes=b'a',
mime_type='text/plain; charset=utf8, language=python',
test_id='id')
result.stopTestRun()
self.assertThat(tests, HasLength(1))
test = tests[0]
self.assertEqual("id", test['id'])
details = test['details']
self.assertEqual("a", details['file'].as_text())
self.assertEqual(
"text/plain; charset=\"utf8\"",
repr(details['file'].content_type))
def test_timestamps(self):
tests = []
result = StreamToDict(tests.append)
result.startTestRun()
result.status(test_id='foo', test_status='inprogress', timestamp="A")
result.status(test_id='foo', test_status='success', timestamp="B")
result.status(test_id='bar', test_status='inprogress', timestamp="C")
result.stopTestRun()
self.assertThat(tests, HasLength(2))
self.assertEqual(["A", "B"], tests[0]['timestamps'])
self.assertEqual(["C", None], tests[1]['timestamps'])
def test_files_skipped(self):
tests = []
result = StreamToDict(tests.append)
result.startTestRun()
result.status(file_name="some log.txt",
file_bytes="", eof=True,
mime_type="text/plain; charset=utf8", test_id="foo.bar")
result.stopTestRun()
self.assertThat(tests, HasLength(1))
details = tests[0]['details']
self.assertNotIn("some log.txt", details)
class TestExtendedToStreamDecorator(TestCase):
def test_explicit_time(self):
log = LoggingStreamResult()
result = ExtendedToStreamDecorator(log)
result.startTestRun()
now = datetime.datetime.now(utc)
result.time(now)
result.startTest(self)
result.addSuccess(self)
result.stopTest(self)
result.stopTestRun()
self.assertEqual([
('startTestRun',),
('status',
'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_explicit_time',
'inprogress',
None,
True,
None,
None,
False,
None,
None,
now),
('status',
'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_explicit_time',
'success',
set(),
True,
None,
None,
False,
None,
None,
now),
('stopTestRun',)], log._events)
def test_wasSuccessful_after_stopTestRun(self):
log = LoggingStreamResult()
result = ExtendedToStreamDecorator(log)
result.startTestRun()
result.status(test_id='foo', test_status='fail')
result.stopTestRun()
self.assertEqual(False, result.wasSuccessful())
def test_empty_detail_status_correct(self):
log = LoggingStreamResult()
result = ExtendedToStreamDecorator(log)
result.startTestRun()
now = datetime.datetime.now(utc)
result.time(now)
result.startTest(self)
result.addError(self, details={'foo': text_content("")})
result.stopTest(self)
result.stopTestRun()
self.assertEqual([
('startTestRun',),
('status',
'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_empty_detail_status_correct',
'inprogress',
None,
True,
None,
None,
False,
None,
None,
now),
('status',
'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_empty_detail_status_correct',
None,
None,
True,
'foo',
_b(''),
True,
'text/plain; charset="utf8"',
None,
now),
('status',
'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_empty_detail_status_correct',
'fail',
set(),
True,
None,
None,
False,
None,
None,
now),
('stopTestRun',)], log._events)
class TestResourcedToStreamDecorator(TestCase):
def setUp(self):
super().setUp()
if testresources is None:
self.skipTest('Need testresources')
def test_startMakeResource(self):
log = LoggingStreamResult()
result = ResourcedToStreamDecorator(log)
timestamp = datetime.datetime.utcfromtimestamp(3.476)
result.startTestRun()
result.time(timestamp)
resource = testresources.TestResourceManager()
result.startMakeResource(resource)
[_, event] = log._events
self.assertEqual(
'testresources.TestResourceManager.make', event.test_id)
self.assertEqual('inprogress', event.test_status)
self.assertFalse(event.runnable)
self.assertEqual(timestamp, event.timestamp)
def test_startMakeResource_with_custom_id_method(self):
log = LoggingStreamResult()
result = ResourcedToStreamDecorator(log)
resource = testresources.TestResourceManager()
resource.id = lambda: 'nice.resource'
result.startTestRun()
result.startMakeResource(resource)
self.assertEqual('nice.resource.make', log._events[1].test_id)
def test_stopMakeResource(self):
log = LoggingStreamResult()
result = ResourcedToStreamDecorator(log)
resource = testresources.TestResourceManager()
result.startTestRun()
result.stopMakeResource(resource)
[_, event] = log._events
self.assertEqual(
'testresources.TestResourceManager.make', event.test_id)
self.assertEqual('success', event.test_status)
def test_startCleanResource(self):
log = LoggingStreamResult()
result = ResourcedToStreamDecorator(log)
resource = testresources.TestResourceManager()
result.startTestRun()
result.startCleanResource(resource)
[_, event] = log._events
self.assertEqual(
'testresources.TestResourceManager.clean', event.test_id)
self.assertEqual('inprogress', event.test_status)
def test_stopCleanResource(self):
log = LoggingStreamResult()
result = ResourcedToStreamDecorator(log)
resource = testresources.TestResourceManager()
result.startTestRun()
result.stopCleanResource(resource)
[_, event] = log._events
self.assertEqual(
'testresources.TestResourceManager.clean', event.test_id)