File: matrix.py

package info (click to toggle)
junit2html 31.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 576 kB
  • sloc: xml: 3,208; python: 1,023; makefile: 6; sh: 5
file content (280 lines) | stat: -rw-r--r-- 9,642 bytes parent folder | download
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
"""
Handle multiple parsed junit reports
"""
from __future__ import unicode_literals

import os
from typing import TYPE_CHECKING

from . import parser
from .case_result import CaseResult
from .common import ReportContainer
from .render import HTMLMatrix

UNTESTED = CaseResult.UNTESTED
PARTIAL_PASS = CaseResult.PARTIAL_PASS
PARTIAL_FAIL = CaseResult.PARTIAL_FAIL
TOTAL_FAIL = CaseResult.TOTAL_FAIL


if TYPE_CHECKING: # pragma: no cover
    from .parser import Case, Class
    from typing import Dict, List, Optional, Any, Literal


class ReportMatrix(ReportContainer):
    """
    Load and handle several report files
    """
    cases: "Dict[str, Dict[str, Dict[str, Case]]]"
    classes: "Dict[str, Dict[str, Class]]"
    casenames: "Dict[str, List[str]]"
    result_stats: "Dict[CaseResult, int]"
    case_results: "Dict[str, Dict[str, List[CaseResult]]]"

    def __init__(self):
        super(ReportMatrix, self).__init__()
        self.cases = {}
        self.classes = {}
        self.casenames = {}
        self.result_stats = {}
        self.case_results = {}

    def add_case_result(self, case: "Case"):
        if case.testclass is None or case.testclass.name is None:
            testclass = ""
        else:
            testclass = case.testclass.name
        casename = "" if case.name is None else case.name
        if testclass not in self.case_results:
            self.case_results[testclass] = {}
        if casename not in self.case_results[testclass]:
            self.case_results[testclass][casename] = []
        self.case_results[testclass][casename].append(case.outcome())

    def report_order(self):
        return sorted(self.reports.keys())

    def short_outcome(self, outcome: CaseResult) -> "Literal['ok', '/', 's', 'f', 'F', '%', 'X', 'U', '?']":
        if outcome == CaseResult.PASSED:
            return "/"
        elif outcome == CaseResult.SKIPPED: # pragma: no cover
            return "s" # currently unused because SKIPPED returns UNTESTED
        elif outcome == CaseResult.FAILED:
            return "f"
        elif outcome == CaseResult.TOTAL_FAIL:
            return "F"
        elif outcome == CaseResult.PARTIAL_PASS:
            return "%"
        elif outcome == CaseResult.PARTIAL_FAIL:
            return "X"
        elif outcome == CaseResult.UNTESTED:
            return "U"

        return "?"

    def add_report(self, filename: str):
        """
        Load a report into the matrix
        :param filename:
        :return:
        """
        parsed = parser.Junit(filename=filename)
        filename = os.path.basename(filename)
        self.reports[filename] = parsed

        for suite in parsed.suites:
            for testclass in suite.classes:
                if testclass not in self.classes:
                    self.classes[testclass] = {}
                if testclass not in self.casenames:
                    self.casenames[testclass] = list()
                self.classes[testclass][filename] = suite.classes[testclass]

                for testcase in self.classes[testclass][filename].cases:
                    name = "" if testcase.name is None else testcase.name.strip()
                    if name not in self.casenames[testclass]:
                        self.casenames[testclass].append(name)

                    if testclass not in self.cases:
                        self.cases[testclass] = {}
                    if name not in self.cases[testclass]:
                        self.cases[testclass][name] = {}
                    self.cases[testclass][name][filename] = testcase

                    outcome = testcase.outcome()
                    self.add_case_result(testcase)

                    self.result_stats[outcome] = 1 + self.result_stats.get(
                        outcome, 0)

    def summary(self) -> str:
        """
        Render a summary of the matrix
        :return:
        """
        raise NotImplementedError()

    def combined_result_list(self, classname: str, casename: str):
        """
        Combone the result of all instances of the given case
        :param classname:
        :param casename:
        :return:
        """
        if classname in self.case_results:
            if casename in self.case_results[classname]:
                results = self.case_results[classname][casename]
                return self.combined_result(results)

        return " ", ""

    def combined_result(self, results: "List[CaseResult]"):
        """
        Given a list of results, produce a "combined" overall result
        :param results:
        :return:
        """
        if results:
            if CaseResult.PASSED in results:
                if CaseResult.FAILED in results:
                    return self.short_outcome(CaseResult.PARTIAL_FAIL), CaseResult.PARTIAL_FAIL.title()
                return self.short_outcome(CaseResult.PASSED), CaseResult.PASSED.title()

            if CaseResult.FAILED in results:
                return self.short_outcome(CaseResult.FAILED), CaseResult.FAILED.title()
            if CaseResult.SKIPPED in results:
                return self.short_outcome(CaseResult.UNTESTED), CaseResult.UNTESTED.title()
            if CaseResult.PARTIAL_PASS in results:
                return self.short_outcome(CaseResult.PARTIAL_PASS), CaseResult.PARTIAL_PASS.title()
            if CaseResult.TOTAL_FAIL in results:
                return self.short_outcome(CaseResult.TOTAL_FAIL), CaseResult.TOTAL_FAIL.title()
        return " ", ""


