summaryrefslogtreecommitdiffstats
path: root/testing/mozbase/mozlog/tests/test_formatters.py
blob: 5192f97b212d78c9171f6d2c005c1bd8d0156f06 (plain)
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
# encoding: utf-8

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from __future__ import absolute_import, print_function, unicode_literals

import json
import os
import signal
import time
import unittest
import xml.etree.ElementTree as ET
from textwrap import dedent

import mozunit
import pytest
from six import StringIO, ensure_text, unichr

from mozlog.structuredlog import StructuredLogger
from mozlog.formatters import (
    MachFormatter,
    TbplFormatter,
    HTMLFormatter,
    XUnitFormatter,
    GroupingFormatter,
    ErrorSummaryFormatter,
)
from mozlog.handlers import StreamHandler

formatters = {
    "mach": MachFormatter,
    "errorsummary": ErrorSummaryFormatter,
}

FORMATS = {
    # A list of tuples consisting of (name, options, expected string).
    "PASS": [
        (
            "mach",
            {},
            dedent(
                """
             0:00.00 SUITE_START: running 3 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: OK
             0:00.00 TEST_START: test_bar
             0:00.00 TEST_END: Test OK. Subtests passed 1/1. Unexpected 0
             0:00.00 TEST_START: test_baz
             0:00.00 TEST_END: FAIL
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 4 checks (1 subtests, 3 tests)
            Expected results: 4
            Unexpected results: 0
            OK
            """
            ).lstrip("\n"),
        ),
        (
            "mach",
            {"verbose": True},
            dedent(
                """
             0:00.00 SUITE_START: running 3 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: OK
             0:00.00 TEST_START: test_bar
             0:00.00 PASS a subtest
             0:00.00 TEST_END: Test OK. Subtests passed 1/1. Unexpected 0
             0:00.00 TEST_START: test_baz
             0:00.00 TEST_END: FAIL
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 4 checks (1 subtests, 3 tests)
            Expected results: 4
            Unexpected results: 0
            OK
            """
            ).lstrip("\n"),
        ),
    ],
    "FAIL": [
        (
            "mach",
            {},
            dedent(
                """
             0:00.00 SUITE_START: running 3 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: FAIL, expected PASS - expected 0 got 1
             0:00.00 TEST_START: test_bar
             0:00.00 TEST_END: Test OK. Subtests passed 0/2. Unexpected 2
            FAIL a subtest - expected 0 got 1
                SimpleTest.is@SimpleTest/SimpleTest.js:312:5
                @caps/tests/mochitest/test_bug246699.html:53:1
            TIMEOUT another subtest
             0:00.00 TEST_START: test_baz
             0:00.00 TEST_END: PASS, expected FAIL
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 5 checks (2 subtests, 3 tests)
            Expected results: 1
            Unexpected results: 4
              test: 2 (1 fail, 1 pass)
              subtest: 2 (1 fail, 1 timeout)

            Unexpected Results
            ------------------
            test_foo
              FAIL test_foo - expected 0 got 1
            test_bar
              FAIL a subtest - expected 0 got 1
                SimpleTest.is@SimpleTest/SimpleTest.js:312:5
                @caps/tests/mochitest/test_bug246699.html:53:1
              TIMEOUT another subtest
            test_baz
              UNEXPECTED-PASS test_baz
            """
            ).lstrip("\n"),
        ),
        (
            "mach",
            {"verbose": True},
            dedent(
                """
             0:00.00 SUITE_START: running 3 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: FAIL, expected PASS - expected 0 got 1
             0:00.00 TEST_START: test_bar
             0:00.00 FAIL a subtest - expected 0 got 1
                SimpleTest.is@SimpleTest/SimpleTest.js:312:5
                @caps/tests/mochitest/test_bug246699.html:53:1
             0:00.00 TIMEOUT another subtest
             0:00.00 TEST_END: Test OK. Subtests passed 0/2. Unexpected 2
             0:00.00 TEST_START: test_baz
             0:00.00 TEST_END: PASS, expected FAIL
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 5 checks (2 subtests, 3 tests)
            Expected results: 1
            Unexpected results: 4
              test: 2 (1 fail, 1 pass)
              subtest: 2 (1 fail, 1 timeout)

            Unexpected Results
            ------------------
            test_foo
              FAIL test_foo - expected 0 got 1
            test_bar
              FAIL a subtest - expected 0 got 1
                SimpleTest.is@SimpleTest/SimpleTest.js:312:5
                @caps/tests/mochitest/test_bug246699.html:53:1
              TIMEOUT another subtest
            test_baz
              UNEXPECTED-PASS test_baz
            """
            ).lstrip("\n"),
        ),
    ],
    "PRECONDITION_FAILED": [
        (
            "mach",
            {},
            dedent(
                """
             0:00.00 SUITE_START: running 2 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: PRECONDITION_FAILED, expected OK
             0:00.00 TEST_START: test_bar
             0:00.00 TEST_END: Test OK. Subtests passed 1/2. Unexpected 1
            PRECONDITION_FAILED another subtest
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 4 checks (2 subtests, 2 tests)
            Expected results: 2
            Unexpected results: 2
              test: 1 (1 precondition_failed)
              subtest: 1 (1 precondition_failed)

            Unexpected Results
            ------------------
            test_foo
              PRECONDITION_FAILED test_foo
            test_bar
              PRECONDITION_FAILED another subtest
            """
            ).lstrip("\n"),
        ),
        (
            "mach",
            {"verbose": True},
            dedent(
                """
             0:00.00 SUITE_START: running 2 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: PRECONDITION_FAILED, expected OK
             0:00.00 TEST_START: test_bar
             0:00.00 PASS a subtest
             0:00.00 PRECONDITION_FAILED another subtest
             0:00.00 TEST_END: Test OK. Subtests passed 1/2. Unexpected 1
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 4 checks (2 subtests, 2 tests)
            Expected results: 2
            Unexpected results: 2
              test: 1 (1 precondition_failed)
              subtest: 1 (1 precondition_failed)

            Unexpected Results
            ------------------
            test_foo
              PRECONDITION_FAILED test_foo
            test_bar
              PRECONDITION_FAILED another subtest
            """
            ).lstrip("\n"),
        ),
    ],
    "KNOWN-INTERMITTENT": [
        (
            "mach",
            {},
            dedent(
                """
             0:00.00 SUITE_START: running 3 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: FAIL
            KNOWN-INTERMITTENT-FAIL test_foo
             0:00.00 TEST_START: test_bar
             0:00.00 TEST_END: Test OK. Subtests passed 1/1. Unexpected 0
            KNOWN-INTERMITTENT-PASS a subtest
             0:00.00 TEST_START: test_baz
             0:00.00 TEST_END: FAIL
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 4 checks (1 subtests, 3 tests)
            Expected results: 4 (2 known intermittents)
            Unexpected results: 0

            Known Intermittent Results
            --------------------------
            test_foo
              KNOWN-INTERMITTENT-FAIL test_foo
            test_bar
              KNOWN-INTERMITTENT-PASS a subtest
            OK
            """
            ).lstrip("\n"),
        ),
        (
            "mach",
            {"verbose": True},
            dedent(
                """
             0:00.00 SUITE_START: running 3 tests
             0:00.00 TEST_START: test_foo
             0:00.00 TEST_END: FAIL
            KNOWN-INTERMITTENT-FAIL test_foo
             0:00.00 TEST_START: test_bar
             0:00.00 KNOWN-INTERMITTENT-PASS a subtest
             0:00.00 TEST_END: Test OK. Subtests passed 1/1. Unexpected 0
            KNOWN-INTERMITTENT-PASS a subtest
             0:00.00 TEST_START: test_baz
             0:00.00 TEST_END: FAIL
             0:00.00 SUITE_END

            suite 1
            ~~~~~~~
            Ran 4 checks (1 subtests, 3 tests)
            Expected results: 4 (2 known intermittents)
            Unexpected results: 0

            Known Intermittent Results
            --------------------------
            test_foo
              KNOWN-INTERMITTENT-FAIL test_foo
            test_bar
              KNOWN-INTERMITTENT-PASS a subtest
            OK
            """
            ).lstrip("\n"),
        ),
    ],
    "ERRORSUMMARY": [
        (
            "errorsummary",
            {},
            dedent(
                """
            {"groups": ["manifestA", "manifestB"], "action": "test_groups", "line": 0}
            {"test": "test_baz", "subtest": null, "group": "manifestA", "status": "PASS", "expected": "FAIL", "message": null, "stack": null, "known_intermittent": [], "action": "test_result", "line": 8}
            {"group": "manifestA", "status": "ERROR", "duration": 70, "action": "group_result", "line": 9}
            {"group": "manifestB", "status": "OK", "duration": 10, "action": "group_result", "line": 9}
            """
            ).lstrip("\n"),
        ),
    ],
}


