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
|
#!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from typing import Iterable, Optional
import unittest
from unittest import mock
# //testing imports.
from unexpected_passes_common import builders
from unexpected_passes_common import constants
from unexpected_passes_common import data_types
from unexpected_passes_common import expectations
from unexpected_passes_common import queries
from unexpected_passes_common import unittest_utils as uu
# Protected access is allowed for unittests.
# pylint: disable=protected-access
class HelperMethodUnittest(unittest.TestCase):
def testStripPrefixFromBuildIdValidId(self) -> None:
self.assertEqual(queries._StripPrefixFromBuildId('build-1'), '1')
def testStripPrefixFromBuildIdInvalidId(self) -> None:
with self.assertRaises(AssertionError):
queries._StripPrefixFromBuildId('build1')
with self.assertRaises(AssertionError):
queries._StripPrefixFromBuildId('build-1-2')
def testConvertActualResultToExpectationFileFormatAbort(self) -> None:
self.assertEqual(
queries._ConvertActualResultToExpectationFileFormat('ABORT'), 'Timeout')
class BigQueryQuerierInitUnittest(unittest.TestCase):
def testInvalidNumSamples(self):
"""Tests that the number of samples is validated."""
with self.assertRaises(AssertionError):
uu.CreateGenericQuerier(num_samples=-1)
def testDefaultSamples(self):
"""Tests that the number of samples is set to a default if not provided."""
querier = uu.CreateGenericQuerier(num_samples=0)
self.assertGreater(querier._num_samples, 0)
class GetBuilderGroupedQueryResultsUnittest(unittest.TestCase):
def setUp(self):
builders.ClearInstance()
expectations.ClearInstance()
uu.RegisterGenericBuildersImplementation()
uu.RegisterGenericExpectationsImplementation()
self._querier = uu.CreateGenericQuerier()
def testUnknownBuilderType(self):
"""Tests behavior when an unknown builder type is provided."""
with self.assertRaisesRegex(RuntimeError, 'Unknown builder type unknown'):
for _ in self._querier.GetBuilderGroupedQueryResults('unknown', False):
pass
def testQueryRouting(self):
"""Tests that the correct query is used based on inputs."""
with mock.patch.object(self._querier,
'_GetPublicCiQuery',
return_value='public_ci') as public_ci_mock:
with mock.patch.object(self._querier,
'_GetInternalCiQuery',
return_value='internal_ci') as internal_ci_mock:
with mock.patch.object(self._querier,
'_GetPublicTryQuery',
return_value='public_try') as public_try_mock:
with mock.patch.object(
self._querier,
'_GetInternalTryQuery',
return_value='internal_try') as internal_try_mock:
all_mocks = [
public_ci_mock,
internal_ci_mock,
public_try_mock,
internal_try_mock,
]
inputs = [
(constants.BuilderTypes.CI, False, public_ci_mock),
(constants.BuilderTypes.CI, True, internal_ci_mock),
(constants.BuilderTypes.TRY, False, public_try_mock),
(constants.BuilderTypes.TRY, True, internal_try_mock),
]
for builder_type, internal_status, called_mock in inputs:
for _ in self._querier.GetBuilderGroupedQueryResults(
builder_type, internal_status):
pass
for m in all_mocks:
if m == called_mock:
m.assert_called_once()
else:
m.assert_not_called()
for m in all_mocks:
m.reset_mock()
def testNoResults(self):
"""Tests functionality if the query returns no results."""
returned_builders = []
with self.assertLogs(level='WARNING') as log_manager:
with mock.patch.object(self._querier,
'_GetPublicCiQuery',
return_value=''):
for builder_name, _, _ in self._querier.GetBuilderGroupedQueryResults(
constants.BuilderTypes.CI, False):
returned_builders.append(builder_name)
for message in log_manager.output:
if ('Did not get any results for builder type ci and internal status '
'False. Depending on where tests are run and how frequently '
'trybots are used for submission, this may be benign') in message:
break
else:
self.fail('Did not find expected log message: %s' % log_manager.output)
self.assertEqual(len(returned_builders), 0)
def testHappyPath(self):
"""Tests functionality in the happy path."""
self._querier.query_results = [
uu.FakeQueryResult(builder_name='builder_a',
id_='build-a',
test_id='test_a',
status='PASS',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a'),
uu.FakeQueryResult(builder_name='builder_b',
id_='build-b',
test_id='test_b',
status='FAIL',
typ_tags=['win'],
step_name='step_b'),
]
expected_results = [
('builder_a',
[data_types.BaseResult('test_a', ('linux', ), 'Pass', 'step_a',
'a')], None),
('builder_b',
[data_types.BaseResult('test_b', ('win', ), 'Failure', 'step_b',
'b')], None),
]
results = []
with mock.patch.object(self._querier, '_GetPublicCiQuery', return_value=''):
for builder_name, result_list, expectation_files in (
self._querier.GetBuilderGroupedQueryResults(constants.BuilderTypes.CI,
False)):
results.append((builder_name, result_list, expectation_files))
self.assertEqual(results, expected_results)
def testHappyPathWithExpectationFiles(self):
"""Tests functionality in the happy path with expectation files provided."""
self._querier.query_results = [
uu.FakeQueryResult(builder_name='builder_a',
id_='build-a',
test_id='test_a',
status='PASS',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a'),
uu.FakeQueryResult(builder_name='builder_b',
id_='build-b',
test_id='test_b',
status='FAIL',
typ_tags=['win'],
step_name='step_b'),
]
expected_results = [
('builder_a',
[data_types.BaseResult('test_a', ('linux', ), 'Pass', 'step_a',
'a')], list(set(['ef_a']))),
('builder_b',
[data_types.BaseResult('test_b', ('win', ), 'Failure', 'step_b',
'b')], list(set(['ef_b', 'ef_c']))),
]
results = []
with mock.patch.object(self._querier,
'_GetRelevantExpectationFilesForQueryResult',
side_effect=(['ef_a'], ['ef_b', 'ef_c'])):
with mock.patch.object(self._querier,
'_GetPublicCiQuery',
return_value=''):
for builder_name, result_list, expectation_files in (
self._querier.GetBuilderGroupedQueryResults(
constants.BuilderTypes.CI, False)):
results.append((builder_name, result_list, expectation_files))
self.assertEqual(results, expected_results)
class FillExpectationMapForBuildersUnittest(unittest.TestCase):
def setUp(self) -> None:
self._querier = uu.CreateGenericQuerier()
expectations.ClearInstance()
uu.RegisterGenericExpectationsImplementation()
def testErrorOnMixedBuilders(self) -> None:
"""Tests that providing builders of mixed type is an error."""
builders_to_fill = [
data_types.BuilderEntry('ci_builder', constants.BuilderTypes.CI, False),
data_types.BuilderEntry('try_builder', constants.BuilderTypes.TRY,
False)
]
with self.assertRaises(AssertionError):
self._querier.FillExpectationMapForBuilders(
data_types.TestExpectationMap({}), builders_to_fill)
def _runValidResultsTest(self, keep_unmatched_results: bool) -> None:
self._querier = uu.CreateGenericQuerier(
keep_unmatched_results=keep_unmatched_results)
public_results = [
uu.FakeQueryResult(builder_name='matched_builder',
id_='build-build_id',
test_id='foo',
status='PASS',
typ_tags=['win'],
step_name='step_name'),
uu.FakeQueryResult(builder_name='unmatched_builder',
id_='build-build_id',
test_id='bar',
status='PASS',
typ_tags=[],
step_name='step_name'),
uu.FakeQueryResult(builder_name='extra_builder',
id_='build-build_id',
test_id='foo',
status='PASS',
typ_tags=['win'],
step_name='step_name'),
]
internal_results = [
uu.FakeQueryResult(builder_name='matched_internal',
id_='build-build_id',
test_id='foo',
status='PASS',
typ_tags=['win'],
step_name='step_name_internal'),
uu.FakeQueryResult(builder_name='unmatched_internal',
id_='build-build_id',
test_id='bar',
status='PASS',
typ_tags=[],
step_name='step_name_internal'),
]
builders_to_fill = [
data_types.BuilderEntry('matched_builder', constants.BuilderTypes.CI,
False),
data_types.BuilderEntry('unmatched_builder', constants.BuilderTypes.CI,
False),
data_types.BuilderEntry('matched_internal', constants.BuilderTypes.CI,
True),
data_types.BuilderEntry('unmatched_internal', constants.BuilderTypes.CI,
True),
]
expectation = data_types.Expectation('foo', ['win'], 'RetryOnFailure',
data_types.WildcardType.NON_WILDCARD)
expectation_map = data_types.TestExpectationMap({
'foo':
data_types.ExpectationBuilderMap({
expectation:
data_types.BuilderStepMap(),
}),
})
def PublicSideEffect():
self._querier.query_results = public_results
return ''
def InternalSideEffect():
self._querier.query_results = internal_results
return ''
with self.assertLogs(level='WARNING') as log_manager:
with mock.patch.object(self._querier,
'_GetPublicCiQuery',
side_effect=PublicSideEffect) as public_mock:
with mock.patch.object(self._querier,
'_GetInternalCiQuery',
side_effect=InternalSideEffect) as internal_mock:
unmatched_results = self._querier.FillExpectationMapForBuilders(
expectation_map, builders_to_fill)
public_mock.assert_called_once()
internal_mock.assert_called_once()
for message in log_manager.output:
if ('Did not find a matching builder for name extra_builder and '
'internal status False. This is normal if the builder is no longer '
'running tests (e.g. it was experimental).') in message:
break
else:
self.fail('Did not find expected log message')
stats = data_types.BuildStats()
stats.AddPassedBuild(frozenset(['win']))
expected_expectation_map = {
'foo': {
expectation: {
'chromium/ci:matched_builder': {
'step_name': stats,
},
'chrome/ci:matched_internal': {
'step_name_internal': stats,
},
},
},
}
self.assertEqual(expectation_map, expected_expectation_map)
if keep_unmatched_results:
self.assertEqual(
unmatched_results, {
'chromium/ci:unmatched_builder': [
data_types.Result('bar', [], 'Pass', 'step_name', 'build_id'),
],
'chrome/ci:unmatched_internal': [
data_types.Result('bar', [], 'Pass', 'step_name_internal',
'build_id'),
],
})
else:
self.assertEqual(unmatched_results, {})
def testValidResultsKeepUnmatched(self) -> None:
"""Tests behavior w/ valid results and keeping unmatched results."""
self._runValidResultsTest(True)
def testValidResultsDoNotKeepUnmatched(self) -> None:
"""Tests behavior w/ valid results and not keeping unmatched results."""
self._runValidResultsTest(False)
class ProcessRowsForBuilderUnittest(unittest.TestCase):
def setUp(self):
self._querier = uu.CreateGenericQuerier()
def testHappyPathWithExpectationFiles(self):
"""Tests functionality along the happy path with expectation files."""
def SideEffect(row: queries.QueryResult) -> Optional[Iterable[str]]:
if row.step_name == 'step_a1':
return ['ef_a1']
if row.step_name == 'step_a2':
return ['ef_a2']
if row.step_name == 'step_b':
return ['ef_b1', 'ef_b2']
raise RuntimeError('Unexpected row')
rows = [
uu.FakeQueryResult(builder_name='unused',
id_='build-a',
test_id='test_a',
status='PASS',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a1'),
uu.FakeQueryResult(builder_name='unused',
id_='build-a',
test_id='test_a',
status='FAIL',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a2'),
uu.FakeQueryResult(builder_name='unused',
id_='build-b',
test_id='test_b',
status='FAIL',
typ_tags=['win'],
step_name='step_b'),
]
# Reversed order is expected since results are popped.
expected_results = [
data_types.BaseResult(test='test_b',
tags=['win'],
actual_result='Failure',
step='step_b',
build_id='b'),
data_types.BaseResult(test='test_a',
tags=['linux'],
actual_result='Failure',
step='step_a2',
build_id='a'),
data_types.BaseResult(test='test_a',
tags=['linux'],
actual_result='Pass',
step='step_a1',
build_id='a'),
]
with mock.patch.object(self._querier,
'_GetRelevantExpectationFilesForQueryResult',
side_effect=SideEffect):
results, expectation_files = self._querier._ProcessRowsForBuilder(rows)
self.assertEqual(results, expected_results)
self.assertEqual(len(expectation_files), len(set(expectation_files)))
self.assertEqual(set(expectation_files),
set(['ef_a1', 'ef_a2', 'ef_b1', 'ef_b2']))
def testHappyPathNoneExpectation(self):
"""Tests functionality along the happy path with a None expectation file."""
# A single None expectation file should cause the resulting return value to
# become None.
def SideEffect(row: queries.QueryResult) -> Optional[Iterable[str]]:
if row.step_name == 'step_a1':
return ['ef_a1']
if row.step_name == 'step_a2':
return ['ef_a2']
return None
rows = [
uu.FakeQueryResult(builder_name='unused',
id_='build-a',
test_id='test_a',
status='PASS',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a1'),
uu.FakeQueryResult(builder_name='unused',
id_='build-a',
test_id='test_a',
status='FAIL',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a2'),
uu.FakeQueryResult(builder_name='unused',
id_='build-b',
test_id='test_b',
status='FAIL',
typ_tags=['win'],
step_name='step_b'),
]
# Reversed order is expected since results are popped.
expected_results = [
data_types.BaseResult(test='test_b',
tags=['win'],
actual_result='Failure',
step='step_b',
build_id='b'),
data_types.BaseResult(test='test_a',
tags=['linux'],
actual_result='Failure',
step='step_a2',
build_id='a'),
data_types.BaseResult(test='test_a',
tags=['linux'],
actual_result='Pass',
step='step_a1',
build_id='a'),
]
with mock.patch.object(self._querier,
'_GetRelevantExpectationFilesForQueryResult',
side_effect=SideEffect):
results, expectation_files = self._querier._ProcessRowsForBuilder(rows)
self.assertEqual(results, expected_results)
self.assertEqual(expectation_files, None)
def testHappyPathSkippedResult(self):
"""Tests functionality along the happy path with a skipped result."""
def SideEffect(row: queries.QueryResult) -> bool:
if row.step_name == 'step_b':
return True
return False
rows = [
uu.FakeQueryResult(builder_name='unused',
id_='build-a',
test_id='test_a',
status='PASS',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a1'),
uu.FakeQueryResult(builder_name='unused',
id_='build-a',
test_id='test_a',
status='FAIL',
typ_tags=['linux', 'unknown_tag'],
step_name='step_a2'),
uu.FakeQueryResult(builder_name='unused',
id_='build-b',
test_id='test_b',
status='FAIL',
typ_tags=['win'],
step_name='step_b'),
]
# Reversed order is expected since results are popped.
expected_results = [
data_types.BaseResult(test='test_a',
tags=['linux'],
actual_result='Failure',
step='step_a2',
build_id='a'),
data_types.BaseResult(test='test_a',
tags=['linux'],
actual_result='Pass',
step='step_a1',
build_id='a'),
]
with mock.patch.object(self._querier,
'_ShouldSkipOverResult',
side_effect=SideEffect):
results, expectation_files = self._querier._ProcessRowsForBuilder(rows)
self.assertEqual(results, expected_results)
self.assertEqual(expectation_files, None)
if __name__ == '__main__':
unittest.main(verbosity=2)
|