1"""
2                     The LLVM Compiler Infrastructure
3
4This file is distributed under the University of Illinois Open Source
5License. See LICENSE.TXT for details.
6
7Provides the LLDBTestResult class, which holds information about progress
8and results of a single test run.
9"""
10
11from __future__ import absolute_import
12from __future__ import print_function
13
14# System modules
15import inspect
16import os
17
18# Third-party modules
19import unittest2
20
21# LLDB Modules
22from . import configuration
23from lldbsuite.test_event.event_builder import EventBuilder
24from lldbsuite.test_event import build_exception
25
26class LLDBTestResult(unittest2.TextTestResult):
27    """
28    Enforce a singleton pattern to allow introspection of test progress.
29
30    Overwrite addError(), addFailure(), and addExpectedFailure() methods
31    to enable each test instance to track its failure/error status.  It
32    is used in the LLDB test framework to emit detailed trace messages
33    to a log file for easier human inspection of test failures/errors.
34    """
35    __singleton__ = None
36    __ignore_singleton__ = False
37
38    @staticmethod
39    def getTerminalSize():
40        import os
41        env = os.environ
42        def ioctl_GWINSZ(fd):
43            try:
44                import fcntl, termios, struct, os
45                cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
46            '1234'))
47            except:
48                return
49            return cr
50        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
51        if not cr:
52            try:
53                fd = os.open(os.ctermid(), os.O_RDONLY)
54                cr = ioctl_GWINSZ(fd)
55                os.close(fd)
56            except:
57                pass
58        if not cr:
59            cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
60        return int(cr[1]), int(cr[0])
61
62    def __init__(self, *args):
63        if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__:
64            raise Exception("LLDBTestResult instantiated more than once")
65        super(LLDBTestResult, self).__init__(*args)
66        LLDBTestResult.__singleton__ = self
67        # Now put this singleton into the lldb module namespace.
68        configuration.test_result = self
69        # Computes the format string for displaying the counter.
70        counterWidth = len(str(configuration.suite.countTestCases()))
71        self.fmt = "%" + str(counterWidth) + "d: "
72        self.indentation = ' ' * (counterWidth + 2)
73        # This counts from 1 .. suite.countTestCases().
74        self.counter = 0
75        (width, height) = LLDBTestResult.getTerminalSize()
76        self.results_formatter = configuration.results_formatter_object
77
78    def _config_string(self, test):
79        compiler = getattr(test, "getCompiler", None)
80        arch = getattr(test, "getArchitecture", None)
81        return "%s-%s" % (compiler() if compiler else "", arch() if arch else "")
82
83    def _exc_info_to_string(self, err, test):
84        """Overrides superclass TestResult's method in order to append
85        our test config info string to the exception info string."""
86        if hasattr(test, "getArchitecture") and hasattr(test, "getCompiler"):
87            return '%sConfig=%s-%s' % (super(LLDBTestResult, self)._exc_info_to_string(err, test),
88                                                        test.getArchitecture(),
89                                                        test.getCompiler())
90        else:
91            return super(LLDBTestResult, self)._exc_info_to_string(err, test)
92
93    def getDescription(self, test):
94        doc_first_line = test.shortDescription()
95        if self.descriptions and doc_first_line:
96            return '\n'.join((str(test), self.indentation + doc_first_line))
97        else:
98            return str(test)
99
100    def getCategoriesForTest(self, test):
101        """
102        Gets all the categories for the currently running test method in test case
103        """
104        test_categories = []
105        test_method = getattr(test, test._testMethodName)
106        if test_method != None and hasattr(test_method, "categories"):
107            test_categories.extend(test_method.categories)
108
109        test_categories.extend(test.getCategories())
110
111        return test_categories
112
113    def hardMarkAsSkipped(self,test):
114        getattr(test, test._testMethodName).__func__.__unittest_skip__ = True
115        getattr(test, test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run"
116        test.__class__.__unittest_skip__ = True
117        test.__class__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run"
118
119    def startTest(self, test):
120        if configuration.shouldSkipBecauseOfCategories(self.getCategoriesForTest(test)):
121            self.hardMarkAsSkipped(test)
122        configuration.setCrashInfoHook("%s at %s" % (str(test),inspect.getfile(test.__class__)))
123        self.counter += 1
124        #if self.counter == 4:
125        #    import crashinfo
126        #    crashinfo.testCrashReporterDescription(None)
127        test.test_number = self.counter
128        if self.showAll:
129            self.stream.write(self.fmt % self.counter)
130        super(LLDBTestResult, self).startTest(test)
131        if self.results_formatter:
132            self.results_formatter.handle_event(
133                EventBuilder.event_for_start(test))
134
135    def addSuccess(self, test):
136        super(LLDBTestResult, self).addSuccess(test)
137        if configuration.parsable:
138            self.stream.write("PASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
139        if self.results_formatter:
140            self.results_formatter.handle_event(
141                EventBuilder.event_for_success(test))
142
143    def _isBuildError(self, err_tuple):
144        exception = err_tuple[1]
145        return isinstance(exception, build_exception.BuildError)
146
147    def _getTestPath(self, test):
148        if test is None:
149            return ""
150        elif hasattr(test, "test_filename"):
151            return test.test_filename
152        else:
153            return inspect.getsourcefile(test.__class__)
154
155
156    def _saveBuildErrorTuple(self, test, err):
157        # Adjust the error description so it prints the build command and build error
158        # rather than an uninformative Python backtrace.
159        build_error = err[1]
160        error_description = "{}\nTest Directory:\n{}".format(
161            str(build_error),
162            os.path.dirname(self._getTestPath(test)))
163        self.errors.append((test, error_description))
164        self._mirrorOutput = True
165
166    def addError(self, test, err):
167        configuration.sdir_has_content = True
168        if self._isBuildError(err):
169            self._saveBuildErrorTuple(test, err)
170        else:
171            super(LLDBTestResult, self).addError(test, err)
172
173        method = getattr(test, "markError", None)
174        if method:
175            method()
176        if configuration.parsable:
177            self.stream.write("FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
178        if self.results_formatter:
179            # Handle build errors as a separate event type
180            if self._isBuildError(err):
181                error_event = EventBuilder.event_for_build_error(test, err)
182            else:
183                error_event = EventBuilder.event_for_error(test, err)
184            self.results_formatter.handle_event(error_event)
185
186    def addCleanupError(self, test, err):
187        configuration.sdir_has_content = True
188        super(LLDBTestResult, self).addCleanupError(test, err)
189        method = getattr(test, "markCleanupError", None)
190        if method:
191            method()
192        if configuration.parsable:
193            self.stream.write("CLEANUP ERROR: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
194        if self.results_formatter:
195            self.results_formatter.handle_event(
196                EventBuilder.event_for_cleanup_error(
197                    test, err))
198
199    def addFailure(self, test, err):
200        configuration.sdir_has_content = True
201        super(LLDBTestResult, self).addFailure(test, err)
202        method = getattr(test, "markFailure", None)
203        if method:
204            method()
205        if configuration.parsable:
206            self.stream.write("FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
207        if configuration.useCategories:
208            test_categories = self.getCategoriesForTest(test)
209            for category in test_categories:
210                if category in configuration.failuresPerCategory:
211                    configuration.failuresPerCategory[category] = configuration.failuresPerCategory[category] + 1
212                else:
213                    configuration.failuresPerCategory[category] = 1
214        if self.results_formatter:
215            self.results_formatter.handle_event(
216                EventBuilder.event_for_failure(test, err))
217
218
219    def addExpectedFailure(self, test, err, bugnumber):
220        configuration.sdir_has_content = True
221        super(LLDBTestResult, self).addExpectedFailure(test, err, bugnumber)
222        method = getattr(test, "markExpectedFailure", None)
223        if method:
224            method(err, bugnumber)
225        if configuration.parsable:
226            self.stream.write("XFAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
227        if self.results_formatter:
228            self.results_formatter.handle_event(
229                EventBuilder.event_for_expected_failure(
230                test, err, bugnumber))
231
232    def addSkip(self, test, reason):
233        configuration.sdir_has_content = True
234        super(LLDBTestResult, self).addSkip(test, reason)
235        method = getattr(test, "markSkippedTest", None)
236        if method:
237            method()
238        if configuration.parsable:
239            self.stream.write("UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % (self._config_string(test), str(test), reason))
240        if self.results_formatter:
241            self.results_formatter.handle_event(
242                EventBuilder.event_for_skip(test, reason))
243
244    def addUnexpectedSuccess(self, test, bugnumber):
245        configuration.sdir_has_content = True
246        super(LLDBTestResult, self).addUnexpectedSuccess(test, bugnumber)
247        method = getattr(test, "markUnexpectedSuccess", None)
248        if method:
249            method(bugnumber)
250        if configuration.parsable:
251            self.stream.write("XPASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
252        if self.results_formatter:
253            self.results_formatter.handle_event(
254                EventBuilder.event_for_unexpected_success(
255                    test, bugnumber))
256