def ids(test):
    ids = []
    for value in FORMATS[test]:
        args = ", ".join(["{}={}".format(k, v) for k, v in value[1].items()])
        if args:
            args = "-{}".format(args)
        ids.append("{}{}".format(value[0], args))
    return ids


@pytest.fixture(autouse=True)
def timestamp(monkeypatch):
    def fake_time(*args, **kwargs):
        return 0

    monkeypatch.setattr(MachFormatter, "_time", fake_time)


@pytest.fixture
def get_logger():
    # Ensure a new state instance is created for each test function.
    StructuredLogger._logger_states = {}

    def inner(name, **fmt_args):
        buf = StringIO()
        fmt = formatters[name](**fmt_args)
        logger = StructuredLogger("test_logger")
        logger.add_handler(StreamHandler(buf, fmt))
        return logger

    return inner


@pytest.mark.parametrize("name,opts,expected", FORMATS["PASS"], ids=ids("PASS"))
def test_pass(get_logger, name, opts, expected):
    logger = get_logger(name, **opts)

    logger.suite_start(["test_foo", "test_bar", "test_baz"])
    logger.test_start("test_foo")
    logger.test_end("test_foo", "OK")
    logger.test_start("test_bar")
    logger.test_status("test_bar", "a subtest", "PASS")
    logger.test_end("test_bar", "OK")
    logger.test_start("test_baz")
    logger.test_end("test_baz", "FAIL", "FAIL", "expected 0 got 1")
    logger.suite_end()

    buf = logger.handlers[0].stream
    result = buf.getvalue()
    print("Dumping result for copy/paste:")
    print(result)
    assert result == expected


