blob: 22f2716493d71cd05f7d65a65f847d22a708485b [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
Edward Lesmes9c349062021-05-06 20:02:39 +000034import metrics_utils
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000035# We have to disable monitoring before importing git_cl.
Edward Lesmes9c349062021-05-06 20:02:39 +000036metrics_utils.COLLECT_METRICS = False
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000037
Jamie Madill5e96ad12020-01-13 16:08:35 +000038import clang_format
Edward Lemur227d5102020-02-25 23:45:35 +000039import contextlib
Edward Lemur1773f372020-02-22 00:27:14 +000040import gclient_utils
Eric Boren2fb63102018-10-05 13:05:03 +000041import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000042import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000043import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000044import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000045import git_new_branch
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +000046import owners_client
Edward Lemur85153282020-02-14 22:06:29 +000047import scm
maruel@chromium.orgddd59412011-11-30 14:20:38 +000048import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000049
Josip Sokcevic464e9ff2020-03-18 23:48:55 +000050NETRC_FILENAME = '_netrc' if sys.platform == 'win32' else '.netrc'
51
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000052
Edward Lemur0db01f02019-11-12 22:01:51 +000053def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070054 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
55
tandrii5d48c322016-08-18 16:19:37 -070056CERR1 = callError(1)
57
58
Edward Lemur1773f372020-02-22 00:27:14 +000059class TemporaryFileMock(object):
60 def __init__(self):
61 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070062
Edward Lemur1773f372020-02-22 00:27:14 +000063 @contextlib.contextmanager
64 def __call__(self):
65 self.suffix += 1
66 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070067
68
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000069class ChangelistMock(object):
70 # A class variable so we can access it when we don't have access to the
71 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000072 desc = ''
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000073
Dirk Pranke6f0df682021-06-25 00:42:33 +000074 def __init__(self, gerrit_change=None, use_python3=False, **kwargs):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000075 self._gerrit_change = gerrit_change
Dirk Pranke6f0df682021-06-25 00:42:33 +000076 self._use_python3 = use_python3
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000077
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000078 def GetIssue(self):
79 return 1
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000080
Edward Lemur6c6827c2020-02-06 21:15:18 +000081 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000082 return ChangelistMock.desc
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000083
dsansomee2d6fd92016-09-08 00:10:47 -070084 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000085 ChangelistMock.desc = desc
86
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000087 def GetGerritChange(self, patchset=None, **kwargs):
88 del patchset
89 return self._gerrit_change
90
Josip Sokcevic9011a5b2021-02-12 18:59:44 +000091 def GetRemoteBranch(self):
92 return ('origin', 'refs/remotes/origin/main')
93
Dirk Pranke6f0df682021-06-25 00:42:33 +000094 def GetUsePython3(self):
95 return self._use_python3
tandrii5d48c322016-08-18 16:19:37 -070096
Edward Lemur85153282020-02-14 22:06:29 +000097class GitMocks(object):
98 def __init__(self, config=None, branchref=None):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +000099 self.branchref = branchref or 'refs/heads/main'
Edward Lemur85153282020-02-14 22:06:29 +0000100 self.config = config or {}
101
102 def GetBranchRef(self, _root):
103 return self.branchref
104
105 def NewBranch(self, branchref):
106 self.branchref = branchref
107
Edward Lemur26964072020-02-19 19:18:51 +0000108 def GetConfig(self, root, key, default=None):
109 if root != '':
110 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000111 return self.config.get(key, default)
112
Edward Lemur26964072020-02-19 19:18:51 +0000113 def SetConfig(self, root, key, value=None):
114 if root != '':
115 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000116 if value:
117 self.config[key] = value
118 return
119 if key not in self.config:
120 raise CERR1
121 del self.config[key]
122
123
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000124class WatchlistsMock(object):
125 def __init__(self, _):
126 pass
127 @staticmethod
128 def GetWatchersForPaths(_):
129 return ['joe@example.com']
130
131
Edward Lemur4c707a22019-09-24 21:13:43 +0000132class CodereviewSettingsFileMock(object):
133 def __init__(self):
134 pass
135 # pylint: disable=no-self-use
136 def read(self):
137 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
138 'GERRIT_HOST: True\n')
139
140
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000141class AuthenticatorMock(object):
142 def __init__(self, *_args):
143 pass
144 def has_cached_credentials(self):
145 return True
tandrii221ab252016-10-06 08:12:04 -0700146 def authorize(self, http):
147 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000148
149
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100150def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000151 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
152
153 Usage:
154 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100155 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000156
157 OR
158 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100159 CookiesAuthenticatorMockFactory(
160 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000161 """
162 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800163 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000164 # Intentionally not calling super() because it reads actual cookie files.
165 pass
166 @classmethod
167 def get_gitcookies_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000168 return os.path.join('~', '.gitcookies')
169
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000170 @classmethod
171 def get_netrc_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000172 return os.path.join('~', NETRC_FILENAME)
173
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100174 def _get_auth_for_host(self, host):
175 if same_auth:
176 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000177 return (hosts_with_creds or {}).get(host)
178 return CookiesAuthenticatorMock
179
Aaron Gable9a03ae02017-11-03 11:31:07 -0700180
kmarshall9249e012016-08-23 12:02:16 -0700181class MockChangelistWithBranchAndIssue():
182 def __init__(self, branch, issue):
183 self.branch = branch
184 self.issue = issue
185 def GetBranch(self):
186 return self.branch
187 def GetIssue(self):
188 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000189
tandriic2405f52016-10-10 08:13:15 -0700190
191class SystemExitMock(Exception):
192 pass
193
194
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000195class TestGitClBasic(unittest.TestCase):
Josip Sokcevic953278a2020-02-28 19:46:36 +0000196 def setUp(self):
197 mock.patch('sys.exit', side_effect=SystemExitMock).start()
198 mock.patch('sys.stdout', StringIO()).start()
199 mock.patch('sys.stderr', StringIO()).start()
200 self.addCleanup(mock.patch.stopall)
201
202 def test_die_with_error(self):
203 with self.assertRaises(SystemExitMock):
204 git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
205 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
206 self.assertTrue('saving CL description' in sys.stdout.getvalue())
207 self.assertTrue('Content of CL description' in sys.stdout.getvalue())
208 self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
209 sys.exit.assert_called_once_with(1)
210
211 def test_die_with_error_no_desc(self):
212 with self.assertRaises(SystemExitMock):
213 git_cl.DieWithError('foo')
214 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
215 self.assertEqual(sys.stdout.getvalue(), '')
216 sys.exit.assert_called_once_with(1)
217
Edward Lemur6c6827c2020-02-06 21:15:18 +0000218 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000219 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100220 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000221 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700222
Edward Lemur61bf4172020-02-24 23:22:37 +0000223 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
224 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
225 def test_get_cl_statuses(self, *_mocks):
226 statuses = [
227 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
228 changes = []
229 for status in statuses:
230 cl = git_cl.Changelist()
231 cl.status = status
232 changes.append(cl)
233
234 actual = set(git_cl.get_cl_statuses(changes, True))
235 self.assertEqual(set(zip(changes, statuses)), actual)
236
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000237 def test_upload_to_non_default_branch_no_retry(self):
238 m = mock.patch('git_cl.Changelist._CMDUploadChange',
239 side_effect=[git_cl.GitPushError(), None]).start()
240 mock.patch('git_cl.Changelist.GetRemoteBranch',
241 return_value=('foo', 'bar')).start()
Edward Lesmeseeca9c62020-11-20 00:00:17 +0000242 mock.patch('git_cl.Changelist.GetGerritProject',
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000243 return_value='foo').start()
244 mock.patch('git_cl.gerrit_util.GetProjectHead',
245 return_value='refs/heads/main').start()
246
247 cl = git_cl.Changelist()
248 options = optparse.Values()
Josip Sokcevicb631a882021-01-06 18:18:10 +0000249 options.target_branch = 'refs/heads/bar'
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000250 with self.assertRaises(SystemExitMock):
251 cl.CMDUploadChange(options, [], 'foo', git_cl.ChangeDescription('bar'))
252
253 # ensure upload is called once
254 self.assertEqual(len(m.mock_calls), 1)
255 sys.exit.assert_called_once_with(1)
256 # option not set as retry didn't happen
257 self.assertFalse(hasattr(options, 'force'))
258 self.assertFalse(hasattr(options, 'edit_description'))
259
260 def test_upload_to_old_default_still_active(self):
261 m = mock.patch('git_cl.Changelist._CMDUploadChange',
262 side_effect=[git_cl.GitPushError(), None]).start()
263 mock.patch('git_cl.Changelist.GetRemoteBranch',
264 return_value=('foo', git_cl.DEFAULT_OLD_BRANCH)).start()
Edward Lesmeseeca9c62020-11-20 00:00:17 +0000265 mock.patch('git_cl.Changelist.GetGerritProject',
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000266 return_value='foo').start()
267 mock.patch('git_cl.gerrit_util.GetProjectHead',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000268 return_value='refs/heads/main').start()
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000269
270 cl = git_cl.Changelist()
271 options = optparse.Values()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000272 options.target_branch = 'refs/heads/main'
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000273 with self.assertRaises(SystemExitMock):
274 cl.CMDUploadChange(options, [], 'foo', git_cl.ChangeDescription('bar'))
275
276 # ensure upload is called once
277 self.assertEqual(len(m.mock_calls), 1)
278 sys.exit.assert_called_once_with(1)
279 # option not set as retry didn't happen
280 self.assertFalse(hasattr(options, 'force'))
281 self.assertFalse(hasattr(options, 'edit_description'))
282
Gavin Mak68e6cf32021-01-25 18:24:08 +0000283 def test_upload_with_message_file_no_editor(self):
284 m = mock.patch('git_cl.ChangeDescription.prompt',
285 return_value=None).start()
286 mock.patch('git_cl.Changelist.GetRemoteBranch',
287 return_value=('foo', git_cl.DEFAULT_NEW_BRANCH)).start()
288 mock.patch('git_cl.GetTargetRef',
289 return_value='refs/heads/main').start()
290 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
291 lambda _, offer_removal: None).start()
292 mock.patch('git_cl.Changelist.GetIssue', return_value=None).start()
293 mock.patch('git_cl.Changelist.GetBranch',
294 side_effect=SystemExitMock).start()
295 mock.patch('git_cl.GenerateGerritChangeId', return_value=None).start()
296 mock.patch('git_cl.RunGit').start()
297
298 cl = git_cl.Changelist()
299 options = optparse.Values()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000300 options.target_branch = 'refs/heads/main'
Gavin Mak68e6cf32021-01-25 18:24:08 +0000301 options.squash = True
302 options.edit_description = False
303 options.force = False
304 options.preserve_tryjobs = False
305 options.message_file = "message.txt"
306
307 with self.assertRaises(SystemExitMock):
308 cl.CMDUploadChange(options, [], 'foo', git_cl.ChangeDescription('bar'))
309 self.assertEqual(len(m.mock_calls), 0)
310
311 options.message_file = None
312 with self.assertRaises(SystemExitMock):
313 cl.CMDUploadChange(options, [], 'foo', git_cl.ChangeDescription('bar'))
314 self.assertEqual(len(m.mock_calls), 1)
315
Edward Lemur61bf4172020-02-24 23:22:37 +0000316 def test_get_cl_statuses_no_changes(self):
317 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
318
319 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
320 @mock.patch('multiprocessing.pool.ThreadPool')
321 def test_get_cl_statuses_timeout(self, *_mocks):
322 changes = [git_cl.Changelist() for _ in range(2)]
323 pool = multiprocessing.pool.ThreadPool()
324 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
325 it.return_value.next.side_effect = [
326 (changes[0], 'lgtm'),
327 multiprocessing.TimeoutError,
328 ]
329
330 actual = list(git_cl.get_cl_statuses(changes, True))
331 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
332
333 @mock.patch('git_cl.Changelist.GetIssueURL')
334 def test_get_cl_statuses_not_finegrained(self, _mock):
335 changes = [git_cl.Changelist() for _ in range(2)]
336 urls = ['some-url', None]
337 git_cl.Changelist.GetIssueURL.side_effect = urls
338
339 actual = set(git_cl.get_cl_statuses(changes, False))
340 self.assertEqual(
341 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
342
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000343 def test_get_issue_url(self):
344 cl = git_cl.Changelist(issue=123)
345 cl._gerrit_server = 'https://example.com'
346 self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
347 self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
348
349 cl = git_cl.Changelist(issue=123)
350 cl._gerrit_server = 'https://chromium-review.googlesource.com'
351 self.assertEqual(cl.GetIssueURL(),
352 'https://chromium-review.googlesource.com/123')
353 self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
354
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000355 def test_set_preserve_tryjobs(self):
356 d = git_cl.ChangeDescription('Simple.')
357 d.set_preserve_tryjobs()
358 self.assertEqual(d.description.splitlines(), [
359 'Simple.',
360 '',
361 'Cq-Do-Not-Cancel-Tryjobs: true',
362 ])
363 before = d.description
364 d.set_preserve_tryjobs()
365 self.assertEqual(before, d.description)
366
367 d = git_cl.ChangeDescription('\n'.join([
368 'One is enough',
369 '',
370 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
371 'Change-Id: Ideadbeef',
372 ]))
373 d.set_preserve_tryjobs()
374 self.assertEqual(d.description.splitlines(), [
375 'One is enough',
376 '',
377 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
378 'Change-Id: Ideadbeef',
379 'Cq-Do-Not-Cancel-Tryjobs: true',
380 ])
381
tandriif9aefb72016-07-01 09:06:51 -0700382 def test_get_bug_line_values(self):
383 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
384 self.assertEqual(f('', ''), [])
385 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
Lei Zhang8a0efc12020-08-05 19:58:45 +0000386 # Prefix that ends with colon.
387 self.assertEqual(f('v8:', '456'), ['v8:456'])
388 self.assertEqual(f('v8:', 'chromium:123,456'), ['v8:456', 'chromium:123'])
389 # Prefix that ends without colon.
tandriif9aefb72016-07-01 09:06:51 -0700390 self.assertEqual(f('v8', '456'), ['v8:456'])
391 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
392 # Not nice, but not worth carying.
Lei Zhang8a0efc12020-08-05 19:58:45 +0000393 self.assertEqual(f('v8:', 'chromium:123,456,v8:123'),
394 ['v8:456', 'chromium:123', 'v8:123'])
tandriif9aefb72016-07-01 09:06:51 -0700395 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
396 ['v8:456', 'chromium:123', 'v8:123'])
397
Edward Lemurda4b6c62020-02-13 00:28:40 +0000398 @mock.patch('gerrit_util.GetAccountDetails')
399 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000400 mock_per_account = {
401 'u1': None, # 404, doesn't exist.
402 'u2': {
403 '_account_id': 123124,
404 'avatars': [],
405 'email': 'u2@example.com',
406 'name': 'User Number 2',
407 'status': 'OOO',
408 },
409 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
410 }
411 def GetAccountDetailsMock(_, account):
412 # Poor-man's mock library's side_effect.
413 v = mock_per_account.pop(account)
414 if isinstance(v, Exception):
415 raise v
416 return v
417
Edward Lemurda4b6c62020-02-13 00:28:40 +0000418 mockGetAccountDetails.side_effect = GetAccountDetailsMock
419 actual = git_cl.gerrit_util.ValidAccounts(
420 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000421 self.assertEqual(actual, {
422 'u2': {
423 '_account_id': 123124,
424 'avatars': [],
425 'email': 'u2@example.com',
426 'name': 'User Number 2',
427 'status': 'OOO',
428 },
429 })
430
431
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200432class TestParseIssueURL(unittest.TestCase):
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000433 def _test(self, arg, issue=None, patchset=None, hostname=None, fail=False):
434 parsed = git_cl.ParseIssueNumberArgument(arg)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200435 self.assertIsNotNone(parsed)
436 if fail:
437 self.assertFalse(parsed.valid)
438 return
439 self.assertTrue(parsed.valid)
440 self.assertEqual(parsed.issue, issue)
441 self.assertEqual(parsed.patchset, patchset)
442 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200443
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000444 def test_basic(self):
445 self._test('123', 123)
446 self._test('', fail=True)
447 self._test('abc', fail=True)
448 self._test('123/1', fail=True)
449 self._test('123a', fail=True)
450 self._test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
451 self._test('ssh://chrome-review.source.com/c/123/1/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200452
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000453 def test_gerrit_url(self):
454 self._test('https://codereview.source.com/123', 123, None,
455 'codereview.source.com')
456 self._test('http://chrome-review.source.com/c/123', 123, None,
457 'chrome-review.source.com')
458 self._test('https://chrome-review.source.com/c/123/', 123, None,
459 'chrome-review.source.com')
460 self._test('https://chrome-review.source.com/c/123/4', 123, 4,
461 'chrome-review.source.com')
462 self._test('https://chrome-review.source.com/#/c/123/4', 123, 4,
463 'chrome-review.source.com')
464 self._test('https://chrome-review.source.com/c/123/4', 123, 4,
465 'chrome-review.source.com')
466 self._test('https://chrome-review.source.com/123', 123, None,
467 'chrome-review.source.com')
468 self._test('https://chrome-review.source.com/123/4', 123, 4,
469 'chrome-review.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200470
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000471 self._test('https://chrome-review.source.com/bad/123/4', fail=True)
472 self._test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
473 self._test('https://chrome-review.source.com/c/abc/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200474
Andrii Shyshkalov8aebb602020-04-16 22:10:27 +0000475 def test_short_urls(self):
476 self._test('https://crrev.com/c/2151934', 2151934, None,
477 'chromium-review.googlesource.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200478
Alex Turner30ae6372022-01-04 02:32:52 +0000479 def test_missing_scheme(self):
480 self._test('codereview.source.com/123', 123, None, 'codereview.source.com')
481 self._test('crrev.com/c/2151934', 2151934, None,
482 'chromium-review.googlesource.com')
483
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200484
Edward Lemurda4b6c62020-02-13 00:28:40 +0000485class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100486 def setUp(self):
487 super(GitCookiesCheckerTest, self).setUp()
488 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100489 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000490 mock.patch('sys.stdout', StringIO()).start()
491 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100492
493 def mock_hosts_creds(self, subhost_identity_pairs):
494 def ensure_googlesource(h):
495 if not h.endswith(self.c._GOOGLESOURCE):
496 assert not h.endswith('.')
497 return h + '.' + self.c._GOOGLESOURCE
498 return h
499 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
500 for h, i in subhost_identity_pairs]
501
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200502 def test_identity_parsing(self):
503 self.assertEqual(self.c._parse_identity('ldap.google.com'),
504 ('ldap', 'google.com'))
505 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
506 ('ldap', 'example.com'))
507 # Specical case because we know there are no subdomains in chromium.org.
508 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
509 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800510 # Pathological: ".period." can be either username OR domain, more likely
511 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200512 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
513 ('note', 'period.example.com'))
514
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100515 def test_analysis_nothing(self):
516 self.c._all_hosts = []
517 self.assertFalse(self.c.has_generic_host())
518 self.assertEqual(set(), self.c.get_conflicting_hosts())
519 self.assertEqual(set(), self.c.get_duplicated_hosts())
520 self.assertEqual(set(), self.c.get_partially_configured_hosts())
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100521
522 def test_analysis(self):
523 self.mock_hosts_creds([
524 ('.googlesource.com', 'git-example.chromium.org'),
525
526 ('chromium', 'git-example.google.com'),
527 ('chromium-review', 'git-example.google.com'),
528 ('chrome-internal', 'git-example.chromium.org'),
529 ('chrome-internal-review', 'git-example.chromium.org'),
530 ('conflict', 'git-example.google.com'),
531 ('conflict-review', 'git-example.chromium.org'),
532 ('dup', 'git-example.google.com'),
533 ('dup', 'git-example.google.com'),
534 ('dup-review', 'git-example.google.com'),
535 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200536 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100537 ])
538 self.assertTrue(self.c.has_generic_host())
539 self.assertEqual(set(['conflict.googlesource.com']),
540 self.c.get_conflicting_hosts())
541 self.assertEqual(set(['dup.googlesource.com']),
542 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200543 self.assertEqual(set(['partial.googlesource.com',
544 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100545 self.c.get_partially_configured_hosts())
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100546
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100547 def test_report_no_problems(self):
548 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100549 self.assertFalse(self.c.find_and_report_problems())
550 self.assertEqual(sys.stdout.getvalue(), '')
551
Edward Lemurda4b6c62020-02-13 00:28:40 +0000552 @mock.patch(
553 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000554 return_value=os.path.join('~', '.gitcookies'))
Edward Lemurda4b6c62020-02-13 00:28:40 +0000555 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100556 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100557 self.assertTrue(self.c.find_and_report_problems())
558 with open(os.path.join(os.path.dirname(__file__),
559 'git_cl_creds_check_report.txt')) as f:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000560 expected = f.read() % {
561 'sep': os.sep,
562 }
563
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100564 def by_line(text):
565 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700566 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200567 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100568
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800569
Edward Lemurda4b6c62020-02-13 00:28:40 +0000570class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000571 def setUp(self):
572 super(TestGitCl, self).setUp()
573 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700574 self._calls_done = []
Edward Lesmes0dd54822020-03-26 18:24:25 +0000575 self.failed = False
Edward Lemurda4b6c62020-02-13 00:28:40 +0000576 mock.patch('sys.stdout', StringIO()).start()
577 mock.patch(
578 'git_cl.time_time',
579 lambda: self._mocked_call('time.time')).start()
580 mock.patch(
581 'git_cl.metrics.collector.add_repeated',
582 lambda *a: self._mocked_call('add_repeated', *a)).start()
583 mock.patch('subprocess2.call', self._mocked_call).start()
584 mock.patch('subprocess2.check_call', self._mocked_call).start()
585 mock.patch('subprocess2.check_output', self._mocked_call).start()
586 mock.patch(
587 'subprocess2.communicate',
588 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
589 mock.patch(
590 'git_cl.gclient_utils.CheckCallAndFilter',
591 self._mocked_call).start()
592 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000593 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
594 mock.patch(
595 'git_cl.SaveDescriptionBackup',
596 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
597 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000598 'git_cl.write_json',
599 lambda *a: self._mocked_call('write_json', *a)).start()
600 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000601 'git_cl.Changelist.RunHook',
602 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000603 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
604 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000605 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000606 mock.patch(
607 'git_cl.gerrit_util.GetChangeComments',
608 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
609 mock.patch(
610 'git_cl.gerrit_util.GetChangeRobotComments',
611 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
612 mock.patch(
613 'git_cl.gerrit_util.AddReviewers',
614 lambda *a: self._mocked_call('AddReviewers', *a)).start()
615 mock.patch(
616 'git_cl.gerrit_util.SetReview',
617 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
618 self._mocked_call(
619 'SetReview', h, i, msg, labels, notify, ready))).start()
620 mock.patch(
621 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
622 return_value=False).start()
623 mock.patch(
624 'git_cl.gerrit_util.GceAuthenticator.is_gce',
625 return_value=False).start()
626 mock.patch(
627 'git_cl.gerrit_util.ValidAccounts',
628 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000629 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000630 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000631 self.mockGit = GitMocks()
632 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
633 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
Edward Lesmes50da7702020-03-30 19:23:43 +0000634 mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
635 mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
Edward Lemur85153282020-02-14 22:06:29 +0000636 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000637 mock.patch(
638 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000639 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000640 'scm.GIT.FetchUpstreamTuple',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000641 return_value=('origin', 'refs/heads/main')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000642 mock.patch(
643 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000644 # It's important to reset settings to not have inter-tests interference.
645 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000646 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000647
648 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000649 try:
Edward Lesmes0dd54822020-03-26 18:24:25 +0000650 if not self.failed:
651 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100652 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000653 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
654 if len(self.calls) > 5:
655 calls += ' ...\n'
656 self.fail(
657 '\n'
658 'There are un-consumed calls after this test has finished:\n' +
659 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000660 finally:
661 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000662
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000663 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000664 self.assertTrue(
665 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700666 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000667 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000668 expected_args, result = top
669
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000670 # Also logs otherwise it could get caught in a try/finally and be hard to
671 # diagnose.
672 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700673 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000674 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700675 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
676 for i, c in enumerate(self._calls_done[-N:]))
677 following_calls = '\n '.join(
678 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
679 for i, c in enumerate(self.calls[:N]))
680 extended_msg = (
681 'A few prior calls:\n %s\n\n'
682 'This (expected):\n @%d: %r\n'
683 'This (actual):\n @%d: %r\n\n'
684 'A few following expected calls:\n %s' %
685 (prior_calls, len(self._calls_done), expected_args,
686 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700687
Edward Lesmes0dd54822020-03-26 18:24:25 +0000688 self.failed = True
tandrii99a72f22016-08-17 14:33:24 -0700689 self.fail('@%d\n'
690 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000691 ' Actual: %r\n'
692 '\n'
693 '%s' % (
694 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700695
696 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700697 if isinstance(result, Exception):
698 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000699 # stdout from git commands is supposed to be a bytestream. Convert it here
700 # instead of converting all test output in this file to bytes.
701 if args[0][0] == 'git' and not isinstance(result, bytes):
702 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000703 return result
704
Edward Lemur1a83da12020-03-04 21:18:36 +0000705 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
706 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100707 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100708 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000709 self.assertEqual(
710 'prompt [Yes/No]: Please, type yes or no: ',
711 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100712
tandrii48df5812016-10-17 03:55:37 -0700713 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000714 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700715 self.calls = [
716 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700717 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
718 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
719 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
720 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700721 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
722 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700723 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
724 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000725 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
726 CERR1),
Dirk Pranke6f0df682021-06-25 00:42:33 +0000727 ((['git', 'config', '--unset-all', 'rietveld.use-python3'],),
728 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700729 ((['git', 'config', 'gerrit.host', 'true'],), ''),
730 ]
731 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
732
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000733 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100734 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200735 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000736 custom_cl_base=None, short_hostname='chromium',
Joanna Wang583ca662022-04-27 21:17:17 +0000737 change_id=None, default_branch='main',
738 reset_issue=False):
Edward Lemur26964072020-02-19 19:18:51 +0000739 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200740 if custom_cl_base:
741 ancestor_revision = custom_cl_base
742 else:
743 # Determine ancestor_revision to be merge base.
Edward Lesmes8c43c3f2021-01-20 00:20:26 +0000744 ancestor_revision = 'origin/' + default_branch
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200745
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100746 if issue:
Joanna Wang583ca662022-04-27 21:17:17 +0000747 # TODO: if tests don't provide a `change_id` the default used here
748 # will cause the TRACES_README_FORMAT mock (which uses the test provided
749 # `change_id` to fail.
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000750 gerrit_util.GetChangeDetail.return_value = {
751 'owner': {'email': (other_cl_owner or 'owner@example.com')},
752 'change_id': (change_id or '123456789'),
753 'current_revision': 'sha1_of_current_revision',
754 'revisions': {'sha1_of_current_revision': {
755 'commit': {'message': fetched_description},
756 }},
757 'status': fetched_status or 'NEW',
758 }
Joanna Wang583ca662022-04-27 21:17:17 +0000759
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100760 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100761 return calls
Joanna Wang583ca662022-04-27 21:17:17 +0000762 if fetched_status == 'MERGED':
763 calls.append(
764 (('ask_for_data',
765 'Change https://chromium-review.googlesource.com/%s has been '
766 'submitted, new uploads are not allowed. Would you like to start '
767 'a new change (Y/n)?' % issue), 'y' if reset_issue else 'n')
768 )
769 if not reset_issue:
770 return calls
771 # Part of SetIssue call.
772 calls.append(
773 ((['git', 'log', '-1', '--format=%B'],), ''))
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100774 if other_cl_owner:
775 calls += [
776 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
777 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100778
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100779 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200780 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
781 ([custom_cl_base] if custom_cl_base else
782 [ancestor_revision, 'HEAD']),),
783 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100784 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000785
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100786 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000787
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000788 def _gerrit_upload_calls(self,
789 description,
790 reviewers,
791 squash,
tandriia60502f2016-06-20 02:01:53 -0700792 squash_mode='default',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000793 title=None,
794 notify=False,
795 post_amend_description=None,
796 issue=None,
797 cc=None,
798 custom_cl_base=None,
799 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000800 short_hostname='chromium',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000801 labels=None,
802 change_id=None,
803 final_description=None,
804 gitcookies_exists=True,
805 force=False,
806 edit_description=None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000807 default_branch='main',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000808 push_opts=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000809 if post_amend_description is None:
810 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700811 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200812
813 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000814
Edward Lesmes4de54132020-05-05 19:41:33 +0000815 if squash_mode in ('override_squash', 'override_nosquash'):
816 self.mockGit.config['gerrit.override-squash-uploads'] = (
817 'true' if squash_mode == 'override_squash' else 'false')
818
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000819 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000820 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200821 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200822 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000823 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000824 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000825 calls += [
826 ((['RunEditor'],), description),
827 ]
Josipe827b0f2020-01-30 00:07:20 +0000828 # user wants to edit description
829 if edit_description:
830 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000831 ((['RunEditor'],), edit_description),
832 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000833 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200834
835 if custom_cl_base is None:
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000836 parent = 'origin/' + default_branch
Edward Lesmes8c43c3f2021-01-20 00:20:26 +0000837 git_common.get_or_create_merge_base.return_value = parent
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200838 else:
839 calls += [
840 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000841 'refs/remotes/origin/' + default_branch],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200842 callError(1)), # Means not ancenstor.
843 (('ask_for_data',
844 'Do you take responsibility for cleaning up potential mess '
845 'resulting from proceeding with upload? Press Enter to upload, '
846 'or Ctrl+C to abort'), ''),
847 ]
848 parent = custom_cl_base
849
850 calls += [
851 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
852 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000853 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200854 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000855 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200856 ref_to_push),
857 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000858 else:
859 ref_to_push = 'HEAD'
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000860 parent = 'origin/refs/heads/' + default_branch
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000861
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000862 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000863 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000864 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200865 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000866
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000867 metrics_arguments = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000868
Aaron Gableafd52772017-06-27 16:40:10 -0700869 if notify:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000870 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000871 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700872 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400873 if not issue and squash:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000874 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000875 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700876 else:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000877 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000878 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800879
Edward Lemur5a644f82020-03-18 16:44:57 +0000880 # If issue is given, then description is fetched from Gerrit instead.
manukh566e9d02022-06-30 19:49:53 +0000881 if not title:
882 if issue is None:
883 if squash:
884 title = 'Initial upload'
885 else:
Edward Lemur5a644f82020-03-18 16:44:57 +0000886 calls += [
887 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
888 (('ask_for_data', 'Title for patchset []: '), 'User input'),
889 ]
890 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700891 if title:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000892 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000893 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000894
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000895 if short_hostname == 'chromium':
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000896 # All reviewers and ccs get into ref_suffix.
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000897 for r in sorted(reviewers):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000898 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000899 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000900 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000901 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000902 for c in sorted(cc):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000903 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000904 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000905 reviewers, cc = [], []
906 else:
907 # TODO(crbug/877717): remove this case.
908 calls += [
909 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
910 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000911 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000912 {
913 e: {'email': e}
914 for e in (reviewers + ['joe@example.com'] + cc)
915 })
916 ]
917 for r in sorted(reviewers):
918 if r != 'bad-account-or-email':
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000919 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000920 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000921 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000922 if issue is None:
923 cc += ['joe@example.com']
924 for c in sorted(cc):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000925 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000926 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000927 if c in cc:
928 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000929
Edward Lemur687ca902018-12-05 02:30:30 +0000930 for k, v in sorted((labels or {}).items()):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000931 ref_suffix += ',l=%s+%d' % (k, v)
Edward Lemur687ca902018-12-05 02:30:30 +0000932 metrics_arguments.append('l=%s+%d' % (k, v))
933
934 if tbr:
935 calls += [
936 (('GetCodeReviewTbrScore',
937 '%s-review.googlesource.com' % short_hostname,
938 'my/repo'),
939 2,),
940 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000941
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000942 calls += [
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000943 (
944 ('time.time', ),
945 1000,
946 ),
947 (
948 ([
949 'git', 'push',
950 'https://%s.googlesource.com/my/repo' % short_hostname,
951 ref_to_push + ':refs/for/refs/heads/' + default_branch +
952 ref_suffix
953 ] + (push_opts if push_opts else []), ),
954 (('remote:\n'
955 'remote: Processing changes: (\)\n'
956 'remote: Processing changes: (|)\n'
957 'remote: Processing changes: (/)\n'
958 'remote: Processing changes: (-)\n'
959 'remote: Processing changes: new: 1 (/)\n'
960 'remote: Processing changes: new: 1, done\n'
961 'remote:\n'
962 'remote: New Changes:\n'
963 'remote: '
964 'https://%s-review.googlesource.com/#/c/my/repo/+/123456'
965 ' XXX\n'
966 'remote:\n'
967 'To https://%s.googlesource.com/my/repo\n'
968 ' * [new branch] hhhh -> refs/for/refs/heads/%s\n') %
969 (short_hostname, short_hostname, default_branch)),
970 ),
971 (
972 ('time.time', ),
973 2000,
974 ),
975 (
976 ('add_repeated', 'sub_commands', {
977 'execution_time': 1000,
978 'command': 'git push',
979 'exit_code': 0,
980 'arguments': sorted(metrics_arguments),
981 }),
982 None,
983 ),
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000984 ]
985
Edward Lemur1b52d872019-05-09 21:12:12 +0000986 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000987
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000988 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
989
Edward Lemur1b52d872019-05-09 21:12:12 +0000990 # Trace-related calls
991 calls += [
992 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000993 (
994 ([
995 'FileWrite', trace_name + '-README',
996 '%(date)s\n'
997 '%(short_hostname)s-review.googlesource.com\n'
998 '%(change_id)s\n'
999 '%(title)s\n'
1000 '%(description)s\n'
1001 '1000\n'
1002 '0\n'
1003 '%(trace_name)s' % {
Josip Sokcevic5e18b602020-04-23 21:47:00 +00001004 'date': '2017-03-16T20:00:41.000000',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001005 'short_hostname': short_hostname,
1006 'change_id': change_id,
1007 'description': final_description,
1008 'title': title or '<untitled>',
1009 'trace_name': trace_name,
1010 }
1011 ], ),
1012 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001013 ),
1014 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001015 (
1016 (['os.path.isfile',
1017 os.path.join('TEMP_DIR', 'trace-packet')], ),
1018 True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001019 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001020 (
1021 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
1022 ('git-hash: 0123456789012345678901234567890123456789\n'
1023 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +00001024 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001025 (
1026 ([
1027 'FileWrite',
1028 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
1029 'git-hash: abcdea\n'
1030 ], ),
1031 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001032 ),
1033 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001034 (
1035 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
1036 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001037 ),
1038 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001039 (
1040 (['git', 'config', '-l'], ),
1041 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +00001042 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001043 (
1044 ([
1045 'FileWrite',
1046 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
1047 ], ),
1048 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001049 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001050 (
1051 (['os.path.isfile',
1052 os.path.join('~', '.gitcookies')], ),
1053 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +00001054 ),
1055 ]
1056 if gitcookies_exists:
1057 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001058 (
1059 (['FileRead', os.path.join('~', '.gitcookies')], ),
1060 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +00001061 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001062 (
1063 ([
1064 'FileWrite',
1065 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
1066 ], ),
1067 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001068 ),
1069 ]
1070 calls += [
1071 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001072 (
1073 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
1074 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001075 ),
1076 ]
1077
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001078 # TODO(crbug/877717): this should never be used.
1079 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001080 calls += [
1081 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001082 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001083 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001084 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001085 notify),
1086 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001087 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001088 return calls
1089
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001090 def _run_gerrit_upload_test(self,
1091 upload_args,
1092 description,
1093 reviewers=None,
1094 squash=True,
1095 squash_mode=None,
1096 title=None,
1097 notify=False,
1098 post_amend_description=None,
1099 issue=None,
1100 cc=None,
1101 fetched_status=None,
1102 other_cl_owner=None,
1103 custom_cl_base=None,
1104 tbr=None,
1105 short_hostname='chromium',
1106 labels=None,
1107 change_id=None,
1108 final_description=None,
1109 gitcookies_exists=True,
1110 force=False,
1111 log_description=None,
1112 edit_description=None,
1113 fetched_description=None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001114 default_branch='main',
Joanna Wang583ca662022-04-27 21:17:17 +00001115 push_opts=None,
1116 reset_issue=False):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001117 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001118 if squash_mode is None:
1119 if '--no-squash' in upload_args:
1120 squash_mode = 'nosquash'
1121 elif '--squash' in upload_args:
1122 squash_mode = 'squash'
1123 else:
1124 squash_mode = 'default'
1125
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001126 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001127 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001128 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001129 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001130 same_auth=('git-owner.example.com', '', 'pass'))).start()
1131 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1132 lambda _, offer_removal: None).start()
1133 mock.patch('git_cl.gclient_utils.RunEditor',
1134 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1135 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001136 'DownloadGerritHook', force)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001137 mock.patch('git_cl.gclient_utils.FileRead',
1138 lambda path: self._mocked_call(['FileRead', path])).start()
1139 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001140 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001141 ['FileWrite', path, contents])).start()
1142 mock.patch('git_cl.datetime_now',
1143 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1144 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1145 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1146 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001147 '%(now)s\n'
1148 '%(gerrit_host)s\n'
1149 '%(change_id)s\n'
1150 '%(title)s\n'
1151 '%(description)s\n'
1152 '%(execution_time)s\n'
1153 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001154 '%(trace_name)s').start()
1155 mock.patch('git_cl.shutil.make_archive',
1156 lambda *args: self._mocked_call(['make_archive'] +
1157 list(args))).start()
1158 mock.patch('os.path.isfile',
1159 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001160 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001161 'git_cl._create_description_from_log',
1162 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001163 mock.patch(
1164 'git_cl.Changelist._AddChangeIdToCommitMessage',
1165 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001166 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001167 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1168 mock.patch(
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001169 'git_common.get_or_create_merge_base',
1170 return_value='origin/' + default_branch).start()
1171 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001172 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001173 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001174
Edward Lemur26964072020-02-19 19:18:51 +00001175 self.mockGit.config['gerrit.host'] = 'true'
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001176 self.mockGit.config['branch.main.gerritissue'] = (
Edward Lemur85153282020-02-14 22:06:29 +00001177 str(issue) if issue else None)
1178 self.mockGit.config['remote.origin.url'] = (
1179 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001180 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001181
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001182 self.calls = self._gerrit_base_calls(
1183 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001184 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001185 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001186 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001187 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001188 short_hostname=short_hostname,
Josip Sokcevicc39ab992020-09-24 20:09:15 +00001189 change_id=change_id,
Joanna Wang583ca662022-04-27 21:17:17 +00001190 default_branch=default_branch,
1191 reset_issue=reset_issue)
1192
1193 if fetched_status == 'ABANDONED' or (
1194 fetched_status == 'MERGED' and not reset_issue):
1195 pass # readability
1196 else:
1197 if fetched_status == 'MERGED' and reset_issue:
1198 fetched_status = 'NEW'
1199 issue = None
Edward Lemurda4b6c62020-02-13 00:28:40 +00001200 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001201 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001202 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001203 self.calls += self._gerrit_upload_calls(
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001204 description,
1205 reviewers,
1206 squash,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001207 squash_mode=squash_mode,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001208 title=title,
1209 notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001210 post_amend_description=post_amend_description,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001211 issue=issue,
1212 cc=cc,
1213 custom_cl_base=custom_cl_base,
1214 tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001215 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001216 labels=labels,
1217 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001218 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001219 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001220 force=force,
Josip Sokcevicc39ab992020-09-24 20:09:15 +00001221 edit_description=edit_description,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001222 default_branch=default_branch,
1223 push_opts=push_opts)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001224 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001225 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001226 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001227 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001228 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001229 self.assertEqual(
1230 'abcdef0123456789',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001231 scm.GIT.GetBranchConfig('', 'main', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001232
Edward Lemur1b52d872019-05-09 21:12:12 +00001233 def test_gerrit_upload_traces_no_gitcookies(self):
1234 self._run_gerrit_upload_test(
1235 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001236 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001237 [],
1238 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001239 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001240 change_id='Ixxx',
1241 gitcookies_exists=False)
1242
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001243 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001244 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001245 [],
1246 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1247 [],
1248 change_id='Ixxx')
1249
1250 def test_gerrit_upload_without_change_id_nosquash(self):
1251 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001252 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001253 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001254 [],
1255 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001256 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001257 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001258
Edward Lesmes4de54132020-05-05 19:41:33 +00001259 def test_gerrit_upload_without_change_id_override_nosquash(self):
1260 self._run_gerrit_upload_test(
1261 [],
1262 'desc ✔\n\nBUG=\n',
1263 [],
1264 squash=False,
1265 squash_mode='override_nosquash',
1266 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1267 change_id='Ixxx')
1268
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001269 def test_gerrit_no_reviewer(self):
1270 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001271 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001272 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001273 [],
1274 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001275 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001276 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001277
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001278 def test_gerrit_push_opts(self):
1279 self._run_gerrit_upload_test(['-o', 'wip'],
1280 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
1281 [],
1282 squash=False,
1283 squash_mode='override_nosquash',
1284 change_id='I123456789',
1285 push_opts=['-o', 'wip'])
1286
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001287 def test_gerrit_no_reviewer_non_chromium_host(self):
1288 # TODO(crbug/877717): remove this test case.
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001289 self._run_gerrit_upload_test([],
1290 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
1291 [],
1292 squash=False,
1293 squash_mode='override_nosquash',
1294 short_hostname='other',
1295 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001296
Edward Lesmes0dd54822020-03-26 18:24:25 +00001297 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001298 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001299 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001300 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001301 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001302 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001303 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001304 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001305
ukai@chromium.orge8077812012-02-03 03:41:46 +00001306 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001307 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001308 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001309 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001310 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001311 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001312 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001313 notify=True,
1314 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001315 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001316 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001317
Thiago Perrottab0fb8d52022-08-30 21:26:19 +00001318 def test_gerrit_reviewers_cmd_line_send_email(self):
1319 self._run_gerrit_upload_test(
1320 ['-r', 'foo@example.com', '--send-email'],
1321 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
1322 reviewers=['foo@example.com'],
1323 squash=False,
1324 squash_mode='override_nosquash',
1325 notify=True,
1326 change_id='I123456789',
1327 final_description=(
1328 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
1329
Anthony Polito8b955342019-09-24 19:01:36 +00001330 def test_gerrit_upload_force_sets_bug(self):
1331 self._run_gerrit_upload_test(
1332 ['-b', '10000', '-f'],
1333 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1334 [],
1335 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001336 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001337 change_id='Ixxx')
1338
Edward Lemur5fb22242020-03-12 22:05:13 +00001339 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001340 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001341 ['-b', '10000', '-m', 'Title', '--edit-description'],
1342 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001343 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001344 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001345 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001346 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001347 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001348 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001349
Dan Beamd8b04ca2019-10-10 21:23:26 +00001350 def test_gerrit_upload_force_sets_fixed(self):
1351 self._run_gerrit_upload_test(
1352 ['-x', '10000', '-f'],
1353 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1354 [],
1355 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001356 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001357 change_id='Ixxx')
1358
ukai@chromium.orge8077812012-02-03 03:41:46 +00001359 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001360 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1361 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001362 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001363 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001364 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001365 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001366 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001367 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001368 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001369 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001370 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001371 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001372
1373 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001374 self._run_gerrit_upload_test(
1375 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001376 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001377 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001378 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001379
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001380 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001381 self._run_gerrit_upload_test(
1382 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001383 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001384 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001385 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001386 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001387
Edward Lesmes0dd54822020-03-26 18:24:25 +00001388 def test_gerrit_upload_squash_first_title(self):
1389 self._run_gerrit_upload_test(
1390 ['-f', '-t', 'title'],
1391 'title\n\ndesc\n\nChange-Id: 123456789',
1392 [],
manukh566e9d02022-06-30 19:49:53 +00001393 title='title',
Edward Lesmes0dd54822020-03-26 18:24:25 +00001394 force=True,
1395 squash=True,
1396 log_description='desc',
1397 change_id='123456789')
1398
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001399 def test_gerrit_upload_squash_first_with_labels(self):
1400 self._run_gerrit_upload_test(
1401 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001402 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001403 [],
1404 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001405 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001406 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001407
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001408 def test_gerrit_upload_squash_first_against_rev(self):
1409 custom_cl_base = 'custom_cl_base_rev_or_branch'
1410 self._run_gerrit_upload_test(
1411 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001412 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001413 [],
1414 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001415 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001416 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001417 self.assertIn(
1418 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1419 sys.stdout.getvalue())
1420
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001421 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001422 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001423 self._run_gerrit_upload_test(
1424 ['--squash'],
1425 description,
1426 [],
1427 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001428 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001429 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001430
Edward Lemurd55c5072020-02-20 01:09:07 +00001431 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001432 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001433 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001434 with self.assertRaises(SystemExitMock):
1435 self._run_gerrit_upload_test(
1436 ['--squash'],
1437 description,
1438 [],
1439 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001440 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001441 fetched_status='ABANDONED',
1442 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001443 self.assertEqual(
1444 'Change https://chromium-review.googlesource.com/123456 has been '
1445 'abandoned, new uploads are not allowed\n',
1446 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001447
Edward Lemurda4b6c62020-02-13 00:28:40 +00001448 @mock.patch(
1449 'gerrit_util.GetAccountDetails',
1450 return_value={'email': 'yet-another@example.com'})
1451 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001452 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001453 self._run_gerrit_upload_test(
1454 ['--squash'],
1455 description,
1456 [],
1457 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001458 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001459 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001460 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001461 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001462 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001463 'authenticate to Gerrit as yet-another@example.com.\n'
1464 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001465 sys.stdout.getvalue())
Joanna Wang583ca662022-04-27 21:17:17 +00001466 @mock.patch('sys.stderr', StringIO())
1467 def test_gerrit_upload_for_merged(self):
1468 with self.assertRaises(SystemExitMock):
1469 self._run_gerrit_upload_test(
1470 [],
1471 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
1472 [],
1473 issue=123456,
1474 fetched_status='MERGED',
1475 change_id='I123456789',
1476 reset_issue=False)
1477 self.assertEqual(
1478 'New uploads are not allowed.\n',
1479 sys.stderr.getvalue())
1480
1481 def test_gerrit_upload_new_issue_for_merged(self):
1482 self._run_gerrit_upload_test(
1483 [],
1484 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
1485 [],
1486 issue=123456,
1487 fetched_status='MERGED',
1488 change_id='I123456789',
1489 reset_issue=True)
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001490
Josipe827b0f2020-01-30 00:07:20 +00001491 def test_upload_change_description_editor(self):
1492 fetched_description = 'foo\n\nChange-Id: 123456789'
1493 description = 'bar\n\nChange-Id: 123456789'
1494 self._run_gerrit_upload_test(
1495 ['--squash', '--edit-description'],
1496 description,
1497 [],
1498 fetched_description=fetched_description,
1499 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001500 issue=123456,
1501 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001502 edit_description=description)
1503
Edward Lemurda4b6c62020-02-13 00:28:40 +00001504 @mock.patch('git_cl.RunGit')
1505 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001506 @mock.patch('sys.stdin', StringIO('\n'))
1507 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001508 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001509 def mock_run_git(*args, **_kwargs):
1510 if args[0] == ['for-each-ref',
1511 '--format=%(refname:short) %(upstream:short)',
1512 'refs/heads']:
1513 # Create a local branch dependency tree that looks like this:
1514 # test1 -> test2 -> test3 -> test4 -> test5
1515 # -> test3.1
1516 # test6 -> test0
1517 branch_deps = [
1518 'test2 test1', # test1 -> test2
1519 'test3 test2', # test2 -> test3
1520 'test3.1 test2', # test2 -> test3.1
1521 'test4 test3', # test3 -> test4
1522 'test5 test4', # test4 -> test5
1523 'test6 test0', # test0 -> test6
1524 'test7', # test7
1525 ]
1526 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001527 git_cl.RunGit.side_effect = mock_run_git
1528 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001529
1530 class MockChangelist():
1531 def __init__(self):
1532 pass
1533 def GetBranch(self):
1534 return 'test1'
1535 def GetIssue(self):
1536 return '123'
1537 def GetPatchset(self):
1538 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001539 def IsGerrit(self):
1540 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001541
1542 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1543 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001544 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001545 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001546 'This command will checkout all dependent branches '
1547 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001548 'or Ctrl+C to abort',
1549 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001550 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001551
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001552 def test_gerrit_change_id(self):
1553 self.calls = [
1554 ((['git', 'write-tree'], ),
1555 'hashtree'),
1556 ((['git', 'rev-parse', 'HEAD~0'], ),
1557 'branch-parent'),
1558 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1559 'A B <a@b.org> 1456848326 +0100'),
1560 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1561 'C D <c@d.org> 1456858326 +0100'),
1562 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1563 'hashchange'),
1564 ]
1565 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1566 self.assertEqual(change_id, 'Ihashchange')
1567
Edward Lesmes8170c292021-03-19 20:04:43 +00001568 @mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001569 @mock.patch('git_cl.Settings.GetBugPrefix')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001570 @mock.patch('git_cl.Changelist.FetchDescription')
1571 @mock.patch('git_cl.Changelist.GetBranch')
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001572 @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
Edward Lesmese1576912021-02-16 21:53:34 +00001573 @mock.patch('git_cl.Changelist.GetGerritHost')
1574 @mock.patch('git_cl.Changelist.GetGerritProject')
1575 @mock.patch('git_cl.Changelist.GetRemoteBranch')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001576 @mock.patch('owners_client.OwnersClient.BatchListOwners')
1577 def getDescriptionForUploadTest(
Edward Lesmese1576912021-02-16 21:53:34 +00001578 self, mockBatchListOwners=None, mockGetRemoteBranch=None,
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001579 mockGetGerritProject=None, mockGetGerritHost=None,
1580 mockGetCommonAncestorWithUpstream=None, mockGetBranch=None,
Edward Lesmese1576912021-02-16 21:53:34 +00001581 mockFetchDescription=None, mockGetBugPrefix=None,
Edward Lesmes8170c292021-03-19 20:04:43 +00001582 mockIsCodeOwnersEnabledOnHost=None,
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001583 initial_description='desc', bug=None, fixed=None, branch='branch',
1584 reviewers=None, tbrs=None, add_owners_to=None,
1585 expected_description='desc'):
1586 reviewers = reviewers or []
1587 tbrs = tbrs or []
1588 owners_by_path = {
1589 'a': ['a@example.com'],
1590 'b': ['b@example.com'],
1591 'c': ['c@example.com'],
1592 }
Edward Lesmes8170c292021-03-19 20:04:43 +00001593 mockIsCodeOwnersEnabledOnHost.return_value = True
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001594 mockGetBranch.return_value = branch
1595 mockGetBugPrefix.return_value = 'prefix'
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001596 mockGetCommonAncestorWithUpstream.return_value = 'upstream'
Edward Lesmese1576912021-02-16 21:53:34 +00001597 mockGetRemoteBranch.return_value = ('origin', 'refs/remotes/origin/main')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001598 mockFetchDescription.return_value = 'desc'
1599 mockBatchListOwners.side_effect = lambda ps: {
1600 p: owners_by_path.get(p)
1601 for p in ps
1602 }
1603
1604 cl = git_cl.Changelist(issue=1234)
Josip Sokcevic340edc32021-07-08 17:01:46 +00001605 actual = cl._GetDescriptionForUpload(options=mock.Mock(
1606 bug=bug,
1607 fixed=fixed,
1608 reviewers=reviewers,
1609 tbrs=tbrs,
1610 add_owners_to=add_owners_to,
1611 message=initial_description),
1612 git_diff_args=None,
1613 files=list(owners_by_path))
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001614 self.assertEqual(expected_description, actual.description)
1615
1616 def testGetDescriptionForUpload(self):
1617 self.getDescriptionForUploadTest()
1618
1619 def testGetDescriptionForUpload_Bug(self):
1620 self.getDescriptionForUploadTest(
1621 bug='1234',
1622 expected_description='\n'.join([
1623 'desc',
1624 '',
1625 'Bug: prefix:1234',
1626 ]))
1627
1628 def testGetDescriptionForUpload_Fixed(self):
1629 self.getDescriptionForUploadTest(
1630 fixed='1234',
1631 expected_description='\n'.join([
1632 'desc',
1633 '',
1634 'Fixed: prefix:1234',
1635 ]))
1636
Josip Sokcevic340edc32021-07-08 17:01:46 +00001637 @mock.patch('git_cl.Changelist.GetIssue')
1638 def testGetDescriptionForUpload_BugFromBranch(self, mockGetIssue):
1639 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001640 self.getDescriptionForUploadTest(
1641 branch='bug-1234',
1642 expected_description='\n'.join([
1643 'desc',
1644 '',
1645 'Bug: prefix:1234',
1646 ]))
1647
Josip Sokcevic340edc32021-07-08 17:01:46 +00001648 @mock.patch('git_cl.Changelist.GetIssue')
1649 def testGetDescriptionForUpload_FixedFromBranch(self, mockGetIssue):
1650 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001651 self.getDescriptionForUploadTest(
1652 branch='fix-1234',
1653 expected_description='\n'.join([
1654 'desc',
1655 '',
1656 'Fixed: prefix:1234',
1657 ]))
1658
Josip Sokcevic340edc32021-07-08 17:01:46 +00001659 def testGetDescriptionForUpload_SkipBugFromBranchIfAlreadyUploaded(self):
1660 self.getDescriptionForUploadTest(
1661 branch='bug-1234',
1662 expected_description='desc',
1663 )
1664
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001665 def testGetDescriptionForUpload_AddOwnersToR(self):
1666 self.getDescriptionForUploadTest(
1667 reviewers=['a@example.com'],
1668 tbrs=['b@example.com'],
1669 add_owners_to='R',
1670 expected_description='\n'.join([
1671 'desc',
1672 '',
1673 'R=a@example.com, c@example.com',
1674 'TBR=b@example.com',
1675 ]))
1676
1677 def testGetDescriptionForUpload_AddOwnersToTBR(self):
1678 self.getDescriptionForUploadTest(
1679 reviewers=['a@example.com'],
1680 tbrs=['b@example.com'],
1681 add_owners_to='TBR',
1682 expected_description='\n'.join([
1683 'desc',
1684 '',
1685 'R=a@example.com',
1686 'TBR=b@example.com, c@example.com',
1687 ]))
1688
1689 def testGetDescriptionForUpload_AddOwnersToNoOwnersNeeded(self):
1690 self.getDescriptionForUploadTest(
1691 reviewers=['a@example.com', 'c@example.com'],
1692 tbrs=['b@example.com'],
1693 add_owners_to='TBR',
1694 expected_description='\n'.join([
1695 'desc',
1696 '',
1697 'R=a@example.com, c@example.com',
1698 'TBR=b@example.com',
1699 ]))
1700
1701 def testGetDescriptionForUpload_Reviewers(self):
1702 self.getDescriptionForUploadTest(
1703 reviewers=['a@example.com', 'b@example.com'],
1704 expected_description='\n'.join([
1705 'desc',
1706 '',
1707 'R=a@example.com, b@example.com',
1708 ]))
1709
1710 def testGetDescriptionForUpload_TBRs(self):
1711 self.getDescriptionForUploadTest(
1712 tbrs=['a@example.com', 'b@example.com'],
1713 expected_description='\n'.join([
1714 'desc',
1715 '',
1716 'TBR=a@example.com, b@example.com',
1717 ]))
1718
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001719 def test_desecription_append_footer(self):
1720 for init_desc, footer_line, expected_desc in [
1721 # Use unique desc first lines for easy test failure identification.
1722 ('foo', 'R=one', 'foo\n\nR=one'),
1723 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1724 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1725 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1726 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1727 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1728 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1729 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1730 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1731 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1732 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1733 ]:
1734 desc = git_cl.ChangeDescription(init_desc)
1735 desc.append_footer(footer_line)
1736 self.assertEqual(desc.description, expected_desc)
1737
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001738 def test_update_reviewers(self):
1739 data = [
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001740 ('foo', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001741 'foo'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001742 ('foo\nR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001743 'foo\nR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001744 ('foo\nTBR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001745 'foo\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001746 ('foo', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001747 'foo\n\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001748 ('foo\nR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001749 'foo\n\nR=a@c, xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001750 ('foo\nTBR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001751 'foo\n\nR=a@c\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001752 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001753 'foo\n\nR=a@c, yy\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001754 ('foo\nBUG=', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001755 'foo\nBUG=\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001756 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001757 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001758 ('foo', ['a@c', 'b@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001759 'foo\n\nR=a@c, b@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001760 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001761 'foo\nBar\n\nR=c@c\nBUG='),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001762 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001763 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001764 # Same as the line before, but full of whitespaces.
1765 (
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001766 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001767 'foo\nBar\n\nR=c@c\n BUG =',
1768 ),
1769 # Whitespaces aren't interpreted as new lines.
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001770 ('foo BUG=allo R=joe ', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001771 'foo BUG=allo R=joe\n\nR=c@c'),
1772 # Redundant TBRs get promoted to Rs
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001773 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001774 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001775 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001776 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001777 actual = []
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001778 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001779 obj = git_cl.ChangeDescription(orig)
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001780 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001781 actual.append(obj.description)
1782 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001783
Nodir Turakulov23b82142017-11-16 11:04:25 -08001784 def test_get_hash_tags(self):
1785 cases = [
1786 ('', []),
1787 ('a', []),
1788 ('[a]', ['a']),
1789 ('[aa]', ['aa']),
1790 ('[a ]', ['a']),
1791 ('[a- ]', ['a']),
1792 ('[a- b]', ['a-b']),
1793 ('[a--b]', ['a-b']),
1794 ('[a', []),
1795 ('[a]x', ['a']),
1796 ('[aa]x', ['aa']),
1797 ('[a b]', ['a-b']),
1798 ('[a b]', ['a-b']),
1799 ('[a__b]', ['a-b']),
1800 ('[a] x', ['a']),
1801 ('[a][b]', ['a', 'b']),
1802 ('[a] [b]', ['a', 'b']),
1803 ('[a][b]x', ['a', 'b']),
1804 ('[a][b] x', ['a', 'b']),
1805 ('[a]\n[b]', ['a']),
1806 ('[a\nb]', []),
1807 ('[a][', ['a']),
1808 ('Revert "[a] feature"', ['a']),
1809 ('Reland "[a] feature"', ['a']),
1810 ('Revert: [a] feature', ['a']),
1811 ('Reland: [a] feature', ['a']),
1812 ('Revert "Reland: [a] feature"', ['a']),
1813 ('Foo: feature', ['foo']),
1814 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001815 ('Change Foo::Bar', []),
1816 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001817 ('Revert "Foo bar: feature"', ['foo-bar']),
1818 ('Reland "Foo bar: feature"', ['foo-bar']),
1819 ]
1820 for desc, expected in cases:
1821 change_desc = git_cl.ChangeDescription(desc)
1822 actual = change_desc.get_hash_tags()
1823 self.assertEqual(
1824 actual,
1825 expected,
1826 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1827
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001828 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'main'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001829 self.assertEqual(None, git_cl.GetTargetRef(None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001830 'refs/remotes/origin/main',
1831 'main'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001832
wittman@chromium.org455dc922015-01-26 20:15:50 +00001833 # Check default target refs for branches.
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001834 self.assertEqual('refs/heads/main',
1835 git_cl.GetTargetRef('origin', 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001836 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001837 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001838 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001839 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001840 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001841 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001842 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001843 self.assertEqual('refs/branch-heads/123',
1844 git_cl.GetTargetRef('origin',
1845 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001846 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001847 self.assertEqual('refs/diff/test',
1848 git_cl.GetTargetRef('origin',
1849 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001850 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001851 self.assertEqual('refs/heads/chrome/m42',
1852 git_cl.GetTargetRef('origin',
1853 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001854 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001855
1856 # Check target refs for user-specified target branch.
1857 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1858 'refs/remotes/branch-heads/123'):
1859 self.assertEqual('refs/branch-heads/123',
1860 git_cl.GetTargetRef('origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001861 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001862 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001863 for branch in ('origin/main', 'remotes/origin/main',
1864 'refs/remotes/origin/main'):
1865 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001866 git_cl.GetTargetRef('origin',
1867 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001868 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001869 for branch in ('main', 'heads/main', 'refs/heads/main'):
1870 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001871 git_cl.GetTargetRef('origin',
1872 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001873 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001874
Edward Lemurda4b6c62020-02-13 00:28:40 +00001875 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1876 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001877 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001878 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1879
Edward Lemur85153282020-02-14 22:06:29 +00001880 def assertIssueAndPatchset(
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001881 self, branch='main', issue='123456', patchset='7',
Edward Lemur85153282020-02-14 22:06:29 +00001882 git_short_host='chromium'):
1883 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001884 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001885 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001886 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001887 self.assertEqual(
1888 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001889 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001890
Edward Lemur85153282020-02-14 22:06:29 +00001891 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001892 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001893 self.mockGit.config['remote.origin.url'] = (
1894 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001895 gerrit_util.GetChangeDetail.return_value = {
1896 'current_revision': '7777777777',
1897 'revisions': {
1898 '1111111111': {
1899 '_number': 1,
1900 'fetch': {'http': {
1901 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1902 'ref': 'refs/changes/56/123456/1',
1903 }},
1904 },
1905 '7777777777': {
1906 '_number': 7,
1907 'fetch': {'http': {
1908 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1909 'ref': 'refs/changes/56/123456/7',
1910 }},
1911 },
1912 },
1913 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001914
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001915 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001916 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001917 self.calls += [
1918 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1919 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001920 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001921 ]
1922 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001923 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001924
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001925 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001926 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001927 self.calls += [
1928 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1929 'refs/changes/56/123456/7'],), ''),
1930 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001931 ]
Edward Lemur85153282020-02-14 22:06:29 +00001932 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1933 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001934
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001935 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001936 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001937 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001938 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001939 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001940 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001941 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001942 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001943 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001944
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001945 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001946 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001947 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001948 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001949 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001950 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001951 ]
1952 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001953 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001954 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001955
Aaron Gable697a91b2018-01-19 15:20:15 -08001956 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001957 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001958 self.calls += [
1959 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1960 'refs/changes/56/123456/1'],), ''),
1961 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001962 ]
1963 self.assertEqual(git_cl.main(
1964 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1965 0)
Edward Lemur85153282020-02-14 22:06:29 +00001966 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001967
Edward Lemurd55c5072020-02-20 01:09:07 +00001968 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001969 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001970 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001971 self.calls += [
1972 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001973 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001974 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001975 ]
1976 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001977 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001978 self.assertEqual(
1979 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1980 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001981
Edward Lemurda4b6c62020-02-13 00:28:40 +00001982 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001983 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001984 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001985 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001986 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001987 self.mockGit.config['remote.origin.url'] = (
1988 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001989 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001990 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001991 self.assertEqual(
1992 'change 123456 at https://chromium-review.googlesource.com does not '
1993 'exist or you have no access to it\n',
1994 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001995
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001996 def _checkout_calls(self):
1997 return [
1998 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001999 'branch\\..*\\.gerritissue'], ),
2000 ('branch.ger-branch.gerritissue 123456\n'
2001 'branch.gbranch654.gerritissue 654321\n')),
2002 ]
2003
2004 def test_checkout_gerrit(self):
2005 """Tests git cl checkout <issue>."""
2006 self.calls = self._checkout_calls()
2007 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
2008 self.assertEqual(0, git_cl.main(['checkout', '123456']))
2009
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00002010 def test_checkout_not_found(self):
2011 """Tests git cl checkout <issue>."""
2012 self.calls = self._checkout_calls()
2013 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2014
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002015 def test_checkout_no_branch_issues(self):
2016 """Tests git cl checkout <issue>."""
2017 self.calls = [
2018 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07002019 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002020 ]
2021 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2022
Edward Lemur26964072020-02-19 19:18:51 +00002023 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00002024 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002025 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002026 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002027 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2028 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00002029 self.mockGit.config['remote.origin.url'] = (
2030 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00002031 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002032 cl.branch = 'main'
2033 cl.branchref = 'refs/heads/main'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002034 return cl
2035
Edward Lemurd55c5072020-02-20 01:09:07 +00002036 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002037 def test_gerrit_ensure_authenticated_missing(self):
2038 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002039 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002040 })
Edward Lemurd55c5072020-02-20 01:09:07 +00002041 with self.assertRaises(SystemExitMock):
2042 cl.EnsureAuthenticated(force=False)
2043 self.assertEqual(
2044 'Credentials for the following hosts are required:\n'
2045 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002046 'These are read from ~%(sep)s.gitcookies '
2047 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00002048 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002049 'https://chromium-review.googlesource.com/new-password\n' % {
2050 'sep': os.sep,
2051 'netrc': NETRC_FILENAME,
2052 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002053
2054 def test_gerrit_ensure_authenticated_conflict(self):
2055 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002056 'chromium.googlesource.com':
2057 ('git-one.example.com', None, 'secret1'),
2058 'chromium-review.googlesource.com':
2059 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002060 })
2061 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002062 (('ask_for_data', 'If you know what you are doing '
2063 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002064 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2065
2066 def test_gerrit_ensure_authenticated_ok(self):
2067 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002068 'chromium.googlesource.com':
2069 ('git-same.example.com', None, 'secret'),
2070 'chromium-review.googlesource.com':
2071 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002072 })
2073 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2074
tandrii@chromium.org28253532016-04-14 13:46:56 +00002075 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00002076 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
2077 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00002078 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2079
Eric Boren2fb63102018-10-05 13:05:03 +00002080 def test_gerrit_ensure_authenticated_bearer_token(self):
2081 cl = self._test_gerrit_ensure_authenticated_common(auth={
2082 'chromium.googlesource.com':
2083 ('', None, 'secret'),
2084 'chromium-review.googlesource.com':
2085 ('', None, 'secret'),
2086 })
2087 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2088 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2089 'chromium.googlesource.com')
2090 self.assertTrue('Bearer' in header)
2091
Daniel Chengcf6269b2019-05-18 01:02:12 +00002092 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00002093 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002094 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002095 (('logging.warning',
2096 'Ignoring branch %(branch)s with non-https remote '
2097 '%(remote)s', {
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002098 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002099 'remote': 'custom-scheme://repo'}
2100 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00002101 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002102 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2103 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2104 mock.patch('logging.warning',
2105 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002106 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002107 cl.branch = 'main'
2108 cl.branchref = 'refs/heads/main'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002109 cl.lookedup_issue = True
2110 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2111
Florian Mayerae510e82020-01-30 21:04:48 +00002112 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00002113 self.mockGit.config['remote.origin.url'] = (
2114 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00002115 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002116 (('logging.error',
2117 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2118 'but it doesn\'t exist.', {
2119 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002120 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002121 'url': 'git@somehost.example:foo/bar.git'}
2122 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00002123 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002124 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2125 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2126 mock.patch('logging.error',
2127 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00002128 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002129 cl.branch = 'main'
2130 cl.branchref = 'refs/heads/main'
Florian Mayerae510e82020-01-30 21:04:48 +00002131 cl.lookedup_issue = True
2132 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2133
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002134 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002135 self.mockGit.config['branch.main.gerritissue'] = '123'
2136 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002137 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00002138 self.mockGit.config['remote.origin.url'] = (
2139 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002140 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00002141 (('SetReview', 'chromium-review.googlesource.com',
2142 'infra%2Finfra~123', None,
2143 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002144 ]
tandriid9e5ce52016-07-13 02:32:59 -07002145
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002146 def _cmd_set_quick_run_gerrit(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002147 self.mockGit.config['branch.main.gerritissue'] = '123'
2148 self.mockGit.config['branch.main.gerritserver'] = (
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002149 'https://chromium-review.googlesource.com')
2150 self.mockGit.config['remote.origin.url'] = (
2151 'https://chromium.googlesource.com/infra/infra')
2152 self.calls = [
2153 (('SetReview', 'chromium-review.googlesource.com',
2154 'infra%2Finfra~123', None,
2155 {'Commit-Queue': 1, 'Quick-Run': 1}, None, None), ''),
2156 ]
2157
tandriid9e5ce52016-07-13 02:32:59 -07002158 def test_cmd_set_commit_gerrit_clear(self):
2159 self._cmd_set_commit_gerrit_common(0)
2160 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2161
2162 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002163 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002164 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2165
tandriid9e5ce52016-07-13 02:32:59 -07002166 def test_cmd_set_commit_gerrit(self):
2167 self._cmd_set_commit_gerrit_common(2)
2168 self.assertEqual(0, git_cl.main(['set-commit']))
2169
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002170 def test_cmd_set_quick_run_gerrit(self):
2171 self._cmd_set_quick_run_gerrit()
2172 self.assertEqual(0, git_cl.main(['set-commit', '-q']))
2173
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002174 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002175 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002176 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002177
2178 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002179 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002180
Edward Lemurda4b6c62020-02-13 00:28:40 +00002181 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07002182 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07002183 try:
2184 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00002185 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00002186 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00002187 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07002188
2189 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07002190 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002191 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002192 return 'foobar'
2193
Edward Lemurda4b6c62020-02-13 00:28:40 +00002194 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07002195 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002196 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002197 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002198 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002199
iannuccie53c9352016-08-17 14:40:40 -07002200 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002201
iannuccie53c9352016-08-17 14:40:40 -07002202 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002203 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002204 return 'foobar'
2205
Edward Lemurda4b6c62020-02-13 00:28:40 +00002206 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2207 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002208 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002209 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002210
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002211 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002212 self.mockGit.config['remote.origin.url'] = (
2213 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002214 gerrit_util.GetChangeDetail.return_value = {
2215 'current_revision': 'sha1',
2216 'revisions': {'sha1': {
2217 'commit': {'message': 'foobar'},
2218 }},
2219 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002220 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002221 'description',
2222 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2223 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002224 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002225
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002226 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002227 mock.patch('git_cl.Changelist', ChangelistMock).start()
2228 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002229
2230 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2231 self.assertEqual('hihi', ChangelistMock.desc)
2232
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002233 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002234 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002235
2236 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002237 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002238 '# Enter a description of the change.\n'
2239 '# This will be displayed on the codereview site.\n'
2240 '# The first line will also be used as the subject of the review.\n'
2241 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002242 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002243 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002244 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002245 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002246 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002247
Edward Lemur6c6827c2020-02-06 21:15:18 +00002248 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002249 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002250
Edward Lemurda4b6c62020-02-13 00:28:40 +00002251 mock.patch('git_cl.Changelist.FetchDescription',
2252 lambda *args: current_desc).start()
2253 mock.patch('git_cl.Changelist.UpdateDescription',
2254 UpdateDescription).start()
2255 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002256
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002257 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002258 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002259
Dan Beamd8b04ca2019-10-10 21:23:26 +00002260 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2261 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2262
2263 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002264 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002265 '# Enter a description of the change.\n'
2266 '# This will be displayed on the codereview site.\n'
2267 '# The first line will also be used as the subject of the review.\n'
2268 '#--------------------This line is 72 characters long'
2269 '--------------------\n'
2270 'Some.\n\nFixed: 123\nChange-Id: xxx',
2271 desc)
2272 return desc
2273
Edward Lemurda4b6c62020-02-13 00:28:40 +00002274 mock.patch('git_cl.Changelist.FetchDescription',
2275 lambda *args: current_desc).start()
2276 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002277
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002278 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002279 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002280
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002281 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002282 mock.patch('git_cl.Changelist', ChangelistMock).start()
2283 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002284
2285 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2286 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2287
kmarshall3bff56b2016-06-06 18:31:47 -07002288 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002289 self.calls = [
2290 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002291 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002292 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002293 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002294 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002295 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002296
Edward Lemurda4b6c62020-02-13 00:28:40 +00002297 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002298 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002299 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002300 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002301 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002302
2303 self.assertEqual(0, git_cl.main(['archive', '-f']))
2304
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002305 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002306 self.calls = [
2307 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002308 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002309 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2310 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002311 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2312 ((['git', 'branch', '-D', 'foo'],), '')
2313 ]
2314
Edward Lemurda4b6c62020-02-13 00:28:40 +00002315 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002316 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002317 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002318 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002319 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002320
2321 self.assertEqual(0, git_cl.main(['archive', '-f']))
2322
kmarshall3bff56b2016-06-06 18:31:47 -07002323 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002324 self.calls = [
2325 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002326 'refs/heads/main'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002327 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002328 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002329
Edward Lemurda4b6c62020-02-13 00:28:40 +00002330 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002331 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002332 [(MockChangelistWithBranchAndIssue('main', 1),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002333 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002334
2335 self.assertEqual(1, git_cl.main(['archive', '-f']))
2336
2337 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002338 self.calls = [
2339 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002340 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002341 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002342 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002343
Edward Lemurda4b6c62020-02-13 00:28:40 +00002344 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002345 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002346 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002347 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002348 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002349
kmarshall9249e012016-08-23 12:02:16 -07002350 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2351
2352 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002353 self.calls = [
2354 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002355 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002356 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002357 ((['git', 'branch', '-D', 'foo'],), '')
2358 ]
kmarshall9249e012016-08-23 12:02:16 -07002359
Edward Lemurda4b6c62020-02-13 00:28:40 +00002360 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002361 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002362 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002363 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002364 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002365
2366 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002367
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002368 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002369 self.calls = [
2370 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002371 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002372 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002373 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2374 'refs/tags/git-cl-archived-456-foo'),
2375 ((['git', 'branch', '-D', 'foo'],), CERR1),
2376 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2377 'refs/tags/git-cl-archived-456-foo'),
2378 ]
2379
Edward Lemurda4b6c62020-02-13 00:28:40 +00002380 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002381 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002382 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002383 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002384 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002385
2386 self.assertEqual(0, git_cl.main(['archive', '-f']))
2387
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002388 def test_archive_with_format(self):
2389 self.calls = [
2390 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002391 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002392 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2393 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2394 ((['git', 'branch', '-D', 'foo'], ), ''),
2395 ]
2396
2397 mock.patch('git_cl.get_cl_statuses',
2398 lambda branches, fine_grained, max_processes:
2399 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2400
2401 self.assertEqual(
2402 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2403
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002404 def test_cmd_issue_erase_existing(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002405 self.mockGit.config['branch.main.gerritissue'] = '123'
2406 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002407 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002408 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002409 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002410 ]
2411 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002412 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2413 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002414
Aaron Gable400e9892017-07-12 15:31:21 -07002415 def test_cmd_issue_erase_existing_with_change_id(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002416 self.mockGit.config['branch.main.gerritissue'] = '123'
2417 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002418 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002419 mock.patch('git_cl.Changelist.FetchDescription',
2420 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002421 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002422 ((['git', 'log', '-1', '--format=%B'],),
2423 'This is a description\n\nChange-Id: Ideadbeef'),
2424 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002425 ]
2426 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002427 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2428 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002429
phajdan.jre328cf92016-08-22 04:12:17 -07002430 def test_cmd_issue_json(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002431 self.mockGit.config['branch.main.gerritissue'] = '123'
2432 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002433 'https://chromium-review.googlesource.com')
Nodir Turakulov27379632021-03-17 18:53:29 +00002434 self.mockGit.config['remote.origin.url'] = (
2435 'https://chromium.googlesource.com/chromium/src'
2436 )
2437 self.calls = [(
2438 (
2439 'write_json',
2440 'output.json',
2441 {
2442 'issue': 123,
2443 'issue_url': 'https://chromium-review.googlesource.com/123',
2444 'gerrit_host': 'chromium-review.googlesource.com',
2445 'gerrit_project': 'chromium/src',
2446 },
2447 ),
2448 '',
2449 )]
phajdan.jre328cf92016-08-22 04:12:17 -07002450 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2451
tandrii16e0b4e2016-06-07 10:34:28 -07002452 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002453 mock.patch(
2454 'git_cl.os.path.abspath',
2455 lambda path: self._mocked_call(['abspath', path])).start()
2456 mock.patch(
2457 'git_cl.os.path.exists',
2458 lambda path: self._mocked_call(['exists', path])).start()
2459 mock.patch(
2460 'git_cl.gclient_utils.FileRead',
2461 lambda path: self._mocked_call(['FileRead', path])).start()
2462 mock.patch(
2463 'git_cl.gclient_utils.rm_file_or_tree',
2464 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002465 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002466 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002467 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002468 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002469
2470 def test_GerritCommitMsgHookCheck_custom_hook(self):
2471 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002472 self.calls += [((['exists',
2473 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2474 ((['FileRead',
2475 os.path.join('.git', 'hooks', 'commit-msg')], ),
2476 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002477 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002478
2479 def test_GerritCommitMsgHookCheck_not_exists(self):
2480 cl = self._common_GerritCommitMsgHookCheck()
2481 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002482 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002483 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002484 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002485
2486 def test_GerritCommitMsgHookCheck(self):
2487 cl = self._common_GerritCommitMsgHookCheck()
2488 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002489 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2490 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002491 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002492 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002493 ((['rm_file_or_tree',
2494 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002495 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002496 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002497
tandriic4344b52016-08-29 06:04:54 -07002498 def test_GerritCmdLand(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002499 self.mockGit.config['branch.main.gerritsquashhash'] = 'deadbeaf'
2500 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002501 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002502 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002503 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002504 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002505 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002506 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002507 'labels': {},
2508 'current_revision': 'deadbeaf',
2509 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002510 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002511 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002512 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002513 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2514 }
Xinan Lin1bd4ffa2021-07-28 00:54:22 +00002515 cl.SubmitIssue = lambda: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002516 self.assertEqual(0, cl.CMDLand(force=True,
2517 bypass_hooks=True,
2518 verbose=True,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00002519 parallel=False,
2520 resultdb=False,
2521 realm=None))
Edward Lemur73c76702020-02-06 23:57:18 +00002522 self.assertIn(
2523 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002524 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002525 self.assertIn(
2526 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002527 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002528
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002529 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lesmeseeca9c62020-11-20 00:00:17 +00002530 mock.patch('git_cl.Changelist.GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002531
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002532 def test_gerrit_change_detail_cache_simple(self):
2533 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002534 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002535 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002536 cl1._cached_remote_url = (
2537 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002538 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002539 cl2._cached_remote_url = (
2540 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002541 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2542 self.assertEqual(cl1._GetChangeDetail(), 'a')
2543 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002544
2545 def test_gerrit_change_detail_cache_options(self):
2546 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002547 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002548 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002549 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002550 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2551 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2552 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2553 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2554 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2555 self.assertEqual(cl._GetChangeDetail(), 'cab')
2556
2557 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2558 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2559 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2560 self.assertEqual(cl._GetChangeDetail(), 'cab')
2561
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002562 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002563 gerrit_util.GetChangeDetail.return_value = {
2564 'current_revision': 'rev1',
2565 'revisions': {
2566 'rev1': {'commit': {'message': 'desc1'}},
2567 },
2568 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002569
2570 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002571 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002572 cl._cached_remote_url = (
2573 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002574 self.assertEqual(cl.FetchDescription(), 'desc1')
2575 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002576
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002577 def test_print_current_creds(self):
2578 class CookiesAuthenticatorMock(object):
2579 def __init__(self):
2580 self.gitcookies = {
2581 'host.googlesource.com': ('user', 'pass'),
2582 'host-review.googlesource.com': ('user', 'pass'),
2583 }
2584 self.netrc = self
2585 self.netrc.hosts = {
2586 'github.com': ('user2', None, 'pass2'),
2587 'host2.googlesource.com': ('user3', None, 'pass'),
2588 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002589 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2590 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002591 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2592 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2593 ' Host\t User\t Which file',
2594 '============================\t=====\t===========',
2595 'host-review.googlesource.com\t user\t.gitcookies',
2596 ' host.googlesource.com\t user\t.gitcookies',
2597 ' host2.googlesource.com\tuser3\t .netrc',
2598 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002599 sys.stdout.seek(0)
2600 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002601 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2602 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2603 ' Host\tUser\t Which file',
2604 '============================\t====\t===========',
2605 'host-review.googlesource.com\tuser\t.gitcookies',
2606 ' host.googlesource.com\tuser\t.gitcookies',
2607 ])
2608
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002609 def _common_creds_check_mocks(self):
2610 def exists_mock(path):
2611 dirname = os.path.dirname(path)
2612 if dirname == os.path.expanduser('~'):
2613 dirname = '~'
2614 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002615 if base in (NETRC_FILENAME, '.gitcookies'):
2616 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002617 # git cl also checks for existence other files not relevant to this test.
2618 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002619 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002620 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002621 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002622 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002623
2624 def test_creds_check_gitcookies_not_configured(self):
2625 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002626 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2627 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002628 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002629 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2630 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2631 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2632 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2633 'or Ctrl+C to abort'), ''),
2634 (([
2635 'git', 'config', '--global', 'http.cookiefile',
2636 os.path.expanduser(os.path.join('~', '.gitcookies'))
2637 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002638 ]
2639 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002640 self.assertTrue(
2641 sys.stdout.getvalue().startswith(
2642 'You seem to be using outdated .netrc for git credentials:'))
2643 self.assertIn(
2644 '\nConfigured git to use .gitcookies from',
2645 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002646
2647 def test_creds_check_gitcookies_configured_custom_broken(self):
2648 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002649 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2650 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002651 custom_cookie_path = ('C:\\.gitcookies'
2652 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002653 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002654 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2655 ((['git', 'config', '--global', 'http.cookiefile'], ),
2656 custom_cookie_path),
2657 (('os.path.exists', custom_cookie_path), False),
2658 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2659 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2660 (([
2661 'git', 'config', '--global', 'http.cookiefile',
2662 os.path.expanduser(os.path.join('~', '.gitcookies'))
2663 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002664 ]
2665 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002666 self.assertIn(
2667 'WARNING: You have configured custom path to .gitcookies: ',
2668 sys.stdout.getvalue())
2669 self.assertIn(
2670 'However, your configured .gitcookies file is missing.',
2671 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002672
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002673 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002674 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002675 self.mockGit.config['remote.origin.url'] = (
2676 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002677 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002678 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002679 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002680 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002681 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002682 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002683
Edward Lemurda4b6c62020-02-13 00:28:40 +00002684 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2685 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002686 self.mockGit.config['remote.origin.url'] = (
2687 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002688 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002689 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002690 'current_revision': 'ba5eba11',
2691 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002692 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002693 '_number': 1,
2694 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002695 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002696 '_number': 2,
2697 },
2698 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002699 'messages': [
2700 {
2701 u'_revision_number': 1,
2702 u'author': {
2703 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002704 u'email': u'could-be-anything@example.com',
2705 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002706 },
2707 u'date': u'2017-03-15 20:08:45.000000000',
2708 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002709 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov899785a2021-07-09 12:45:37 +00002710 u'tag': u'autogenerated:cv:dry-run'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002711 },
2712 {
2713 u'_revision_number': 2,
2714 u'author': {
2715 u'_account_id': 11151243,
2716 u'email': u'owner@example.com',
2717 u'name': u'owner'
2718 },
2719 u'date': u'2017-03-16 20:00:41.000000000',
2720 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2721 u'message': u'PTAL',
2722 },
2723 {
2724 u'_revision_number': 2,
2725 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002726 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002727 u'email': u'reviewer@example.com',
2728 u'name': u'reviewer'
2729 },
2730 u'date': u'2017-03-17 05:19:37.500000000',
2731 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2732 u'message': u'Patch Set 2: Code-Review+1',
2733 },
Josip Sokcevic266129c2021-11-09 00:22:00 +00002734 {
2735 u'_revision_number': 2,
2736 u'author': {
2737 u'_account_id': 42,
2738 u'name': u'reviewer'
2739 },
2740 u'date': u'2017-03-17 05:19:37.900000000',
2741 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d0000',
2742 u'message': u'A bot with no email set',
2743 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002744 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002745 }
2746 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002747 (('GetChangeComments', 'chromium-review.googlesource.com',
2748 'infra%2Finfra~1'), {
2749 '/COMMIT_MSG': [
2750 {
2751 'author': {
2752 'email': u'reviewer@example.com'
2753 },
2754 'updated': u'2017-03-17 05:19:37.500000000',
2755 'patch_set': 2,
2756 'side': 'REVISION',
2757 'message': 'Please include a bug link',
2758 },
2759 ],
2760 'codereview.settings': [
2761 {
2762 'author': {
2763 'email': u'owner@example.com'
2764 },
2765 'updated': u'2017-03-16 20:00:41.000000000',
2766 'patch_set': 2,
2767 'side': 'PARENT',
2768 'line': 42,
2769 'message': 'I removed this because it is bad',
2770 },
2771 ]
2772 }),
2773 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2774 'infra%2Finfra~1'), {}),
2775 ] * 2 + [(('write_json', 'output.json', [{
2776 u'date':
2777 u'2017-03-16 20:00:41.000000',
2778 u'message': (u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2779 u' Base, Line 42: https://crrev.com/c/1/2/'
2780 u'codereview.settings#b42\n' +
2781 u' I removed this because it is bad\n'),
2782 u'autogenerated':
2783 False,
2784 u'approval':
2785 False,
2786 u'disapproval':
2787 False,
2788 u'sender':
2789 u'owner@example.com'
2790 }, {
2791 u'date':
2792 u'2017-03-17 05:19:37.500000',
2793 u'message':
2794 (u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2795 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
2796 u' Please include a bug link\n'),
2797 u'autogenerated':
2798 False,
2799 u'approval':
2800 False,
2801 u'disapproval':
2802 False,
2803 u'sender':
2804 u'reviewer@example.com'
2805 }]), '')]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002806 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002807 git_cl._CommentSummary(
2808 message=(u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2809 u' Base, Line 42: https://crrev.com/c/1/2/' +
2810 u'codereview.settings#b42\n' +
2811 u' I removed this because it is bad\n'),
2812 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
2813 autogenerated=False,
2814 disapproval=False,
2815 approval=False,
2816 sender=u'owner@example.com'),
2817 git_cl._CommentSummary(message=(
2818 u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2819 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002820 u' Please include a bug link\n'),
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002821 date=datetime.datetime(2017, 3, 17, 5, 19, 37,
2822 500000),
2823 autogenerated=False,
2824 disapproval=False,
2825 approval=False,
2826 sender=u'reviewer@example.com'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002827 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002828 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002829 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002830 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002831 self.assertEqual(
2832 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2833
2834 def test_git_cl_comments_robot_comments(self):
2835 # git cl comments also fetches robot comments (which are considered a type
2836 # of autogenerated comment), and unlike other types of comments, only robot
2837 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002838 self.mockGit.config['remote.origin.url'] = (
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002839 'https://x.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002840 gerrit_util.GetChangeDetail.return_value = {
2841 'owner': {'email': 'owner@example.com'},
2842 'current_revision': 'ba5eba11',
2843 'revisions': {
2844 'deadbeaf': {
2845 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002846 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002847 'ba5eba11': {
2848 '_number': 2,
2849 },
2850 },
2851 'messages': [
2852 {
2853 u'_revision_number': 1,
2854 u'author': {
2855 u'_account_id': 1111084,
2856 u'email': u'commit-bot@chromium.org',
2857 u'name': u'Commit Bot'
2858 },
2859 u'date': u'2017-03-15 20:08:45.000000000',
2860 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2861 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2862 u'tag': u'autogenerated:cq:dry-run'
2863 },
2864 {
2865 u'_revision_number': 1,
2866 u'author': {
2867 u'_account_id': 123,
2868 u'email': u'tricium@serviceaccount.com',
2869 u'name': u'Tricium'
2870 },
2871 u'date': u'2017-03-16 20:00:41.000000000',
2872 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2873 u'message': u'(1 comment)',
2874 u'tag': u'autogenerated:tricium',
2875 },
2876 {
2877 u'_revision_number': 1,
2878 u'author': {
2879 u'_account_id': 123,
2880 u'email': u'tricium@serviceaccount.com',
2881 u'name': u'Tricium'
2882 },
2883 u'date': u'2017-03-16 20:00:41.000000000',
2884 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2885 u'message': u'(1 comment)',
2886 u'tag': u'autogenerated:tricium',
2887 },
2888 {
2889 u'_revision_number': 2,
2890 u'author': {
2891 u'_account_id': 123,
2892 u'email': u'tricium@serviceaccount.com',
2893 u'name': u'reviewer'
2894 },
2895 u'date': u'2017-03-17 05:30:37.000000000',
2896 u'tag': u'autogenerated:tricium',
2897 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2898 u'message': u'(1 comment)',
2899 },
2900 ]
2901 }
2902 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002903 (('GetChangeComments', 'x-review.googlesource.com', 'infra%2Finfra~1'),
2904 {}),
2905 (('GetChangeRobotComments', 'x-review.googlesource.com',
2906 'infra%2Finfra~1'), {
2907 'codereview.settings': [
2908 {
2909 u'author': {
2910 u'email': u'tricium@serviceaccount.com'
2911 },
2912 u'updated': u'2017-03-17 05:30:37.000000000',
2913 u'robot_run_id': u'5565031076855808',
2914 u'robot_id': u'Linter/Category',
2915 u'tag': u'autogenerated:tricium',
2916 u'patch_set': 2,
2917 u'side': u'REVISION',
2918 u'message': u'Linter warning message text',
2919 u'line': 32,
2920 },
2921 ],
2922 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002923 ]
2924 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002925 git_cl._CommentSummary(
2926 date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2927 message=(u'(1 comment)\n\ncodereview.settings\n'
2928 u' PS2, Line 32: https://x-review.googlesource.com/c/1/2/'
2929 u'codereview.settings#32\n'
2930 u' Linter warning message text\n'),
2931 sender=u'tricium@serviceaccount.com',
2932 autogenerated=True,
2933 approval=False,
2934 disapproval=False)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002935 ]
2936 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002937 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002938 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002939
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002940 def test_get_remote_url_with_mirror(self):
2941 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002942
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002943 def selective_os_path_isdir_mock(path):
2944 if path == '/cache/this-dir-exists':
2945 return self._mocked_call('os.path.isdir', path)
2946 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002947
Edward Lemurda4b6c62020-02-13 00:28:40 +00002948 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002949
2950 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002951 self.mockGit.config['remote.origin.url'] = (
2952 '/cache/this-dir-exists')
2953 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2954 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002955 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002956 (('os.path.isdir', '/cache/this-dir-exists'),
2957 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002958 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002959 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002960 self.assertEqual(cl.GetRemoteUrl(), url)
2961 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2962
Edward Lemur298f2cf2019-02-22 21:40:39 +00002963 def test_get_remote_url_non_existing_mirror(self):
2964 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002965
Edward Lemur298f2cf2019-02-22 21:40:39 +00002966 def selective_os_path_isdir_mock(path):
2967 if path == '/cache/this-dir-doesnt-exist':
2968 return self._mocked_call('os.path.isdir', path)
2969 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002970
Edward Lemurda4b6c62020-02-13 00:28:40 +00002971 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2972 mock.patch('logging.error',
2973 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002974
Edward Lemur26964072020-02-19 19:18:51 +00002975 self.mockGit.config['remote.origin.url'] = (
2976 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002977 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002978 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2979 False),
2980 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002981 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2982 'but it doesn\'t exist.', {
2983 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002984 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002985 'url': '/cache/this-dir-doesnt-exist'}
2986 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002987 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002988 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002989 self.assertIsNone(cl.GetRemoteUrl())
2990
2991 def test_get_remote_url_misconfigured_mirror(self):
2992 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002993
Edward Lemur298f2cf2019-02-22 21:40:39 +00002994 def selective_os_path_isdir_mock(path):
2995 if path == '/cache/this-dir-exists':
2996 return self._mocked_call('os.path.isdir', path)
2997 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002998
Edward Lemurda4b6c62020-02-13 00:28:40 +00002999 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
3000 mock.patch('logging.error',
3001 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00003002
Edward Lemur26964072020-02-19 19:18:51 +00003003 self.mockGit.config['remote.origin.url'] = (
3004 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00003005 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00003006 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00003007 (('logging.error',
3008 'Remote "%(remote)s" for branch "%(branch)s" points to '
3009 '"%(cache_path)s", but it is misconfigured.\n'
3010 '"%(cache_path)s" must be a git repo and must have a remote named '
3011 '"%(remote)s" pointing to the git host.', {
3012 'remote': 'origin',
3013 'cache_path': '/cache/this-dir-exists',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00003014 'branch': 'main'}
Edward Lemur298f2cf2019-02-22 21:40:39 +00003015 ), None),
3016 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003017 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00003018 self.assertIsNone(cl.GetRemoteUrl())
3019
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003020 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00003021 self.mockGit.config['remote.origin.url'] = (
3022 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00003023 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003024 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3025
3026 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00003027 mock.patch('logging.error',
3028 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00003029
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003030 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00003031 (('logging.error',
3032 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
3033 'but it doesn\'t exist.', {
3034 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00003035 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00003036 'url': ''}
3037 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003038 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003039 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003040 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003041
Josip Sokcevicc39ab992020-09-24 20:09:15 +00003042 def test_gerrit_new_default(self):
3043 self._run_gerrit_upload_test(
3044 [],
3045 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
3046 [],
3047 squash=False,
3048 squash_mode='override_nosquash',
3049 change_id='I123456789',
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00003050 default_branch='main')
Josip Sokcevicc39ab992020-09-24 20:09:15 +00003051
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003052
Edward Lemur9aa1a962020-02-25 00:58:38 +00003053class ChangelistTest(unittest.TestCase):
mlcui3da91712021-05-05 10:00:30 +00003054 LAST_COMMIT_SUBJECT = 'Fixes goat teleporter destination to be Australia'
3055
3056 def _mock_run_git(commands):
3057 if commands == ['show', '-s', '--format=%s', 'HEAD']:
3058 return ChangelistTest.LAST_COMMIT_SUBJECT
3059
Edward Lemur227d5102020-02-25 23:45:35 +00003060 def setUp(self):
3061 super(ChangelistTest, self).setUp()
3062 mock.patch('gclient_utils.FileRead').start()
3063 mock.patch('gclient_utils.FileWrite').start()
3064 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
3065 mock.patch(
3066 'git_cl.Changelist.GetCodereviewServer',
3067 return_value='https://chromium-review.googlesource.com').start()
3068 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
3069 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
3070 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
Dirk Pranke6f0df682021-06-25 00:42:33 +00003071 mock.patch('git_cl.Changelist.GetUsePython3', return_value=False).start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003072 mock.patch(
3073 'git_cl.Changelist.GetRemoteBranch',
3074 return_value=('origin', 'refs/remotes/origin/main')).start()
Edward Lemur227d5102020-02-25 23:45:35 +00003075 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
3076 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
Aleksey Khoroshilov35ef5ad2022-06-03 18:29:25 +00003077 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Edward Lemur227d5102020-02-25 23:45:35 +00003078 mock.patch('git_cl.time_time').start()
3079 mock.patch('metrics.collector').start()
3080 mock.patch('subprocess2.Popen').start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003081 mock.patch(
3082 'git_cl.Changelist.GetGerritProject', return_value='project').start()
Edward Lemur227d5102020-02-25 23:45:35 +00003083 self.addCleanup(mock.patch.stopall)
3084 self.temp_count = 0
3085
Edward Lemur227d5102020-02-25 23:45:35 +00003086 def testRunHook(self):
3087 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003088 'more_cc': ['cc@example.com', 'more@example.com'],
3089 'errors': [],
3090 'notifications': [],
3091 'warnings': [],
Edward Lemur227d5102020-02-25 23:45:35 +00003092 }
3093 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003094 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur227d5102020-02-25 23:45:35 +00003095 mockProcess = mock.Mock()
3096 mockProcess.wait.return_value = 0
3097 subprocess2.Popen.return_value = mockProcess
3098
3099 cl = git_cl.Changelist()
3100 results = cl.RunHook(
3101 committing=True,
3102 may_prompt=True,
3103 verbose=2,
3104 parallel=True,
3105 upstream='upstream',
3106 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003107 all_files=True,
3108 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003109
3110 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003111 subprocess2.Popen.assert_any_call([
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003112 'vpython3', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00003113 '--root', 'root',
3114 '--upstream', 'upstream',
3115 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00003116 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003117 '--gerrit_project', 'project',
3118 '--gerrit_branch', 'refs/heads/main',
3119 '--author', 'author',
Edward Lemur227d5102020-02-25 23:45:35 +00003120 '--issue', '123456',
3121 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00003122 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00003123 '--may_prompt',
3124 '--parallel',
3125 '--all_files',
Bruce Dawson09c0c072022-05-26 20:28:58 +00003126 '--no_diffs',
Edward Lemur227d5102020-02-25 23:45:35 +00003127 '--json_output', '/tmp/fake-temp2',
3128 '--description_file', '/tmp/fake-temp1',
3129 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003130 subprocess2.Popen.assert_any_call([
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003131 'vpython', 'PRESUBMIT_SUPPORT',
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003132 '--root', 'root',
3133 '--upstream', 'upstream',
3134 '--verbose', '--verbose',
3135 '--gerrit_url', 'https://chromium-review.googlesource.com',
3136 '--gerrit_project', 'project',
3137 '--gerrit_branch', 'refs/heads/main',
3138 '--author', 'author',
3139 '--issue', '123456',
3140 '--patchset', '7',
3141 '--commit',
3142 '--may_prompt',
3143 '--parallel',
3144 '--all_files',
Bruce Dawson09c0c072022-05-26 20:28:58 +00003145 '--no_diffs',
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003146 '--json_output', '/tmp/fake-temp4',
3147 '--description_file', '/tmp/fake-temp3',
3148 ])
3149 gclient_utils.FileWrite.assert_any_call(
Edward Lemur1a83da12020-03-04 21:18:36 +00003150 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00003151 metrics.collector.add_repeated('sub_commands', {
3152 'command': 'presubmit',
3153 'execution_time': 100,
3154 'exit_code': 0,
3155 })
3156
Edward Lemur99df04e2020-03-05 19:39:43 +00003157 def testRunHook_FewerOptions(self):
3158 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003159 'more_cc': ['cc@example.com', 'more@example.com'],
3160 'errors': [],
3161 'notifications': [],
3162 'warnings': [],
Edward Lemur99df04e2020-03-05 19:39:43 +00003163 }
3164 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003165 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur99df04e2020-03-05 19:39:43 +00003166 mockProcess = mock.Mock()
3167 mockProcess.wait.return_value = 0
3168 subprocess2.Popen.return_value = mockProcess
3169
3170 git_cl.Changelist.GetAuthor.return_value = None
3171 git_cl.Changelist.GetIssue.return_value = None
3172 git_cl.Changelist.GetPatchset.return_value = None
Edward Lemur99df04e2020-03-05 19:39:43 +00003173
3174 cl = git_cl.Changelist()
3175 results = cl.RunHook(
3176 committing=False,
3177 may_prompt=False,
3178 verbose=0,
3179 parallel=False,
3180 upstream='upstream',
3181 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003182 all_files=False,
3183 resultdb=False)
Edward Lemur99df04e2020-03-05 19:39:43 +00003184
3185 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003186 subprocess2.Popen.assert_any_call([
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003187 'vpython3', 'PRESUBMIT_SUPPORT',
Edward Lemur99df04e2020-03-05 19:39:43 +00003188 '--root', 'root',
3189 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003190 '--gerrit_url', 'https://chromium-review.googlesource.com',
3191 '--gerrit_project', 'project',
3192 '--gerrit_branch', 'refs/heads/main',
Edward Lemur99df04e2020-03-05 19:39:43 +00003193 '--upload',
3194 '--json_output', '/tmp/fake-temp2',
3195 '--description_file', '/tmp/fake-temp1',
3196 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003197 gclient_utils.FileWrite.assert_any_call(
Edward Lemur99df04e2020-03-05 19:39:43 +00003198 '/tmp/fake-temp1', 'description')
3199 metrics.collector.add_repeated('sub_commands', {
3200 'command': 'presubmit',
3201 'execution_time': 100,
3202 'exit_code': 0,
3203 })
3204
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003205 def testRunHook_FewerOptionsResultDB(self):
3206 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003207 'more_cc': ['cc@example.com', 'more@example.com'],
3208 'errors': [],
3209 'notifications': [],
3210 'warnings': [],
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003211 }
3212 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003213 git_cl.time_time.side_effect = [100, 200, 300, 400]
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003214 mockProcess = mock.Mock()
3215 mockProcess.wait.return_value = 0
3216 subprocess2.Popen.return_value = mockProcess
3217
3218 git_cl.Changelist.GetAuthor.return_value = None
3219 git_cl.Changelist.GetIssue.return_value = None
3220 git_cl.Changelist.GetPatchset.return_value = None
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003221
3222 cl = git_cl.Changelist()
3223 results = cl.RunHook(
3224 committing=False,
3225 may_prompt=False,
3226 verbose=0,
3227 parallel=False,
3228 upstream='upstream',
3229 description='description',
3230 all_files=False,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003231 resultdb=True,
3232 realm='chromium:public')
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003233
3234 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003235 subprocess2.Popen.assert_any_call([
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003236 'rdb', 'stream', '-new', '-realm', 'chromium:public', '--',
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003237 'vpython3', 'PRESUBMIT_SUPPORT',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003238 '--root', 'root',
3239 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003240 '--gerrit_url', 'https://chromium-review.googlesource.com',
3241 '--gerrit_project', 'project',
3242 '--gerrit_branch', 'refs/heads/main',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003243 '--upload',
3244 '--json_output', '/tmp/fake-temp2',
3245 '--description_file', '/tmp/fake-temp1',
3246 ])
3247
Aleksey Khoroshilov35ef5ad2022-06-03 18:29:25 +00003248 def testRunHook_NoGerrit(self):
3249 mock.patch('git_cl.Settings.GetIsGerrit', return_value=False).start()
3250
3251 expected_results = {
3252 'more_cc': ['cc@example.com', 'more@example.com'],
3253 'errors': [],
3254 'notifications': [],
3255 'warnings': [],
3256 }
3257 gclient_utils.FileRead.return_value = json.dumps(expected_results)
3258 git_cl.time_time.side_effect = [100, 200, 300, 400]
3259 mockProcess = mock.Mock()
3260 mockProcess.wait.return_value = 0
3261 subprocess2.Popen.return_value = mockProcess
3262
3263 git_cl.Changelist.GetAuthor.return_value = None
3264 git_cl.Changelist.GetIssue.return_value = None
3265 git_cl.Changelist.GetPatchset.return_value = None
3266
3267 cl = git_cl.Changelist()
3268 results = cl.RunHook(
3269 committing=False,
3270 may_prompt=False,
3271 verbose=0,
3272 parallel=False,
3273 upstream='upstream',
3274 description='description',
3275 all_files=False,
3276 resultdb=False)
3277
3278 self.assertEqual(expected_results, results)
3279 subprocess2.Popen.assert_any_call([
3280 'vpython3', 'PRESUBMIT_SUPPORT',
3281 '--root', 'root',
3282 '--upstream', 'upstream',
3283 '--upload',
3284 '--json_output', '/tmp/fake-temp2',
3285 '--description_file', '/tmp/fake-temp1',
3286 ])
3287 gclient_utils.FileWrite.assert_any_call(
3288 '/tmp/fake-temp1', 'description')
3289 metrics.collector.add_repeated('sub_commands', {
3290 'command': 'presubmit',
3291 'execution_time': 100,
3292 'exit_code': 0,
3293 })
3294
Edward Lemur227d5102020-02-25 23:45:35 +00003295 @mock.patch('sys.exit', side_effect=SystemExitMock)
3296 def testRunHook_Failure(self, _mock):
3297 git_cl.time_time.side_effect = [100, 200]
3298 mockProcess = mock.Mock()
3299 mockProcess.wait.return_value = 2
3300 subprocess2.Popen.return_value = mockProcess
3301
3302 cl = git_cl.Changelist()
3303 with self.assertRaises(SystemExitMock):
3304 cl.RunHook(
3305 committing=True,
3306 may_prompt=True,
3307 verbose=2,
3308 parallel=True,
3309 upstream='upstream',
3310 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003311 all_files=True,
3312 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003313
3314 sys.exit.assert_called_once_with(2)
3315
Edward Lemur75526302020-02-27 22:31:05 +00003316 def testRunPostUploadHook(self):
3317 cl = git_cl.Changelist()
3318 cl.RunPostUploadHook(2, 'upstream', 'description')
3319
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003320 subprocess2.Popen.assert_any_call([
3321 'vpython',
3322 'PRESUBMIT_SUPPORT',
3323 '--root',
3324 'root',
3325 '--upstream',
3326 'upstream',
3327 '--verbose',
3328 '--verbose',
3329 '--gerrit_url',
3330 'https://chromium-review.googlesource.com',
3331 '--gerrit_project',
3332 'project',
3333 '--gerrit_branch',
3334 'refs/heads/main',
3335 '--author',
3336 'author',
3337 '--issue',
3338 '123456',
3339 '--patchset',
3340 '7',
Edward Lemur75526302020-02-27 22:31:05 +00003341 '--post_upload',
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003342 '--description_file',
3343 '/tmp/fake-temp1',
Edward Lemur75526302020-02-27 22:31:05 +00003344 ])
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003345 subprocess2.Popen.assert_called_with([
3346 'vpython3',
3347 'PRESUBMIT_SUPPORT',
3348 '--root',
3349 'root',
3350 '--upstream',
3351 'upstream',
3352 '--verbose',
3353 '--verbose',
3354 '--gerrit_url',
3355 'https://chromium-review.googlesource.com',
3356 '--gerrit_project',
3357 'project',
3358 '--gerrit_branch',
3359 'refs/heads/main',
3360 '--author',
3361 'author',
3362 '--issue',
3363 '123456',
3364 '--patchset',
3365 '7',
3366 '--post_upload',
3367 '--description_file',
3368 '/tmp/fake-temp1',
3369 '--use-python3',
3370 ])
3371
Edward Lemur75526302020-02-27 22:31:05 +00003372 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00003373 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00003374
mlcui3da91712021-05-05 10:00:30 +00003375 @mock.patch('git_cl.RunGit', _mock_run_git)
3376 def testDefaultTitleEmptyMessage(self):
3377 cl = git_cl.Changelist()
3378 cl.issue = 100
3379 options = optparse.Values({
3380 'squash': True,
3381 'title': None,
3382 'message': None,
3383 'force': None,
3384 'skip_title': None
3385 })
3386
3387 mock.patch('gclient_utils.AskForData', lambda _: user_title).start()
3388 for user_title in ['', 'y', 'Y']:
3389 self.assertEqual(cl._GetTitleForUpload(options), self.LAST_COMMIT_SUBJECT)
3390
3391 for user_title in ['not empty', 'yes', 'YES']:
3392 self.assertEqual(cl._GetTitleForUpload(options), user_title)
3393
Edward Lemur9aa1a962020-02-25 00:58:38 +00003394
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003395class CMDTestCaseBase(unittest.TestCase):
3396 _STATUSES = [
3397 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3398 'INFRA_FAILURE', 'CANCELED',
3399 ]
3400 _CHANGE_DETAIL = {
3401 'project': 'depot_tools',
3402 'status': 'OPEN',
3403 'owner': {'email': 'owner@e.mail'},
3404 'current_revision': 'beeeeeef',
3405 'revisions': {
Gavin Make61ccc52020-11-13 00:12:57 +00003406 'deadbeaf': {
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00003407 '_number': 6,
Gavin Make61ccc52020-11-13 00:12:57 +00003408 'kind': 'REWORK',
3409 },
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003410 'beeeeeef': {
3411 '_number': 7,
Gavin Make61ccc52020-11-13 00:12:57 +00003412 'kind': 'NO_CODE_CHANGE',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003413 'fetch': {'http': {
3414 'url': 'https://chromium.googlesource.com/depot_tools',
3415 'ref': 'refs/changes/56/123456/7'
3416 }},
3417 },
3418 },
3419 }
3420 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003421 'builds': [{
3422 'id': str(100 + idx),
3423 'builder': {
3424 'project': 'chromium',
3425 'bucket': 'try',
3426 'builder': 'bot_' + status.lower(),
3427 },
3428 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3429 'tags': [],
3430 'status': status,
3431 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003432 }
3433
Edward Lemur4c707a22019-09-24 21:13:43 +00003434 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003435 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00003436 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003437 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3438 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003439 mock.patch(
3440 'git_cl.Changelist.GetCodereviewServer',
3441 return_value='https://chromium-review.googlesource.com').start()
3442 mock.patch(
Edward Lesmeseeca9c62020-11-20 00:00:17 +00003443 'git_cl.Changelist.GetGerritHost',
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003444 return_value='chromium-review.googlesource.com').start()
3445 mock.patch(
3446 'git_cl.Changelist.GetMostRecentPatchset',
3447 return_value=7).start()
3448 mock.patch(
Gavin Make61ccc52020-11-13 00:12:57 +00003449 'git_cl.Changelist.GetMostRecentDryRunPatchset',
3450 return_value=6).start()
3451 mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003452 'git_cl.Changelist.GetRemoteUrl',
3453 return_value='https://chromium.googlesource.com/depot_tools').start()
3454 mock.patch(
3455 'auth.Authenticator',
3456 return_value=AuthenticatorMock()).start()
3457 mock.patch(
3458 'gerrit_util.GetChangeDetail',
3459 return_value=self._CHANGE_DETAIL).start()
3460 mock.patch(
3461 'git_cl._call_buildbucket',
3462 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003463 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003464 self.addCleanup(mock.patch.stopall)
3465
Edward Lemur4c707a22019-09-24 21:13:43 +00003466
Edward Lemur9468eba2020-02-27 19:07:22 +00003467class CMDPresubmitTestCase(CMDTestCaseBase):
3468 def setUp(self):
3469 super(CMDPresubmitTestCase, self).setUp()
3470 mock.patch(
3471 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3472 return_value='upstream').start()
3473 mock.patch(
3474 'git_cl.Changelist.FetchDescription',
3475 return_value='fetch description').start()
3476 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003477 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003478 return_value='get description').start()
3479 mock.patch('git_cl.Changelist.RunHook').start()
3480
3481 def testDefaultCase(self):
3482 self.assertEqual(0, git_cl.main(['presubmit']))
3483 git_cl.Changelist.RunHook.assert_called_once_with(
3484 committing=True,
3485 may_prompt=False,
3486 verbose=0,
3487 parallel=None,
3488 upstream='upstream',
3489 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003490 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003491 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003492 resultdb=None,
3493 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003494
3495 def testNoIssue(self):
3496 git_cl.Changelist.GetIssue.return_value = None
3497 self.assertEqual(0, git_cl.main(['presubmit']))
3498 git_cl.Changelist.RunHook.assert_called_once_with(
3499 committing=True,
3500 may_prompt=False,
3501 verbose=0,
3502 parallel=None,
3503 upstream='upstream',
3504 description='get description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003505 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003506 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003507 resultdb=None,
3508 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003509
3510 def testCustomBranch(self):
3511 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3512 git_cl.Changelist.RunHook.assert_called_once_with(
3513 committing=True,
3514 may_prompt=False,
3515 verbose=0,
3516 parallel=None,
3517 upstream='custom_branch',
3518 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003519 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003520 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003521 resultdb=None,
3522 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003523
3524 def testOptions(self):
3525 self.assertEqual(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003526 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u',
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003527 '--resultdb', '--realm', 'chromium:public']))
Edward Lemur9468eba2020-02-27 19:07:22 +00003528 git_cl.Changelist.RunHook.assert_called_once_with(
3529 committing=False,
3530 may_prompt=False,
3531 verbose=2,
3532 parallel=True,
3533 upstream='upstream',
3534 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003535 all_files=True,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003536 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003537 resultdb=True,
3538 realm='chromium:public')
Edward Lemur9468eba2020-02-27 19:07:22 +00003539
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003540class CMDTryResultsTestCase(CMDTestCaseBase):
3541 _DEFAULT_REQUEST = {
3542 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003543 "gerritChanges": [{
3544 "project": "depot_tools",
3545 "host": "chromium-review.googlesource.com",
Gavin Make61ccc52020-11-13 00:12:57 +00003546 "patchset": 6,
3547 "change": 123456,
3548 }],
3549 },
3550 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3551 ',builds.*.createTime,builds.*.tags'),
3552 }
3553
3554 _TRIVIAL_REQUEST = {
3555 'predicate': {
3556 "gerritChanges": [{
3557 "project": "depot_tools",
3558 "host": "chromium-review.googlesource.com",
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003559 "patchset": 7,
3560 "change": 123456,
3561 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003562 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003563 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3564 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003565 }
3566
3567 def testNoJobs(self):
3568 git_cl._call_buildbucket.return_value = {}
3569
3570 self.assertEqual(0, git_cl.main(['try-results']))
3571 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3572 git_cl._call_buildbucket.assert_called_once_with(
3573 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3574 self._DEFAULT_REQUEST)
3575
Gavin Make61ccc52020-11-13 00:12:57 +00003576 def testTrivialCommits(self):
3577 self.assertEqual(0, git_cl.main(['try-results']))
3578 git_cl._call_buildbucket.assert_called_with(
3579 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3580 self._DEFAULT_REQUEST)
3581
3582 git_cl._call_buildbucket.return_value = {}
3583 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '7']))
3584 git_cl._call_buildbucket.assert_called_with(
3585 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3586 self._TRIVIAL_REQUEST)
3587 self.assertEqual([
3588 'Successes:',
3589 ' bot_success https://ci.chromium.org/b/103',
3590 'Infra Failures:',
3591 ' bot_infra_failure https://ci.chromium.org/b/105',
3592 'Failures:',
3593 ' bot_failure https://ci.chromium.org/b/104',
3594 'Canceled:',
3595 ' bot_canceled ',
3596 'Started:',
3597 ' bot_started https://ci.chromium.org/b/102',
3598 'Scheduled:',
3599 ' bot_scheduled id=101',
3600 'Other:',
3601 ' bot_status_unspecified id=100',
3602 'Total: 7 tryjobs',
3603 'No tryjobs scheduled.',
3604 ], sys.stdout.getvalue().splitlines())
3605
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003606 def testPrintToStdout(self):
3607 self.assertEqual(0, git_cl.main(['try-results']))
3608 self.assertEqual([
3609 'Successes:',
3610 ' bot_success https://ci.chromium.org/b/103',
3611 'Infra Failures:',
3612 ' bot_infra_failure https://ci.chromium.org/b/105',
3613 'Failures:',
3614 ' bot_failure https://ci.chromium.org/b/104',
3615 'Canceled:',
3616 ' bot_canceled ',
3617 'Started:',
3618 ' bot_started https://ci.chromium.org/b/102',
3619 'Scheduled:',
3620 ' bot_scheduled id=101',
3621 'Other:',
3622 ' bot_status_unspecified id=100',
3623 'Total: 7 tryjobs',
3624 ], sys.stdout.getvalue().splitlines())
3625 git_cl._call_buildbucket.assert_called_once_with(
3626 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3627 self._DEFAULT_REQUEST)
3628
3629 def testPrintToStdoutWithMasters(self):
3630 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3631 self.assertEqual([
3632 'Successes:',
3633 ' try bot_success https://ci.chromium.org/b/103',
3634 'Infra Failures:',
3635 ' try bot_infra_failure https://ci.chromium.org/b/105',
3636 'Failures:',
3637 ' try bot_failure https://ci.chromium.org/b/104',
3638 'Canceled:',
3639 ' try bot_canceled ',
3640 'Started:',
3641 ' try bot_started https://ci.chromium.org/b/102',
3642 'Scheduled:',
3643 ' try bot_scheduled id=101',
3644 'Other:',
3645 ' try bot_status_unspecified id=100',
3646 'Total: 7 tryjobs',
3647 ], sys.stdout.getvalue().splitlines())
3648 git_cl._call_buildbucket.assert_called_once_with(
3649 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3650 self._DEFAULT_REQUEST)
3651
3652 @mock.patch('git_cl.write_json')
3653 def testWriteToJson(self, mockJsonDump):
3654 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3655 git_cl._call_buildbucket.assert_called_once_with(
3656 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3657 self._DEFAULT_REQUEST)
3658 mockJsonDump.assert_called_once_with(
3659 'file.json', self._DEFAULT_RESPONSE['builds'])
3660
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003661 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003662 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3663 self.assertEqual(
3664 [
3665 ('chromium', 'try', 'bot_failure'),
3666 ('chromium', 'try', 'bot_infra_failure'),
3667 ],
3668 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003669
3670 def test_filter_failed_for_retry_many_builds(self):
3671
3672 def _build(name, created_sec, status, experimental=False):
3673 assert 0 <= created_sec < 100, created_sec
3674 b = {
3675 'id': 112112,
3676 'builder': {
3677 'project': 'chromium',
3678 'bucket': 'try',
3679 'builder': name,
3680 },
3681 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3682 'status': status,
3683 'tags': [],
3684 }
3685 if experimental:
3686 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3687 return b
3688
3689 builds = [
3690 _build('flaky-last-green', 1, 'FAILURE'),
3691 _build('flaky-last-green', 2, 'SUCCESS'),
3692 _build('flaky', 1, 'SUCCESS'),
3693 _build('flaky', 2, 'FAILURE'),
3694 _build('running', 1, 'FAILED'),
3695 _build('running', 2, 'SCHEDULED'),
3696 _build('yep-still-running', 1, 'STARTED'),
3697 _build('yep-still-running', 2, 'FAILURE'),
3698 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3699 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3700
3701 # Simulate experimental in CQ builder, which developer decided
3702 # to retry manually which resulted in 2nd build non-experimental.
3703 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3704 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3705 ]
3706 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003707 self.assertEqual(
3708 [
3709 ('chromium', 'try', 'flaky'),
3710 ('chromium', 'try', 'sometimes-experimental'),
3711 ],
3712 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003713
3714
3715class CMDTryTestCase(CMDTestCaseBase):
3716
3717 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003718 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003719 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003720 self.assertEqual(0, git_cl.main(['try']))
3721 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3722 self.assertEqual(
3723 sys.stdout.getvalue(),
3724 'Scheduling CQ dry run on: '
3725 'https://chromium-review.googlesource.com/123456\n')
3726
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00003727 @mock.patch('git_cl.Changelist.SetCQState')
3728 def testSetCQQuickRunByDefault(self, mockSetCQState):
3729 mockSetCQState.return_value = 0
3730 self.assertEqual(0, git_cl.main(['try', '-q']))
3731 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.QUICK_RUN)
3732 self.assertEqual(
3733 sys.stdout.getvalue(),
3734 'Scheduling CQ quick run on: '
3735 'https://chromium-review.googlesource.com/123456\n')
3736
Edward Lemur4c707a22019-09-24 21:13:43 +00003737 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003738 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003739 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003740
3741 self.assertEqual(0, git_cl.main([
3742 'try', '-B', 'luci.chromium.try', '-b', 'win',
3743 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3744 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003745 'Scheduling jobs on:\n'
3746 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003747 git_cl.sys.stdout.getvalue())
3748
3749 expected_request = {
3750 "requests": [{
3751 "scheduleBuild": {
3752 "requestId": "uuid4",
3753 "builder": {
3754 "project": "chromium",
3755 "builder": "win",
3756 "bucket": "try",
3757 },
3758 "gerritChanges": [{
3759 "project": "depot_tools",
3760 "host": "chromium-review.googlesource.com",
3761 "patchset": 7,
3762 "change": 123456,
3763 }],
3764 "properties": {
3765 "category": "git_cl_try",
3766 "json": [{"a": 1}, None],
3767 "key": "val",
3768 },
3769 "tags": [
3770 {"value": "win", "key": "builder"},
3771 {"value": "git_cl_try", "key": "user_agent"},
3772 ],
3773 },
3774 }],
3775 }
3776 mockCallBuildbucket.assert_called_with(
3777 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3778
Anthony Polito1a5fe232020-01-24 23:17:52 +00003779 @mock.patch('git_cl._call_buildbucket')
3780 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3781 mockCallBuildbucket.return_value = {}
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003782 mock.patch('git_cl.Changelist.GetRemoteBranch',
3783 return_value=('origin', 'refs/remotes/origin/main')).start()
Anthony Polito1a5fe232020-01-24 23:17:52 +00003784
3785 self.assertEqual(0, git_cl.main([
3786 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3787 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3788 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3789 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003790 'Scheduling jobs on:\n'
3791 ' chromium/try: linux\n'
3792 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003793 git_cl.sys.stdout.getvalue())
3794
3795 expected_request = {
3796 "requests": [{
3797 "scheduleBuild": {
3798 "requestId": "uuid4",
3799 "builder": {
3800 "project": "chromium",
3801 "builder": "linux",
3802 "bucket": "try",
3803 },
3804 "gerritChanges": [{
3805 "project": "depot_tools",
3806 "host": "chromium-review.googlesource.com",
3807 "patchset": 7,
3808 "change": 123456,
3809 }],
3810 "properties": {
3811 "category": "git_cl_try",
3812 "json": [{"a": 1}, None],
3813 "key": "val",
3814 },
3815 "tags": [
3816 {"value": "linux", "key": "builder"},
3817 {"value": "git_cl_try", "key": "user_agent"},
3818 ],
3819 "gitilesCommit": {
3820 "host": "chromium-review.googlesource.com",
3821 "project": "depot_tools",
3822 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003823 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003824 }
3825 },
3826 },
3827 {
3828 "scheduleBuild": {
3829 "requestId": "uuid4",
3830 "builder": {
3831 "project": "chromium",
3832 "builder": "win",
3833 "bucket": "try",
3834 },
3835 "gerritChanges": [{
3836 "project": "depot_tools",
3837 "host": "chromium-review.googlesource.com",
3838 "patchset": 7,
3839 "change": 123456,
3840 }],
3841 "properties": {
3842 "category": "git_cl_try",
3843 "json": [{"a": 1}, None],
3844 "key": "val",
3845 },
3846 "tags": [
3847 {"value": "win", "key": "builder"},
3848 {"value": "git_cl_try", "key": "user_agent"},
3849 ],
3850 "gitilesCommit": {
3851 "host": "chromium-review.googlesource.com",
3852 "project": "depot_tools",
3853 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003854 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003855 }
3856 },
3857 }],
3858 }
3859 mockCallBuildbucket.assert_called_with(
3860 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3861
Edward Lemur45768512020-03-02 19:03:14 +00003862 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003863 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003864 with self.assertRaises(SystemExit):
3865 git_cl.main([
3866 'try', '-B', 'not-a-bucket', '-b', 'win',
3867 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003868 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003869 'Invalid bucket: not-a-bucket.',
3870 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003871
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003872 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003873 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003874 def testScheduleOnBuildbucketRetryFailed(
3875 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003876 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003877 7: [],
3878 6: [{
3879 'id': 112112,
3880 'builder': {
3881 'project': 'chromium',
3882 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003883 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003884 'createTime': '2019-10-09T08:00:01.854286Z',
3885 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003886 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003887 mockCallBuildbucket.return_value = {}
3888
3889 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3890 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003891 'Scheduling jobs on:\n'
3892 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003893 git_cl.sys.stdout.getvalue())
3894
3895 expected_request = {
3896 "requests": [{
3897 "scheduleBuild": {
3898 "requestId": "uuid4",
3899 "builder": {
3900 "project": "chromium",
3901 "bucket": "try",
3902 "builder": "linux",
3903 },
3904 "gerritChanges": [{
3905 "project": "depot_tools",
3906 "host": "chromium-review.googlesource.com",
3907 "patchset": 7,
3908 "change": 123456,
3909 }],
3910 "properties": {
3911 "category": "git_cl_try",
3912 },
3913 "tags": [
3914 {"value": "linux", "key": "builder"},
3915 {"value": "git_cl_try", "key": "user_agent"},
3916 {"value": "1", "key": "retry_failed"},
3917 ],
3918 },
3919 }],
3920 }
3921 mockCallBuildbucket.assert_called_with(
3922 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3923
Edward Lemur4c707a22019-09-24 21:13:43 +00003924 def test_parse_bucket(self):
3925 test_cases = [
3926 {
3927 'bucket': 'chromium/try',
3928 'result': ('chromium', 'try'),
3929 },
3930 {
3931 'bucket': 'luci.chromium.try',
3932 'result': ('chromium', 'try'),
3933 'has_warning': True,
3934 },
3935 {
3936 'bucket': 'skia.primary',
3937 'result': ('skia', 'skia.primary'),
3938 'has_warning': True,
3939 },
3940 {
3941 'bucket': 'not-a-bucket',
3942 'result': (None, None),
3943 },
3944 ]
3945
3946 for test_case in test_cases:
3947 git_cl.sys.stdout.truncate(0)
3948 self.assertEqual(
3949 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3950 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003951 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3952 test_case['result'])
3953 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003954
3955
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003956class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003957
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003958 def setUp(self):
3959 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003960 mock.patch('git_cl._fetch_tryjobs').start()
3961 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003962 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003963 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3964 mock.patch(
3965 'git_cl.Settings.GetSquashGerritUploads',
3966 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003967 self.addCleanup(mock.patch.stopall)
3968
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003969 def testWarmUpChangeDetailCache(self):
3970 self.assertEqual(0, git_cl.main(['upload']))
3971 gerrit_util.GetChangeDetail.assert_called_once_with(
3972 'chromium-review.googlesource.com', 'depot_tools~123456',
3973 frozenset([
3974 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3975 'CURRENT_COMMIT']))
3976
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003977 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003978 # This test mocks out the actual upload part, and just asserts that after
3979 # upload, if --retry-failed is added, then the tool will fetch try jobs
3980 # from the previous patchset and trigger the right builders on the latest
3981 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003982 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003983 # Latest patchset: No builds.
3984 [],
3985 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003986 [{
3987 'id': str(100 + idx),
3988 'builder': {
3989 'project': 'chromium',
3990 'bucket': 'try',
3991 'builder': 'bot_' + status.lower(),
3992 },
3993 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3994 'tags': [],
3995 'status': status,
3996 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003997 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003998
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003999 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00004000 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00004001 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
4002 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00004003 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00004004 expected_buckets = [
4005 ('chromium', 'try', 'bot_failure'),
4006 ('chromium', 'try', 'bot_infra_failure'),
4007 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00004008 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
4009 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004010
Brian Sheedy59b06a82019-10-14 17:03:29 +00004011
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00004012class MakeRequestsHelperTestCase(unittest.TestCase):
4013
4014 def exampleGerritChange(self):
4015 return {
4016 'host': 'chromium-review.googlesource.com',
4017 'project': 'depot_tools',
4018 'change': 1,
4019 'patchset': 2,
4020 }
4021
4022 def testMakeRequestsHelperNoOptions(self):
4023 # Basic test for the helper function _make_tryjob_schedule_requests;
4024 # it shouldn't throw AttributeError even when options doesn't have any
4025 # of the expected values; it will use default option values.
4026 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4027 jobs = [('chromium', 'try', 'my-builder')]
4028 options = optparse.Values()
4029 requests = git_cl._make_tryjob_schedule_requests(
4030 changelist, jobs, options, patchset=None)
4031
4032 # requestId is non-deterministic. Just assert that it's there and has
4033 # a particular length.
4034 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
4035 self.assertEqual(requests, [{
4036 'scheduleBuild': {
4037 'builder': {
4038 'bucket': 'try',
4039 'builder': 'my-builder',
4040 'project': 'chromium'
4041 },
4042 'gerritChanges': [self.exampleGerritChange()],
4043 'properties': {
4044 'category': 'git_cl_try'
4045 },
4046 'tags': [{
4047 'key': 'builder',
4048 'value': 'my-builder'
4049 }, {
4050 'key': 'user_agent',
4051 'value': 'git_cl_try'
4052 }]
4053 }
4054 }])
4055
4056 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
4057 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4058 jobs = [('chromium', 'try', 'presubmit')]
4059 options = optparse.Values()
4060 requests = git_cl._make_tryjob_schedule_requests(
4061 changelist, jobs, options, patchset=None)
4062 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
4063 'category': 'git_cl_try',
4064 'dry_run': 'true'
4065 })
4066
4067 def testMakeRequestsHelperRevisionSet(self):
4068 # Gitiles commit is specified when revision is in options.
4069 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4070 jobs = [('chromium', 'try', 'my-builder')]
4071 options = optparse.Values({'revision': 'ba5eba11'})
4072 requests = git_cl._make_tryjob_schedule_requests(
4073 changelist, jobs, options, patchset=None)
4074 self.assertEqual(
4075 requests[0]['scheduleBuild']['gitilesCommit'], {
4076 'host': 'chromium-review.googlesource.com',
4077 'id': 'ba5eba11',
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00004078 'project': 'depot_tools',
4079 'ref': 'refs/heads/main',
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00004080 })
4081
4082 def testMakeRequestsHelperRetryFailedSet(self):
4083 # An extra tag is added when retry_failed is in options.
4084 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4085 jobs = [('chromium', 'try', 'my-builder')]
4086 options = optparse.Values({'retry_failed': 'true'})
4087 requests = git_cl._make_tryjob_schedule_requests(
4088 changelist, jobs, options, patchset=None)
4089 self.assertEqual(
4090 requests[0]['scheduleBuild']['tags'], [
4091 {
4092 'key': 'builder',
4093 'value': 'my-builder'
4094 },
4095 {
4096 'key': 'user_agent',
4097 'value': 'git_cl_try'
4098 },
4099 {
4100 'key': 'retry_failed',
4101 'value': '1'
4102 }
4103 ])
4104
4105 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00004106 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00004107 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4108 jobs = [('chromium', 'try', 'my-builder')]
4109 options = optparse.Values({'category': 'my-special-category'})
4110 requests = git_cl._make_tryjob_schedule_requests(
4111 changelist, jobs, options, patchset=None)
4112 self.assertEqual(requests[0]['scheduleBuild']['properties'],
4113 {'category': 'my-special-category'})
4114
4115
Edward Lemurda4b6c62020-02-13 00:28:40 +00004116class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004117
4118 def setUp(self):
4119 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00004120 mock.patch('git_cl.RunCommand').start()
4121 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
4122 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
4123 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00004124 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00004125 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004126
4127 def tearDown(self):
4128 shutil.rmtree(self._top_dir)
4129 super(CMDFormatTestCase, self).tearDown()
4130
Jamie Madill5e96ad12020-01-13 16:08:35 +00004131 def _make_temp_file(self, fname, contents):
Anthony Politoc64e3902021-04-30 21:55:25 +00004132 gclient_utils.FileWrite(os.path.join(self._top_dir, fname),
4133 ('\n'.join(contents)))
Jamie Madill5e96ad12020-01-13 16:08:35 +00004134
Brian Sheedy59b06a82019-10-14 17:03:29 +00004135 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00004136 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004137
Brian Sheedyb4307d52019-12-02 19:18:17 +00004138 def _check_yapf_filtering(self, files, expected):
4139 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
4140 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00004141
Edward Lemur1a83da12020-03-04 21:18:36 +00004142 def _run_command_mock(self, return_value):
4143 def f(*args, **kwargs):
4144 if 'stdin' in kwargs:
4145 self.assertIsInstance(kwargs['stdin'], bytes)
4146 return return_value
4147 return f
4148
Jamie Madill5e96ad12020-01-13 16:08:35 +00004149 def testClangFormatDiffFull(self):
4150 self._make_temp_file('test.cc', ['// test'])
4151 git_cl.settings.GetFormatFullByDefault.return_value = False
4152 diff_file = [os.path.join(self._top_dir, 'test.cc')]
4153 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
4154
4155 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004156 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004157 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
4158 self._top_dir, 'HEAD')
4159 self.assertEqual(2, return_value)
4160
4161 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004162 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004163 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
4164 self._top_dir, 'HEAD')
4165 self.assertEqual(0, return_value)
4166
4167 def testClangFormatDiff(self):
4168 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00004169 # A valid file is required, so use this test.
4170 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00004171 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
4172
4173 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004174 git_cl.RunCommand.side_effect = self._run_command_mock('error')
4175 return_value = git_cl._RunClangFormatDiff(
4176 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004177 self.assertEqual(2, return_value)
4178
4179 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004180 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004181 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
4182 'HEAD')
4183 self.assertEqual(0, return_value)
4184
Brian Sheedyb4307d52019-12-02 19:18:17 +00004185 def testYapfignoreExplicit(self):
4186 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
4187 files = [
4188 'bar.py',
4189 'foo/bar.py',
4190 'foo/baz.py',
4191 'foo/bar/baz.py',
4192 'foo/bar/foobar.py',
4193 ]
4194 expected = [
4195 'bar.py',
4196 'foo/baz.py',
4197 'foo/bar/foobar.py',
4198 ]
4199 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004200
Brian Sheedyb4307d52019-12-02 19:18:17 +00004201 def testYapfignoreSingleWildcards(self):
4202 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
4203 files = [
4204 'bar.py', # Matched by *bar.py.
4205 'bar.txt',
4206 'foobar.py', # Matched by *bar.py, foo*.
4207 'foobar.txt', # Matched by foo*.
4208 'bazbar.py', # Matched by *bar.py, baz*.py.
4209 'bazbar.txt',
4210 'foo/baz.txt', # Matched by foo*.
4211 'bar/bar.py', # Matched by *bar.py.
4212 'baz/foo.py', # Matched by baz*.py, foo*.
4213 'baz/foo.txt',
4214 ]
4215 expected = [
4216 'bar.txt',
4217 'bazbar.txt',
4218 'baz/foo.txt',
4219 ]
4220 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004221
Brian Sheedyb4307d52019-12-02 19:18:17 +00004222 def testYapfignoreMultiplewildcards(self):
4223 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
4224 files = [
4225 'bar.py', # Matched by *bar*.
4226 'bar.txt', # Matched by *bar*.
4227 'abar.py', # Matched by *bar*.
4228 'foobaz.txt', # Matched by *foo*baz.txt.
4229 'foobaz.py',
4230 'afoobaz.txt', # Matched by *foo*baz.txt.
4231 ]
4232 expected = [
4233 'foobaz.py',
4234 ]
4235 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004236
4237 def testYapfignoreComments(self):
4238 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004239 files = [
4240 'test.py',
4241 'test2.py',
4242 ]
4243 expected = [
4244 'test2.py',
4245 ]
4246 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004247
Anthony Politoc64e3902021-04-30 21:55:25 +00004248 def testYapfHandleUtf8(self):
4249 self._make_yapfignore(['test.py', 'test_🌐.py'])
4250 files = [
4251 'test.py',
4252 'test_🌐.py',
4253 'test2.py',
4254 ]
4255 expected = [
4256 'test2.py',
4257 ]
4258 self._check_yapf_filtering(files, expected)
4259
Brian Sheedy59b06a82019-10-14 17:03:29 +00004260 def testYapfignoreBlankLines(self):
4261 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004262 files = [
4263 'test.py',
4264 'test2.py',
4265 'test3.py',
4266 ]
4267 expected = [
4268 'test3.py',
4269 ]
4270 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004271
4272 def testYapfignoreWhitespace(self):
4273 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004274 files = [
4275 'test.py',
4276 'test2.py',
4277 ]
4278 expected = [
4279 'test2.py',
4280 ]
4281 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004282
Brian Sheedyb4307d52019-12-02 19:18:17 +00004283 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004284 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004285 self._check_yapf_filtering([], [])
4286
4287 def testYapfignoreMissingYapfignore(self):
4288 files = [
4289 'test.py',
4290 ]
4291 expected = [
4292 'test.py',
4293 ]
4294 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004295
4296
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004297class CMDStatusTestCase(CMDTestCaseBase):
4298 # Return branch names a,..,f with comitterdates in increasing order, i.e.
4299 # 'f' is the most-recently changed branch.
4300 def _mock_run_git(commands):
4301 if commands == [
4302 'for-each-ref', '--format=%(refname) %(committerdate:unix)',
4303 'refs/heads'
4304 ]:
4305 branches_and_committerdates = [
4306 'refs/heads/a 1',
4307 'refs/heads/b 2',
4308 'refs/heads/c 3',
4309 'refs/heads/d 4',
4310 'refs/heads/e 5',
4311 'refs/heads/f 6',
4312 ]
4313 return '\n'.join(branches_and_committerdates)
4314
4315 # Mock the status in such a way that the issue number gives us an
4316 # indication of the commit date (simplifies manual debugging).
4317 def _mock_get_cl_statuses(branches, fine_grained, max_processes):
4318 for c in branches:
4319 c.issue = (100 + int(c.GetCommitDate()))
4320 yield (c, 'open')
4321
4322 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4323 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4324 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4325 @mock.patch('git_cl.RunGit', _mock_run_git)
4326 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4327 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004328 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004329 @mock.patch('scm.GIT.GetBranch', return_value='a')
4330 def testStatus(self, *_mocks):
4331 self.assertEqual(0, git_cl.main(['status', '--no-branch-color']))
4332 self.maxDiff = None
4333 self.assertEqual(
4334 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4335 ' * a : https://crrev.com/c/101 (open)\n'
4336 ' b : https://crrev.com/c/102 (open)\n'
4337 ' c : https://crrev.com/c/103 (open)\n'
4338 ' d : https://crrev.com/c/104 (open)\n'
4339 ' e : https://crrev.com/c/105 (open)\n'
4340 ' f : https://crrev.com/c/106 (open)\n\n'
4341 'Current branch: a\n'
4342 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4343 'Issue description:\n'
4344 'x\n')
4345
4346 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4347 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4348 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4349 @mock.patch('git_cl.RunGit', _mock_run_git)
4350 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4351 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004352 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004353 @mock.patch('scm.GIT.GetBranch', return_value='a')
4354 def testStatusByDate(self, *_mocks):
4355 self.assertEqual(
4356 0, git_cl.main(['status', '--no-branch-color', '--date-order']))
4357 self.maxDiff = None
4358 self.assertEqual(
4359 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4360 ' f : https://crrev.com/c/106 (open)\n'
4361 ' e : https://crrev.com/c/105 (open)\n'
4362 ' d : https://crrev.com/c/104 (open)\n'
4363 ' c : https://crrev.com/c/103 (open)\n'
4364 ' b : https://crrev.com/c/102 (open)\n'
4365 ' * a : https://crrev.com/c/101 (open)\n\n'
4366 'Current branch: a\n'
4367 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4368 'Issue description:\n'
4369 'x\n')
4370
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004371 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4372 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4373 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4374 @mock.patch('git_cl.RunGit', _mock_run_git)
4375 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4376 @mock.patch('git_cl.Settings.GetRoot', return_value='')
4377 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=True)
4378 @mock.patch('scm.GIT.GetBranch', return_value='a')
4379 def testStatusByDate(self, *_mocks):
4380 self.assertEqual(
4381 0, git_cl.main(['status', '--no-branch-color']))
4382 self.maxDiff = None
4383 self.assertEqual(
4384 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4385 ' f : https://crrev.com/c/106 (open)\n'
4386 ' e : https://crrev.com/c/105 (open)\n'
4387 ' d : https://crrev.com/c/104 (open)\n'
4388 ' c : https://crrev.com/c/103 (open)\n'
4389 ' b : https://crrev.com/c/102 (open)\n'
4390 ' * a : https://crrev.com/c/101 (open)\n\n'
4391 'Current branch: a\n'
4392 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4393 'Issue description:\n'
4394 'x\n')
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004395
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004396class CMDOwnersTestCase(CMDTestCaseBase):
4397 def setUp(self):
4398 super(CMDOwnersTestCase, self).setUp()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004399 self.owners_by_path = {
4400 'foo': ['a@example.com'],
4401 'bar': ['b@example.com', 'c@example.com'],
4402 }
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004403 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
4404 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
4405 mock.patch(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004406 'git_cl.Changelist.GetAffectedFiles',
4407 return_value=list(self.owners_by_path)).start()
4408 mock.patch(
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004409 'git_cl.Changelist.GetCommonAncestorWithUpstream',
4410 return_value='upstream').start()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004411 mock.patch(
Edward Lesmese1576912021-02-16 21:53:34 +00004412 'git_cl.Changelist.GetGerritHost',
4413 return_value='host').start()
4414 mock.patch(
4415 'git_cl.Changelist.GetGerritProject',
4416 return_value='project').start()
4417 mock.patch(
4418 'git_cl.Changelist.GetRemoteBranch',
4419 return_value=('origin', 'refs/remotes/origin/main')).start()
4420 mock.patch(
4421 'owners_client.OwnersClient.BatchListOwners',
Edward Lesmes82b992a2021-01-11 23:24:55 +00004422 return_value=self.owners_by_path).start()
Edward Lesmes8170c292021-03-19 20:04:43 +00004423 mock.patch(
4424 'gerrit_util.IsCodeOwnersEnabledOnHost', return_value=True).start()
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004425 self.addCleanup(mock.patch.stopall)
4426
4427 def testShowAllNoArgs(self):
4428 self.assertEqual(0, git_cl.main(['owners', '--show-all']))
4429 self.assertEqual(
4430 'No files specified for --show-all. Nothing to do.\n',
4431 git_cl.sys.stdout.getvalue())
4432
4433 def testShowAll(self):
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004434 self.assertEqual(
4435 0,
4436 git_cl.main(['owners', '--show-all', 'foo', 'bar', 'baz']))
Edward Lesmese1576912021-02-16 21:53:34 +00004437 owners_client.OwnersClient.BatchListOwners.assert_called_once_with(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004438 ['foo', 'bar', 'baz'])
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004439 self.assertEqual(
4440 '\n'.join([
4441 'Owners for foo:',
4442 ' - a@example.com',
4443 'Owners for bar:',
4444 ' - b@example.com',
4445 ' - c@example.com',
4446 'Owners for baz:',
4447 ' - No owners found',
4448 '',
4449 ]),
4450 sys.stdout.getvalue())
4451
Edward Lesmes82b992a2021-01-11 23:24:55 +00004452 def testBatch(self):
4453 self.assertEqual(0, git_cl.main(['owners', '--batch']))
4454 self.assertIn('a@example.com', sys.stdout.getvalue())
4455 self.assertIn('b@example.com', sys.stdout.getvalue())
4456
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004457
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004458if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01004459 logging.basicConfig(
4460 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004461 unittest.main()