blob: 9b3cdb068a34a497a1fcadd522572d460953a023 [file] [log] [blame]
Edward Lemur0db01f02019-11-12 22:01:51 +00001#!/usr/bin/env vpython3
2# coding=utf-8
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00003# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004# 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 git_cl.py."""
8
Edward Lemur85153282020-02-14 22:06:29 +00009from __future__ import print_function
Edward Lemur0db01f02019-11-12 22:01:51 +000010from __future__ import unicode_literals
11
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +010012import datetime
tandriide281ae2016-10-12 06:02:30 -070013import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010014import logging
Edward Lemur61bf4172020-02-24 23:22:37 +000015import multiprocessing
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000016import optparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000017import os
Edward Lemur85153282020-02-14 22:06:29 +000018import pprint
Brian Sheedy59b06a82019-10-14 17:03:29 +000019import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000020import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070021import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000022import unittest
23
Edward Lemura8145022020-01-06 18:47:54 +000024if sys.version_info.major == 2:
25 from StringIO import StringIO
26 import mock
27else:
28 from io import StringIO
29 from unittest import mock
30
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
32
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000033import metrics
34# We have to disable monitoring before importing git_cl.
35metrics.DISABLE_METRICS_COLLECTION = True
36
Jamie Madill5e96ad12020-01-13 16:08:35 +000037import clang_format
Edward Lemur227d5102020-02-25 23:45:35 +000038import contextlib
Edward Lemur1773f372020-02-22 00:27:14 +000039import gclient_utils
Eric Boren2fb63102018-10-05 13:05:03 +000040import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000041import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000042import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000043import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000044import git_new_branch
45import scm
maruel@chromium.orgddd59412011-11-30 14:20:38 +000046import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000047
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000048
Edward Lemur0db01f02019-11-12 22:01:51 +000049def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070050 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
51
tandrii5d48c322016-08-18 16:19:37 -070052CERR1 = callError(1)
53
54
Edward Lemur1773f372020-02-22 00:27:14 +000055class TemporaryFileMock(object):
56 def __init__(self):
57 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070058
Edward Lemur1773f372020-02-22 00:27:14 +000059 @contextlib.contextmanager
60 def __call__(self):
61 self.suffix += 1
62 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070063
64
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000065class ChangelistMock(object):
66 # A class variable so we can access it when we don't have access to the
67 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000068 desc = ''
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000069
70 def __init__(self, gerrit_change=None, **kwargs):
71 self._gerrit_change = gerrit_change
72
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000073 def GetIssue(self):
74 return 1
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000075
Edward Lemur6c6827c2020-02-06 21:15:18 +000076 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000077 return ChangelistMock.desc
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000078
dsansomee2d6fd92016-09-08 00:10:47 -070079 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000080 ChangelistMock.desc = desc
81
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000082 def GetGerritChange(self, patchset=None, **kwargs):
83 del patchset
84 return self._gerrit_change
85
tandrii5d48c322016-08-18 16:19:37 -070086
Edward Lemur85153282020-02-14 22:06:29 +000087class GitMocks(object):
88 def __init__(self, config=None, branchref=None):
89 self.branchref = branchref or 'refs/heads/master'
90 self.config = config or {}
91
92 def GetBranchRef(self, _root):
93 return self.branchref
94
95 def NewBranch(self, branchref):
96 self.branchref = branchref
97
Edward Lemur26964072020-02-19 19:18:51 +000098 def GetConfig(self, root, key, default=None):
99 if root != '':
100 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000101 return self.config.get(key, default)
102
Edward Lemur26964072020-02-19 19:18:51 +0000103 def SetConfig(self, root, key, value=None):
104 if root != '':
105 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000106 if value:
107 self.config[key] = value
108 return
109 if key not in self.config:
110 raise CERR1
111 del self.config[key]
112
113
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000114class WatchlistsMock(object):
115 def __init__(self, _):
116 pass
117 @staticmethod
118 def GetWatchersForPaths(_):
119 return ['joe@example.com']
120
121
Edward Lemur4c707a22019-09-24 21:13:43 +0000122class CodereviewSettingsFileMock(object):
123 def __init__(self):
124 pass
125 # pylint: disable=no-self-use
126 def read(self):
127 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
128 'GERRIT_HOST: True\n')
129
130
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000131class AuthenticatorMock(object):
132 def __init__(self, *_args):
133 pass
134 def has_cached_credentials(self):
135 return True
tandrii221ab252016-10-06 08:12:04 -0700136 def authorize(self, http):
137 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000138
139
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100140def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000141 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
142
143 Usage:
144 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100145 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000146
147 OR
148 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100149 CookiesAuthenticatorMockFactory(
150 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000151 """
152 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800153 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000154 # Intentionally not calling super() because it reads actual cookie files.
155 pass
156 @classmethod
157 def get_gitcookies_path(cls):
158 return '~/.gitcookies'
159 @classmethod
160 def get_netrc_path(cls):
161 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100162 def _get_auth_for_host(self, host):
163 if same_auth:
164 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000165 return (hosts_with_creds or {}).get(host)
166 return CookiesAuthenticatorMock
167
Aaron Gable9a03ae02017-11-03 11:31:07 -0700168
kmarshall9249e012016-08-23 12:02:16 -0700169class MockChangelistWithBranchAndIssue():
170 def __init__(self, branch, issue):
171 self.branch = branch
172 self.issue = issue
173 def GetBranch(self):
174 return self.branch
175 def GetIssue(self):
176 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000177
tandriic2405f52016-10-10 08:13:15 -0700178
179class SystemExitMock(Exception):
180 pass
181
182
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000183class TestGitClBasic(unittest.TestCase):
Josip Sokcevic953278a2020-02-28 19:46:36 +0000184 def setUp(self):
185 mock.patch('sys.exit', side_effect=SystemExitMock).start()
186 mock.patch('sys.stdout', StringIO()).start()
187 mock.patch('sys.stderr', StringIO()).start()
188 self.addCleanup(mock.patch.stopall)
189
190 def test_die_with_error(self):
191 with self.assertRaises(SystemExitMock):
192 git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
193 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
194 self.assertTrue('saving CL description' in sys.stdout.getvalue())
195 self.assertTrue('Content of CL description' in sys.stdout.getvalue())
196 self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
197 sys.exit.assert_called_once_with(1)
198
199 def test_die_with_error_no_desc(self):
200 with self.assertRaises(SystemExitMock):
201 git_cl.DieWithError('foo')
202 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
203 self.assertEqual(sys.stdout.getvalue(), '')
204 sys.exit.assert_called_once_with(1)
205
Edward Lemur6c6827c2020-02-06 21:15:18 +0000206 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000207 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100208 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000209 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700210
Edward Lemur61bf4172020-02-24 23:22:37 +0000211 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
212 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
213 def test_get_cl_statuses(self, *_mocks):
214 statuses = [
215 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
216 changes = []
217 for status in statuses:
218 cl = git_cl.Changelist()
219 cl.status = status
220 changes.append(cl)
221
222 actual = set(git_cl.get_cl_statuses(changes, True))
223 self.assertEqual(set(zip(changes, statuses)), actual)
224
225 def test_get_cl_statuses_no_changes(self):
226 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
227
228 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
229 @mock.patch('multiprocessing.pool.ThreadPool')
230 def test_get_cl_statuses_timeout(self, *_mocks):
231 changes = [git_cl.Changelist() for _ in range(2)]
232 pool = multiprocessing.pool.ThreadPool()
233 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
234 it.return_value.next.side_effect = [
235 (changes[0], 'lgtm'),
236 multiprocessing.TimeoutError,
237 ]
238
239 actual = list(git_cl.get_cl_statuses(changes, True))
240 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
241
242 @mock.patch('git_cl.Changelist.GetIssueURL')
243 def test_get_cl_statuses_not_finegrained(self, _mock):
244 changes = [git_cl.Changelist() for _ in range(2)]
245 urls = ['some-url', None]
246 git_cl.Changelist.GetIssueURL.side_effect = urls
247
248 actual = set(git_cl.get_cl_statuses(changes, False))
249 self.assertEqual(
250 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
251
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000252 def test_get_issue_url(self):
253 cl = git_cl.Changelist(issue=123)
254 cl._gerrit_server = 'https://example.com'
255 self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
256 self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
257
258 cl = git_cl.Changelist(issue=123)
259 cl._gerrit_server = 'https://chromium-review.googlesource.com'
260 self.assertEqual(cl.GetIssueURL(),
261 'https://chromium-review.googlesource.com/123')
262 self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
263
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000264 def test_set_preserve_tryjobs(self):
265 d = git_cl.ChangeDescription('Simple.')
266 d.set_preserve_tryjobs()
267 self.assertEqual(d.description.splitlines(), [
268 'Simple.',
269 '',
270 'Cq-Do-Not-Cancel-Tryjobs: true',
271 ])
272 before = d.description
273 d.set_preserve_tryjobs()
274 self.assertEqual(before, d.description)
275
276 d = git_cl.ChangeDescription('\n'.join([
277 'One is enough',
278 '',
279 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
280 'Change-Id: Ideadbeef',
281 ]))
282 d.set_preserve_tryjobs()
283 self.assertEqual(d.description.splitlines(), [
284 'One is enough',
285 '',
286 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
287 'Change-Id: Ideadbeef',
288 'Cq-Do-Not-Cancel-Tryjobs: true',
289 ])
290
tandriif9aefb72016-07-01 09:06:51 -0700291 def test_get_bug_line_values(self):
292 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
293 self.assertEqual(f('', ''), [])
294 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
295 self.assertEqual(f('v8', '456'), ['v8:456'])
296 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
297 # Not nice, but not worth carying.
298 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
299 ['v8:456', 'chromium:123', 'v8:123'])
300
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100301 def _test_git_number(self, parent_msg, dest_ref, child_msg,
302 parent_hash='parenthash'):
303 desc = git_cl.ChangeDescription(child_msg)
304 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
305 return desc.description
306
307 def assertEqualByLine(self, actual, expected):
308 self.assertEqual(actual.splitlines(), expected.splitlines())
309
310 def test_git_number_bad_parent(self):
311 with self.assertRaises(ValueError):
312 self._test_git_number('Parent', 'refs/heads/master', 'Child')
313
314 def test_git_number_bad_parent_footer(self):
315 with self.assertRaises(AssertionError):
316 self._test_git_number(
317 'Parent\n'
318 '\n'
319 'Cr-Commit-Position: wrong',
320 'refs/heads/master', 'Child')
321
322 def test_git_number_bad_lineage_ignored(self):
323 actual = self._test_git_number(
324 'Parent\n'
325 '\n'
326 'Cr-Commit-Position: refs/heads/master@{#1}\n'
327 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
328 'refs/heads/master', 'Child')
329 self.assertEqualByLine(
330 actual,
331 'Child\n'
332 '\n'
333 'Cr-Commit-Position: refs/heads/master@{#2}\n'
334 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
335
336 def test_git_number_same_branch(self):
337 actual = self._test_git_number(
338 'Parent\n'
339 '\n'
340 'Cr-Commit-Position: refs/heads/master@{#12}',
341 dest_ref='refs/heads/master',
342 child_msg='Child')
343 self.assertEqualByLine(
344 actual,
345 'Child\n'
346 '\n'
347 'Cr-Commit-Position: refs/heads/master@{#13}')
348
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200349 def test_git_number_same_branch_mixed_footers(self):
350 actual = self._test_git_number(
351 'Parent\n'
352 '\n'
353 'Cr-Commit-Position: refs/heads/master@{#12}',
354 dest_ref='refs/heads/master',
355 child_msg='Child\n'
356 '\n'
357 'Broken-by: design\n'
358 'BUG=123')
359 self.assertEqualByLine(
360 actual,
361 'Child\n'
362 '\n'
363 'Broken-by: design\n'
364 'BUG=123\n'
365 'Cr-Commit-Position: refs/heads/master@{#13}')
366
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100367 def test_git_number_same_branch_with_originals(self):
368 actual = self._test_git_number(
369 'Parent\n'
370 '\n'
371 'Cr-Commit-Position: refs/heads/master@{#12}',
372 dest_ref='refs/heads/master',
373 child_msg='Child\n'
374 '\n'
375 'Some users are smart and insert their own footers\n'
376 '\n'
377 'Cr-Whatever: value\n'
378 'Cr-Commit-Position: refs/copy/paste@{#22}')
379 self.assertEqualByLine(
380 actual,
381 'Child\n'
382 '\n'
383 'Some users are smart and insert their own footers\n'
384 '\n'
385 'Cr-Original-Whatever: value\n'
386 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
387 'Cr-Commit-Position: refs/heads/master@{#13}')
388
389 def test_git_number_new_branch(self):
390 actual = self._test_git_number(
391 'Parent\n'
392 '\n'
393 'Cr-Commit-Position: refs/heads/master@{#12}',
394 dest_ref='refs/heads/branch',
395 child_msg='Child')
396 self.assertEqualByLine(
397 actual,
398 'Child\n'
399 '\n'
400 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
401 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
402
403 def test_git_number_lineage(self):
404 actual = self._test_git_number(
405 'Parent\n'
406 '\n'
407 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
408 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
409 dest_ref='refs/heads/branch',
410 child_msg='Child')
411 self.assertEqualByLine(
412 actual,
413 'Child\n'
414 '\n'
415 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
416 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
417
418 def test_git_number_moooooooore_lineage(self):
419 actual = self._test_git_number(
420 'Parent\n'
421 '\n'
422 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
423 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
424 dest_ref='refs/heads/mooore',
425 child_msg='Child')
426 self.assertEqualByLine(
427 actual,
428 'Child\n'
429 '\n'
430 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
431 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
432 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
433
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100434 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700435 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100436 actual = self._test_git_number(
437 'CQ commit on fresh new branch + numbering.\n'
438 '\n'
439 'NOTRY=True\n'
440 'NOPRESUBMIT=True\n'
441 'BUG=\n'
442 '\n'
443 'Review-Url: https://codereview.chromium.org/2577703003\n'
444 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
445 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
446 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
447 dest_ref='refs/heads/gnumb-test/cl',
448 child_msg='git cl on fresh new branch + numbering.\n'
449 '\n'
450 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
451 self.assertEqualByLine(
452 actual,
453 'git cl on fresh new branch + numbering.\n'
454 '\n'
455 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
456 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
457 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
458 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
459 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100460
461 def test_git_number_cherry_pick(self):
462 actual = self._test_git_number(
463 'Parent\n'
464 '\n'
465 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
466 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
467 dest_ref='refs/heads/branch',
468 child_msg='Child, which is cherry-pick from master\n'
469 '\n'
470 'Cr-Commit-Position: refs/heads/master@{#100}\n'
471 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
472 self.assertEqualByLine(
473 actual,
474 'Child, which is cherry-pick from master\n'
475 '\n'
476 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
477 '\n'
478 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
479 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
480 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
481
Edward Lemurda4b6c62020-02-13 00:28:40 +0000482 @mock.patch('gerrit_util.GetAccountDetails')
483 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000484 mock_per_account = {
485 'u1': None, # 404, doesn't exist.
486 'u2': {
487 '_account_id': 123124,
488 'avatars': [],
489 'email': 'u2@example.com',
490 'name': 'User Number 2',
491 'status': 'OOO',
492 },
493 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
494 }
495 def GetAccountDetailsMock(_, account):
496 # Poor-man's mock library's side_effect.
497 v = mock_per_account.pop(account)
498 if isinstance(v, Exception):
499 raise v
500 return v
501
Edward Lemurda4b6c62020-02-13 00:28:40 +0000502 mockGetAccountDetails.side_effect = GetAccountDetailsMock
503 actual = git_cl.gerrit_util.ValidAccounts(
504 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000505 self.assertEqual(actual, {
506 'u2': {
507 '_account_id': 123124,
508 'avatars': [],
509 'email': 'u2@example.com',
510 'name': 'User Number 2',
511 'status': 'OOO',
512 },
513 })
514
515
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200516class TestParseIssueURL(unittest.TestCase):
517 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000518 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200519 self.assertIsNotNone(parsed)
520 if fail:
521 self.assertFalse(parsed.valid)
522 return
523 self.assertTrue(parsed.valid)
524 self.assertEqual(parsed.issue, issue)
525 self.assertEqual(parsed.patchset, patchset)
526 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200527
Edward Lemur678a6842019-10-03 22:25:05 +0000528 def test_ParseIssueNumberArgument(self):
529 def test(arg, *args, **kwargs):
530 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200531
Edward Lemur678a6842019-10-03 22:25:05 +0000532 test('123', 123)
533 test('', fail=True)
534 test('abc', fail=True)
535 test('123/1', fail=True)
536 test('123a', fail=True)
537 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200538
Edward Lemur678a6842019-10-03 22:25:05 +0000539 test('https://codereview.source.com/123',
540 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200541 test('http://chrome-review.source.com/c/123',
542 123, None, 'chrome-review.source.com')
543 test('https://chrome-review.source.com/c/123/',
544 123, None, 'chrome-review.source.com')
545 test('https://chrome-review.source.com/c/123/4',
546 123, 4, 'chrome-review.source.com')
547 test('https://chrome-review.source.com/#/c/123/4',
548 123, 4, 'chrome-review.source.com')
549 test('https://chrome-review.source.com/c/123/4',
550 123, 4, 'chrome-review.source.com')
551 test('https://chrome-review.source.com/123',
552 123, None, 'chrome-review.source.com')
553 test('https://chrome-review.source.com/123/4',
554 123, 4, 'chrome-review.source.com')
555
Edward Lemur678a6842019-10-03 22:25:05 +0000556 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200557 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
558 test('https://chrome-review.source.com/c/abc/', fail=True)
559 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
560
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200561
562
Edward Lemurda4b6c62020-02-13 00:28:40 +0000563class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100564 def setUp(self):
565 super(GitCookiesCheckerTest, self).setUp()
566 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100567 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000568 mock.patch('sys.stdout', StringIO()).start()
569 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100570
571 def mock_hosts_creds(self, subhost_identity_pairs):
572 def ensure_googlesource(h):
573 if not h.endswith(self.c._GOOGLESOURCE):
574 assert not h.endswith('.')
575 return h + '.' + self.c._GOOGLESOURCE
576 return h
577 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
578 for h, i in subhost_identity_pairs]
579
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200580 def test_identity_parsing(self):
581 self.assertEqual(self.c._parse_identity('ldap.google.com'),
582 ('ldap', 'google.com'))
583 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
584 ('ldap', 'example.com'))
585 # Specical case because we know there are no subdomains in chromium.org.
586 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
587 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800588 # Pathological: ".period." can be either username OR domain, more likely
589 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200590 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
591 ('note', 'period.example.com'))
592
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100593 def test_analysis_nothing(self):
594 self.c._all_hosts = []
595 self.assertFalse(self.c.has_generic_host())
596 self.assertEqual(set(), self.c.get_conflicting_hosts())
597 self.assertEqual(set(), self.c.get_duplicated_hosts())
598 self.assertEqual(set(), self.c.get_partially_configured_hosts())
599 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
600
601 def test_analysis(self):
602 self.mock_hosts_creds([
603 ('.googlesource.com', 'git-example.chromium.org'),
604
605 ('chromium', 'git-example.google.com'),
606 ('chromium-review', 'git-example.google.com'),
607 ('chrome-internal', 'git-example.chromium.org'),
608 ('chrome-internal-review', 'git-example.chromium.org'),
609 ('conflict', 'git-example.google.com'),
610 ('conflict-review', 'git-example.chromium.org'),
611 ('dup', 'git-example.google.com'),
612 ('dup', 'git-example.google.com'),
613 ('dup-review', 'git-example.google.com'),
614 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200615 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100616 ])
617 self.assertTrue(self.c.has_generic_host())
618 self.assertEqual(set(['conflict.googlesource.com']),
619 self.c.get_conflicting_hosts())
620 self.assertEqual(set(['dup.googlesource.com']),
621 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200622 self.assertEqual(set(['partial.googlesource.com',
623 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100624 self.c.get_partially_configured_hosts())
625 self.assertEqual(set(['chromium.googlesource.com',
626 'chrome-internal.googlesource.com']),
627 self.c.get_hosts_with_wrong_identities())
628
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100629 def test_report_no_problems(self):
630 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100631 self.assertFalse(self.c.find_and_report_problems())
632 self.assertEqual(sys.stdout.getvalue(), '')
633
Edward Lemurda4b6c62020-02-13 00:28:40 +0000634 @mock.patch(
635 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
636 return_value='~/.gitcookies')
637 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100638 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100639 self.assertTrue(self.c.find_and_report_problems())
640 with open(os.path.join(os.path.dirname(__file__),
641 'git_cl_creds_check_report.txt')) as f:
642 expected = f.read()
643 def by_line(text):
644 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700645 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200646 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100647
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800648
Edward Lemurda4b6c62020-02-13 00:28:40 +0000649class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000650 def setUp(self):
651 super(TestGitCl, self).setUp()
652 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700653 self._calls_done = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000654 mock.patch('sys.stdout', StringIO()).start()
655 mock.patch(
656 'git_cl.time_time',
657 lambda: self._mocked_call('time.time')).start()
658 mock.patch(
659 'git_cl.metrics.collector.add_repeated',
660 lambda *a: self._mocked_call('add_repeated', *a)).start()
661 mock.patch('subprocess2.call', self._mocked_call).start()
662 mock.patch('subprocess2.check_call', self._mocked_call).start()
663 mock.patch('subprocess2.check_output', self._mocked_call).start()
664 mock.patch(
665 'subprocess2.communicate',
666 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
667 mock.patch(
668 'git_cl.gclient_utils.CheckCallAndFilter',
669 self._mocked_call).start()
670 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
671 mock.patch(
672 'git_common.get_or_create_merge_base',
673 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
674 mock.patch('git_cl.BranchExists', return_value=True).start()
675 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
676 mock.patch(
677 'git_cl.SaveDescriptionBackup',
678 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
679 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000680 'git_cl.write_json',
681 lambda *a: self._mocked_call('write_json', *a)).start()
682 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000683 'git_cl.Changelist.RunHook',
684 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000685 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
686 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000687 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000688 mock.patch(
689 'git_cl.gerrit_util.GetChangeComments',
690 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
691 mock.patch(
692 'git_cl.gerrit_util.GetChangeRobotComments',
693 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
694 mock.patch(
695 'git_cl.gerrit_util.AddReviewers',
696 lambda *a: self._mocked_call('AddReviewers', *a)).start()
697 mock.patch(
698 'git_cl.gerrit_util.SetReview',
699 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
700 self._mocked_call(
701 'SetReview', h, i, msg, labels, notify, ready))).start()
702 mock.patch(
703 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
704 return_value=False).start()
705 mock.patch(
706 'git_cl.gerrit_util.GceAuthenticator.is_gce',
707 return_value=False).start()
708 mock.patch(
709 'git_cl.gerrit_util.ValidAccounts',
710 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000711 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000712 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000713 self.mockGit = GitMocks()
714 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
715 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
716 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000717 mock.patch(
718 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000719 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000720 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000721 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000722 mock.patch(
723 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000724 # It's important to reset settings to not have inter-tests interference.
725 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000726 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000727
728 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000729 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000730 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100731 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000732 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
733 if len(self.calls) > 5:
734 calls += ' ...\n'
735 self.fail(
736 '\n'
737 'There are un-consumed calls after this test has finished:\n' +
738 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000739 finally:
740 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000741
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000742 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000743 self.assertTrue(
744 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700745 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000746 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000747 expected_args, result = top
748
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000749 # Also logs otherwise it could get caught in a try/finally and be hard to
750 # diagnose.
751 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700752 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000753 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700754 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
755 for i, c in enumerate(self._calls_done[-N:]))
756 following_calls = '\n '.join(
757 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
758 for i, c in enumerate(self.calls[:N]))
759 extended_msg = (
760 'A few prior calls:\n %s\n\n'
761 'This (expected):\n @%d: %r\n'
762 'This (actual):\n @%d: %r\n\n'
763 'A few following expected calls:\n %s' %
764 (prior_calls, len(self._calls_done), expected_args,
765 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700766
tandrii99a72f22016-08-17 14:33:24 -0700767 self.fail('@%d\n'
768 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000769 ' Actual: %r\n'
770 '\n'
771 '%s' % (
772 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700773
774 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700775 if isinstance(result, Exception):
776 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000777 # stdout from git commands is supposed to be a bytestream. Convert it here
778 # instead of converting all test output in this file to bytes.
779 if args[0][0] == 'git' and not isinstance(result, bytes):
780 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000781 return result
782
Edward Lemur1a83da12020-03-04 21:18:36 +0000783 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
784 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100785 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100786 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000787 self.assertEqual(
788 'prompt [Yes/No]: Please, type yes or no: ',
789 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100790
tandrii48df5812016-10-17 03:55:37 -0700791 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000792 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700793 self.calls = [
794 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700795 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
796 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
797 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
798 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700799 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
800 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700801 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
802 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000803 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
804 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700805 ((['git', 'config', 'gerrit.host', 'true'],), ''),
806 ]
807 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
808
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000809 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100810 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200811 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000812 custom_cl_base=None, short_hostname='chromium',
813 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000814 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200815 if custom_cl_base:
816 ancestor_revision = custom_cl_base
817 else:
818 # Determine ancestor_revision to be merge base.
819 ancestor_revision = 'fake_ancestor_sha'
820 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000821 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
822 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200823 ]
824
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100825 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000826 gerrit_util.GetChangeDetail.return_value = {
827 'owner': {'email': (other_cl_owner or 'owner@example.com')},
828 'change_id': (change_id or '123456789'),
829 'current_revision': 'sha1_of_current_revision',
830 'revisions': {'sha1_of_current_revision': {
831 'commit': {'message': fetched_description},
832 }},
833 'status': fetched_status or 'NEW',
834 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100835 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100836 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100837 if other_cl_owner:
838 calls += [
839 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
840 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100841
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100842 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200843 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
844 ([custom_cl_base] if custom_cl_base else
845 [ancestor_revision, 'HEAD']),),
846 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100847 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000848
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100849 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000850
Edward Lemur26964072020-02-19 19:18:51 +0000851 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700852 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000853 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700854 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100855 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000856 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000857 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000858 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000859 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000860 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000861 if post_amend_description is None:
862 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700863 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200864
865 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000866
Edward Lemur26964072020-02-19 19:18:51 +0000867 if squash_mode in ('override_squash', 'override_nosquash'):
868 self.mockGit.config['gerrit.override-squash-uploads'] = (
869 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700870
Edward Lesmesc48fb842020-03-13 23:05:55 +0000871 # If issue is given, then description is fetched from Gerrit instead.
872 if issue is None:
873 if squash:
874 title = 'Initial_upload'
875 else:
876 if not title:
877 calls += [
878 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
879 (('ask_for_data', 'Title for patchset []: '), 'User input'),
880 ]
881 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000882 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000883 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200884 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200885 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000886 if squash:
Edward Lemur5fb22242020-03-12 22:05:13 +0000887 if not force and not issue:
888 calls += [
889 ((['RunEditor'],), description),
890 ]
Josipe827b0f2020-01-30 00:07:20 +0000891 # user wants to edit description
892 if edit_description:
893 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000894 ((['RunEditor'],), edit_description),
895 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000896 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200897
898 if custom_cl_base is None:
899 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000900 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000901 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200902 ]
903 parent = 'origin/master'
904 else:
905 calls += [
906 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
907 'refs/remotes/origin/master'],),
908 callError(1)), # Means not ancenstor.
909 (('ask_for_data',
910 'Do you take responsibility for cleaning up potential mess '
911 'resulting from proceeding with upload? Press Enter to upload, '
912 'or Ctrl+C to abort'), ''),
913 ]
914 parent = custom_cl_base
915
916 calls += [
917 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
918 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000919 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200920 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000921 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200922 ref_to_push),
923 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000924 else:
925 ref_to_push = 'HEAD'
926
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000927 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000928 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200929 ((['git', 'rev-list',
930 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
931 ref_to_push],),
932 '1hashPerLine\n'),
933 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000934
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000935 metrics_arguments = []
936
Aaron Gableafd52772017-06-27 16:40:10 -0700937 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700938 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000939 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700940 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400941 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700942 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000943 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700944 else:
945 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000946 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800947
Aaron Gable70f4e242017-06-26 10:45:59 -0700948 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700949 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000950 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000951
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000952 if short_hostname == 'chromium':
953 # All reviwers and ccs get into ref_suffix.
954 for r in sorted(reviewers):
955 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000956 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000957 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000958 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000959 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000960 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000961 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000962 reviewers, cc = [], []
963 else:
964 # TODO(crbug/877717): remove this case.
965 calls += [
966 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
967 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000968 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000969 {
970 e: {'email': e}
971 for e in (reviewers + ['joe@example.com'] + cc)
972 })
973 ]
974 for r in sorted(reviewers):
975 if r != 'bad-account-or-email':
976 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000977 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000978 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000979 if issue is None:
980 cc += ['joe@example.com']
981 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000982 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000983 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000984 if c in cc:
985 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000986
Edward Lemur687ca902018-12-05 02:30:30 +0000987 for k, v in sorted((labels or {}).items()):
988 ref_suffix += ',l=%s+%d' % (k, v)
989 metrics_arguments.append('l=%s+%d' % (k, v))
990
991 if tbr:
992 calls += [
993 (('GetCodeReviewTbrScore',
994 '%s-review.googlesource.com' % short_hostname,
995 'my/repo'),
996 2,),
997 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000998
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000999 calls += [
1000 (('time.time',), 1000,),
1001 ((['git', 'push',
1002 'https://%s.googlesource.com/my/repo' % short_hostname,
1003 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1004 (('remote:\n'
1005 'remote: Processing changes: (\)\n'
1006 'remote: Processing changes: (|)\n'
1007 'remote: Processing changes: (/)\n'
1008 'remote: Processing changes: (-)\n'
1009 'remote: Processing changes: new: 1 (/)\n'
1010 'remote: Processing changes: new: 1, done\n'
1011 'remote:\n'
1012 'remote: New Changes:\n'
1013 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1014 ' XXX\n'
1015 'remote:\n'
1016 'To https://%s.googlesource.com/my/repo\n'
1017 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1018 ) % (short_hostname, short_hostname)),),
1019 (('time.time',), 2000,),
1020 (('add_repeated',
1021 'sub_commands',
1022 {
1023 'execution_time': 1000,
1024 'command': 'git push',
1025 'exit_code': 0,
1026 'arguments': sorted(metrics_arguments),
1027 }),
1028 None,),
1029 ]
1030
Edward Lemur1b52d872019-05-09 21:12:12 +00001031 final_description = final_description or post_amend_description.strip()
1032 original_title = original_title or title or '<untitled>'
1033 # Trace-related calls
1034 calls += [
1035 # Write a description with context for the current trace.
1036 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001037 'Thu Mar 16 20:00:41 2017\n'
1038 '%(short_hostname)s-review.googlesource.com\n'
1039 '%(change_id)s\n'
1040 '%(title)s\n'
1041 '%(description)s\n'
1042 '1000\n'
1043 '0\n'
1044 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001045 'short_hostname': short_hostname,
1046 'change_id': change_id,
1047 'description': final_description,
1048 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001049 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001050 }],),
1051 None,
1052 ),
1053 # Read traces and shorten git hashes.
1054 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1055 True,
1056 ),
1057 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1058 ('git-hash: 0123456789012345678901234567890123456789\n'
1059 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1060 ),
1061 ((['FileWrite', 'TEMP_DIR/trace-packet',
1062 'git-hash: 012345\n'
1063 'git-hash: abcdea\n'],),
1064 None,
1065 ),
1066 # Make zip file for the git traces.
1067 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1068 'TEMP_DIR'],),
1069 None,
1070 ),
1071 # Collect git config and gitcookies.
1072 ((['git', 'config', '-l'],),
1073 'git-config-output',
1074 ),
1075 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1076 None,
1077 ),
1078 ((['os.path.isfile', '~/.gitcookies'],),
1079 gitcookies_exists,
1080 ),
1081 ]
1082 if gitcookies_exists:
1083 calls += [
1084 ((['FileRead', '~/.gitcookies'],),
1085 'gitcookies 1/SECRET',
1086 ),
1087 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1088 None,
1089 ),
1090 ]
1091 calls += [
1092 # Make zip file for the git config and gitcookies.
1093 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1094 'TEMP_DIR'],),
1095 None,
1096 ),
1097 ]
1098
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001099 # TODO(crbug/877717): this should never be used.
1100 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001101 calls += [
1102 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001103 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001104 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001105 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001106 notify),
1107 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001108 ]
Edward Lemur26964072020-02-19 19:18:51 +00001109 calls += [
1110 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1111 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001112 return calls
1113
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001114 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001115 self,
1116 upload_args,
1117 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001118 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001119 squash=True,
1120 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001121 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001122 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001123 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001124 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001125 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001126 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001127 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001128 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001129 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001130 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001131 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001132 labels=None,
1133 change_id=None,
1134 original_title=None,
1135 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001136 gitcookies_exists=True,
1137 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001138 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001139 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001140 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001141 if squash_mode is None:
1142 if '--no-squash' in upload_args:
1143 squash_mode = 'nosquash'
1144 elif '--squash' in upload_args:
1145 squash_mode = 'squash'
1146 else:
1147 squash_mode = 'default'
1148
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001149 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001150 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001151 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001152 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001153 same_auth=('git-owner.example.com', '', 'pass'))).start()
1154 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1155 lambda _, offer_removal: None).start()
1156 mock.patch('git_cl.gclient_utils.RunEditor',
1157 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1158 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1159 'DownloadGerritHook', force)).start()
1160 mock.patch('git_cl.gclient_utils.FileRead',
1161 lambda path: self._mocked_call(['FileRead', path])).start()
1162 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001163 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001164 ['FileWrite', path, contents])).start()
1165 mock.patch('git_cl.datetime_now',
1166 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1167 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1168 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1169 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001170 '%(now)s\n'
1171 '%(gerrit_host)s\n'
1172 '%(change_id)s\n'
1173 '%(title)s\n'
1174 '%(description)s\n'
1175 '%(execution_time)s\n'
1176 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001177 '%(trace_name)s').start()
1178 mock.patch('git_cl.shutil.make_archive',
1179 lambda *args: self._mocked_call(['make_archive'] +
1180 list(args))).start()
1181 mock.patch('os.path.isfile',
1182 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001183 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001184 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00001185 'git_cl._create_description_from_log', return_value=description).start()
1186 mock.patch(
1187 'git_cl.Changelist._AddChangeIdToCommitMessage',
1188 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001189 mock.patch(
1190 'git_cl.ask_for_data',
1191 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001192
Edward Lemur26964072020-02-19 19:18:51 +00001193 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001194 self.mockGit.config['branch.master.gerritissue'] = (
1195 str(issue) if issue else None)
1196 self.mockGit.config['remote.origin.url'] = (
1197 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001198 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001199
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001200 self.calls = self._gerrit_base_calls(
1201 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001202 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001203 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001204 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001205 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001206 short_hostname=short_hostname,
1207 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001208 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001209 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001210 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001211 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001212 self.calls += self._gerrit_upload_calls(
1213 description, reviewers, squash,
1214 squash_mode=squash_mode,
1215 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001216 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001217 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001218 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001219 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001220 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001221 labels=labels,
1222 change_id=change_id,
1223 original_title=original_title,
1224 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001225 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001226 force=force,
1227 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001228 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001229 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001230 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001231 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001232 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001233 self.assertEqual(
1234 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001235 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001236
Edward Lemur1b52d872019-05-09 21:12:12 +00001237 def test_gerrit_upload_traces_no_gitcookies(self):
1238 self._run_gerrit_upload_test(
1239 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001240 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001241 [],
1242 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001243 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001244 change_id='Ixxx',
1245 gitcookies_exists=False)
1246
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001247 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001248 self._run_gerrit_upload_test(
1249 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001250 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001251 [],
1252 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001253 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001254 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001255
1256 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001257 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001258 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001259 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001260 [],
tandriia60502f2016-06-20 02:01:53 -07001261 squash=False,
1262 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001263 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001264 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001265
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001266 def test_gerrit_no_reviewer(self):
1267 self._run_gerrit_upload_test(
1268 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001269 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001270 [],
1271 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001272 squash_mode='override_nosquash',
1273 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001274
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001275 def test_gerrit_no_reviewer_non_chromium_host(self):
1276 # TODO(crbug/877717): remove this test case.
1277 self._run_gerrit_upload_test(
1278 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001279 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001280 [],
1281 squash=False,
1282 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001283 short_hostname='other',
1284 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001285
Nick Carter8692b182017-11-06 16:30:38 -08001286 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001287 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001288 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001289 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001290 squash=False,
1291 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001292 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1293 change_id='I123456789',
1294 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001295
ukai@chromium.orge8077812012-02-03 03:41:46 +00001296 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001297 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001298 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001299 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lesmesc48fb842020-03-13 23:05:55 +00001300 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001301 squash=False,
1302 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001303 notify=True,
1304 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001305 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001306 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001307
Anthony Polito8b955342019-09-24 19:01:36 +00001308 def test_gerrit_upload_force_sets_bug(self):
1309 self._run_gerrit_upload_test(
1310 ['-b', '10000', '-f'],
1311 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1312 [],
1313 force=True,
1314 expected_upstream_ref='origin/master',
1315 fetched_description='desc=\n\nChange-Id: Ixxx',
1316 original_title='Initial upload',
1317 change_id='Ixxx')
1318
Edward Lemur5fb22242020-03-12 22:05:13 +00001319 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001320 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001321 ['-b', '10000', '-m', 'Title', '--edit-description'],
1322 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001323 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001324 issue='123456',
1325 expected_upstream_ref='origin/master',
Edward Lemur5fb22242020-03-12 22:05:13 +00001326 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001327 fetched_description='desc=\n\nChange-Id: Ixxxx',
1328 original_title='Title',
1329 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001330 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001331
Dan Beamd8b04ca2019-10-10 21:23:26 +00001332 def test_gerrit_upload_force_sets_fixed(self):
1333 self._run_gerrit_upload_test(
1334 ['-x', '10000', '-f'],
1335 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1336 [],
1337 force=True,
1338 expected_upstream_ref='origin/master',
1339 fetched_description='desc=\n\nChange-Id: Ixxx',
1340 original_title='Initial upload',
1341 change_id='Ixxx')
1342
ukai@chromium.orge8077812012-02-03 03:41:46 +00001343 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001344 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1345 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001346 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001347 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001348 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001349 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001350 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001351 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001352 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001353 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001354 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001355 labels={'Code-Review': 2},
1356 change_id='123456789',
1357 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001358
1359 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001360 self._run_gerrit_upload_test(
1361 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001362 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001363 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001364 expected_upstream_ref='origin/master',
1365 change_id='123456789',
1366 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001367
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001368 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001369 self._run_gerrit_upload_test(
1370 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001371 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001372 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001373 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001374 expected_upstream_ref='origin/master',
1375 change_id='123456789',
1376 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001377
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001378 def test_gerrit_upload_squash_first_with_labels(self):
1379 self._run_gerrit_upload_test(
1380 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001381 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001382 [],
1383 squash=True,
1384 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001385 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1386 change_id='123456789',
1387 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001388
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001389 def test_gerrit_upload_squash_first_against_rev(self):
1390 custom_cl_base = 'custom_cl_base_rev_or_branch'
1391 self._run_gerrit_upload_test(
1392 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001393 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001394 [],
1395 squash=True,
1396 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001397 custom_cl_base=custom_cl_base,
1398 change_id='123456789',
1399 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001400 self.assertIn(
1401 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1402 sys.stdout.getvalue())
1403
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001404 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001405 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001406 self._run_gerrit_upload_test(
1407 ['--squash'],
1408 description,
1409 [],
1410 squash=True,
1411 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001412 issue=123456,
1413 change_id='123456789',
1414 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001415
Edward Lemurd55c5072020-02-20 01:09:07 +00001416 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001417 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001418 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001419 with self.assertRaises(SystemExitMock):
1420 self._run_gerrit_upload_test(
1421 ['--squash'],
1422 description,
1423 [],
1424 squash=True,
1425 expected_upstream_ref='origin/master',
1426 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001427 fetched_status='ABANDONED',
1428 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001429 self.assertEqual(
1430 'Change https://chromium-review.googlesource.com/123456 has been '
1431 'abandoned, new uploads are not allowed\n',
1432 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001433
Edward Lemurda4b6c62020-02-13 00:28:40 +00001434 @mock.patch(
1435 'gerrit_util.GetAccountDetails',
1436 return_value={'email': 'yet-another@example.com'})
1437 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001438 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001439 self._run_gerrit_upload_test(
1440 ['--squash'],
1441 description,
1442 [],
1443 squash=True,
1444 expected_upstream_ref='origin/master',
1445 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001446 other_cl_owner='other@example.com',
1447 change_id='123456789',
1448 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001449 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001450 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001451 'authenticate to Gerrit as yet-another@example.com.\n'
1452 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001453 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001454
Josipe827b0f2020-01-30 00:07:20 +00001455 def test_upload_change_description_editor(self):
1456 fetched_description = 'foo\n\nChange-Id: 123456789'
1457 description = 'bar\n\nChange-Id: 123456789'
1458 self._run_gerrit_upload_test(
1459 ['--squash', '--edit-description'],
1460 description,
1461 [],
1462 fetched_description=fetched_description,
1463 squash=True,
1464 expected_upstream_ref='origin/master',
1465 issue=123456,
1466 change_id='123456789',
1467 original_title='User input',
1468 edit_description=description)
1469
Edward Lemurda4b6c62020-02-13 00:28:40 +00001470 @mock.patch('git_cl.RunGit')
1471 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001472 @mock.patch('sys.stdin', StringIO('\n'))
1473 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001474 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001475 def mock_run_git(*args, **_kwargs):
1476 if args[0] == ['for-each-ref',
1477 '--format=%(refname:short) %(upstream:short)',
1478 'refs/heads']:
1479 # Create a local branch dependency tree that looks like this:
1480 # test1 -> test2 -> test3 -> test4 -> test5
1481 # -> test3.1
1482 # test6 -> test0
1483 branch_deps = [
1484 'test2 test1', # test1 -> test2
1485 'test3 test2', # test2 -> test3
1486 'test3.1 test2', # test2 -> test3.1
1487 'test4 test3', # test3 -> test4
1488 'test5 test4', # test4 -> test5
1489 'test6 test0', # test0 -> test6
1490 'test7', # test7
1491 ]
1492 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001493 git_cl.RunGit.side_effect = mock_run_git
1494 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001495
1496 class MockChangelist():
1497 def __init__(self):
1498 pass
1499 def GetBranch(self):
1500 return 'test1'
1501 def GetIssue(self):
1502 return '123'
1503 def GetPatchset(self):
1504 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001505 def IsGerrit(self):
1506 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001507
1508 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1509 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001510 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001511 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001512 'This command will checkout all dependent branches '
1513 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001514 'or Ctrl+C to abort',
1515 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001516 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001517
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001518 def test_gerrit_change_id(self):
1519 self.calls = [
1520 ((['git', 'write-tree'], ),
1521 'hashtree'),
1522 ((['git', 'rev-parse', 'HEAD~0'], ),
1523 'branch-parent'),
1524 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1525 'A B <a@b.org> 1456848326 +0100'),
1526 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1527 'C D <c@d.org> 1456858326 +0100'),
1528 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1529 'hashchange'),
1530 ]
1531 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1532 self.assertEqual(change_id, 'Ihashchange')
1533
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001534 def test_desecription_append_footer(self):
1535 for init_desc, footer_line, expected_desc in [
1536 # Use unique desc first lines for easy test failure identification.
1537 ('foo', 'R=one', 'foo\n\nR=one'),
1538 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1539 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1540 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1541 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1542 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1543 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1544 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1545 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1546 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1547 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1548 ]:
1549 desc = git_cl.ChangeDescription(init_desc)
1550 desc.append_footer(footer_line)
1551 self.assertEqual(desc.description, expected_desc)
1552
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001553 def test_update_reviewers(self):
1554 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001555 ('foo', [], [],
1556 'foo'),
1557 ('foo\nR=xx', [], [],
1558 'foo\nR=xx'),
1559 ('foo\nTBR=xx', [], [],
1560 'foo\nTBR=xx'),
1561 ('foo', ['a@c'], [],
1562 'foo\n\nR=a@c'),
1563 ('foo\nR=xx', ['a@c'], [],
1564 'foo\n\nR=a@c, xx'),
1565 ('foo\nTBR=xx', ['a@c'], [],
1566 'foo\n\nR=a@c\nTBR=xx'),
1567 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1568 'foo\n\nR=a@c, yy\nTBR=xx'),
1569 ('foo\nBUG=', ['a@c'], [],
1570 'foo\nBUG=\nR=a@c'),
1571 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1572 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1573 ('foo', ['a@c', 'b@c'], [],
1574 'foo\n\nR=a@c, b@c'),
1575 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1576 'foo\nBar\n\nR=c@c\nBUG='),
1577 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1578 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001579 # Same as the line before, but full of whitespaces.
1580 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001581 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001582 'foo\nBar\n\nR=c@c\n BUG =',
1583 ),
1584 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001585 ('foo BUG=allo R=joe ', ['c@c'], [],
1586 'foo BUG=allo R=joe\n\nR=c@c'),
1587 # Redundant TBRs get promoted to Rs
1588 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1589 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001590 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001591 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001592 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001593 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001594 obj = git_cl.ChangeDescription(orig)
Edward Lemur2c62b332020-03-12 22:12:33 +00001595 obj.update_reviewers(reviewers, tbrs, None, None, None)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001596 actual.append(obj.description)
1597 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001598
Nodir Turakulov23b82142017-11-16 11:04:25 -08001599 def test_get_hash_tags(self):
1600 cases = [
1601 ('', []),
1602 ('a', []),
1603 ('[a]', ['a']),
1604 ('[aa]', ['aa']),
1605 ('[a ]', ['a']),
1606 ('[a- ]', ['a']),
1607 ('[a- b]', ['a-b']),
1608 ('[a--b]', ['a-b']),
1609 ('[a', []),
1610 ('[a]x', ['a']),
1611 ('[aa]x', ['aa']),
1612 ('[a b]', ['a-b']),
1613 ('[a b]', ['a-b']),
1614 ('[a__b]', ['a-b']),
1615 ('[a] x', ['a']),
1616 ('[a][b]', ['a', 'b']),
1617 ('[a] [b]', ['a', 'b']),
1618 ('[a][b]x', ['a', 'b']),
1619 ('[a][b] x', ['a', 'b']),
1620 ('[a]\n[b]', ['a']),
1621 ('[a\nb]', []),
1622 ('[a][', ['a']),
1623 ('Revert "[a] feature"', ['a']),
1624 ('Reland "[a] feature"', ['a']),
1625 ('Revert: [a] feature', ['a']),
1626 ('Reland: [a] feature', ['a']),
1627 ('Revert "Reland: [a] feature"', ['a']),
1628 ('Foo: feature', ['foo']),
1629 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001630 ('Change Foo::Bar', []),
1631 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001632 ('Revert "Foo bar: feature"', ['foo-bar']),
1633 ('Reland "Foo bar: feature"', ['foo-bar']),
1634 ]
1635 for desc, expected in cases:
1636 change_desc = git_cl.ChangeDescription(desc)
1637 actual = change_desc.get_hash_tags()
1638 self.assertEqual(
1639 actual,
1640 expected,
1641 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1642
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001643 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001644 self.assertEqual(None, git_cl.GetTargetRef(None,
1645 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001646 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001647
wittman@chromium.org455dc922015-01-26 20:15:50 +00001648 # Check default target refs for branches.
1649 self.assertEqual('refs/heads/master',
1650 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001651 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001652 self.assertEqual('refs/heads/master',
1653 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001654 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001655 self.assertEqual('refs/heads/master',
1656 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001657 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001658 self.assertEqual('refs/branch-heads/123',
1659 git_cl.GetTargetRef('origin',
1660 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001661 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001662 self.assertEqual('refs/diff/test',
1663 git_cl.GetTargetRef('origin',
1664 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001665 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001666 self.assertEqual('refs/heads/chrome/m42',
1667 git_cl.GetTargetRef('origin',
1668 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001669 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001670
1671 # Check target refs for user-specified target branch.
1672 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1673 'refs/remotes/branch-heads/123'):
1674 self.assertEqual('refs/branch-heads/123',
1675 git_cl.GetTargetRef('origin',
1676 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001677 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001678 for branch in ('origin/master', 'remotes/origin/master',
1679 'refs/remotes/origin/master'):
1680 self.assertEqual('refs/heads/master',
1681 git_cl.GetTargetRef('origin',
1682 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001683 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001684 for branch in ('master', 'heads/master', 'refs/heads/master'):
1685 self.assertEqual('refs/heads/master',
1686 git_cl.GetTargetRef('origin',
1687 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001688 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001689
Edward Lemurda4b6c62020-02-13 00:28:40 +00001690 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1691 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001692 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001693 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1694
Edward Lemur85153282020-02-14 22:06:29 +00001695 def assertIssueAndPatchset(
1696 self, branch='master', issue='123456', patchset='7',
1697 git_short_host='chromium'):
1698 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001699 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001700 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001701 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001702 self.assertEqual(
1703 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001704 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001705
Edward Lemur85153282020-02-14 22:06:29 +00001706 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001707 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001708 self.mockGit.config['remote.origin.url'] = (
1709 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001710 gerrit_util.GetChangeDetail.return_value = {
1711 'current_revision': '7777777777',
1712 'revisions': {
1713 '1111111111': {
1714 '_number': 1,
1715 'fetch': {'http': {
1716 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1717 'ref': 'refs/changes/56/123456/1',
1718 }},
1719 },
1720 '7777777777': {
1721 '_number': 7,
1722 'fetch': {'http': {
1723 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1724 'ref': 'refs/changes/56/123456/7',
1725 }},
1726 },
1727 },
1728 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001729
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001730 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001731 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001732 self.calls += [
1733 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1734 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001735 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001736 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001737 ]
1738 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001739 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001740
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001741 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001742 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001743 self.calls += [
1744 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1745 'refs/changes/56/123456/7'],), ''),
1746 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001747 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001748 ]
Edward Lemur85153282020-02-14 22:06:29 +00001749 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1750 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001751
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001752 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001753 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001754 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001755 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001756 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001757 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001758 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001759 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001760 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001761 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001762
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001763 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001764 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001765 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001766 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001767 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001768 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001769 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001770 ]
1771 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001772 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001773 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001774
Aaron Gable697a91b2018-01-19 15:20:15 -08001775 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001776 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001777 self.calls += [
1778 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1779 'refs/changes/56/123456/1'],), ''),
1780 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001781 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001782 ]
1783 self.assertEqual(git_cl.main(
1784 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1785 0)
Edward Lemur85153282020-02-14 22:06:29 +00001786 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001787
Edward Lemurd55c5072020-02-20 01:09:07 +00001788 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001789 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001790 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001791 self.calls += [
1792 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001793 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001794 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001795 ]
1796 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001797 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001798 self.assertEqual(
1799 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1800 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001801
Edward Lemurda4b6c62020-02-13 00:28:40 +00001802 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001803 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001804 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001805 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001806 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001807 self.mockGit.config['remote.origin.url'] = (
1808 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001809 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001810 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001811 self.assertEqual(
1812 'change 123456 at https://chromium-review.googlesource.com does not '
1813 'exist or you have no access to it\n',
1814 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001815
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001816 def _checkout_calls(self):
1817 return [
1818 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001819 'branch\\..*\\.gerritissue'], ),
1820 ('branch.ger-branch.gerritissue 123456\n'
1821 'branch.gbranch654.gerritissue 654321\n')),
1822 ]
1823
1824 def test_checkout_gerrit(self):
1825 """Tests git cl checkout <issue>."""
1826 self.calls = self._checkout_calls()
1827 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1828 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1829
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001830 def test_checkout_not_found(self):
1831 """Tests git cl checkout <issue>."""
1832 self.calls = self._checkout_calls()
1833 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1834
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001835 def test_checkout_no_branch_issues(self):
1836 """Tests git cl checkout <issue>."""
1837 self.calls = [
1838 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001839 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001840 ]
1841 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1842
Edward Lemur26964072020-02-19 19:18:51 +00001843 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001844 mock.patch(
1845 'git_cl.ask_for_data',
1846 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001847 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1848 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001849 self.mockGit.config['remote.origin.url'] = (
1850 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001851 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001852 cl.branch = 'master'
1853 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001854 return cl
1855
Edward Lemurd55c5072020-02-20 01:09:07 +00001856 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001857 def test_gerrit_ensure_authenticated_missing(self):
1858 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001859 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001860 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001861 with self.assertRaises(SystemExitMock):
1862 cl.EnsureAuthenticated(force=False)
1863 self.assertEqual(
1864 'Credentials for the following hosts are required:\n'
1865 ' chromium-review.googlesource.com\n'
1866 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1867 'You can (re)generate your credentials by visiting '
1868 'https://chromium-review.googlesource.com/new-password\n',
1869 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001870
1871 def test_gerrit_ensure_authenticated_conflict(self):
1872 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001873 'chromium.googlesource.com':
1874 ('git-one.example.com', None, 'secret1'),
1875 'chromium-review.googlesource.com':
1876 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001877 })
1878 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001879 (('ask_for_data', 'If you know what you are doing '
1880 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001881 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1882
1883 def test_gerrit_ensure_authenticated_ok(self):
1884 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001885 'chromium.googlesource.com':
1886 ('git-same.example.com', None, 'secret'),
1887 'chromium-review.googlesource.com':
1888 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001889 })
1890 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1891
tandrii@chromium.org28253532016-04-14 13:46:56 +00001892 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001893 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1894 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001895 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1896
Eric Boren2fb63102018-10-05 13:05:03 +00001897 def test_gerrit_ensure_authenticated_bearer_token(self):
1898 cl = self._test_gerrit_ensure_authenticated_common(auth={
1899 'chromium.googlesource.com':
1900 ('', None, 'secret'),
1901 'chromium-review.googlesource.com':
1902 ('', None, 'secret'),
1903 })
1904 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1905 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1906 'chromium.googlesource.com')
1907 self.assertTrue('Bearer' in header)
1908
Daniel Chengcf6269b2019-05-18 01:02:12 +00001909 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001910 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001911 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001912 (('logging.warning',
1913 'Ignoring branch %(branch)s with non-https remote '
1914 '%(remote)s', {
1915 'branch': 'master',
1916 'remote': 'custom-scheme://repo'}
1917 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001918 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001919 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1920 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1921 mock.patch('logging.warning',
1922 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001923 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001924 cl.branch = 'master'
1925 cl.branchref = 'refs/heads/master'
1926 cl.lookedup_issue = True
1927 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1928
Florian Mayerae510e82020-01-30 21:04:48 +00001929 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001930 self.mockGit.config['remote.origin.url'] = (
1931 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001932 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001933 (('logging.error',
1934 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1935 'but it doesn\'t exist.', {
1936 'remote': 'origin',
1937 'branch': 'master',
1938 'url': 'git@somehost.example:foo/bar.git'}
1939 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001940 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001941 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1942 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1943 mock.patch('logging.error',
1944 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001945 cl = git_cl.Changelist()
1946 cl.branch = 'master'
1947 cl.branchref = 'refs/heads/master'
1948 cl.lookedup_issue = True
1949 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1950
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001951 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001952 self.mockGit.config['branch.master.gerritissue'] = '123'
1953 self.mockGit.config['branch.master.gerritserver'] = (
1954 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001955 self.mockGit.config['remote.origin.url'] = (
1956 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001957 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001958 (('SetReview', 'chromium-review.googlesource.com',
1959 'infra%2Finfra~123', None,
1960 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001961 ]
tandriid9e5ce52016-07-13 02:32:59 -07001962
1963 def test_cmd_set_commit_gerrit_clear(self):
1964 self._cmd_set_commit_gerrit_common(0)
1965 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1966
1967 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001968 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001969 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1970
tandriid9e5ce52016-07-13 02:32:59 -07001971 def test_cmd_set_commit_gerrit(self):
1972 self._cmd_set_commit_gerrit_common(2)
1973 self.assertEqual(0, git_cl.main(['set-commit']))
1974
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001975 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001976 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001977 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001978
1979 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001980 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001981
Edward Lemurda4b6c62020-02-13 00:28:40 +00001982 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001983 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001984 try:
1985 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001986 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001987 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001988 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001989
1990 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001991 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001992 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001993 return 'foobar'
1994
Edward Lemurda4b6c62020-02-13 00:28:40 +00001995 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001996 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001997 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001998 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001999 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002000
iannuccie53c9352016-08-17 14:40:40 -07002001 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002002
iannuccie53c9352016-08-17 14:40:40 -07002003 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002004 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002005 return 'foobar'
2006
Edward Lemurda4b6c62020-02-13 00:28:40 +00002007 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2008 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002009 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002010 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002011
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002012 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002013 self.mockGit.config['remote.origin.url'] = (
2014 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002015 gerrit_util.GetChangeDetail.return_value = {
2016 'current_revision': 'sha1',
2017 'revisions': {'sha1': {
2018 'commit': {'message': 'foobar'},
2019 }},
2020 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002021 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002022 'description',
2023 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2024 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002025 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002026
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002027 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002028 mock.patch('git_cl.Changelist', ChangelistMock).start()
2029 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002030
2031 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2032 self.assertEqual('hihi', ChangelistMock.desc)
2033
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002034 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002035 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002036
2037 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002038 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002039 '# Enter a description of the change.\n'
2040 '# This will be displayed on the codereview site.\n'
2041 '# The first line will also be used as the subject of the review.\n'
2042 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002043 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002044 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002045 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002046 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002047 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002048
Edward Lemur6c6827c2020-02-06 21:15:18 +00002049 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002050 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002051
Edward Lemurda4b6c62020-02-13 00:28:40 +00002052 mock.patch('git_cl.Changelist.FetchDescription',
2053 lambda *args: current_desc).start()
2054 mock.patch('git_cl.Changelist.UpdateDescription',
2055 UpdateDescription).start()
2056 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002057
Edward Lemur85153282020-02-14 22:06:29 +00002058 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002059 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002060
Dan Beamd8b04ca2019-10-10 21:23:26 +00002061 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2062 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2063
2064 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002065 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002066 '# Enter a description of the change.\n'
2067 '# This will be displayed on the codereview site.\n'
2068 '# The first line will also be used as the subject of the review.\n'
2069 '#--------------------This line is 72 characters long'
2070 '--------------------\n'
2071 'Some.\n\nFixed: 123\nChange-Id: xxx',
2072 desc)
2073 return desc
2074
Edward Lemurda4b6c62020-02-13 00:28:40 +00002075 mock.patch('git_cl.Changelist.FetchDescription',
2076 lambda *args: current_desc).start()
2077 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002078
Edward Lemur85153282020-02-14 22:06:29 +00002079 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002080 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002081
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002082 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002083 mock.patch('git_cl.Changelist', ChangelistMock).start()
2084 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002085
2086 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2087 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2088
kmarshall3bff56b2016-06-06 18:31:47 -07002089 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002090 self.calls = [
2091 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002092 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002093 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002094 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002095 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002096 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002097
Edward Lemurda4b6c62020-02-13 00:28:40 +00002098 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002099 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002100 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2101 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002102 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002103
2104 self.assertEqual(0, git_cl.main(['archive', '-f']))
2105
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002106 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002107 self.calls = [
2108 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2109 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2110 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2111 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002112 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2113 ((['git', 'branch', '-D', 'foo'],), '')
2114 ]
2115
Edward Lemurda4b6c62020-02-13 00:28:40 +00002116 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002117 lambda branches, fine_grained, max_processes:
2118 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2119 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002120 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002121
2122 self.assertEqual(0, git_cl.main(['archive', '-f']))
2123
kmarshall3bff56b2016-06-06 18:31:47 -07002124 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002125 self.calls = [
2126 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2127 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002128 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002129 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002130
Edward Lemurda4b6c62020-02-13 00:28:40 +00002131 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002132 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002133 [(MockChangelistWithBranchAndIssue('master', 1),
2134 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002135
2136 self.assertEqual(1, git_cl.main(['archive', '-f']))
2137
2138 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002139 self.calls = [
2140 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2141 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002142 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002143 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002144
Edward Lemurda4b6c62020-02-13 00:28:40 +00002145 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002146 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002147 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2148 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002149 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002150
kmarshall9249e012016-08-23 12:02:16 -07002151 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2152
2153 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002154 self.calls = [
2155 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2156 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002157 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002158 ((['git', 'branch', '-D', 'foo'],), '')
2159 ]
kmarshall9249e012016-08-23 12:02:16 -07002160
Edward Lemurda4b6c62020-02-13 00:28:40 +00002161 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002162 lambda branches, fine_grained, max_processes:
2163 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2164 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002165 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002166
2167 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002168
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002169 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002170 self.calls = [
2171 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2172 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2173 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002174 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2175 'refs/tags/git-cl-archived-456-foo'),
2176 ((['git', 'branch', '-D', 'foo'],), CERR1),
2177 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2178 'refs/tags/git-cl-archived-456-foo'),
2179 ]
2180
Edward Lemurda4b6c62020-02-13 00:28:40 +00002181 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002182 lambda branches, fine_grained, max_processes:
2183 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2184 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002185 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002186
2187 self.assertEqual(0, git_cl.main(['archive', '-f']))
2188
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002189 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002190 self.mockGit.config['branch.master.gerritissue'] = '123'
2191 self.mockGit.config['branch.master.gerritserver'] = (
2192 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002193 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002194 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002195 ]
2196 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002197 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2198 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002199
Aaron Gable400e9892017-07-12 15:31:21 -07002200 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002201 self.mockGit.config['branch.master.gerritissue'] = '123'
2202 self.mockGit.config['branch.master.gerritserver'] = (
2203 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002204 mock.patch('git_cl.Changelist.FetchDescription',
2205 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002206 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002207 ((['git', 'log', '-1', '--format=%B'],),
2208 'This is a description\n\nChange-Id: Ideadbeef'),
2209 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002210 ]
2211 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002212 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2213 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002214
phajdan.jre328cf92016-08-22 04:12:17 -07002215 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002216 self.mockGit.config['branch.master.gerritissue'] = '123'
2217 self.mockGit.config['branch.master.gerritserver'] = (
2218 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002219 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002220 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002221 {'issue': 123,
2222 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002223 ''),
2224 ]
2225 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2226
tandrii16e0b4e2016-06-07 10:34:28 -07002227 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002228 mock.patch(
2229 'git_cl.os.path.abspath',
2230 lambda path: self._mocked_call(['abspath', path])).start()
2231 mock.patch(
2232 'git_cl.os.path.exists',
2233 lambda path: self._mocked_call(['exists', path])).start()
2234 mock.patch(
2235 'git_cl.gclient_utils.FileRead',
2236 lambda path: self._mocked_call(['FileRead', path])).start()
2237 mock.patch(
2238 'git_cl.gclient_utils.rm_file_or_tree',
2239 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002240 mock.patch(
2241 'git_cl.ask_for_data',
2242 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002243 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002244
2245 def test_GerritCommitMsgHookCheck_custom_hook(self):
2246 cl = self._common_GerritCommitMsgHookCheck()
2247 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002248 ((['exists', '.git/hooks/commit-msg'],), True),
2249 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002250 '#!/bin/sh\necho "custom hook"')
2251 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002252 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002253
2254 def test_GerritCommitMsgHookCheck_not_exists(self):
2255 cl = self._common_GerritCommitMsgHookCheck()
2256 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002257 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002258 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002259 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002260
2261 def test_GerritCommitMsgHookCheck(self):
2262 cl = self._common_GerritCommitMsgHookCheck()
2263 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002264 ((['exists', '.git/hooks/commit-msg'],), True),
2265 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002266 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002267 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002268 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002269 ''),
2270 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002271 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002272
tandriic4344b52016-08-29 06:04:54 -07002273 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002274 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2275 self.mockGit.config['branch.master.gerritserver'] = (
2276 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002277 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002278 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002279 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002280 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002281 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002282 'labels': {},
2283 'current_revision': 'deadbeaf',
2284 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002285 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002286 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002287 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002288 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2289 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002290 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002291 self.assertEqual(0, cl.CMDLand(force=True,
2292 bypass_hooks=True,
2293 verbose=True,
2294 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002295 self.assertIn(
2296 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002297 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002298 self.assertIn(
2299 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002300 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002301
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002302 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002303 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002304
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002305 def test_gerrit_change_detail_cache_simple(self):
2306 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002307 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002308 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002309 cl1._cached_remote_url = (
2310 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002311 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002312 cl2._cached_remote_url = (
2313 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002314 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2315 self.assertEqual(cl1._GetChangeDetail(), 'a')
2316 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002317
2318 def test_gerrit_change_detail_cache_options(self):
2319 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002320 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002321 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002322 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002323 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2324 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2325 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2326 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2327 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2328 self.assertEqual(cl._GetChangeDetail(), 'cab')
2329
2330 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2331 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2332 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2333 self.assertEqual(cl._GetChangeDetail(), 'cab')
2334
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002335 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002336 gerrit_util.GetChangeDetail.return_value = {
2337 'current_revision': 'rev1',
2338 'revisions': {
2339 'rev1': {'commit': {'message': 'desc1'}},
2340 },
2341 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002342
2343 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002344 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002345 cl._cached_remote_url = (
2346 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002347 self.assertEqual(cl.FetchDescription(), 'desc1')
2348 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002349
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002350 def test_print_current_creds(self):
2351 class CookiesAuthenticatorMock(object):
2352 def __init__(self):
2353 self.gitcookies = {
2354 'host.googlesource.com': ('user', 'pass'),
2355 'host-review.googlesource.com': ('user', 'pass'),
2356 }
2357 self.netrc = self
2358 self.netrc.hosts = {
2359 'github.com': ('user2', None, 'pass2'),
2360 'host2.googlesource.com': ('user3', None, 'pass'),
2361 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002362 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2363 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002364 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2365 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2366 ' Host\t User\t Which file',
2367 '============================\t=====\t===========',
2368 'host-review.googlesource.com\t user\t.gitcookies',
2369 ' host.googlesource.com\t user\t.gitcookies',
2370 ' host2.googlesource.com\tuser3\t .netrc',
2371 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002372 sys.stdout.seek(0)
2373 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002374 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2375 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2376 ' Host\tUser\t Which file',
2377 '============================\t====\t===========',
2378 'host-review.googlesource.com\tuser\t.gitcookies',
2379 ' host.googlesource.com\tuser\t.gitcookies',
2380 ])
2381
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002382 def _common_creds_check_mocks(self):
2383 def exists_mock(path):
2384 dirname = os.path.dirname(path)
2385 if dirname == os.path.expanduser('~'):
2386 dirname = '~'
2387 base = os.path.basename(path)
2388 if base in ('.netrc', '.gitcookies'):
2389 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2390 # git cl also checks for existence other files not relevant to this test.
2391 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002392 mock.patch(
2393 'git_cl.ask_for_data',
2394 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002395 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002396
2397 def test_creds_check_gitcookies_not_configured(self):
2398 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002399 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2400 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002401 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002402 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002403 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2404 (('os.path.exists', '~/.netrc'), True),
2405 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2406 'or Ctrl+C to abort'), ''),
2407 ((['git', 'config', '--global', 'http.cookiefile',
2408 os.path.expanduser('~/.gitcookies')], ), ''),
2409 ]
2410 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002411 self.assertTrue(
2412 sys.stdout.getvalue().startswith(
2413 'You seem to be using outdated .netrc for git credentials:'))
2414 self.assertIn(
2415 '\nConfigured git to use .gitcookies from',
2416 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002417
2418 def test_creds_check_gitcookies_configured_custom_broken(self):
2419 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002420 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2421 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002422 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002423 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002424 ((['git', 'config', '--global', 'http.cookiefile'],),
2425 '/custom/.gitcookies'),
2426 (('os.path.exists', '/custom/.gitcookies'), False),
2427 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2428 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2429 ((['git', 'config', '--global', 'http.cookiefile',
2430 os.path.expanduser('~/.gitcookies')], ), ''),
2431 ]
2432 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002433 self.assertIn(
2434 'WARNING: You have configured custom path to .gitcookies: ',
2435 sys.stdout.getvalue())
2436 self.assertIn(
2437 'However, your configured .gitcookies file is missing.',
2438 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002439
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002440 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002441 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002442 self.mockGit.config['remote.origin.url'] = (
2443 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002444 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002445 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002446 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002447 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002448 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002449 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002450
Edward Lemurda4b6c62020-02-13 00:28:40 +00002451 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2452 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002453 self.mockGit.config['remote.origin.url'] = (
2454 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002455 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002456 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002457 'current_revision': 'ba5eba11',
2458 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002459 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002460 '_number': 1,
2461 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002462 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002463 '_number': 2,
2464 },
2465 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002466 'messages': [
2467 {
2468 u'_revision_number': 1,
2469 u'author': {
2470 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002471 u'email': u'could-be-anything@example.com',
2472 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002473 },
2474 u'date': u'2017-03-15 20:08:45.000000000',
2475 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002476 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002477 u'tag': u'autogenerated:cq:dry-run'
2478 },
2479 {
2480 u'_revision_number': 2,
2481 u'author': {
2482 u'_account_id': 11151243,
2483 u'email': u'owner@example.com',
2484 u'name': u'owner'
2485 },
2486 u'date': u'2017-03-16 20:00:41.000000000',
2487 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2488 u'message': u'PTAL',
2489 },
2490 {
2491 u'_revision_number': 2,
2492 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002493 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002494 u'email': u'reviewer@example.com',
2495 u'name': u'reviewer'
2496 },
2497 u'date': u'2017-03-17 05:19:37.500000000',
2498 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2499 u'message': u'Patch Set 2: Code-Review+1',
2500 },
2501 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002502 }
2503 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002504 (('GetChangeComments', 'chromium-review.googlesource.com',
2505 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002506 '/COMMIT_MSG': [
2507 {
2508 'author': {'email': u'reviewer@example.com'},
2509 'updated': u'2017-03-17 05:19:37.500000000',
2510 'patch_set': 2,
2511 'side': 'REVISION',
2512 'message': 'Please include a bug link',
2513 },
2514 ],
2515 'codereview.settings': [
2516 {
2517 'author': {'email': u'owner@example.com'},
2518 'updated': u'2017-03-16 20:00:41.000000000',
2519 'patch_set': 2,
2520 'side': 'PARENT',
2521 'line': 42,
2522 'message': 'I removed this because it is bad',
2523 },
2524 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002525 }),
2526 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2527 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002528 ] * 2 + [
2529 (('write_json', 'output.json', [
2530 {
2531 u'date': u'2017-03-16 20:00:41.000000',
2532 u'message': (
2533 u'PTAL\n' +
2534 u'\n' +
2535 u'codereview.settings\n' +
2536 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2537 u'c/1/2/codereview.settings#b42\n' +
2538 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002539 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002540 u'approval': False,
2541 u'disapproval': False,
2542 u'sender': u'owner@example.com'
2543 }, {
2544 u'date': u'2017-03-17 05:19:37.500000',
2545 u'message': (
2546 u'Patch Set 2: Code-Review+1\n' +
2547 u'\n' +
2548 u'/COMMIT_MSG\n' +
2549 u' PS2, File comment: https://chromium-review.googlesource' +
2550 u'.com/c/1/2//COMMIT_MSG#\n' +
2551 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002552 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002553 u'approval': False,
2554 u'disapproval': False,
2555 u'sender': u'reviewer@example.com'
2556 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002557 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002558 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002559 expected_comments_summary = [
2560 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002561 message=(
2562 u'PTAL\n' +
2563 u'\n' +
2564 u'codereview.settings\n' +
2565 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2566 u'c/1/2/codereview.settings#b42\n' +
2567 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002568 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002569 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002570 disapproval=False, approval=False, sender=u'owner@example.com'),
2571 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002572 message=(
2573 u'Patch Set 2: Code-Review+1\n' +
2574 u'\n' +
2575 u'/COMMIT_MSG\n' +
2576 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2577 u'c/1/2//COMMIT_MSG#\n' +
2578 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002579 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002580 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002581 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2582 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002583 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002584 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002585 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002586 self.assertEqual(
2587 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2588
2589 def test_git_cl_comments_robot_comments(self):
2590 # git cl comments also fetches robot comments (which are considered a type
2591 # of autogenerated comment), and unlike other types of comments, only robot
2592 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002593 self.mockGit.config['remote.origin.url'] = (
2594 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002595 gerrit_util.GetChangeDetail.return_value = {
2596 'owner': {'email': 'owner@example.com'},
2597 'current_revision': 'ba5eba11',
2598 'revisions': {
2599 'deadbeaf': {
2600 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002601 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002602 'ba5eba11': {
2603 '_number': 2,
2604 },
2605 },
2606 'messages': [
2607 {
2608 u'_revision_number': 1,
2609 u'author': {
2610 u'_account_id': 1111084,
2611 u'email': u'commit-bot@chromium.org',
2612 u'name': u'Commit Bot'
2613 },
2614 u'date': u'2017-03-15 20:08:45.000000000',
2615 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2616 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2617 u'tag': u'autogenerated:cq:dry-run'
2618 },
2619 {
2620 u'_revision_number': 1,
2621 u'author': {
2622 u'_account_id': 123,
2623 u'email': u'tricium@serviceaccount.com',
2624 u'name': u'Tricium'
2625 },
2626 u'date': u'2017-03-16 20:00:41.000000000',
2627 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2628 u'message': u'(1 comment)',
2629 u'tag': u'autogenerated:tricium',
2630 },
2631 {
2632 u'_revision_number': 1,
2633 u'author': {
2634 u'_account_id': 123,
2635 u'email': u'tricium@serviceaccount.com',
2636 u'name': u'Tricium'
2637 },
2638 u'date': u'2017-03-16 20:00:41.000000000',
2639 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2640 u'message': u'(1 comment)',
2641 u'tag': u'autogenerated:tricium',
2642 },
2643 {
2644 u'_revision_number': 2,
2645 u'author': {
2646 u'_account_id': 123,
2647 u'email': u'tricium@serviceaccount.com',
2648 u'name': u'reviewer'
2649 },
2650 u'date': u'2017-03-17 05:30:37.000000000',
2651 u'tag': u'autogenerated:tricium',
2652 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2653 u'message': u'(1 comment)',
2654 },
2655 ]
2656 }
2657 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002658 (('GetChangeComments', 'chromium-review.googlesource.com',
2659 'infra%2Finfra~1'), {}),
2660 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2661 'infra%2Finfra~1'), {
2662 'codereview.settings': [
2663 {
2664 u'author': {u'email': u'tricium@serviceaccount.com'},
2665 u'updated': u'2017-03-17 05:30:37.000000000',
2666 u'robot_run_id': u'5565031076855808',
2667 u'robot_id': u'Linter/Category',
2668 u'tag': u'autogenerated:tricium',
2669 u'patch_set': 2,
2670 u'side': u'REVISION',
2671 u'message': u'Linter warning message text',
2672 u'line': 32,
2673 },
2674 ],
2675 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002676 ]
2677 expected_comments_summary = [
2678 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2679 message=(
2680 u'(1 comment)\n\ncodereview.settings\n'
2681 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2682 u'c/1/2/codereview.settings#32\n'
2683 u' Linter warning message text\n'),
2684 sender=u'tricium@serviceaccount.com',
2685 autogenerated=True, approval=False, disapproval=False)
2686 ]
2687 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002688 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002689 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002690
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002691 def test_get_remote_url_with_mirror(self):
2692 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002693
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002694 def selective_os_path_isdir_mock(path):
2695 if path == '/cache/this-dir-exists':
2696 return self._mocked_call('os.path.isdir', path)
2697 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002698
Edward Lemurda4b6c62020-02-13 00:28:40 +00002699 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002700
2701 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002702 self.mockGit.config['remote.origin.url'] = (
2703 '/cache/this-dir-exists')
2704 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2705 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002706 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002707 (('os.path.isdir', '/cache/this-dir-exists'),
2708 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002709 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002710 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002711 self.assertEqual(cl.GetRemoteUrl(), url)
2712 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2713
Edward Lemur298f2cf2019-02-22 21:40:39 +00002714 def test_get_remote_url_non_existing_mirror(self):
2715 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002716
Edward Lemur298f2cf2019-02-22 21:40:39 +00002717 def selective_os_path_isdir_mock(path):
2718 if path == '/cache/this-dir-doesnt-exist':
2719 return self._mocked_call('os.path.isdir', path)
2720 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002721
Edward Lemurda4b6c62020-02-13 00:28:40 +00002722 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2723 mock.patch('logging.error',
2724 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002725
Edward Lemur26964072020-02-19 19:18:51 +00002726 self.mockGit.config['remote.origin.url'] = (
2727 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002728 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002729 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2730 False),
2731 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002732 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2733 'but it doesn\'t exist.', {
2734 'remote': 'origin',
2735 'branch': 'master',
2736 'url': '/cache/this-dir-doesnt-exist'}
2737 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002738 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002739 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002740 self.assertIsNone(cl.GetRemoteUrl())
2741
2742 def test_get_remote_url_misconfigured_mirror(self):
2743 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002744
Edward Lemur298f2cf2019-02-22 21:40:39 +00002745 def selective_os_path_isdir_mock(path):
2746 if path == '/cache/this-dir-exists':
2747 return self._mocked_call('os.path.isdir', path)
2748 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002749
Edward Lemurda4b6c62020-02-13 00:28:40 +00002750 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2751 mock.patch('logging.error',
2752 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002753
Edward Lemur26964072020-02-19 19:18:51 +00002754 self.mockGit.config['remote.origin.url'] = (
2755 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002756 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002757 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002758 (('logging.error',
2759 'Remote "%(remote)s" for branch "%(branch)s" points to '
2760 '"%(cache_path)s", but it is misconfigured.\n'
2761 '"%(cache_path)s" must be a git repo and must have a remote named '
2762 '"%(remote)s" pointing to the git host.', {
2763 'remote': 'origin',
2764 'cache_path': '/cache/this-dir-exists',
2765 'branch': 'master'}
2766 ), None),
2767 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002768 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002769 self.assertIsNone(cl.GetRemoteUrl())
2770
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002771 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002772 self.mockGit.config['remote.origin.url'] = (
2773 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002774 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002775 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2776
2777 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002778 mock.patch('logging.error',
2779 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002780
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002781 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002782 (('logging.error',
2783 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2784 'but it doesn\'t exist.', {
2785 'remote': 'origin',
2786 'branch': 'master',
2787 'url': ''}
2788 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002789 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002790 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002791 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002792
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002793
Edward Lemur9aa1a962020-02-25 00:58:38 +00002794class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002795 def setUp(self):
2796 super(ChangelistTest, self).setUp()
2797 mock.patch('gclient_utils.FileRead').start()
2798 mock.patch('gclient_utils.FileWrite').start()
2799 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2800 mock.patch(
2801 'git_cl.Changelist.GetCodereviewServer',
2802 return_value='https://chromium-review.googlesource.com').start()
2803 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2804 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2805 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2806 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2807 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2808 mock.patch('git_cl.time_time').start()
2809 mock.patch('metrics.collector').start()
2810 mock.patch('subprocess2.Popen').start()
2811 self.addCleanup(mock.patch.stopall)
2812 self.temp_count = 0
2813
Edward Lemur227d5102020-02-25 23:45:35 +00002814 def testRunHook(self):
2815 expected_results = {
2816 'more_cc': ['more@example.com', 'cc@example.com'],
2817 'should_continue': True,
2818 }
2819 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2820 git_cl.time_time.side_effect = [100, 200]
2821 mockProcess = mock.Mock()
2822 mockProcess.wait.return_value = 0
2823 subprocess2.Popen.return_value = mockProcess
2824
2825 cl = git_cl.Changelist()
2826 results = cl.RunHook(
2827 committing=True,
2828 may_prompt=True,
2829 verbose=2,
2830 parallel=True,
2831 upstream='upstream',
2832 description='description',
2833 all_files=True)
2834
2835 self.assertEqual(expected_results, results)
2836 subprocess2.Popen.assert_called_once_with([
2837 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002838 '--root', 'root',
2839 '--upstream', 'upstream',
2840 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002841 '--author', 'author',
2842 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002843 '--issue', '123456',
2844 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002845 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002846 '--may_prompt',
2847 '--parallel',
2848 '--all_files',
2849 '--json_output', '/tmp/fake-temp2',
2850 '--description_file', '/tmp/fake-temp1',
2851 ])
2852 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002853 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002854 metrics.collector.add_repeated('sub_commands', {
2855 'command': 'presubmit',
2856 'execution_time': 100,
2857 'exit_code': 0,
2858 })
2859
Edward Lemur99df04e2020-03-05 19:39:43 +00002860 def testRunHook_FewerOptions(self):
2861 expected_results = {
2862 'more_cc': ['more@example.com', 'cc@example.com'],
2863 'should_continue': True,
2864 }
2865 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2866 git_cl.time_time.side_effect = [100, 200]
2867 mockProcess = mock.Mock()
2868 mockProcess.wait.return_value = 0
2869 subprocess2.Popen.return_value = mockProcess
2870
2871 git_cl.Changelist.GetAuthor.return_value = None
2872 git_cl.Changelist.GetIssue.return_value = None
2873 git_cl.Changelist.GetPatchset.return_value = None
2874 git_cl.Changelist.GetCodereviewServer.return_value = None
2875
2876 cl = git_cl.Changelist()
2877 results = cl.RunHook(
2878 committing=False,
2879 may_prompt=False,
2880 verbose=0,
2881 parallel=False,
2882 upstream='upstream',
2883 description='description',
2884 all_files=False)
2885
2886 self.assertEqual(expected_results, results)
2887 subprocess2.Popen.assert_called_once_with([
2888 'vpython', 'PRESUBMIT_SUPPORT',
2889 '--root', 'root',
2890 '--upstream', 'upstream',
2891 '--upload',
2892 '--json_output', '/tmp/fake-temp2',
2893 '--description_file', '/tmp/fake-temp1',
2894 ])
2895 gclient_utils.FileWrite.assert_called_once_with(
2896 '/tmp/fake-temp1', 'description')
2897 metrics.collector.add_repeated('sub_commands', {
2898 'command': 'presubmit',
2899 'execution_time': 100,
2900 'exit_code': 0,
2901 })
2902
Edward Lemur227d5102020-02-25 23:45:35 +00002903 @mock.patch('sys.exit', side_effect=SystemExitMock)
2904 def testRunHook_Failure(self, _mock):
2905 git_cl.time_time.side_effect = [100, 200]
2906 mockProcess = mock.Mock()
2907 mockProcess.wait.return_value = 2
2908 subprocess2.Popen.return_value = mockProcess
2909
2910 cl = git_cl.Changelist()
2911 with self.assertRaises(SystemExitMock):
2912 cl.RunHook(
2913 committing=True,
2914 may_prompt=True,
2915 verbose=2,
2916 parallel=True,
2917 upstream='upstream',
2918 description='description',
2919 all_files=True)
2920
2921 sys.exit.assert_called_once_with(2)
2922
Edward Lemur75526302020-02-27 22:31:05 +00002923 def testRunPostUploadHook(self):
2924 cl = git_cl.Changelist()
2925 cl.RunPostUploadHook(2, 'upstream', 'description')
2926
2927 subprocess2.Popen.assert_called_once_with([
2928 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002929 '--root', 'root',
2930 '--upstream', 'upstream',
2931 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002932 '--author', 'author',
2933 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002934 '--issue', '123456',
2935 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002936 '--post_upload',
2937 '--description_file', '/tmp/fake-temp1',
2938 ])
2939 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002940 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002941
Edward Lemur9aa1a962020-02-25 00:58:38 +00002942
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002943class CMDTestCaseBase(unittest.TestCase):
2944 _STATUSES = [
2945 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2946 'INFRA_FAILURE', 'CANCELED',
2947 ]
2948 _CHANGE_DETAIL = {
2949 'project': 'depot_tools',
2950 'status': 'OPEN',
2951 'owner': {'email': 'owner@e.mail'},
2952 'current_revision': 'beeeeeef',
2953 'revisions': {
2954 'deadbeaf': {'_number': 6},
2955 'beeeeeef': {
2956 '_number': 7,
2957 'fetch': {'http': {
2958 'url': 'https://chromium.googlesource.com/depot_tools',
2959 'ref': 'refs/changes/56/123456/7'
2960 }},
2961 },
2962 },
2963 }
2964 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002965 'builds': [{
2966 'id': str(100 + idx),
2967 'builder': {
2968 'project': 'chromium',
2969 'bucket': 'try',
2970 'builder': 'bot_' + status.lower(),
2971 },
2972 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2973 'tags': [],
2974 'status': status,
2975 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002976 }
2977
Edward Lemur4c707a22019-09-24 21:13:43 +00002978 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002979 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002980 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002981 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2982 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002983 mock.patch(
2984 'git_cl.Changelist.GetCodereviewServer',
2985 return_value='https://chromium-review.googlesource.com').start()
2986 mock.patch(
2987 'git_cl.Changelist._GetGerritHost',
2988 return_value='chromium-review.googlesource.com').start()
2989 mock.patch(
2990 'git_cl.Changelist.GetMostRecentPatchset',
2991 return_value=7).start()
2992 mock.patch(
2993 'git_cl.Changelist.GetRemoteUrl',
2994 return_value='https://chromium.googlesource.com/depot_tools').start()
2995 mock.patch(
2996 'auth.Authenticator',
2997 return_value=AuthenticatorMock()).start()
2998 mock.patch(
2999 'gerrit_util.GetChangeDetail',
3000 return_value=self._CHANGE_DETAIL).start()
3001 mock.patch(
3002 'git_cl._call_buildbucket',
3003 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003004 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003005 self.addCleanup(mock.patch.stopall)
3006
Edward Lemur4c707a22019-09-24 21:13:43 +00003007
Edward Lemur9468eba2020-02-27 19:07:22 +00003008class CMDPresubmitTestCase(CMDTestCaseBase):
3009 def setUp(self):
3010 super(CMDPresubmitTestCase, self).setUp()
3011 mock.patch(
3012 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3013 return_value='upstream').start()
3014 mock.patch(
3015 'git_cl.Changelist.FetchDescription',
3016 return_value='fetch description').start()
3017 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003018 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003019 return_value='get description').start()
3020 mock.patch('git_cl.Changelist.RunHook').start()
3021
3022 def testDefaultCase(self):
3023 self.assertEqual(0, git_cl.main(['presubmit']))
3024 git_cl.Changelist.RunHook.assert_called_once_with(
3025 committing=True,
3026 may_prompt=False,
3027 verbose=0,
3028 parallel=None,
3029 upstream='upstream',
3030 description='fetch description',
3031 all_files=None)
3032
3033 def testNoIssue(self):
3034 git_cl.Changelist.GetIssue.return_value = None
3035 self.assertEqual(0, git_cl.main(['presubmit']))
3036 git_cl.Changelist.RunHook.assert_called_once_with(
3037 committing=True,
3038 may_prompt=False,
3039 verbose=0,
3040 parallel=None,
3041 upstream='upstream',
3042 description='get description',
3043 all_files=None)
3044
3045 def testCustomBranch(self):
3046 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3047 git_cl.Changelist.RunHook.assert_called_once_with(
3048 committing=True,
3049 may_prompt=False,
3050 verbose=0,
3051 parallel=None,
3052 upstream='custom_branch',
3053 description='fetch description',
3054 all_files=None)
3055
3056 def testOptions(self):
3057 self.assertEqual(
3058 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
3059 git_cl.Changelist.RunHook.assert_called_once_with(
3060 committing=False,
3061 may_prompt=False,
3062 verbose=2,
3063 parallel=True,
3064 upstream='upstream',
3065 description='fetch description',
3066 all_files=True)
3067
3068
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003069class CMDTryResultsTestCase(CMDTestCaseBase):
3070 _DEFAULT_REQUEST = {
3071 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003072 "gerritChanges": [{
3073 "project": "depot_tools",
3074 "host": "chromium-review.googlesource.com",
3075 "patchset": 7,
3076 "change": 123456,
3077 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003078 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003079 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3080 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003081 }
3082
3083 def testNoJobs(self):
3084 git_cl._call_buildbucket.return_value = {}
3085
3086 self.assertEqual(0, git_cl.main(['try-results']))
3087 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3088 git_cl._call_buildbucket.assert_called_once_with(
3089 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3090 self._DEFAULT_REQUEST)
3091
3092 def testPrintToStdout(self):
3093 self.assertEqual(0, git_cl.main(['try-results']))
3094 self.assertEqual([
3095 'Successes:',
3096 ' bot_success https://ci.chromium.org/b/103',
3097 'Infra Failures:',
3098 ' bot_infra_failure https://ci.chromium.org/b/105',
3099 'Failures:',
3100 ' bot_failure https://ci.chromium.org/b/104',
3101 'Canceled:',
3102 ' bot_canceled ',
3103 'Started:',
3104 ' bot_started https://ci.chromium.org/b/102',
3105 'Scheduled:',
3106 ' bot_scheduled id=101',
3107 'Other:',
3108 ' bot_status_unspecified id=100',
3109 'Total: 7 tryjobs',
3110 ], sys.stdout.getvalue().splitlines())
3111 git_cl._call_buildbucket.assert_called_once_with(
3112 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3113 self._DEFAULT_REQUEST)
3114
3115 def testPrintToStdoutWithMasters(self):
3116 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3117 self.assertEqual([
3118 'Successes:',
3119 ' try bot_success https://ci.chromium.org/b/103',
3120 'Infra Failures:',
3121 ' try bot_infra_failure https://ci.chromium.org/b/105',
3122 'Failures:',
3123 ' try bot_failure https://ci.chromium.org/b/104',
3124 'Canceled:',
3125 ' try bot_canceled ',
3126 'Started:',
3127 ' try bot_started https://ci.chromium.org/b/102',
3128 'Scheduled:',
3129 ' try bot_scheduled id=101',
3130 'Other:',
3131 ' try bot_status_unspecified id=100',
3132 'Total: 7 tryjobs',
3133 ], sys.stdout.getvalue().splitlines())
3134 git_cl._call_buildbucket.assert_called_once_with(
3135 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3136 self._DEFAULT_REQUEST)
3137
3138 @mock.patch('git_cl.write_json')
3139 def testWriteToJson(self, mockJsonDump):
3140 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3141 git_cl._call_buildbucket.assert_called_once_with(
3142 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3143 self._DEFAULT_REQUEST)
3144 mockJsonDump.assert_called_once_with(
3145 'file.json', self._DEFAULT_RESPONSE['builds'])
3146
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003147 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003148 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3149 self.assertEqual(
3150 [
3151 ('chromium', 'try', 'bot_failure'),
3152 ('chromium', 'try', 'bot_infra_failure'),
3153 ],
3154 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003155
3156 def test_filter_failed_for_retry_many_builds(self):
3157
3158 def _build(name, created_sec, status, experimental=False):
3159 assert 0 <= created_sec < 100, created_sec
3160 b = {
3161 'id': 112112,
3162 'builder': {
3163 'project': 'chromium',
3164 'bucket': 'try',
3165 'builder': name,
3166 },
3167 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3168 'status': status,
3169 'tags': [],
3170 }
3171 if experimental:
3172 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3173 return b
3174
3175 builds = [
3176 _build('flaky-last-green', 1, 'FAILURE'),
3177 _build('flaky-last-green', 2, 'SUCCESS'),
3178 _build('flaky', 1, 'SUCCESS'),
3179 _build('flaky', 2, 'FAILURE'),
3180 _build('running', 1, 'FAILED'),
3181 _build('running', 2, 'SCHEDULED'),
3182 _build('yep-still-running', 1, 'STARTED'),
3183 _build('yep-still-running', 2, 'FAILURE'),
3184 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3185 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3186
3187 # Simulate experimental in CQ builder, which developer decided
3188 # to retry manually which resulted in 2nd build non-experimental.
3189 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3190 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3191 ]
3192 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003193 self.assertEqual(
3194 [
3195 ('chromium', 'try', 'flaky'),
3196 ('chromium', 'try', 'sometimes-experimental'),
3197 ],
3198 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003199
3200
3201class CMDTryTestCase(CMDTestCaseBase):
3202
3203 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003204 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003205 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003206 self.assertEqual(0, git_cl.main(['try']))
3207 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3208 self.assertEqual(
3209 sys.stdout.getvalue(),
3210 'Scheduling CQ dry run on: '
3211 'https://chromium-review.googlesource.com/123456\n')
3212
Edward Lemur4c707a22019-09-24 21:13:43 +00003213 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003214 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003215 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003216
3217 self.assertEqual(0, git_cl.main([
3218 'try', '-B', 'luci.chromium.try', '-b', 'win',
3219 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3220 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003221 'Scheduling jobs on:\n'
3222 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003223 git_cl.sys.stdout.getvalue())
3224
3225 expected_request = {
3226 "requests": [{
3227 "scheduleBuild": {
3228 "requestId": "uuid4",
3229 "builder": {
3230 "project": "chromium",
3231 "builder": "win",
3232 "bucket": "try",
3233 },
3234 "gerritChanges": [{
3235 "project": "depot_tools",
3236 "host": "chromium-review.googlesource.com",
3237 "patchset": 7,
3238 "change": 123456,
3239 }],
3240 "properties": {
3241 "category": "git_cl_try",
3242 "json": [{"a": 1}, None],
3243 "key": "val",
3244 },
3245 "tags": [
3246 {"value": "win", "key": "builder"},
3247 {"value": "git_cl_try", "key": "user_agent"},
3248 ],
3249 },
3250 }],
3251 }
3252 mockCallBuildbucket.assert_called_with(
3253 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3254
Anthony Polito1a5fe232020-01-24 23:17:52 +00003255 @mock.patch('git_cl._call_buildbucket')
3256 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3257 mockCallBuildbucket.return_value = {}
3258
3259 self.assertEqual(0, git_cl.main([
3260 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3261 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3262 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3263 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003264 'Scheduling jobs on:\n'
3265 ' chromium/try: linux\n'
3266 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003267 git_cl.sys.stdout.getvalue())
3268
3269 expected_request = {
3270 "requests": [{
3271 "scheduleBuild": {
3272 "requestId": "uuid4",
3273 "builder": {
3274 "project": "chromium",
3275 "builder": "linux",
3276 "bucket": "try",
3277 },
3278 "gerritChanges": [{
3279 "project": "depot_tools",
3280 "host": "chromium-review.googlesource.com",
3281 "patchset": 7,
3282 "change": 123456,
3283 }],
3284 "properties": {
3285 "category": "git_cl_try",
3286 "json": [{"a": 1}, None],
3287 "key": "val",
3288 },
3289 "tags": [
3290 {"value": "linux", "key": "builder"},
3291 {"value": "git_cl_try", "key": "user_agent"},
3292 ],
3293 "gitilesCommit": {
3294 "host": "chromium-review.googlesource.com",
3295 "project": "depot_tools",
3296 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3297 }
3298 },
3299 },
3300 {
3301 "scheduleBuild": {
3302 "requestId": "uuid4",
3303 "builder": {
3304 "project": "chromium",
3305 "builder": "win",
3306 "bucket": "try",
3307 },
3308 "gerritChanges": [{
3309 "project": "depot_tools",
3310 "host": "chromium-review.googlesource.com",
3311 "patchset": 7,
3312 "change": 123456,
3313 }],
3314 "properties": {
3315 "category": "git_cl_try",
3316 "json": [{"a": 1}, None],
3317 "key": "val",
3318 },
3319 "tags": [
3320 {"value": "win", "key": "builder"},
3321 {"value": "git_cl_try", "key": "user_agent"},
3322 ],
3323 "gitilesCommit": {
3324 "host": "chromium-review.googlesource.com",
3325 "project": "depot_tools",
3326 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3327 }
3328 },
3329 }],
3330 }
3331 mockCallBuildbucket.assert_called_with(
3332 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3333
Edward Lemur45768512020-03-02 19:03:14 +00003334 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003335 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003336 with self.assertRaises(SystemExit):
3337 git_cl.main([
3338 'try', '-B', 'not-a-bucket', '-b', 'win',
3339 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003340 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003341 'Invalid bucket: not-a-bucket.',
3342 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003343
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003344 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003345 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003346 def testScheduleOnBuildbucketRetryFailed(
3347 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003348 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003349 7: [],
3350 6: [{
3351 'id': 112112,
3352 'builder': {
3353 'project': 'chromium',
3354 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003355 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003356 'createTime': '2019-10-09T08:00:01.854286Z',
3357 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003358 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003359 mockCallBuildbucket.return_value = {}
3360
3361 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3362 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003363 'Scheduling jobs on:\n'
3364 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003365 git_cl.sys.stdout.getvalue())
3366
3367 expected_request = {
3368 "requests": [{
3369 "scheduleBuild": {
3370 "requestId": "uuid4",
3371 "builder": {
3372 "project": "chromium",
3373 "bucket": "try",
3374 "builder": "linux",
3375 },
3376 "gerritChanges": [{
3377 "project": "depot_tools",
3378 "host": "chromium-review.googlesource.com",
3379 "patchset": 7,
3380 "change": 123456,
3381 }],
3382 "properties": {
3383 "category": "git_cl_try",
3384 },
3385 "tags": [
3386 {"value": "linux", "key": "builder"},
3387 {"value": "git_cl_try", "key": "user_agent"},
3388 {"value": "1", "key": "retry_failed"},
3389 ],
3390 },
3391 }],
3392 }
3393 mockCallBuildbucket.assert_called_with(
3394 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3395
Edward Lemur4c707a22019-09-24 21:13:43 +00003396 def test_parse_bucket(self):
3397 test_cases = [
3398 {
3399 'bucket': 'chromium/try',
3400 'result': ('chromium', 'try'),
3401 },
3402 {
3403 'bucket': 'luci.chromium.try',
3404 'result': ('chromium', 'try'),
3405 'has_warning': True,
3406 },
3407 {
3408 'bucket': 'skia.primary',
3409 'result': ('skia', 'skia.primary'),
3410 'has_warning': True,
3411 },
3412 {
3413 'bucket': 'not-a-bucket',
3414 'result': (None, None),
3415 },
3416 ]
3417
3418 for test_case in test_cases:
3419 git_cl.sys.stdout.truncate(0)
3420 self.assertEqual(
3421 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3422 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003423 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3424 test_case['result'])
3425 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003426
3427
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003428class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003429
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003430 def setUp(self):
3431 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003432 mock.patch('git_cl._fetch_tryjobs').start()
3433 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003434 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003435 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003436 self.addCleanup(mock.patch.stopall)
3437
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003438 def testWarmUpChangeDetailCache(self):
3439 self.assertEqual(0, git_cl.main(['upload']))
3440 gerrit_util.GetChangeDetail.assert_called_once_with(
3441 'chromium-review.googlesource.com', 'depot_tools~123456',
3442 frozenset([
3443 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3444 'CURRENT_COMMIT']))
3445
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003446 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003447 # This test mocks out the actual upload part, and just asserts that after
3448 # upload, if --retry-failed is added, then the tool will fetch try jobs
3449 # from the previous patchset and trigger the right builders on the latest
3450 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003451 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003452 # Latest patchset: No builds.
3453 [],
3454 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003455 [{
3456 'id': str(100 + idx),
3457 'builder': {
3458 'project': 'chromium',
3459 'bucket': 'try',
3460 'builder': 'bot_' + status.lower(),
3461 },
3462 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3463 'tags': [],
3464 'status': status,
3465 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003466 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003467
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003468 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003469 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003470 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3471 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003472 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003473 expected_buckets = [
3474 ('chromium', 'try', 'bot_failure'),
3475 ('chromium', 'try', 'bot_infra_failure'),
3476 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003477 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3478 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003479
Brian Sheedy59b06a82019-10-14 17:03:29 +00003480
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003481class MakeRequestsHelperTestCase(unittest.TestCase):
3482
3483 def exampleGerritChange(self):
3484 return {
3485 'host': 'chromium-review.googlesource.com',
3486 'project': 'depot_tools',
3487 'change': 1,
3488 'patchset': 2,
3489 }
3490
3491 def testMakeRequestsHelperNoOptions(self):
3492 # Basic test for the helper function _make_tryjob_schedule_requests;
3493 # it shouldn't throw AttributeError even when options doesn't have any
3494 # of the expected values; it will use default option values.
3495 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3496 jobs = [('chromium', 'try', 'my-builder')]
3497 options = optparse.Values()
3498 requests = git_cl._make_tryjob_schedule_requests(
3499 changelist, jobs, options, patchset=None)
3500
3501 # requestId is non-deterministic. Just assert that it's there and has
3502 # a particular length.
3503 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3504 self.assertEqual(requests, [{
3505 'scheduleBuild': {
3506 'builder': {
3507 'bucket': 'try',
3508 'builder': 'my-builder',
3509 'project': 'chromium'
3510 },
3511 'gerritChanges': [self.exampleGerritChange()],
3512 'properties': {
3513 'category': 'git_cl_try'
3514 },
3515 'tags': [{
3516 'key': 'builder',
3517 'value': 'my-builder'
3518 }, {
3519 'key': 'user_agent',
3520 'value': 'git_cl_try'
3521 }]
3522 }
3523 }])
3524
3525 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3526 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3527 jobs = [('chromium', 'try', 'presubmit')]
3528 options = optparse.Values()
3529 requests = git_cl._make_tryjob_schedule_requests(
3530 changelist, jobs, options, patchset=None)
3531 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3532 'category': 'git_cl_try',
3533 'dry_run': 'true'
3534 })
3535
3536 def testMakeRequestsHelperRevisionSet(self):
3537 # Gitiles commit is specified when revision is in options.
3538 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3539 jobs = [('chromium', 'try', 'my-builder')]
3540 options = optparse.Values({'revision': 'ba5eba11'})
3541 requests = git_cl._make_tryjob_schedule_requests(
3542 changelist, jobs, options, patchset=None)
3543 self.assertEqual(
3544 requests[0]['scheduleBuild']['gitilesCommit'], {
3545 'host': 'chromium-review.googlesource.com',
3546 'id': 'ba5eba11',
3547 'project': 'depot_tools'
3548 })
3549
3550 def testMakeRequestsHelperRetryFailedSet(self):
3551 # An extra tag is added when retry_failed is in options.
3552 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3553 jobs = [('chromium', 'try', 'my-builder')]
3554 options = optparse.Values({'retry_failed': 'true'})
3555 requests = git_cl._make_tryjob_schedule_requests(
3556 changelist, jobs, options, patchset=None)
3557 self.assertEqual(
3558 requests[0]['scheduleBuild']['tags'], [
3559 {
3560 'key': 'builder',
3561 'value': 'my-builder'
3562 },
3563 {
3564 'key': 'user_agent',
3565 'value': 'git_cl_try'
3566 },
3567 {
3568 'key': 'retry_failed',
3569 'value': '1'
3570 }
3571 ])
3572
3573 def testMakeRequestsHelperCategorySet(self):
3574 # The category property can be overriden with options.
3575 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3576 jobs = [('chromium', 'try', 'my-builder')]
3577 options = optparse.Values({'category': 'my-special-category'})
3578 requests = git_cl._make_tryjob_schedule_requests(
3579 changelist, jobs, options, patchset=None)
3580 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3581 {'category': 'my-special-category'})
3582
3583
Edward Lemurda4b6c62020-02-13 00:28:40 +00003584class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003585
3586 def setUp(self):
3587 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003588 mock.patch('git_cl.RunCommand').start()
3589 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3590 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3591 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003592 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003593 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003594
3595 def tearDown(self):
3596 shutil.rmtree(self._top_dir)
3597 super(CMDFormatTestCase, self).tearDown()
3598
Jamie Madill5e96ad12020-01-13 16:08:35 +00003599 def _make_temp_file(self, fname, contents):
3600 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3601 tf.write('\n'.join(contents))
3602
Brian Sheedy59b06a82019-10-14 17:03:29 +00003603 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003604 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003605
Brian Sheedyb4307d52019-12-02 19:18:17 +00003606 def _check_yapf_filtering(self, files, expected):
3607 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3608 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003609
Edward Lemur1a83da12020-03-04 21:18:36 +00003610 def _run_command_mock(self, return_value):
3611 def f(*args, **kwargs):
3612 if 'stdin' in kwargs:
3613 self.assertIsInstance(kwargs['stdin'], bytes)
3614 return return_value
3615 return f
3616
Jamie Madill5e96ad12020-01-13 16:08:35 +00003617 def testClangFormatDiffFull(self):
3618 self._make_temp_file('test.cc', ['// test'])
3619 git_cl.settings.GetFormatFullByDefault.return_value = False
3620 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3621 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3622
3623 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003624 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003625 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3626 self._top_dir, 'HEAD')
3627 self.assertEqual(2, return_value)
3628
3629 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003630 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003631 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3632 self._top_dir, 'HEAD')
3633 self.assertEqual(0, return_value)
3634
3635 def testClangFormatDiff(self):
3636 git_cl.settings.GetFormatFullByDefault.return_value = False
3637 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3638
3639 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003640 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3641 return_value = git_cl._RunClangFormatDiff(
3642 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003643 self.assertEqual(2, return_value)
3644
3645 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003646 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003647 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3648 'HEAD')
3649 self.assertEqual(0, return_value)
3650
Brian Sheedyb4307d52019-12-02 19:18:17 +00003651 def testYapfignoreExplicit(self):
3652 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3653 files = [
3654 'bar.py',
3655 'foo/bar.py',
3656 'foo/baz.py',
3657 'foo/bar/baz.py',
3658 'foo/bar/foobar.py',
3659 ]
3660 expected = [
3661 'bar.py',
3662 'foo/baz.py',
3663 'foo/bar/foobar.py',
3664 ]
3665 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003666
Brian Sheedyb4307d52019-12-02 19:18:17 +00003667 def testYapfignoreSingleWildcards(self):
3668 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3669 files = [
3670 'bar.py', # Matched by *bar.py.
3671 'bar.txt',
3672 'foobar.py', # Matched by *bar.py, foo*.
3673 'foobar.txt', # Matched by foo*.
3674 'bazbar.py', # Matched by *bar.py, baz*.py.
3675 'bazbar.txt',
3676 'foo/baz.txt', # Matched by foo*.
3677 'bar/bar.py', # Matched by *bar.py.
3678 'baz/foo.py', # Matched by baz*.py, foo*.
3679 'baz/foo.txt',
3680 ]
3681 expected = [
3682 'bar.txt',
3683 'bazbar.txt',
3684 'baz/foo.txt',
3685 ]
3686 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003687
Brian Sheedyb4307d52019-12-02 19:18:17 +00003688 def testYapfignoreMultiplewildcards(self):
3689 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3690 files = [
3691 'bar.py', # Matched by *bar*.
3692 'bar.txt', # Matched by *bar*.
3693 'abar.py', # Matched by *bar*.
3694 'foobaz.txt', # Matched by *foo*baz.txt.
3695 'foobaz.py',
3696 'afoobaz.txt', # Matched by *foo*baz.txt.
3697 ]
3698 expected = [
3699 'foobaz.py',
3700 ]
3701 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003702
3703 def testYapfignoreComments(self):
3704 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003705 files = [
3706 'test.py',
3707 'test2.py',
3708 ]
3709 expected = [
3710 'test2.py',
3711 ]
3712 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003713
3714 def testYapfignoreBlankLines(self):
3715 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003716 files = [
3717 'test.py',
3718 'test2.py',
3719 'test3.py',
3720 ]
3721 expected = [
3722 'test3.py',
3723 ]
3724 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003725
3726 def testYapfignoreWhitespace(self):
3727 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003728 files = [
3729 'test.py',
3730 'test2.py',
3731 ]
3732 expected = [
3733 'test2.py',
3734 ]
3735 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003736
Brian Sheedyb4307d52019-12-02 19:18:17 +00003737 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003738 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003739 self._check_yapf_filtering([], [])
3740
3741 def testYapfignoreMissingYapfignore(self):
3742 files = [
3743 'test.py',
3744 ]
3745 expected = [
3746 'test.py',
3747 ]
3748 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003749
3750
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003751if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003752 logging.basicConfig(
3753 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003754 unittest.main()