@pytest.mark.parametrize("name,opts,expected", FORMATS["FAIL"], ids=ids("FAIL"))
def test_fail(get_logger, name, opts, expected):
    stack = """
    SimpleTest.is@SimpleTest/SimpleTest.js:312:5
    @caps/tests/mochitest/test_bug246699.html:53:1
""".strip(
        "\n"
    )

    logger = get_logger(name, **opts)

    logger.suite_start(["test_foo", "test_bar", "test_baz"])
    logger.test_start("test_foo")
    logger.test_end("test_foo", "FAIL", "PASS", "expected 0 got 1")
    logger.test_start("test_bar")
    logger.test_status(
        "test_bar", "a subtest", "FAIL", "PASS", "expected 0 got 1", stack
    )
    logger.test_status("test_bar", "another subtest", "TIMEOUT")
    logger.test_end("test_bar", "OK")
    logger.test_start("test_baz")
    logger.test_end("test_baz", "PASS", "FAIL")
    logger.suite_end()

    buf = logger.handlers[0].stream
    result = buf.getvalue()
    print("Dumping result for copy/paste:")
    print(result)
    assert result == expected


@pytest.mark.parametrize(
    "name,opts,expected", FORMATS["PRECONDITION_FAILED"], ids=ids("PRECONDITION_FAILED")
)
def test_precondition_failed(get_logger, name, opts, expected):
    logger = get_logger(name, **opts)

    logger.suite_start(["test_foo", "test_bar"])
    logger.test_start("test_foo")
    logger.test_end("test_foo", "PRECONDITION_FAILED")
    logger.test_start("test_bar")
    logger.test_status("test_bar", "a subtest", "PASS")
    logger.test_status("test_bar", "another subtest", "PRECONDITION_FAILED")
    logger.test_end("test_bar", "OK")
    logger.suite_end()

    buf = logger.handlers[0].stream
    result = buf.getvalue()
    print("Dumping result for copy/paste:")
    print(result)
    assert result == expected


