summaryrefslogtreecommitdiff
path: root/framework/status.py
blob: 14f05880454a0dadc970066a2a61e7a83893657b (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
# coding=utf-8
# Copyright (c) 2013, 2015 Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

""" Provides classes that represent test statuses

These classes work similar to enums in other languages. They provide a limited
set of attributes that are defined per status:

A name -- a string representation of the values
An integer -- a value that allows classes to be compared using python's rich
comparisons
A tuple representing :
  [0] -- whether the test is considered a passing status
  [1] -- whether the test should be added to the total number of tests. This
         allows statuses like 'skip' to not affect the total percentage.


Status ordering from best to worst:

pass
warn
dmesg-warn
fail
dmesg-fail
timeout
crash
incomplete

SKIP and NOTRUN are not factored into regressions and fixes, they are counted
separately. They also derive from a sublcass of Status, which always returns
False

The formula for determining regressions is:
  old_status < new_status

The formula for determining fixes is:
  old_status > new_status

"""

from __future__ import (
    absolute_import, division, print_function, unicode_literals
)

import six

from framework import exceptions, compat

__all__ = ['NOTRUN',
           'PASS',
           'FAIL',
           'WARN',
           'CRASH',
           'DMESG_WARN',
           'DMESG_FAIL',
           'SKIP',
           'TIMEOUT',
           'INCOMPLETE',
           'ALL']


def status_lookup(status):
    """ Provided a string return a status object instance

    When provided a string that corresponds to a key in it's status_dict
    variable, this function returns a status object instance. If the string
    does not correspond to a key it will raise an exception

    """
    # Don't go through this if what we've been passed already is a status, it's
    # very expensive
    if isinstance(status, Status):
        return status

    try:
        return _STATUS_MAP[status]
    except KeyError:
        # Raise a StatusException rather than a key error
        raise StatusException(status)


@compat.python_2_unicode_compatible
class StatusException(exceptions.PiglitInternalError):
    """ Raise this exception when a string is passed to status_lookup that
    doesn't exists

    The primary reason to have a special exception is that otherwise
    status_lookup returns a KeyError, but there are many cases where it is
    desirable to except a KeyError and have an exception path. Using a custom
    Error class here allows for more fine-grained control.

    """
    def __init__(self, status):
        self.__status = status
        super(StatusException, self).__init__(self)

    def __str__(self):
        return u'Unknown status "{}"'.format(self.__status)


@compat.python_2_unicode_compatible
class Status(object):
    """ A simple class for representing the output values of tests.

    This class creatse the necessary magic values to use python's rich
    comparison methods. This allows two objects to be compared using common
    operators like <. >, ==, etc. It also alows them to be looked up in
    containers using ``for x in []`` syntax.

    This class is meant to be immutable, it (ab)uses two tools to provide this
    psuedo-immutability: the property decorator, and the __slots__ attribute to
    1: make the three attributes getters, therefor unwritable, and 2: make
    adding additional attributes impossible

    Arguments:
    name -- the name of the status
    value -- an int used to sort statuses from best to worst (0 -> inf)
    fraction -- a tuple with two ints representing
                [0]: 1 if the status is 'passing', else 0
                [1]: 1 if the status counts toward the total number of tests,
                     else 0

    """
    __slots__ = ['__name', '__value', '__fraction']

    def __init__(self, name, value, fraction=(0, 1)):
        assert isinstance(value, int), type(value)
        # The object is immutable, so calling self.foo = foo will raise a
        # TypeError. Using setattr from the parrent object works around this.
        self.__name = six.text_type(name)
        self.__value = value
        self.__fraction = fraction

    @property
    def name(self):
        """ Return the value of name """
        return self.__name

    @property
    def value(self):
        """ Return the sorting value """
        return self.__value

    @property
    def fraction(self):
        """ Return the totals of the test as a tuple: (<pass>. <total>) """
        return self.__fraction

    def __repr__(self):
        return 'Status("{}", {}, {})'.format(
            self.name, self.value, self.fraction)

    def __bytes__(self):
        if six.PY2:
            return str(self.name)
        elif six.PY3:
            return bytes(self.name, 'utf-8')

    def __str__(self):
        return self.name

    def __lt__(self, other):
        return not self.__ge__(other)

    def __le__(self, other):
        return not self.__gt__(other)

    def __eq__(self, other):
        # This must be int or status, since status comparisons are done using
        # the __int__ magic method
        if isinstance(other, (int, Status)):
            return int(self) == int(other)
        elif isinstance(other, six.text_type):
            return six.text_type(self) == other
        elif isinstance(other, six.binary_type):
            return six.binary_type(self) == other
        raise TypeError("Cannot compare type: {}".format(type(other)))

    def __ne__(self, other):
        return not self == other

    def __ge__(self, other):
        return self.fraction[1] > other.fraction[1] or (
            self.fraction[1] == other.fraction[1] and int(self) >= int(other))

    def __gt__(self, other):
        return self.fraction[1] > other.fraction[1] or int(self) > int(other)

    def __int__(self):
        return self.value

    def __hash__(self):
        return hash(self.name)


class NoChangeStatus(Status):
    """ Special sublcass of status that overides rich comparison methods

    This special class of a Status is for use with NOTRUN and SKIP, it never
    returns that it is a pass or regression

    """
    def __init__(self, name, value=0, fraction=(0, 0)):
        super(NoChangeStatus, self).__init__(name, value, fraction)

    def __eq__(self, other):
        if isinstance(other, (str, six.text_type, Status)):
            return six.text_type(self) == six.text_type(other)
        raise TypeError("Cannot compare type: {}".format(type(other)))

    def __ne__(self, other):
        if isinstance(other, (str, six.text_type, Status)):
            return six.text_type(self) != six.text_type(other)
        raise TypeError("Cannot compare type: {}".format(type(other)))

    def __hash__(self):
        return hash(self.name)


NOTRUN = NoChangeStatus('notrun')

SKIP = NoChangeStatus('skip')

PASS = Status('pass', 0, (1, 1))

WARN = Status('warn', 10)

DMESG_WARN = Status('dmesg-warn', 20)

FAIL = Status('fail', 30)

DMESG_FAIL = Status('dmesg-fail', 40)

TIMEOUT = Status('timeout', 50)

CRASH = Status('crash', 60)

INCOMPLETE = Status('incomplete', 100)

_STATUS_MAP = {
    'skip': SKIP,
    'pass': PASS,
    'warn': WARN,
    'fail': FAIL,
    'crash': CRASH,
    'dmesg-warn': DMESG_WARN,
    'dmesg-fail': DMESG_FAIL,
    'notrun': NOTRUN,
    'timeout': TIMEOUT,
    'incomplete': INCOMPLETE,
}

# A tuple (ordered, immutable) of all statuses in this module
ALL = (PASS, WARN, DMESG_WARN, FAIL, DMESG_FAIL, TIMEOUT, CRASH, INCOMPLETE,
       SKIP, NOTRUN)