Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / chromite / scripts / gather_builder_stats_unittest.py
1 #!/usr/bin/python
2
3 # Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
6
7 """Unit tests for gather_builder_stats."""
8
9 import datetime
10 import itertools
11 import os
12 import random
13 import sys
14 import unittest
15
16 sys.path.insert(0, os.path.abspath('%s/../..' % os.path.dirname(__file__)))
17 from chromite.lib import cros_build_lib
18 from chromite.lib import cros_test_lib
19 from chromite.scripts import gather_builder_stats
20 from chromite.cbuildbot import metadata_lib
21 from chromite.cbuildbot import constants
22
23 import mock
24
25
26 REASON_BAD_CL = gather_builder_stats.CLStats.REASON_BAD_CL
27 CQ = constants.CQ
28 PRE_CQ = constants.PRE_CQ
29
30
31 class TestCLActionLogic(unittest.TestCase):
32   """Ensures that CL action analysis logic is correct."""
33
34   def _getTestBuildData(self, cq):
35     """Generate a return test data.
36
37     Args:
38       cq: Whether this is a CQ run. If False, this is a Pre-CQ run.
39
40     Returns:
41       A list of metadata_lib.BuildData objects to use as
42       test data for CL action summary logic.
43     """
44     # Mock patches for test data.
45     c1p1 = metadata_lib.GerritPatchTuple(1, 1, False)
46     c2p1 = metadata_lib.GerritPatchTuple(2, 1, True)
47     c2p2 = metadata_lib.GerritPatchTuple(2, 2, True)
48     c3p1 = metadata_lib.GerritPatchTuple(3, 1, True)
49     c3p2 = metadata_lib.GerritPatchTuple(3, 2, True)
50     c4p1 = metadata_lib.GerritPatchTuple(4, 1, True)
51     c4p2 = metadata_lib.GerritPatchTuple(4, 2, True)
52
53     # Mock builder status dictionaries
54     passed_status = {'status' : constants.FINAL_STATUS_PASSED}
55     failed_status = {'status' : constants.FINAL_STATUS_FAILED}
56
57     t = itertools.count()
58     bot_config = constants.CQ_MASTER if cq else constants.PRE_CQ_GROUP
59
60     # pylint: disable=W0212
61     TEST_METADATA = [
62       # Build 1 picks up no patches.
63       metadata_lib.CBuildbotMetadata(
64           ).UpdateWithDict({'build-number' : 1,
65                             'bot-config' : bot_config,
66                             'results' : [],
67                             'status' : passed_status}),
68       # Build 2 picks up c1p1 and does nothing.
69       metadata_lib.CBuildbotMetadata(
70           ).UpdateWithDict({'build-number' : 2,
71                             'bot-config' : bot_config,
72                             'results' : [],
73                             'status' : failed_status,
74                             'changes': [c1p1._asdict()]}
75           ).RecordCLAction(c1p1, constants.CL_ACTION_PICKED_UP, t.next()),
76       # Build 3 picks up c1p1 and c2p1 and rejects both.
77       # c3p1 is not included in the run because it fails to apply.
78       metadata_lib.CBuildbotMetadata(
79           ).UpdateWithDict({'build-number' : 3,
80                             'bot-config' : bot_config,
81                             'results' : [],
82                             'status' : failed_status,
83                             'changes': [c1p1._asdict(),
84                                         c2p1._asdict()]}
85           ).RecordCLAction(c1p1, constants.CL_ACTION_PICKED_UP, t.next()
86           ).RecordCLAction(c2p1, constants.CL_ACTION_PICKED_UP, t.next()
87           ).RecordCLAction(c1p1, constants.CL_ACTION_KICKED_OUT, t.next()
88           ).RecordCLAction(c2p1, constants.CL_ACTION_KICKED_OUT, t.next()
89           ).RecordCLAction(c3p1, constants.CL_ACTION_KICKED_OUT, t.next()),
90       # Build 4 picks up c4p1 and rejects it.
91       metadata_lib.CBuildbotMetadata(
92           ).UpdateWithDict({'build-number' : 3,
93                             'bot-config' : bot_config,
94                             'results' : [],
95                             'status' : failed_status,
96                             'changes': [c4p1._asdict()]}
97           ).RecordCLAction(c4p2, constants.CL_ACTION_PICKED_UP, t.next()
98           ).RecordCLAction(c4p2, constants.CL_ACTION_KICKED_OUT, t.next()),
99     ]
100     if cq:
101       TEST_METADATA += [
102         # Build 4 picks up c1p1 and c2p2 and submits both.
103         # So  c1p1 should be detected as a 1-time rejected good patch,
104         # and c2p1 should be detected as a possibly bad patch.
105         metadata_lib.CBuildbotMetadata(
106             ).UpdateWithDict({'build-number' : 4,
107                               'bot-config' : bot_config,
108                               'results' : [],
109                               'status' : passed_status,
110                               'changes': [c1p1._asdict(),
111                                           c2p2._asdict()]}
112             ).RecordCLAction(c1p1, constants.CL_ACTION_PICKED_UP, t.next()
113             ).RecordCLAction(c2p2, constants.CL_ACTION_PICKED_UP, t.next()
114             ).RecordCLAction(c3p2, constants.CL_ACTION_PICKED_UP, t.next()
115             ).RecordCLAction(c4p1, constants.CL_ACTION_PICKED_UP, t.next()
116             ).RecordCLAction(c1p1, constants.CL_ACTION_SUBMITTED, t.next()
117             ).RecordCLAction(c2p2, constants.CL_ACTION_SUBMITTED, t.next()
118             ).RecordCLAction(c3p2, constants.CL_ACTION_SUBMITTED, t.next()
119             ).RecordCLAction(c4p2, constants.CL_ACTION_SUBMITTED, t.next()),
120       ]
121     else:
122       TEST_METADATA += [
123         metadata_lib.CBuildbotMetadata(
124             ).UpdateWithDict({'build-number' : 5,
125                               'bot-config' : bot_config,
126                               'results' : [],
127                               'status' : failed_status,
128                               'changes': [c4p1._asdict()]}
129             ).RecordCLAction(c4p1, constants.CL_ACTION_PICKED_UP, t.next()
130             ).RecordCLAction(c4p1, constants.CL_ACTION_KICKED_OUT, t.next()),
131         metadata_lib.CBuildbotMetadata(
132             ).UpdateWithDict({'build-number' : 6,
133                               'bot-config' : bot_config,
134                               'results' : [],
135                               'status' : failed_status,
136                               'changes': [c4p1._asdict()]}
137             ).RecordCLAction(c1p1, constants.CL_ACTION_PICKED_UP, t.next()
138             ).RecordCLAction(c1p1, constants.CL_ACTION_KICKED_OUT, t.next())
139       ]
140     # pylint: enable=W0212
141
142     # TEST_METADATA should not be guaranteed to be ordered by build number
143     # so shuffle it, but use the same seed each time so that unit test is
144     # deterministic.
145     random.seed(0)
146     random.shuffle(TEST_METADATA)
147
148     # Wrap the test metadata into BuildData objects.
149     TEST_BUILDDATA = [metadata_lib.BuildData('', d.GetDict())
150                       for d in TEST_METADATA]
151
152     return TEST_BUILDDATA
153
154
155   def testCLStatsSummary(self):
156     with cros_build_lib.ContextManagerStack() as stack:
157       pre_cq_builddata = self._getTestBuildData(cq=False)
158       cq_builddata = self._getTestBuildData(cq=True)
159       stack.Add(mock.patch.object, gather_builder_stats.StatsManager,
160                 '_FetchBuildData', side_effect=[cq_builddata, pre_cq_builddata])
161       stack.Add(mock.patch.object, gather_builder_stats, '_PrepareCreds')
162       stack.Add(mock.patch.object, gather_builder_stats.CLStats,
163                 'GatherFailureReasons')
164       cl_stats = gather_builder_stats.CLStats('foo@bar.com')
165       cl_stats.Gather(datetime.date.today())
166       cl_stats.reasons = {1: '', 2: '', 3: REASON_BAD_CL, 4: REASON_BAD_CL}
167       cl_stats.blames =  {1: '', 2: '', 3: 'crosreview.com/1',
168                           4: 'crosreview.com/1'}
169       summary = cl_stats.Summarize()
170
171       expected = {
172           'mean_good_patch_rejections': 0.5,
173           'unique_patches': 7,
174           'unique_blames_change_count': 0,
175           'total_cl_actions': 28,
176           'good_patch_rejection_breakdown': [(0, 3), (1, 0), (2, 1)],
177           'good_patch_rejection_count': {CQ: 1, PRE_CQ: 1},
178           'good_patch_rejections': 2,
179           'false_rejection_rate': {CQ: 20., PRE_CQ: 20., 'combined': 100./3,},
180           'submitted_patches': 4,
181           'submit_fails': 0,
182           'unique_cls': 4,
183           'median_handling_time': -1, # This will be ignored in comparison
184           'patch_handling_time': -1,  # This will be ignored in comparison
185           'bad_cl_candidates': {
186               CQ: [metadata_lib.GerritChangeTuple(gerrit_number=2,
187                                                   internal=True)],
188               PRE_CQ: [metadata_lib.GerritChangeTuple(gerrit_number=2,
189                                                       internal=True),
190                        metadata_lib.GerritChangeTuple(gerrit_number=4,
191                                                       internal=True)],
192           },
193           'correctly_rejected_by_stage': {CQ: {}, PRE_CQ: {}},
194           'incorrectly_rejected_by_stage': {PRE_CQ: {}},
195           'rejections': 10}
196       # Ignore handling times in comparison, since these are not fully
197       # reproducible from run to run of the unit test.
198       summary['median_handling_time'] = expected['median_handling_time']
199       summary['patch_handling_time'] = expected['patch_handling_time']
200       self.maxDiff = None
201       self.assertEqual(summary, expected)
202
203   def testProcessBlameString(self):
204     """Tests that bug and CL links are correctly parsed."""
205     blame = ('some words then crbug.com/1234, then other junk and '
206              'https://code.google.com/p/chromium/issues/detail?id=4321 '
207              'then some stuff and other stuff and b/2345 and also '
208              'https://b.corp.google.com/issue?id=5432&query=5432 '
209              'and then some crosreview.com/3456 or some '
210              'https://chromium-review.googlesource.com/#/c/6543/ and '
211              'then crosreview.com/i/9876 followed by '
212              'https://chrome-internal-review.googlesource.com/#/c/6789/ '
213              'blah https://gutsv3.corp.google.com/#ticket/1234 t/4321')
214     expected = ['crbug.com/1234',
215                 'crbug.com/4321',
216                 'b/2345',
217                 'b/5432',
218                 'crosreview.com/3456',
219                 'crosreview.com/6543',
220                 'crosreview.com/i/9876',
221                 'crosreview.com/i/6789',
222                 't/1234',
223                 't/4321']
224     self.assertEqual(gather_builder_stats.CLStats.ProcessBlameString(blame),
225                      expected)
226
227
228 if __name__ == '__main__':
229   cros_test_lib.main()