@pytest.mark.parametrize(
    "name,opts,expected", FORMATS["KNOWN-INTERMITTENT"], ids=ids("KNOWN-INTERMITTENT")
)
def test_known_intermittent(get_logger, name, opts, expected):
    logger = get_logger(name, **opts)

    logger.suite_start(["test_foo", "test_bar", "test_baz"])
    logger.test_start("test_foo")
    logger.test_end("test_foo", "FAIL", "PASS", known_intermittent=["FAIL"])
    logger.test_start("test_bar")
    logger.test_status(
        "test_bar", "a subtest", "PASS", "FAIL", known_intermittent=["PASS"]
    )
    logger.test_end("test_bar", "OK")
    logger.test_start("test_baz")
    logger.test_end(
        "test_baz", "FAIL", "FAIL", "expected 0 got 1", known_intermittent=["PASS"]
    )
    logger.suite_end()

    buf = logger.handlers[0].stream
    result = buf.getvalue()
    print("Dumping result for copy/paste:")
    print(result)
    assert result == expected


@pytest.mark.parametrize(
    "name,opts,expected", FORMATS["ERRORSUMMARY"], ids=ids("ERRORSUMMARY")
)
def test_errorsummary(monkeypatch, get_logger, name, opts, expected):

    ts = {"ts": 0}  # need to use dict since 'nonlocal' doesn't exist on PY2

    def fake_time():
        ts["ts"] += 0.01
        return ts["ts"]

    monkeypatch.setattr(time, "time", fake_time)
    logger = get_logger(name, **opts)

    logger.suite_start(
        {
            "manifestA": ["test_foo", "test_bar", "test_baz"],
            "manifestB": ["test_something"],
        }
    )
    logger.test_start("test_foo")
    logger.test_end("test_foo", "SKIP")
    logger.test_start("test_bar")
    logger.test_end("test_bar", "OK")
    logger.test_start("test_something")
    logger.test_end("test_something", "OK")
    logger.test_start("test_baz")
    logger.test_end("test_baz", "PASS", "FAIL")
    logger.suite_end()

    buf = logger.handlers[0].stream
    result = buf.getvalue()
    print("Dumping result for copy/paste:")
    print(result)

    expected = expected.split("\n")
    for i, line in enumerate(result.split("\n")):
        if not line:
            continue

        data = json.loads(line)
        assert data == json.loads(expected[i])


class FormatterTest(unittest.TestCase):
    def setUp(self):
        self.position = 0
        self.logger = StructuredLogger("test_%s" % type(self).__name__)
        self.output_file = StringIO()
        self.handler = StreamHandler(self.output_file, self.get_formatter())
        self.logger.add_handler(self.handler)

    def set_position(self, pos=None):
        if pos is None:
            pos = self.output_file.tell()
        self.position = pos

    def get_formatter(self):
        raise NotImplementedError(
            "FormatterTest subclasses must implement get_formatter"
        )

    @property
    def loglines(self):
        self.output_file.seek(self.position)
        return [ensure_text(line.rstrip()) for line in self.output_file.readlines()]


