blob: 0ddc5a999591740fb5f513281ab17339b6b1f226 [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
Josip Sokcevic464e9ff2020-03-18 23:48:55 +000048NETRC_FILENAME = '_netrc' if sys.platform == 'win32' else '.netrc'
49
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000050
Edward Lemur0db01f02019-11-12 22:01:51 +000051def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070052 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
53
tandrii5d48c322016-08-18 16:19:37 -070054CERR1 = callError(1)
55
56
Edward Lemur1773f372020-02-22 00:27:14 +000057class TemporaryFileMock(object):
58 def __init__(self):
59 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070060
Edward Lemur1773f372020-02-22 00:27:14 +000061 @contextlib.contextmanager
62 def __call__(self):
63 self.suffix += 1
64 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070065
66
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000067class ChangelistMock(object):
68 # A class variable so we can access it when we don't have access to the
69 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000070 desc = ''
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000071
72 def __init__(self, gerrit_change=None, **kwargs):
73 self._gerrit_change = gerrit_change
74
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000075 def GetIssue(self):
76 return 1
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000077
Edward Lemur6c6827c2020-02-06 21:15:18 +000078 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000079 return ChangelistMock.desc
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000080
dsansomee2d6fd92016-09-08 00:10:47 -070081 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000082 ChangelistMock.desc = desc
83
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000084 def GetGerritChange(self, patchset=None, **kwargs):
85 del patchset
86 return self._gerrit_change
87
tandrii5d48c322016-08-18 16:19:37 -070088
Edward Lemur85153282020-02-14 22:06:29 +000089class GitMocks(object):
90 def __init__(self, config=None, branchref=None):
91 self.branchref = branchref or 'refs/heads/master'
92 self.config = config or {}
93
94 def GetBranchRef(self, _root):
95 return self.branchref
96
97 def NewBranch(self, branchref):
98 self.branchref = branchref
99
Edward Lemur26964072020-02-19 19:18:51 +0000100 def GetConfig(self, root, key, default=None):
101 if root != '':
102 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000103 return self.config.get(key, default)
104
Edward Lemur26964072020-02-19 19:18:51 +0000105 def SetConfig(self, root, key, value=None):
106 if root != '':
107 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000108 if value:
109 self.config[key] = value
110 return
111 if key not in self.config:
112 raise CERR1
113 del self.config[key]
114
115
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000116class WatchlistsMock(object):
117 def __init__(self, _):
118 pass
119 @staticmethod
120 def GetWatchersForPaths(_):
121 return ['joe@example.com']
122
123
Edward Lemur4c707a22019-09-24 21:13:43 +0000124class CodereviewSettingsFileMock(object):
125 def __init__(self):
126 pass
127 # pylint: disable=no-self-use
128 def read(self):
129 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
130 'GERRIT_HOST: True\n')
131
132
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000133class AuthenticatorMock(object):
134 def __init__(self, *_args):
135 pass
136 def has_cached_credentials(self):
137 return True
tandrii221ab252016-10-06 08:12:04 -0700138 def authorize(self, http):
139 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000140
141
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100142def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000143 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
144
145 Usage:
146 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100147 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000148
149 OR
150 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100151 CookiesAuthenticatorMockFactory(
152 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000153 """
154 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800155 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000156 # Intentionally not calling super() because it reads actual cookie files.
157 pass
158 @classmethod
159 def get_gitcookies_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000160 return os.path.join('~', '.gitcookies')
161
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000162 @classmethod
163 def get_netrc_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000164 return os.path.join('~', NETRC_FILENAME)
165
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100166 def _get_auth_for_host(self, host):
167 if same_auth:
168 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000169 return (hosts_with_creds or {}).get(host)
170 return CookiesAuthenticatorMock
171
Aaron Gable9a03ae02017-11-03 11:31:07 -0700172
kmarshall9249e012016-08-23 12:02:16 -0700173class MockChangelistWithBranchAndIssue():
174 def __init__(self, branch, issue):
175 self.branch = branch
176 self.issue = issue
177 def GetBranch(self):
178 return self.branch
179 def GetIssue(self):
180 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000181
tandriic2405f52016-10-10 08:13:15 -0700182
183class SystemExitMock(Exception):
184 pass
185
186
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000187class TestGitClBasic(unittest.TestCase):
Josip Sokcevic953278a2020-02-28 19:46:36 +0000188 def setUp(self):
189 mock.patch('sys.exit', side_effect=SystemExitMock).start()
190 mock.patch('sys.stdout', StringIO()).start()
191 mock.patch('sys.stderr', StringIO()).start()
192 self.addCleanup(mock.patch.stopall)
193
194 def test_die_with_error(self):
195 with self.assertRaises(SystemExitMock):
196 git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
197 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
198 self.assertTrue('saving CL description' in sys.stdout.getvalue())
199 self.assertTrue('Content of CL description' in sys.stdout.getvalue())
200 self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
201 sys.exit.assert_called_once_with(1)
202
203 def test_die_with_error_no_desc(self):
204 with self.assertRaises(SystemExitMock):
205 git_cl.DieWithError('foo')
206 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
207 self.assertEqual(sys.stdout.getvalue(), '')
208 sys.exit.assert_called_once_with(1)
209
Edward Lemur6c6827c2020-02-06 21:15:18 +0000210 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000211 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100212 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000213 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700214
Edward Lemur61bf4172020-02-24 23:22:37 +0000215 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
216 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
217 def test_get_cl_statuses(self, *_mocks):
218 statuses = [
219 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
220 changes = []
221 for status in statuses:
222 cl = git_cl.Changelist()
223 cl.status = status
224 changes.append(cl)
225
226 actual = set(git_cl.get_cl_statuses(changes, True))
227 self.assertEqual(set(zip(changes, statuses)), actual)
228
229 def test_get_cl_statuses_no_changes(self):
230 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
231
232 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
233 @mock.patch('multiprocessing.pool.ThreadPool')
234 def test_get_cl_statuses_timeout(self, *_mocks):
235 changes = [git_cl.Changelist() for _ in range(2)]
236 pool = multiprocessing.pool.ThreadPool()
237 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
238 it.return_value.next.side_effect = [
239 (changes[0], 'lgtm'),
240 multiprocessing.TimeoutError,
241 ]
242
243 actual = list(git_cl.get_cl_statuses(changes, True))
244 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
245
246 @mock.patch('git_cl.Changelist.GetIssueURL')
247 def test_get_cl_statuses_not_finegrained(self, _mock):
248 changes = [git_cl.Changelist() for _ in range(2)]
249 urls = ['some-url', None]
250 git_cl.Changelist.GetIssueURL.side_effect = urls
251
252 actual = set(git_cl.get_cl_statuses(changes, False))
253 self.assertEqual(
254 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
255
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000256 def test_get_issue_url(self):
257 cl = git_cl.Changelist(issue=123)
258 cl._gerrit_server = 'https://example.com'
259 self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
260 self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
261
262 cl = git_cl.Changelist(issue=123)
263 cl._gerrit_server = 'https://chromium-review.googlesource.com'
264 self.assertEqual(cl.GetIssueURL(),
265 'https://chromium-review.googlesource.com/123')
266 self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
267
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000268 def test_set_preserve_tryjobs(self):
269 d = git_cl.ChangeDescription('Simple.')
270 d.set_preserve_tryjobs()
271 self.assertEqual(d.description.splitlines(), [
272 'Simple.',
273 '',
274 'Cq-Do-Not-Cancel-Tryjobs: true',
275 ])
276 before = d.description
277 d.set_preserve_tryjobs()
278 self.assertEqual(before, d.description)
279
280 d = git_cl.ChangeDescription('\n'.join([
281 'One is enough',
282 '',
283 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
284 'Change-Id: Ideadbeef',
285 ]))
286 d.set_preserve_tryjobs()
287 self.assertEqual(d.description.splitlines(), [
288 'One is enough',
289 '',
290 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
291 'Change-Id: Ideadbeef',
292 'Cq-Do-Not-Cancel-Tryjobs: true',
293 ])
294
tandriif9aefb72016-07-01 09:06:51 -0700295 def test_get_bug_line_values(self):
296 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
297 self.assertEqual(f('', ''), [])
298 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
299 self.assertEqual(f('v8', '456'), ['v8:456'])
300 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
301 # Not nice, but not worth carying.
302 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
303 ['v8:456', 'chromium:123', 'v8:123'])
304
Edward Lemurda4b6c62020-02-13 00:28:40 +0000305 @mock.patch('gerrit_util.GetAccountDetails')
306 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000307 mock_per_account = {
308 'u1': None, # 404, doesn't exist.
309 'u2': {
310 '_account_id': 123124,
311 'avatars': [],
312 'email': 'u2@example.com',
313 'name': 'User Number 2',
314 'status': 'OOO',
315 },
316 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
317 }
318 def GetAccountDetailsMock(_, account):
319 # Poor-man's mock library's side_effect.
320 v = mock_per_account.pop(account)
321 if isinstance(v, Exception):
322 raise v
323 return v
324
Edward Lemurda4b6c62020-02-13 00:28:40 +0000325 mockGetAccountDetails.side_effect = GetAccountDetailsMock
326 actual = git_cl.gerrit_util.ValidAccounts(
327 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000328 self.assertEqual(actual, {
329 'u2': {
330 '_account_id': 123124,
331 'avatars': [],
332 'email': 'u2@example.com',
333 'name': 'User Number 2',
334 'status': 'OOO',
335 },
336 })
337
338
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200339class TestParseIssueURL(unittest.TestCase):
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000340 def _test(self, arg, issue=None, patchset=None, hostname=None, fail=False):
341 parsed = git_cl.ParseIssueNumberArgument(arg)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200342 self.assertIsNotNone(parsed)
343 if fail:
344 self.assertFalse(parsed.valid)
345 return
346 self.assertTrue(parsed.valid)
347 self.assertEqual(parsed.issue, issue)
348 self.assertEqual(parsed.patchset, patchset)
349 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200350
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000351 def test_basic(self):
352 self._test('123', 123)
353 self._test('', fail=True)
354 self._test('abc', fail=True)
355 self._test('123/1', fail=True)
356 self._test('123a', fail=True)
357 self._test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
358 self._test('ssh://chrome-review.source.com/c/123/1/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200359
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000360 def test_gerrit_url(self):
361 self._test('https://codereview.source.com/123', 123, None,
362 'codereview.source.com')
363 self._test('http://chrome-review.source.com/c/123', 123, None,
364 'chrome-review.source.com')
365 self._test('https://chrome-review.source.com/c/123/', 123, None,
366 'chrome-review.source.com')
367 self._test('https://chrome-review.source.com/c/123/4', 123, 4,
368 'chrome-review.source.com')
369 self._test('https://chrome-review.source.com/#/c/123/4', 123, 4,
370 'chrome-review.source.com')
371 self._test('https://chrome-review.source.com/c/123/4', 123, 4,
372 'chrome-review.source.com')
373 self._test('https://chrome-review.source.com/123', 123, None,
374 'chrome-review.source.com')
375 self._test('https://chrome-review.source.com/123/4', 123, 4,
376 'chrome-review.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200377
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000378 self._test('https://chrome-review.source.com/bad/123/4', fail=True)
379 self._test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
380 self._test('https://chrome-review.source.com/c/abc/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200381
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000382 def test_short_urls(self):
383 self._test('https://crrev.com/c/2151934', 2151934, None,
384 'chromium-review.googlesource.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200385
386
Edward Lemurda4b6c62020-02-13 00:28:40 +0000387class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100388 def setUp(self):
389 super(GitCookiesCheckerTest, self).setUp()
390 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100391 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000392 mock.patch('sys.stdout', StringIO()).start()
393 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100394
395 def mock_hosts_creds(self, subhost_identity_pairs):
396 def ensure_googlesource(h):
397 if not h.endswith(self.c._GOOGLESOURCE):
398 assert not h.endswith('.')
399 return h + '.' + self.c._GOOGLESOURCE
400 return h
401 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
402 for h, i in subhost_identity_pairs]
403
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200404 def test_identity_parsing(self):
405 self.assertEqual(self.c._parse_identity('ldap.google.com'),
406 ('ldap', 'google.com'))
407 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
408 ('ldap', 'example.com'))
409 # Specical case because we know there are no subdomains in chromium.org.
410 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
411 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800412 # Pathological: ".period." can be either username OR domain, more likely
413 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200414 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
415 ('note', 'period.example.com'))
416
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100417 def test_analysis_nothing(self):
418 self.c._all_hosts = []
419 self.assertFalse(self.c.has_generic_host())
420 self.assertEqual(set(), self.c.get_conflicting_hosts())
421 self.assertEqual(set(), self.c.get_duplicated_hosts())
422 self.assertEqual(set(), self.c.get_partially_configured_hosts())
423 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
424
425 def test_analysis(self):
426 self.mock_hosts_creds([
427 ('.googlesource.com', 'git-example.chromium.org'),
428
429 ('chromium', 'git-example.google.com'),
430 ('chromium-review', 'git-example.google.com'),
431 ('chrome-internal', 'git-example.chromium.org'),
432 ('chrome-internal-review', 'git-example.chromium.org'),
433 ('conflict', 'git-example.google.com'),
434 ('conflict-review', 'git-example.chromium.org'),
435 ('dup', 'git-example.google.com'),
436 ('dup', 'git-example.google.com'),
437 ('dup-review', 'git-example.google.com'),
438 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200439 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100440 ])
441 self.assertTrue(self.c.has_generic_host())
442 self.assertEqual(set(['conflict.googlesource.com']),
443 self.c.get_conflicting_hosts())
444 self.assertEqual(set(['dup.googlesource.com']),
445 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200446 self.assertEqual(set(['partial.googlesource.com',
447 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100448 self.c.get_partially_configured_hosts())
449 self.assertEqual(set(['chromium.googlesource.com',
450 'chrome-internal.googlesource.com']),
451 self.c.get_hosts_with_wrong_identities())
452
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100453 def test_report_no_problems(self):
454 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100455 self.assertFalse(self.c.find_and_report_problems())
456 self.assertEqual(sys.stdout.getvalue(), '')
457
Edward Lemurda4b6c62020-02-13 00:28:40 +0000458 @mock.patch(
459 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000460 return_value=os.path.join('~', '.gitcookies'))
Edward Lemurda4b6c62020-02-13 00:28:40 +0000461 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100462 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100463 self.assertTrue(self.c.find_and_report_problems())
464 with open(os.path.join(os.path.dirname(__file__),
465 'git_cl_creds_check_report.txt')) as f:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000466 expected = f.read() % {
467 'sep': os.sep,
468 }
469
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100470 def by_line(text):
471 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700472 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200473 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100474
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800475
Edward Lemurda4b6c62020-02-13 00:28:40 +0000476class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000477 def setUp(self):
478 super(TestGitCl, self).setUp()
479 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700480 self._calls_done = []
Edward Lesmes0dd54822020-03-26 18:24:25 +0000481 self.failed = False
Edward Lemurda4b6c62020-02-13 00:28:40 +0000482 mock.patch('sys.stdout', StringIO()).start()
483 mock.patch(
484 'git_cl.time_time',
485 lambda: self._mocked_call('time.time')).start()
486 mock.patch(
487 'git_cl.metrics.collector.add_repeated',
488 lambda *a: self._mocked_call('add_repeated', *a)).start()
489 mock.patch('subprocess2.call', self._mocked_call).start()
490 mock.patch('subprocess2.check_call', self._mocked_call).start()
491 mock.patch('subprocess2.check_output', self._mocked_call).start()
492 mock.patch(
493 'subprocess2.communicate',
494 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
495 mock.patch(
496 'git_cl.gclient_utils.CheckCallAndFilter',
497 self._mocked_call).start()
498 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
499 mock.patch(
500 'git_common.get_or_create_merge_base',
501 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000502 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
503 mock.patch(
504 'git_cl.SaveDescriptionBackup',
505 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
506 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000507 'git_cl.write_json',
508 lambda *a: self._mocked_call('write_json', *a)).start()
509 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000510 'git_cl.Changelist.RunHook',
511 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000512 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
513 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000514 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000515 mock.patch(
516 'git_cl.gerrit_util.GetChangeComments',
517 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
518 mock.patch(
519 'git_cl.gerrit_util.GetChangeRobotComments',
520 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
521 mock.patch(
522 'git_cl.gerrit_util.AddReviewers',
523 lambda *a: self._mocked_call('AddReviewers', *a)).start()
524 mock.patch(
525 'git_cl.gerrit_util.SetReview',
526 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
527 self._mocked_call(
528 'SetReview', h, i, msg, labels, notify, ready))).start()
529 mock.patch(
530 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
531 return_value=False).start()
532 mock.patch(
533 'git_cl.gerrit_util.GceAuthenticator.is_gce',
534 return_value=False).start()
535 mock.patch(
536 'git_cl.gerrit_util.ValidAccounts',
537 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000538 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000539 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000540 self.mockGit = GitMocks()
541 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
542 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
Edward Lesmes50da7702020-03-30 19:23:43 +0000543 mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
544 mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
Edward Lemur85153282020-02-14 22:06:29 +0000545 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000546 mock.patch(
547 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000548 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000549 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000550 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000551 mock.patch(
552 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000553 # It's important to reset settings to not have inter-tests interference.
554 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000555 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000556
557 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000558 try:
Edward Lesmes0dd54822020-03-26 18:24:25 +0000559 if not self.failed:
560 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100561 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000562 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
563 if len(self.calls) > 5:
564 calls += ' ...\n'
565 self.fail(
566 '\n'
567 'There are un-consumed calls after this test has finished:\n' +
568 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000569 finally:
570 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000571
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000572 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000573 self.assertTrue(
574 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700575 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000576 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000577 expected_args, result = top
578
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000579 # Also logs otherwise it could get caught in a try/finally and be hard to
580 # diagnose.
581 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700582 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000583 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700584 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
585 for i, c in enumerate(self._calls_done[-N:]))
586 following_calls = '\n '.join(
587 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
588 for i, c in enumerate(self.calls[:N]))
589 extended_msg = (
590 'A few prior calls:\n %s\n\n'
591 'This (expected):\n @%d: %r\n'
592 'This (actual):\n @%d: %r\n\n'
593 'A few following expected calls:\n %s' %
594 (prior_calls, len(self._calls_done), expected_args,
595 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700596
Edward Lesmes0dd54822020-03-26 18:24:25 +0000597 self.failed = True
tandrii99a72f22016-08-17 14:33:24 -0700598 self.fail('@%d\n'
599 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000600 ' Actual: %r\n'
601 '\n'
602 '%s' % (
603 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700604
605 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700606 if isinstance(result, Exception):
607 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000608 # stdout from git commands is supposed to be a bytestream. Convert it here
609 # instead of converting all test output in this file to bytes.
610 if args[0][0] == 'git' and not isinstance(result, bytes):
611 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000612 return result
613
Edward Lemur1a83da12020-03-04 21:18:36 +0000614 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
615 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100616 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100617 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000618 self.assertEqual(
619 'prompt [Yes/No]: Please, type yes or no: ',
620 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100621
tandrii48df5812016-10-17 03:55:37 -0700622 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000623 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700624 self.calls = [
625 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700626 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
627 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
628 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
629 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700630 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
631 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700632 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
633 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000634 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
635 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700636 ((['git', 'config', 'gerrit.host', 'true'],), ''),
637 ]
638 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
639
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000640 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100641 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200642 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000643 custom_cl_base=None, short_hostname='chromium',
644 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000645 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200646 if custom_cl_base:
647 ancestor_revision = custom_cl_base
648 else:
649 # Determine ancestor_revision to be merge base.
650 ancestor_revision = 'fake_ancestor_sha'
651 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000652 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
653 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200654 ]
655
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100656 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000657 gerrit_util.GetChangeDetail.return_value = {
658 'owner': {'email': (other_cl_owner or 'owner@example.com')},
659 'change_id': (change_id or '123456789'),
660 'current_revision': 'sha1_of_current_revision',
661 'revisions': {'sha1_of_current_revision': {
662 'commit': {'message': fetched_description},
663 }},
664 'status': fetched_status or 'NEW',
665 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100666 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100667 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100668 if other_cl_owner:
669 calls += [
670 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
671 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100672
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100673 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200674 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
675 ([custom_cl_base] if custom_cl_base else
676 [ancestor_revision, 'HEAD']),),
677 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100678 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000679
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100680 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000681
Edward Lemur26964072020-02-19 19:18:51 +0000682 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700683 squash_mode='default',
Aaron Gablefd238082017-06-07 13:42:34 -0700684 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100685 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000686 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000687 short_hostname='chromium',
Edward Lemur5a644f82020-03-18 16:44:57 +0000688 labels=None, change_id=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000689 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000690 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000691 if post_amend_description is None:
692 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700693 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200694
695 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000696
Edward Lemur26964072020-02-19 19:18:51 +0000697 if squash_mode in ('override_squash', 'override_nosquash'):
698 self.mockGit.config['gerrit.override-squash-uploads'] = (
699 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700700
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000701 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000702 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200703 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200704 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000705 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000706 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000707 calls += [
708 ((['RunEditor'],), description),
709 ]
Josipe827b0f2020-01-30 00:07:20 +0000710 # user wants to edit description
711 if edit_description:
712 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000713 ((['RunEditor'],), edit_description),
714 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000715 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200716
717 if custom_cl_base is None:
718 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000719 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000720 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200721 ]
722 parent = 'origin/master'
723 else:
724 calls += [
725 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
726 'refs/remotes/origin/master'],),
727 callError(1)), # Means not ancenstor.
728 (('ask_for_data',
729 'Do you take responsibility for cleaning up potential mess '
730 'resulting from proceeding with upload? Press Enter to upload, '
731 'or Ctrl+C to abort'), ''),
732 ]
733 parent = custom_cl_base
734
735 calls += [
736 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
737 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000738 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200739 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000740 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200741 ref_to_push),
742 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000743 else:
744 ref_to_push = 'HEAD'
Edward Lemur5a644f82020-03-18 16:44:57 +0000745 parent = 'origin/refs/heads/master'
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000746
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000747 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000748 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000749 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200750 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000751
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000752 metrics_arguments = []
753
Aaron Gableafd52772017-06-27 16:40:10 -0700754 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700755 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000756 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700757 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400758 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700759 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000760 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700761 else:
762 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000763 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800764
Edward Lemur5a644f82020-03-18 16:44:57 +0000765 # If issue is given, then description is fetched from Gerrit instead.
766 if issue is None:
767 if squash:
768 title = 'Initial upload'
769 else:
770 if not title:
771 calls += [
772 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
773 (('ask_for_data', 'Title for patchset []: '), 'User input'),
774 ]
775 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700776 if title:
Edward Lemur5a644f82020-03-18 16:44:57 +0000777 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000778 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000779
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000780 if short_hostname == 'chromium':
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000781 # All reviewers and ccs get into ref_suffix.
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000782 for r in sorted(reviewers):
783 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000784 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000785 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000786 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000787 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000788 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000789 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000790 reviewers, cc = [], []
791 else:
792 # TODO(crbug/877717): remove this case.
793 calls += [
794 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
795 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000796 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000797 {
798 e: {'email': e}
799 for e in (reviewers + ['joe@example.com'] + cc)
800 })
801 ]
802 for r in sorted(reviewers):
803 if r != 'bad-account-or-email':
804 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000805 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000806 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000807 if issue is None:
808 cc += ['joe@example.com']
809 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000810 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000811 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000812 if c in cc:
813 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000814
Edward Lemur687ca902018-12-05 02:30:30 +0000815 for k, v in sorted((labels or {}).items()):
816 ref_suffix += ',l=%s+%d' % (k, v)
817 metrics_arguments.append('l=%s+%d' % (k, v))
818
819 if tbr:
820 calls += [
821 (('GetCodeReviewTbrScore',
822 '%s-review.googlesource.com' % short_hostname,
823 'my/repo'),
824 2,),
825 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000826
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000827 calls += [
828 (('time.time',), 1000,),
829 ((['git', 'push',
830 'https://%s.googlesource.com/my/repo' % short_hostname,
831 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
832 (('remote:\n'
833 'remote: Processing changes: (\)\n'
834 'remote: Processing changes: (|)\n'
835 'remote: Processing changes: (/)\n'
836 'remote: Processing changes: (-)\n'
837 'remote: Processing changes: new: 1 (/)\n'
838 'remote: Processing changes: new: 1, done\n'
839 'remote:\n'
840 'remote: New Changes:\n'
841 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
842 ' XXX\n'
843 'remote:\n'
844 'To https://%s.googlesource.com/my/repo\n'
845 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
846 ) % (short_hostname, short_hostname)),),
847 (('time.time',), 2000,),
848 (('add_repeated',
849 'sub_commands',
850 {
851 'execution_time': 1000,
852 'command': 'git push',
853 'exit_code': 0,
854 'arguments': sorted(metrics_arguments),
855 }),
856 None,),
857 ]
858
Edward Lemur1b52d872019-05-09 21:12:12 +0000859 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000860
861 date_format = ('03/16/17 20:00:41'
862 if sys.platform == 'win32' and sys.version_info.major == 2
863 else 'Thu Mar 16 20:00:41 2017')
864 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
865
Edward Lemur1b52d872019-05-09 21:12:12 +0000866 # Trace-related calls
867 calls += [
868 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000869 (
870 ([
871 'FileWrite', trace_name + '-README',
872 '%(date)s\n'
873 '%(short_hostname)s-review.googlesource.com\n'
874 '%(change_id)s\n'
875 '%(title)s\n'
876 '%(description)s\n'
877 '1000\n'
878 '0\n'
879 '%(trace_name)s' % {
880 'date': date_format,
881 'short_hostname': short_hostname,
882 'change_id': change_id,
883 'description': final_description,
884 'title': title or '<untitled>',
885 'trace_name': trace_name,
886 }
887 ], ),
888 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000889 ),
890 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000891 (
892 (['os.path.isfile',
893 os.path.join('TEMP_DIR', 'trace-packet')], ),
894 True,
Edward Lemur1b52d872019-05-09 21:12:12 +0000895 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000896 (
897 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
898 ('git-hash: 0123456789012345678901234567890123456789\n'
899 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +0000900 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000901 (
902 ([
903 'FileWrite',
904 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
905 'git-hash: abcdea\n'
906 ], ),
907 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000908 ),
909 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000910 (
911 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
912 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000913 ),
914 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000915 (
916 (['git', 'config', '-l'], ),
917 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +0000918 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000919 (
920 ([
921 'FileWrite',
922 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
923 ], ),
924 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000925 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000926 (
927 (['os.path.isfile',
928 os.path.join('~', '.gitcookies')], ),
929 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +0000930 ),
931 ]
932 if gitcookies_exists:
933 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000934 (
935 (['FileRead', os.path.join('~', '.gitcookies')], ),
936 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +0000937 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000938 (
939 ([
940 'FileWrite',
941 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
942 ], ),
943 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000944 ),
945 ]
946 calls += [
947 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000948 (
949 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
950 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000951 ),
952 ]
953
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000954 # TODO(crbug/877717): this should never be used.
955 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000956 calls += [
957 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +0000958 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000959 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +0000960 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +0000961 notify),
962 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000963 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000964 return calls
965
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000966 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000967 self,
968 upload_args,
969 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000970 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700971 squash=True,
972 squash_mode=None,
Aaron Gable9b713dd2016-12-14 16:04:21 -0800973 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000974 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000975 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -0700976 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100977 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100978 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200979 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -0700980 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000981 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000982 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000983 labels=None,
984 change_id=None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000985 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000986 gitcookies_exists=True,
987 force=False,
Edward Lesmes0dd54822020-03-26 18:24:25 +0000988 log_description=None,
Josipe827b0f2020-01-30 00:07:20 +0000989 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000990 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000991 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700992 if squash_mode is None:
993 if '--no-squash' in upload_args:
994 squash_mode = 'nosquash'
995 elif '--squash' in upload_args:
996 squash_mode = 'squash'
997 else:
998 squash_mode = 'default'
999
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001000 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001001 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001002 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001003 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001004 same_auth=('git-owner.example.com', '', 'pass'))).start()
1005 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1006 lambda _, offer_removal: None).start()
1007 mock.patch('git_cl.gclient_utils.RunEditor',
1008 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1009 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1010 'DownloadGerritHook', force)).start()
1011 mock.patch('git_cl.gclient_utils.FileRead',
1012 lambda path: self._mocked_call(['FileRead', path])).start()
1013 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001014 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001015 ['FileWrite', path, contents])).start()
1016 mock.patch('git_cl.datetime_now',
1017 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1018 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1019 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1020 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001021 '%(now)s\n'
1022 '%(gerrit_host)s\n'
1023 '%(change_id)s\n'
1024 '%(title)s\n'
1025 '%(description)s\n'
1026 '%(execution_time)s\n'
1027 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001028 '%(trace_name)s').start()
1029 mock.patch('git_cl.shutil.make_archive',
1030 lambda *args: self._mocked_call(['make_archive'] +
1031 list(args))).start()
1032 mock.patch('os.path.isfile',
1033 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001034 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001035 'git_cl._create_description_from_log',
1036 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001037 mock.patch(
1038 'git_cl.Changelist._AddChangeIdToCommitMessage',
1039 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001040 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001041 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1042 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001043 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001044 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001045
Edward Lemur26964072020-02-19 19:18:51 +00001046 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001047 self.mockGit.config['branch.master.gerritissue'] = (
1048 str(issue) if issue else None)
1049 self.mockGit.config['remote.origin.url'] = (
1050 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001051 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001052
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001053 self.calls = self._gerrit_base_calls(
1054 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001055 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001056 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001057 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001058 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001059 short_hostname=short_hostname,
1060 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001061 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001062 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001063 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001064 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001065 self.calls += self._gerrit_upload_calls(
1066 description, reviewers, squash,
1067 squash_mode=squash_mode,
Aaron Gablefd238082017-06-07 13:42:34 -07001068 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001069 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001070 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001071 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001072 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001073 labels=labels,
1074 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001075 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001076 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001077 force=force,
1078 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001079 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001080 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001081 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001082 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001083 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001084 self.assertEqual(
1085 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001086 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001087
Edward Lemur1b52d872019-05-09 21:12:12 +00001088 def test_gerrit_upload_traces_no_gitcookies(self):
1089 self._run_gerrit_upload_test(
1090 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001091 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001092 [],
1093 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001094 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001095 change_id='Ixxx',
1096 gitcookies_exists=False)
1097
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001098 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001099 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001100 [],
1101 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1102 [],
1103 change_id='Ixxx')
1104
1105 def test_gerrit_upload_without_change_id_nosquash(self):
1106 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001107 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001108 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001109 [],
1110 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001111 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001112 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001113
1114 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001115 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001116 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001117 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001118 [],
tandriia60502f2016-06-20 02:01:53 -07001119 squash=False,
1120 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001121 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001122 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001123
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001124 def test_gerrit_no_reviewer(self):
1125 self._run_gerrit_upload_test(
1126 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001127 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001128 [],
1129 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001130 squash_mode='override_nosquash',
1131 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001132
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001133 def test_gerrit_no_reviewer_non_chromium_host(self):
1134 # TODO(crbug/877717): remove this test case.
1135 self._run_gerrit_upload_test(
1136 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001137 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001138 [],
1139 squash=False,
1140 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001141 short_hostname='other',
1142 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001143
Edward Lesmes0dd54822020-03-26 18:24:25 +00001144 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001145 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001146 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001147 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001148 squash=False,
1149 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001150 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001151 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001152
ukai@chromium.orge8077812012-02-03 03:41:46 +00001153 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001154 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001155 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001156 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001157 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001158 squash=False,
1159 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001160 notify=True,
1161 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001162 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001163 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001164
Anthony Polito8b955342019-09-24 19:01:36 +00001165 def test_gerrit_upload_force_sets_bug(self):
1166 self._run_gerrit_upload_test(
1167 ['-b', '10000', '-f'],
1168 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1169 [],
1170 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001171 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001172 change_id='Ixxx')
1173
Edward Lemur5fb22242020-03-12 22:05:13 +00001174 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001175 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001176 ['-b', '10000', '-m', 'Title', '--edit-description'],
1177 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001178 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001179 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001180 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001181 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001182 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001183 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001184
Dan Beamd8b04ca2019-10-10 21:23:26 +00001185 def test_gerrit_upload_force_sets_fixed(self):
1186 self._run_gerrit_upload_test(
1187 ['-x', '10000', '-f'],
1188 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1189 [],
1190 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001191 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001192 change_id='Ixxx')
1193
ukai@chromium.orge8077812012-02-03 03:41:46 +00001194 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001195 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1196 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001197 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001198 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001199 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001200 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001201 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001202 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001203 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001204 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001205 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001206 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001207
1208 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001209 self._run_gerrit_upload_test(
1210 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001211 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001212 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001213 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001214
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001215 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001216 self._run_gerrit_upload_test(
1217 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001218 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001219 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001220 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001221 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001222
Edward Lesmes0dd54822020-03-26 18:24:25 +00001223 def test_gerrit_upload_squash_first_title(self):
1224 self._run_gerrit_upload_test(
1225 ['-f', '-t', 'title'],
1226 'title\n\ndesc\n\nChange-Id: 123456789',
1227 [],
1228 force=True,
1229 squash=True,
1230 log_description='desc',
1231 change_id='123456789')
1232
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001233 def test_gerrit_upload_squash_first_with_labels(self):
1234 self._run_gerrit_upload_test(
1235 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001236 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001237 [],
1238 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001239 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001240 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001241
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001242 def test_gerrit_upload_squash_first_against_rev(self):
1243 custom_cl_base = 'custom_cl_base_rev_or_branch'
1244 self._run_gerrit_upload_test(
1245 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001246 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001247 [],
1248 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001249 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001250 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001251 self.assertIn(
1252 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1253 sys.stdout.getvalue())
1254
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001255 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001256 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001257 self._run_gerrit_upload_test(
1258 ['--squash'],
1259 description,
1260 [],
1261 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001262 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001263 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001264
Edward Lemurd55c5072020-02-20 01:09:07 +00001265 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001266 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001267 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001268 with self.assertRaises(SystemExitMock):
1269 self._run_gerrit_upload_test(
1270 ['--squash'],
1271 description,
1272 [],
1273 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001274 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001275 fetched_status='ABANDONED',
1276 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001277 self.assertEqual(
1278 'Change https://chromium-review.googlesource.com/123456 has been '
1279 'abandoned, new uploads are not allowed\n',
1280 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001281
Edward Lemurda4b6c62020-02-13 00:28:40 +00001282 @mock.patch(
1283 'gerrit_util.GetAccountDetails',
1284 return_value={'email': 'yet-another@example.com'})
1285 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001286 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001287 self._run_gerrit_upload_test(
1288 ['--squash'],
1289 description,
1290 [],
1291 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001292 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001293 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001294 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001295 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001296 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001297 'authenticate to Gerrit as yet-another@example.com.\n'
1298 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001299 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001300
Josipe827b0f2020-01-30 00:07:20 +00001301 def test_upload_change_description_editor(self):
1302 fetched_description = 'foo\n\nChange-Id: 123456789'
1303 description = 'bar\n\nChange-Id: 123456789'
1304 self._run_gerrit_upload_test(
1305 ['--squash', '--edit-description'],
1306 description,
1307 [],
1308 fetched_description=fetched_description,
1309 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001310 issue=123456,
1311 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001312 edit_description=description)
1313
Edward Lemurda4b6c62020-02-13 00:28:40 +00001314 @mock.patch('git_cl.RunGit')
1315 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001316 @mock.patch('sys.stdin', StringIO('\n'))
1317 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001318 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001319 def mock_run_git(*args, **_kwargs):
1320 if args[0] == ['for-each-ref',
1321 '--format=%(refname:short) %(upstream:short)',
1322 'refs/heads']:
1323 # Create a local branch dependency tree that looks like this:
1324 # test1 -> test2 -> test3 -> test4 -> test5
1325 # -> test3.1
1326 # test6 -> test0
1327 branch_deps = [
1328 'test2 test1', # test1 -> test2
1329 'test3 test2', # test2 -> test3
1330 'test3.1 test2', # test2 -> test3.1
1331 'test4 test3', # test3 -> test4
1332 'test5 test4', # test4 -> test5
1333 'test6 test0', # test0 -> test6
1334 'test7', # test7
1335 ]
1336 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001337 git_cl.RunGit.side_effect = mock_run_git
1338 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001339
1340 class MockChangelist():
1341 def __init__(self):
1342 pass
1343 def GetBranch(self):
1344 return 'test1'
1345 def GetIssue(self):
1346 return '123'
1347 def GetPatchset(self):
1348 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001349 def IsGerrit(self):
1350 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001351
1352 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1353 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001354 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001355 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001356 'This command will checkout all dependent branches '
1357 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001358 'or Ctrl+C to abort',
1359 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001360 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001361
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001362 def test_gerrit_change_id(self):
1363 self.calls = [
1364 ((['git', 'write-tree'], ),
1365 'hashtree'),
1366 ((['git', 'rev-parse', 'HEAD~0'], ),
1367 'branch-parent'),
1368 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1369 'A B <a@b.org> 1456848326 +0100'),
1370 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1371 'C D <c@d.org> 1456858326 +0100'),
1372 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1373 'hashchange'),
1374 ]
1375 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1376 self.assertEqual(change_id, 'Ihashchange')
1377
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001378 def test_desecription_append_footer(self):
1379 for init_desc, footer_line, expected_desc in [
1380 # Use unique desc first lines for easy test failure identification.
1381 ('foo', 'R=one', 'foo\n\nR=one'),
1382 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1383 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1384 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1385 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1386 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1387 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1388 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1389 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1390 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1391 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1392 ]:
1393 desc = git_cl.ChangeDescription(init_desc)
1394 desc.append_footer(footer_line)
1395 self.assertEqual(desc.description, expected_desc)
1396
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001397 def test_update_reviewers(self):
1398 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001399 ('foo', [], [],
1400 'foo'),
1401 ('foo\nR=xx', [], [],
1402 'foo\nR=xx'),
1403 ('foo\nTBR=xx', [], [],
1404 'foo\nTBR=xx'),
1405 ('foo', ['a@c'], [],
1406 'foo\n\nR=a@c'),
1407 ('foo\nR=xx', ['a@c'], [],
1408 'foo\n\nR=a@c, xx'),
1409 ('foo\nTBR=xx', ['a@c'], [],
1410 'foo\n\nR=a@c\nTBR=xx'),
1411 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1412 'foo\n\nR=a@c, yy\nTBR=xx'),
1413 ('foo\nBUG=', ['a@c'], [],
1414 'foo\nBUG=\nR=a@c'),
1415 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1416 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1417 ('foo', ['a@c', 'b@c'], [],
1418 'foo\n\nR=a@c, b@c'),
1419 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1420 'foo\nBar\n\nR=c@c\nBUG='),
1421 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1422 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001423 # Same as the line before, but full of whitespaces.
1424 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001425 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001426 'foo\nBar\n\nR=c@c\n BUG =',
1427 ),
1428 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001429 ('foo BUG=allo R=joe ', ['c@c'], [],
1430 'foo BUG=allo R=joe\n\nR=c@c'),
1431 # Redundant TBRs get promoted to Rs
1432 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1433 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001434 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001435 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001436 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001437 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001438 obj = git_cl.ChangeDescription(orig)
Edward Lemur2c62b332020-03-12 22:12:33 +00001439 obj.update_reviewers(reviewers, tbrs, None, None, None)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001440 actual.append(obj.description)
1441 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001442
Nodir Turakulov23b82142017-11-16 11:04:25 -08001443 def test_get_hash_tags(self):
1444 cases = [
1445 ('', []),
1446 ('a', []),
1447 ('[a]', ['a']),
1448 ('[aa]', ['aa']),
1449 ('[a ]', ['a']),
1450 ('[a- ]', ['a']),
1451 ('[a- b]', ['a-b']),
1452 ('[a--b]', ['a-b']),
1453 ('[a', []),
1454 ('[a]x', ['a']),
1455 ('[aa]x', ['aa']),
1456 ('[a b]', ['a-b']),
1457 ('[a b]', ['a-b']),
1458 ('[a__b]', ['a-b']),
1459 ('[a] x', ['a']),
1460 ('[a][b]', ['a', 'b']),
1461 ('[a] [b]', ['a', 'b']),
1462 ('[a][b]x', ['a', 'b']),
1463 ('[a][b] x', ['a', 'b']),
1464 ('[a]\n[b]', ['a']),
1465 ('[a\nb]', []),
1466 ('[a][', ['a']),
1467 ('Revert "[a] feature"', ['a']),
1468 ('Reland "[a] feature"', ['a']),
1469 ('Revert: [a] feature', ['a']),
1470 ('Reland: [a] feature', ['a']),
1471 ('Revert "Reland: [a] feature"', ['a']),
1472 ('Foo: feature', ['foo']),
1473 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001474 ('Change Foo::Bar', []),
1475 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001476 ('Revert "Foo bar: feature"', ['foo-bar']),
1477 ('Reland "Foo bar: feature"', ['foo-bar']),
1478 ]
1479 for desc, expected in cases:
1480 change_desc = git_cl.ChangeDescription(desc)
1481 actual = change_desc.get_hash_tags()
1482 self.assertEqual(
1483 actual,
1484 expected,
1485 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1486
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001487 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001488 self.assertEqual(None, git_cl.GetTargetRef(None,
1489 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001490 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001491
wittman@chromium.org455dc922015-01-26 20:15:50 +00001492 # Check default target refs for branches.
1493 self.assertEqual('refs/heads/master',
1494 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001495 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001496 self.assertEqual('refs/heads/master',
1497 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001498 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001499 self.assertEqual('refs/heads/master',
1500 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001501 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001502 self.assertEqual('refs/branch-heads/123',
1503 git_cl.GetTargetRef('origin',
1504 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001505 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001506 self.assertEqual('refs/diff/test',
1507 git_cl.GetTargetRef('origin',
1508 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001509 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001510 self.assertEqual('refs/heads/chrome/m42',
1511 git_cl.GetTargetRef('origin',
1512 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001513 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001514
1515 # Check target refs for user-specified target branch.
1516 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1517 'refs/remotes/branch-heads/123'):
1518 self.assertEqual('refs/branch-heads/123',
1519 git_cl.GetTargetRef('origin',
1520 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001521 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001522 for branch in ('origin/master', 'remotes/origin/master',
1523 'refs/remotes/origin/master'):
1524 self.assertEqual('refs/heads/master',
1525 git_cl.GetTargetRef('origin',
1526 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001527 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001528 for branch in ('master', 'heads/master', 'refs/heads/master'):
1529 self.assertEqual('refs/heads/master',
1530 git_cl.GetTargetRef('origin',
1531 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001532 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001533
Edward Lemurda4b6c62020-02-13 00:28:40 +00001534 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1535 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001536 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001537 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1538
Edward Lemur85153282020-02-14 22:06:29 +00001539 def assertIssueAndPatchset(
1540 self, branch='master', issue='123456', patchset='7',
1541 git_short_host='chromium'):
1542 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001543 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001544 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001545 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001546 self.assertEqual(
1547 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001548 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001549
Edward Lemur85153282020-02-14 22:06:29 +00001550 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001551 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001552 self.mockGit.config['remote.origin.url'] = (
1553 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001554 gerrit_util.GetChangeDetail.return_value = {
1555 'current_revision': '7777777777',
1556 'revisions': {
1557 '1111111111': {
1558 '_number': 1,
1559 'fetch': {'http': {
1560 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1561 'ref': 'refs/changes/56/123456/1',
1562 }},
1563 },
1564 '7777777777': {
1565 '_number': 7,
1566 'fetch': {'http': {
1567 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1568 'ref': 'refs/changes/56/123456/7',
1569 }},
1570 },
1571 },
1572 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001573
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001574 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001575 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001576 self.calls += [
1577 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1578 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001579 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001580 ]
1581 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001582 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001583
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001584 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001585 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001586 self.calls += [
1587 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1588 'refs/changes/56/123456/7'],), ''),
1589 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001590 ]
Edward Lemur85153282020-02-14 22:06:29 +00001591 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1592 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001593
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001594 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001595 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001596 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001597 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001598 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001599 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001600 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001601 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001602 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001603
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001604 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001605 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001606 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001607 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001608 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001609 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001610 ]
1611 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001612 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001613 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001614
Aaron Gable697a91b2018-01-19 15:20:15 -08001615 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001616 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001617 self.calls += [
1618 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1619 'refs/changes/56/123456/1'],), ''),
1620 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001621 ]
1622 self.assertEqual(git_cl.main(
1623 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1624 0)
Edward Lemur85153282020-02-14 22:06:29 +00001625 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001626
Edward Lemurd55c5072020-02-20 01:09:07 +00001627 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001628 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001629 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001630 self.calls += [
1631 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001632 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001633 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001634 ]
1635 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001636 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001637 self.assertEqual(
1638 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1639 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001640
Edward Lemurda4b6c62020-02-13 00:28:40 +00001641 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001642 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001643 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001644 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001645 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001646 self.mockGit.config['remote.origin.url'] = (
1647 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001648 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001649 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001650 self.assertEqual(
1651 'change 123456 at https://chromium-review.googlesource.com does not '
1652 'exist or you have no access to it\n',
1653 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001654
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001655 def _checkout_calls(self):
1656 return [
1657 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001658 'branch\\..*\\.gerritissue'], ),
1659 ('branch.ger-branch.gerritissue 123456\n'
1660 'branch.gbranch654.gerritissue 654321\n')),
1661 ]
1662
1663 def test_checkout_gerrit(self):
1664 """Tests git cl checkout <issue>."""
1665 self.calls = self._checkout_calls()
1666 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1667 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1668
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001669 def test_checkout_not_found(self):
1670 """Tests git cl checkout <issue>."""
1671 self.calls = self._checkout_calls()
1672 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1673
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001674 def test_checkout_no_branch_issues(self):
1675 """Tests git cl checkout <issue>."""
1676 self.calls = [
1677 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001678 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001679 ]
1680 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1681
Edward Lemur26964072020-02-19 19:18:51 +00001682 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001683 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001684 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001685 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001686 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1687 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001688 self.mockGit.config['remote.origin.url'] = (
1689 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001690 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001691 cl.branch = 'master'
1692 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001693 return cl
1694
Edward Lemurd55c5072020-02-20 01:09:07 +00001695 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001696 def test_gerrit_ensure_authenticated_missing(self):
1697 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001698 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001699 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001700 with self.assertRaises(SystemExitMock):
1701 cl.EnsureAuthenticated(force=False)
1702 self.assertEqual(
1703 'Credentials for the following hosts are required:\n'
1704 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001705 'These are read from ~%(sep)s.gitcookies '
1706 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001707 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001708 'https://chromium-review.googlesource.com/new-password\n' % {
1709 'sep': os.sep,
1710 'netrc': NETRC_FILENAME,
1711 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001712
1713 def test_gerrit_ensure_authenticated_conflict(self):
1714 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001715 'chromium.googlesource.com':
1716 ('git-one.example.com', None, 'secret1'),
1717 'chromium-review.googlesource.com':
1718 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001719 })
1720 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001721 (('ask_for_data', 'If you know what you are doing '
1722 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001723 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1724
1725 def test_gerrit_ensure_authenticated_ok(self):
1726 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001727 'chromium.googlesource.com':
1728 ('git-same.example.com', None, 'secret'),
1729 'chromium-review.googlesource.com':
1730 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001731 })
1732 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1733
tandrii@chromium.org28253532016-04-14 13:46:56 +00001734 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001735 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1736 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001737 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1738
Eric Boren2fb63102018-10-05 13:05:03 +00001739 def test_gerrit_ensure_authenticated_bearer_token(self):
1740 cl = self._test_gerrit_ensure_authenticated_common(auth={
1741 'chromium.googlesource.com':
1742 ('', None, 'secret'),
1743 'chromium-review.googlesource.com':
1744 ('', None, 'secret'),
1745 })
1746 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1747 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1748 'chromium.googlesource.com')
1749 self.assertTrue('Bearer' in header)
1750
Daniel Chengcf6269b2019-05-18 01:02:12 +00001751 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001752 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001753 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001754 (('logging.warning',
1755 'Ignoring branch %(branch)s with non-https remote '
1756 '%(remote)s', {
1757 'branch': 'master',
1758 'remote': 'custom-scheme://repo'}
1759 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001760 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001761 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1762 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1763 mock.patch('logging.warning',
1764 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001765 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001766 cl.branch = 'master'
1767 cl.branchref = 'refs/heads/master'
1768 cl.lookedup_issue = True
1769 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1770
Florian Mayerae510e82020-01-30 21:04:48 +00001771 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001772 self.mockGit.config['remote.origin.url'] = (
1773 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001774 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001775 (('logging.error',
1776 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1777 'but it doesn\'t exist.', {
1778 'remote': 'origin',
1779 'branch': 'master',
1780 'url': 'git@somehost.example:foo/bar.git'}
1781 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001782 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001783 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1784 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1785 mock.patch('logging.error',
1786 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001787 cl = git_cl.Changelist()
1788 cl.branch = 'master'
1789 cl.branchref = 'refs/heads/master'
1790 cl.lookedup_issue = True
1791 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1792
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001793 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001794 self.mockGit.config['branch.master.gerritissue'] = '123'
1795 self.mockGit.config['branch.master.gerritserver'] = (
1796 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001797 self.mockGit.config['remote.origin.url'] = (
1798 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001799 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001800 (('SetReview', 'chromium-review.googlesource.com',
1801 'infra%2Finfra~123', None,
1802 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001803 ]
tandriid9e5ce52016-07-13 02:32:59 -07001804
1805 def test_cmd_set_commit_gerrit_clear(self):
1806 self._cmd_set_commit_gerrit_common(0)
1807 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1808
1809 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001810 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001811 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1812
tandriid9e5ce52016-07-13 02:32:59 -07001813 def test_cmd_set_commit_gerrit(self):
1814 self._cmd_set_commit_gerrit_common(2)
1815 self.assertEqual(0, git_cl.main(['set-commit']))
1816
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001817 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001818 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001819 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001820
1821 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001822 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001823
Edward Lemurda4b6c62020-02-13 00:28:40 +00001824 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001825 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001826 try:
1827 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001828 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001829 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001830 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001831
1832 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001833 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001834 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001835 return 'foobar'
1836
Edward Lemurda4b6c62020-02-13 00:28:40 +00001837 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001838 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001839 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001840 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001841 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001842
iannuccie53c9352016-08-17 14:40:40 -07001843 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001844
iannuccie53c9352016-08-17 14:40:40 -07001845 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001846 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001847 return 'foobar'
1848
Edward Lemurda4b6c62020-02-13 00:28:40 +00001849 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
1850 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07001851 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001852 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07001853
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001854 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00001855 self.mockGit.config['remote.origin.url'] = (
1856 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001857 gerrit_util.GetChangeDetail.return_value = {
1858 'current_revision': 'sha1',
1859 'revisions': {'sha1': {
1860 'commit': {'message': 'foobar'},
1861 }},
1862 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001863 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001864 'description',
1865 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
1866 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001867 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001868
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001869 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001870 mock.patch('git_cl.Changelist', ChangelistMock).start()
1871 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001872
1873 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1874 self.assertEqual('hihi', ChangelistMock.desc)
1875
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001876 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001877 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001878
1879 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001880 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001881 '# Enter a description of the change.\n'
1882 '# This will be displayed on the codereview site.\n'
1883 '# The first line will also be used as the subject of the review.\n'
1884 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001885 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07001886 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001887 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001888 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07001889 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001890
Edward Lemur6c6827c2020-02-06 21:15:18 +00001891 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001892 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001893
Edward Lemurda4b6c62020-02-13 00:28:40 +00001894 mock.patch('git_cl.Changelist.FetchDescription',
1895 lambda *args: current_desc).start()
1896 mock.patch('git_cl.Changelist.UpdateDescription',
1897 UpdateDescription).start()
1898 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001899
Edward Lemur85153282020-02-14 22:06:29 +00001900 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001901 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001902
Dan Beamd8b04ca2019-10-10 21:23:26 +00001903 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
1904 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
1905
1906 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001907 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00001908 '# Enter a description of the change.\n'
1909 '# This will be displayed on the codereview site.\n'
1910 '# The first line will also be used as the subject of the review.\n'
1911 '#--------------------This line is 72 characters long'
1912 '--------------------\n'
1913 'Some.\n\nFixed: 123\nChange-Id: xxx',
1914 desc)
1915 return desc
1916
Edward Lemurda4b6c62020-02-13 00:28:40 +00001917 mock.patch('git_cl.Changelist.FetchDescription',
1918 lambda *args: current_desc).start()
1919 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00001920
Edward Lemur85153282020-02-14 22:06:29 +00001921 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001922 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00001923
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001924 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001925 mock.patch('git_cl.Changelist', ChangelistMock).start()
1926 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001927
1928 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1929 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1930
kmarshall3bff56b2016-06-06 18:31:47 -07001931 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001932 self.calls = [
1933 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00001934 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001935 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001936 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00001937 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001938 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001939
Edward Lemurda4b6c62020-02-13 00:28:40 +00001940 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001941 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001942 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1943 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001944 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001945
1946 self.assertEqual(0, git_cl.main(['archive', '-f']))
1947
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001948 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001949 self.calls = [
1950 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1951 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1952 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
1953 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001954 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
1955 ((['git', 'branch', '-D', 'foo'],), '')
1956 ]
1957
Edward Lemurda4b6c62020-02-13 00:28:40 +00001958 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001959 lambda branches, fine_grained, max_processes:
1960 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1961 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001962 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001963
1964 self.assertEqual(0, git_cl.main(['archive', '-f']))
1965
kmarshall3bff56b2016-06-06 18:31:47 -07001966 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001967 self.calls = [
1968 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1969 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001970 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001971 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001972
Edward Lemurda4b6c62020-02-13 00:28:40 +00001973 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001974 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00001975 [(MockChangelistWithBranchAndIssue('master', 1),
1976 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001977
1978 self.assertEqual(1, git_cl.main(['archive', '-f']))
1979
1980 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001981 self.calls = [
1982 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1983 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001984 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001985 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001986
Edward Lemurda4b6c62020-02-13 00:28:40 +00001987 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001988 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001989 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1990 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001991 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001992
kmarshall9249e012016-08-23 12:02:16 -07001993 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
1994
1995 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001996 self.calls = [
1997 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1998 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001999 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002000 ((['git', 'branch', '-D', 'foo'],), '')
2001 ]
kmarshall9249e012016-08-23 12:02:16 -07002002
Edward Lemurda4b6c62020-02-13 00:28:40 +00002003 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002004 lambda branches, fine_grained, max_processes:
2005 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2006 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002007 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002008
2009 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002010
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002011 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002012 self.calls = [
2013 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2014 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2015 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002016 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2017 'refs/tags/git-cl-archived-456-foo'),
2018 ((['git', 'branch', '-D', 'foo'],), CERR1),
2019 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2020 'refs/tags/git-cl-archived-456-foo'),
2021 ]
2022
Edward Lemurda4b6c62020-02-13 00:28:40 +00002023 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002024 lambda branches, fine_grained, max_processes:
2025 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2026 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002027 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002028
2029 self.assertEqual(0, git_cl.main(['archive', '-f']))
2030
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002031 def test_archive_with_format(self):
2032 self.calls = [
2033 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
2034 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2035 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2036 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2037 ((['git', 'branch', '-D', 'foo'], ), ''),
2038 ]
2039
2040 mock.patch('git_cl.get_cl_statuses',
2041 lambda branches, fine_grained, max_processes:
2042 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2043
2044 self.assertEqual(
2045 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2046
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002047 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002048 self.mockGit.config['branch.master.gerritissue'] = '123'
2049 self.mockGit.config['branch.master.gerritserver'] = (
2050 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002051 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002052 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002053 ]
2054 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002055 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2056 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002057
Aaron Gable400e9892017-07-12 15:31:21 -07002058 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002059 self.mockGit.config['branch.master.gerritissue'] = '123'
2060 self.mockGit.config['branch.master.gerritserver'] = (
2061 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002062 mock.patch('git_cl.Changelist.FetchDescription',
2063 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002064 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002065 ((['git', 'log', '-1', '--format=%B'],),
2066 'This is a description\n\nChange-Id: Ideadbeef'),
2067 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002068 ]
2069 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002070 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2071 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002072
phajdan.jre328cf92016-08-22 04:12:17 -07002073 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002074 self.mockGit.config['branch.master.gerritissue'] = '123'
2075 self.mockGit.config['branch.master.gerritserver'] = (
2076 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002077 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002078 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002079 {'issue': 123,
2080 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002081 ''),
2082 ]
2083 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2084
tandrii16e0b4e2016-06-07 10:34:28 -07002085 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002086 mock.patch(
2087 'git_cl.os.path.abspath',
2088 lambda path: self._mocked_call(['abspath', path])).start()
2089 mock.patch(
2090 'git_cl.os.path.exists',
2091 lambda path: self._mocked_call(['exists', path])).start()
2092 mock.patch(
2093 'git_cl.gclient_utils.FileRead',
2094 lambda path: self._mocked_call(['FileRead', path])).start()
2095 mock.patch(
2096 'git_cl.gclient_utils.rm_file_or_tree',
2097 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002098 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002099 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002100 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002101 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002102
2103 def test_GerritCommitMsgHookCheck_custom_hook(self):
2104 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002105 self.calls += [((['exists',
2106 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2107 ((['FileRead',
2108 os.path.join('.git', 'hooks', 'commit-msg')], ),
2109 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002110 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002111
2112 def test_GerritCommitMsgHookCheck_not_exists(self):
2113 cl = self._common_GerritCommitMsgHookCheck()
2114 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002115 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002116 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002117 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002118
2119 def test_GerritCommitMsgHookCheck(self):
2120 cl = self._common_GerritCommitMsgHookCheck()
2121 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002122 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2123 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002124 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002125 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002126 ((['rm_file_or_tree',
2127 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002128 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002129 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002130
tandriic4344b52016-08-29 06:04:54 -07002131 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002132 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2133 self.mockGit.config['branch.master.gerritserver'] = (
2134 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002135 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002136 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002137 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002138 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002139 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002140 'labels': {},
2141 'current_revision': 'deadbeaf',
2142 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002143 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002144 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002145 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002146 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2147 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002148 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002149 self.assertEqual(0, cl.CMDLand(force=True,
2150 bypass_hooks=True,
2151 verbose=True,
2152 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002153 self.assertIn(
2154 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002155 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002156 self.assertIn(
2157 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002158 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002159
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002160 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002161 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002162
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002163 def test_gerrit_change_detail_cache_simple(self):
2164 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002165 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002166 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002167 cl1._cached_remote_url = (
2168 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002169 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002170 cl2._cached_remote_url = (
2171 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002172 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2173 self.assertEqual(cl1._GetChangeDetail(), 'a')
2174 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002175
2176 def test_gerrit_change_detail_cache_options(self):
2177 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002178 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002179 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002180 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002181 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2182 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2183 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2184 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2185 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2186 self.assertEqual(cl._GetChangeDetail(), 'cab')
2187
2188 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2189 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2190 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2191 self.assertEqual(cl._GetChangeDetail(), 'cab')
2192
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002193 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002194 gerrit_util.GetChangeDetail.return_value = {
2195 'current_revision': 'rev1',
2196 'revisions': {
2197 'rev1': {'commit': {'message': 'desc1'}},
2198 },
2199 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002200
2201 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002202 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002203 cl._cached_remote_url = (
2204 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002205 self.assertEqual(cl.FetchDescription(), 'desc1')
2206 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002207
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002208 def test_print_current_creds(self):
2209 class CookiesAuthenticatorMock(object):
2210 def __init__(self):
2211 self.gitcookies = {
2212 'host.googlesource.com': ('user', 'pass'),
2213 'host-review.googlesource.com': ('user', 'pass'),
2214 }
2215 self.netrc = self
2216 self.netrc.hosts = {
2217 'github.com': ('user2', None, 'pass2'),
2218 'host2.googlesource.com': ('user3', None, 'pass'),
2219 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002220 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2221 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002222 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2223 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2224 ' Host\t User\t Which file',
2225 '============================\t=====\t===========',
2226 'host-review.googlesource.com\t user\t.gitcookies',
2227 ' host.googlesource.com\t user\t.gitcookies',
2228 ' host2.googlesource.com\tuser3\t .netrc',
2229 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002230 sys.stdout.seek(0)
2231 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002232 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2233 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2234 ' Host\tUser\t Which file',
2235 '============================\t====\t===========',
2236 'host-review.googlesource.com\tuser\t.gitcookies',
2237 ' host.googlesource.com\tuser\t.gitcookies',
2238 ])
2239
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002240 def _common_creds_check_mocks(self):
2241 def exists_mock(path):
2242 dirname = os.path.dirname(path)
2243 if dirname == os.path.expanduser('~'):
2244 dirname = '~'
2245 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002246 if base in (NETRC_FILENAME, '.gitcookies'):
2247 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002248 # git cl also checks for existence other files not relevant to this test.
2249 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002250 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002251 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002252 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002253 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002254
2255 def test_creds_check_gitcookies_not_configured(self):
2256 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002257 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2258 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002259 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002260 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2261 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2262 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2263 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2264 'or Ctrl+C to abort'), ''),
2265 (([
2266 'git', 'config', '--global', 'http.cookiefile',
2267 os.path.expanduser(os.path.join('~', '.gitcookies'))
2268 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002269 ]
2270 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002271 self.assertTrue(
2272 sys.stdout.getvalue().startswith(
2273 'You seem to be using outdated .netrc for git credentials:'))
2274 self.assertIn(
2275 '\nConfigured git to use .gitcookies from',
2276 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002277
2278 def test_creds_check_gitcookies_configured_custom_broken(self):
2279 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002280 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2281 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002282 custom_cookie_path = ('C:\\.gitcookies'
2283 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002284 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002285 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2286 ((['git', 'config', '--global', 'http.cookiefile'], ),
2287 custom_cookie_path),
2288 (('os.path.exists', custom_cookie_path), False),
2289 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2290 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2291 (([
2292 'git', 'config', '--global', 'http.cookiefile',
2293 os.path.expanduser(os.path.join('~', '.gitcookies'))
2294 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002295 ]
2296 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002297 self.assertIn(
2298 'WARNING: You have configured custom path to .gitcookies: ',
2299 sys.stdout.getvalue())
2300 self.assertIn(
2301 'However, your configured .gitcookies file is missing.',
2302 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002303
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002304 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002305 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002306 self.mockGit.config['remote.origin.url'] = (
2307 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002308 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002309 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002310 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002311 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002312 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002313 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002314
Edward Lemurda4b6c62020-02-13 00:28:40 +00002315 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2316 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002317 self.mockGit.config['remote.origin.url'] = (
2318 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002319 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002320 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002321 'current_revision': 'ba5eba11',
2322 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002323 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002324 '_number': 1,
2325 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002326 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002327 '_number': 2,
2328 },
2329 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002330 'messages': [
2331 {
2332 u'_revision_number': 1,
2333 u'author': {
2334 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002335 u'email': u'could-be-anything@example.com',
2336 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002337 },
2338 u'date': u'2017-03-15 20:08:45.000000000',
2339 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002340 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002341 u'tag': u'autogenerated:cq:dry-run'
2342 },
2343 {
2344 u'_revision_number': 2,
2345 u'author': {
2346 u'_account_id': 11151243,
2347 u'email': u'owner@example.com',
2348 u'name': u'owner'
2349 },
2350 u'date': u'2017-03-16 20:00:41.000000000',
2351 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2352 u'message': u'PTAL',
2353 },
2354 {
2355 u'_revision_number': 2,
2356 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002357 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002358 u'email': u'reviewer@example.com',
2359 u'name': u'reviewer'
2360 },
2361 u'date': u'2017-03-17 05:19:37.500000000',
2362 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2363 u'message': u'Patch Set 2: Code-Review+1',
2364 },
2365 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002366 }
2367 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002368 (('GetChangeComments', 'chromium-review.googlesource.com',
2369 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002370 '/COMMIT_MSG': [
2371 {
2372 'author': {'email': u'reviewer@example.com'},
2373 'updated': u'2017-03-17 05:19:37.500000000',
2374 'patch_set': 2,
2375 'side': 'REVISION',
2376 'message': 'Please include a bug link',
2377 },
2378 ],
2379 'codereview.settings': [
2380 {
2381 'author': {'email': u'owner@example.com'},
2382 'updated': u'2017-03-16 20:00:41.000000000',
2383 'patch_set': 2,
2384 'side': 'PARENT',
2385 'line': 42,
2386 'message': 'I removed this because it is bad',
2387 },
2388 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002389 }),
2390 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2391 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002392 ] * 2 + [
2393 (('write_json', 'output.json', [
2394 {
2395 u'date': u'2017-03-16 20:00:41.000000',
2396 u'message': (
2397 u'PTAL\n' +
2398 u'\n' +
2399 u'codereview.settings\n' +
2400 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2401 u'c/1/2/codereview.settings#b42\n' +
2402 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002403 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002404 u'approval': False,
2405 u'disapproval': False,
2406 u'sender': u'owner@example.com'
2407 }, {
2408 u'date': u'2017-03-17 05:19:37.500000',
2409 u'message': (
2410 u'Patch Set 2: Code-Review+1\n' +
2411 u'\n' +
2412 u'/COMMIT_MSG\n' +
2413 u' PS2, File comment: https://chromium-review.googlesource' +
2414 u'.com/c/1/2//COMMIT_MSG#\n' +
2415 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002416 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002417 u'approval': False,
2418 u'disapproval': False,
2419 u'sender': u'reviewer@example.com'
2420 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002421 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002422 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002423 expected_comments_summary = [
2424 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002425 message=(
2426 u'PTAL\n' +
2427 u'\n' +
2428 u'codereview.settings\n' +
2429 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2430 u'c/1/2/codereview.settings#b42\n' +
2431 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002432 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002433 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002434 disapproval=False, approval=False, sender=u'owner@example.com'),
2435 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002436 message=(
2437 u'Patch Set 2: Code-Review+1\n' +
2438 u'\n' +
2439 u'/COMMIT_MSG\n' +
2440 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2441 u'c/1/2//COMMIT_MSG#\n' +
2442 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002443 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002444 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002445 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2446 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002447 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002448 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002449 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002450 self.assertEqual(
2451 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2452
2453 def test_git_cl_comments_robot_comments(self):
2454 # git cl comments also fetches robot comments (which are considered a type
2455 # of autogenerated comment), and unlike other types of comments, only robot
2456 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002457 self.mockGit.config['remote.origin.url'] = (
2458 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002459 gerrit_util.GetChangeDetail.return_value = {
2460 'owner': {'email': 'owner@example.com'},
2461 'current_revision': 'ba5eba11',
2462 'revisions': {
2463 'deadbeaf': {
2464 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002465 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002466 'ba5eba11': {
2467 '_number': 2,
2468 },
2469 },
2470 'messages': [
2471 {
2472 u'_revision_number': 1,
2473 u'author': {
2474 u'_account_id': 1111084,
2475 u'email': u'commit-bot@chromium.org',
2476 u'name': u'Commit Bot'
2477 },
2478 u'date': u'2017-03-15 20:08:45.000000000',
2479 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2480 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2481 u'tag': u'autogenerated:cq:dry-run'
2482 },
2483 {
2484 u'_revision_number': 1,
2485 u'author': {
2486 u'_account_id': 123,
2487 u'email': u'tricium@serviceaccount.com',
2488 u'name': u'Tricium'
2489 },
2490 u'date': u'2017-03-16 20:00:41.000000000',
2491 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2492 u'message': u'(1 comment)',
2493 u'tag': u'autogenerated:tricium',
2494 },
2495 {
2496 u'_revision_number': 1,
2497 u'author': {
2498 u'_account_id': 123,
2499 u'email': u'tricium@serviceaccount.com',
2500 u'name': u'Tricium'
2501 },
2502 u'date': u'2017-03-16 20:00:41.000000000',
2503 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2504 u'message': u'(1 comment)',
2505 u'tag': u'autogenerated:tricium',
2506 },
2507 {
2508 u'_revision_number': 2,
2509 u'author': {
2510 u'_account_id': 123,
2511 u'email': u'tricium@serviceaccount.com',
2512 u'name': u'reviewer'
2513 },
2514 u'date': u'2017-03-17 05:30:37.000000000',
2515 u'tag': u'autogenerated:tricium',
2516 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2517 u'message': u'(1 comment)',
2518 },
2519 ]
2520 }
2521 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002522 (('GetChangeComments', 'chromium-review.googlesource.com',
2523 'infra%2Finfra~1'), {}),
2524 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2525 'infra%2Finfra~1'), {
2526 'codereview.settings': [
2527 {
2528 u'author': {u'email': u'tricium@serviceaccount.com'},
2529 u'updated': u'2017-03-17 05:30:37.000000000',
2530 u'robot_run_id': u'5565031076855808',
2531 u'robot_id': u'Linter/Category',
2532 u'tag': u'autogenerated:tricium',
2533 u'patch_set': 2,
2534 u'side': u'REVISION',
2535 u'message': u'Linter warning message text',
2536 u'line': 32,
2537 },
2538 ],
2539 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002540 ]
2541 expected_comments_summary = [
2542 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2543 message=(
2544 u'(1 comment)\n\ncodereview.settings\n'
2545 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2546 u'c/1/2/codereview.settings#32\n'
2547 u' Linter warning message text\n'),
2548 sender=u'tricium@serviceaccount.com',
2549 autogenerated=True, approval=False, disapproval=False)
2550 ]
2551 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002552 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002553 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002554
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002555 def test_get_remote_url_with_mirror(self):
2556 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002557
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002558 def selective_os_path_isdir_mock(path):
2559 if path == '/cache/this-dir-exists':
2560 return self._mocked_call('os.path.isdir', path)
2561 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002562
Edward Lemurda4b6c62020-02-13 00:28:40 +00002563 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002564
2565 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002566 self.mockGit.config['remote.origin.url'] = (
2567 '/cache/this-dir-exists')
2568 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2569 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002570 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002571 (('os.path.isdir', '/cache/this-dir-exists'),
2572 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002573 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002574 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002575 self.assertEqual(cl.GetRemoteUrl(), url)
2576 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2577
Edward Lemur298f2cf2019-02-22 21:40:39 +00002578 def test_get_remote_url_non_existing_mirror(self):
2579 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002580
Edward Lemur298f2cf2019-02-22 21:40:39 +00002581 def selective_os_path_isdir_mock(path):
2582 if path == '/cache/this-dir-doesnt-exist':
2583 return self._mocked_call('os.path.isdir', path)
2584 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002585
Edward Lemurda4b6c62020-02-13 00:28:40 +00002586 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2587 mock.patch('logging.error',
2588 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002589
Edward Lemur26964072020-02-19 19:18:51 +00002590 self.mockGit.config['remote.origin.url'] = (
2591 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002592 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002593 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2594 False),
2595 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002596 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2597 'but it doesn\'t exist.', {
2598 'remote': 'origin',
2599 'branch': 'master',
2600 'url': '/cache/this-dir-doesnt-exist'}
2601 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002602 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002603 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002604 self.assertIsNone(cl.GetRemoteUrl())
2605
2606 def test_get_remote_url_misconfigured_mirror(self):
2607 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002608
Edward Lemur298f2cf2019-02-22 21:40:39 +00002609 def selective_os_path_isdir_mock(path):
2610 if path == '/cache/this-dir-exists':
2611 return self._mocked_call('os.path.isdir', path)
2612 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002613
Edward Lemurda4b6c62020-02-13 00:28:40 +00002614 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2615 mock.patch('logging.error',
2616 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002617
Edward Lemur26964072020-02-19 19:18:51 +00002618 self.mockGit.config['remote.origin.url'] = (
2619 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002620 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002621 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002622 (('logging.error',
2623 'Remote "%(remote)s" for branch "%(branch)s" points to '
2624 '"%(cache_path)s", but it is misconfigured.\n'
2625 '"%(cache_path)s" must be a git repo and must have a remote named '
2626 '"%(remote)s" pointing to the git host.', {
2627 'remote': 'origin',
2628 'cache_path': '/cache/this-dir-exists',
2629 'branch': 'master'}
2630 ), None),
2631 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002632 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002633 self.assertIsNone(cl.GetRemoteUrl())
2634
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002635 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002636 self.mockGit.config['remote.origin.url'] = (
2637 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002638 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002639 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2640
2641 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002642 mock.patch('logging.error',
2643 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002644
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002645 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002646 (('logging.error',
2647 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2648 'but it doesn\'t exist.', {
2649 'remote': 'origin',
2650 'branch': 'master',
2651 'url': ''}
2652 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002653 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002654 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002655 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002656
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002657
Edward Lemur9aa1a962020-02-25 00:58:38 +00002658class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002659 def setUp(self):
2660 super(ChangelistTest, self).setUp()
2661 mock.patch('gclient_utils.FileRead').start()
2662 mock.patch('gclient_utils.FileWrite').start()
2663 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2664 mock.patch(
2665 'git_cl.Changelist.GetCodereviewServer',
2666 return_value='https://chromium-review.googlesource.com').start()
2667 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2668 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2669 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2670 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2671 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2672 mock.patch('git_cl.time_time').start()
2673 mock.patch('metrics.collector').start()
2674 mock.patch('subprocess2.Popen').start()
2675 self.addCleanup(mock.patch.stopall)
2676 self.temp_count = 0
2677
Edward Lemur227d5102020-02-25 23:45:35 +00002678 def testRunHook(self):
2679 expected_results = {
2680 'more_cc': ['more@example.com', 'cc@example.com'],
2681 'should_continue': True,
2682 }
2683 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2684 git_cl.time_time.side_effect = [100, 200]
2685 mockProcess = mock.Mock()
2686 mockProcess.wait.return_value = 0
2687 subprocess2.Popen.return_value = mockProcess
2688
2689 cl = git_cl.Changelist()
2690 results = cl.RunHook(
2691 committing=True,
2692 may_prompt=True,
2693 verbose=2,
2694 parallel=True,
2695 upstream='upstream',
2696 description='description',
2697 all_files=True)
2698
2699 self.assertEqual(expected_results, results)
2700 subprocess2.Popen.assert_called_once_with([
2701 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002702 '--root', 'root',
2703 '--upstream', 'upstream',
2704 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002705 '--author', 'author',
2706 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002707 '--issue', '123456',
2708 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002709 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002710 '--may_prompt',
2711 '--parallel',
2712 '--all_files',
2713 '--json_output', '/tmp/fake-temp2',
2714 '--description_file', '/tmp/fake-temp1',
2715 ])
2716 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002717 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002718 metrics.collector.add_repeated('sub_commands', {
2719 'command': 'presubmit',
2720 'execution_time': 100,
2721 'exit_code': 0,
2722 })
2723
Edward Lemur99df04e2020-03-05 19:39:43 +00002724 def testRunHook_FewerOptions(self):
2725 expected_results = {
2726 'more_cc': ['more@example.com', 'cc@example.com'],
2727 'should_continue': True,
2728 }
2729 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2730 git_cl.time_time.side_effect = [100, 200]
2731 mockProcess = mock.Mock()
2732 mockProcess.wait.return_value = 0
2733 subprocess2.Popen.return_value = mockProcess
2734
2735 git_cl.Changelist.GetAuthor.return_value = None
2736 git_cl.Changelist.GetIssue.return_value = None
2737 git_cl.Changelist.GetPatchset.return_value = None
2738 git_cl.Changelist.GetCodereviewServer.return_value = None
2739
2740 cl = git_cl.Changelist()
2741 results = cl.RunHook(
2742 committing=False,
2743 may_prompt=False,
2744 verbose=0,
2745 parallel=False,
2746 upstream='upstream',
2747 description='description',
2748 all_files=False)
2749
2750 self.assertEqual(expected_results, results)
2751 subprocess2.Popen.assert_called_once_with([
2752 'vpython', 'PRESUBMIT_SUPPORT',
2753 '--root', 'root',
2754 '--upstream', 'upstream',
2755 '--upload',
2756 '--json_output', '/tmp/fake-temp2',
2757 '--description_file', '/tmp/fake-temp1',
2758 ])
2759 gclient_utils.FileWrite.assert_called_once_with(
2760 '/tmp/fake-temp1', 'description')
2761 metrics.collector.add_repeated('sub_commands', {
2762 'command': 'presubmit',
2763 'execution_time': 100,
2764 'exit_code': 0,
2765 })
2766
Edward Lemur227d5102020-02-25 23:45:35 +00002767 @mock.patch('sys.exit', side_effect=SystemExitMock)
2768 def testRunHook_Failure(self, _mock):
2769 git_cl.time_time.side_effect = [100, 200]
2770 mockProcess = mock.Mock()
2771 mockProcess.wait.return_value = 2
2772 subprocess2.Popen.return_value = mockProcess
2773
2774 cl = git_cl.Changelist()
2775 with self.assertRaises(SystemExitMock):
2776 cl.RunHook(
2777 committing=True,
2778 may_prompt=True,
2779 verbose=2,
2780 parallel=True,
2781 upstream='upstream',
2782 description='description',
2783 all_files=True)
2784
2785 sys.exit.assert_called_once_with(2)
2786
Edward Lemur75526302020-02-27 22:31:05 +00002787 def testRunPostUploadHook(self):
2788 cl = git_cl.Changelist()
2789 cl.RunPostUploadHook(2, 'upstream', 'description')
2790
2791 subprocess2.Popen.assert_called_once_with([
2792 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002793 '--root', 'root',
2794 '--upstream', 'upstream',
2795 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002796 '--author', 'author',
2797 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002798 '--issue', '123456',
2799 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002800 '--post_upload',
2801 '--description_file', '/tmp/fake-temp1',
2802 ])
2803 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002804 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002805
Edward Lemur9aa1a962020-02-25 00:58:38 +00002806
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002807class CMDTestCaseBase(unittest.TestCase):
2808 _STATUSES = [
2809 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2810 'INFRA_FAILURE', 'CANCELED',
2811 ]
2812 _CHANGE_DETAIL = {
2813 'project': 'depot_tools',
2814 'status': 'OPEN',
2815 'owner': {'email': 'owner@e.mail'},
2816 'current_revision': 'beeeeeef',
2817 'revisions': {
2818 'deadbeaf': {'_number': 6},
2819 'beeeeeef': {
2820 '_number': 7,
2821 'fetch': {'http': {
2822 'url': 'https://chromium.googlesource.com/depot_tools',
2823 'ref': 'refs/changes/56/123456/7'
2824 }},
2825 },
2826 },
2827 }
2828 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002829 'builds': [{
2830 'id': str(100 + idx),
2831 'builder': {
2832 'project': 'chromium',
2833 'bucket': 'try',
2834 'builder': 'bot_' + status.lower(),
2835 },
2836 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2837 'tags': [],
2838 'status': status,
2839 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002840 }
2841
Edward Lemur4c707a22019-09-24 21:13:43 +00002842 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002843 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002844 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002845 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2846 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002847 mock.patch(
2848 'git_cl.Changelist.GetCodereviewServer',
2849 return_value='https://chromium-review.googlesource.com').start()
2850 mock.patch(
2851 'git_cl.Changelist._GetGerritHost',
2852 return_value='chromium-review.googlesource.com').start()
2853 mock.patch(
2854 'git_cl.Changelist.GetMostRecentPatchset',
2855 return_value=7).start()
2856 mock.patch(
2857 'git_cl.Changelist.GetRemoteUrl',
2858 return_value='https://chromium.googlesource.com/depot_tools').start()
2859 mock.patch(
2860 'auth.Authenticator',
2861 return_value=AuthenticatorMock()).start()
2862 mock.patch(
2863 'gerrit_util.GetChangeDetail',
2864 return_value=self._CHANGE_DETAIL).start()
2865 mock.patch(
2866 'git_cl._call_buildbucket',
2867 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002868 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002869 self.addCleanup(mock.patch.stopall)
2870
Edward Lemur4c707a22019-09-24 21:13:43 +00002871
Edward Lemur9468eba2020-02-27 19:07:22 +00002872class CMDPresubmitTestCase(CMDTestCaseBase):
2873 def setUp(self):
2874 super(CMDPresubmitTestCase, self).setUp()
2875 mock.patch(
2876 'git_cl.Changelist.GetCommonAncestorWithUpstream',
2877 return_value='upstream').start()
2878 mock.patch(
2879 'git_cl.Changelist.FetchDescription',
2880 return_value='fetch description').start()
2881 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00002882 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00002883 return_value='get description').start()
2884 mock.patch('git_cl.Changelist.RunHook').start()
2885
2886 def testDefaultCase(self):
2887 self.assertEqual(0, git_cl.main(['presubmit']))
2888 git_cl.Changelist.RunHook.assert_called_once_with(
2889 committing=True,
2890 may_prompt=False,
2891 verbose=0,
2892 parallel=None,
2893 upstream='upstream',
2894 description='fetch description',
2895 all_files=None)
2896
2897 def testNoIssue(self):
2898 git_cl.Changelist.GetIssue.return_value = None
2899 self.assertEqual(0, git_cl.main(['presubmit']))
2900 git_cl.Changelist.RunHook.assert_called_once_with(
2901 committing=True,
2902 may_prompt=False,
2903 verbose=0,
2904 parallel=None,
2905 upstream='upstream',
2906 description='get description',
2907 all_files=None)
2908
2909 def testCustomBranch(self):
2910 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
2911 git_cl.Changelist.RunHook.assert_called_once_with(
2912 committing=True,
2913 may_prompt=False,
2914 verbose=0,
2915 parallel=None,
2916 upstream='custom_branch',
2917 description='fetch description',
2918 all_files=None)
2919
2920 def testOptions(self):
2921 self.assertEqual(
2922 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
2923 git_cl.Changelist.RunHook.assert_called_once_with(
2924 committing=False,
2925 may_prompt=False,
2926 verbose=2,
2927 parallel=True,
2928 upstream='upstream',
2929 description='fetch description',
2930 all_files=True)
2931
2932
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002933class CMDTryResultsTestCase(CMDTestCaseBase):
2934 _DEFAULT_REQUEST = {
2935 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002936 "gerritChanges": [{
2937 "project": "depot_tools",
2938 "host": "chromium-review.googlesource.com",
2939 "patchset": 7,
2940 "change": 123456,
2941 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002942 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002943 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2944 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002945 }
2946
2947 def testNoJobs(self):
2948 git_cl._call_buildbucket.return_value = {}
2949
2950 self.assertEqual(0, git_cl.main(['try-results']))
2951 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2952 git_cl._call_buildbucket.assert_called_once_with(
2953 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2954 self._DEFAULT_REQUEST)
2955
2956 def testPrintToStdout(self):
2957 self.assertEqual(0, git_cl.main(['try-results']))
2958 self.assertEqual([
2959 'Successes:',
2960 ' bot_success https://ci.chromium.org/b/103',
2961 'Infra Failures:',
2962 ' bot_infra_failure https://ci.chromium.org/b/105',
2963 'Failures:',
2964 ' bot_failure https://ci.chromium.org/b/104',
2965 'Canceled:',
2966 ' bot_canceled ',
2967 'Started:',
2968 ' bot_started https://ci.chromium.org/b/102',
2969 'Scheduled:',
2970 ' bot_scheduled id=101',
2971 'Other:',
2972 ' bot_status_unspecified id=100',
2973 'Total: 7 tryjobs',
2974 ], sys.stdout.getvalue().splitlines())
2975 git_cl._call_buildbucket.assert_called_once_with(
2976 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2977 self._DEFAULT_REQUEST)
2978
2979 def testPrintToStdoutWithMasters(self):
2980 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2981 self.assertEqual([
2982 'Successes:',
2983 ' try bot_success https://ci.chromium.org/b/103',
2984 'Infra Failures:',
2985 ' try bot_infra_failure https://ci.chromium.org/b/105',
2986 'Failures:',
2987 ' try bot_failure https://ci.chromium.org/b/104',
2988 'Canceled:',
2989 ' try bot_canceled ',
2990 'Started:',
2991 ' try bot_started https://ci.chromium.org/b/102',
2992 'Scheduled:',
2993 ' try bot_scheduled id=101',
2994 'Other:',
2995 ' try bot_status_unspecified id=100',
2996 'Total: 7 tryjobs',
2997 ], sys.stdout.getvalue().splitlines())
2998 git_cl._call_buildbucket.assert_called_once_with(
2999 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3000 self._DEFAULT_REQUEST)
3001
3002 @mock.patch('git_cl.write_json')
3003 def testWriteToJson(self, mockJsonDump):
3004 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3005 git_cl._call_buildbucket.assert_called_once_with(
3006 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3007 self._DEFAULT_REQUEST)
3008 mockJsonDump.assert_called_once_with(
3009 'file.json', self._DEFAULT_RESPONSE['builds'])
3010
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003011 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003012 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3013 self.assertEqual(
3014 [
3015 ('chromium', 'try', 'bot_failure'),
3016 ('chromium', 'try', 'bot_infra_failure'),
3017 ],
3018 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003019
3020 def test_filter_failed_for_retry_many_builds(self):
3021
3022 def _build(name, created_sec, status, experimental=False):
3023 assert 0 <= created_sec < 100, created_sec
3024 b = {
3025 'id': 112112,
3026 'builder': {
3027 'project': 'chromium',
3028 'bucket': 'try',
3029 'builder': name,
3030 },
3031 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3032 'status': status,
3033 'tags': [],
3034 }
3035 if experimental:
3036 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3037 return b
3038
3039 builds = [
3040 _build('flaky-last-green', 1, 'FAILURE'),
3041 _build('flaky-last-green', 2, 'SUCCESS'),
3042 _build('flaky', 1, 'SUCCESS'),
3043 _build('flaky', 2, 'FAILURE'),
3044 _build('running', 1, 'FAILED'),
3045 _build('running', 2, 'SCHEDULED'),
3046 _build('yep-still-running', 1, 'STARTED'),
3047 _build('yep-still-running', 2, 'FAILURE'),
3048 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3049 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3050
3051 # Simulate experimental in CQ builder, which developer decided
3052 # to retry manually which resulted in 2nd build non-experimental.
3053 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3054 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3055 ]
3056 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003057 self.assertEqual(
3058 [
3059 ('chromium', 'try', 'flaky'),
3060 ('chromium', 'try', 'sometimes-experimental'),
3061 ],
3062 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003063
3064
3065class CMDTryTestCase(CMDTestCaseBase):
3066
3067 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003068 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003069 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003070 self.assertEqual(0, git_cl.main(['try']))
3071 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3072 self.assertEqual(
3073 sys.stdout.getvalue(),
3074 'Scheduling CQ dry run on: '
3075 'https://chromium-review.googlesource.com/123456\n')
3076
Edward Lemur4c707a22019-09-24 21:13:43 +00003077 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003078 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003079 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003080
3081 self.assertEqual(0, git_cl.main([
3082 'try', '-B', 'luci.chromium.try', '-b', 'win',
3083 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3084 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003085 'Scheduling jobs on:\n'
3086 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003087 git_cl.sys.stdout.getvalue())
3088
3089 expected_request = {
3090 "requests": [{
3091 "scheduleBuild": {
3092 "requestId": "uuid4",
3093 "builder": {
3094 "project": "chromium",
3095 "builder": "win",
3096 "bucket": "try",
3097 },
3098 "gerritChanges": [{
3099 "project": "depot_tools",
3100 "host": "chromium-review.googlesource.com",
3101 "patchset": 7,
3102 "change": 123456,
3103 }],
3104 "properties": {
3105 "category": "git_cl_try",
3106 "json": [{"a": 1}, None],
3107 "key": "val",
3108 },
3109 "tags": [
3110 {"value": "win", "key": "builder"},
3111 {"value": "git_cl_try", "key": "user_agent"},
3112 ],
3113 },
3114 }],
3115 }
3116 mockCallBuildbucket.assert_called_with(
3117 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3118
Anthony Polito1a5fe232020-01-24 23:17:52 +00003119 @mock.patch('git_cl._call_buildbucket')
3120 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3121 mockCallBuildbucket.return_value = {}
3122
3123 self.assertEqual(0, git_cl.main([
3124 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3125 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3126 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3127 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003128 'Scheduling jobs on:\n'
3129 ' chromium/try: linux\n'
3130 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003131 git_cl.sys.stdout.getvalue())
3132
3133 expected_request = {
3134 "requests": [{
3135 "scheduleBuild": {
3136 "requestId": "uuid4",
3137 "builder": {
3138 "project": "chromium",
3139 "builder": "linux",
3140 "bucket": "try",
3141 },
3142 "gerritChanges": [{
3143 "project": "depot_tools",
3144 "host": "chromium-review.googlesource.com",
3145 "patchset": 7,
3146 "change": 123456,
3147 }],
3148 "properties": {
3149 "category": "git_cl_try",
3150 "json": [{"a": 1}, None],
3151 "key": "val",
3152 },
3153 "tags": [
3154 {"value": "linux", "key": "builder"},
3155 {"value": "git_cl_try", "key": "user_agent"},
3156 ],
3157 "gitilesCommit": {
3158 "host": "chromium-review.googlesource.com",
3159 "project": "depot_tools",
3160 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3161 }
3162 },
3163 },
3164 {
3165 "scheduleBuild": {
3166 "requestId": "uuid4",
3167 "builder": {
3168 "project": "chromium",
3169 "builder": "win",
3170 "bucket": "try",
3171 },
3172 "gerritChanges": [{
3173 "project": "depot_tools",
3174 "host": "chromium-review.googlesource.com",
3175 "patchset": 7,
3176 "change": 123456,
3177 }],
3178 "properties": {
3179 "category": "git_cl_try",
3180 "json": [{"a": 1}, None],
3181 "key": "val",
3182 },
3183 "tags": [
3184 {"value": "win", "key": "builder"},
3185 {"value": "git_cl_try", "key": "user_agent"},
3186 ],
3187 "gitilesCommit": {
3188 "host": "chromium-review.googlesource.com",
3189 "project": "depot_tools",
3190 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3191 }
3192 },
3193 }],
3194 }
3195 mockCallBuildbucket.assert_called_with(
3196 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3197
Edward Lemur45768512020-03-02 19:03:14 +00003198 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003199 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003200 with self.assertRaises(SystemExit):
3201 git_cl.main([
3202 'try', '-B', 'not-a-bucket', '-b', 'win',
3203 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003204 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003205 'Invalid bucket: not-a-bucket.',
3206 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003207
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003208 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003209 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003210 def testScheduleOnBuildbucketRetryFailed(
3211 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003212 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003213 7: [],
3214 6: [{
3215 'id': 112112,
3216 'builder': {
3217 'project': 'chromium',
3218 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003219 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003220 'createTime': '2019-10-09T08:00:01.854286Z',
3221 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003222 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003223 mockCallBuildbucket.return_value = {}
3224
3225 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3226 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003227 'Scheduling jobs on:\n'
3228 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003229 git_cl.sys.stdout.getvalue())
3230
3231 expected_request = {
3232 "requests": [{
3233 "scheduleBuild": {
3234 "requestId": "uuid4",
3235 "builder": {
3236 "project": "chromium",
3237 "bucket": "try",
3238 "builder": "linux",
3239 },
3240 "gerritChanges": [{
3241 "project": "depot_tools",
3242 "host": "chromium-review.googlesource.com",
3243 "patchset": 7,
3244 "change": 123456,
3245 }],
3246 "properties": {
3247 "category": "git_cl_try",
3248 },
3249 "tags": [
3250 {"value": "linux", "key": "builder"},
3251 {"value": "git_cl_try", "key": "user_agent"},
3252 {"value": "1", "key": "retry_failed"},
3253 ],
3254 },
3255 }],
3256 }
3257 mockCallBuildbucket.assert_called_with(
3258 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3259
Edward Lemur4c707a22019-09-24 21:13:43 +00003260 def test_parse_bucket(self):
3261 test_cases = [
3262 {
3263 'bucket': 'chromium/try',
3264 'result': ('chromium', 'try'),
3265 },
3266 {
3267 'bucket': 'luci.chromium.try',
3268 'result': ('chromium', 'try'),
3269 'has_warning': True,
3270 },
3271 {
3272 'bucket': 'skia.primary',
3273 'result': ('skia', 'skia.primary'),
3274 'has_warning': True,
3275 },
3276 {
3277 'bucket': 'not-a-bucket',
3278 'result': (None, None),
3279 },
3280 ]
3281
3282 for test_case in test_cases:
3283 git_cl.sys.stdout.truncate(0)
3284 self.assertEqual(
3285 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3286 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003287 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3288 test_case['result'])
3289 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003290
3291
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003292class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003293
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003294 def setUp(self):
3295 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003296 mock.patch('git_cl._fetch_tryjobs').start()
3297 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003298 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003299 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3300 mock.patch(
3301 'git_cl.Settings.GetSquashGerritUploads',
3302 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003303 self.addCleanup(mock.patch.stopall)
3304
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003305 def testWarmUpChangeDetailCache(self):
3306 self.assertEqual(0, git_cl.main(['upload']))
3307 gerrit_util.GetChangeDetail.assert_called_once_with(
3308 'chromium-review.googlesource.com', 'depot_tools~123456',
3309 frozenset([
3310 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3311 'CURRENT_COMMIT']))
3312
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003313 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003314 # This test mocks out the actual upload part, and just asserts that after
3315 # upload, if --retry-failed is added, then the tool will fetch try jobs
3316 # from the previous patchset and trigger the right builders on the latest
3317 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003318 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003319 # Latest patchset: No builds.
3320 [],
3321 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003322 [{
3323 'id': str(100 + idx),
3324 'builder': {
3325 'project': 'chromium',
3326 'bucket': 'try',
3327 'builder': 'bot_' + status.lower(),
3328 },
3329 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3330 'tags': [],
3331 'status': status,
3332 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003333 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003334
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003335 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003336 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003337 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3338 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003339 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003340 expected_buckets = [
3341 ('chromium', 'try', 'bot_failure'),
3342 ('chromium', 'try', 'bot_infra_failure'),
3343 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003344 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3345 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003346
Brian Sheedy59b06a82019-10-14 17:03:29 +00003347
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003348class MakeRequestsHelperTestCase(unittest.TestCase):
3349
3350 def exampleGerritChange(self):
3351 return {
3352 'host': 'chromium-review.googlesource.com',
3353 'project': 'depot_tools',
3354 'change': 1,
3355 'patchset': 2,
3356 }
3357
3358 def testMakeRequestsHelperNoOptions(self):
3359 # Basic test for the helper function _make_tryjob_schedule_requests;
3360 # it shouldn't throw AttributeError even when options doesn't have any
3361 # of the expected values; it will use default option values.
3362 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3363 jobs = [('chromium', 'try', 'my-builder')]
3364 options = optparse.Values()
3365 requests = git_cl._make_tryjob_schedule_requests(
3366 changelist, jobs, options, patchset=None)
3367
3368 # requestId is non-deterministic. Just assert that it's there and has
3369 # a particular length.
3370 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3371 self.assertEqual(requests, [{
3372 'scheduleBuild': {
3373 'builder': {
3374 'bucket': 'try',
3375 'builder': 'my-builder',
3376 'project': 'chromium'
3377 },
3378 'gerritChanges': [self.exampleGerritChange()],
3379 'properties': {
3380 'category': 'git_cl_try'
3381 },
3382 'tags': [{
3383 'key': 'builder',
3384 'value': 'my-builder'
3385 }, {
3386 'key': 'user_agent',
3387 'value': 'git_cl_try'
3388 }]
3389 }
3390 }])
3391
3392 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3393 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3394 jobs = [('chromium', 'try', 'presubmit')]
3395 options = optparse.Values()
3396 requests = git_cl._make_tryjob_schedule_requests(
3397 changelist, jobs, options, patchset=None)
3398 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3399 'category': 'git_cl_try',
3400 'dry_run': 'true'
3401 })
3402
3403 def testMakeRequestsHelperRevisionSet(self):
3404 # Gitiles commit is specified when revision is in options.
3405 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3406 jobs = [('chromium', 'try', 'my-builder')]
3407 options = optparse.Values({'revision': 'ba5eba11'})
3408 requests = git_cl._make_tryjob_schedule_requests(
3409 changelist, jobs, options, patchset=None)
3410 self.assertEqual(
3411 requests[0]['scheduleBuild']['gitilesCommit'], {
3412 'host': 'chromium-review.googlesource.com',
3413 'id': 'ba5eba11',
3414 'project': 'depot_tools'
3415 })
3416
3417 def testMakeRequestsHelperRetryFailedSet(self):
3418 # An extra tag is added when retry_failed is in options.
3419 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3420 jobs = [('chromium', 'try', 'my-builder')]
3421 options = optparse.Values({'retry_failed': 'true'})
3422 requests = git_cl._make_tryjob_schedule_requests(
3423 changelist, jobs, options, patchset=None)
3424 self.assertEqual(
3425 requests[0]['scheduleBuild']['tags'], [
3426 {
3427 'key': 'builder',
3428 'value': 'my-builder'
3429 },
3430 {
3431 'key': 'user_agent',
3432 'value': 'git_cl_try'
3433 },
3434 {
3435 'key': 'retry_failed',
3436 'value': '1'
3437 }
3438 ])
3439
3440 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00003441 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003442 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3443 jobs = [('chromium', 'try', 'my-builder')]
3444 options = optparse.Values({'category': 'my-special-category'})
3445 requests = git_cl._make_tryjob_schedule_requests(
3446 changelist, jobs, options, patchset=None)
3447 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3448 {'category': 'my-special-category'})
3449
3450
Edward Lemurda4b6c62020-02-13 00:28:40 +00003451class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003452
3453 def setUp(self):
3454 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003455 mock.patch('git_cl.RunCommand').start()
3456 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3457 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3458 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003459 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003460 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003461
3462 def tearDown(self):
3463 shutil.rmtree(self._top_dir)
3464 super(CMDFormatTestCase, self).tearDown()
3465
Jamie Madill5e96ad12020-01-13 16:08:35 +00003466 def _make_temp_file(self, fname, contents):
3467 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3468 tf.write('\n'.join(contents))
3469
Brian Sheedy59b06a82019-10-14 17:03:29 +00003470 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003471 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003472
Brian Sheedyb4307d52019-12-02 19:18:17 +00003473 def _check_yapf_filtering(self, files, expected):
3474 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3475 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003476
Edward Lemur1a83da12020-03-04 21:18:36 +00003477 def _run_command_mock(self, return_value):
3478 def f(*args, **kwargs):
3479 if 'stdin' in kwargs:
3480 self.assertIsInstance(kwargs['stdin'], bytes)
3481 return return_value
3482 return f
3483
Jamie Madill5e96ad12020-01-13 16:08:35 +00003484 def testClangFormatDiffFull(self):
3485 self._make_temp_file('test.cc', ['// test'])
3486 git_cl.settings.GetFormatFullByDefault.return_value = False
3487 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3488 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3489
3490 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003491 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003492 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3493 self._top_dir, 'HEAD')
3494 self.assertEqual(2, return_value)
3495
3496 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003497 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003498 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3499 self._top_dir, 'HEAD')
3500 self.assertEqual(0, return_value)
3501
3502 def testClangFormatDiff(self):
3503 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00003504 # A valid file is required, so use this test.
3505 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00003506 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3507
3508 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003509 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3510 return_value = git_cl._RunClangFormatDiff(
3511 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003512 self.assertEqual(2, return_value)
3513
3514 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003515 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003516 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3517 'HEAD')
3518 self.assertEqual(0, return_value)
3519
Brian Sheedyb4307d52019-12-02 19:18:17 +00003520 def testYapfignoreExplicit(self):
3521 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3522 files = [
3523 'bar.py',
3524 'foo/bar.py',
3525 'foo/baz.py',
3526 'foo/bar/baz.py',
3527 'foo/bar/foobar.py',
3528 ]
3529 expected = [
3530 'bar.py',
3531 'foo/baz.py',
3532 'foo/bar/foobar.py',
3533 ]
3534 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003535
Brian Sheedyb4307d52019-12-02 19:18:17 +00003536 def testYapfignoreSingleWildcards(self):
3537 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3538 files = [
3539 'bar.py', # Matched by *bar.py.
3540 'bar.txt',
3541 'foobar.py', # Matched by *bar.py, foo*.
3542 'foobar.txt', # Matched by foo*.
3543 'bazbar.py', # Matched by *bar.py, baz*.py.
3544 'bazbar.txt',
3545 'foo/baz.txt', # Matched by foo*.
3546 'bar/bar.py', # Matched by *bar.py.
3547 'baz/foo.py', # Matched by baz*.py, foo*.
3548 'baz/foo.txt',
3549 ]
3550 expected = [
3551 'bar.txt',
3552 'bazbar.txt',
3553 'baz/foo.txt',
3554 ]
3555 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003556
Brian Sheedyb4307d52019-12-02 19:18:17 +00003557 def testYapfignoreMultiplewildcards(self):
3558 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3559 files = [
3560 'bar.py', # Matched by *bar*.
3561 'bar.txt', # Matched by *bar*.
3562 'abar.py', # Matched by *bar*.
3563 'foobaz.txt', # Matched by *foo*baz.txt.
3564 'foobaz.py',
3565 'afoobaz.txt', # Matched by *foo*baz.txt.
3566 ]
3567 expected = [
3568 'foobaz.py',
3569 ]
3570 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003571
3572 def testYapfignoreComments(self):
3573 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003574 files = [
3575 'test.py',
3576 'test2.py',
3577 ]
3578 expected = [
3579 'test2.py',
3580 ]
3581 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003582
3583 def testYapfignoreBlankLines(self):
3584 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003585 files = [
3586 'test.py',
3587 'test2.py',
3588 'test3.py',
3589 ]
3590 expected = [
3591 'test3.py',
3592 ]
3593 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003594
3595 def testYapfignoreWhitespace(self):
3596 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003597 files = [
3598 'test.py',
3599 'test2.py',
3600 ]
3601 expected = [
3602 'test2.py',
3603 ]
3604 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003605
Brian Sheedyb4307d52019-12-02 19:18:17 +00003606 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003607 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003608 self._check_yapf_filtering([], [])
3609
3610 def testYapfignoreMissingYapfignore(self):
3611 files = [
3612 'test.py',
3613 ]
3614 expected = [
3615 'test.py',
3616 ]
3617 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003618
3619
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003620if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003621 logging.basicConfig(
3622 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003623 unittest.main()