blob: 29c88d5d69fedf6e4faeffa3636b7a21606562bb [file] [log] [blame]
Edward Lemur0db01f02019-11-12 22:01:51 +00001#!/usr/bin/env vpython3
2# coding=utf-8
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00003# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Unit tests for git_cl.py."""
8
Edward Lemur85153282020-02-14 22:06:29 +00009from __future__ import print_function
Edward Lemur0db01f02019-11-12 22:01:51 +000010from __future__ import unicode_literals
11
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +010012import datetime
tandriide281ae2016-10-12 06:02:30 -070013import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010014import logging
Edward Lemur61bf4172020-02-24 23:22:37 +000015import multiprocessing
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000016import optparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000017import os
Edward Lemur85153282020-02-14 22:06:29 +000018import pprint
Brian Sheedy59b06a82019-10-14 17:03:29 +000019import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000020import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070021import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000022import unittest
23
Edward Lemura8145022020-01-06 18:47:54 +000024if sys.version_info.major == 2:
25 from StringIO import StringIO
26 import mock
27else:
28 from io import StringIO
29 from unittest import mock
30
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
32
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000033import metrics
34# We have to disable monitoring before importing git_cl.
35metrics.DISABLE_METRICS_COLLECTION = True
36
Jamie Madill5e96ad12020-01-13 16:08:35 +000037import clang_format
Edward Lemur227d5102020-02-25 23:45:35 +000038import contextlib
Edward Lemur1773f372020-02-22 00:27:14 +000039import gclient_utils
Eric Boren2fb63102018-10-05 13:05:03 +000040import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000041import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000042import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000043import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000044import git_new_branch
45import scm
maruel@chromium.orgddd59412011-11-30 14:20:38 +000046import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000047
Josip Sokcevic464e9ff2020-03-18 23:48:55 +000048NETRC_FILENAME = '_netrc' if sys.platform == 'win32' else '.netrc'
49
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000050
Edward Lemur0db01f02019-11-12 22:01:51 +000051def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070052 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
53
tandrii5d48c322016-08-18 16:19:37 -070054CERR1 = callError(1)
55
56
Edward Lemur1773f372020-02-22 00:27:14 +000057class TemporaryFileMock(object):
58 def __init__(self):
59 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070060
Edward Lemur1773f372020-02-22 00:27:14 +000061 @contextlib.contextmanager
62 def __call__(self):
63 self.suffix += 1
64 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070065
66
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000067class ChangelistMock(object):
68 # A class variable so we can access it when we don't have access to the
69 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000070 desc = ''
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000071
72 def __init__(self, gerrit_change=None, **kwargs):
73 self._gerrit_change = gerrit_change
74
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000075 def GetIssue(self):
76 return 1
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000077
Edward Lemur6c6827c2020-02-06 21:15:18 +000078 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000079 return ChangelistMock.desc
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000080
dsansomee2d6fd92016-09-08 00:10:47 -070081 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000082 ChangelistMock.desc = desc
83
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000084 def GetGerritChange(self, patchset=None, **kwargs):
85 del patchset
86 return self._gerrit_change
87
tandrii5d48c322016-08-18 16:19:37 -070088
Edward Lemur85153282020-02-14 22:06:29 +000089class GitMocks(object):
90 def __init__(self, config=None, branchref=None):
91 self.branchref = branchref or 'refs/heads/master'
92 self.config = config or {}
93
94 def GetBranchRef(self, _root):
95 return self.branchref
96
97 def NewBranch(self, branchref):
98 self.branchref = branchref
99
Edward Lemur26964072020-02-19 19:18:51 +0000100 def GetConfig(self, root, key, default=None):
101 if root != '':
102 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000103 return self.config.get(key, default)
104
Edward Lemur26964072020-02-19 19:18:51 +0000105 def SetConfig(self, root, key, value=None):
106 if root != '':
107 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000108 if value:
109 self.config[key] = value
110 return
111 if key not in self.config:
112 raise CERR1
113 del self.config[key]
114
115
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000116class WatchlistsMock(object):
117 def __init__(self, _):
118 pass
119 @staticmethod
120 def GetWatchersForPaths(_):
121 return ['joe@example.com']
122
123
Edward Lemur4c707a22019-09-24 21:13:43 +0000124class CodereviewSettingsFileMock(object):
125 def __init__(self):
126 pass
127 # pylint: disable=no-self-use
128 def read(self):
129 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
130 'GERRIT_HOST: True\n')
131
132
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000133class AuthenticatorMock(object):
134 def __init__(self, *_args):
135 pass
136 def has_cached_credentials(self):
137 return True
tandrii221ab252016-10-06 08:12:04 -0700138 def authorize(self, http):
139 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000140
141
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100142def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000143 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
144
145 Usage:
146 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100147 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000148
149 OR
150 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100151 CookiesAuthenticatorMockFactory(
152 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000153 """
154 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800155 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000156 # Intentionally not calling super() because it reads actual cookie files.
157 pass
158 @classmethod
159 def get_gitcookies_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000160 return os.path.join('~', '.gitcookies')
161
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000162 @classmethod
163 def get_netrc_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000164 return os.path.join('~', NETRC_FILENAME)
165
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100166 def _get_auth_for_host(self, host):
167 if same_auth:
168 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000169 return (hosts_with_creds or {}).get(host)
170 return CookiesAuthenticatorMock
171
Aaron Gable9a03ae02017-11-03 11:31:07 -0700172
kmarshall9249e012016-08-23 12:02:16 -0700173class MockChangelistWithBranchAndIssue():
174 def __init__(self, branch, issue):
175 self.branch = branch
176 self.issue = issue
177 def GetBranch(self):
178 return self.branch
179 def GetIssue(self):
180 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000181
tandriic2405f52016-10-10 08:13:15 -0700182
183class SystemExitMock(Exception):
184 pass
185
186
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000187class TestGitClBasic(unittest.TestCase):
Josip Sokcevic953278a2020-02-28 19:46:36 +0000188 def setUp(self):
189 mock.patch('sys.exit', side_effect=SystemExitMock).start()
190 mock.patch('sys.stdout', StringIO()).start()
191 mock.patch('sys.stderr', StringIO()).start()
192 self.addCleanup(mock.patch.stopall)
193
194 def test_die_with_error(self):
195 with self.assertRaises(SystemExitMock):
196 git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
197 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
198 self.assertTrue('saving CL description' in sys.stdout.getvalue())
199 self.assertTrue('Content of CL description' in sys.stdout.getvalue())
200 self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
201 sys.exit.assert_called_once_with(1)
202
203 def test_die_with_error_no_desc(self):
204 with self.assertRaises(SystemExitMock):
205 git_cl.DieWithError('foo')
206 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
207 self.assertEqual(sys.stdout.getvalue(), '')
208 sys.exit.assert_called_once_with(1)
209
Edward Lemur6c6827c2020-02-06 21:15:18 +0000210 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000211 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100212 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000213 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700214
Edward Lemur61bf4172020-02-24 23:22:37 +0000215 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
216 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
217 def test_get_cl_statuses(self, *_mocks):
218 statuses = [
219 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
220 changes = []
221 for status in statuses:
222 cl = git_cl.Changelist()
223 cl.status = status
224 changes.append(cl)
225
226 actual = set(git_cl.get_cl_statuses(changes, True))
227 self.assertEqual(set(zip(changes, statuses)), actual)
228
229 def test_get_cl_statuses_no_changes(self):
230 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
231
232 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
233 @mock.patch('multiprocessing.pool.ThreadPool')
234 def test_get_cl_statuses_timeout(self, *_mocks):
235 changes = [git_cl.Changelist() for _ in range(2)]
236 pool = multiprocessing.pool.ThreadPool()
237 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
238 it.return_value.next.side_effect = [
239 (changes[0], 'lgtm'),
240 multiprocessing.TimeoutError,
241 ]
242
243 actual = list(git_cl.get_cl_statuses(changes, True))
244 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
245
246 @mock.patch('git_cl.Changelist.GetIssueURL')
247 def test_get_cl_statuses_not_finegrained(self, _mock):
248 changes = [git_cl.Changelist() for _ in range(2)]
249 urls = ['some-url', None]
250 git_cl.Changelist.GetIssueURL.side_effect = urls
251
252 actual = set(git_cl.get_cl_statuses(changes, False))
253 self.assertEqual(
254 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
255
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000256 def test_get_issue_url(self):
257 cl = git_cl.Changelist(issue=123)
258 cl._gerrit_server = 'https://example.com'
259 self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
260 self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
261
262 cl = git_cl.Changelist(issue=123)
263 cl._gerrit_server = 'https://chromium-review.googlesource.com'
264 self.assertEqual(cl.GetIssueURL(),
265 'https://chromium-review.googlesource.com/123')
266 self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
267
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000268 def test_set_preserve_tryjobs(self):
269 d = git_cl.ChangeDescription('Simple.')
270 d.set_preserve_tryjobs()
271 self.assertEqual(d.description.splitlines(), [
272 'Simple.',
273 '',
274 'Cq-Do-Not-Cancel-Tryjobs: true',
275 ])
276 before = d.description
277 d.set_preserve_tryjobs()
278 self.assertEqual(before, d.description)
279
280 d = git_cl.ChangeDescription('\n'.join([
281 'One is enough',
282 '',
283 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
284 'Change-Id: Ideadbeef',
285 ]))
286 d.set_preserve_tryjobs()
287 self.assertEqual(d.description.splitlines(), [
288 'One is enough',
289 '',
290 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
291 'Change-Id: Ideadbeef',
292 'Cq-Do-Not-Cancel-Tryjobs: true',
293 ])
294
tandriif9aefb72016-07-01 09:06:51 -0700295 def test_get_bug_line_values(self):
296 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
297 self.assertEqual(f('', ''), [])
298 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
299 self.assertEqual(f('v8', '456'), ['v8:456'])
300 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
301 # Not nice, but not worth carying.
302 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
303 ['v8:456', 'chromium:123', 'v8:123'])
304
Edward Lemurda4b6c62020-02-13 00:28:40 +0000305 @mock.patch('gerrit_util.GetAccountDetails')
306 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000307 mock_per_account = {
308 'u1': None, # 404, doesn't exist.
309 'u2': {
310 '_account_id': 123124,
311 'avatars': [],
312 'email': 'u2@example.com',
313 'name': 'User Number 2',
314 'status': 'OOO',
315 },
316 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
317 }
318 def GetAccountDetailsMock(_, account):
319 # Poor-man's mock library's side_effect.
320 v = mock_per_account.pop(account)
321 if isinstance(v, Exception):
322 raise v
323 return v
324
Edward Lemurda4b6c62020-02-13 00:28:40 +0000325 mockGetAccountDetails.side_effect = GetAccountDetailsMock
326 actual = git_cl.gerrit_util.ValidAccounts(
327 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000328 self.assertEqual(actual, {
329 'u2': {
330 '_account_id': 123124,
331 'avatars': [],
332 'email': 'u2@example.com',
333 'name': 'User Number 2',
334 'status': 'OOO',
335 },
336 })
337
338
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200339class TestParseIssueURL(unittest.TestCase):
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000340 def _test(self, arg, issue=None, patchset=None, hostname=None, fail=False):
341 parsed = git_cl.ParseIssueNumberArgument(arg)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200342 self.assertIsNotNone(parsed)
343 if fail:
344 self.assertFalse(parsed.valid)
345 return
346 self.assertTrue(parsed.valid)
347 self.assertEqual(parsed.issue, issue)
348 self.assertEqual(parsed.patchset, patchset)
349 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200350
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000351 def test_basic(self):
352 self._test('123', 123)
353 self._test('', fail=True)
354 self._test('abc', fail=True)
355 self._test('123/1', fail=True)
356 self._test('123a', fail=True)
357 self._test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
358 self._test('ssh://chrome-review.source.com/c/123/1/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200359
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000360 def test_gerrit_url(self):
361 self._test('https://codereview.source.com/123', 123, None,
362 'codereview.source.com')
363 self._test('http://chrome-review.source.com/c/123', 123, None,
364 'chrome-review.source.com')
365 self._test('https://chrome-review.source.com/c/123/', 123, None,
366 'chrome-review.source.com')
367 self._test('https://chrome-review.source.com/c/123/4', 123, 4,
368 'chrome-review.source.com')
369 self._test('https://chrome-review.source.com/#/c/123/4', 123, 4,
370 'chrome-review.source.com')
371 self._test('https://chrome-review.source.com/c/123/4', 123, 4,
372 'chrome-review.source.com')
373 self._test('https://chrome-review.source.com/123', 123, None,
374 'chrome-review.source.com')
375 self._test('https://chrome-review.source.com/123/4', 123, 4,
376 'chrome-review.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200377
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000378 self._test('https://chrome-review.source.com/bad/123/4', fail=True)
379 self._test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
380 self._test('https://chrome-review.source.com/c/abc/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200381
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000382 def test_short_urls(self):
383 self._test('https://crrev.com/c/2151934', 2151934, None,
384 'chromium-review.googlesource.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200385
386
Edward Lemurda4b6c62020-02-13 00:28:40 +0000387class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100388 def setUp(self):
389 super(GitCookiesCheckerTest, self).setUp()
390 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100391 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000392 mock.patch('sys.stdout', StringIO()).start()
393 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100394
395 def mock_hosts_creds(self, subhost_identity_pairs):
396 def ensure_googlesource(h):
397 if not h.endswith(self.c._GOOGLESOURCE):
398 assert not h.endswith('.')
399 return h + '.' + self.c._GOOGLESOURCE
400 return h
401 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
402 for h, i in subhost_identity_pairs]
403
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200404 def test_identity_parsing(self):
405 self.assertEqual(self.c._parse_identity('ldap.google.com'),
406 ('ldap', 'google.com'))
407 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
408 ('ldap', 'example.com'))
409 # Specical case because we know there are no subdomains in chromium.org.
410 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
411 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800412 # Pathological: ".period." can be either username OR domain, more likely
413 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200414 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
415 ('note', 'period.example.com'))
416
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100417 def test_analysis_nothing(self):
418 self.c._all_hosts = []
419 self.assertFalse(self.c.has_generic_host())
420 self.assertEqual(set(), self.c.get_conflicting_hosts())
421 self.assertEqual(set(), self.c.get_duplicated_hosts())
422 self.assertEqual(set(), self.c.get_partially_configured_hosts())
423 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
424
425 def test_analysis(self):
426 self.mock_hosts_creds([
427 ('.googlesource.com', 'git-example.chromium.org'),
428
429 ('chromium', 'git-example.google.com'),
430 ('chromium-review', 'git-example.google.com'),
431 ('chrome-internal', 'git-example.chromium.org'),
432 ('chrome-internal-review', 'git-example.chromium.org'),
433 ('conflict', 'git-example.google.com'),
434 ('conflict-review', 'git-example.chromium.org'),
435 ('dup', 'git-example.google.com'),
436 ('dup', 'git-example.google.com'),
437 ('dup-review', 'git-example.google.com'),
438 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200439 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100440 ])
441 self.assertTrue(self.c.has_generic_host())
442 self.assertEqual(set(['conflict.googlesource.com']),
443 self.c.get_conflicting_hosts())
444 self.assertEqual(set(['dup.googlesource.com']),
445 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200446 self.assertEqual(set(['partial.googlesource.com',
447 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100448 self.c.get_partially_configured_hosts())
449 self.assertEqual(set(['chromium.googlesource.com',
450 'chrome-internal.googlesource.com']),
451 self.c.get_hosts_with_wrong_identities())
452
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100453 def test_report_no_problems(self):
454 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100455 self.assertFalse(self.c.find_and_report_problems())
456 self.assertEqual(sys.stdout.getvalue(), '')
457
Edward Lemurda4b6c62020-02-13 00:28:40 +0000458 @mock.patch(
459 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000460 return_value=os.path.join('~', '.gitcookies'))
Edward Lemurda4b6c62020-02-13 00:28:40 +0000461 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100462 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100463 self.assertTrue(self.c.find_and_report_problems())
464 with open(os.path.join(os.path.dirname(__file__),
465 'git_cl_creds_check_report.txt')) as f:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000466 expected = f.read() % {
467 'sep': os.sep,
468 }
469
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100470 def by_line(text):
471 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700472 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200473 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100474
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800475
Edward Lemurda4b6c62020-02-13 00:28:40 +0000476class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000477 def setUp(self):
478 super(TestGitCl, self).setUp()
479 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700480 self._calls_done = []
Edward Lesmes0dd54822020-03-26 18:24:25 +0000481 self.failed = False
Edward Lemurda4b6c62020-02-13 00:28:40 +0000482 mock.patch('sys.stdout', StringIO()).start()
483 mock.patch(
484 'git_cl.time_time',
485 lambda: self._mocked_call('time.time')).start()
486 mock.patch(
487 'git_cl.metrics.collector.add_repeated',
488 lambda *a: self._mocked_call('add_repeated', *a)).start()
489 mock.patch('subprocess2.call', self._mocked_call).start()
490 mock.patch('subprocess2.check_call', self._mocked_call).start()
491 mock.patch('subprocess2.check_output', self._mocked_call).start()
492 mock.patch(
493 'subprocess2.communicate',
494 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
495 mock.patch(
496 'git_cl.gclient_utils.CheckCallAndFilter',
497 self._mocked_call).start()
498 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
499 mock.patch(
500 'git_common.get_or_create_merge_base',
501 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000502 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
503 mock.patch(
504 'git_cl.SaveDescriptionBackup',
505 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
506 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000507 'git_cl.write_json',
508 lambda *a: self._mocked_call('write_json', *a)).start()
509 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000510 'git_cl.Changelist.RunHook',
511 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000512 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
513 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000514 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000515 mock.patch(
516 'git_cl.gerrit_util.GetChangeComments',
517 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
518 mock.patch(
519 'git_cl.gerrit_util.GetChangeRobotComments',
520 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
521 mock.patch(
522 'git_cl.gerrit_util.AddReviewers',
523 lambda *a: self._mocked_call('AddReviewers', *a)).start()
524 mock.patch(
525 'git_cl.gerrit_util.SetReview',
526 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
527 self._mocked_call(
528 'SetReview', h, i, msg, labels, notify, ready))).start()
529 mock.patch(
530 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
531 return_value=False).start()
532 mock.patch(
533 'git_cl.gerrit_util.GceAuthenticator.is_gce',
534 return_value=False).start()
535 mock.patch(
536 'git_cl.gerrit_util.ValidAccounts',
537 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000538 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000539 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000540 self.mockGit = GitMocks()
541 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
542 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
Edward Lesmes50da7702020-03-30 19:23:43 +0000543 mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
544 mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
Edward Lemur85153282020-02-14 22:06:29 +0000545 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000546 mock.patch(
547 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000548 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000549 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000550 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000551 mock.patch(
552 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000553 # It's important to reset settings to not have inter-tests interference.
554 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000555 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000556
557 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000558 try:
Edward Lesmes0dd54822020-03-26 18:24:25 +0000559 if not self.failed:
560 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100561 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000562 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
563 if len(self.calls) > 5:
564 calls += ' ...\n'
565 self.fail(
566 '\n'
567 'There are un-consumed calls after this test has finished:\n' +
568 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000569 finally:
570 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000571
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000572 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000573 self.assertTrue(
574 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700575 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000576 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000577 expected_args, result = top
578
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000579 # Also logs otherwise it could get caught in a try/finally and be hard to
580 # diagnose.
581 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700582 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000583 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700584 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
585 for i, c in enumerate(self._calls_done[-N:]))
586 following_calls = '\n '.join(
587 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
588 for i, c in enumerate(self.calls[:N]))
589 extended_msg = (
590 'A few prior calls:\n %s\n\n'
591 'This (expected):\n @%d: %r\n'
592 'This (actual):\n @%d: %r\n\n'
593 'A few following expected calls:\n %s' %
594 (prior_calls, len(self._calls_done), expected_args,
595 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700596
Edward Lesmes0dd54822020-03-26 18:24:25 +0000597 self.failed = True
tandrii99a72f22016-08-17 14:33:24 -0700598 self.fail('@%d\n'
599 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000600 ' Actual: %r\n'
601 '\n'
602 '%s' % (
603 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700604
605 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700606 if isinstance(result, Exception):
607 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000608 # stdout from git commands is supposed to be a bytestream. Convert it here
609 # instead of converting all test output in this file to bytes.
610 if args[0][0] == 'git' and not isinstance(result, bytes):
611 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000612 return result
613
Edward Lemur1a83da12020-03-04 21:18:36 +0000614 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
615 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100616 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100617 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000618 self.assertEqual(
619 'prompt [Yes/No]: Please, type yes or no: ',
620 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100621
tandrii48df5812016-10-17 03:55:37 -0700622 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000623 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700624 self.calls = [
625 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700626 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
627 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
628 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
629 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700630 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
631 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700632 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
633 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000634 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
635 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700636 ((['git', 'config', 'gerrit.host', 'true'],), ''),
637 ]
638 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
639
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000640 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100641 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200642 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000643 custom_cl_base=None, short_hostname='chromium',
644 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000645 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200646 if custom_cl_base:
647 ancestor_revision = custom_cl_base
648 else:
649 # Determine ancestor_revision to be merge base.
650 ancestor_revision = 'fake_ancestor_sha'
651 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000652 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
653 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200654 ]
655
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100656 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000657 gerrit_util.GetChangeDetail.return_value = {
658 'owner': {'email': (other_cl_owner or 'owner@example.com')},
659 'change_id': (change_id or '123456789'),
660 'current_revision': 'sha1_of_current_revision',
661 'revisions': {'sha1_of_current_revision': {
662 'commit': {'message': fetched_description},
663 }},
664 'status': fetched_status or 'NEW',
665 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100666 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100667 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100668 if other_cl_owner:
669 calls += [
670 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
671 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100672
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100673 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200674 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
675 ([custom_cl_base] if custom_cl_base else
676 [ancestor_revision, 'HEAD']),),
677 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100678 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000679
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100680 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000681
Edward Lemur26964072020-02-19 19:18:51 +0000682 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700683 squash_mode='default',
Aaron Gablefd238082017-06-07 13:42:34 -0700684 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100685 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000686 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000687 short_hostname='chromium',
Edward Lemur5a644f82020-03-18 16:44:57 +0000688 labels=None, change_id=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000689 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000690 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000691 if post_amend_description is None:
692 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700693 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200694
695 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000696
Edward Lemur26964072020-02-19 19:18:51 +0000697 if squash_mode in ('override_squash', 'override_nosquash'):
698 self.mockGit.config['gerrit.override-squash-uploads'] = (
699 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700700
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000701 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000702 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200703 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200704 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000705 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000706 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000707 calls += [
708 ((['RunEditor'],), description),
709 ]
Josipe827b0f2020-01-30 00:07:20 +0000710 # user wants to edit description
711 if edit_description:
712 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000713 ((['RunEditor'],), edit_description),
714 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000715 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200716
717 if custom_cl_base is None:
718 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000719 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000720 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200721 ]
722 parent = 'origin/master'
723 else:
724 calls += [
725 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
726 'refs/remotes/origin/master'],),
727 callError(1)), # Means not ancenstor.
728 (('ask_for_data',
729 'Do you take responsibility for cleaning up potential mess '
730 'resulting from proceeding with upload? Press Enter to upload, '
731 'or Ctrl+C to abort'), ''),
732 ]
733 parent = custom_cl_base
734
735 calls += [
736 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
737 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000738 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200739 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000740 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200741 ref_to_push),
742 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000743 else:
744 ref_to_push = 'HEAD'
Edward Lemur5a644f82020-03-18 16:44:57 +0000745 parent = 'origin/refs/heads/master'
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000746
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000747 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000748 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000749 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200750 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000751
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000752 metrics_arguments = []
753
Aaron Gableafd52772017-06-27 16:40:10 -0700754 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700755 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000756 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700757 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400758 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700759 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000760 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700761 else:
762 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000763 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800764
Edward Lemur5a644f82020-03-18 16:44:57 +0000765 # If issue is given, then description is fetched from Gerrit instead.
766 if issue is None:
767 if squash:
768 title = 'Initial upload'
769 else:
770 if not title:
771 calls += [
772 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
773 (('ask_for_data', 'Title for patchset []: '), 'User input'),
774 ]
775 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700776 if title:
Edward Lemur5a644f82020-03-18 16:44:57 +0000777 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000778 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000779
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000780 if short_hostname == 'chromium':
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000781 # All reviewers and ccs get into ref_suffix.
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000782 for r in sorted(reviewers):
783 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000784 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000785 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000786 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000787 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000788 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000789 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000790 reviewers, cc = [], []
791 else:
792 # TODO(crbug/877717): remove this case.
793 calls += [
794 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
795 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000796 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000797 {
798 e: {'email': e}
799 for e in (reviewers + ['joe@example.com'] + cc)
800 })
801 ]
802 for r in sorted(reviewers):
803 if r != 'bad-account-or-email':
804 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000805 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000806 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000807 if issue is None:
808 cc += ['joe@example.com']
809 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000810 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000811 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000812 if c in cc:
813 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000814
Edward Lemur687ca902018-12-05 02:30:30 +0000815 for k, v in sorted((labels or {}).items()):
816 ref_suffix += ',l=%s+%d' % (k, v)
817 metrics_arguments.append('l=%s+%d' % (k, v))
818
819 if tbr:
820 calls += [
821 (('GetCodeReviewTbrScore',
822 '%s-review.googlesource.com' % short_hostname,
823 'my/repo'),
824 2,),
825 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000826
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000827 calls += [
828 (('time.time',), 1000,),
829 ((['git', 'push',
830 'https://%s.googlesource.com/my/repo' % short_hostname,
831 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
832 (('remote:\n'
833 'remote: Processing changes: (\)\n'
834 'remote: Processing changes: (|)\n'
835 'remote: Processing changes: (/)\n'
836 'remote: Processing changes: (-)\n'
837 'remote: Processing changes: new: 1 (/)\n'
838 'remote: Processing changes: new: 1, done\n'
839 'remote:\n'
840 'remote: New Changes:\n'
841 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
842 ' XXX\n'
843 'remote:\n'
844 'To https://%s.googlesource.com/my/repo\n'
845 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
846 ) % (short_hostname, short_hostname)),),
847 (('time.time',), 2000,),
848 (('add_repeated',
849 'sub_commands',
850 {
851 'execution_time': 1000,
852 'command': 'git push',
853 'exit_code': 0,
854 'arguments': sorted(metrics_arguments),
855 }),
856 None,),
857 ]
858
Edward Lemur1b52d872019-05-09 21:12:12 +0000859 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000860
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000861 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
862
Edward Lemur1b52d872019-05-09 21:12:12 +0000863 # Trace-related calls
864 calls += [
865 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000866 (
867 ([
868 'FileWrite', trace_name + '-README',
869 '%(date)s\n'
870 '%(short_hostname)s-review.googlesource.com\n'
871 '%(change_id)s\n'
872 '%(title)s\n'
873 '%(description)s\n'
874 '1000\n'
875 '0\n'
876 '%(trace_name)s' % {
Josip Sokcevic5e18b602020-04-23 21:47:00 +0000877 'date': '2017-03-16T20:00:41.000000',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000878 'short_hostname': short_hostname,
879 'change_id': change_id,
880 'description': final_description,
881 'title': title or '<untitled>',
882 'trace_name': trace_name,
883 }
884 ], ),
885 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000886 ),
887 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000888 (
889 (['os.path.isfile',
890 os.path.join('TEMP_DIR', 'trace-packet')], ),
891 True,
Edward Lemur1b52d872019-05-09 21:12:12 +0000892 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000893 (
894 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
895 ('git-hash: 0123456789012345678901234567890123456789\n'
896 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +0000897 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000898 (
899 ([
900 'FileWrite',
901 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
902 'git-hash: abcdea\n'
903 ], ),
904 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000905 ),
906 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000907 (
908 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
909 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000910 ),
911 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000912 (
913 (['git', 'config', '-l'], ),
914 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +0000915 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000916 (
917 ([
918 'FileWrite',
919 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
920 ], ),
921 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000922 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000923 (
924 (['os.path.isfile',
925 os.path.join('~', '.gitcookies')], ),
926 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +0000927 ),
928 ]
929 if gitcookies_exists:
930 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000931 (
932 (['FileRead', os.path.join('~', '.gitcookies')], ),
933 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +0000934 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000935 (
936 ([
937 'FileWrite',
938 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
939 ], ),
940 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000941 ),
942 ]
943 calls += [
944 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000945 (
946 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
947 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000948 ),
949 ]
950
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000951 # TODO(crbug/877717): this should never be used.
952 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000953 calls += [
954 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +0000955 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000956 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +0000957 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +0000958 notify),
959 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000960 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000961 return calls
962
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000963 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000964 self,
965 upload_args,
966 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000967 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700968 squash=True,
969 squash_mode=None,
Aaron Gable9b713dd2016-12-14 16:04:21 -0800970 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000971 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000972 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -0700973 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100974 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100975 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200976 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -0700977 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000978 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000979 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000980 labels=None,
981 change_id=None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000982 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000983 gitcookies_exists=True,
984 force=False,
Edward Lesmes0dd54822020-03-26 18:24:25 +0000985 log_description=None,
Josipe827b0f2020-01-30 00:07:20 +0000986 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000987 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000988 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700989 if squash_mode is None:
990 if '--no-squash' in upload_args:
991 squash_mode = 'nosquash'
992 elif '--squash' in upload_args:
993 squash_mode = 'squash'
994 else:
995 squash_mode = 'default'
996
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000997 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -0700998 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000999 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001000 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001001 same_auth=('git-owner.example.com', '', 'pass'))).start()
1002 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1003 lambda _, offer_removal: None).start()
1004 mock.patch('git_cl.gclient_utils.RunEditor',
1005 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1006 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1007 'DownloadGerritHook', force)).start()
1008 mock.patch('git_cl.gclient_utils.FileRead',
1009 lambda path: self._mocked_call(['FileRead', path])).start()
1010 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001011 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001012 ['FileWrite', path, contents])).start()
1013 mock.patch('git_cl.datetime_now',
1014 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1015 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1016 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1017 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001018 '%(now)s\n'
1019 '%(gerrit_host)s\n'
1020 '%(change_id)s\n'
1021 '%(title)s\n'
1022 '%(description)s\n'
1023 '%(execution_time)s\n'
1024 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001025 '%(trace_name)s').start()
1026 mock.patch('git_cl.shutil.make_archive',
1027 lambda *args: self._mocked_call(['make_archive'] +
1028 list(args))).start()
1029 mock.patch('os.path.isfile',
1030 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001031 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001032 'git_cl._create_description_from_log',
1033 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001034 mock.patch(
1035 'git_cl.Changelist._AddChangeIdToCommitMessage',
1036 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001037 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001038 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1039 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001040 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001041 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001042
Edward Lemur26964072020-02-19 19:18:51 +00001043 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001044 self.mockGit.config['branch.master.gerritissue'] = (
1045 str(issue) if issue else None)
1046 self.mockGit.config['remote.origin.url'] = (
1047 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001048 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001049
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001050 self.calls = self._gerrit_base_calls(
1051 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001052 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001053 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001054 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001055 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001056 short_hostname=short_hostname,
1057 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001058 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001059 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001060 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001061 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001062 self.calls += self._gerrit_upload_calls(
1063 description, reviewers, squash,
1064 squash_mode=squash_mode,
Aaron Gablefd238082017-06-07 13:42:34 -07001065 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001066 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001067 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001068 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001069 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001070 labels=labels,
1071 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001072 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001073 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001074 force=force,
1075 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001076 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001077 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001078 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001079 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001080 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001081 self.assertEqual(
1082 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001083 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001084
Edward Lemur1b52d872019-05-09 21:12:12 +00001085 def test_gerrit_upload_traces_no_gitcookies(self):
1086 self._run_gerrit_upload_test(
1087 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001088 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001089 [],
1090 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001091 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001092 change_id='Ixxx',
1093 gitcookies_exists=False)
1094
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001095 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001096 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001097 [],
1098 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1099 [],
1100 change_id='Ixxx')
1101
1102 def test_gerrit_upload_without_change_id_nosquash(self):
1103 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001104 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001105 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001106 [],
1107 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001108 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001109 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001110
1111 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001112 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001113 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001114 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001115 [],
tandriia60502f2016-06-20 02:01:53 -07001116 squash=False,
1117 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001118 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001119 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001120
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001121 def test_gerrit_no_reviewer(self):
1122 self._run_gerrit_upload_test(
1123 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001124 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001125 [],
1126 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001127 squash_mode='override_nosquash',
1128 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001129
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001130 def test_gerrit_no_reviewer_non_chromium_host(self):
1131 # TODO(crbug/877717): remove this test case.
1132 self._run_gerrit_upload_test(
1133 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001134 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001135 [],
1136 squash=False,
1137 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001138 short_hostname='other',
1139 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001140
Edward Lesmes0dd54822020-03-26 18:24:25 +00001141 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001142 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001143 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001144 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001145 squash=False,
1146 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001147 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001148 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001149
ukai@chromium.orge8077812012-02-03 03:41:46 +00001150 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001151 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001152 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001153 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001154 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001155 squash=False,
1156 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001157 notify=True,
1158 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001159 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001160 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001161
Anthony Polito8b955342019-09-24 19:01:36 +00001162 def test_gerrit_upload_force_sets_bug(self):
1163 self._run_gerrit_upload_test(
1164 ['-b', '10000', '-f'],
1165 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1166 [],
1167 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001168 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001169 change_id='Ixxx')
1170
Edward Lemur5fb22242020-03-12 22:05:13 +00001171 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001172 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001173 ['-b', '10000', '-m', 'Title', '--edit-description'],
1174 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001175 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001176 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001177 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001178 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001179 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001180 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001181
Dan Beamd8b04ca2019-10-10 21:23:26 +00001182 def test_gerrit_upload_force_sets_fixed(self):
1183 self._run_gerrit_upload_test(
1184 ['-x', '10000', '-f'],
1185 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1186 [],
1187 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001188 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001189 change_id='Ixxx')
1190
ukai@chromium.orge8077812012-02-03 03:41:46 +00001191 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001192 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1193 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001194 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001195 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001196 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001197 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001198 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001199 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001200 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001201 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001202 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001203 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001204
1205 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001206 self._run_gerrit_upload_test(
1207 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001208 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001209 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001210 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001211
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001212 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001213 self._run_gerrit_upload_test(
1214 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001215 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001216 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001217 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001218 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001219
Edward Lesmes0dd54822020-03-26 18:24:25 +00001220 def test_gerrit_upload_squash_first_title(self):
1221 self._run_gerrit_upload_test(
1222 ['-f', '-t', 'title'],
1223 'title\n\ndesc\n\nChange-Id: 123456789',
1224 [],
1225 force=True,
1226 squash=True,
1227 log_description='desc',
1228 change_id='123456789')
1229
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001230 def test_gerrit_upload_squash_first_with_labels(self):
1231 self._run_gerrit_upload_test(
1232 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001233 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001234 [],
1235 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001236 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001237 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001238
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001239 def test_gerrit_upload_squash_first_against_rev(self):
1240 custom_cl_base = 'custom_cl_base_rev_or_branch'
1241 self._run_gerrit_upload_test(
1242 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001243 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001244 [],
1245 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001246 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001247 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001248 self.assertIn(
1249 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1250 sys.stdout.getvalue())
1251
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001252 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001253 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001254 self._run_gerrit_upload_test(
1255 ['--squash'],
1256 description,
1257 [],
1258 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001259 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001260 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001261
Edward Lemurd55c5072020-02-20 01:09:07 +00001262 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001263 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001264 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001265 with self.assertRaises(SystemExitMock):
1266 self._run_gerrit_upload_test(
1267 ['--squash'],
1268 description,
1269 [],
1270 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001271 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001272 fetched_status='ABANDONED',
1273 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001274 self.assertEqual(
1275 'Change https://chromium-review.googlesource.com/123456 has been '
1276 'abandoned, new uploads are not allowed\n',
1277 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001278
Edward Lemurda4b6c62020-02-13 00:28:40 +00001279 @mock.patch(
1280 'gerrit_util.GetAccountDetails',
1281 return_value={'email': 'yet-another@example.com'})
1282 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001283 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001284 self._run_gerrit_upload_test(
1285 ['--squash'],
1286 description,
1287 [],
1288 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001289 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001290 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001291 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001292 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001293 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001294 'authenticate to Gerrit as yet-another@example.com.\n'
1295 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001296 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001297
Josipe827b0f2020-01-30 00:07:20 +00001298 def test_upload_change_description_editor(self):
1299 fetched_description = 'foo\n\nChange-Id: 123456789'
1300 description = 'bar\n\nChange-Id: 123456789'
1301 self._run_gerrit_upload_test(
1302 ['--squash', '--edit-description'],
1303 description,
1304 [],
1305 fetched_description=fetched_description,
1306 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001307 issue=123456,
1308 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001309 edit_description=description)
1310
Edward Lemurda4b6c62020-02-13 00:28:40 +00001311 @mock.patch('git_cl.RunGit')
1312 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001313 @mock.patch('sys.stdin', StringIO('\n'))
1314 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001315 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001316 def mock_run_git(*args, **_kwargs):
1317 if args[0] == ['for-each-ref',
1318 '--format=%(refname:short) %(upstream:short)',
1319 'refs/heads']:
1320 # Create a local branch dependency tree that looks like this:
1321 # test1 -> test2 -> test3 -> test4 -> test5
1322 # -> test3.1
1323 # test6 -> test0
1324 branch_deps = [
1325 'test2 test1', # test1 -> test2
1326 'test3 test2', # test2 -> test3
1327 'test3.1 test2', # test2 -> test3.1
1328 'test4 test3', # test3 -> test4
1329 'test5 test4', # test4 -> test5
1330 'test6 test0', # test0 -> test6
1331 'test7', # test7
1332 ]
1333 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001334 git_cl.RunGit.side_effect = mock_run_git
1335 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001336
1337 class MockChangelist():
1338 def __init__(self):
1339 pass
1340 def GetBranch(self):
1341 return 'test1'
1342 def GetIssue(self):
1343 return '123'
1344 def GetPatchset(self):
1345 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001346 def IsGerrit(self):
1347 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001348
1349 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1350 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001351 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001352 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001353 'This command will checkout all dependent branches '
1354 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001355 'or Ctrl+C to abort',
1356 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001357 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001358
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001359 def test_gerrit_change_id(self):
1360 self.calls = [
1361 ((['git', 'write-tree'], ),
1362 'hashtree'),
1363 ((['git', 'rev-parse', 'HEAD~0'], ),
1364 'branch-parent'),
1365 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1366 'A B <a@b.org> 1456848326 +0100'),
1367 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1368 'C D <c@d.org> 1456858326 +0100'),
1369 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1370 'hashchange'),
1371 ]
1372 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1373 self.assertEqual(change_id, 'Ihashchange')
1374
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001375 def test_desecription_append_footer(self):
1376 for init_desc, footer_line, expected_desc in [
1377 # Use unique desc first lines for easy test failure identification.
1378 ('foo', 'R=one', 'foo\n\nR=one'),
1379 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1380 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1381 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1382 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1383 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1384 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1385 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1386 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1387 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1388 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1389 ]:
1390 desc = git_cl.ChangeDescription(init_desc)
1391 desc.append_footer(footer_line)
1392 self.assertEqual(desc.description, expected_desc)
1393
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001394 def test_update_reviewers(self):
1395 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001396 ('foo', [], [],
1397 'foo'),
1398 ('foo\nR=xx', [], [],
1399 'foo\nR=xx'),
1400 ('foo\nTBR=xx', [], [],
1401 'foo\nTBR=xx'),
1402 ('foo', ['a@c'], [],
1403 'foo\n\nR=a@c'),
1404 ('foo\nR=xx', ['a@c'], [],
1405 'foo\n\nR=a@c, xx'),
1406 ('foo\nTBR=xx', ['a@c'], [],
1407 'foo\n\nR=a@c\nTBR=xx'),
1408 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1409 'foo\n\nR=a@c, yy\nTBR=xx'),
1410 ('foo\nBUG=', ['a@c'], [],
1411 'foo\nBUG=\nR=a@c'),
1412 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1413 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1414 ('foo', ['a@c', 'b@c'], [],
1415 'foo\n\nR=a@c, b@c'),
1416 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1417 'foo\nBar\n\nR=c@c\nBUG='),
1418 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1419 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001420 # Same as the line before, but full of whitespaces.
1421 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001422 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001423 'foo\nBar\n\nR=c@c\n BUG =',
1424 ),
1425 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001426 ('foo BUG=allo R=joe ', ['c@c'], [],
1427 'foo BUG=allo R=joe\n\nR=c@c'),
1428 # Redundant TBRs get promoted to Rs
1429 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1430 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001431 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001432 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001433 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001434 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001435 obj = git_cl.ChangeDescription(orig)
Edward Lemur2c62b332020-03-12 22:12:33 +00001436 obj.update_reviewers(reviewers, tbrs, None, None, None)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001437 actual.append(obj.description)
1438 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001439
Nodir Turakulov23b82142017-11-16 11:04:25 -08001440 def test_get_hash_tags(self):
1441 cases = [
1442 ('', []),
1443 ('a', []),
1444 ('[a]', ['a']),
1445 ('[aa]', ['aa']),
1446 ('[a ]', ['a']),
1447 ('[a- ]', ['a']),
1448 ('[a- b]', ['a-b']),
1449 ('[a--b]', ['a-b']),
1450 ('[a', []),
1451 ('[a]x', ['a']),
1452 ('[aa]x', ['aa']),
1453 ('[a b]', ['a-b']),
1454 ('[a b]', ['a-b']),
1455 ('[a__b]', ['a-b']),
1456 ('[a] x', ['a']),
1457 ('[a][b]', ['a', 'b']),
1458 ('[a] [b]', ['a', 'b']),
1459 ('[a][b]x', ['a', 'b']),
1460 ('[a][b] x', ['a', 'b']),
1461 ('[a]\n[b]', ['a']),
1462 ('[a\nb]', []),
1463 ('[a][', ['a']),
1464 ('Revert "[a] feature"', ['a']),
1465 ('Reland "[a] feature"', ['a']),
1466 ('Revert: [a] feature', ['a']),
1467 ('Reland: [a] feature', ['a']),
1468 ('Revert "Reland: [a] feature"', ['a']),
1469 ('Foo: feature', ['foo']),
1470 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001471 ('Change Foo::Bar', []),
1472 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001473 ('Revert "Foo bar: feature"', ['foo-bar']),
1474 ('Reland "Foo bar: feature"', ['foo-bar']),
1475 ]
1476 for desc, expected in cases:
1477 change_desc = git_cl.ChangeDescription(desc)
1478 actual = change_desc.get_hash_tags()
1479 self.assertEqual(
1480 actual,
1481 expected,
1482 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1483
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001484 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001485 self.assertEqual(None, git_cl.GetTargetRef(None,
1486 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001487 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001488
wittman@chromium.org455dc922015-01-26 20:15:50 +00001489 # Check default target refs for branches.
1490 self.assertEqual('refs/heads/master',
1491 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001492 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001493 self.assertEqual('refs/heads/master',
1494 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001495 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001496 self.assertEqual('refs/heads/master',
1497 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001498 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001499 self.assertEqual('refs/branch-heads/123',
1500 git_cl.GetTargetRef('origin',
1501 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001502 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001503 self.assertEqual('refs/diff/test',
1504 git_cl.GetTargetRef('origin',
1505 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001506 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001507 self.assertEqual('refs/heads/chrome/m42',
1508 git_cl.GetTargetRef('origin',
1509 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001510 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001511
1512 # Check target refs for user-specified target branch.
1513 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1514 'refs/remotes/branch-heads/123'):
1515 self.assertEqual('refs/branch-heads/123',
1516 git_cl.GetTargetRef('origin',
1517 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001518 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001519 for branch in ('origin/master', 'remotes/origin/master',
1520 'refs/remotes/origin/master'):
1521 self.assertEqual('refs/heads/master',
1522 git_cl.GetTargetRef('origin',
1523 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001524 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001525 for branch in ('master', 'heads/master', 'refs/heads/master'):
1526 self.assertEqual('refs/heads/master',
1527 git_cl.GetTargetRef('origin',
1528 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001529 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001530
Edward Lemurda4b6c62020-02-13 00:28:40 +00001531 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1532 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001533 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001534 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1535
Edward Lemur85153282020-02-14 22:06:29 +00001536 def assertIssueAndPatchset(
1537 self, branch='master', issue='123456', patchset='7',
1538 git_short_host='chromium'):
1539 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001540 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001541 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001542 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001543 self.assertEqual(
1544 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001545 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001546
Edward Lemur85153282020-02-14 22:06:29 +00001547 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001548 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001549 self.mockGit.config['remote.origin.url'] = (
1550 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001551 gerrit_util.GetChangeDetail.return_value = {
1552 'current_revision': '7777777777',
1553 'revisions': {
1554 '1111111111': {
1555 '_number': 1,
1556 'fetch': {'http': {
1557 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1558 'ref': 'refs/changes/56/123456/1',
1559 }},
1560 },
1561 '7777777777': {
1562 '_number': 7,
1563 'fetch': {'http': {
1564 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1565 'ref': 'refs/changes/56/123456/7',
1566 }},
1567 },
1568 },
1569 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001570
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001571 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001572 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001573 self.calls += [
1574 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1575 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001576 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001577 ]
1578 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001579 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001580
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001581 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001582 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001583 self.calls += [
1584 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1585 'refs/changes/56/123456/7'],), ''),
1586 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001587 ]
Edward Lemur85153282020-02-14 22:06:29 +00001588 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1589 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001590
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001591 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001592 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001593 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001594 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001595 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001596 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001597 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001598 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001599 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001600
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001601 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001602 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001603 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001604 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001605 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001606 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001607 ]
1608 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001609 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001610 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001611
Aaron Gable697a91b2018-01-19 15:20:15 -08001612 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001613 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001614 self.calls += [
1615 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1616 'refs/changes/56/123456/1'],), ''),
1617 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001618 ]
1619 self.assertEqual(git_cl.main(
1620 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1621 0)
Edward Lemur85153282020-02-14 22:06:29 +00001622 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001623
Edward Lemurd55c5072020-02-20 01:09:07 +00001624 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001625 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001626 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001627 self.calls += [
1628 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001629 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001630 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001631 ]
1632 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001633 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001634 self.assertEqual(
1635 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1636 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001637
Edward Lemurda4b6c62020-02-13 00:28:40 +00001638 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001639 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001640 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001641 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001642 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001643 self.mockGit.config['remote.origin.url'] = (
1644 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001645 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001646 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001647 self.assertEqual(
1648 'change 123456 at https://chromium-review.googlesource.com does not '
1649 'exist or you have no access to it\n',
1650 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001651
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001652 def _checkout_calls(self):
1653 return [
1654 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001655 'branch\\..*\\.gerritissue'], ),
1656 ('branch.ger-branch.gerritissue 123456\n'
1657 'branch.gbranch654.gerritissue 654321\n')),
1658 ]
1659
1660 def test_checkout_gerrit(self):
1661 """Tests git cl checkout <issue>."""
1662 self.calls = self._checkout_calls()
1663 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1664 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1665
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001666 def test_checkout_not_found(self):
1667 """Tests git cl checkout <issue>."""
1668 self.calls = self._checkout_calls()
1669 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1670
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001671 def test_checkout_no_branch_issues(self):
1672 """Tests git cl checkout <issue>."""
1673 self.calls = [
1674 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001675 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001676 ]
1677 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1678
Edward Lemur26964072020-02-19 19:18:51 +00001679 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001680 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001681 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001682 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001683 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1684 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001685 self.mockGit.config['remote.origin.url'] = (
1686 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001687 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001688 cl.branch = 'master'
1689 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001690 return cl
1691
Edward Lemurd55c5072020-02-20 01:09:07 +00001692 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001693 def test_gerrit_ensure_authenticated_missing(self):
1694 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001695 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001696 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001697 with self.assertRaises(SystemExitMock):
1698 cl.EnsureAuthenticated(force=False)
1699 self.assertEqual(
1700 'Credentials for the following hosts are required:\n'
1701 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001702 'These are read from ~%(sep)s.gitcookies '
1703 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001704 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001705 'https://chromium-review.googlesource.com/new-password\n' % {
1706 'sep': os.sep,
1707 'netrc': NETRC_FILENAME,
1708 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001709
1710 def test_gerrit_ensure_authenticated_conflict(self):
1711 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001712 'chromium.googlesource.com':
1713 ('git-one.example.com', None, 'secret1'),
1714 'chromium-review.googlesource.com':
1715 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001716 })
1717 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001718 (('ask_for_data', 'If you know what you are doing '
1719 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001720 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1721
1722 def test_gerrit_ensure_authenticated_ok(self):
1723 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001724 'chromium.googlesource.com':
1725 ('git-same.example.com', None, 'secret'),
1726 'chromium-review.googlesource.com':
1727 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001728 })
1729 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1730
tandrii@chromium.org28253532016-04-14 13:46:56 +00001731 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001732 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1733 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001734 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1735
Eric Boren2fb63102018-10-05 13:05:03 +00001736 def test_gerrit_ensure_authenticated_bearer_token(self):
1737 cl = self._test_gerrit_ensure_authenticated_common(auth={
1738 'chromium.googlesource.com':
1739 ('', None, 'secret'),
1740 'chromium-review.googlesource.com':
1741 ('', None, 'secret'),
1742 })
1743 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1744 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1745 'chromium.googlesource.com')
1746 self.assertTrue('Bearer' in header)
1747
Daniel Chengcf6269b2019-05-18 01:02:12 +00001748 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001749 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001750 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001751 (('logging.warning',
1752 'Ignoring branch %(branch)s with non-https remote '
1753 '%(remote)s', {
1754 'branch': 'master',
1755 'remote': 'custom-scheme://repo'}
1756 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001757 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001758 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1759 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1760 mock.patch('logging.warning',
1761 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001762 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001763 cl.branch = 'master'
1764 cl.branchref = 'refs/heads/master'
1765 cl.lookedup_issue = True
1766 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1767
Florian Mayerae510e82020-01-30 21:04:48 +00001768 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001769 self.mockGit.config['remote.origin.url'] = (
1770 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001771 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001772 (('logging.error',
1773 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1774 'but it doesn\'t exist.', {
1775 'remote': 'origin',
1776 'branch': 'master',
1777 'url': 'git@somehost.example:foo/bar.git'}
1778 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001779 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001780 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1781 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1782 mock.patch('logging.error',
1783 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001784 cl = git_cl.Changelist()
1785 cl.branch = 'master'
1786 cl.branchref = 'refs/heads/master'
1787 cl.lookedup_issue = True
1788 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1789
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001790 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001791 self.mockGit.config['branch.master.gerritissue'] = '123'
1792 self.mockGit.config['branch.master.gerritserver'] = (
1793 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001794 self.mockGit.config['remote.origin.url'] = (
1795 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001796 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001797 (('SetReview', 'chromium-review.googlesource.com',
1798 'infra%2Finfra~123', None,
1799 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001800 ]
tandriid9e5ce52016-07-13 02:32:59 -07001801
1802 def test_cmd_set_commit_gerrit_clear(self):
1803 self._cmd_set_commit_gerrit_common(0)
1804 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1805
1806 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001807 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001808 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1809
tandriid9e5ce52016-07-13 02:32:59 -07001810 def test_cmd_set_commit_gerrit(self):
1811 self._cmd_set_commit_gerrit_common(2)
1812 self.assertEqual(0, git_cl.main(['set-commit']))
1813
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001814 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001815 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001816 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001817
1818 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001819 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001820
Edward Lemurda4b6c62020-02-13 00:28:40 +00001821 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001822 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001823 try:
1824 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001825 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001826 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001827 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001828
1829 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001830 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001831 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001832 return 'foobar'
1833
Edward Lemurda4b6c62020-02-13 00:28:40 +00001834 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001835 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001836 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001837 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001838 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001839
iannuccie53c9352016-08-17 14:40:40 -07001840 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001841
iannuccie53c9352016-08-17 14:40:40 -07001842 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001843 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001844 return 'foobar'
1845
Edward Lemurda4b6c62020-02-13 00:28:40 +00001846 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
1847 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07001848 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001849 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07001850
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001851 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00001852 self.mockGit.config['remote.origin.url'] = (
1853 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001854 gerrit_util.GetChangeDetail.return_value = {
1855 'current_revision': 'sha1',
1856 'revisions': {'sha1': {
1857 'commit': {'message': 'foobar'},
1858 }},
1859 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001860 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001861 'description',
1862 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
1863 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001864 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001865
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001866 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001867 mock.patch('git_cl.Changelist', ChangelistMock).start()
1868 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001869
1870 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1871 self.assertEqual('hihi', ChangelistMock.desc)
1872
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001873 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001874 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001875
1876 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001877 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001878 '# Enter a description of the change.\n'
1879 '# This will be displayed on the codereview site.\n'
1880 '# The first line will also be used as the subject of the review.\n'
1881 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001882 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07001883 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001884 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001885 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07001886 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001887
Edward Lemur6c6827c2020-02-06 21:15:18 +00001888 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001889 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001890
Edward Lemurda4b6c62020-02-13 00:28:40 +00001891 mock.patch('git_cl.Changelist.FetchDescription',
1892 lambda *args: current_desc).start()
1893 mock.patch('git_cl.Changelist.UpdateDescription',
1894 UpdateDescription).start()
1895 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001896
Edward Lemur85153282020-02-14 22:06:29 +00001897 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001898 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001899
Dan Beamd8b04ca2019-10-10 21:23:26 +00001900 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
1901 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
1902
1903 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001904 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00001905 '# Enter a description of the change.\n'
1906 '# This will be displayed on the codereview site.\n'
1907 '# The first line will also be used as the subject of the review.\n'
1908 '#--------------------This line is 72 characters long'
1909 '--------------------\n'
1910 'Some.\n\nFixed: 123\nChange-Id: xxx',
1911 desc)
1912 return desc
1913
Edward Lemurda4b6c62020-02-13 00:28:40 +00001914 mock.patch('git_cl.Changelist.FetchDescription',
1915 lambda *args: current_desc).start()
1916 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00001917
Edward Lemur85153282020-02-14 22:06:29 +00001918 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001919 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00001920
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001921 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001922 mock.patch('git_cl.Changelist', ChangelistMock).start()
1923 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001924
1925 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1926 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1927
kmarshall3bff56b2016-06-06 18:31:47 -07001928 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001929 self.calls = [
1930 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00001931 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001932 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001933 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00001934 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001935 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001936
Edward Lemurda4b6c62020-02-13 00:28:40 +00001937 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001938 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001939 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1940 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001941 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001942
1943 self.assertEqual(0, git_cl.main(['archive', '-f']))
1944
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001945 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001946 self.calls = [
1947 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1948 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1949 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
1950 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001951 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
1952 ((['git', 'branch', '-D', 'foo'],), '')
1953 ]
1954
Edward Lemurda4b6c62020-02-13 00:28:40 +00001955 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001956 lambda branches, fine_grained, max_processes:
1957 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1958 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001959 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001960
1961 self.assertEqual(0, git_cl.main(['archive', '-f']))
1962
kmarshall3bff56b2016-06-06 18:31:47 -07001963 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001964 self.calls = [
1965 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1966 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001967 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001968 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001969
Edward Lemurda4b6c62020-02-13 00:28:40 +00001970 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001971 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00001972 [(MockChangelistWithBranchAndIssue('master', 1),
1973 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001974
1975 self.assertEqual(1, git_cl.main(['archive', '-f']))
1976
1977 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001978 self.calls = [
1979 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1980 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001981 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001982 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001983
Edward Lemurda4b6c62020-02-13 00:28:40 +00001984 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001985 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001986 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1987 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001988 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001989
kmarshall9249e012016-08-23 12:02:16 -07001990 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
1991
1992 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001993 self.calls = [
1994 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1995 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001996 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001997 ((['git', 'branch', '-D', 'foo'],), '')
1998 ]
kmarshall9249e012016-08-23 12:02:16 -07001999
Edward Lemurda4b6c62020-02-13 00:28:40 +00002000 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002001 lambda branches, fine_grained, max_processes:
2002 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2003 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002004 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002005
2006 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002007
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002008 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002009 self.calls = [
2010 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2011 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2012 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002013 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2014 'refs/tags/git-cl-archived-456-foo'),
2015 ((['git', 'branch', '-D', 'foo'],), CERR1),
2016 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2017 'refs/tags/git-cl-archived-456-foo'),
2018 ]
2019
Edward Lemurda4b6c62020-02-13 00:28:40 +00002020 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002021 lambda branches, fine_grained, max_processes:
2022 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2023 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002024 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002025
2026 self.assertEqual(0, git_cl.main(['archive', '-f']))
2027
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002028 def test_archive_with_format(self):
2029 self.calls = [
2030 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
2031 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2032 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2033 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2034 ((['git', 'branch', '-D', 'foo'], ), ''),
2035 ]
2036
2037 mock.patch('git_cl.get_cl_statuses',
2038 lambda branches, fine_grained, max_processes:
2039 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2040
2041 self.assertEqual(
2042 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2043
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002044 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002045 self.mockGit.config['branch.master.gerritissue'] = '123'
2046 self.mockGit.config['branch.master.gerritserver'] = (
2047 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002048 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002049 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002050 ]
2051 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002052 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2053 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002054
Aaron Gable400e9892017-07-12 15:31:21 -07002055 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002056 self.mockGit.config['branch.master.gerritissue'] = '123'
2057 self.mockGit.config['branch.master.gerritserver'] = (
2058 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002059 mock.patch('git_cl.Changelist.FetchDescription',
2060 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002061 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002062 ((['git', 'log', '-1', '--format=%B'],),
2063 'This is a description\n\nChange-Id: Ideadbeef'),
2064 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002065 ]
2066 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002067 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2068 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002069
phajdan.jre328cf92016-08-22 04:12:17 -07002070 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002071 self.mockGit.config['branch.master.gerritissue'] = '123'
2072 self.mockGit.config['branch.master.gerritserver'] = (
2073 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002074 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002075 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002076 {'issue': 123,
2077 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002078 ''),
2079 ]
2080 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2081
tandrii16e0b4e2016-06-07 10:34:28 -07002082 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002083 mock.patch(
2084 'git_cl.os.path.abspath',
2085 lambda path: self._mocked_call(['abspath', path])).start()
2086 mock.patch(
2087 'git_cl.os.path.exists',
2088 lambda path: self._mocked_call(['exists', path])).start()
2089 mock.patch(
2090 'git_cl.gclient_utils.FileRead',
2091 lambda path: self._mocked_call(['FileRead', path])).start()
2092 mock.patch(
2093 'git_cl.gclient_utils.rm_file_or_tree',
2094 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002095 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002096 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002097 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002098 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002099
2100 def test_GerritCommitMsgHookCheck_custom_hook(self):
2101 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002102 self.calls += [((['exists',
2103 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2104 ((['FileRead',
2105 os.path.join('.git', 'hooks', 'commit-msg')], ),
2106 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002107 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002108
2109 def test_GerritCommitMsgHookCheck_not_exists(self):
2110 cl = self._common_GerritCommitMsgHookCheck()
2111 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002112 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002113 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002114 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002115
2116 def test_GerritCommitMsgHookCheck(self):
2117 cl = self._common_GerritCommitMsgHookCheck()
2118 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002119 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2120 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002121 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002122 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002123 ((['rm_file_or_tree',
2124 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002125 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002126 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002127
tandriic4344b52016-08-29 06:04:54 -07002128 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002129 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2130 self.mockGit.config['branch.master.gerritserver'] = (
2131 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002132 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002133 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002134 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002135 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002136 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002137 'labels': {},
2138 'current_revision': 'deadbeaf',
2139 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002140 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002141 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002142 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002143 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2144 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002145 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002146 self.assertEqual(0, cl.CMDLand(force=True,
2147 bypass_hooks=True,
2148 verbose=True,
2149 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002150 self.assertIn(
2151 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002152 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002153 self.assertIn(
2154 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002155 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002156
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002157 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002158 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002159
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002160 def test_gerrit_change_detail_cache_simple(self):
2161 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002162 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002163 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002164 cl1._cached_remote_url = (
2165 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002166 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002167 cl2._cached_remote_url = (
2168 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002169 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2170 self.assertEqual(cl1._GetChangeDetail(), 'a')
2171 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002172
2173 def test_gerrit_change_detail_cache_options(self):
2174 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002175 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002176 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002177 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002178 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2179 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2180 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2181 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2182 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2183 self.assertEqual(cl._GetChangeDetail(), 'cab')
2184
2185 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2186 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2187 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2188 self.assertEqual(cl._GetChangeDetail(), 'cab')
2189
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002190 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002191 gerrit_util.GetChangeDetail.return_value = {
2192 'current_revision': 'rev1',
2193 'revisions': {
2194 'rev1': {'commit': {'message': 'desc1'}},
2195 },
2196 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002197
2198 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002199 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002200 cl._cached_remote_url = (
2201 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002202 self.assertEqual(cl.FetchDescription(), 'desc1')
2203 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002204
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002205 def test_print_current_creds(self):
2206 class CookiesAuthenticatorMock(object):
2207 def __init__(self):
2208 self.gitcookies = {
2209 'host.googlesource.com': ('user', 'pass'),
2210 'host-review.googlesource.com': ('user', 'pass'),
2211 }
2212 self.netrc = self
2213 self.netrc.hosts = {
2214 'github.com': ('user2', None, 'pass2'),
2215 'host2.googlesource.com': ('user3', None, 'pass'),
2216 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002217 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2218 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002219 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2220 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2221 ' Host\t User\t Which file',
2222 '============================\t=====\t===========',
2223 'host-review.googlesource.com\t user\t.gitcookies',
2224 ' host.googlesource.com\t user\t.gitcookies',
2225 ' host2.googlesource.com\tuser3\t .netrc',
2226 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002227 sys.stdout.seek(0)
2228 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002229 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2230 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2231 ' Host\tUser\t Which file',
2232 '============================\t====\t===========',
2233 'host-review.googlesource.com\tuser\t.gitcookies',
2234 ' host.googlesource.com\tuser\t.gitcookies',
2235 ])
2236
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002237 def _common_creds_check_mocks(self):
2238 def exists_mock(path):
2239 dirname = os.path.dirname(path)
2240 if dirname == os.path.expanduser('~'):
2241 dirname = '~'
2242 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002243 if base in (NETRC_FILENAME, '.gitcookies'):
2244 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002245 # git cl also checks for existence other files not relevant to this test.
2246 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002247 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002248 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002249 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002250 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002251
2252 def test_creds_check_gitcookies_not_configured(self):
2253 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002254 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2255 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002256 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002257 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2258 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2259 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2260 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2261 'or Ctrl+C to abort'), ''),
2262 (([
2263 'git', 'config', '--global', 'http.cookiefile',
2264 os.path.expanduser(os.path.join('~', '.gitcookies'))
2265 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002266 ]
2267 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002268 self.assertTrue(
2269 sys.stdout.getvalue().startswith(
2270 'You seem to be using outdated .netrc for git credentials:'))
2271 self.assertIn(
2272 '\nConfigured git to use .gitcookies from',
2273 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002274
2275 def test_creds_check_gitcookies_configured_custom_broken(self):
2276 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002277 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2278 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002279 custom_cookie_path = ('C:\\.gitcookies'
2280 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002281 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002282 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2283 ((['git', 'config', '--global', 'http.cookiefile'], ),
2284 custom_cookie_path),
2285 (('os.path.exists', custom_cookie_path), False),
2286 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2287 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2288 (([
2289 'git', 'config', '--global', 'http.cookiefile',
2290 os.path.expanduser(os.path.join('~', '.gitcookies'))
2291 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002292 ]
2293 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002294 self.assertIn(
2295 'WARNING: You have configured custom path to .gitcookies: ',
2296 sys.stdout.getvalue())
2297 self.assertIn(
2298 'However, your configured .gitcookies file is missing.',
2299 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002300
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002301 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002302 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002303 self.mockGit.config['remote.origin.url'] = (
2304 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002305 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002306 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002307 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002308 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002309 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002310 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002311
Edward Lemurda4b6c62020-02-13 00:28:40 +00002312 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2313 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002314 self.mockGit.config['remote.origin.url'] = (
2315 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002316 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002317 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002318 'current_revision': 'ba5eba11',
2319 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002320 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002321 '_number': 1,
2322 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002323 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002324 '_number': 2,
2325 },
2326 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002327 'messages': [
2328 {
2329 u'_revision_number': 1,
2330 u'author': {
2331 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002332 u'email': u'could-be-anything@example.com',
2333 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002334 },
2335 u'date': u'2017-03-15 20:08:45.000000000',
2336 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002337 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002338 u'tag': u'autogenerated:cq:dry-run'
2339 },
2340 {
2341 u'_revision_number': 2,
2342 u'author': {
2343 u'_account_id': 11151243,
2344 u'email': u'owner@example.com',
2345 u'name': u'owner'
2346 },
2347 u'date': u'2017-03-16 20:00:41.000000000',
2348 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2349 u'message': u'PTAL',
2350 },
2351 {
2352 u'_revision_number': 2,
2353 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002354 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002355 u'email': u'reviewer@example.com',
2356 u'name': u'reviewer'
2357 },
2358 u'date': u'2017-03-17 05:19:37.500000000',
2359 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2360 u'message': u'Patch Set 2: Code-Review+1',
2361 },
2362 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002363 }
2364 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002365 (('GetChangeComments', 'chromium-review.googlesource.com',
2366 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002367 '/COMMIT_MSG': [
2368 {
2369 'author': {'email': u'reviewer@example.com'},
2370 'updated': u'2017-03-17 05:19:37.500000000',
2371 'patch_set': 2,
2372 'side': 'REVISION',
2373 'message': 'Please include a bug link',
2374 },
2375 ],
2376 'codereview.settings': [
2377 {
2378 'author': {'email': u'owner@example.com'},
2379 'updated': u'2017-03-16 20:00:41.000000000',
2380 'patch_set': 2,
2381 'side': 'PARENT',
2382 'line': 42,
2383 'message': 'I removed this because it is bad',
2384 },
2385 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002386 }),
2387 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2388 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002389 ] * 2 + [
2390 (('write_json', 'output.json', [
2391 {
2392 u'date': u'2017-03-16 20:00:41.000000',
2393 u'message': (
2394 u'PTAL\n' +
2395 u'\n' +
2396 u'codereview.settings\n' +
2397 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2398 u'c/1/2/codereview.settings#b42\n' +
2399 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002400 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002401 u'approval': False,
2402 u'disapproval': False,
2403 u'sender': u'owner@example.com'
2404 }, {
2405 u'date': u'2017-03-17 05:19:37.500000',
2406 u'message': (
2407 u'Patch Set 2: Code-Review+1\n' +
2408 u'\n' +
2409 u'/COMMIT_MSG\n' +
2410 u' PS2, File comment: https://chromium-review.googlesource' +
2411 u'.com/c/1/2//COMMIT_MSG#\n' +
2412 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002413 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002414 u'approval': False,
2415 u'disapproval': False,
2416 u'sender': u'reviewer@example.com'
2417 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002418 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002419 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002420 expected_comments_summary = [
2421 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002422 message=(
2423 u'PTAL\n' +
2424 u'\n' +
2425 u'codereview.settings\n' +
2426 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2427 u'c/1/2/codereview.settings#b42\n' +
2428 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002429 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002430 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002431 disapproval=False, approval=False, sender=u'owner@example.com'),
2432 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002433 message=(
2434 u'Patch Set 2: Code-Review+1\n' +
2435 u'\n' +
2436 u'/COMMIT_MSG\n' +
2437 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2438 u'c/1/2//COMMIT_MSG#\n' +
2439 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002440 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002441 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002442 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2443 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002444 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002445 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002446 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002447 self.assertEqual(
2448 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2449
2450 def test_git_cl_comments_robot_comments(self):
2451 # git cl comments also fetches robot comments (which are considered a type
2452 # of autogenerated comment), and unlike other types of comments, only robot
2453 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002454 self.mockGit.config['remote.origin.url'] = (
2455 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002456 gerrit_util.GetChangeDetail.return_value = {
2457 'owner': {'email': 'owner@example.com'},
2458 'current_revision': 'ba5eba11',
2459 'revisions': {
2460 'deadbeaf': {
2461 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002462 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002463 'ba5eba11': {
2464 '_number': 2,
2465 },
2466 },
2467 'messages': [
2468 {
2469 u'_revision_number': 1,
2470 u'author': {
2471 u'_account_id': 1111084,
2472 u'email': u'commit-bot@chromium.org',
2473 u'name': u'Commit Bot'
2474 },
2475 u'date': u'2017-03-15 20:08:45.000000000',
2476 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2477 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2478 u'tag': u'autogenerated:cq:dry-run'
2479 },
2480 {
2481 u'_revision_number': 1,
2482 u'author': {
2483 u'_account_id': 123,
2484 u'email': u'tricium@serviceaccount.com',
2485 u'name': u'Tricium'
2486 },
2487 u'date': u'2017-03-16 20:00:41.000000000',
2488 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2489 u'message': u'(1 comment)',
2490 u'tag': u'autogenerated:tricium',
2491 },
2492 {
2493 u'_revision_number': 1,
2494 u'author': {
2495 u'_account_id': 123,
2496 u'email': u'tricium@serviceaccount.com',
2497 u'name': u'Tricium'
2498 },
2499 u'date': u'2017-03-16 20:00:41.000000000',
2500 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2501 u'message': u'(1 comment)',
2502 u'tag': u'autogenerated:tricium',
2503 },
2504 {
2505 u'_revision_number': 2,
2506 u'author': {
2507 u'_account_id': 123,
2508 u'email': u'tricium@serviceaccount.com',
2509 u'name': u'reviewer'
2510 },
2511 u'date': u'2017-03-17 05:30:37.000000000',
2512 u'tag': u'autogenerated:tricium',
2513 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2514 u'message': u'(1 comment)',
2515 },
2516 ]
2517 }
2518 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002519 (('GetChangeComments', 'chromium-review.googlesource.com',
2520 'infra%2Finfra~1'), {}),
2521 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2522 'infra%2Finfra~1'), {
2523 'codereview.settings': [
2524 {
2525 u'author': {u'email': u'tricium@serviceaccount.com'},
2526 u'updated': u'2017-03-17 05:30:37.000000000',
2527 u'robot_run_id': u'5565031076855808',
2528 u'robot_id': u'Linter/Category',
2529 u'tag': u'autogenerated:tricium',
2530 u'patch_set': 2,
2531 u'side': u'REVISION',
2532 u'message': u'Linter warning message text',
2533 u'line': 32,
2534 },
2535 ],
2536 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002537 ]
2538 expected_comments_summary = [
2539 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2540 message=(
2541 u'(1 comment)\n\ncodereview.settings\n'
2542 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2543 u'c/1/2/codereview.settings#32\n'
2544 u' Linter warning message text\n'),
2545 sender=u'tricium@serviceaccount.com',
2546 autogenerated=True, approval=False, disapproval=False)
2547 ]
2548 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002549 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002550 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002551
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002552 def test_get_remote_url_with_mirror(self):
2553 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002554
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002555 def selective_os_path_isdir_mock(path):
2556 if path == '/cache/this-dir-exists':
2557 return self._mocked_call('os.path.isdir', path)
2558 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002559
Edward Lemurda4b6c62020-02-13 00:28:40 +00002560 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002561
2562 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002563 self.mockGit.config['remote.origin.url'] = (
2564 '/cache/this-dir-exists')
2565 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2566 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002567 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002568 (('os.path.isdir', '/cache/this-dir-exists'),
2569 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002570 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002571 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002572 self.assertEqual(cl.GetRemoteUrl(), url)
2573 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2574
Edward Lemur298f2cf2019-02-22 21:40:39 +00002575 def test_get_remote_url_non_existing_mirror(self):
2576 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002577
Edward Lemur298f2cf2019-02-22 21:40:39 +00002578 def selective_os_path_isdir_mock(path):
2579 if path == '/cache/this-dir-doesnt-exist':
2580 return self._mocked_call('os.path.isdir', path)
2581 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002582
Edward Lemurda4b6c62020-02-13 00:28:40 +00002583 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2584 mock.patch('logging.error',
2585 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002586
Edward Lemur26964072020-02-19 19:18:51 +00002587 self.mockGit.config['remote.origin.url'] = (
2588 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002589 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002590 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2591 False),
2592 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002593 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2594 'but it doesn\'t exist.', {
2595 'remote': 'origin',
2596 'branch': 'master',
2597 'url': '/cache/this-dir-doesnt-exist'}
2598 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002599 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002600 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002601 self.assertIsNone(cl.GetRemoteUrl())
2602
2603 def test_get_remote_url_misconfigured_mirror(self):
2604 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002605
Edward Lemur298f2cf2019-02-22 21:40:39 +00002606 def selective_os_path_isdir_mock(path):
2607 if path == '/cache/this-dir-exists':
2608 return self._mocked_call('os.path.isdir', path)
2609 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002610
Edward Lemurda4b6c62020-02-13 00:28:40 +00002611 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2612 mock.patch('logging.error',
2613 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002614
Edward Lemur26964072020-02-19 19:18:51 +00002615 self.mockGit.config['remote.origin.url'] = (
2616 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002617 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002618 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002619 (('logging.error',
2620 'Remote "%(remote)s" for branch "%(branch)s" points to '
2621 '"%(cache_path)s", but it is misconfigured.\n'
2622 '"%(cache_path)s" must be a git repo and must have a remote named '
2623 '"%(remote)s" pointing to the git host.', {
2624 'remote': 'origin',
2625 'cache_path': '/cache/this-dir-exists',
2626 'branch': 'master'}
2627 ), None),
2628 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002629 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002630 self.assertIsNone(cl.GetRemoteUrl())
2631
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002632 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002633 self.mockGit.config['remote.origin.url'] = (
2634 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002635 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002636 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2637
2638 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002639 mock.patch('logging.error',
2640 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002641
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002642 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002643 (('logging.error',
2644 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2645 'but it doesn\'t exist.', {
2646 'remote': 'origin',
2647 'branch': 'master',
2648 'url': ''}
2649 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002650 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002651 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002652 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002653
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002654
Edward Lemur9aa1a962020-02-25 00:58:38 +00002655class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002656 def setUp(self):
2657 super(ChangelistTest, self).setUp()
2658 mock.patch('gclient_utils.FileRead').start()
2659 mock.patch('gclient_utils.FileWrite').start()
2660 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2661 mock.patch(
2662 'git_cl.Changelist.GetCodereviewServer',
2663 return_value='https://chromium-review.googlesource.com').start()
2664 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2665 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2666 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2667 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2668 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2669 mock.patch('git_cl.time_time').start()
2670 mock.patch('metrics.collector').start()
2671 mock.patch('subprocess2.Popen').start()
2672 self.addCleanup(mock.patch.stopall)
2673 self.temp_count = 0
2674
Edward Lemur227d5102020-02-25 23:45:35 +00002675 def testRunHook(self):
2676 expected_results = {
2677 'more_cc': ['more@example.com', 'cc@example.com'],
2678 'should_continue': True,
2679 }
2680 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2681 git_cl.time_time.side_effect = [100, 200]
2682 mockProcess = mock.Mock()
2683 mockProcess.wait.return_value = 0
2684 subprocess2.Popen.return_value = mockProcess
2685
2686 cl = git_cl.Changelist()
2687 results = cl.RunHook(
2688 committing=True,
2689 may_prompt=True,
2690 verbose=2,
2691 parallel=True,
2692 upstream='upstream',
2693 description='description',
2694 all_files=True)
2695
2696 self.assertEqual(expected_results, results)
2697 subprocess2.Popen.assert_called_once_with([
2698 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002699 '--root', 'root',
2700 '--upstream', 'upstream',
2701 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002702 '--author', 'author',
2703 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002704 '--issue', '123456',
2705 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002706 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002707 '--may_prompt',
2708 '--parallel',
2709 '--all_files',
2710 '--json_output', '/tmp/fake-temp2',
2711 '--description_file', '/tmp/fake-temp1',
2712 ])
2713 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002714 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002715 metrics.collector.add_repeated('sub_commands', {
2716 'command': 'presubmit',
2717 'execution_time': 100,
2718 'exit_code': 0,
2719 })
2720
Edward Lemur99df04e2020-03-05 19:39:43 +00002721 def testRunHook_FewerOptions(self):
2722 expected_results = {
2723 'more_cc': ['more@example.com', 'cc@example.com'],
2724 'should_continue': True,
2725 }
2726 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2727 git_cl.time_time.side_effect = [100, 200]
2728 mockProcess = mock.Mock()
2729 mockProcess.wait.return_value = 0
2730 subprocess2.Popen.return_value = mockProcess
2731
2732 git_cl.Changelist.GetAuthor.return_value = None
2733 git_cl.Changelist.GetIssue.return_value = None
2734 git_cl.Changelist.GetPatchset.return_value = None
2735 git_cl.Changelist.GetCodereviewServer.return_value = None
2736
2737 cl = git_cl.Changelist()
2738 results = cl.RunHook(
2739 committing=False,
2740 may_prompt=False,
2741 verbose=0,
2742 parallel=False,
2743 upstream='upstream',
2744 description='description',
2745 all_files=False)
2746
2747 self.assertEqual(expected_results, results)
2748 subprocess2.Popen.assert_called_once_with([
2749 'vpython', 'PRESUBMIT_SUPPORT',
2750 '--root', 'root',
2751 '--upstream', 'upstream',
2752 '--upload',
2753 '--json_output', '/tmp/fake-temp2',
2754 '--description_file', '/tmp/fake-temp1',
2755 ])
2756 gclient_utils.FileWrite.assert_called_once_with(
2757 '/tmp/fake-temp1', 'description')
2758 metrics.collector.add_repeated('sub_commands', {
2759 'command': 'presubmit',
2760 'execution_time': 100,
2761 'exit_code': 0,
2762 })
2763
Edward Lemur227d5102020-02-25 23:45:35 +00002764 @mock.patch('sys.exit', side_effect=SystemExitMock)
2765 def testRunHook_Failure(self, _mock):
2766 git_cl.time_time.side_effect = [100, 200]
2767 mockProcess = mock.Mock()
2768 mockProcess.wait.return_value = 2
2769 subprocess2.Popen.return_value = mockProcess
2770
2771 cl = git_cl.Changelist()
2772 with self.assertRaises(SystemExitMock):
2773 cl.RunHook(
2774 committing=True,
2775 may_prompt=True,
2776 verbose=2,
2777 parallel=True,
2778 upstream='upstream',
2779 description='description',
2780 all_files=True)
2781
2782 sys.exit.assert_called_once_with(2)
2783
Edward Lemur75526302020-02-27 22:31:05 +00002784 def testRunPostUploadHook(self):
2785 cl = git_cl.Changelist()
2786 cl.RunPostUploadHook(2, 'upstream', 'description')
2787
2788 subprocess2.Popen.assert_called_once_with([
2789 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002790 '--root', 'root',
2791 '--upstream', 'upstream',
2792 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002793 '--author', 'author',
2794 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002795 '--issue', '123456',
2796 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002797 '--post_upload',
2798 '--description_file', '/tmp/fake-temp1',
2799 ])
2800 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002801 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002802
Edward Lemur9aa1a962020-02-25 00:58:38 +00002803
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002804class CMDTestCaseBase(unittest.TestCase):
2805 _STATUSES = [
2806 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2807 'INFRA_FAILURE', 'CANCELED',
2808 ]
2809 _CHANGE_DETAIL = {
2810 'project': 'depot_tools',
2811 'status': 'OPEN',
2812 'owner': {'email': 'owner@e.mail'},
2813 'current_revision': 'beeeeeef',
2814 'revisions': {
2815 'deadbeaf': {'_number': 6},
2816 'beeeeeef': {
2817 '_number': 7,
2818 'fetch': {'http': {
2819 'url': 'https://chromium.googlesource.com/depot_tools',
2820 'ref': 'refs/changes/56/123456/7'
2821 }},
2822 },
2823 },
2824 }
2825 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002826 'builds': [{
2827 'id': str(100 + idx),
2828 'builder': {
2829 'project': 'chromium',
2830 'bucket': 'try',
2831 'builder': 'bot_' + status.lower(),
2832 },
2833 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2834 'tags': [],
2835 'status': status,
2836 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002837 }
2838
Edward Lemur4c707a22019-09-24 21:13:43 +00002839 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002840 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002841 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002842 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2843 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002844 mock.patch(
2845 'git_cl.Changelist.GetCodereviewServer',
2846 return_value='https://chromium-review.googlesource.com').start()
2847 mock.patch(
2848 'git_cl.Changelist._GetGerritHost',
2849 return_value='chromium-review.googlesource.com').start()
2850 mock.patch(
2851 'git_cl.Changelist.GetMostRecentPatchset',
2852 return_value=7).start()
2853 mock.patch(
2854 'git_cl.Changelist.GetRemoteUrl',
2855 return_value='https://chromium.googlesource.com/depot_tools').start()
2856 mock.patch(
2857 'auth.Authenticator',
2858 return_value=AuthenticatorMock()).start()
2859 mock.patch(
2860 'gerrit_util.GetChangeDetail',
2861 return_value=self._CHANGE_DETAIL).start()
2862 mock.patch(
2863 'git_cl._call_buildbucket',
2864 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002865 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002866 self.addCleanup(mock.patch.stopall)
2867
Edward Lemur4c707a22019-09-24 21:13:43 +00002868
Edward Lemur9468eba2020-02-27 19:07:22 +00002869class CMDPresubmitTestCase(CMDTestCaseBase):
2870 def setUp(self):
2871 super(CMDPresubmitTestCase, self).setUp()
2872 mock.patch(
2873 'git_cl.Changelist.GetCommonAncestorWithUpstream',
2874 return_value='upstream').start()
2875 mock.patch(
2876 'git_cl.Changelist.FetchDescription',
2877 return_value='fetch description').start()
2878 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00002879 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00002880 return_value='get description').start()
2881 mock.patch('git_cl.Changelist.RunHook').start()
2882
2883 def testDefaultCase(self):
2884 self.assertEqual(0, git_cl.main(['presubmit']))
2885 git_cl.Changelist.RunHook.assert_called_once_with(
2886 committing=True,
2887 may_prompt=False,
2888 verbose=0,
2889 parallel=None,
2890 upstream='upstream',
2891 description='fetch description',
2892 all_files=None)
2893
2894 def testNoIssue(self):
2895 git_cl.Changelist.GetIssue.return_value = None
2896 self.assertEqual(0, git_cl.main(['presubmit']))
2897 git_cl.Changelist.RunHook.assert_called_once_with(
2898 committing=True,
2899 may_prompt=False,
2900 verbose=0,
2901 parallel=None,
2902 upstream='upstream',
2903 description='get description',
2904 all_files=None)
2905
2906 def testCustomBranch(self):
2907 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
2908 git_cl.Changelist.RunHook.assert_called_once_with(
2909 committing=True,
2910 may_prompt=False,
2911 verbose=0,
2912 parallel=None,
2913 upstream='custom_branch',
2914 description='fetch description',
2915 all_files=None)
2916
2917 def testOptions(self):
2918 self.assertEqual(
2919 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
2920 git_cl.Changelist.RunHook.assert_called_once_with(
2921 committing=False,
2922 may_prompt=False,
2923 verbose=2,
2924 parallel=True,
2925 upstream='upstream',
2926 description='fetch description',
2927 all_files=True)
2928
2929
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002930class CMDTryResultsTestCase(CMDTestCaseBase):
2931 _DEFAULT_REQUEST = {
2932 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002933 "gerritChanges": [{
2934 "project": "depot_tools",
2935 "host": "chromium-review.googlesource.com",
2936 "patchset": 7,
2937 "change": 123456,
2938 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002939 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002940 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2941 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002942 }
2943
2944 def testNoJobs(self):
2945 git_cl._call_buildbucket.return_value = {}
2946
2947 self.assertEqual(0, git_cl.main(['try-results']))
2948 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2949 git_cl._call_buildbucket.assert_called_once_with(
2950 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2951 self._DEFAULT_REQUEST)
2952
2953 def testPrintToStdout(self):
2954 self.assertEqual(0, git_cl.main(['try-results']))
2955 self.assertEqual([
2956 'Successes:',
2957 ' bot_success https://ci.chromium.org/b/103',
2958 'Infra Failures:',
2959 ' bot_infra_failure https://ci.chromium.org/b/105',
2960 'Failures:',
2961 ' bot_failure https://ci.chromium.org/b/104',
2962 'Canceled:',
2963 ' bot_canceled ',
2964 'Started:',
2965 ' bot_started https://ci.chromium.org/b/102',
2966 'Scheduled:',
2967 ' bot_scheduled id=101',
2968 'Other:',
2969 ' bot_status_unspecified id=100',
2970 'Total: 7 tryjobs',
2971 ], sys.stdout.getvalue().splitlines())
2972 git_cl._call_buildbucket.assert_called_once_with(
2973 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2974 self._DEFAULT_REQUEST)
2975
2976 def testPrintToStdoutWithMasters(self):
2977 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2978 self.assertEqual([
2979 'Successes:',
2980 ' try bot_success https://ci.chromium.org/b/103',
2981 'Infra Failures:',
2982 ' try bot_infra_failure https://ci.chromium.org/b/105',
2983 'Failures:',
2984 ' try bot_failure https://ci.chromium.org/b/104',
2985 'Canceled:',
2986 ' try bot_canceled ',
2987 'Started:',
2988 ' try bot_started https://ci.chromium.org/b/102',
2989 'Scheduled:',
2990 ' try bot_scheduled id=101',
2991 'Other:',
2992 ' try bot_status_unspecified id=100',
2993 'Total: 7 tryjobs',
2994 ], sys.stdout.getvalue().splitlines())
2995 git_cl._call_buildbucket.assert_called_once_with(
2996 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2997 self._DEFAULT_REQUEST)
2998
2999 @mock.patch('git_cl.write_json')
3000 def testWriteToJson(self, mockJsonDump):
3001 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3002 git_cl._call_buildbucket.assert_called_once_with(
3003 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3004 self._DEFAULT_REQUEST)
3005 mockJsonDump.assert_called_once_with(
3006 'file.json', self._DEFAULT_RESPONSE['builds'])
3007
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003008 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003009 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3010 self.assertEqual(
3011 [
3012 ('chromium', 'try', 'bot_failure'),
3013 ('chromium', 'try', 'bot_infra_failure'),
3014 ],
3015 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003016
3017 def test_filter_failed_for_retry_many_builds(self):
3018
3019 def _build(name, created_sec, status, experimental=False):
3020 assert 0 <= created_sec < 100, created_sec
3021 b = {
3022 'id': 112112,
3023 'builder': {
3024 'project': 'chromium',
3025 'bucket': 'try',
3026 'builder': name,
3027 },
3028 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3029 'status': status,
3030 'tags': [],
3031 }
3032 if experimental:
3033 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3034 return b
3035
3036 builds = [
3037 _build('flaky-last-green', 1, 'FAILURE'),
3038 _build('flaky-last-green', 2, 'SUCCESS'),
3039 _build('flaky', 1, 'SUCCESS'),
3040 _build('flaky', 2, 'FAILURE'),
3041 _build('running', 1, 'FAILED'),
3042 _build('running', 2, 'SCHEDULED'),
3043 _build('yep-still-running', 1, 'STARTED'),
3044 _build('yep-still-running', 2, 'FAILURE'),
3045 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3046 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3047
3048 # Simulate experimental in CQ builder, which developer decided
3049 # to retry manually which resulted in 2nd build non-experimental.
3050 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3051 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3052 ]
3053 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003054 self.assertEqual(
3055 [
3056 ('chromium', 'try', 'flaky'),
3057 ('chromium', 'try', 'sometimes-experimental'),
3058 ],
3059 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003060
3061
3062class CMDTryTestCase(CMDTestCaseBase):
3063
3064 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003065 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003066 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003067 self.assertEqual(0, git_cl.main(['try']))
3068 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3069 self.assertEqual(
3070 sys.stdout.getvalue(),
3071 'Scheduling CQ dry run on: '
3072 'https://chromium-review.googlesource.com/123456\n')
3073
Edward Lemur4c707a22019-09-24 21:13:43 +00003074 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003075 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003076 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003077
3078 self.assertEqual(0, git_cl.main([
3079 'try', '-B', 'luci.chromium.try', '-b', 'win',
3080 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3081 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003082 'Scheduling jobs on:\n'
3083 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003084 git_cl.sys.stdout.getvalue())
3085
3086 expected_request = {
3087 "requests": [{
3088 "scheduleBuild": {
3089 "requestId": "uuid4",
3090 "builder": {
3091 "project": "chromium",
3092 "builder": "win",
3093 "bucket": "try",
3094 },
3095 "gerritChanges": [{
3096 "project": "depot_tools",
3097 "host": "chromium-review.googlesource.com",
3098 "patchset": 7,
3099 "change": 123456,
3100 }],
3101 "properties": {
3102 "category": "git_cl_try",
3103 "json": [{"a": 1}, None],
3104 "key": "val",
3105 },
3106 "tags": [
3107 {"value": "win", "key": "builder"},
3108 {"value": "git_cl_try", "key": "user_agent"},
3109 ],
3110 },
3111 }],
3112 }
3113 mockCallBuildbucket.assert_called_with(
3114 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3115
Anthony Polito1a5fe232020-01-24 23:17:52 +00003116 @mock.patch('git_cl._call_buildbucket')
3117 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3118 mockCallBuildbucket.return_value = {}
3119
3120 self.assertEqual(0, git_cl.main([
3121 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3122 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3123 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3124 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003125 'Scheduling jobs on:\n'
3126 ' chromium/try: linux\n'
3127 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003128 git_cl.sys.stdout.getvalue())
3129
3130 expected_request = {
3131 "requests": [{
3132 "scheduleBuild": {
3133 "requestId": "uuid4",
3134 "builder": {
3135 "project": "chromium",
3136 "builder": "linux",
3137 "bucket": "try",
3138 },
3139 "gerritChanges": [{
3140 "project": "depot_tools",
3141 "host": "chromium-review.googlesource.com",
3142 "patchset": 7,
3143 "change": 123456,
3144 }],
3145 "properties": {
3146 "category": "git_cl_try",
3147 "json": [{"a": 1}, None],
3148 "key": "val",
3149 },
3150 "tags": [
3151 {"value": "linux", "key": "builder"},
3152 {"value": "git_cl_try", "key": "user_agent"},
3153 ],
3154 "gitilesCommit": {
3155 "host": "chromium-review.googlesource.com",
3156 "project": "depot_tools",
3157 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3158 }
3159 },
3160 },
3161 {
3162 "scheduleBuild": {
3163 "requestId": "uuid4",
3164 "builder": {
3165 "project": "chromium",
3166 "builder": "win",
3167 "bucket": "try",
3168 },
3169 "gerritChanges": [{
3170 "project": "depot_tools",
3171 "host": "chromium-review.googlesource.com",
3172 "patchset": 7,
3173 "change": 123456,
3174 }],
3175 "properties": {
3176 "category": "git_cl_try",
3177 "json": [{"a": 1}, None],
3178 "key": "val",
3179 },
3180 "tags": [
3181 {"value": "win", "key": "builder"},
3182 {"value": "git_cl_try", "key": "user_agent"},
3183 ],
3184 "gitilesCommit": {
3185 "host": "chromium-review.googlesource.com",
3186 "project": "depot_tools",
3187 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3188 }
3189 },
3190 }],
3191 }
3192 mockCallBuildbucket.assert_called_with(
3193 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3194
Edward Lemur45768512020-03-02 19:03:14 +00003195 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003196 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003197 with self.assertRaises(SystemExit):
3198 git_cl.main([
3199 'try', '-B', 'not-a-bucket', '-b', 'win',
3200 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003201 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003202 'Invalid bucket: not-a-bucket.',
3203 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003204
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003205 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003206 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003207 def testScheduleOnBuildbucketRetryFailed(
3208 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003209 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003210 7: [],
3211 6: [{
3212 'id': 112112,
3213 'builder': {
3214 'project': 'chromium',
3215 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003216 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003217 'createTime': '2019-10-09T08:00:01.854286Z',
3218 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003219 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003220 mockCallBuildbucket.return_value = {}
3221
3222 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3223 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003224 'Scheduling jobs on:\n'
3225 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003226 git_cl.sys.stdout.getvalue())
3227
3228 expected_request = {
3229 "requests": [{
3230 "scheduleBuild": {
3231 "requestId": "uuid4",
3232 "builder": {
3233 "project": "chromium",
3234 "bucket": "try",
3235 "builder": "linux",
3236 },
3237 "gerritChanges": [{
3238 "project": "depot_tools",
3239 "host": "chromium-review.googlesource.com",
3240 "patchset": 7,
3241 "change": 123456,
3242 }],
3243 "properties": {
3244 "category": "git_cl_try",
3245 },
3246 "tags": [
3247 {"value": "linux", "key": "builder"},
3248 {"value": "git_cl_try", "key": "user_agent"},
3249 {"value": "1", "key": "retry_failed"},
3250 ],
3251 },
3252 }],
3253 }
3254 mockCallBuildbucket.assert_called_with(
3255 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3256
Edward Lemur4c707a22019-09-24 21:13:43 +00003257 def test_parse_bucket(self):
3258 test_cases = [
3259 {
3260 'bucket': 'chromium/try',
3261 'result': ('chromium', 'try'),
3262 },
3263 {
3264 'bucket': 'luci.chromium.try',
3265 'result': ('chromium', 'try'),
3266 'has_warning': True,
3267 },
3268 {
3269 'bucket': 'skia.primary',
3270 'result': ('skia', 'skia.primary'),
3271 'has_warning': True,
3272 },
3273 {
3274 'bucket': 'not-a-bucket',
3275 'result': (None, None),
3276 },
3277 ]
3278
3279 for test_case in test_cases:
3280 git_cl.sys.stdout.truncate(0)
3281 self.assertEqual(
3282 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3283 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003284 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3285 test_case['result'])
3286 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003287
3288
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003289class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003290
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003291 def setUp(self):
3292 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003293 mock.patch('git_cl._fetch_tryjobs').start()
3294 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003295 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003296 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3297 mock.patch(
3298 'git_cl.Settings.GetSquashGerritUploads',
3299 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003300 self.addCleanup(mock.patch.stopall)
3301
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003302 def testWarmUpChangeDetailCache(self):
3303 self.assertEqual(0, git_cl.main(['upload']))
3304 gerrit_util.GetChangeDetail.assert_called_once_with(
3305 'chromium-review.googlesource.com', 'depot_tools~123456',
3306 frozenset([
3307 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3308 'CURRENT_COMMIT']))
3309
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003310 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003311 # This test mocks out the actual upload part, and just asserts that after
3312 # upload, if --retry-failed is added, then the tool will fetch try jobs
3313 # from the previous patchset and trigger the right builders on the latest
3314 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003315 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003316 # Latest patchset: No builds.
3317 [],
3318 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003319 [{
3320 'id': str(100 + idx),
3321 'builder': {
3322 'project': 'chromium',
3323 'bucket': 'try',
3324 'builder': 'bot_' + status.lower(),
3325 },
3326 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3327 'tags': [],
3328 'status': status,
3329 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003330 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003331
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003332 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003333 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003334 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3335 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003336 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003337 expected_buckets = [
3338 ('chromium', 'try', 'bot_failure'),
3339 ('chromium', 'try', 'bot_infra_failure'),
3340 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003341 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3342 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003343
Brian Sheedy59b06a82019-10-14 17:03:29 +00003344
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003345class MakeRequestsHelperTestCase(unittest.TestCase):
3346
3347 def exampleGerritChange(self):
3348 return {
3349 'host': 'chromium-review.googlesource.com',
3350 'project': 'depot_tools',
3351 'change': 1,
3352 'patchset': 2,
3353 }
3354
3355 def testMakeRequestsHelperNoOptions(self):
3356 # Basic test for the helper function _make_tryjob_schedule_requests;
3357 # it shouldn't throw AttributeError even when options doesn't have any
3358 # of the expected values; it will use default option values.
3359 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3360 jobs = [('chromium', 'try', 'my-builder')]
3361 options = optparse.Values()
3362 requests = git_cl._make_tryjob_schedule_requests(
3363 changelist, jobs, options, patchset=None)
3364
3365 # requestId is non-deterministic. Just assert that it's there and has
3366 # a particular length.
3367 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3368 self.assertEqual(requests, [{
3369 'scheduleBuild': {
3370 'builder': {
3371 'bucket': 'try',
3372 'builder': 'my-builder',
3373 'project': 'chromium'
3374 },
3375 'gerritChanges': [self.exampleGerritChange()],
3376 'properties': {
3377 'category': 'git_cl_try'
3378 },
3379 'tags': [{
3380 'key': 'builder',
3381 'value': 'my-builder'
3382 }, {
3383 'key': 'user_agent',
3384 'value': 'git_cl_try'
3385 }]
3386 }
3387 }])
3388
3389 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3390 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3391 jobs = [('chromium', 'try', 'presubmit')]
3392 options = optparse.Values()
3393 requests = git_cl._make_tryjob_schedule_requests(
3394 changelist, jobs, options, patchset=None)
3395 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3396 'category': 'git_cl_try',
3397 'dry_run': 'true'
3398 })
3399
3400 def testMakeRequestsHelperRevisionSet(self):
3401 # Gitiles commit is specified when revision is in options.
3402 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3403 jobs = [('chromium', 'try', 'my-builder')]
3404 options = optparse.Values({'revision': 'ba5eba11'})
3405 requests = git_cl._make_tryjob_schedule_requests(
3406 changelist, jobs, options, patchset=None)
3407 self.assertEqual(
3408 requests[0]['scheduleBuild']['gitilesCommit'], {
3409 'host': 'chromium-review.googlesource.com',
3410 'id': 'ba5eba11',
3411 'project': 'depot_tools'
3412 })
3413
3414 def testMakeRequestsHelperRetryFailedSet(self):
3415 # An extra tag is added when retry_failed is in options.
3416 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3417 jobs = [('chromium', 'try', 'my-builder')]
3418 options = optparse.Values({'retry_failed': 'true'})
3419 requests = git_cl._make_tryjob_schedule_requests(
3420 changelist, jobs, options, patchset=None)
3421 self.assertEqual(
3422 requests[0]['scheduleBuild']['tags'], [
3423 {
3424 'key': 'builder',
3425 'value': 'my-builder'
3426 },
3427 {
3428 'key': 'user_agent',
3429 'value': 'git_cl_try'
3430 },
3431 {
3432 'key': 'retry_failed',
3433 'value': '1'
3434 }
3435 ])
3436
3437 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00003438 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003439 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3440 jobs = [('chromium', 'try', 'my-builder')]
3441 options = optparse.Values({'category': 'my-special-category'})
3442 requests = git_cl._make_tryjob_schedule_requests(
3443 changelist, jobs, options, patchset=None)
3444 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3445 {'category': 'my-special-category'})
3446
3447
Edward Lemurda4b6c62020-02-13 00:28:40 +00003448class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003449
3450 def setUp(self):
3451 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003452 mock.patch('git_cl.RunCommand').start()
3453 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3454 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3455 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003456 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003457 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003458
3459 def tearDown(self):
3460 shutil.rmtree(self._top_dir)
3461 super(CMDFormatTestCase, self).tearDown()
3462
Jamie Madill5e96ad12020-01-13 16:08:35 +00003463 def _make_temp_file(self, fname, contents):
3464 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3465 tf.write('\n'.join(contents))
3466
Brian Sheedy59b06a82019-10-14 17:03:29 +00003467 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003468 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003469
Brian Sheedyb4307d52019-12-02 19:18:17 +00003470 def _check_yapf_filtering(self, files, expected):
3471 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3472 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003473
Edward Lemur1a83da12020-03-04 21:18:36 +00003474 def _run_command_mock(self, return_value):
3475 def f(*args, **kwargs):
3476 if 'stdin' in kwargs:
3477 self.assertIsInstance(kwargs['stdin'], bytes)
3478 return return_value
3479 return f
3480
Jamie Madill5e96ad12020-01-13 16:08:35 +00003481 def testClangFormatDiffFull(self):
3482 self._make_temp_file('test.cc', ['// test'])
3483 git_cl.settings.GetFormatFullByDefault.return_value = False
3484 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3485 mock_opts = mock.Mock(full=True, 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(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003489 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3490 self._top_dir, 'HEAD')
3491 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('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003495 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3496 self._top_dir, 'HEAD')
3497 self.assertEqual(0, return_value)
3498
3499 def testClangFormatDiff(self):
3500 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00003501 # A valid file is required, so use this test.
3502 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00003503 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3504
3505 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003506 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3507 return_value = git_cl._RunClangFormatDiff(
3508 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003509 self.assertEqual(2, return_value)
3510
3511 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003512 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003513 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3514 'HEAD')
3515 self.assertEqual(0, return_value)
3516
Brian Sheedyb4307d52019-12-02 19:18:17 +00003517 def testYapfignoreExplicit(self):
3518 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3519 files = [
3520 'bar.py',
3521 'foo/bar.py',
3522 'foo/baz.py',
3523 'foo/bar/baz.py',
3524 'foo/bar/foobar.py',
3525 ]
3526 expected = [
3527 'bar.py',
3528 'foo/baz.py',
3529 'foo/bar/foobar.py',
3530 ]
3531 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003532
Brian Sheedyb4307d52019-12-02 19:18:17 +00003533 def testYapfignoreSingleWildcards(self):
3534 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3535 files = [
3536 'bar.py', # Matched by *bar.py.
3537 'bar.txt',
3538 'foobar.py', # Matched by *bar.py, foo*.
3539 'foobar.txt', # Matched by foo*.
3540 'bazbar.py', # Matched by *bar.py, baz*.py.
3541 'bazbar.txt',
3542 'foo/baz.txt', # Matched by foo*.
3543 'bar/bar.py', # Matched by *bar.py.
3544 'baz/foo.py', # Matched by baz*.py, foo*.
3545 'baz/foo.txt',
3546 ]
3547 expected = [
3548 'bar.txt',
3549 'bazbar.txt',
3550 'baz/foo.txt',
3551 ]
3552 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003553
Brian Sheedyb4307d52019-12-02 19:18:17 +00003554 def testYapfignoreMultiplewildcards(self):
3555 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3556 files = [
3557 'bar.py', # Matched by *bar*.
3558 'bar.txt', # Matched by *bar*.
3559 'abar.py', # Matched by *bar*.
3560 'foobaz.txt', # Matched by *foo*baz.txt.
3561 'foobaz.py',
3562 'afoobaz.txt', # Matched by *foo*baz.txt.
3563 ]
3564 expected = [
3565 'foobaz.py',
3566 ]
3567 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003568
3569 def testYapfignoreComments(self):
3570 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003571 files = [
3572 'test.py',
3573 'test2.py',
3574 ]
3575 expected = [
3576 'test2.py',
3577 ]
3578 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003579
3580 def testYapfignoreBlankLines(self):
3581 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003582 files = [
3583 'test.py',
3584 'test2.py',
3585 'test3.py',
3586 ]
3587 expected = [
3588 'test3.py',
3589 ]
3590 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003591
3592 def testYapfignoreWhitespace(self):
3593 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003594 files = [
3595 'test.py',
3596 'test2.py',
3597 ]
3598 expected = [
3599 'test2.py',
3600 ]
3601 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003602
Brian Sheedyb4307d52019-12-02 19:18:17 +00003603 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003604 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003605 self._check_yapf_filtering([], [])
3606
3607 def testYapfignoreMissingYapfignore(self):
3608 files = [
3609 'test.py',
3610 ]
3611 expected = [
3612 'test.py',
3613 ]
3614 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003615
3616
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003617if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003618 logging.basicConfig(
3619 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003620 unittest.main()