class TestHTMLFormatter(FormatterTest):
    def get_formatter(self):
        return HTMLFormatter()

    def test_base64_string(self):
        self.logger.suite_start([])
        self.logger.test_start("string_test")
        self.logger.test_end("string_test", "FAIL", extra={"data": "foobar"})
        self.logger.suite_end()
        self.assertIn("data:text/html;charset=utf-8;base64,Zm9vYmFy", self.loglines[-3])

    def test_base64_unicode(self):
        self.logger.suite_start([])
        self.logger.test_start("unicode_test")
        self.logger.test_end("unicode_test", "FAIL", extra={"data": unichr(0x02A9)})
        self.logger.suite_end()
        self.assertIn("data:text/html;charset=utf-8;base64,yqk=", self.loglines[-3])

    def test_base64_other(self):
        self.logger.suite_start([])
        self.logger.test_start("int_test")
        self.logger.test_end("int_test", "FAIL", extra={"data": {"foo": "bar"}})
        self.logger.suite_end()
        self.assertIn(
            "data:text/html;charset=utf-8;base64,eyJmb28iOiAiYmFyIn0=",
            self.loglines[-3],
        )


class TestTBPLFormatter(FormatterTest):
    def get_formatter(self):
        return TbplFormatter()

    def test_unexpected_message(self):
        self.logger.suite_start([])
        self.logger.test_start("timeout_test")
        self.logger.test_end("timeout_test", "TIMEOUT", message="timed out")
        self.assertIn(
            "TEST-UNEXPECTED-TIMEOUT | timeout_test | timed out", self.loglines
        )
        self.logger.suite_end()

    def test_default_unexpected_end_message(self):
        self.logger.suite_start([])
        self.logger.test_start("timeout_test")
        self.logger.test_end("timeout_test", "TIMEOUT")
        self.assertIn(
            "TEST-UNEXPECTED-TIMEOUT | timeout_test | expected OK", self.loglines
        )
        self.logger.suite_end()

    def test_default_unexpected_status_message(self):
        self.logger.suite_start([])
        self.logger.test_start("timeout_test")
        self.logger.test_status("timeout_test", "subtest", status="TIMEOUT")
        self.assertIn(
            "TEST-UNEXPECTED-TIMEOUT | timeout_test | subtest - expected PASS",
            self.loglines,
        )
        self.logger.test_end("timeout_test", "OK")
        self.logger.suite_end()

    def test_known_intermittent_end(self):
        self.logger.suite_start([])
        self.logger.test_start("intermittent_test")
        self.logger.test_end(
            "intermittent_test",
            status="FAIL",
            expected="PASS",
            known_intermittent=["FAIL"],
        )
        # test_end log format:
        # "TEST-KNOWN-INTERMITTENT-<STATUS> | <test> | took <duration>ms"
        # where duration may be different each time
        self.assertIn(
            "TEST-KNOWN-INTERMITTENT-FAIL | intermittent_test | took ", self.loglines[2]
        )
        self.assertIn("ms", self.loglines[2])
        self.logger.suite_end()

    def test_known_intermittent_status(self):
        self.logger.suite_start([])
        self.logger.test_start("intermittent_test")
        self.logger.test_status(
            "intermittent_test",
            "subtest",
            status="FAIL",
            expected="PASS",
            known_intermittent=["FAIL"],
        )
        self.assertIn(
            "TEST-KNOWN-INTERMITTENT-FAIL | intermittent_test | subtest", self.loglines
        )
        self.logger.test_end("intermittent_test", "OK")
        self.logger.suite_end()

    def test_single_newline(self):
        self.logger.suite_start([])
        self.logger.test_start("test1")
        self.set_position()
        self.logger.test_status("test1", "subtest", status="PASS", expected="FAIL")
        self.logger.test_end("test1", "OK")
        self.logger.suite_end()

        # This sequence should not produce blanklines
        for line in self.loglines:
            self.assertNotEqual("", line)

    def test_process_exit(self):
        self.logger.process_exit(1234, 0)
        self.assertIn("TEST-INFO | 1234: exit 0", self.loglines)

    @unittest.skipUnless(os.name == "posix", "posix only")
    def test_process_exit_with_sig(self):
        # subprocess return code is negative when process
        # has been killed by signal on posix.
        self.logger.process_exit(1234, -signal.SIGTERM)
        self.assertIn("TEST-INFO | 1234: killed by SIGTERM", self.loglines)