class HtmlReportMatrix(ReportMatrix):
    """
    Render a matrix report as html
    """

    outdir: str

    def __init__(self, outdir: str):
        super(HtmlReportMatrix, self).__init__()
        self.outdir = outdir

    def add_report(self, filename: str, show_toc: bool=True):
        """
        Load a report
        """
        super(HtmlReportMatrix, self).add_report(filename)
        basename = os.path.basename(filename)
        # make the individual report too
        report = self.reports[basename].html(show_toc=show_toc)
        if self.outdir != "" and not os.path.exists(self.outdir):
            os.makedirs(self.outdir)
        with open(
                os.path.join(self.outdir, basename) + ".html", "wb") as filehandle:
            filehandle.write(report.encode("utf-8"))

    def short_outcome(self, outcome: CaseResult) -> "Literal['ok', '/', 's', 'f', 'F', '%', 'X', 'U', '?']":
        if outcome == CaseResult.PASSED:
            return "ok"
        return super(HtmlReportMatrix, self).short_outcome(outcome)

    def short_axis(self, axis: str):
        if axis.endswith(".xml"):
            return axis[:-4]
        return axis

    def summary(self, template: "Optional[Any]"=None):
        """
        Render the html
        :return:
        """
        html_matrix = HTMLMatrix(self, template)

        return str(html_matrix)


class TextReportMatrix(ReportMatrix):
    """
    Render a matrix report as text
    """

    def summary(self):
        """
        Render as a string
        :return:
        """

        output = "\nMatrix Test Report\n"
        output += "===================\n"

        axis = list(self.reports.keys())
        axis.sort()

        # find the longest classname or test case name
        left_indent = 0
        for classname in self.classes:
            left_indent = max(len(classname), left_indent)
            for casename in self.casenames[classname]:
                left_indent = max(len(casename), left_indent)

        # render the axis headings in a stepped tree
        treelines = ""
        for filename in self.report_order():
            output += "{}    {}{}\n".format(" " * left_indent, treelines,
                                            filename)
            treelines += "| "
        output += "{}    {}\n".format(" " * left_indent, treelines)
        # render in groups of the same class

        for classname in self.classes:
            # new class
            output += "{}  \n".format(classname)

            # print the case name
            for casename in sorted(set(self.casenames[classname])):
                output += "- {}{}  ".format(casename,
                                            " " * (left_indent - len(casename)))

                # print each test and its result for each axis
                case_data = ""
                testcase: "Optional[Case]" = None
                for axis in self.report_order():
                    if axis not in self.cases[classname][casename]:
                        case_data += "  "
                    else:
                        testcase = self.cases[classname][casename][axis]
                        if testcase.skipped:
                            case_data += "s "
                        elif testcase.failure:
                            case_data += "f "
                        else:
                            case_data += "/ "

                if testcase is None or testcase.name is None:
                    testcase_name = ""
                else:
                    testcase_name = testcase.name
                combined, combined_name = self.combined_result(
                    self.case_results[classname][testcase_name])

                output += case_data
                output += " {} {}\n".format(combined, combined_name)

        # print the result stats

        output += "\n"
        output += "-" * 79
        output += "\n"

        output += "Test Results:\n"

        for outcome in sorted(self.result_stats):
            output += "  {:<12} : {:>6}\n".format(
                outcome.title(),
                self.result_stats[outcome])

        return output