blob: 3c582842d83b5f5d922dc1506e48e57953e06768 [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
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000697 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000698 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200699 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200700 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000701 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000702 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000703 calls += [
704 ((['RunEditor'],), description),
705 ]
Josipe827b0f2020-01-30 00:07:20 +0000706 # user wants to edit description
707 if edit_description:
708 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000709 ((['RunEditor'],), edit_description),
710 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000711 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200712
713 if custom_cl_base is None:
714 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000715 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000716 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200717 ]
718 parent = 'origin/master'
719 else:
720 calls += [
721 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
722 'refs/remotes/origin/master'],),
723 callError(1)), # Means not ancenstor.
724 (('ask_for_data',
725 'Do you take responsibility for cleaning up potential mess '
726 'resulting from proceeding with upload? Press Enter to upload, '
727 'or Ctrl+C to abort'), ''),
728 ]
729 parent = custom_cl_base
730
731 calls += [
732 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
733 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000734 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200735 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000736 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200737 ref_to_push),
738 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000739 else:
740 ref_to_push = 'HEAD'
Edward Lemur5a644f82020-03-18 16:44:57 +0000741 parent = 'origin/refs/heads/master'
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000742
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000743 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000744 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000745 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200746 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000747
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000748 metrics_arguments = []
749
Aaron Gableafd52772017-06-27 16:40:10 -0700750 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700751 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000752 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700753 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400754 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700755 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000756 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700757 else:
758 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000759 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800760
Edward Lemur5a644f82020-03-18 16:44:57 +0000761 # If issue is given, then description is fetched from Gerrit instead.
762 if issue is None:
763 if squash:
764 title = 'Initial upload'
765 else:
766 if not title:
767 calls += [
768 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
769 (('ask_for_data', 'Title for patchset []: '), 'User input'),
770 ]
771 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700772 if title:
Edward Lemur5a644f82020-03-18 16:44:57 +0000773 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000774 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000775
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000776 if short_hostname == 'chromium':
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000777 # All reviewers and ccs get into ref_suffix.
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000778 for r in sorted(reviewers):
779 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000780 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000781 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000782 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000783 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000784 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000785 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000786 reviewers, cc = [], []
787 else:
788 # TODO(crbug/877717): remove this case.
789 calls += [
790 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
791 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000792 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000793 {
794 e: {'email': e}
795 for e in (reviewers + ['joe@example.com'] + cc)
796 })
797 ]
798 for r in sorted(reviewers):
799 if r != 'bad-account-or-email':
800 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000801 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000802 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000803 if issue is None:
804 cc += ['joe@example.com']
805 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000806 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000807 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000808 if c in cc:
809 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000810
Edward Lemur687ca902018-12-05 02:30:30 +0000811 for k, v in sorted((labels or {}).items()):
812 ref_suffix += ',l=%s+%d' % (k, v)
813 metrics_arguments.append('l=%s+%d' % (k, v))
814
815 if tbr:
816 calls += [
817 (('GetCodeReviewTbrScore',
818 '%s-review.googlesource.com' % short_hostname,
819 'my/repo'),
820 2,),
821 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000822
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000823 calls += [
824 (('time.time',), 1000,),
825 ((['git', 'push',
826 'https://%s.googlesource.com/my/repo' % short_hostname,
827 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
828 (('remote:\n'
829 'remote: Processing changes: (\)\n'
830 'remote: Processing changes: (|)\n'
831 'remote: Processing changes: (/)\n'
832 'remote: Processing changes: (-)\n'
833 'remote: Processing changes: new: 1 (/)\n'
834 'remote: Processing changes: new: 1, done\n'
835 'remote:\n'
836 'remote: New Changes:\n'
837 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
838 ' XXX\n'
839 'remote:\n'
840 'To https://%s.googlesource.com/my/repo\n'
841 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
842 ) % (short_hostname, short_hostname)),),
843 (('time.time',), 2000,),
844 (('add_repeated',
845 'sub_commands',
846 {
847 'execution_time': 1000,
848 'command': 'git push',
849 'exit_code': 0,
850 'arguments': sorted(metrics_arguments),
851 }),
852 None,),
853 ]
854
Edward Lemur1b52d872019-05-09 21:12:12 +0000855 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000856
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000857 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
858
Edward Lemur1b52d872019-05-09 21:12:12 +0000859 # Trace-related calls
860 calls += [
861 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000862 (
863 ([
864 'FileWrite', trace_name + '-README',
865 '%(date)s\n'
866 '%(short_hostname)s-review.googlesource.com\n'
867 '%(change_id)s\n'
868 '%(title)s\n'
869 '%(description)s\n'
870 '1000\n'
871 '0\n'
872 '%(trace_name)s' % {
Josip Sokcevic5e18b602020-04-23 21:47:00 +0000873 'date': '2017-03-16T20:00:41.000000',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000874 'short_hostname': short_hostname,
875 'change_id': change_id,
876 'description': final_description,
877 'title': title or '<untitled>',
878 'trace_name': trace_name,
879 }
880 ], ),
881 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000882 ),
883 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000884 (
885 (['os.path.isfile',
886 os.path.join('TEMP_DIR', 'trace-packet')], ),
887 True,
Edward Lemur1b52d872019-05-09 21:12:12 +0000888 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000889 (
890 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
891 ('git-hash: 0123456789012345678901234567890123456789\n'
892 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +0000893 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000894 (
895 ([
896 'FileWrite',
897 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
898 'git-hash: abcdea\n'
899 ], ),
900 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000901 ),
902 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000903 (
904 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
905 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000906 ),
907 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000908 (
909 (['git', 'config', '-l'], ),
910 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +0000911 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000912 (
913 ([
914 'FileWrite',
915 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
916 ], ),
917 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000918 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000919 (
920 (['os.path.isfile',
921 os.path.join('~', '.gitcookies')], ),
922 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +0000923 ),
924 ]
925 if gitcookies_exists:
926 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000927 (
928 (['FileRead', os.path.join('~', '.gitcookies')], ),
929 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +0000930 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000931 (
932 ([
933 'FileWrite',
934 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
935 ], ),
936 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000937 ),
938 ]
939 calls += [
940 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000941 (
942 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
943 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000944 ),
945 ]
946
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000947 # TODO(crbug/877717): this should never be used.
948 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000949 calls += [
950 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +0000951 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000952 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +0000953 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +0000954 notify),
955 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000956 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000957 return calls
958
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000959 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000960 self,
961 upload_args,
962 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000963 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700964 squash=True,
965 squash_mode=None,
Aaron Gable9b713dd2016-12-14 16:04:21 -0800966 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000967 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000968 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -0700969 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100970 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100971 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200972 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -0700973 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000974 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000975 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000976 labels=None,
977 change_id=None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000978 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000979 gitcookies_exists=True,
980 force=False,
Edward Lesmes0dd54822020-03-26 18:24:25 +0000981 log_description=None,
Josipe827b0f2020-01-30 00:07:20 +0000982 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000983 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000984 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700985 if squash_mode is None:
986 if '--no-squash' in upload_args:
987 squash_mode = 'nosquash'
988 elif '--squash' in upload_args:
989 squash_mode = 'squash'
990 else:
991 squash_mode = 'default'
992
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000993 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -0700994 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000995 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100996 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000997 same_auth=('git-owner.example.com', '', 'pass'))).start()
998 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
999 lambda _, offer_removal: None).start()
1000 mock.patch('git_cl.gclient_utils.RunEditor',
1001 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1002 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1003 'DownloadGerritHook', force)).start()
1004 mock.patch('git_cl.gclient_utils.FileRead',
1005 lambda path: self._mocked_call(['FileRead', path])).start()
1006 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001007 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001008 ['FileWrite', path, contents])).start()
1009 mock.patch('git_cl.datetime_now',
1010 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1011 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1012 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1013 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001014 '%(now)s\n'
1015 '%(gerrit_host)s\n'
1016 '%(change_id)s\n'
1017 '%(title)s\n'
1018 '%(description)s\n'
1019 '%(execution_time)s\n'
1020 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001021 '%(trace_name)s').start()
1022 mock.patch('git_cl.shutil.make_archive',
1023 lambda *args: self._mocked_call(['make_archive'] +
1024 list(args))).start()
1025 mock.patch('os.path.isfile',
1026 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001027 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001028 'git_cl._create_description_from_log',
1029 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001030 mock.patch(
1031 'git_cl.Changelist._AddChangeIdToCommitMessage',
1032 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001033 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001034 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1035 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001036 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001037 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001038
Edward Lemur26964072020-02-19 19:18:51 +00001039 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001040 self.mockGit.config['branch.master.gerritissue'] = (
1041 str(issue) if issue else None)
1042 self.mockGit.config['remote.origin.url'] = (
1043 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001044 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001045
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001046 self.calls = self._gerrit_base_calls(
1047 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001048 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001049 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001050 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001051 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001052 short_hostname=short_hostname,
1053 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001054 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001055 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001056 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001057 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001058 self.calls += self._gerrit_upload_calls(
1059 description, reviewers, squash,
1060 squash_mode=squash_mode,
Aaron Gablefd238082017-06-07 13:42:34 -07001061 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001062 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001063 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001064 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001065 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001066 labels=labels,
1067 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001068 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001069 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001070 force=force,
1071 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001072 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001073 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001074 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001075 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001076 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001077 self.assertEqual(
1078 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001079 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001080
Edward Lemur1b52d872019-05-09 21:12:12 +00001081 def test_gerrit_upload_traces_no_gitcookies(self):
1082 self._run_gerrit_upload_test(
1083 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001084 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001085 [],
1086 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001087 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001088 change_id='Ixxx',
1089 gitcookies_exists=False)
1090
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001091 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001092 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001093 [],
1094 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1095 [],
1096 change_id='Ixxx')
1097
1098 def test_gerrit_upload_without_change_id_nosquash(self):
1099 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001100 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001101 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001102 [],
1103 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001104 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001105 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001106
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001107 def test_gerrit_no_reviewer(self):
1108 self._run_gerrit_upload_test(
Mike Frysinger31a538a2020-05-05 18:38:51 +00001109 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001110 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001111 [],
1112 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001113 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001114
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001115 def test_gerrit_no_reviewer_non_chromium_host(self):
1116 # TODO(crbug/877717): remove this test case.
1117 self._run_gerrit_upload_test(
Mike Frysinger31a538a2020-05-05 18:38:51 +00001118 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001119 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001120 [],
1121 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001122 short_hostname='other',
1123 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001124
Edward Lesmes0dd54822020-03-26 18:24:25 +00001125 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001126 self._run_gerrit_upload_test(
Mike Frysinger31a538a2020-05-05 18:38:51 +00001127 ['--no-squash', '-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001128 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001129 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001130 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001131 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001132
ukai@chromium.orge8077812012-02-03 03:41:46 +00001133 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001134 self._run_gerrit_upload_test(
Mike Frysinger31a538a2020-05-05 18:38:51 +00001135 ['--no-squash', '-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001136 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001137 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001138 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001139 notify=True,
1140 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001141 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001142 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001143
Anthony Polito8b955342019-09-24 19:01:36 +00001144 def test_gerrit_upload_force_sets_bug(self):
1145 self._run_gerrit_upload_test(
1146 ['-b', '10000', '-f'],
1147 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1148 [],
1149 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001150 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001151 change_id='Ixxx')
1152
Edward Lemur5fb22242020-03-12 22:05:13 +00001153 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001154 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001155 ['-b', '10000', '-m', 'Title', '--edit-description'],
1156 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001157 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001158 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001159 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001160 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001161 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001162 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001163
Dan Beamd8b04ca2019-10-10 21:23:26 +00001164 def test_gerrit_upload_force_sets_fixed(self):
1165 self._run_gerrit_upload_test(
1166 ['-x', '10000', '-f'],
1167 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1168 [],
1169 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001170 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001171 change_id='Ixxx')
1172
ukai@chromium.orge8077812012-02-03 03:41:46 +00001173 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001174 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1175 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001176 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001177 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001178 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001179 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001180 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001181 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001182 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001183 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001184 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001185 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001186
1187 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001188 self._run_gerrit_upload_test(
1189 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001190 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001191 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001192 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001193
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001194 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001195 self._run_gerrit_upload_test(
1196 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001197 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001198 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001199 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001200 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001201
Edward Lesmes0dd54822020-03-26 18:24:25 +00001202 def test_gerrit_upload_squash_first_title(self):
1203 self._run_gerrit_upload_test(
1204 ['-f', '-t', 'title'],
1205 'title\n\ndesc\n\nChange-Id: 123456789',
1206 [],
1207 force=True,
1208 squash=True,
1209 log_description='desc',
1210 change_id='123456789')
1211
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001212 def test_gerrit_upload_squash_first_with_labels(self):
1213 self._run_gerrit_upload_test(
1214 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001215 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001216 [],
1217 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001218 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001219 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001220
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001221 def test_gerrit_upload_squash_first_against_rev(self):
1222 custom_cl_base = 'custom_cl_base_rev_or_branch'
1223 self._run_gerrit_upload_test(
1224 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001225 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001226 [],
1227 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001228 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001229 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001230 self.assertIn(
1231 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1232 sys.stdout.getvalue())
1233
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001234 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001235 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001236 self._run_gerrit_upload_test(
1237 ['--squash'],
1238 description,
1239 [],
1240 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001241 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001242 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001243
Edward Lemurd55c5072020-02-20 01:09:07 +00001244 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001245 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001246 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001247 with self.assertRaises(SystemExitMock):
1248 self._run_gerrit_upload_test(
1249 ['--squash'],
1250 description,
1251 [],
1252 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001253 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001254 fetched_status='ABANDONED',
1255 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001256 self.assertEqual(
1257 'Change https://chromium-review.googlesource.com/123456 has been '
1258 'abandoned, new uploads are not allowed\n',
1259 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001260
Edward Lemurda4b6c62020-02-13 00:28:40 +00001261 @mock.patch(
1262 'gerrit_util.GetAccountDetails',
1263 return_value={'email': 'yet-another@example.com'})
1264 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001265 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001266 self._run_gerrit_upload_test(
1267 ['--squash'],
1268 description,
1269 [],
1270 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001271 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001272 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001273 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001274 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001275 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001276 'authenticate to Gerrit as yet-another@example.com.\n'
1277 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001278 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001279
Josipe827b0f2020-01-30 00:07:20 +00001280 def test_upload_change_description_editor(self):
1281 fetched_description = 'foo\n\nChange-Id: 123456789'
1282 description = 'bar\n\nChange-Id: 123456789'
1283 self._run_gerrit_upload_test(
1284 ['--squash', '--edit-description'],
1285 description,
1286 [],
1287 fetched_description=fetched_description,
1288 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001289 issue=123456,
1290 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001291 edit_description=description)
1292
Edward Lemurda4b6c62020-02-13 00:28:40 +00001293 @mock.patch('git_cl.RunGit')
1294 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001295 @mock.patch('sys.stdin', StringIO('\n'))
1296 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001297 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001298 def mock_run_git(*args, **_kwargs):
1299 if args[0] == ['for-each-ref',
1300 '--format=%(refname:short) %(upstream:short)',
1301 'refs/heads']:
1302 # Create a local branch dependency tree that looks like this:
1303 # test1 -> test2 -> test3 -> test4 -> test5
1304 # -> test3.1
1305 # test6 -> test0
1306 branch_deps = [
1307 'test2 test1', # test1 -> test2
1308 'test3 test2', # test2 -> test3
1309 'test3.1 test2', # test2 -> test3.1
1310 'test4 test3', # test3 -> test4
1311 'test5 test4', # test4 -> test5
1312 'test6 test0', # test0 -> test6
1313 'test7', # test7
1314 ]
1315 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001316 git_cl.RunGit.side_effect = mock_run_git
1317 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001318
1319 class MockChangelist():
1320 def __init__(self):
1321 pass
1322 def GetBranch(self):
1323 return 'test1'
1324 def GetIssue(self):
1325 return '123'
1326 def GetPatchset(self):
1327 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001328 def IsGerrit(self):
1329 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001330
1331 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1332 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001333 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001334 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001335 'This command will checkout all dependent branches '
1336 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001337 'or Ctrl+C to abort',
1338 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001339 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001340
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001341 def test_gerrit_change_id(self):
1342 self.calls = [
1343 ((['git', 'write-tree'], ),
1344 'hashtree'),
1345 ((['git', 'rev-parse', 'HEAD~0'], ),
1346 'branch-parent'),
1347 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1348 'A B <a@b.org> 1456848326 +0100'),
1349 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1350 'C D <c@d.org> 1456858326 +0100'),
1351 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1352 'hashchange'),
1353 ]
1354 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1355 self.assertEqual(change_id, 'Ihashchange')
1356
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001357 def test_desecription_append_footer(self):
1358 for init_desc, footer_line, expected_desc in [
1359 # Use unique desc first lines for easy test failure identification.
1360 ('foo', 'R=one', 'foo\n\nR=one'),
1361 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1362 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1363 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1364 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1365 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1366 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1367 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1368 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1369 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1370 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1371 ]:
1372 desc = git_cl.ChangeDescription(init_desc)
1373 desc.append_footer(footer_line)
1374 self.assertEqual(desc.description, expected_desc)
1375
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001376 def test_update_reviewers(self):
1377 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001378 ('foo', [], [],
1379 'foo'),
1380 ('foo\nR=xx', [], [],
1381 'foo\nR=xx'),
1382 ('foo\nTBR=xx', [], [],
1383 'foo\nTBR=xx'),
1384 ('foo', ['a@c'], [],
1385 'foo\n\nR=a@c'),
1386 ('foo\nR=xx', ['a@c'], [],
1387 'foo\n\nR=a@c, xx'),
1388 ('foo\nTBR=xx', ['a@c'], [],
1389 'foo\n\nR=a@c\nTBR=xx'),
1390 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1391 'foo\n\nR=a@c, yy\nTBR=xx'),
1392 ('foo\nBUG=', ['a@c'], [],
1393 'foo\nBUG=\nR=a@c'),
1394 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1395 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1396 ('foo', ['a@c', 'b@c'], [],
1397 'foo\n\nR=a@c, b@c'),
1398 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1399 'foo\nBar\n\nR=c@c\nBUG='),
1400 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1401 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001402 # Same as the line before, but full of whitespaces.
1403 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001404 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001405 'foo\nBar\n\nR=c@c\n BUG =',
1406 ),
1407 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001408 ('foo BUG=allo R=joe ', ['c@c'], [],
1409 'foo BUG=allo R=joe\n\nR=c@c'),
1410 # Redundant TBRs get promoted to Rs
1411 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1412 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001413 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001414 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001415 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001416 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001417 obj = git_cl.ChangeDescription(orig)
Edward Lemur2c62b332020-03-12 22:12:33 +00001418 obj.update_reviewers(reviewers, tbrs, None, None, None)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001419 actual.append(obj.description)
1420 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001421
Nodir Turakulov23b82142017-11-16 11:04:25 -08001422 def test_get_hash_tags(self):
1423 cases = [
1424 ('', []),
1425 ('a', []),
1426 ('[a]', ['a']),
1427 ('[aa]', ['aa']),
1428 ('[a ]', ['a']),
1429 ('[a- ]', ['a']),
1430 ('[a- b]', ['a-b']),
1431 ('[a--b]', ['a-b']),
1432 ('[a', []),
1433 ('[a]x', ['a']),
1434 ('[aa]x', ['aa']),
1435 ('[a b]', ['a-b']),
1436 ('[a b]', ['a-b']),
1437 ('[a__b]', ['a-b']),
1438 ('[a] x', ['a']),
1439 ('[a][b]', ['a', 'b']),
1440 ('[a] [b]', ['a', 'b']),
1441 ('[a][b]x', ['a', 'b']),
1442 ('[a][b] x', ['a', 'b']),
1443 ('[a]\n[b]', ['a']),
1444 ('[a\nb]', []),
1445 ('[a][', ['a']),
1446 ('Revert "[a] feature"', ['a']),
1447 ('Reland "[a] feature"', ['a']),
1448 ('Revert: [a] feature', ['a']),
1449 ('Reland: [a] feature', ['a']),
1450 ('Revert "Reland: [a] feature"', ['a']),
1451 ('Foo: feature', ['foo']),
1452 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001453 ('Change Foo::Bar', []),
1454 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001455 ('Revert "Foo bar: feature"', ['foo-bar']),
1456 ('Reland "Foo bar: feature"', ['foo-bar']),
1457 ]
1458 for desc, expected in cases:
1459 change_desc = git_cl.ChangeDescription(desc)
1460 actual = change_desc.get_hash_tags()
1461 self.assertEqual(
1462 actual,
1463 expected,
1464 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1465
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001466 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001467 self.assertEqual(None, git_cl.GetTargetRef(None,
1468 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001469 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001470
wittman@chromium.org455dc922015-01-26 20:15:50 +00001471 # Check default target refs for branches.
1472 self.assertEqual('refs/heads/master',
1473 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001474 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001475 self.assertEqual('refs/heads/master',
1476 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001477 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001478 self.assertEqual('refs/heads/master',
1479 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001480 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001481 self.assertEqual('refs/branch-heads/123',
1482 git_cl.GetTargetRef('origin',
1483 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001484 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001485 self.assertEqual('refs/diff/test',
1486 git_cl.GetTargetRef('origin',
1487 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001488 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001489 self.assertEqual('refs/heads/chrome/m42',
1490 git_cl.GetTargetRef('origin',
1491 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001492 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001493
1494 # Check target refs for user-specified target branch.
1495 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1496 'refs/remotes/branch-heads/123'):
1497 self.assertEqual('refs/branch-heads/123',
1498 git_cl.GetTargetRef('origin',
1499 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001500 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001501 for branch in ('origin/master', 'remotes/origin/master',
1502 'refs/remotes/origin/master'):
1503 self.assertEqual('refs/heads/master',
1504 git_cl.GetTargetRef('origin',
1505 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001506 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001507 for branch in ('master', 'heads/master', 'refs/heads/master'):
1508 self.assertEqual('refs/heads/master',
1509 git_cl.GetTargetRef('origin',
1510 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001511 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001512
Edward Lemurda4b6c62020-02-13 00:28:40 +00001513 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1514 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001515 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001516 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1517
Edward Lemur85153282020-02-14 22:06:29 +00001518 def assertIssueAndPatchset(
1519 self, branch='master', issue='123456', patchset='7',
1520 git_short_host='chromium'):
1521 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001522 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001523 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001524 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001525 self.assertEqual(
1526 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001527 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001528
Edward Lemur85153282020-02-14 22:06:29 +00001529 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001530 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001531 self.mockGit.config['remote.origin.url'] = (
1532 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001533 gerrit_util.GetChangeDetail.return_value = {
1534 'current_revision': '7777777777',
1535 'revisions': {
1536 '1111111111': {
1537 '_number': 1,
1538 'fetch': {'http': {
1539 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1540 'ref': 'refs/changes/56/123456/1',
1541 }},
1542 },
1543 '7777777777': {
1544 '_number': 7,
1545 'fetch': {'http': {
1546 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1547 'ref': 'refs/changes/56/123456/7',
1548 }},
1549 },
1550 },
1551 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001552
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001553 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001554 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001555 self.calls += [
1556 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1557 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001558 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001559 ]
1560 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001561 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001562
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001563 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001564 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001565 self.calls += [
1566 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1567 'refs/changes/56/123456/7'],), ''),
1568 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001569 ]
Edward Lemur85153282020-02-14 22:06:29 +00001570 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1571 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001572
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001573 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001574 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001575 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001576 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001577 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001578 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001579 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001580 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001581 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001582
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001583 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001584 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001585 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001586 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001587 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001588 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001589 ]
1590 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001591 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001592 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001593
Aaron Gable697a91b2018-01-19 15:20:15 -08001594 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001595 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001596 self.calls += [
1597 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1598 'refs/changes/56/123456/1'],), ''),
1599 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001600 ]
1601 self.assertEqual(git_cl.main(
1602 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1603 0)
Edward Lemur85153282020-02-14 22:06:29 +00001604 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001605
Edward Lemurd55c5072020-02-20 01:09:07 +00001606 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001607 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001608 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001609 self.calls += [
1610 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001611 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001612 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001613 ]
1614 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001615 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001616 self.assertEqual(
1617 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1618 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001619
Edward Lemurda4b6c62020-02-13 00:28:40 +00001620 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001621 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001622 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001623 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001624 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001625 self.mockGit.config['remote.origin.url'] = (
1626 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001627 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001628 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001629 self.assertEqual(
1630 'change 123456 at https://chromium-review.googlesource.com does not '
1631 'exist or you have no access to it\n',
1632 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001633
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001634 def _checkout_calls(self):
1635 return [
1636 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001637 'branch\\..*\\.gerritissue'], ),
1638 ('branch.ger-branch.gerritissue 123456\n'
1639 'branch.gbranch654.gerritissue 654321\n')),
1640 ]
1641
1642 def test_checkout_gerrit(self):
1643 """Tests git cl checkout <issue>."""
1644 self.calls = self._checkout_calls()
1645 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1646 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1647
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001648 def test_checkout_not_found(self):
1649 """Tests git cl checkout <issue>."""
1650 self.calls = self._checkout_calls()
1651 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1652
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001653 def test_checkout_no_branch_issues(self):
1654 """Tests git cl checkout <issue>."""
1655 self.calls = [
1656 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001657 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001658 ]
1659 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1660
Edward Lemur26964072020-02-19 19:18:51 +00001661 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001662 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001663 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001664 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001665 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1666 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001667 self.mockGit.config['remote.origin.url'] = (
1668 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001669 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001670 cl.branch = 'master'
1671 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001672 return cl
1673
Edward Lemurd55c5072020-02-20 01:09:07 +00001674 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001675 def test_gerrit_ensure_authenticated_missing(self):
1676 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001677 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001678 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001679 with self.assertRaises(SystemExitMock):
1680 cl.EnsureAuthenticated(force=False)
1681 self.assertEqual(
1682 'Credentials for the following hosts are required:\n'
1683 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001684 'These are read from ~%(sep)s.gitcookies '
1685 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001686 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001687 'https://chromium-review.googlesource.com/new-password\n' % {
1688 'sep': os.sep,
1689 'netrc': NETRC_FILENAME,
1690 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001691
1692 def test_gerrit_ensure_authenticated_conflict(self):
1693 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001694 'chromium.googlesource.com':
1695 ('git-one.example.com', None, 'secret1'),
1696 'chromium-review.googlesource.com':
1697 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001698 })
1699 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001700 (('ask_for_data', 'If you know what you are doing '
1701 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001702 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1703
1704 def test_gerrit_ensure_authenticated_ok(self):
1705 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001706 'chromium.googlesource.com':
1707 ('git-same.example.com', None, 'secret'),
1708 'chromium-review.googlesource.com':
1709 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001710 })
1711 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1712
tandrii@chromium.org28253532016-04-14 13:46:56 +00001713 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001714 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1715 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001716 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1717
Eric Boren2fb63102018-10-05 13:05:03 +00001718 def test_gerrit_ensure_authenticated_bearer_token(self):
1719 cl = self._test_gerrit_ensure_authenticated_common(auth={
1720 'chromium.googlesource.com':
1721 ('', None, 'secret'),
1722 'chromium-review.googlesource.com':
1723 ('', None, 'secret'),
1724 })
1725 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1726 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1727 'chromium.googlesource.com')
1728 self.assertTrue('Bearer' in header)
1729
Daniel Chengcf6269b2019-05-18 01:02:12 +00001730 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001731 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001732 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001733 (('logging.warning',
1734 'Ignoring branch %(branch)s with non-https remote '
1735 '%(remote)s', {
1736 'branch': 'master',
1737 'remote': 'custom-scheme://repo'}
1738 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001739 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001740 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1741 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1742 mock.patch('logging.warning',
1743 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001744 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001745 cl.branch = 'master'
1746 cl.branchref = 'refs/heads/master'
1747 cl.lookedup_issue = True
1748 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1749
Florian Mayerae510e82020-01-30 21:04:48 +00001750 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001751 self.mockGit.config['remote.origin.url'] = (
1752 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001753 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001754 (('logging.error',
1755 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1756 'but it doesn\'t exist.', {
1757 'remote': 'origin',
1758 'branch': 'master',
1759 'url': 'git@somehost.example:foo/bar.git'}
1760 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001761 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001762 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1763 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1764 mock.patch('logging.error',
1765 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001766 cl = git_cl.Changelist()
1767 cl.branch = 'master'
1768 cl.branchref = 'refs/heads/master'
1769 cl.lookedup_issue = True
1770 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1771
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001772 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001773 self.mockGit.config['branch.master.gerritissue'] = '123'
1774 self.mockGit.config['branch.master.gerritserver'] = (
1775 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001776 self.mockGit.config['remote.origin.url'] = (
1777 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001778 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001779 (('SetReview', 'chromium-review.googlesource.com',
1780 'infra%2Finfra~123', None,
1781 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001782 ]
tandriid9e5ce52016-07-13 02:32:59 -07001783
1784 def test_cmd_set_commit_gerrit_clear(self):
1785 self._cmd_set_commit_gerrit_common(0)
1786 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1787
1788 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001789 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001790 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1791
tandriid9e5ce52016-07-13 02:32:59 -07001792 def test_cmd_set_commit_gerrit(self):
1793 self._cmd_set_commit_gerrit_common(2)
1794 self.assertEqual(0, git_cl.main(['set-commit']))
1795
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001796 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001797 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001798 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001799
1800 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001801 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001802
Edward Lemurda4b6c62020-02-13 00:28:40 +00001803 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001804 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001805 try:
1806 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001807 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001808 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001809 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001810
1811 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001812 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001813 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001814 return 'foobar'
1815
Edward Lemurda4b6c62020-02-13 00:28:40 +00001816 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001817 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001818 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001819 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001820 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001821
iannuccie53c9352016-08-17 14:40:40 -07001822 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001823
iannuccie53c9352016-08-17 14:40:40 -07001824 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001825 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001826 return 'foobar'
1827
Edward Lemurda4b6c62020-02-13 00:28:40 +00001828 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
1829 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07001830 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001831 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07001832
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001833 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00001834 self.mockGit.config['remote.origin.url'] = (
1835 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001836 gerrit_util.GetChangeDetail.return_value = {
1837 'current_revision': 'sha1',
1838 'revisions': {'sha1': {
1839 'commit': {'message': 'foobar'},
1840 }},
1841 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001842 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001843 'description',
1844 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
1845 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001846 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001847
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001848 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001849 mock.patch('git_cl.Changelist', ChangelistMock).start()
1850 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001851
1852 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1853 self.assertEqual('hihi', ChangelistMock.desc)
1854
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001855 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001856 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001857
1858 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001859 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001860 '# Enter a description of the change.\n'
1861 '# This will be displayed on the codereview site.\n'
1862 '# The first line will also be used as the subject of the review.\n'
1863 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001864 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07001865 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001866 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001867 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07001868 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001869
Edward Lemur6c6827c2020-02-06 21:15:18 +00001870 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001871 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001872
Edward Lemurda4b6c62020-02-13 00:28:40 +00001873 mock.patch('git_cl.Changelist.FetchDescription',
1874 lambda *args: current_desc).start()
1875 mock.patch('git_cl.Changelist.UpdateDescription',
1876 UpdateDescription).start()
1877 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001878
Edward Lemur85153282020-02-14 22:06:29 +00001879 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001880 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001881
Dan Beamd8b04ca2019-10-10 21:23:26 +00001882 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
1883 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
1884
1885 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001886 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00001887 '# Enter a description of the change.\n'
1888 '# This will be displayed on the codereview site.\n'
1889 '# The first line will also be used as the subject of the review.\n'
1890 '#--------------------This line is 72 characters long'
1891 '--------------------\n'
1892 'Some.\n\nFixed: 123\nChange-Id: xxx',
1893 desc)
1894 return desc
1895
Edward Lemurda4b6c62020-02-13 00:28:40 +00001896 mock.patch('git_cl.Changelist.FetchDescription',
1897 lambda *args: current_desc).start()
1898 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +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']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00001902
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001903 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001904 mock.patch('git_cl.Changelist', ChangelistMock).start()
1905 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001906
1907 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1908 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1909
kmarshall3bff56b2016-06-06 18:31:47 -07001910 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001911 self.calls = [
1912 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00001913 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001914 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001915 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00001916 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001917 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001918
Edward Lemurda4b6c62020-02-13 00:28:40 +00001919 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001920 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001921 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1922 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001923 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001924
1925 self.assertEqual(0, git_cl.main(['archive', '-f']))
1926
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001927 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001928 self.calls = [
1929 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1930 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1931 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
1932 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001933 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
1934 ((['git', 'branch', '-D', 'foo'],), '')
1935 ]
1936
Edward Lemurda4b6c62020-02-13 00:28:40 +00001937 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001938 lambda branches, fine_grained, max_processes:
1939 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1940 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001941 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001942
1943 self.assertEqual(0, git_cl.main(['archive', '-f']))
1944
kmarshall3bff56b2016-06-06 18:31:47 -07001945 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001946 self.calls = [
1947 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1948 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001949 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001950 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001951
Edward Lemurda4b6c62020-02-13 00:28:40 +00001952 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001953 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00001954 [(MockChangelistWithBranchAndIssue('master', 1),
1955 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001956
1957 self.assertEqual(1, git_cl.main(['archive', '-f']))
1958
1959 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001960 self.calls = [
1961 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1962 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001963 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001964 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001965
Edward Lemurda4b6c62020-02-13 00:28:40 +00001966 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001967 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001968 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1969 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001970 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001971
kmarshall9249e012016-08-23 12:02:16 -07001972 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
1973
1974 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001975 self.calls = [
1976 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1977 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001978 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001979 ((['git', 'branch', '-D', 'foo'],), '')
1980 ]
kmarshall9249e012016-08-23 12:02:16 -07001981
Edward Lemurda4b6c62020-02-13 00:28:40 +00001982 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001983 lambda branches, fine_grained, max_processes:
1984 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1985 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001986 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001987
1988 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07001989
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001990 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001991 self.calls = [
1992 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1993 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1994 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001995 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
1996 'refs/tags/git-cl-archived-456-foo'),
1997 ((['git', 'branch', '-D', 'foo'],), CERR1),
1998 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
1999 'refs/tags/git-cl-archived-456-foo'),
2000 ]
2001
Edward Lemurda4b6c62020-02-13 00:28:40 +00002002 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002003 lambda branches, fine_grained, max_processes:
2004 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2005 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002006 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002007
2008 self.assertEqual(0, git_cl.main(['archive', '-f']))
2009
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002010 def test_archive_with_format(self):
2011 self.calls = [
2012 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
2013 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2014 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2015 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2016 ((['git', 'branch', '-D', 'foo'], ), ''),
2017 ]
2018
2019 mock.patch('git_cl.get_cl_statuses',
2020 lambda branches, fine_grained, max_processes:
2021 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2022
2023 self.assertEqual(
2024 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2025
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002026 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002027 self.mockGit.config['branch.master.gerritissue'] = '123'
2028 self.mockGit.config['branch.master.gerritserver'] = (
2029 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002030 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002031 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002032 ]
2033 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002034 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2035 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002036
Aaron Gable400e9892017-07-12 15:31:21 -07002037 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002038 self.mockGit.config['branch.master.gerritissue'] = '123'
2039 self.mockGit.config['branch.master.gerritserver'] = (
2040 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002041 mock.patch('git_cl.Changelist.FetchDescription',
2042 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002043 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002044 ((['git', 'log', '-1', '--format=%B'],),
2045 'This is a description\n\nChange-Id: Ideadbeef'),
2046 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002047 ]
2048 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002049 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2050 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002051
phajdan.jre328cf92016-08-22 04:12:17 -07002052 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002053 self.mockGit.config['branch.master.gerritissue'] = '123'
2054 self.mockGit.config['branch.master.gerritserver'] = (
2055 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002056 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002057 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002058 {'issue': 123,
2059 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002060 ''),
2061 ]
2062 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2063
tandrii16e0b4e2016-06-07 10:34:28 -07002064 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002065 mock.patch(
2066 'git_cl.os.path.abspath',
2067 lambda path: self._mocked_call(['abspath', path])).start()
2068 mock.patch(
2069 'git_cl.os.path.exists',
2070 lambda path: self._mocked_call(['exists', path])).start()
2071 mock.patch(
2072 'git_cl.gclient_utils.FileRead',
2073 lambda path: self._mocked_call(['FileRead', path])).start()
2074 mock.patch(
2075 'git_cl.gclient_utils.rm_file_or_tree',
2076 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002077 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002078 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002079 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002080 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002081
2082 def test_GerritCommitMsgHookCheck_custom_hook(self):
2083 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002084 self.calls += [((['exists',
2085 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2086 ((['FileRead',
2087 os.path.join('.git', 'hooks', 'commit-msg')], ),
2088 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002089 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002090
2091 def test_GerritCommitMsgHookCheck_not_exists(self):
2092 cl = self._common_GerritCommitMsgHookCheck()
2093 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002094 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002095 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002096 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002097
2098 def test_GerritCommitMsgHookCheck(self):
2099 cl = self._common_GerritCommitMsgHookCheck()
2100 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002101 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2102 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002103 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002104 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002105 ((['rm_file_or_tree',
2106 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002107 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002108 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002109
tandriic4344b52016-08-29 06:04:54 -07002110 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002111 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2112 self.mockGit.config['branch.master.gerritserver'] = (
2113 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002114 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002115 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002116 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002117 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002118 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002119 'labels': {},
2120 'current_revision': 'deadbeaf',
2121 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002122 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002123 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002124 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002125 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2126 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002127 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002128 self.assertEqual(0, cl.CMDLand(force=True,
2129 bypass_hooks=True,
2130 verbose=True,
2131 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002132 self.assertIn(
2133 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002134 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002135 self.assertIn(
2136 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002137 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002138
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002139 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002140 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002141
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002142 def test_gerrit_change_detail_cache_simple(self):
2143 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002144 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002145 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002146 cl1._cached_remote_url = (
2147 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002148 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002149 cl2._cached_remote_url = (
2150 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002151 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2152 self.assertEqual(cl1._GetChangeDetail(), 'a')
2153 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002154
2155 def test_gerrit_change_detail_cache_options(self):
2156 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002157 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002158 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002159 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002160 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2161 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2162 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2163 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2164 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2165 self.assertEqual(cl._GetChangeDetail(), 'cab')
2166
2167 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2168 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2169 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2170 self.assertEqual(cl._GetChangeDetail(), 'cab')
2171
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002172 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002173 gerrit_util.GetChangeDetail.return_value = {
2174 'current_revision': 'rev1',
2175 'revisions': {
2176 'rev1': {'commit': {'message': 'desc1'}},
2177 },
2178 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002179
2180 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002181 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002182 cl._cached_remote_url = (
2183 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002184 self.assertEqual(cl.FetchDescription(), 'desc1')
2185 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002186
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002187 def test_print_current_creds(self):
2188 class CookiesAuthenticatorMock(object):
2189 def __init__(self):
2190 self.gitcookies = {
2191 'host.googlesource.com': ('user', 'pass'),
2192 'host-review.googlesource.com': ('user', 'pass'),
2193 }
2194 self.netrc = self
2195 self.netrc.hosts = {
2196 'github.com': ('user2', None, 'pass2'),
2197 'host2.googlesource.com': ('user3', None, 'pass'),
2198 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002199 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2200 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002201 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2202 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2203 ' Host\t User\t Which file',
2204 '============================\t=====\t===========',
2205 'host-review.googlesource.com\t user\t.gitcookies',
2206 ' host.googlesource.com\t user\t.gitcookies',
2207 ' host2.googlesource.com\tuser3\t .netrc',
2208 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002209 sys.stdout.seek(0)
2210 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002211 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2212 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2213 ' Host\tUser\t Which file',
2214 '============================\t====\t===========',
2215 'host-review.googlesource.com\tuser\t.gitcookies',
2216 ' host.googlesource.com\tuser\t.gitcookies',
2217 ])
2218
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002219 def _common_creds_check_mocks(self):
2220 def exists_mock(path):
2221 dirname = os.path.dirname(path)
2222 if dirname == os.path.expanduser('~'):
2223 dirname = '~'
2224 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002225 if base in (NETRC_FILENAME, '.gitcookies'):
2226 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002227 # git cl also checks for existence other files not relevant to this test.
2228 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002229 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002230 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002231 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002232 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002233
2234 def test_creds_check_gitcookies_not_configured(self):
2235 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002236 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2237 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002238 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002239 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2240 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2241 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2242 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2243 'or Ctrl+C to abort'), ''),
2244 (([
2245 'git', 'config', '--global', 'http.cookiefile',
2246 os.path.expanduser(os.path.join('~', '.gitcookies'))
2247 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002248 ]
2249 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002250 self.assertTrue(
2251 sys.stdout.getvalue().startswith(
2252 'You seem to be using outdated .netrc for git credentials:'))
2253 self.assertIn(
2254 '\nConfigured git to use .gitcookies from',
2255 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002256
2257 def test_creds_check_gitcookies_configured_custom_broken(self):
2258 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002259 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2260 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002261 custom_cookie_path = ('C:\\.gitcookies'
2262 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002263 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002264 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2265 ((['git', 'config', '--global', 'http.cookiefile'], ),
2266 custom_cookie_path),
2267 (('os.path.exists', custom_cookie_path), False),
2268 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2269 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2270 (([
2271 'git', 'config', '--global', 'http.cookiefile',
2272 os.path.expanduser(os.path.join('~', '.gitcookies'))
2273 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002274 ]
2275 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002276 self.assertIn(
2277 'WARNING: You have configured custom path to .gitcookies: ',
2278 sys.stdout.getvalue())
2279 self.assertIn(
2280 'However, your configured .gitcookies file is missing.',
2281 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002282
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002283 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002284 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002285 self.mockGit.config['remote.origin.url'] = (
2286 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002287 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002288 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002289 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002290 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002291 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002292 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002293
Edward Lemurda4b6c62020-02-13 00:28:40 +00002294 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2295 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002296 self.mockGit.config['remote.origin.url'] = (
2297 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002298 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002299 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002300 'current_revision': 'ba5eba11',
2301 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002302 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002303 '_number': 1,
2304 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002305 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002306 '_number': 2,
2307 },
2308 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002309 'messages': [
2310 {
2311 u'_revision_number': 1,
2312 u'author': {
2313 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002314 u'email': u'could-be-anything@example.com',
2315 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002316 },
2317 u'date': u'2017-03-15 20:08:45.000000000',
2318 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002319 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002320 u'tag': u'autogenerated:cq:dry-run'
2321 },
2322 {
2323 u'_revision_number': 2,
2324 u'author': {
2325 u'_account_id': 11151243,
2326 u'email': u'owner@example.com',
2327 u'name': u'owner'
2328 },
2329 u'date': u'2017-03-16 20:00:41.000000000',
2330 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2331 u'message': u'PTAL',
2332 },
2333 {
2334 u'_revision_number': 2,
2335 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002336 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002337 u'email': u'reviewer@example.com',
2338 u'name': u'reviewer'
2339 },
2340 u'date': u'2017-03-17 05:19:37.500000000',
2341 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2342 u'message': u'Patch Set 2: Code-Review+1',
2343 },
2344 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002345 }
2346 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002347 (('GetChangeComments', 'chromium-review.googlesource.com',
2348 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002349 '/COMMIT_MSG': [
2350 {
2351 'author': {'email': u'reviewer@example.com'},
2352 'updated': u'2017-03-17 05:19:37.500000000',
2353 'patch_set': 2,
2354 'side': 'REVISION',
2355 'message': 'Please include a bug link',
2356 },
2357 ],
2358 'codereview.settings': [
2359 {
2360 'author': {'email': u'owner@example.com'},
2361 'updated': u'2017-03-16 20:00:41.000000000',
2362 'patch_set': 2,
2363 'side': 'PARENT',
2364 'line': 42,
2365 'message': 'I removed this because it is bad',
2366 },
2367 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002368 }),
2369 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2370 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002371 ] * 2 + [
2372 (('write_json', 'output.json', [
2373 {
2374 u'date': u'2017-03-16 20:00:41.000000',
2375 u'message': (
2376 u'PTAL\n' +
2377 u'\n' +
2378 u'codereview.settings\n' +
2379 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2380 u'c/1/2/codereview.settings#b42\n' +
2381 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002382 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002383 u'approval': False,
2384 u'disapproval': False,
2385 u'sender': u'owner@example.com'
2386 }, {
2387 u'date': u'2017-03-17 05:19:37.500000',
2388 u'message': (
2389 u'Patch Set 2: Code-Review+1\n' +
2390 u'\n' +
2391 u'/COMMIT_MSG\n' +
2392 u' PS2, File comment: https://chromium-review.googlesource' +
2393 u'.com/c/1/2//COMMIT_MSG#\n' +
2394 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002395 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002396 u'approval': False,
2397 u'disapproval': False,
2398 u'sender': u'reviewer@example.com'
2399 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002400 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002401 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002402 expected_comments_summary = [
2403 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002404 message=(
2405 u'PTAL\n' +
2406 u'\n' +
2407 u'codereview.settings\n' +
2408 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2409 u'c/1/2/codereview.settings#b42\n' +
2410 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002411 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002412 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002413 disapproval=False, approval=False, sender=u'owner@example.com'),
2414 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002415 message=(
2416 u'Patch Set 2: Code-Review+1\n' +
2417 u'\n' +
2418 u'/COMMIT_MSG\n' +
2419 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2420 u'c/1/2//COMMIT_MSG#\n' +
2421 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002422 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002423 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002424 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2425 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002426 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002427 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002428 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002429 self.assertEqual(
2430 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2431
2432 def test_git_cl_comments_robot_comments(self):
2433 # git cl comments also fetches robot comments (which are considered a type
2434 # of autogenerated comment), and unlike other types of comments, only robot
2435 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002436 self.mockGit.config['remote.origin.url'] = (
2437 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002438 gerrit_util.GetChangeDetail.return_value = {
2439 'owner': {'email': 'owner@example.com'},
2440 'current_revision': 'ba5eba11',
2441 'revisions': {
2442 'deadbeaf': {
2443 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002444 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002445 'ba5eba11': {
2446 '_number': 2,
2447 },
2448 },
2449 'messages': [
2450 {
2451 u'_revision_number': 1,
2452 u'author': {
2453 u'_account_id': 1111084,
2454 u'email': u'commit-bot@chromium.org',
2455 u'name': u'Commit Bot'
2456 },
2457 u'date': u'2017-03-15 20:08:45.000000000',
2458 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2459 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2460 u'tag': u'autogenerated:cq:dry-run'
2461 },
2462 {
2463 u'_revision_number': 1,
2464 u'author': {
2465 u'_account_id': 123,
2466 u'email': u'tricium@serviceaccount.com',
2467 u'name': u'Tricium'
2468 },
2469 u'date': u'2017-03-16 20:00:41.000000000',
2470 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2471 u'message': u'(1 comment)',
2472 u'tag': u'autogenerated:tricium',
2473 },
2474 {
2475 u'_revision_number': 1,
2476 u'author': {
2477 u'_account_id': 123,
2478 u'email': u'tricium@serviceaccount.com',
2479 u'name': u'Tricium'
2480 },
2481 u'date': u'2017-03-16 20:00:41.000000000',
2482 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2483 u'message': u'(1 comment)',
2484 u'tag': u'autogenerated:tricium',
2485 },
2486 {
2487 u'_revision_number': 2,
2488 u'author': {
2489 u'_account_id': 123,
2490 u'email': u'tricium@serviceaccount.com',
2491 u'name': u'reviewer'
2492 },
2493 u'date': u'2017-03-17 05:30:37.000000000',
2494 u'tag': u'autogenerated:tricium',
2495 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2496 u'message': u'(1 comment)',
2497 },
2498 ]
2499 }
2500 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002501 (('GetChangeComments', 'chromium-review.googlesource.com',
2502 'infra%2Finfra~1'), {}),
2503 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2504 'infra%2Finfra~1'), {
2505 'codereview.settings': [
2506 {
2507 u'author': {u'email': u'tricium@serviceaccount.com'},
2508 u'updated': u'2017-03-17 05:30:37.000000000',
2509 u'robot_run_id': u'5565031076855808',
2510 u'robot_id': u'Linter/Category',
2511 u'tag': u'autogenerated:tricium',
2512 u'patch_set': 2,
2513 u'side': u'REVISION',
2514 u'message': u'Linter warning message text',
2515 u'line': 32,
2516 },
2517 ],
2518 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002519 ]
2520 expected_comments_summary = [
2521 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2522 message=(
2523 u'(1 comment)\n\ncodereview.settings\n'
2524 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2525 u'c/1/2/codereview.settings#32\n'
2526 u' Linter warning message text\n'),
2527 sender=u'tricium@serviceaccount.com',
2528 autogenerated=True, approval=False, disapproval=False)
2529 ]
2530 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002531 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002532 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002533
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002534 def test_get_remote_url_with_mirror(self):
2535 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002536
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002537 def selective_os_path_isdir_mock(path):
2538 if path == '/cache/this-dir-exists':
2539 return self._mocked_call('os.path.isdir', path)
2540 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002541
Edward Lemurda4b6c62020-02-13 00:28:40 +00002542 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002543
2544 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002545 self.mockGit.config['remote.origin.url'] = (
2546 '/cache/this-dir-exists')
2547 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2548 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002549 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002550 (('os.path.isdir', '/cache/this-dir-exists'),
2551 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002552 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002553 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002554 self.assertEqual(cl.GetRemoteUrl(), url)
2555 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2556
Edward Lemur298f2cf2019-02-22 21:40:39 +00002557 def test_get_remote_url_non_existing_mirror(self):
2558 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002559
Edward Lemur298f2cf2019-02-22 21:40:39 +00002560 def selective_os_path_isdir_mock(path):
2561 if path == '/cache/this-dir-doesnt-exist':
2562 return self._mocked_call('os.path.isdir', path)
2563 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002564
Edward Lemurda4b6c62020-02-13 00:28:40 +00002565 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2566 mock.patch('logging.error',
2567 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002568
Edward Lemur26964072020-02-19 19:18:51 +00002569 self.mockGit.config['remote.origin.url'] = (
2570 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002571 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002572 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2573 False),
2574 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002575 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2576 'but it doesn\'t exist.', {
2577 'remote': 'origin',
2578 'branch': 'master',
2579 'url': '/cache/this-dir-doesnt-exist'}
2580 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002581 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002582 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002583 self.assertIsNone(cl.GetRemoteUrl())
2584
2585 def test_get_remote_url_misconfigured_mirror(self):
2586 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002587
Edward Lemur298f2cf2019-02-22 21:40:39 +00002588 def selective_os_path_isdir_mock(path):
2589 if path == '/cache/this-dir-exists':
2590 return self._mocked_call('os.path.isdir', path)
2591 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002592
Edward Lemurda4b6c62020-02-13 00:28:40 +00002593 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2594 mock.patch('logging.error',
2595 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002596
Edward Lemur26964072020-02-19 19:18:51 +00002597 self.mockGit.config['remote.origin.url'] = (
2598 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002599 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002600 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002601 (('logging.error',
2602 'Remote "%(remote)s" for branch "%(branch)s" points to '
2603 '"%(cache_path)s", but it is misconfigured.\n'
2604 '"%(cache_path)s" must be a git repo and must have a remote named '
2605 '"%(remote)s" pointing to the git host.', {
2606 'remote': 'origin',
2607 'cache_path': '/cache/this-dir-exists',
2608 'branch': 'master'}
2609 ), None),
2610 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002611 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002612 self.assertIsNone(cl.GetRemoteUrl())
2613
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002614 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002615 self.mockGit.config['remote.origin.url'] = (
2616 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002617 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002618 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2619
2620 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002621 mock.patch('logging.error',
2622 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002623
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002624 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002625 (('logging.error',
2626 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2627 'but it doesn\'t exist.', {
2628 'remote': 'origin',
2629 'branch': 'master',
2630 'url': ''}
2631 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002632 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002633 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002634 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002635
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002636
Edward Lemur9aa1a962020-02-25 00:58:38 +00002637class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002638 def setUp(self):
2639 super(ChangelistTest, self).setUp()
2640 mock.patch('gclient_utils.FileRead').start()
2641 mock.patch('gclient_utils.FileWrite').start()
2642 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2643 mock.patch(
2644 'git_cl.Changelist.GetCodereviewServer',
2645 return_value='https://chromium-review.googlesource.com').start()
2646 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2647 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2648 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2649 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2650 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2651 mock.patch('git_cl.time_time').start()
2652 mock.patch('metrics.collector').start()
2653 mock.patch('subprocess2.Popen').start()
2654 self.addCleanup(mock.patch.stopall)
2655 self.temp_count = 0
2656
Edward Lemur227d5102020-02-25 23:45:35 +00002657 def testRunHook(self):
2658 expected_results = {
2659 'more_cc': ['more@example.com', 'cc@example.com'],
2660 'should_continue': True,
2661 }
2662 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2663 git_cl.time_time.side_effect = [100, 200]
2664 mockProcess = mock.Mock()
2665 mockProcess.wait.return_value = 0
2666 subprocess2.Popen.return_value = mockProcess
2667
2668 cl = git_cl.Changelist()
2669 results = cl.RunHook(
2670 committing=True,
2671 may_prompt=True,
2672 verbose=2,
2673 parallel=True,
2674 upstream='upstream',
2675 description='description',
2676 all_files=True)
2677
2678 self.assertEqual(expected_results, results)
2679 subprocess2.Popen.assert_called_once_with([
2680 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002681 '--root', 'root',
2682 '--upstream', 'upstream',
2683 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002684 '--author', 'author',
2685 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002686 '--issue', '123456',
2687 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002688 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002689 '--may_prompt',
2690 '--parallel',
2691 '--all_files',
2692 '--json_output', '/tmp/fake-temp2',
2693 '--description_file', '/tmp/fake-temp1',
2694 ])
2695 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002696 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002697 metrics.collector.add_repeated('sub_commands', {
2698 'command': 'presubmit',
2699 'execution_time': 100,
2700 'exit_code': 0,
2701 })
2702
Edward Lemur99df04e2020-03-05 19:39:43 +00002703 def testRunHook_FewerOptions(self):
2704 expected_results = {
2705 'more_cc': ['more@example.com', 'cc@example.com'],
2706 'should_continue': True,
2707 }
2708 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2709 git_cl.time_time.side_effect = [100, 200]
2710 mockProcess = mock.Mock()
2711 mockProcess.wait.return_value = 0
2712 subprocess2.Popen.return_value = mockProcess
2713
2714 git_cl.Changelist.GetAuthor.return_value = None
2715 git_cl.Changelist.GetIssue.return_value = None
2716 git_cl.Changelist.GetPatchset.return_value = None
2717 git_cl.Changelist.GetCodereviewServer.return_value = None
2718
2719 cl = git_cl.Changelist()
2720 results = cl.RunHook(
2721 committing=False,
2722 may_prompt=False,
2723 verbose=0,
2724 parallel=False,
2725 upstream='upstream',
2726 description='description',
2727 all_files=False)
2728
2729 self.assertEqual(expected_results, results)
2730 subprocess2.Popen.assert_called_once_with([
2731 'vpython', 'PRESUBMIT_SUPPORT',
2732 '--root', 'root',
2733 '--upstream', 'upstream',
2734 '--upload',
2735 '--json_output', '/tmp/fake-temp2',
2736 '--description_file', '/tmp/fake-temp1',
2737 ])
2738 gclient_utils.FileWrite.assert_called_once_with(
2739 '/tmp/fake-temp1', 'description')
2740 metrics.collector.add_repeated('sub_commands', {
2741 'command': 'presubmit',
2742 'execution_time': 100,
2743 'exit_code': 0,
2744 })
2745
Edward Lemur227d5102020-02-25 23:45:35 +00002746 @mock.patch('sys.exit', side_effect=SystemExitMock)
2747 def testRunHook_Failure(self, _mock):
2748 git_cl.time_time.side_effect = [100, 200]
2749 mockProcess = mock.Mock()
2750 mockProcess.wait.return_value = 2
2751 subprocess2.Popen.return_value = mockProcess
2752
2753 cl = git_cl.Changelist()
2754 with self.assertRaises(SystemExitMock):
2755 cl.RunHook(
2756 committing=True,
2757 may_prompt=True,
2758 verbose=2,
2759 parallel=True,
2760 upstream='upstream',
2761 description='description',
2762 all_files=True)
2763
2764 sys.exit.assert_called_once_with(2)
2765
Edward Lemur75526302020-02-27 22:31:05 +00002766 def testRunPostUploadHook(self):
2767 cl = git_cl.Changelist()
2768 cl.RunPostUploadHook(2, 'upstream', 'description')
2769
2770 subprocess2.Popen.assert_called_once_with([
2771 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002772 '--root', 'root',
2773 '--upstream', 'upstream',
2774 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002775 '--author', 'author',
2776 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002777 '--issue', '123456',
2778 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002779 '--post_upload',
2780 '--description_file', '/tmp/fake-temp1',
2781 ])
2782 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002783 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002784
Edward Lemur9aa1a962020-02-25 00:58:38 +00002785
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002786class CMDTestCaseBase(unittest.TestCase):
2787 _STATUSES = [
2788 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2789 'INFRA_FAILURE', 'CANCELED',
2790 ]
2791 _CHANGE_DETAIL = {
2792 'project': 'depot_tools',
2793 'status': 'OPEN',
2794 'owner': {'email': 'owner@e.mail'},
2795 'current_revision': 'beeeeeef',
2796 'revisions': {
2797 'deadbeaf': {'_number': 6},
2798 'beeeeeef': {
2799 '_number': 7,
2800 'fetch': {'http': {
2801 'url': 'https://chromium.googlesource.com/depot_tools',
2802 'ref': 'refs/changes/56/123456/7'
2803 }},
2804 },
2805 },
2806 }
2807 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002808 'builds': [{
2809 'id': str(100 + idx),
2810 'builder': {
2811 'project': 'chromium',
2812 'bucket': 'try',
2813 'builder': 'bot_' + status.lower(),
2814 },
2815 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2816 'tags': [],
2817 'status': status,
2818 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002819 }
2820
Edward Lemur4c707a22019-09-24 21:13:43 +00002821 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002822 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002823 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002824 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2825 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002826 mock.patch(
2827 'git_cl.Changelist.GetCodereviewServer',
2828 return_value='https://chromium-review.googlesource.com').start()
2829 mock.patch(
2830 'git_cl.Changelist._GetGerritHost',
2831 return_value='chromium-review.googlesource.com').start()
2832 mock.patch(
2833 'git_cl.Changelist.GetMostRecentPatchset',
2834 return_value=7).start()
2835 mock.patch(
2836 'git_cl.Changelist.GetRemoteUrl',
2837 return_value='https://chromium.googlesource.com/depot_tools').start()
2838 mock.patch(
2839 'auth.Authenticator',
2840 return_value=AuthenticatorMock()).start()
2841 mock.patch(
2842 'gerrit_util.GetChangeDetail',
2843 return_value=self._CHANGE_DETAIL).start()
2844 mock.patch(
2845 'git_cl._call_buildbucket',
2846 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002847 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002848 self.addCleanup(mock.patch.stopall)
2849
Edward Lemur4c707a22019-09-24 21:13:43 +00002850
Edward Lemur9468eba2020-02-27 19:07:22 +00002851class CMDPresubmitTestCase(CMDTestCaseBase):
2852 def setUp(self):
2853 super(CMDPresubmitTestCase, self).setUp()
2854 mock.patch(
2855 'git_cl.Changelist.GetCommonAncestorWithUpstream',
2856 return_value='upstream').start()
2857 mock.patch(
2858 'git_cl.Changelist.FetchDescription',
2859 return_value='fetch description').start()
2860 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00002861 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00002862 return_value='get description').start()
2863 mock.patch('git_cl.Changelist.RunHook').start()
2864
2865 def testDefaultCase(self):
2866 self.assertEqual(0, git_cl.main(['presubmit']))
2867 git_cl.Changelist.RunHook.assert_called_once_with(
2868 committing=True,
2869 may_prompt=False,
2870 verbose=0,
2871 parallel=None,
2872 upstream='upstream',
2873 description='fetch description',
2874 all_files=None)
2875
2876 def testNoIssue(self):
2877 git_cl.Changelist.GetIssue.return_value = None
2878 self.assertEqual(0, git_cl.main(['presubmit']))
2879 git_cl.Changelist.RunHook.assert_called_once_with(
2880 committing=True,
2881 may_prompt=False,
2882 verbose=0,
2883 parallel=None,
2884 upstream='upstream',
2885 description='get description',
2886 all_files=None)
2887
2888 def testCustomBranch(self):
2889 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
2890 git_cl.Changelist.RunHook.assert_called_once_with(
2891 committing=True,
2892 may_prompt=False,
2893 verbose=0,
2894 parallel=None,
2895 upstream='custom_branch',
2896 description='fetch description',
2897 all_files=None)
2898
2899 def testOptions(self):
2900 self.assertEqual(
2901 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
2902 git_cl.Changelist.RunHook.assert_called_once_with(
2903 committing=False,
2904 may_prompt=False,
2905 verbose=2,
2906 parallel=True,
2907 upstream='upstream',
2908 description='fetch description',
2909 all_files=True)
2910
2911
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002912class CMDTryResultsTestCase(CMDTestCaseBase):
2913 _DEFAULT_REQUEST = {
2914 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002915 "gerritChanges": [{
2916 "project": "depot_tools",
2917 "host": "chromium-review.googlesource.com",
2918 "patchset": 7,
2919 "change": 123456,
2920 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002921 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002922 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2923 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002924 }
2925
2926 def testNoJobs(self):
2927 git_cl._call_buildbucket.return_value = {}
2928
2929 self.assertEqual(0, git_cl.main(['try-results']))
2930 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2931 git_cl._call_buildbucket.assert_called_once_with(
2932 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2933 self._DEFAULT_REQUEST)
2934
2935 def testPrintToStdout(self):
2936 self.assertEqual(0, git_cl.main(['try-results']))
2937 self.assertEqual([
2938 'Successes:',
2939 ' bot_success https://ci.chromium.org/b/103',
2940 'Infra Failures:',
2941 ' bot_infra_failure https://ci.chromium.org/b/105',
2942 'Failures:',
2943 ' bot_failure https://ci.chromium.org/b/104',
2944 'Canceled:',
2945 ' bot_canceled ',
2946 'Started:',
2947 ' bot_started https://ci.chromium.org/b/102',
2948 'Scheduled:',
2949 ' bot_scheduled id=101',
2950 'Other:',
2951 ' bot_status_unspecified id=100',
2952 'Total: 7 tryjobs',
2953 ], sys.stdout.getvalue().splitlines())
2954 git_cl._call_buildbucket.assert_called_once_with(
2955 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2956 self._DEFAULT_REQUEST)
2957
2958 def testPrintToStdoutWithMasters(self):
2959 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2960 self.assertEqual([
2961 'Successes:',
2962 ' try bot_success https://ci.chromium.org/b/103',
2963 'Infra Failures:',
2964 ' try bot_infra_failure https://ci.chromium.org/b/105',
2965 'Failures:',
2966 ' try bot_failure https://ci.chromium.org/b/104',
2967 'Canceled:',
2968 ' try bot_canceled ',
2969 'Started:',
2970 ' try bot_started https://ci.chromium.org/b/102',
2971 'Scheduled:',
2972 ' try bot_scheduled id=101',
2973 'Other:',
2974 ' try bot_status_unspecified id=100',
2975 'Total: 7 tryjobs',
2976 ], sys.stdout.getvalue().splitlines())
2977 git_cl._call_buildbucket.assert_called_once_with(
2978 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2979 self._DEFAULT_REQUEST)
2980
2981 @mock.patch('git_cl.write_json')
2982 def testWriteToJson(self, mockJsonDump):
2983 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
2984 git_cl._call_buildbucket.assert_called_once_with(
2985 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2986 self._DEFAULT_REQUEST)
2987 mockJsonDump.assert_called_once_with(
2988 'file.json', self._DEFAULT_RESPONSE['builds'])
2989
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002990 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00002991 self.assertEqual([], git_cl._filter_failed_for_retry([]))
2992 self.assertEqual(
2993 [
2994 ('chromium', 'try', 'bot_failure'),
2995 ('chromium', 'try', 'bot_infra_failure'),
2996 ],
2997 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002998
2999 def test_filter_failed_for_retry_many_builds(self):
3000
3001 def _build(name, created_sec, status, experimental=False):
3002 assert 0 <= created_sec < 100, created_sec
3003 b = {
3004 'id': 112112,
3005 'builder': {
3006 'project': 'chromium',
3007 'bucket': 'try',
3008 'builder': name,
3009 },
3010 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3011 'status': status,
3012 'tags': [],
3013 }
3014 if experimental:
3015 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3016 return b
3017
3018 builds = [
3019 _build('flaky-last-green', 1, 'FAILURE'),
3020 _build('flaky-last-green', 2, 'SUCCESS'),
3021 _build('flaky', 1, 'SUCCESS'),
3022 _build('flaky', 2, 'FAILURE'),
3023 _build('running', 1, 'FAILED'),
3024 _build('running', 2, 'SCHEDULED'),
3025 _build('yep-still-running', 1, 'STARTED'),
3026 _build('yep-still-running', 2, 'FAILURE'),
3027 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3028 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3029
3030 # Simulate experimental in CQ builder, which developer decided
3031 # to retry manually which resulted in 2nd build non-experimental.
3032 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3033 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3034 ]
3035 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003036 self.assertEqual(
3037 [
3038 ('chromium', 'try', 'flaky'),
3039 ('chromium', 'try', 'sometimes-experimental'),
3040 ],
3041 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003042
3043
3044class CMDTryTestCase(CMDTestCaseBase):
3045
3046 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003047 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003048 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003049 self.assertEqual(0, git_cl.main(['try']))
3050 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3051 self.assertEqual(
3052 sys.stdout.getvalue(),
3053 'Scheduling CQ dry run on: '
3054 'https://chromium-review.googlesource.com/123456\n')
3055
Edward Lemur4c707a22019-09-24 21:13:43 +00003056 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003057 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003058 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003059
3060 self.assertEqual(0, git_cl.main([
3061 'try', '-B', 'luci.chromium.try', '-b', 'win',
3062 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3063 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003064 'Scheduling jobs on:\n'
3065 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003066 git_cl.sys.stdout.getvalue())
3067
3068 expected_request = {
3069 "requests": [{
3070 "scheduleBuild": {
3071 "requestId": "uuid4",
3072 "builder": {
3073 "project": "chromium",
3074 "builder": "win",
3075 "bucket": "try",
3076 },
3077 "gerritChanges": [{
3078 "project": "depot_tools",
3079 "host": "chromium-review.googlesource.com",
3080 "patchset": 7,
3081 "change": 123456,
3082 }],
3083 "properties": {
3084 "category": "git_cl_try",
3085 "json": [{"a": 1}, None],
3086 "key": "val",
3087 },
3088 "tags": [
3089 {"value": "win", "key": "builder"},
3090 {"value": "git_cl_try", "key": "user_agent"},
3091 ],
3092 },
3093 }],
3094 }
3095 mockCallBuildbucket.assert_called_with(
3096 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3097
Anthony Polito1a5fe232020-01-24 23:17:52 +00003098 @mock.patch('git_cl._call_buildbucket')
3099 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3100 mockCallBuildbucket.return_value = {}
3101
3102 self.assertEqual(0, git_cl.main([
3103 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3104 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3105 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3106 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003107 'Scheduling jobs on:\n'
3108 ' chromium/try: linux\n'
3109 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003110 git_cl.sys.stdout.getvalue())
3111
3112 expected_request = {
3113 "requests": [{
3114 "scheduleBuild": {
3115 "requestId": "uuid4",
3116 "builder": {
3117 "project": "chromium",
3118 "builder": "linux",
3119 "bucket": "try",
3120 },
3121 "gerritChanges": [{
3122 "project": "depot_tools",
3123 "host": "chromium-review.googlesource.com",
3124 "patchset": 7,
3125 "change": 123456,
3126 }],
3127 "properties": {
3128 "category": "git_cl_try",
3129 "json": [{"a": 1}, None],
3130 "key": "val",
3131 },
3132 "tags": [
3133 {"value": "linux", "key": "builder"},
3134 {"value": "git_cl_try", "key": "user_agent"},
3135 ],
3136 "gitilesCommit": {
3137 "host": "chromium-review.googlesource.com",
3138 "project": "depot_tools",
3139 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3140 }
3141 },
3142 },
3143 {
3144 "scheduleBuild": {
3145 "requestId": "uuid4",
3146 "builder": {
3147 "project": "chromium",
3148 "builder": "win",
3149 "bucket": "try",
3150 },
3151 "gerritChanges": [{
3152 "project": "depot_tools",
3153 "host": "chromium-review.googlesource.com",
3154 "patchset": 7,
3155 "change": 123456,
3156 }],
3157 "properties": {
3158 "category": "git_cl_try",
3159 "json": [{"a": 1}, None],
3160 "key": "val",
3161 },
3162 "tags": [
3163 {"value": "win", "key": "builder"},
3164 {"value": "git_cl_try", "key": "user_agent"},
3165 ],
3166 "gitilesCommit": {
3167 "host": "chromium-review.googlesource.com",
3168 "project": "depot_tools",
3169 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3170 }
3171 },
3172 }],
3173 }
3174 mockCallBuildbucket.assert_called_with(
3175 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3176
Edward Lemur45768512020-03-02 19:03:14 +00003177 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003178 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003179 with self.assertRaises(SystemExit):
3180 git_cl.main([
3181 'try', '-B', 'not-a-bucket', '-b', 'win',
3182 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003183 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003184 'Invalid bucket: not-a-bucket.',
3185 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003186
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003187 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003188 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003189 def testScheduleOnBuildbucketRetryFailed(
3190 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003191 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003192 7: [],
3193 6: [{
3194 'id': 112112,
3195 'builder': {
3196 'project': 'chromium',
3197 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003198 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003199 'createTime': '2019-10-09T08:00:01.854286Z',
3200 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003201 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003202 mockCallBuildbucket.return_value = {}
3203
3204 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3205 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003206 'Scheduling jobs on:\n'
3207 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003208 git_cl.sys.stdout.getvalue())
3209
3210 expected_request = {
3211 "requests": [{
3212 "scheduleBuild": {
3213 "requestId": "uuid4",
3214 "builder": {
3215 "project": "chromium",
3216 "bucket": "try",
3217 "builder": "linux",
3218 },
3219 "gerritChanges": [{
3220 "project": "depot_tools",
3221 "host": "chromium-review.googlesource.com",
3222 "patchset": 7,
3223 "change": 123456,
3224 }],
3225 "properties": {
3226 "category": "git_cl_try",
3227 },
3228 "tags": [
3229 {"value": "linux", "key": "builder"},
3230 {"value": "git_cl_try", "key": "user_agent"},
3231 {"value": "1", "key": "retry_failed"},
3232 ],
3233 },
3234 }],
3235 }
3236 mockCallBuildbucket.assert_called_with(
3237 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3238
Edward Lemur4c707a22019-09-24 21:13:43 +00003239 def test_parse_bucket(self):
3240 test_cases = [
3241 {
3242 'bucket': 'chromium/try',
3243 'result': ('chromium', 'try'),
3244 },
3245 {
3246 'bucket': 'luci.chromium.try',
3247 'result': ('chromium', 'try'),
3248 'has_warning': True,
3249 },
3250 {
3251 'bucket': 'skia.primary',
3252 'result': ('skia', 'skia.primary'),
3253 'has_warning': True,
3254 },
3255 {
3256 'bucket': 'not-a-bucket',
3257 'result': (None, None),
3258 },
3259 ]
3260
3261 for test_case in test_cases:
3262 git_cl.sys.stdout.truncate(0)
3263 self.assertEqual(
3264 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3265 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003266 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3267 test_case['result'])
3268 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003269
3270
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003271class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003272
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003273 def setUp(self):
3274 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003275 mock.patch('git_cl._fetch_tryjobs').start()
3276 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003277 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003278 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3279 mock.patch(
3280 'git_cl.Settings.GetSquashGerritUploads',
3281 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003282 self.addCleanup(mock.patch.stopall)
3283
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003284 def testWarmUpChangeDetailCache(self):
3285 self.assertEqual(0, git_cl.main(['upload']))
3286 gerrit_util.GetChangeDetail.assert_called_once_with(
3287 'chromium-review.googlesource.com', 'depot_tools~123456',
3288 frozenset([
3289 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3290 'CURRENT_COMMIT']))
3291
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003292 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003293 # This test mocks out the actual upload part, and just asserts that after
3294 # upload, if --retry-failed is added, then the tool will fetch try jobs
3295 # from the previous patchset and trigger the right builders on the latest
3296 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003297 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003298 # Latest patchset: No builds.
3299 [],
3300 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003301 [{
3302 'id': str(100 + idx),
3303 'builder': {
3304 'project': 'chromium',
3305 'bucket': 'try',
3306 'builder': 'bot_' + status.lower(),
3307 },
3308 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3309 'tags': [],
3310 'status': status,
3311 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003312 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003313
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003314 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003315 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003316 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3317 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003318 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003319 expected_buckets = [
3320 ('chromium', 'try', 'bot_failure'),
3321 ('chromium', 'try', 'bot_infra_failure'),
3322 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003323 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3324 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003325
Brian Sheedy59b06a82019-10-14 17:03:29 +00003326
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003327class MakeRequestsHelperTestCase(unittest.TestCase):
3328
3329 def exampleGerritChange(self):
3330 return {
3331 'host': 'chromium-review.googlesource.com',
3332 'project': 'depot_tools',
3333 'change': 1,
3334 'patchset': 2,
3335 }
3336
3337 def testMakeRequestsHelperNoOptions(self):
3338 # Basic test for the helper function _make_tryjob_schedule_requests;
3339 # it shouldn't throw AttributeError even when options doesn't have any
3340 # of the expected values; it will use default option values.
3341 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3342 jobs = [('chromium', 'try', 'my-builder')]
3343 options = optparse.Values()
3344 requests = git_cl._make_tryjob_schedule_requests(
3345 changelist, jobs, options, patchset=None)
3346
3347 # requestId is non-deterministic. Just assert that it's there and has
3348 # a particular length.
3349 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3350 self.assertEqual(requests, [{
3351 'scheduleBuild': {
3352 'builder': {
3353 'bucket': 'try',
3354 'builder': 'my-builder',
3355 'project': 'chromium'
3356 },
3357 'gerritChanges': [self.exampleGerritChange()],
3358 'properties': {
3359 'category': 'git_cl_try'
3360 },
3361 'tags': [{
3362 'key': 'builder',
3363 'value': 'my-builder'
3364 }, {
3365 'key': 'user_agent',
3366 'value': 'git_cl_try'
3367 }]
3368 }
3369 }])
3370
3371 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3372 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3373 jobs = [('chromium', 'try', 'presubmit')]
3374 options = optparse.Values()
3375 requests = git_cl._make_tryjob_schedule_requests(
3376 changelist, jobs, options, patchset=None)
3377 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3378 'category': 'git_cl_try',
3379 'dry_run': 'true'
3380 })
3381
3382 def testMakeRequestsHelperRevisionSet(self):
3383 # Gitiles commit is specified when revision is in options.
3384 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3385 jobs = [('chromium', 'try', 'my-builder')]
3386 options = optparse.Values({'revision': 'ba5eba11'})
3387 requests = git_cl._make_tryjob_schedule_requests(
3388 changelist, jobs, options, patchset=None)
3389 self.assertEqual(
3390 requests[0]['scheduleBuild']['gitilesCommit'], {
3391 'host': 'chromium-review.googlesource.com',
3392 'id': 'ba5eba11',
3393 'project': 'depot_tools'
3394 })
3395
3396 def testMakeRequestsHelperRetryFailedSet(self):
3397 # An extra tag is added when retry_failed is in options.
3398 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3399 jobs = [('chromium', 'try', 'my-builder')]
3400 options = optparse.Values({'retry_failed': 'true'})
3401 requests = git_cl._make_tryjob_schedule_requests(
3402 changelist, jobs, options, patchset=None)
3403 self.assertEqual(
3404 requests[0]['scheduleBuild']['tags'], [
3405 {
3406 'key': 'builder',
3407 'value': 'my-builder'
3408 },
3409 {
3410 'key': 'user_agent',
3411 'value': 'git_cl_try'
3412 },
3413 {
3414 'key': 'retry_failed',
3415 'value': '1'
3416 }
3417 ])
3418
3419 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00003420 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003421 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3422 jobs = [('chromium', 'try', 'my-builder')]
3423 options = optparse.Values({'category': 'my-special-category'})
3424 requests = git_cl._make_tryjob_schedule_requests(
3425 changelist, jobs, options, patchset=None)
3426 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3427 {'category': 'my-special-category'})
3428
3429
Edward Lemurda4b6c62020-02-13 00:28:40 +00003430class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003431
3432 def setUp(self):
3433 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003434 mock.patch('git_cl.RunCommand').start()
3435 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3436 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3437 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003438 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003439 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003440
3441 def tearDown(self):
3442 shutil.rmtree(self._top_dir)
3443 super(CMDFormatTestCase, self).tearDown()
3444
Jamie Madill5e96ad12020-01-13 16:08:35 +00003445 def _make_temp_file(self, fname, contents):
3446 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3447 tf.write('\n'.join(contents))
3448
Brian Sheedy59b06a82019-10-14 17:03:29 +00003449 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003450 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003451
Brian Sheedyb4307d52019-12-02 19:18:17 +00003452 def _check_yapf_filtering(self, files, expected):
3453 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3454 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003455
Edward Lemur1a83da12020-03-04 21:18:36 +00003456 def _run_command_mock(self, return_value):
3457 def f(*args, **kwargs):
3458 if 'stdin' in kwargs:
3459 self.assertIsInstance(kwargs['stdin'], bytes)
3460 return return_value
3461 return f
3462
Jamie Madill5e96ad12020-01-13 16:08:35 +00003463 def testClangFormatDiffFull(self):
3464 self._make_temp_file('test.cc', ['// test'])
3465 git_cl.settings.GetFormatFullByDefault.return_value = False
3466 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3467 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3468
3469 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003470 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003471 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3472 self._top_dir, 'HEAD')
3473 self.assertEqual(2, return_value)
3474
3475 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003476 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003477 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3478 self._top_dir, 'HEAD')
3479 self.assertEqual(0, return_value)
3480
3481 def testClangFormatDiff(self):
3482 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00003483 # A valid file is required, so use this test.
3484 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00003485 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3486
3487 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003488 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3489 return_value = git_cl._RunClangFormatDiff(
3490 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003491 self.assertEqual(2, return_value)
3492
3493 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003494 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003495 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3496 'HEAD')
3497 self.assertEqual(0, return_value)
3498
Brian Sheedyb4307d52019-12-02 19:18:17 +00003499 def testYapfignoreExplicit(self):
3500 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3501 files = [
3502 'bar.py',
3503 'foo/bar.py',
3504 'foo/baz.py',
3505 'foo/bar/baz.py',
3506 'foo/bar/foobar.py',
3507 ]
3508 expected = [
3509 'bar.py',
3510 'foo/baz.py',
3511 'foo/bar/foobar.py',
3512 ]
3513 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003514
Brian Sheedyb4307d52019-12-02 19:18:17 +00003515 def testYapfignoreSingleWildcards(self):
3516 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3517 files = [
3518 'bar.py', # Matched by *bar.py.
3519 'bar.txt',
3520 'foobar.py', # Matched by *bar.py, foo*.
3521 'foobar.txt', # Matched by foo*.
3522 'bazbar.py', # Matched by *bar.py, baz*.py.
3523 'bazbar.txt',
3524 'foo/baz.txt', # Matched by foo*.
3525 'bar/bar.py', # Matched by *bar.py.
3526 'baz/foo.py', # Matched by baz*.py, foo*.
3527 'baz/foo.txt',
3528 ]
3529 expected = [
3530 'bar.txt',
3531 'bazbar.txt',
3532 'baz/foo.txt',
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 testYapfignoreMultiplewildcards(self):
3537 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3538 files = [
3539 'bar.py', # Matched by *bar*.
3540 'bar.txt', # Matched by *bar*.
3541 'abar.py', # Matched by *bar*.
3542 'foobaz.txt', # Matched by *foo*baz.txt.
3543 'foobaz.py',
3544 'afoobaz.txt', # Matched by *foo*baz.txt.
3545 ]
3546 expected = [
3547 'foobaz.py',
3548 ]
3549 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003550
3551 def testYapfignoreComments(self):
3552 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003553 files = [
3554 'test.py',
3555 'test2.py',
3556 ]
3557 expected = [
3558 'test2.py',
3559 ]
3560 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003561
3562 def testYapfignoreBlankLines(self):
3563 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003564 files = [
3565 'test.py',
3566 'test2.py',
3567 'test3.py',
3568 ]
3569 expected = [
3570 'test3.py',
3571 ]
3572 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003573
3574 def testYapfignoreWhitespace(self):
3575 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003576 files = [
3577 'test.py',
3578 'test2.py',
3579 ]
3580 expected = [
3581 'test2.py',
3582 ]
3583 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003584
Brian Sheedyb4307d52019-12-02 19:18:17 +00003585 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003586 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003587 self._check_yapf_filtering([], [])
3588
3589 def testYapfignoreMissingYapfignore(self):
3590 files = [
3591 'test.py',
3592 ]
3593 expected = [
3594 'test.py',
3595 ]
3596 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003597
3598
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003599if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003600 logging.basicConfig(
3601 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003602 unittest.main()