class TestTBPLFormatterWithShutdown(FormatterTest):
    def get_formatter(self):
        return TbplFormatter(summary_on_shutdown=True)

    def test_suite_summary_on_shutdown(self):
        self.logger.suite_start([])
        self.logger.test_start("summary_test")
        self.logger.test_status(
            "summary_test", "subtest", "FAIL", "PASS", known_intermittent=["FAIL"]
        )
        self.logger.test_end("summary_test", "FAIL", "OK", known_intermittent=["FAIL"])
        self.logger.suite_end()
        self.logger.shutdown()

        self.assertIn("suite 1: 2/2 (2 known intermittent tests)", self.loglines)
        self.assertIn("Known Intermittent tests:", self.loglines)
        self.assertIn(
            "TEST-KNOWN-INTERMITTENT-FAIL | summary_test | subtest", self.loglines
        )


class TestMachFormatter(FormatterTest):
    def get_formatter(self):
        return MachFormatter(disable_colors=True)

    def test_summary(self):
        self.logger.suite_start([])

        # Some tests that pass
        self.logger.test_start("test1")
        self.logger.test_end("test1", status="PASS", expected="PASS")

        self.logger.test_start("test2")
        self.logger.test_end("test2", status="PASS", expected="TIMEOUT")

        self.logger.test_start("test3")
        self.logger.test_end("test3", status="FAIL", expected="PASS")

        self.set_position()
        self.logger.suite_end()

        self.assertIn("Ran 3 checks (3 tests)", self.loglines)
        self.assertIn("Expected results: 1", self.loglines)
        self.assertIn(
            """
Unexpected results: 2
  test: 2 (1 fail, 1 pass)
""".strip(),
            "\n".join(self.loglines),
        )
        self.assertNotIn("test1", self.loglines)
        self.assertIn("UNEXPECTED-PASS test2", self.loglines)
        self.assertIn("FAIL test3", self.loglines)

    def test_summary_subtests(self):
        self.logger.suite_start([])

        self.logger.test_start("test1")
        self.logger.test_status("test1", "subtest1", status="PASS")
        self.logger.test_status("test1", "subtest2", status="FAIL")
        self.logger.test_end("test1", status="OK", expected="OK")

        self.logger.test_start("test2")
        self.logger.test_status("test2", "subtest1", status="TIMEOUT", expected="PASS")
        self.logger.test_end("test2", status="TIMEOUT", expected="OK")

        self.set_position()
        self.logger.suite_end()

        self.assertIn("Ran 5 checks (3 subtests, 2 tests)", self.loglines)
        self.assertIn("Expected results: 2", self.loglines)
        self.assertIn(
            """
Unexpected results: 3
  test: 1 (1 timeout)
  subtest: 2 (1 fail, 1 timeout)
""".strip(),
            "\n".join(self.loglines),
        )

    def test_summary_ok(self):
        self.logger.suite_start([])

        self.logger.test_start("test1")
        self.logger.test_status("test1", "subtest1", status="PASS")
        self.logger.test_status("test1", "subtest2", status="PASS")
        self.logger.test_end("test1", status="OK", expected="OK")

        self.logger.test_start("test2")
        self.logger.test_status("test2", "subtest1", status="PASS", expected="PASS")
        self.logger.test_end("test2", status="OK", expected="OK")

        self.set_position()
        self.logger.suite_end()

        self.assertIn("OK", self.loglines)
        self.assertIn("Expected results: 5", self.loglines)
        self.assertIn("Unexpected results: 0", self.loglines)

    def test_process_start(self):
        self.logger.process_start(1234)
        self.assertIn("Started process `1234`", self.loglines[0])

    def test_process_start_with_command(self):
        self.logger.process_start(1234, command="test cmd")
        self.assertIn("Started process `1234` (test cmd)", self.loglines[0])

    def test_process_exit(self):
        self.logger.process_exit(1234, 0)
        self.assertIn("1234: exit 0", self.loglines[0])

    @unittest.skipUnless(os.name == "posix", "posix only")
    def test_process_exit_with_sig(self):
        # subprocess return code is negative when process
        # has been killed by signal on posix.
        self.logger.process_exit(1234, -signal.SIGTERM)
        self.assertIn("1234: killed by SIGTERM", self.loglines[0])


