2 # Permission is hereby granted, free of charge, to any person
3 # obtaining a copy of this software and associated documentation
4 # files (the "Software"), to deal in the Software without
5 # restriction, including without limitation the rights to use,
6 # copy, modify, merge, publish, distribute, sublicense, and/or
7 # sell copies of the Software, and to permit persons to whom the
8 # Software is furnished to do so, subject to the following
11 # This permission notice shall be included in all copies or
12 # substantial portions of the Software.
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
15 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
16 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
17 # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR(S) BE
18 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
19 # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
20 # OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 # DEALINGS IN THE SOFTWARE.
23 """ Module for results generation """
29 from framework
import status
, exceptions
, grouptools
37 class Subtests(collections
.abc
.MutableMapping
):
38 """A dict-like object that stores Statuses as values."""
39 def __init__(self
, dict_
=None):
40 self
.__container
= collections
.OrderedDict()
45 def __setitem__(self
, name
, value
):
46 self
.__container
[name
.lower()] = status
.status_lookup(value
)
48 def __getitem__(self
, name
):
49 return self
.__container
[name
.lower()]
51 def __delitem__(self
, name
):
52 del self
.__container
[name
.lower()]
55 return iter(self
.__container
)
58 return len(self
.__container
)
61 return repr(self
.__container
)
65 res
['__type__'] = 'Subtests'
69 def from_dict(cls
, dict_
):
70 if '__type__' in dict_
:
78 class StringDescriptor(object): # pylint: disable=too-few-public-methods
79 """A Shared data descriptor class for TestResult.
81 This provides a property that can be passed a str or unicode, but always
82 returns a unicode object.
85 def __init__(self
, name
, default
=''):
86 assert isinstance(default
, str)
88 self
.__default
= default
90 def __get__(self
, instance
, cls
):
91 return getattr(instance
, self
.__name
, self
.__default
)
93 def __set__(self
, instance
, value
):
94 if isinstance(value
, bytes
):
95 setattr(instance
, self
.__name
, value
.decode('utf-8', 'replace'))
96 elif isinstance(value
, str):
97 setattr(instance
, self
.__name
, value
)
99 raise TypeError('{} attribute must be a unicode or bytes instance, '
100 'but was {}.'.format(self
.__name
, type(value
)))
102 def __delete__(self
, instance
):
103 raise NotImplementedError
106 class TimeAttribute(object):
107 """Attribute of TestResult for time.
109 This attribute provides a couple of nice helpers. It stores the start and
110 end time and provides methods for getting the total and delta of the times.
113 __slots__
= ['start', 'end']
115 def __init__(self
, start
=0.0, end
=0.0):
121 return self
.end
- self
.start
125 return str(datetime
.timedelta(seconds
=self
.total
))
131 '__type__': 'TimeAttribute',
135 def from_dict(cls
, dict_
):
136 dict_
= copy
.copy(dict_
)
138 if '__type__' in dict_
:
139 del dict_
['__type__']
143 class TestResult(object):
144 """An object representing the result of a single test."""
145 __slots__
= ['returncode', '_err', '_out', 'time', 'command', 'traceback',
146 'environment', 'subtests', 'dmesg', '__result', 'images',
148 err
= StringDescriptor('_err')
149 out
= StringDescriptor('_out')
151 def __init__(self
, result
=None):
152 self
.returncode
= None
153 self
.time
= TimeAttribute()
155 self
.environment
= str()
156 self
.subtests
= Subtests()
159 self
.traceback
= None
160 self
.exception
= None
165 self
.__result
= status
.NOTRUN
169 """Return the result of the test.
171 If there are subtests return the "worst" value of those subtests. If
172 there are not return the stored value of the test. There is an
173 exception to this rule, and that's if the status is crash; since this
174 status is set by the framework, and can be generated even when some or
178 if self
.subtests
and self
.__result
!= status
.CRASH
:
179 return max(self
.subtests
.values())
183 def raw_result(self
):
184 """Get the result of the test without taking subtests into account."""
188 def result(self
, new
):
190 self
.__result
= status
.status_lookup(new
)
191 except exceptions
.PiglitInternalError
as e
:
192 raise exceptions
.PiglitFatalError(str(e
))
195 """Return the TestResult as a json serializable object."""
197 '__type__': 'TestResult',
198 'command': self
.command
,
199 'environment': self
.environment
,
202 'result': self
.result
,
203 'returncode': self
.returncode
,
204 'subtests': self
.subtests
.to_json(),
205 'time': self
.time
.to_json(),
206 'exception': self
.exception
,
207 'traceback': self
.traceback
,
209 'images': self
.images
,
215 def from_dict(cls
, dict_
):
216 """Load an already generated result in dictionary form.
218 This is used as an alternate constructor which converts an existing
219 dictionary into a TestResult object. It converts a key 'result' into a
223 # pylint will say that assining to inst.out or inst.err is a non-slot
224 # because self.err and self.out are descriptors, methods that act like
225 # variables. Just silence pylint
226 # pylint: disable=assigning-non-slot
229 for each
in ['returncode', 'command', 'exception', 'environment',
230 'traceback', 'dmesg', 'images', 'pid', 'result']:
232 setattr(inst
, each
, dict_
[each
])
234 # Set special instances
235 if 'subtests' in dict_
:
236 inst
.subtests
= Subtests
.from_dict(dict_
['subtests'])
238 inst
.time
= TimeAttribute
.from_dict(dict_
['time'])
240 # out and err must be set manually to avoid replacing the setter
242 inst
.out
= dict_
['out']
244 inst
.err
= dict_
['err']
248 def update(self
, dict_
):
249 """Update the results and subtests fields from a piglit test.
251 Native piglit tests output their data as valid json, and piglit uses
252 the json module to parse this data. This method consumes that raw
253 dictionary data and updates itself.
256 if 'result' in dict_
:
257 self
.result
= dict_
['result']
258 if 'images' in dict_
:
259 self
.images
= dict_
['images']
260 elif 'subtest' in dict_
:
261 self
.subtests
.update(dict_
['subtest'])
265 def __init__(self
, *args
, **kwargs
):
266 super(Totals
, self
).__init
__(*args
, **kwargs
)
267 for each
in status
.ALL
:
273 # Since totals are prepopulated, calling 'if not <Totals instance>'
274 # will always result in True, this will cause it to return True only if
275 # one of the values is not zero
276 for each
in self
.values():
282 """Convert totals to a json object."""
283 result
= copy
.copy(self
)
284 result
['__type__'] = 'Totals'
288 def from_dict(cls
, dict_
):
289 """Convert a dictionary into a Totals object."""
291 if '__type__' in tots
:
296 class TestrunResult(object):
297 """The result of a single piglit run."""
301 self
.time_elapsed
= TimeAttribute()
302 self
.tests
= collections
.OrderedDict()
303 self
.totals
= collections
.defaultdict(Totals
)
305 def get_result(self
, key
):
306 """Get the result of a test or subtest.
308 If neither a test nor a subtest instance exist, then raise the original
309 KeyError generated from looking up <key> in the tests attribute. It is
310 the job of the caller to handle this error.
313 key -- the key name of the test to return
317 return self
.tests
[key
].result
318 except KeyError as e
:
319 name
, test
= grouptools
.splitname(key
)
321 return self
.tests
[name
].subtests
[test
]
325 def calculate_group_totals(self
):
326 """Calculate the number of passes, fails, etc at each level."""
327 for name
, result
in self
.tests
.items():
328 # If there are subtests treat the test as if it is a group instead
331 for res
in result
.subtests
.values():
335 self
.totals
[temp
][res
] += 1
337 temp
= grouptools
.groupname(temp
)
338 self
.totals
[temp
][res
] += 1
339 self
.totals
['root'][res
] += 1
341 res
= str(result
.result
)
343 name
= grouptools
.groupname(name
)
344 self
.totals
[name
][res
] += 1
345 self
.totals
['root'][res
] += 1
349 self
.calculate_group_totals()
350 rep
= copy
.copy(self
.__dict
__)
351 rep
['tests'] = collections
.OrderedDict((k
, t
.to_json())
352 for k
, t
in self
.tests
.items())
353 rep
['__type__'] = 'TestrunResult'
357 def from_dict(cls
, dict_
, _no_totals
=False):
358 """Convert a dictionary into a TestrunResult.
360 This method is meant to be used for loading results from json or
363 _no_totals is not meant to be used externally, it allows us to control
364 the generation of totals when loading old results formats.
368 for name
in ['name', 'info', 'options', 'results_version']:
369 value
= dict_
.get(name
)
371 setattr(res
, name
, value
)
373 # Since this is used to load partial metadata when writing final test
374 # results there is no guarantee that this will have a "time_elapsed"
376 if 'time_elapsed' in dict_
:
377 setattr(res
, 'time_elapsed',
378 TimeAttribute
.from_dict(dict_
['time_elapsed']))
379 res
.tests
= collections
.OrderedDict((n
, TestResult
.from_dict(t
))
380 for n
, t
in dict_
['tests'].items())
382 if not 'totals' in dict_
and not _no_totals
:
383 res
.calculate_group_totals()
385 res
.totals
= {n
: Totals
.from_dict(t
) for n
, t
in
386 dict_
['totals'].items()}