class TestGroupingFormatter(FormatterTest):
    def get_formatter(self):
        return GroupingFormatter()

    def test_results_total(self):
        self.logger.suite_start([])

        self.logger.test_start("test1")
        self.logger.test_status("test1", "subtest1", status="PASS")
        self.logger.test_status("test1", "subtest1", status="PASS")
        self.logger.test_end("test1", status="OK")

        self.logger.test_start("test2")
        self.logger.test_status(
            "test2",
            "subtest2",
            status="FAIL",
            expected="PASS",
            known_intermittent=["FAIL"],
        )
        self.logger.test_end("test2", status="FAIL", expected="OK")

        self.set_position()
        self.logger.suite_end()

        self.assertIn("Ran 2 tests finished in 0.0 seconds.", self.loglines)
        self.assertIn("  \u2022 1 ran as expected. 0 tests skipped.", self.loglines)
        self.assertIn("  \u2022 1 known intermittent results.", self.loglines)
        self.assertIn("  \u2022 1 tests failed unexpectedly", self.loglines)
        self.assertIn("  \u25B6 FAIL [expected OK] test2", self.loglines)
        self.assertIn(
            "  \u25B6 FAIL [expected PASS, known intermittent [FAIL] test2, subtest2",
            self.loglines,
        )


class TestXUnitFormatter(FormatterTest):
    def get_formatter(self):
        return XUnitFormatter()

    def log_as_xml(self):
        return ET.fromstring("\n".join(self.loglines))

    def test_stacktrace_is_present(self):
        self.logger.suite_start([])
        self.logger.test_start("test1")
        self.logger.test_end(
            "test1", "fail", message="Test message", stack="this\nis\na\nstack"
        )
        self.logger.suite_end()

        root = self.log_as_xml()
        self.assertIn("this\nis\na\nstack", root.find("testcase/failure").text)

    def test_failure_message(self):
        self.logger.suite_start([])
        self.logger.test_start("test1")
        self.logger.test_end("test1", "fail", message="Test message")
        self.logger.suite_end()

        root = self.log_as_xml()
        self.assertEquals(
            "Expected OK, got FAIL", root.find("testcase/failure").get("message")
        )

    def test_suite_attrs(self):
        self.logger.suite_start([])
        self.logger.test_start("test1")
        self.logger.test_end("test1", "ok", message="Test message")
        self.logger.suite_end()

        root = self.log_as_xml()
        self.assertEqual(root.get("skips"), "0")
        self.assertEqual(root.get("failures"), "0")
        self.assertEqual(root.get("errors"), "0")
        self.assertEqual(root.get("tests"), "1")
        self.assertEqual(root.get("time"), "0.00")

    def test_time_is_not_rounded(self):
        # call formatter directly, it is easier here
        formatter = self.get_formatter()
        formatter.suite_start(dict(time=55000))
        formatter.test_start(dict(time=55100))
        formatter.test_end(
            dict(time=55558, test="id", message="message", status="PASS")
        )
        xml_string = formatter.suite_end(dict(time=55559))

        root = ET.fromstring(xml_string)
        self.assertEqual(root.get("time"), "0.56")
        self.assertEqual(root.find("testcase").get("time"), "0.46")


if __name__ == "__main__":
    mozunit.main()