blob: 6a67c11a015abf98d20a1c21e905d7306ce60a5d [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.
881 if issue is None:
882 if squash:
883 title = 'Initial upload'
884 else:
885 if not title:
886 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
Anthony Polito8b955342019-09-24 19:01:36 +00001318 def test_gerrit_upload_force_sets_bug(self):
1319 self._run_gerrit_upload_test(
1320 ['-b', '10000', '-f'],
1321 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1322 [],
1323 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001324 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001325 change_id='Ixxx')
1326
Edward Lemur5fb22242020-03-12 22:05:13 +00001327 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001328 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001329 ['-b', '10000', '-m', 'Title', '--edit-description'],
1330 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001331 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001332 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001333 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001334 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001335 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001336 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001337
Dan Beamd8b04ca2019-10-10 21:23:26 +00001338 def test_gerrit_upload_force_sets_fixed(self):
1339 self._run_gerrit_upload_test(
1340 ['-x', '10000', '-f'],
1341 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1342 [],
1343 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001344 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001345 change_id='Ixxx')
1346
ukai@chromium.orge8077812012-02-03 03:41:46 +00001347 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001348 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1349 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001350 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001351 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001352 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001353 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001354 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001355 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001356 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001357 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001358 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001359 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001360
1361 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001362 self._run_gerrit_upload_test(
1363 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001364 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001365 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001366 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001367
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001368 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001369 self._run_gerrit_upload_test(
1370 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001371 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001372 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001373 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001374 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001375
Edward Lesmes0dd54822020-03-26 18:24:25 +00001376 def test_gerrit_upload_squash_first_title(self):
1377 self._run_gerrit_upload_test(
1378 ['-f', '-t', 'title'],
1379 'title\n\ndesc\n\nChange-Id: 123456789',
1380 [],
1381 force=True,
1382 squash=True,
1383 log_description='desc',
1384 change_id='123456789')
1385
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001386 def test_gerrit_upload_squash_first_with_labels(self):
1387 self._run_gerrit_upload_test(
1388 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001389 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001390 [],
1391 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001392 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001393 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001394
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001395 def test_gerrit_upload_squash_first_against_rev(self):
1396 custom_cl_base = 'custom_cl_base_rev_or_branch'
1397 self._run_gerrit_upload_test(
1398 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001399 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001400 [],
1401 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001402 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001403 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001404 self.assertIn(
1405 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1406 sys.stdout.getvalue())
1407
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001408 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001409 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001410 self._run_gerrit_upload_test(
1411 ['--squash'],
1412 description,
1413 [],
1414 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001415 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001416 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001417
Edward Lemurd55c5072020-02-20 01:09:07 +00001418 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001419 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001420 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001421 with self.assertRaises(SystemExitMock):
1422 self._run_gerrit_upload_test(
1423 ['--squash'],
1424 description,
1425 [],
1426 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001427 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001428 fetched_status='ABANDONED',
1429 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001430 self.assertEqual(
1431 'Change https://chromium-review.googlesource.com/123456 has been '
1432 'abandoned, new uploads are not allowed\n',
1433 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001434
Edward Lemurda4b6c62020-02-13 00:28:40 +00001435 @mock.patch(
1436 'gerrit_util.GetAccountDetails',
1437 return_value={'email': 'yet-another@example.com'})
1438 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001439 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001440 self._run_gerrit_upload_test(
1441 ['--squash'],
1442 description,
1443 [],
1444 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001445 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001446 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001447 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001448 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001449 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001450 'authenticate to Gerrit as yet-another@example.com.\n'
1451 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001452 sys.stdout.getvalue())
Joanna Wang583ca662022-04-27 21:17:17 +00001453 @mock.patch('sys.stderr', StringIO())
1454 def test_gerrit_upload_for_merged(self):
1455 with self.assertRaises(SystemExitMock):
1456 self._run_gerrit_upload_test(
1457 [],
1458 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
1459 [],
1460 issue=123456,
1461 fetched_status='MERGED',
1462 change_id='I123456789',
1463 reset_issue=False)
1464 self.assertEqual(
1465 'New uploads are not allowed.\n',
1466 sys.stderr.getvalue())
1467
1468 def test_gerrit_upload_new_issue_for_merged(self):
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=True)
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001477
Josipe827b0f2020-01-30 00:07:20 +00001478 def test_upload_change_description_editor(self):
1479 fetched_description = 'foo\n\nChange-Id: 123456789'
1480 description = 'bar\n\nChange-Id: 123456789'
1481 self._run_gerrit_upload_test(
1482 ['--squash', '--edit-description'],
1483 description,
1484 [],
1485 fetched_description=fetched_description,
1486 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001487 issue=123456,
1488 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001489 edit_description=description)
1490
Edward Lemurda4b6c62020-02-13 00:28:40 +00001491 @mock.patch('git_cl.RunGit')
1492 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001493 @mock.patch('sys.stdin', StringIO('\n'))
1494 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001495 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001496 def mock_run_git(*args, **_kwargs):
1497 if args[0] == ['for-each-ref',
1498 '--format=%(refname:short) %(upstream:short)',
1499 'refs/heads']:
1500 # Create a local branch dependency tree that looks like this:
1501 # test1 -> test2 -> test3 -> test4 -> test5
1502 # -> test3.1
1503 # test6 -> test0
1504 branch_deps = [
1505 'test2 test1', # test1 -> test2
1506 'test3 test2', # test2 -> test3
1507 'test3.1 test2', # test2 -> test3.1
1508 'test4 test3', # test3 -> test4
1509 'test5 test4', # test4 -> test5
1510 'test6 test0', # test0 -> test6
1511 'test7', # test7
1512 ]
1513 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001514 git_cl.RunGit.side_effect = mock_run_git
1515 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001516
1517 class MockChangelist():
1518 def __init__(self):
1519 pass
1520 def GetBranch(self):
1521 return 'test1'
1522 def GetIssue(self):
1523 return '123'
1524 def GetPatchset(self):
1525 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001526 def IsGerrit(self):
1527 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001528
1529 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1530 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001531 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001532 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001533 'This command will checkout all dependent branches '
1534 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001535 'or Ctrl+C to abort',
1536 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001537 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001538
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001539 def test_gerrit_change_id(self):
1540 self.calls = [
1541 ((['git', 'write-tree'], ),
1542 'hashtree'),
1543 ((['git', 'rev-parse', 'HEAD~0'], ),
1544 'branch-parent'),
1545 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1546 'A B <a@b.org> 1456848326 +0100'),
1547 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1548 'C D <c@d.org> 1456858326 +0100'),
1549 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1550 'hashchange'),
1551 ]
1552 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1553 self.assertEqual(change_id, 'Ihashchange')
1554
Edward Lesmes8170c292021-03-19 20:04:43 +00001555 @mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001556 @mock.patch('git_cl.Settings.GetBugPrefix')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001557 @mock.patch('git_cl.Changelist.FetchDescription')
1558 @mock.patch('git_cl.Changelist.GetBranch')
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001559 @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
Edward Lesmese1576912021-02-16 21:53:34 +00001560 @mock.patch('git_cl.Changelist.GetGerritHost')
1561 @mock.patch('git_cl.Changelist.GetGerritProject')
1562 @mock.patch('git_cl.Changelist.GetRemoteBranch')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001563 @mock.patch('owners_client.OwnersClient.BatchListOwners')
1564 def getDescriptionForUploadTest(
Edward Lesmese1576912021-02-16 21:53:34 +00001565 self, mockBatchListOwners=None, mockGetRemoteBranch=None,
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001566 mockGetGerritProject=None, mockGetGerritHost=None,
1567 mockGetCommonAncestorWithUpstream=None, mockGetBranch=None,
Edward Lesmese1576912021-02-16 21:53:34 +00001568 mockFetchDescription=None, mockGetBugPrefix=None,
Edward Lesmes8170c292021-03-19 20:04:43 +00001569 mockIsCodeOwnersEnabledOnHost=None,
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001570 initial_description='desc', bug=None, fixed=None, branch='branch',
1571 reviewers=None, tbrs=None, add_owners_to=None,
1572 expected_description='desc'):
1573 reviewers = reviewers or []
1574 tbrs = tbrs or []
1575 owners_by_path = {
1576 'a': ['a@example.com'],
1577 'b': ['b@example.com'],
1578 'c': ['c@example.com'],
1579 }
Edward Lesmes8170c292021-03-19 20:04:43 +00001580 mockIsCodeOwnersEnabledOnHost.return_value = True
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001581 mockGetBranch.return_value = branch
1582 mockGetBugPrefix.return_value = 'prefix'
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001583 mockGetCommonAncestorWithUpstream.return_value = 'upstream'
Edward Lesmese1576912021-02-16 21:53:34 +00001584 mockGetRemoteBranch.return_value = ('origin', 'refs/remotes/origin/main')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001585 mockFetchDescription.return_value = 'desc'
1586 mockBatchListOwners.side_effect = lambda ps: {
1587 p: owners_by_path.get(p)
1588 for p in ps
1589 }
1590
1591 cl = git_cl.Changelist(issue=1234)
Josip Sokcevic340edc32021-07-08 17:01:46 +00001592 actual = cl._GetDescriptionForUpload(options=mock.Mock(
1593 bug=bug,
1594 fixed=fixed,
1595 reviewers=reviewers,
1596 tbrs=tbrs,
1597 add_owners_to=add_owners_to,
1598 message=initial_description),
1599 git_diff_args=None,
1600 files=list(owners_by_path))
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001601 self.assertEqual(expected_description, actual.description)
1602
1603 def testGetDescriptionForUpload(self):
1604 self.getDescriptionForUploadTest()
1605
1606 def testGetDescriptionForUpload_Bug(self):
1607 self.getDescriptionForUploadTest(
1608 bug='1234',
1609 expected_description='\n'.join([
1610 'desc',
1611 '',
1612 'Bug: prefix:1234',
1613 ]))
1614
1615 def testGetDescriptionForUpload_Fixed(self):
1616 self.getDescriptionForUploadTest(
1617 fixed='1234',
1618 expected_description='\n'.join([
1619 'desc',
1620 '',
1621 'Fixed: prefix:1234',
1622 ]))
1623
Josip Sokcevic340edc32021-07-08 17:01:46 +00001624 @mock.patch('git_cl.Changelist.GetIssue')
1625 def testGetDescriptionForUpload_BugFromBranch(self, mockGetIssue):
1626 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001627 self.getDescriptionForUploadTest(
1628 branch='bug-1234',
1629 expected_description='\n'.join([
1630 'desc',
1631 '',
1632 'Bug: prefix:1234',
1633 ]))
1634
Josip Sokcevic340edc32021-07-08 17:01:46 +00001635 @mock.patch('git_cl.Changelist.GetIssue')
1636 def testGetDescriptionForUpload_FixedFromBranch(self, mockGetIssue):
1637 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001638 self.getDescriptionForUploadTest(
1639 branch='fix-1234',
1640 expected_description='\n'.join([
1641 'desc',
1642 '',
1643 'Fixed: prefix:1234',
1644 ]))
1645
Josip Sokcevic340edc32021-07-08 17:01:46 +00001646 def testGetDescriptionForUpload_SkipBugFromBranchIfAlreadyUploaded(self):
1647 self.getDescriptionForUploadTest(
1648 branch='bug-1234',
1649 expected_description='desc',
1650 )
1651
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001652 def testGetDescriptionForUpload_AddOwnersToR(self):
1653 self.getDescriptionForUploadTest(
1654 reviewers=['a@example.com'],
1655 tbrs=['b@example.com'],
1656 add_owners_to='R',
1657 expected_description='\n'.join([
1658 'desc',
1659 '',
1660 'R=a@example.com, c@example.com',
1661 'TBR=b@example.com',
1662 ]))
1663
1664 def testGetDescriptionForUpload_AddOwnersToTBR(self):
1665 self.getDescriptionForUploadTest(
1666 reviewers=['a@example.com'],
1667 tbrs=['b@example.com'],
1668 add_owners_to='TBR',
1669 expected_description='\n'.join([
1670 'desc',
1671 '',
1672 'R=a@example.com',
1673 'TBR=b@example.com, c@example.com',
1674 ]))
1675
1676 def testGetDescriptionForUpload_AddOwnersToNoOwnersNeeded(self):
1677 self.getDescriptionForUploadTest(
1678 reviewers=['a@example.com', 'c@example.com'],
1679 tbrs=['b@example.com'],
1680 add_owners_to='TBR',
1681 expected_description='\n'.join([
1682 'desc',
1683 '',
1684 'R=a@example.com, c@example.com',
1685 'TBR=b@example.com',
1686 ]))
1687
1688 def testGetDescriptionForUpload_Reviewers(self):
1689 self.getDescriptionForUploadTest(
1690 reviewers=['a@example.com', 'b@example.com'],
1691 expected_description='\n'.join([
1692 'desc',
1693 '',
1694 'R=a@example.com, b@example.com',
1695 ]))
1696
1697 def testGetDescriptionForUpload_TBRs(self):
1698 self.getDescriptionForUploadTest(
1699 tbrs=['a@example.com', 'b@example.com'],
1700 expected_description='\n'.join([
1701 'desc',
1702 '',
1703 'TBR=a@example.com, b@example.com',
1704 ]))
1705
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001706 def test_desecription_append_footer(self):
1707 for init_desc, footer_line, expected_desc in [
1708 # Use unique desc first lines for easy test failure identification.
1709 ('foo', 'R=one', 'foo\n\nR=one'),
1710 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1711 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1712 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1713 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1714 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1715 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1716 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1717 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1718 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1719 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1720 ]:
1721 desc = git_cl.ChangeDescription(init_desc)
1722 desc.append_footer(footer_line)
1723 self.assertEqual(desc.description, expected_desc)
1724
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001725 def test_update_reviewers(self):
1726 data = [
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001727 ('foo', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001728 'foo'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001729 ('foo\nR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001730 'foo\nR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001731 ('foo\nTBR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001732 'foo\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001733 ('foo', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001734 'foo\n\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001735 ('foo\nR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001736 'foo\n\nR=a@c, xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001737 ('foo\nTBR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001738 'foo\n\nR=a@c\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001739 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001740 'foo\n\nR=a@c, yy\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001741 ('foo\nBUG=', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001742 'foo\nBUG=\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001743 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001744 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001745 ('foo', ['a@c', 'b@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001746 'foo\n\nR=a@c, b@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001747 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001748 'foo\nBar\n\nR=c@c\nBUG='),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001749 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001750 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001751 # Same as the line before, but full of whitespaces.
1752 (
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001753 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001754 'foo\nBar\n\nR=c@c\n BUG =',
1755 ),
1756 # Whitespaces aren't interpreted as new lines.
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001757 ('foo BUG=allo R=joe ', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001758 'foo BUG=allo R=joe\n\nR=c@c'),
1759 # Redundant TBRs get promoted to Rs
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001760 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001761 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001762 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001763 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001764 actual = []
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001765 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001766 obj = git_cl.ChangeDescription(orig)
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001767 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001768 actual.append(obj.description)
1769 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001770
Nodir Turakulov23b82142017-11-16 11:04:25 -08001771 def test_get_hash_tags(self):
1772 cases = [
1773 ('', []),
1774 ('a', []),
1775 ('[a]', ['a']),
1776 ('[aa]', ['aa']),
1777 ('[a ]', ['a']),
1778 ('[a- ]', ['a']),
1779 ('[a- b]', ['a-b']),
1780 ('[a--b]', ['a-b']),
1781 ('[a', []),
1782 ('[a]x', ['a']),
1783 ('[aa]x', ['aa']),
1784 ('[a b]', ['a-b']),
1785 ('[a b]', ['a-b']),
1786 ('[a__b]', ['a-b']),
1787 ('[a] x', ['a']),
1788 ('[a][b]', ['a', 'b']),
1789 ('[a] [b]', ['a', 'b']),
1790 ('[a][b]x', ['a', 'b']),
1791 ('[a][b] x', ['a', 'b']),
1792 ('[a]\n[b]', ['a']),
1793 ('[a\nb]', []),
1794 ('[a][', ['a']),
1795 ('Revert "[a] feature"', ['a']),
1796 ('Reland "[a] feature"', ['a']),
1797 ('Revert: [a] feature', ['a']),
1798 ('Reland: [a] feature', ['a']),
1799 ('Revert "Reland: [a] feature"', ['a']),
1800 ('Foo: feature', ['foo']),
1801 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001802 ('Change Foo::Bar', []),
1803 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001804 ('Revert "Foo bar: feature"', ['foo-bar']),
1805 ('Reland "Foo bar: feature"', ['foo-bar']),
1806 ]
1807 for desc, expected in cases:
1808 change_desc = git_cl.ChangeDescription(desc)
1809 actual = change_desc.get_hash_tags()
1810 self.assertEqual(
1811 actual,
1812 expected,
1813 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1814
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001815 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'main'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001816 self.assertEqual(None, git_cl.GetTargetRef(None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001817 'refs/remotes/origin/main',
1818 'main'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001819
wittman@chromium.org455dc922015-01-26 20:15:50 +00001820 # Check default target refs for branches.
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001821 self.assertEqual('refs/heads/main',
1822 git_cl.GetTargetRef('origin', 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001823 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001824 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001825 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001826 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001827 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001828 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001829 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001830 self.assertEqual('refs/branch-heads/123',
1831 git_cl.GetTargetRef('origin',
1832 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001833 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001834 self.assertEqual('refs/diff/test',
1835 git_cl.GetTargetRef('origin',
1836 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001837 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001838 self.assertEqual('refs/heads/chrome/m42',
1839 git_cl.GetTargetRef('origin',
1840 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001841 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001842
1843 # Check target refs for user-specified target branch.
1844 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1845 'refs/remotes/branch-heads/123'):
1846 self.assertEqual('refs/branch-heads/123',
1847 git_cl.GetTargetRef('origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001848 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001849 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001850 for branch in ('origin/main', 'remotes/origin/main',
1851 'refs/remotes/origin/main'):
1852 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001853 git_cl.GetTargetRef('origin',
1854 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001855 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001856 for branch in ('main', 'heads/main', 'refs/heads/main'):
1857 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001858 git_cl.GetTargetRef('origin',
1859 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001860 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001861
Edward Lemurda4b6c62020-02-13 00:28:40 +00001862 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1863 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001864 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001865 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1866
Edward Lemur85153282020-02-14 22:06:29 +00001867 def assertIssueAndPatchset(
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001868 self, branch='main', issue='123456', patchset='7',
Edward Lemur85153282020-02-14 22:06:29 +00001869 git_short_host='chromium'):
1870 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001871 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001872 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001873 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001874 self.assertEqual(
1875 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001876 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001877
Edward Lemur85153282020-02-14 22:06:29 +00001878 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001879 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001880 self.mockGit.config['remote.origin.url'] = (
1881 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001882 gerrit_util.GetChangeDetail.return_value = {
1883 'current_revision': '7777777777',
1884 'revisions': {
1885 '1111111111': {
1886 '_number': 1,
1887 'fetch': {'http': {
1888 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1889 'ref': 'refs/changes/56/123456/1',
1890 }},
1891 },
1892 '7777777777': {
1893 '_number': 7,
1894 'fetch': {'http': {
1895 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1896 'ref': 'refs/changes/56/123456/7',
1897 }},
1898 },
1899 },
1900 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001901
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001902 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001903 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001904 self.calls += [
1905 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1906 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001907 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001908 ]
1909 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001910 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001911
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001912 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001913 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001914 self.calls += [
1915 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1916 'refs/changes/56/123456/7'],), ''),
1917 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001918 ]
Edward Lemur85153282020-02-14 22:06:29 +00001919 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1920 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001921
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001922 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001923 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001924 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001925 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001926 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001927 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001928 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001929 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001930 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001931
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001932 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001933 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001934 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001935 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001936 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001937 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001938 ]
1939 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001940 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001941 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001942
Aaron Gable697a91b2018-01-19 15:20:15 -08001943 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001944 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001945 self.calls += [
1946 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1947 'refs/changes/56/123456/1'],), ''),
1948 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001949 ]
1950 self.assertEqual(git_cl.main(
1951 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1952 0)
Edward Lemur85153282020-02-14 22:06:29 +00001953 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001954
Edward Lemurd55c5072020-02-20 01:09:07 +00001955 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001956 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001957 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001958 self.calls += [
1959 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001960 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001961 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001962 ]
1963 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001964 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001965 self.assertEqual(
1966 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1967 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001968
Edward Lemurda4b6c62020-02-13 00:28:40 +00001969 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001970 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001971 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001972 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001973 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001974 self.mockGit.config['remote.origin.url'] = (
1975 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001976 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001977 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001978 self.assertEqual(
1979 'change 123456 at https://chromium-review.googlesource.com does not '
1980 'exist or you have no access to it\n',
1981 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001982
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001983 def _checkout_calls(self):
1984 return [
1985 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001986 'branch\\..*\\.gerritissue'], ),
1987 ('branch.ger-branch.gerritissue 123456\n'
1988 'branch.gbranch654.gerritissue 654321\n')),
1989 ]
1990
1991 def test_checkout_gerrit(self):
1992 """Tests git cl checkout <issue>."""
1993 self.calls = self._checkout_calls()
1994 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1995 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1996
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001997 def test_checkout_not_found(self):
1998 """Tests git cl checkout <issue>."""
1999 self.calls = self._checkout_calls()
2000 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2001
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002002 def test_checkout_no_branch_issues(self):
2003 """Tests git cl checkout <issue>."""
2004 self.calls = [
2005 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07002006 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002007 ]
2008 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2009
Edward Lemur26964072020-02-19 19:18:51 +00002010 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00002011 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002012 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002013 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002014 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2015 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00002016 self.mockGit.config['remote.origin.url'] = (
2017 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00002018 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002019 cl.branch = 'main'
2020 cl.branchref = 'refs/heads/main'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002021 return cl
2022
Edward Lemurd55c5072020-02-20 01:09:07 +00002023 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002024 def test_gerrit_ensure_authenticated_missing(self):
2025 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002026 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002027 })
Edward Lemurd55c5072020-02-20 01:09:07 +00002028 with self.assertRaises(SystemExitMock):
2029 cl.EnsureAuthenticated(force=False)
2030 self.assertEqual(
2031 'Credentials for the following hosts are required:\n'
2032 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002033 'These are read from ~%(sep)s.gitcookies '
2034 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00002035 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002036 'https://chromium-review.googlesource.com/new-password\n' % {
2037 'sep': os.sep,
2038 'netrc': NETRC_FILENAME,
2039 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002040
2041 def test_gerrit_ensure_authenticated_conflict(self):
2042 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002043 'chromium.googlesource.com':
2044 ('git-one.example.com', None, 'secret1'),
2045 'chromium-review.googlesource.com':
2046 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002047 })
2048 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002049 (('ask_for_data', 'If you know what you are doing '
2050 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002051 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2052
2053 def test_gerrit_ensure_authenticated_ok(self):
2054 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002055 'chromium.googlesource.com':
2056 ('git-same.example.com', None, 'secret'),
2057 'chromium-review.googlesource.com':
2058 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002059 })
2060 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2061
tandrii@chromium.org28253532016-04-14 13:46:56 +00002062 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00002063 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
2064 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00002065 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2066
Eric Boren2fb63102018-10-05 13:05:03 +00002067 def test_gerrit_ensure_authenticated_bearer_token(self):
2068 cl = self._test_gerrit_ensure_authenticated_common(auth={
2069 'chromium.googlesource.com':
2070 ('', None, 'secret'),
2071 'chromium-review.googlesource.com':
2072 ('', None, 'secret'),
2073 })
2074 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2075 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2076 'chromium.googlesource.com')
2077 self.assertTrue('Bearer' in header)
2078
Daniel Chengcf6269b2019-05-18 01:02:12 +00002079 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00002080 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002081 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002082 (('logging.warning',
2083 'Ignoring branch %(branch)s with non-https remote '
2084 '%(remote)s', {
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002085 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002086 'remote': 'custom-scheme://repo'}
2087 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00002088 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002089 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2090 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2091 mock.patch('logging.warning',
2092 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002093 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002094 cl.branch = 'main'
2095 cl.branchref = 'refs/heads/main'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002096 cl.lookedup_issue = True
2097 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2098
Florian Mayerae510e82020-01-30 21:04:48 +00002099 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00002100 self.mockGit.config['remote.origin.url'] = (
2101 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00002102 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002103 (('logging.error',
2104 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2105 'but it doesn\'t exist.', {
2106 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002107 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002108 'url': 'git@somehost.example:foo/bar.git'}
2109 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00002110 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002111 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2112 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2113 mock.patch('logging.error',
2114 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00002115 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002116 cl.branch = 'main'
2117 cl.branchref = 'refs/heads/main'
Florian Mayerae510e82020-01-30 21:04:48 +00002118 cl.lookedup_issue = True
2119 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2120
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002121 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002122 self.mockGit.config['branch.main.gerritissue'] = '123'
2123 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002124 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00002125 self.mockGit.config['remote.origin.url'] = (
2126 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002127 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00002128 (('SetReview', 'chromium-review.googlesource.com',
2129 'infra%2Finfra~123', None,
2130 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002131 ]
tandriid9e5ce52016-07-13 02:32:59 -07002132
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002133 def _cmd_set_quick_run_gerrit(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002134 self.mockGit.config['branch.main.gerritissue'] = '123'
2135 self.mockGit.config['branch.main.gerritserver'] = (
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002136 'https://chromium-review.googlesource.com')
2137 self.mockGit.config['remote.origin.url'] = (
2138 'https://chromium.googlesource.com/infra/infra')
2139 self.calls = [
2140 (('SetReview', 'chromium-review.googlesource.com',
2141 'infra%2Finfra~123', None,
2142 {'Commit-Queue': 1, 'Quick-Run': 1}, None, None), ''),
2143 ]
2144
tandriid9e5ce52016-07-13 02:32:59 -07002145 def test_cmd_set_commit_gerrit_clear(self):
2146 self._cmd_set_commit_gerrit_common(0)
2147 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2148
2149 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002150 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002151 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2152
tandriid9e5ce52016-07-13 02:32:59 -07002153 def test_cmd_set_commit_gerrit(self):
2154 self._cmd_set_commit_gerrit_common(2)
2155 self.assertEqual(0, git_cl.main(['set-commit']))
2156
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002157 def test_cmd_set_quick_run_gerrit(self):
2158 self._cmd_set_quick_run_gerrit()
2159 self.assertEqual(0, git_cl.main(['set-commit', '-q']))
2160
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002161 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002162 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002163 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002164
2165 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002166 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002167
Edward Lemurda4b6c62020-02-13 00:28:40 +00002168 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07002169 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07002170 try:
2171 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00002172 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00002173 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00002174 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07002175
2176 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07002177 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002178 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002179 return 'foobar'
2180
Edward Lemurda4b6c62020-02-13 00:28:40 +00002181 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07002182 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002183 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002184 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002185 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002186
iannuccie53c9352016-08-17 14:40:40 -07002187 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002188
iannuccie53c9352016-08-17 14:40:40 -07002189 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002190 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002191 return 'foobar'
2192
Edward Lemurda4b6c62020-02-13 00:28:40 +00002193 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2194 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002195 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002196 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002197
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002198 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002199 self.mockGit.config['remote.origin.url'] = (
2200 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002201 gerrit_util.GetChangeDetail.return_value = {
2202 'current_revision': 'sha1',
2203 'revisions': {'sha1': {
2204 'commit': {'message': 'foobar'},
2205 }},
2206 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002207 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002208 'description',
2209 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2210 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002211 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002212
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002213 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002214 mock.patch('git_cl.Changelist', ChangelistMock).start()
2215 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002216
2217 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2218 self.assertEqual('hihi', ChangelistMock.desc)
2219
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002220 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002221 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002222
2223 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002224 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002225 '# Enter a description of the change.\n'
2226 '# This will be displayed on the codereview site.\n'
2227 '# The first line will also be used as the subject of the review.\n'
2228 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002229 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002230 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002231 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002232 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002233 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002234
Edward Lemur6c6827c2020-02-06 21:15:18 +00002235 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002236 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002237
Edward Lemurda4b6c62020-02-13 00:28:40 +00002238 mock.patch('git_cl.Changelist.FetchDescription',
2239 lambda *args: current_desc).start()
2240 mock.patch('git_cl.Changelist.UpdateDescription',
2241 UpdateDescription).start()
2242 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002243
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002244 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002245 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002246
Dan Beamd8b04ca2019-10-10 21:23:26 +00002247 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2248 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2249
2250 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002251 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002252 '# Enter a description of the change.\n'
2253 '# This will be displayed on the codereview site.\n'
2254 '# The first line will also be used as the subject of the review.\n'
2255 '#--------------------This line is 72 characters long'
2256 '--------------------\n'
2257 'Some.\n\nFixed: 123\nChange-Id: xxx',
2258 desc)
2259 return desc
2260
Edward Lemurda4b6c62020-02-13 00:28:40 +00002261 mock.patch('git_cl.Changelist.FetchDescription',
2262 lambda *args: current_desc).start()
2263 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002264
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002265 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002266 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002267
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002268 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002269 mock.patch('git_cl.Changelist', ChangelistMock).start()
2270 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002271
2272 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2273 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2274
kmarshall3bff56b2016-06-06 18:31:47 -07002275 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002276 self.calls = [
2277 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002278 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002279 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002280 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002281 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002282 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002283
Edward Lemurda4b6c62020-02-13 00:28:40 +00002284 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002285 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002286 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002287 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002288 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002289
2290 self.assertEqual(0, git_cl.main(['archive', '-f']))
2291
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002292 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002293 self.calls = [
2294 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002295 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002296 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2297 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002298 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2299 ((['git', 'branch', '-D', 'foo'],), '')
2300 ]
2301
Edward Lemurda4b6c62020-02-13 00:28:40 +00002302 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002303 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002304 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002305 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002306 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002307
2308 self.assertEqual(0, git_cl.main(['archive', '-f']))
2309
kmarshall3bff56b2016-06-06 18:31:47 -07002310 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002311 self.calls = [
2312 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002313 'refs/heads/main'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002314 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002315 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002316
Edward Lemurda4b6c62020-02-13 00:28:40 +00002317 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002318 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002319 [(MockChangelistWithBranchAndIssue('main', 1),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002320 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002321
2322 self.assertEqual(1, git_cl.main(['archive', '-f']))
2323
2324 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002325 self.calls = [
2326 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002327 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002328 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002329 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002330
Edward Lemurda4b6c62020-02-13 00:28:40 +00002331 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002332 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002333 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002334 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002335 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002336
kmarshall9249e012016-08-23 12:02:16 -07002337 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2338
2339 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002340 self.calls = [
2341 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002342 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002343 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002344 ((['git', 'branch', '-D', 'foo'],), '')
2345 ]
kmarshall9249e012016-08-23 12:02:16 -07002346
Edward Lemurda4b6c62020-02-13 00:28:40 +00002347 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002348 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002349 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002350 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002351 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002352
2353 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002354
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002355 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002356 self.calls = [
2357 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002358 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002359 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002360 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2361 'refs/tags/git-cl-archived-456-foo'),
2362 ((['git', 'branch', '-D', 'foo'],), CERR1),
2363 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2364 'refs/tags/git-cl-archived-456-foo'),
2365 ]
2366
Edward Lemurda4b6c62020-02-13 00:28:40 +00002367 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002368 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002369 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002370 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002371 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002372
2373 self.assertEqual(0, git_cl.main(['archive', '-f']))
2374
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002375 def test_archive_with_format(self):
2376 self.calls = [
2377 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002378 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002379 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2380 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2381 ((['git', 'branch', '-D', 'foo'], ), ''),
2382 ]
2383
2384 mock.patch('git_cl.get_cl_statuses',
2385 lambda branches, fine_grained, max_processes:
2386 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2387
2388 self.assertEqual(
2389 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2390
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002391 def test_cmd_issue_erase_existing(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002392 self.mockGit.config['branch.main.gerritissue'] = '123'
2393 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002394 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002395 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002396 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002397 ]
2398 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002399 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2400 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002401
Aaron Gable400e9892017-07-12 15:31:21 -07002402 def test_cmd_issue_erase_existing_with_change_id(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002403 self.mockGit.config['branch.main.gerritissue'] = '123'
2404 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002405 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002406 mock.patch('git_cl.Changelist.FetchDescription',
2407 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002408 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002409 ((['git', 'log', '-1', '--format=%B'],),
2410 'This is a description\n\nChange-Id: Ideadbeef'),
2411 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002412 ]
2413 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002414 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2415 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002416
phajdan.jre328cf92016-08-22 04:12:17 -07002417 def test_cmd_issue_json(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002418 self.mockGit.config['branch.main.gerritissue'] = '123'
2419 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002420 'https://chromium-review.googlesource.com')
Nodir Turakulov27379632021-03-17 18:53:29 +00002421 self.mockGit.config['remote.origin.url'] = (
2422 'https://chromium.googlesource.com/chromium/src'
2423 )
2424 self.calls = [(
2425 (
2426 'write_json',
2427 'output.json',
2428 {
2429 'issue': 123,
2430 'issue_url': 'https://chromium-review.googlesource.com/123',
2431 'gerrit_host': 'chromium-review.googlesource.com',
2432 'gerrit_project': 'chromium/src',
2433 },
2434 ),
2435 '',
2436 )]
phajdan.jre328cf92016-08-22 04:12:17 -07002437 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2438
tandrii16e0b4e2016-06-07 10:34:28 -07002439 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002440 mock.patch(
2441 'git_cl.os.path.abspath',
2442 lambda path: self._mocked_call(['abspath', path])).start()
2443 mock.patch(
2444 'git_cl.os.path.exists',
2445 lambda path: self._mocked_call(['exists', path])).start()
2446 mock.patch(
2447 'git_cl.gclient_utils.FileRead',
2448 lambda path: self._mocked_call(['FileRead', path])).start()
2449 mock.patch(
2450 'git_cl.gclient_utils.rm_file_or_tree',
2451 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002452 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002453 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002454 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002455 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002456
2457 def test_GerritCommitMsgHookCheck_custom_hook(self):
2458 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002459 self.calls += [((['exists',
2460 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2461 ((['FileRead',
2462 os.path.join('.git', 'hooks', 'commit-msg')], ),
2463 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002464 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002465
2466 def test_GerritCommitMsgHookCheck_not_exists(self):
2467 cl = self._common_GerritCommitMsgHookCheck()
2468 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002469 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002470 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002471 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002472
2473 def test_GerritCommitMsgHookCheck(self):
2474 cl = self._common_GerritCommitMsgHookCheck()
2475 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002476 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2477 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002478 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002479 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002480 ((['rm_file_or_tree',
2481 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002482 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002483 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002484
tandriic4344b52016-08-29 06:04:54 -07002485 def test_GerritCmdLand(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002486 self.mockGit.config['branch.main.gerritsquashhash'] = 'deadbeaf'
2487 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002488 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002489 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002490 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002491 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002492 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002493 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002494 'labels': {},
2495 'current_revision': 'deadbeaf',
2496 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002497 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002498 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002499 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002500 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2501 }
Xinan Lin1bd4ffa2021-07-28 00:54:22 +00002502 cl.SubmitIssue = lambda: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002503 self.assertEqual(0, cl.CMDLand(force=True,
2504 bypass_hooks=True,
2505 verbose=True,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00002506 parallel=False,
2507 resultdb=False,
2508 realm=None))
Edward Lemur73c76702020-02-06 23:57:18 +00002509 self.assertIn(
2510 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002511 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002512 self.assertIn(
2513 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002514 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002515
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002516 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lesmeseeca9c62020-11-20 00:00:17 +00002517 mock.patch('git_cl.Changelist.GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002518
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002519 def test_gerrit_change_detail_cache_simple(self):
2520 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002521 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002522 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002523 cl1._cached_remote_url = (
2524 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002525 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002526 cl2._cached_remote_url = (
2527 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002528 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2529 self.assertEqual(cl1._GetChangeDetail(), 'a')
2530 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002531
2532 def test_gerrit_change_detail_cache_options(self):
2533 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002534 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002535 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002536 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002537 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2538 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2539 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2540 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2541 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2542 self.assertEqual(cl._GetChangeDetail(), 'cab')
2543
2544 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2545 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2546 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2547 self.assertEqual(cl._GetChangeDetail(), 'cab')
2548
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002549 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002550 gerrit_util.GetChangeDetail.return_value = {
2551 'current_revision': 'rev1',
2552 'revisions': {
2553 'rev1': {'commit': {'message': 'desc1'}},
2554 },
2555 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002556
2557 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002558 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002559 cl._cached_remote_url = (
2560 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002561 self.assertEqual(cl.FetchDescription(), 'desc1')
2562 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002563
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002564 def test_print_current_creds(self):
2565 class CookiesAuthenticatorMock(object):
2566 def __init__(self):
2567 self.gitcookies = {
2568 'host.googlesource.com': ('user', 'pass'),
2569 'host-review.googlesource.com': ('user', 'pass'),
2570 }
2571 self.netrc = self
2572 self.netrc.hosts = {
2573 'github.com': ('user2', None, 'pass2'),
2574 'host2.googlesource.com': ('user3', None, 'pass'),
2575 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002576 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2577 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002578 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2579 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2580 ' Host\t User\t Which file',
2581 '============================\t=====\t===========',
2582 'host-review.googlesource.com\t user\t.gitcookies',
2583 ' host.googlesource.com\t user\t.gitcookies',
2584 ' host2.googlesource.com\tuser3\t .netrc',
2585 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002586 sys.stdout.seek(0)
2587 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002588 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2589 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2590 ' Host\tUser\t Which file',
2591 '============================\t====\t===========',
2592 'host-review.googlesource.com\tuser\t.gitcookies',
2593 ' host.googlesource.com\tuser\t.gitcookies',
2594 ])
2595
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002596 def _common_creds_check_mocks(self):
2597 def exists_mock(path):
2598 dirname = os.path.dirname(path)
2599 if dirname == os.path.expanduser('~'):
2600 dirname = '~'
2601 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002602 if base in (NETRC_FILENAME, '.gitcookies'):
2603 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002604 # git cl also checks for existence other files not relevant to this test.
2605 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002606 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002607 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002608 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002609 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002610
2611 def test_creds_check_gitcookies_not_configured(self):
2612 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002613 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2614 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002615 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002616 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2617 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2618 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2619 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2620 'or Ctrl+C to abort'), ''),
2621 (([
2622 'git', 'config', '--global', 'http.cookiefile',
2623 os.path.expanduser(os.path.join('~', '.gitcookies'))
2624 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002625 ]
2626 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002627 self.assertTrue(
2628 sys.stdout.getvalue().startswith(
2629 'You seem to be using outdated .netrc for git credentials:'))
2630 self.assertIn(
2631 '\nConfigured git to use .gitcookies from',
2632 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002633
2634 def test_creds_check_gitcookies_configured_custom_broken(self):
2635 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002636 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2637 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002638 custom_cookie_path = ('C:\\.gitcookies'
2639 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002640 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002641 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2642 ((['git', 'config', '--global', 'http.cookiefile'], ),
2643 custom_cookie_path),
2644 (('os.path.exists', custom_cookie_path), False),
2645 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2646 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2647 (([
2648 'git', 'config', '--global', 'http.cookiefile',
2649 os.path.expanduser(os.path.join('~', '.gitcookies'))
2650 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002651 ]
2652 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002653 self.assertIn(
2654 'WARNING: You have configured custom path to .gitcookies: ',
2655 sys.stdout.getvalue())
2656 self.assertIn(
2657 'However, your configured .gitcookies file is missing.',
2658 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002659
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002660 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002661 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002662 self.mockGit.config['remote.origin.url'] = (
2663 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002664 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002665 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002666 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002667 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002668 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002669 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002670
Edward Lemurda4b6c62020-02-13 00:28:40 +00002671 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2672 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002673 self.mockGit.config['remote.origin.url'] = (
2674 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002675 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002676 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002677 'current_revision': 'ba5eba11',
2678 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002679 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002680 '_number': 1,
2681 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002682 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002683 '_number': 2,
2684 },
2685 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002686 'messages': [
2687 {
2688 u'_revision_number': 1,
2689 u'author': {
2690 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002691 u'email': u'could-be-anything@example.com',
2692 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002693 },
2694 u'date': u'2017-03-15 20:08:45.000000000',
2695 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002696 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov899785a2021-07-09 12:45:37 +00002697 u'tag': u'autogenerated:cv:dry-run'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002698 },
2699 {
2700 u'_revision_number': 2,
2701 u'author': {
2702 u'_account_id': 11151243,
2703 u'email': u'owner@example.com',
2704 u'name': u'owner'
2705 },
2706 u'date': u'2017-03-16 20:00:41.000000000',
2707 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2708 u'message': u'PTAL',
2709 },
2710 {
2711 u'_revision_number': 2,
2712 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002713 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002714 u'email': u'reviewer@example.com',
2715 u'name': u'reviewer'
2716 },
2717 u'date': u'2017-03-17 05:19:37.500000000',
2718 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2719 u'message': u'Patch Set 2: Code-Review+1',
2720 },
Josip Sokcevic266129c2021-11-09 00:22:00 +00002721 {
2722 u'_revision_number': 2,
2723 u'author': {
2724 u'_account_id': 42,
2725 u'name': u'reviewer'
2726 },
2727 u'date': u'2017-03-17 05:19:37.900000000',
2728 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d0000',
2729 u'message': u'A bot with no email set',
2730 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002731 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002732 }
2733 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002734 (('GetChangeComments', 'chromium-review.googlesource.com',
2735 'infra%2Finfra~1'), {
2736 '/COMMIT_MSG': [
2737 {
2738 'author': {
2739 'email': u'reviewer@example.com'
2740 },
2741 'updated': u'2017-03-17 05:19:37.500000000',
2742 'patch_set': 2,
2743 'side': 'REVISION',
2744 'message': 'Please include a bug link',
2745 },
2746 ],
2747 'codereview.settings': [
2748 {
2749 'author': {
2750 'email': u'owner@example.com'
2751 },
2752 'updated': u'2017-03-16 20:00:41.000000000',
2753 'patch_set': 2,
2754 'side': 'PARENT',
2755 'line': 42,
2756 'message': 'I removed this because it is bad',
2757 },
2758 ]
2759 }),
2760 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2761 'infra%2Finfra~1'), {}),
2762 ] * 2 + [(('write_json', 'output.json', [{
2763 u'date':
2764 u'2017-03-16 20:00:41.000000',
2765 u'message': (u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2766 u' Base, Line 42: https://crrev.com/c/1/2/'
2767 u'codereview.settings#b42\n' +
2768 u' I removed this because it is bad\n'),
2769 u'autogenerated':
2770 False,
2771 u'approval':
2772 False,
2773 u'disapproval':
2774 False,
2775 u'sender':
2776 u'owner@example.com'
2777 }, {
2778 u'date':
2779 u'2017-03-17 05:19:37.500000',
2780 u'message':
2781 (u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2782 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
2783 u' Please include a bug link\n'),
2784 u'autogenerated':
2785 False,
2786 u'approval':
2787 False,
2788 u'disapproval':
2789 False,
2790 u'sender':
2791 u'reviewer@example.com'
2792 }]), '')]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002793 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002794 git_cl._CommentSummary(
2795 message=(u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2796 u' Base, Line 42: https://crrev.com/c/1/2/' +
2797 u'codereview.settings#b42\n' +
2798 u' I removed this because it is bad\n'),
2799 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
2800 autogenerated=False,
2801 disapproval=False,
2802 approval=False,
2803 sender=u'owner@example.com'),
2804 git_cl._CommentSummary(message=(
2805 u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2806 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002807 u' Please include a bug link\n'),
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002808 date=datetime.datetime(2017, 3, 17, 5, 19, 37,
2809 500000),
2810 autogenerated=False,
2811 disapproval=False,
2812 approval=False,
2813 sender=u'reviewer@example.com'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002814 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002815 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002816 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002817 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002818 self.assertEqual(
2819 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2820
2821 def test_git_cl_comments_robot_comments(self):
2822 # git cl comments also fetches robot comments (which are considered a type
2823 # of autogenerated comment), and unlike other types of comments, only robot
2824 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002825 self.mockGit.config['remote.origin.url'] = (
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002826 'https://x.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002827 gerrit_util.GetChangeDetail.return_value = {
2828 'owner': {'email': 'owner@example.com'},
2829 'current_revision': 'ba5eba11',
2830 'revisions': {
2831 'deadbeaf': {
2832 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002833 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002834 'ba5eba11': {
2835 '_number': 2,
2836 },
2837 },
2838 'messages': [
2839 {
2840 u'_revision_number': 1,
2841 u'author': {
2842 u'_account_id': 1111084,
2843 u'email': u'commit-bot@chromium.org',
2844 u'name': u'Commit Bot'
2845 },
2846 u'date': u'2017-03-15 20:08:45.000000000',
2847 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2848 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2849 u'tag': u'autogenerated:cq:dry-run'
2850 },
2851 {
2852 u'_revision_number': 1,
2853 u'author': {
2854 u'_account_id': 123,
2855 u'email': u'tricium@serviceaccount.com',
2856 u'name': u'Tricium'
2857 },
2858 u'date': u'2017-03-16 20:00:41.000000000',
2859 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2860 u'message': u'(1 comment)',
2861 u'tag': u'autogenerated:tricium',
2862 },
2863 {
2864 u'_revision_number': 1,
2865 u'author': {
2866 u'_account_id': 123,
2867 u'email': u'tricium@serviceaccount.com',
2868 u'name': u'Tricium'
2869 },
2870 u'date': u'2017-03-16 20:00:41.000000000',
2871 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2872 u'message': u'(1 comment)',
2873 u'tag': u'autogenerated:tricium',
2874 },
2875 {
2876 u'_revision_number': 2,
2877 u'author': {
2878 u'_account_id': 123,
2879 u'email': u'tricium@serviceaccount.com',
2880 u'name': u'reviewer'
2881 },
2882 u'date': u'2017-03-17 05:30:37.000000000',
2883 u'tag': u'autogenerated:tricium',
2884 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2885 u'message': u'(1 comment)',
2886 },
2887 ]
2888 }
2889 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002890 (('GetChangeComments', 'x-review.googlesource.com', 'infra%2Finfra~1'),
2891 {}),
2892 (('GetChangeRobotComments', 'x-review.googlesource.com',
2893 'infra%2Finfra~1'), {
2894 'codereview.settings': [
2895 {
2896 u'author': {
2897 u'email': u'tricium@serviceaccount.com'
2898 },
2899 u'updated': u'2017-03-17 05:30:37.000000000',
2900 u'robot_run_id': u'5565031076855808',
2901 u'robot_id': u'Linter/Category',
2902 u'tag': u'autogenerated:tricium',
2903 u'patch_set': 2,
2904 u'side': u'REVISION',
2905 u'message': u'Linter warning message text',
2906 u'line': 32,
2907 },
2908 ],
2909 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002910 ]
2911 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002912 git_cl._CommentSummary(
2913 date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2914 message=(u'(1 comment)\n\ncodereview.settings\n'
2915 u' PS2, Line 32: https://x-review.googlesource.com/c/1/2/'
2916 u'codereview.settings#32\n'
2917 u' Linter warning message text\n'),
2918 sender=u'tricium@serviceaccount.com',
2919 autogenerated=True,
2920 approval=False,
2921 disapproval=False)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002922 ]
2923 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002924 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002925 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002926
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002927 def test_get_remote_url_with_mirror(self):
2928 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002929
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002930 def selective_os_path_isdir_mock(path):
2931 if path == '/cache/this-dir-exists':
2932 return self._mocked_call('os.path.isdir', path)
2933 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002934
Edward Lemurda4b6c62020-02-13 00:28:40 +00002935 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002936
2937 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002938 self.mockGit.config['remote.origin.url'] = (
2939 '/cache/this-dir-exists')
2940 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2941 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002942 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002943 (('os.path.isdir', '/cache/this-dir-exists'),
2944 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002945 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002946 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002947 self.assertEqual(cl.GetRemoteUrl(), url)
2948 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2949
Edward Lemur298f2cf2019-02-22 21:40:39 +00002950 def test_get_remote_url_non_existing_mirror(self):
2951 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002952
Edward Lemur298f2cf2019-02-22 21:40:39 +00002953 def selective_os_path_isdir_mock(path):
2954 if path == '/cache/this-dir-doesnt-exist':
2955 return self._mocked_call('os.path.isdir', path)
2956 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002957
Edward Lemurda4b6c62020-02-13 00:28:40 +00002958 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2959 mock.patch('logging.error',
2960 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002961
Edward Lemur26964072020-02-19 19:18:51 +00002962 self.mockGit.config['remote.origin.url'] = (
2963 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002964 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002965 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2966 False),
2967 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002968 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2969 'but it doesn\'t exist.', {
2970 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002971 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002972 'url': '/cache/this-dir-doesnt-exist'}
2973 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002974 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002975 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002976 self.assertIsNone(cl.GetRemoteUrl())
2977
2978 def test_get_remote_url_misconfigured_mirror(self):
2979 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002980
Edward Lemur298f2cf2019-02-22 21:40:39 +00002981 def selective_os_path_isdir_mock(path):
2982 if path == '/cache/this-dir-exists':
2983 return self._mocked_call('os.path.isdir', path)
2984 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002985
Edward Lemurda4b6c62020-02-13 00:28:40 +00002986 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2987 mock.patch('logging.error',
2988 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002989
Edward Lemur26964072020-02-19 19:18:51 +00002990 self.mockGit.config['remote.origin.url'] = (
2991 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002992 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002993 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002994 (('logging.error',
2995 'Remote "%(remote)s" for branch "%(branch)s" points to '
2996 '"%(cache_path)s", but it is misconfigured.\n'
2997 '"%(cache_path)s" must be a git repo and must have a remote named '
2998 '"%(remote)s" pointing to the git host.', {
2999 'remote': 'origin',
3000 'cache_path': '/cache/this-dir-exists',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00003001 'branch': 'main'}
Edward Lemur298f2cf2019-02-22 21:40:39 +00003002 ), None),
3003 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003004 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00003005 self.assertIsNone(cl.GetRemoteUrl())
3006
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003007 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00003008 self.mockGit.config['remote.origin.url'] = (
3009 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00003010 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003011 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3012
3013 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00003014 mock.patch('logging.error',
3015 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00003016
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003017 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00003018 (('logging.error',
3019 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
3020 'but it doesn\'t exist.', {
3021 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00003022 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00003023 'url': ''}
3024 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003025 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003026 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003027 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003028
Josip Sokcevicc39ab992020-09-24 20:09:15 +00003029 def test_gerrit_new_default(self):
3030 self._run_gerrit_upload_test(
3031 [],
3032 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
3033 [],
3034 squash=False,
3035 squash_mode='override_nosquash',
3036 change_id='I123456789',
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00003037 default_branch='main')
Josip Sokcevicc39ab992020-09-24 20:09:15 +00003038
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003039
Edward Lemur9aa1a962020-02-25 00:58:38 +00003040class ChangelistTest(unittest.TestCase):
mlcui3da91712021-05-05 10:00:30 +00003041 LAST_COMMIT_SUBJECT = 'Fixes goat teleporter destination to be Australia'
3042
3043 def _mock_run_git(commands):
3044 if commands == ['show', '-s', '--format=%s', 'HEAD']:
3045 return ChangelistTest.LAST_COMMIT_SUBJECT
3046
Edward Lemur227d5102020-02-25 23:45:35 +00003047 def setUp(self):
3048 super(ChangelistTest, self).setUp()
3049 mock.patch('gclient_utils.FileRead').start()
3050 mock.patch('gclient_utils.FileWrite').start()
3051 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
3052 mock.patch(
3053 'git_cl.Changelist.GetCodereviewServer',
3054 return_value='https://chromium-review.googlesource.com').start()
3055 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
3056 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
3057 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
Dirk Pranke6f0df682021-06-25 00:42:33 +00003058 mock.patch('git_cl.Changelist.GetUsePython3', return_value=False).start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003059 mock.patch(
3060 'git_cl.Changelist.GetRemoteBranch',
3061 return_value=('origin', 'refs/remotes/origin/main')).start()
Edward Lemur227d5102020-02-25 23:45:35 +00003062 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
3063 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
3064 mock.patch('git_cl.time_time').start()
3065 mock.patch('metrics.collector').start()
3066 mock.patch('subprocess2.Popen').start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003067 mock.patch(
3068 'git_cl.Changelist.GetGerritProject', return_value='project').start()
Edward Lemur227d5102020-02-25 23:45:35 +00003069 self.addCleanup(mock.patch.stopall)
3070 self.temp_count = 0
3071
Edward Lemur227d5102020-02-25 23:45:35 +00003072 def testRunHook(self):
3073 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003074 'more_cc': ['cc@example.com', 'more@example.com'],
3075 'errors': [],
3076 'notifications': [],
3077 'warnings': [],
Edward Lemur227d5102020-02-25 23:45:35 +00003078 }
3079 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003080 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur227d5102020-02-25 23:45:35 +00003081 mockProcess = mock.Mock()
3082 mockProcess.wait.return_value = 0
3083 subprocess2.Popen.return_value = mockProcess
3084
3085 cl = git_cl.Changelist()
3086 results = cl.RunHook(
3087 committing=True,
3088 may_prompt=True,
3089 verbose=2,
3090 parallel=True,
3091 upstream='upstream',
3092 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003093 all_files=True,
3094 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003095
3096 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003097 subprocess2.Popen.assert_any_call([
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003098 'vpython3', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00003099 '--root', 'root',
3100 '--upstream', 'upstream',
3101 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00003102 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003103 '--gerrit_project', 'project',
3104 '--gerrit_branch', 'refs/heads/main',
3105 '--author', 'author',
Edward Lemur227d5102020-02-25 23:45:35 +00003106 '--issue', '123456',
3107 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00003108 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00003109 '--may_prompt',
3110 '--parallel',
3111 '--all_files',
Bruce Dawson09c0c072022-05-26 20:28:58 +00003112 '--no_diffs',
Edward Lemur227d5102020-02-25 23:45:35 +00003113 '--json_output', '/tmp/fake-temp2',
3114 '--description_file', '/tmp/fake-temp1',
3115 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003116 subprocess2.Popen.assert_any_call([
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003117 'vpython', 'PRESUBMIT_SUPPORT',
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003118 '--root', 'root',
3119 '--upstream', 'upstream',
3120 '--verbose', '--verbose',
3121 '--gerrit_url', 'https://chromium-review.googlesource.com',
3122 '--gerrit_project', 'project',
3123 '--gerrit_branch', 'refs/heads/main',
3124 '--author', 'author',
3125 '--issue', '123456',
3126 '--patchset', '7',
3127 '--commit',
3128 '--may_prompt',
3129 '--parallel',
3130 '--all_files',
Bruce Dawson09c0c072022-05-26 20:28:58 +00003131 '--no_diffs',
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003132 '--json_output', '/tmp/fake-temp4',
3133 '--description_file', '/tmp/fake-temp3',
3134 ])
3135 gclient_utils.FileWrite.assert_any_call(
Edward Lemur1a83da12020-03-04 21:18:36 +00003136 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00003137 metrics.collector.add_repeated('sub_commands', {
3138 'command': 'presubmit',
3139 'execution_time': 100,
3140 'exit_code': 0,
3141 })
3142
Edward Lemur99df04e2020-03-05 19:39:43 +00003143 def testRunHook_FewerOptions(self):
3144 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003145 'more_cc': ['cc@example.com', 'more@example.com'],
3146 'errors': [],
3147 'notifications': [],
3148 'warnings': [],
Edward Lemur99df04e2020-03-05 19:39:43 +00003149 }
3150 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003151 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur99df04e2020-03-05 19:39:43 +00003152 mockProcess = mock.Mock()
3153 mockProcess.wait.return_value = 0
3154 subprocess2.Popen.return_value = mockProcess
3155
3156 git_cl.Changelist.GetAuthor.return_value = None
3157 git_cl.Changelist.GetIssue.return_value = None
3158 git_cl.Changelist.GetPatchset.return_value = None
Edward Lemur99df04e2020-03-05 19:39:43 +00003159
3160 cl = git_cl.Changelist()
3161 results = cl.RunHook(
3162 committing=False,
3163 may_prompt=False,
3164 verbose=0,
3165 parallel=False,
3166 upstream='upstream',
3167 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003168 all_files=False,
3169 resultdb=False)
Edward Lemur99df04e2020-03-05 19:39:43 +00003170
3171 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003172 subprocess2.Popen.assert_any_call([
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003173 'vpython3', 'PRESUBMIT_SUPPORT',
Edward Lemur99df04e2020-03-05 19:39:43 +00003174 '--root', 'root',
3175 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003176 '--gerrit_url', 'https://chromium-review.googlesource.com',
3177 '--gerrit_project', 'project',
3178 '--gerrit_branch', 'refs/heads/main',
Edward Lemur99df04e2020-03-05 19:39:43 +00003179 '--upload',
3180 '--json_output', '/tmp/fake-temp2',
3181 '--description_file', '/tmp/fake-temp1',
3182 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003183 gclient_utils.FileWrite.assert_any_call(
Edward Lemur99df04e2020-03-05 19:39:43 +00003184 '/tmp/fake-temp1', 'description')
3185 metrics.collector.add_repeated('sub_commands', {
3186 'command': 'presubmit',
3187 'execution_time': 100,
3188 'exit_code': 0,
3189 })
3190
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003191 def testRunHook_FewerOptionsResultDB(self):
3192 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003193 'more_cc': ['cc@example.com', 'more@example.com'],
3194 'errors': [],
3195 'notifications': [],
3196 'warnings': [],
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003197 }
3198 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003199 git_cl.time_time.side_effect = [100, 200, 300, 400]
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003200 mockProcess = mock.Mock()
3201 mockProcess.wait.return_value = 0
3202 subprocess2.Popen.return_value = mockProcess
3203
3204 git_cl.Changelist.GetAuthor.return_value = None
3205 git_cl.Changelist.GetIssue.return_value = None
3206 git_cl.Changelist.GetPatchset.return_value = None
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003207
3208 cl = git_cl.Changelist()
3209 results = cl.RunHook(
3210 committing=False,
3211 may_prompt=False,
3212 verbose=0,
3213 parallel=False,
3214 upstream='upstream',
3215 description='description',
3216 all_files=False,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003217 resultdb=True,
3218 realm='chromium:public')
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003219
3220 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003221 subprocess2.Popen.assert_any_call([
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003222 'rdb', 'stream', '-new', '-realm', 'chromium:public', '--',
Josip Sokcevic632bbc02022-05-19 05:32:50 +00003223 'vpython3', 'PRESUBMIT_SUPPORT',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003224 '--root', 'root',
3225 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003226 '--gerrit_url', 'https://chromium-review.googlesource.com',
3227 '--gerrit_project', 'project',
3228 '--gerrit_branch', 'refs/heads/main',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003229 '--upload',
3230 '--json_output', '/tmp/fake-temp2',
3231 '--description_file', '/tmp/fake-temp1',
3232 ])
3233
Edward Lemur227d5102020-02-25 23:45:35 +00003234 @mock.patch('sys.exit', side_effect=SystemExitMock)
3235 def testRunHook_Failure(self, _mock):
3236 git_cl.time_time.side_effect = [100, 200]
3237 mockProcess = mock.Mock()
3238 mockProcess.wait.return_value = 2
3239 subprocess2.Popen.return_value = mockProcess
3240
3241 cl = git_cl.Changelist()
3242 with self.assertRaises(SystemExitMock):
3243 cl.RunHook(
3244 committing=True,
3245 may_prompt=True,
3246 verbose=2,
3247 parallel=True,
3248 upstream='upstream',
3249 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003250 all_files=True,
3251 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003252
3253 sys.exit.assert_called_once_with(2)
3254
Edward Lemur75526302020-02-27 22:31:05 +00003255 def testRunPostUploadHook(self):
3256 cl = git_cl.Changelist()
3257 cl.RunPostUploadHook(2, 'upstream', 'description')
3258
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003259 subprocess2.Popen.assert_any_call([
3260 'vpython',
3261 'PRESUBMIT_SUPPORT',
3262 '--root',
3263 'root',
3264 '--upstream',
3265 'upstream',
3266 '--verbose',
3267 '--verbose',
3268 '--gerrit_url',
3269 'https://chromium-review.googlesource.com',
3270 '--gerrit_project',
3271 'project',
3272 '--gerrit_branch',
3273 'refs/heads/main',
3274 '--author',
3275 'author',
3276 '--issue',
3277 '123456',
3278 '--patchset',
3279 '7',
Edward Lemur75526302020-02-27 22:31:05 +00003280 '--post_upload',
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003281 '--description_file',
3282 '/tmp/fake-temp1',
Edward Lemur75526302020-02-27 22:31:05 +00003283 ])
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003284 subprocess2.Popen.assert_called_with([
3285 'vpython3',
3286 'PRESUBMIT_SUPPORT',
3287 '--root',
3288 'root',
3289 '--upstream',
3290 'upstream',
3291 '--verbose',
3292 '--verbose',
3293 '--gerrit_url',
3294 'https://chromium-review.googlesource.com',
3295 '--gerrit_project',
3296 'project',
3297 '--gerrit_branch',
3298 'refs/heads/main',
3299 '--author',
3300 'author',
3301 '--issue',
3302 '123456',
3303 '--patchset',
3304 '7',
3305 '--post_upload',
3306 '--description_file',
3307 '/tmp/fake-temp1',
3308 '--use-python3',
3309 ])
3310
Edward Lemur75526302020-02-27 22:31:05 +00003311 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00003312 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00003313
mlcui3da91712021-05-05 10:00:30 +00003314 @mock.patch('git_cl.RunGit', _mock_run_git)
3315 def testDefaultTitleEmptyMessage(self):
3316 cl = git_cl.Changelist()
3317 cl.issue = 100
3318 options = optparse.Values({
3319 'squash': True,
3320 'title': None,
3321 'message': None,
3322 'force': None,
3323 'skip_title': None
3324 })
3325
3326 mock.patch('gclient_utils.AskForData', lambda _: user_title).start()
3327 for user_title in ['', 'y', 'Y']:
3328 self.assertEqual(cl._GetTitleForUpload(options), self.LAST_COMMIT_SUBJECT)
3329
3330 for user_title in ['not empty', 'yes', 'YES']:
3331 self.assertEqual(cl._GetTitleForUpload(options), user_title)
3332
Edward Lemur9aa1a962020-02-25 00:58:38 +00003333
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003334class CMDTestCaseBase(unittest.TestCase):
3335 _STATUSES = [
3336 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3337 'INFRA_FAILURE', 'CANCELED',
3338 ]
3339 _CHANGE_DETAIL = {
3340 'project': 'depot_tools',
3341 'status': 'OPEN',
3342 'owner': {'email': 'owner@e.mail'},
3343 'current_revision': 'beeeeeef',
3344 'revisions': {
Gavin Make61ccc52020-11-13 00:12:57 +00003345 'deadbeaf': {
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00003346 '_number': 6,
Gavin Make61ccc52020-11-13 00:12:57 +00003347 'kind': 'REWORK',
3348 },
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003349 'beeeeeef': {
3350 '_number': 7,
Gavin Make61ccc52020-11-13 00:12:57 +00003351 'kind': 'NO_CODE_CHANGE',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003352 'fetch': {'http': {
3353 'url': 'https://chromium.googlesource.com/depot_tools',
3354 'ref': 'refs/changes/56/123456/7'
3355 }},
3356 },
3357 },
3358 }
3359 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003360 'builds': [{
3361 'id': str(100 + idx),
3362 'builder': {
3363 'project': 'chromium',
3364 'bucket': 'try',
3365 'builder': 'bot_' + status.lower(),
3366 },
3367 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3368 'tags': [],
3369 'status': status,
3370 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003371 }
3372
Edward Lemur4c707a22019-09-24 21:13:43 +00003373 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003374 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00003375 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003376 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3377 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003378 mock.patch(
3379 'git_cl.Changelist.GetCodereviewServer',
3380 return_value='https://chromium-review.googlesource.com').start()
3381 mock.patch(
Edward Lesmeseeca9c62020-11-20 00:00:17 +00003382 'git_cl.Changelist.GetGerritHost',
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003383 return_value='chromium-review.googlesource.com').start()
3384 mock.patch(
3385 'git_cl.Changelist.GetMostRecentPatchset',
3386 return_value=7).start()
3387 mock.patch(
Gavin Make61ccc52020-11-13 00:12:57 +00003388 'git_cl.Changelist.GetMostRecentDryRunPatchset',
3389 return_value=6).start()
3390 mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003391 'git_cl.Changelist.GetRemoteUrl',
3392 return_value='https://chromium.googlesource.com/depot_tools').start()
3393 mock.patch(
3394 'auth.Authenticator',
3395 return_value=AuthenticatorMock()).start()
3396 mock.patch(
3397 'gerrit_util.GetChangeDetail',
3398 return_value=self._CHANGE_DETAIL).start()
3399 mock.patch(
3400 'git_cl._call_buildbucket',
3401 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003402 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003403 self.addCleanup(mock.patch.stopall)
3404
Edward Lemur4c707a22019-09-24 21:13:43 +00003405
Edward Lemur9468eba2020-02-27 19:07:22 +00003406class CMDPresubmitTestCase(CMDTestCaseBase):
3407 def setUp(self):
3408 super(CMDPresubmitTestCase, self).setUp()
3409 mock.patch(
3410 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3411 return_value='upstream').start()
3412 mock.patch(
3413 'git_cl.Changelist.FetchDescription',
3414 return_value='fetch description').start()
3415 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003416 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003417 return_value='get description').start()
3418 mock.patch('git_cl.Changelist.RunHook').start()
3419
3420 def testDefaultCase(self):
3421 self.assertEqual(0, git_cl.main(['presubmit']))
3422 git_cl.Changelist.RunHook.assert_called_once_with(
3423 committing=True,
3424 may_prompt=False,
3425 verbose=0,
3426 parallel=None,
3427 upstream='upstream',
3428 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003429 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003430 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003431 resultdb=None,
3432 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003433
3434 def testNoIssue(self):
3435 git_cl.Changelist.GetIssue.return_value = None
3436 self.assertEqual(0, git_cl.main(['presubmit']))
3437 git_cl.Changelist.RunHook.assert_called_once_with(
3438 committing=True,
3439 may_prompt=False,
3440 verbose=0,
3441 parallel=None,
3442 upstream='upstream',
3443 description='get description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003444 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003445 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003446 resultdb=None,
3447 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003448
3449 def testCustomBranch(self):
3450 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3451 git_cl.Changelist.RunHook.assert_called_once_with(
3452 committing=True,
3453 may_prompt=False,
3454 verbose=0,
3455 parallel=None,
3456 upstream='custom_branch',
3457 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003458 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003459 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003460 resultdb=None,
3461 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003462
3463 def testOptions(self):
3464 self.assertEqual(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003465 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u',
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003466 '--resultdb', '--realm', 'chromium:public']))
Edward Lemur9468eba2020-02-27 19:07:22 +00003467 git_cl.Changelist.RunHook.assert_called_once_with(
3468 committing=False,
3469 may_prompt=False,
3470 verbose=2,
3471 parallel=True,
3472 upstream='upstream',
3473 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003474 all_files=True,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003475 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003476 resultdb=True,
3477 realm='chromium:public')
Edward Lemur9468eba2020-02-27 19:07:22 +00003478
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003479class CMDTryResultsTestCase(CMDTestCaseBase):
3480 _DEFAULT_REQUEST = {
3481 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003482 "gerritChanges": [{
3483 "project": "depot_tools",
3484 "host": "chromium-review.googlesource.com",
Gavin Make61ccc52020-11-13 00:12:57 +00003485 "patchset": 6,
3486 "change": 123456,
3487 }],
3488 },
3489 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3490 ',builds.*.createTime,builds.*.tags'),
3491 }
3492
3493 _TRIVIAL_REQUEST = {
3494 'predicate': {
3495 "gerritChanges": [{
3496 "project": "depot_tools",
3497 "host": "chromium-review.googlesource.com",
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003498 "patchset": 7,
3499 "change": 123456,
3500 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003501 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003502 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3503 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003504 }
3505
3506 def testNoJobs(self):
3507 git_cl._call_buildbucket.return_value = {}
3508
3509 self.assertEqual(0, git_cl.main(['try-results']))
3510 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3511 git_cl._call_buildbucket.assert_called_once_with(
3512 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3513 self._DEFAULT_REQUEST)
3514
Gavin Make61ccc52020-11-13 00:12:57 +00003515 def testTrivialCommits(self):
3516 self.assertEqual(0, git_cl.main(['try-results']))
3517 git_cl._call_buildbucket.assert_called_with(
3518 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3519 self._DEFAULT_REQUEST)
3520
3521 git_cl._call_buildbucket.return_value = {}
3522 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '7']))
3523 git_cl._call_buildbucket.assert_called_with(
3524 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3525 self._TRIVIAL_REQUEST)
3526 self.assertEqual([
3527 'Successes:',
3528 ' bot_success https://ci.chromium.org/b/103',
3529 'Infra Failures:',
3530 ' bot_infra_failure https://ci.chromium.org/b/105',
3531 'Failures:',
3532 ' bot_failure https://ci.chromium.org/b/104',
3533 'Canceled:',
3534 ' bot_canceled ',
3535 'Started:',
3536 ' bot_started https://ci.chromium.org/b/102',
3537 'Scheduled:',
3538 ' bot_scheduled id=101',
3539 'Other:',
3540 ' bot_status_unspecified id=100',
3541 'Total: 7 tryjobs',
3542 'No tryjobs scheduled.',
3543 ], sys.stdout.getvalue().splitlines())
3544
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003545 def testPrintToStdout(self):
3546 self.assertEqual(0, git_cl.main(['try-results']))
3547 self.assertEqual([
3548 'Successes:',
3549 ' bot_success https://ci.chromium.org/b/103',
3550 'Infra Failures:',
3551 ' bot_infra_failure https://ci.chromium.org/b/105',
3552 'Failures:',
3553 ' bot_failure https://ci.chromium.org/b/104',
3554 'Canceled:',
3555 ' bot_canceled ',
3556 'Started:',
3557 ' bot_started https://ci.chromium.org/b/102',
3558 'Scheduled:',
3559 ' bot_scheduled id=101',
3560 'Other:',
3561 ' bot_status_unspecified id=100',
3562 'Total: 7 tryjobs',
3563 ], sys.stdout.getvalue().splitlines())
3564 git_cl._call_buildbucket.assert_called_once_with(
3565 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3566 self._DEFAULT_REQUEST)
3567
3568 def testPrintToStdoutWithMasters(self):
3569 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3570 self.assertEqual([
3571 'Successes:',
3572 ' try bot_success https://ci.chromium.org/b/103',
3573 'Infra Failures:',
3574 ' try bot_infra_failure https://ci.chromium.org/b/105',
3575 'Failures:',
3576 ' try bot_failure https://ci.chromium.org/b/104',
3577 'Canceled:',
3578 ' try bot_canceled ',
3579 'Started:',
3580 ' try bot_started https://ci.chromium.org/b/102',
3581 'Scheduled:',
3582 ' try bot_scheduled id=101',
3583 'Other:',
3584 ' try bot_status_unspecified id=100',
3585 'Total: 7 tryjobs',
3586 ], sys.stdout.getvalue().splitlines())
3587 git_cl._call_buildbucket.assert_called_once_with(
3588 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3589 self._DEFAULT_REQUEST)
3590
3591 @mock.patch('git_cl.write_json')
3592 def testWriteToJson(self, mockJsonDump):
3593 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3594 git_cl._call_buildbucket.assert_called_once_with(
3595 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3596 self._DEFAULT_REQUEST)
3597 mockJsonDump.assert_called_once_with(
3598 'file.json', self._DEFAULT_RESPONSE['builds'])
3599
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003600 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003601 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3602 self.assertEqual(
3603 [
3604 ('chromium', 'try', 'bot_failure'),
3605 ('chromium', 'try', 'bot_infra_failure'),
3606 ],
3607 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003608
3609 def test_filter_failed_for_retry_many_builds(self):
3610
3611 def _build(name, created_sec, status, experimental=False):
3612 assert 0 <= created_sec < 100, created_sec
3613 b = {
3614 'id': 112112,
3615 'builder': {
3616 'project': 'chromium',
3617 'bucket': 'try',
3618 'builder': name,
3619 },
3620 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3621 'status': status,
3622 'tags': [],
3623 }
3624 if experimental:
3625 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3626 return b
3627
3628 builds = [
3629 _build('flaky-last-green', 1, 'FAILURE'),
3630 _build('flaky-last-green', 2, 'SUCCESS'),
3631 _build('flaky', 1, 'SUCCESS'),
3632 _build('flaky', 2, 'FAILURE'),
3633 _build('running', 1, 'FAILED'),
3634 _build('running', 2, 'SCHEDULED'),
3635 _build('yep-still-running', 1, 'STARTED'),
3636 _build('yep-still-running', 2, 'FAILURE'),
3637 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3638 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3639
3640 # Simulate experimental in CQ builder, which developer decided
3641 # to retry manually which resulted in 2nd build non-experimental.
3642 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3643 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3644 ]
3645 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003646 self.assertEqual(
3647 [
3648 ('chromium', 'try', 'flaky'),
3649 ('chromium', 'try', 'sometimes-experimental'),
3650 ],
3651 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003652
3653
3654class CMDTryTestCase(CMDTestCaseBase):
3655
3656 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003657 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003658 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003659 self.assertEqual(0, git_cl.main(['try']))
3660 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3661 self.assertEqual(
3662 sys.stdout.getvalue(),
3663 'Scheduling CQ dry run on: '
3664 'https://chromium-review.googlesource.com/123456\n')
3665
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00003666 @mock.patch('git_cl.Changelist.SetCQState')
3667 def testSetCQQuickRunByDefault(self, mockSetCQState):
3668 mockSetCQState.return_value = 0
3669 self.assertEqual(0, git_cl.main(['try', '-q']))
3670 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.QUICK_RUN)
3671 self.assertEqual(
3672 sys.stdout.getvalue(),
3673 'Scheduling CQ quick run on: '
3674 'https://chromium-review.googlesource.com/123456\n')
3675
Edward Lemur4c707a22019-09-24 21:13:43 +00003676 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003677 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003678 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003679
3680 self.assertEqual(0, git_cl.main([
3681 'try', '-B', 'luci.chromium.try', '-b', 'win',
3682 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3683 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003684 'Scheduling jobs on:\n'
3685 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003686 git_cl.sys.stdout.getvalue())
3687
3688 expected_request = {
3689 "requests": [{
3690 "scheduleBuild": {
3691 "requestId": "uuid4",
3692 "builder": {
3693 "project": "chromium",
3694 "builder": "win",
3695 "bucket": "try",
3696 },
3697 "gerritChanges": [{
3698 "project": "depot_tools",
3699 "host": "chromium-review.googlesource.com",
3700 "patchset": 7,
3701 "change": 123456,
3702 }],
3703 "properties": {
3704 "category": "git_cl_try",
3705 "json": [{"a": 1}, None],
3706 "key": "val",
3707 },
3708 "tags": [
3709 {"value": "win", "key": "builder"},
3710 {"value": "git_cl_try", "key": "user_agent"},
3711 ],
3712 },
3713 }],
3714 }
3715 mockCallBuildbucket.assert_called_with(
3716 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3717
Anthony Polito1a5fe232020-01-24 23:17:52 +00003718 @mock.patch('git_cl._call_buildbucket')
3719 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3720 mockCallBuildbucket.return_value = {}
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003721 mock.patch('git_cl.Changelist.GetRemoteBranch',
3722 return_value=('origin', 'refs/remotes/origin/main')).start()
Anthony Polito1a5fe232020-01-24 23:17:52 +00003723
3724 self.assertEqual(0, git_cl.main([
3725 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3726 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3727 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3728 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003729 'Scheduling jobs on:\n'
3730 ' chromium/try: linux\n'
3731 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003732 git_cl.sys.stdout.getvalue())
3733
3734 expected_request = {
3735 "requests": [{
3736 "scheduleBuild": {
3737 "requestId": "uuid4",
3738 "builder": {
3739 "project": "chromium",
3740 "builder": "linux",
3741 "bucket": "try",
3742 },
3743 "gerritChanges": [{
3744 "project": "depot_tools",
3745 "host": "chromium-review.googlesource.com",
3746 "patchset": 7,
3747 "change": 123456,
3748 }],
3749 "properties": {
3750 "category": "git_cl_try",
3751 "json": [{"a": 1}, None],
3752 "key": "val",
3753 },
3754 "tags": [
3755 {"value": "linux", "key": "builder"},
3756 {"value": "git_cl_try", "key": "user_agent"},
3757 ],
3758 "gitilesCommit": {
3759 "host": "chromium-review.googlesource.com",
3760 "project": "depot_tools",
3761 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003762 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003763 }
3764 },
3765 },
3766 {
3767 "scheduleBuild": {
3768 "requestId": "uuid4",
3769 "builder": {
3770 "project": "chromium",
3771 "builder": "win",
3772 "bucket": "try",
3773 },
3774 "gerritChanges": [{
3775 "project": "depot_tools",
3776 "host": "chromium-review.googlesource.com",
3777 "patchset": 7,
3778 "change": 123456,
3779 }],
3780 "properties": {
3781 "category": "git_cl_try",
3782 "json": [{"a": 1}, None],
3783 "key": "val",
3784 },
3785 "tags": [
3786 {"value": "win", "key": "builder"},
3787 {"value": "git_cl_try", "key": "user_agent"},
3788 ],
3789 "gitilesCommit": {
3790 "host": "chromium-review.googlesource.com",
3791 "project": "depot_tools",
3792 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003793 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003794 }
3795 },
3796 }],
3797 }
3798 mockCallBuildbucket.assert_called_with(
3799 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3800
Edward Lemur45768512020-03-02 19:03:14 +00003801 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003802 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003803 with self.assertRaises(SystemExit):
3804 git_cl.main([
3805 'try', '-B', 'not-a-bucket', '-b', 'win',
3806 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003807 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003808 'Invalid bucket: not-a-bucket.',
3809 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003810
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003811 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003812 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003813 def testScheduleOnBuildbucketRetryFailed(
3814 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003815 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003816 7: [],
3817 6: [{
3818 'id': 112112,
3819 'builder': {
3820 'project': 'chromium',
3821 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003822 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003823 'createTime': '2019-10-09T08:00:01.854286Z',
3824 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003825 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003826 mockCallBuildbucket.return_value = {}
3827
3828 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3829 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003830 'Scheduling jobs on:\n'
3831 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003832 git_cl.sys.stdout.getvalue())
3833
3834 expected_request = {
3835 "requests": [{
3836 "scheduleBuild": {
3837 "requestId": "uuid4",
3838 "builder": {
3839 "project": "chromium",
3840 "bucket": "try",
3841 "builder": "linux",
3842 },
3843 "gerritChanges": [{
3844 "project": "depot_tools",
3845 "host": "chromium-review.googlesource.com",
3846 "patchset": 7,
3847 "change": 123456,
3848 }],
3849 "properties": {
3850 "category": "git_cl_try",
3851 },
3852 "tags": [
3853 {"value": "linux", "key": "builder"},
3854 {"value": "git_cl_try", "key": "user_agent"},
3855 {"value": "1", "key": "retry_failed"},
3856 ],
3857 },
3858 }],
3859 }
3860 mockCallBuildbucket.assert_called_with(
3861 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3862
Edward Lemur4c707a22019-09-24 21:13:43 +00003863 def test_parse_bucket(self):
3864 test_cases = [
3865 {
3866 'bucket': 'chromium/try',
3867 'result': ('chromium', 'try'),
3868 },
3869 {
3870 'bucket': 'luci.chromium.try',
3871 'result': ('chromium', 'try'),
3872 'has_warning': True,
3873 },
3874 {
3875 'bucket': 'skia.primary',
3876 'result': ('skia', 'skia.primary'),
3877 'has_warning': True,
3878 },
3879 {
3880 'bucket': 'not-a-bucket',
3881 'result': (None, None),
3882 },
3883 ]
3884
3885 for test_case in test_cases:
3886 git_cl.sys.stdout.truncate(0)
3887 self.assertEqual(
3888 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3889 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003890 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3891 test_case['result'])
3892 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003893
3894
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003895class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003896
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003897 def setUp(self):
3898 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003899 mock.patch('git_cl._fetch_tryjobs').start()
3900 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003901 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003902 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3903 mock.patch(
3904 'git_cl.Settings.GetSquashGerritUploads',
3905 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003906 self.addCleanup(mock.patch.stopall)
3907
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003908 def testWarmUpChangeDetailCache(self):
3909 self.assertEqual(0, git_cl.main(['upload']))
3910 gerrit_util.GetChangeDetail.assert_called_once_with(
3911 'chromium-review.googlesource.com', 'depot_tools~123456',
3912 frozenset([
3913 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3914 'CURRENT_COMMIT']))
3915
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003916 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003917 # This test mocks out the actual upload part, and just asserts that after
3918 # upload, if --retry-failed is added, then the tool will fetch try jobs
3919 # from the previous patchset and trigger the right builders on the latest
3920 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003921 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003922 # Latest patchset: No builds.
3923 [],
3924 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003925 [{
3926 'id': str(100 + idx),
3927 'builder': {
3928 'project': 'chromium',
3929 'bucket': 'try',
3930 'builder': 'bot_' + status.lower(),
3931 },
3932 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3933 'tags': [],
3934 'status': status,
3935 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003936 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003937
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003938 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003939 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003940 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3941 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003942 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003943 expected_buckets = [
3944 ('chromium', 'try', 'bot_failure'),
3945 ('chromium', 'try', 'bot_infra_failure'),
3946 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003947 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3948 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003949
Brian Sheedy59b06a82019-10-14 17:03:29 +00003950
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003951class MakeRequestsHelperTestCase(unittest.TestCase):
3952
3953 def exampleGerritChange(self):
3954 return {
3955 'host': 'chromium-review.googlesource.com',
3956 'project': 'depot_tools',
3957 'change': 1,
3958 'patchset': 2,
3959 }
3960
3961 def testMakeRequestsHelperNoOptions(self):
3962 # Basic test for the helper function _make_tryjob_schedule_requests;
3963 # it shouldn't throw AttributeError even when options doesn't have any
3964 # of the expected values; it will use default option values.
3965 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3966 jobs = [('chromium', 'try', 'my-builder')]
3967 options = optparse.Values()
3968 requests = git_cl._make_tryjob_schedule_requests(
3969 changelist, jobs, options, patchset=None)
3970
3971 # requestId is non-deterministic. Just assert that it's there and has
3972 # a particular length.
3973 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3974 self.assertEqual(requests, [{
3975 'scheduleBuild': {
3976 'builder': {
3977 'bucket': 'try',
3978 'builder': 'my-builder',
3979 'project': 'chromium'
3980 },
3981 'gerritChanges': [self.exampleGerritChange()],
3982 'properties': {
3983 'category': 'git_cl_try'
3984 },
3985 'tags': [{
3986 'key': 'builder',
3987 'value': 'my-builder'
3988 }, {
3989 'key': 'user_agent',
3990 'value': 'git_cl_try'
3991 }]
3992 }
3993 }])
3994
3995 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3996 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3997 jobs = [('chromium', 'try', 'presubmit')]
3998 options = optparse.Values()
3999 requests = git_cl._make_tryjob_schedule_requests(
4000 changelist, jobs, options, patchset=None)
4001 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
4002 'category': 'git_cl_try',
4003 'dry_run': 'true'
4004 })
4005
4006 def testMakeRequestsHelperRevisionSet(self):
4007 # Gitiles commit is specified when revision is in options.
4008 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4009 jobs = [('chromium', 'try', 'my-builder')]
4010 options = optparse.Values({'revision': 'ba5eba11'})
4011 requests = git_cl._make_tryjob_schedule_requests(
4012 changelist, jobs, options, patchset=None)
4013 self.assertEqual(
4014 requests[0]['scheduleBuild']['gitilesCommit'], {
4015 'host': 'chromium-review.googlesource.com',
4016 'id': 'ba5eba11',
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00004017 'project': 'depot_tools',
4018 'ref': 'refs/heads/main',
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00004019 })
4020
4021 def testMakeRequestsHelperRetryFailedSet(self):
4022 # An extra tag is added when retry_failed is in options.
4023 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4024 jobs = [('chromium', 'try', 'my-builder')]
4025 options = optparse.Values({'retry_failed': 'true'})
4026 requests = git_cl._make_tryjob_schedule_requests(
4027 changelist, jobs, options, patchset=None)
4028 self.assertEqual(
4029 requests[0]['scheduleBuild']['tags'], [
4030 {
4031 'key': 'builder',
4032 'value': 'my-builder'
4033 },
4034 {
4035 'key': 'user_agent',
4036 'value': 'git_cl_try'
4037 },
4038 {
4039 'key': 'retry_failed',
4040 'value': '1'
4041 }
4042 ])
4043
4044 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00004045 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00004046 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
4047 jobs = [('chromium', 'try', 'my-builder')]
4048 options = optparse.Values({'category': 'my-special-category'})
4049 requests = git_cl._make_tryjob_schedule_requests(
4050 changelist, jobs, options, patchset=None)
4051 self.assertEqual(requests[0]['scheduleBuild']['properties'],
4052 {'category': 'my-special-category'})
4053
4054
Edward Lemurda4b6c62020-02-13 00:28:40 +00004055class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004056
4057 def setUp(self):
4058 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00004059 mock.patch('git_cl.RunCommand').start()
4060 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
4061 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
4062 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00004063 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00004064 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004065
4066 def tearDown(self):
4067 shutil.rmtree(self._top_dir)
4068 super(CMDFormatTestCase, self).tearDown()
4069
Jamie Madill5e96ad12020-01-13 16:08:35 +00004070 def _make_temp_file(self, fname, contents):
Anthony Politoc64e3902021-04-30 21:55:25 +00004071 gclient_utils.FileWrite(os.path.join(self._top_dir, fname),
4072 ('\n'.join(contents)))
Jamie Madill5e96ad12020-01-13 16:08:35 +00004073
Brian Sheedy59b06a82019-10-14 17:03:29 +00004074 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00004075 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004076
Brian Sheedyb4307d52019-12-02 19:18:17 +00004077 def _check_yapf_filtering(self, files, expected):
4078 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
4079 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00004080
Edward Lemur1a83da12020-03-04 21:18:36 +00004081 def _run_command_mock(self, return_value):
4082 def f(*args, **kwargs):
4083 if 'stdin' in kwargs:
4084 self.assertIsInstance(kwargs['stdin'], bytes)
4085 return return_value
4086 return f
4087
Jamie Madill5e96ad12020-01-13 16:08:35 +00004088 def testClangFormatDiffFull(self):
4089 self._make_temp_file('test.cc', ['// test'])
4090 git_cl.settings.GetFormatFullByDefault.return_value = False
4091 diff_file = [os.path.join(self._top_dir, 'test.cc')]
4092 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
4093
4094 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004095 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004096 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
4097 self._top_dir, 'HEAD')
4098 self.assertEqual(2, return_value)
4099
4100 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004101 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004102 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
4103 self._top_dir, 'HEAD')
4104 self.assertEqual(0, return_value)
4105
4106 def testClangFormatDiff(self):
4107 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00004108 # A valid file is required, so use this test.
4109 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00004110 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
4111
4112 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004113 git_cl.RunCommand.side_effect = self._run_command_mock('error')
4114 return_value = git_cl._RunClangFormatDiff(
4115 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004116 self.assertEqual(2, return_value)
4117
4118 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004119 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004120 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
4121 'HEAD')
4122 self.assertEqual(0, return_value)
4123
Brian Sheedyb4307d52019-12-02 19:18:17 +00004124 def testYapfignoreExplicit(self):
4125 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
4126 files = [
4127 'bar.py',
4128 'foo/bar.py',
4129 'foo/baz.py',
4130 'foo/bar/baz.py',
4131 'foo/bar/foobar.py',
4132 ]
4133 expected = [
4134 'bar.py',
4135 'foo/baz.py',
4136 'foo/bar/foobar.py',
4137 ]
4138 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004139
Brian Sheedyb4307d52019-12-02 19:18:17 +00004140 def testYapfignoreSingleWildcards(self):
4141 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
4142 files = [
4143 'bar.py', # Matched by *bar.py.
4144 'bar.txt',
4145 'foobar.py', # Matched by *bar.py, foo*.
4146 'foobar.txt', # Matched by foo*.
4147 'bazbar.py', # Matched by *bar.py, baz*.py.
4148 'bazbar.txt',
4149 'foo/baz.txt', # Matched by foo*.
4150 'bar/bar.py', # Matched by *bar.py.
4151 'baz/foo.py', # Matched by baz*.py, foo*.
4152 'baz/foo.txt',
4153 ]
4154 expected = [
4155 'bar.txt',
4156 'bazbar.txt',
4157 'baz/foo.txt',
4158 ]
4159 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004160
Brian Sheedyb4307d52019-12-02 19:18:17 +00004161 def testYapfignoreMultiplewildcards(self):
4162 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
4163 files = [
4164 'bar.py', # Matched by *bar*.
4165 'bar.txt', # Matched by *bar*.
4166 'abar.py', # Matched by *bar*.
4167 'foobaz.txt', # Matched by *foo*baz.txt.
4168 'foobaz.py',
4169 'afoobaz.txt', # Matched by *foo*baz.txt.
4170 ]
4171 expected = [
4172 'foobaz.py',
4173 ]
4174 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004175
4176 def testYapfignoreComments(self):
4177 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004178 files = [
4179 'test.py',
4180 'test2.py',
4181 ]
4182 expected = [
4183 'test2.py',
4184 ]
4185 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004186
Anthony Politoc64e3902021-04-30 21:55:25 +00004187 def testYapfHandleUtf8(self):
4188 self._make_yapfignore(['test.py', 'test_🌐.py'])
4189 files = [
4190 'test.py',
4191 'test_🌐.py',
4192 'test2.py',
4193 ]
4194 expected = [
4195 'test2.py',
4196 ]
4197 self._check_yapf_filtering(files, expected)
4198
Brian Sheedy59b06a82019-10-14 17:03:29 +00004199 def testYapfignoreBlankLines(self):
4200 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004201 files = [
4202 'test.py',
4203 'test2.py',
4204 'test3.py',
4205 ]
4206 expected = [
4207 'test3.py',
4208 ]
4209 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004210
4211 def testYapfignoreWhitespace(self):
4212 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004213 files = [
4214 'test.py',
4215 'test2.py',
4216 ]
4217 expected = [
4218 'test2.py',
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 testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004223 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004224 self._check_yapf_filtering([], [])
4225
4226 def testYapfignoreMissingYapfignore(self):
4227 files = [
4228 'test.py',
4229 ]
4230 expected = [
4231 'test.py',
4232 ]
4233 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004234
4235
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004236class CMDStatusTestCase(CMDTestCaseBase):
4237 # Return branch names a,..,f with comitterdates in increasing order, i.e.
4238 # 'f' is the most-recently changed branch.
4239 def _mock_run_git(commands):
4240 if commands == [
4241 'for-each-ref', '--format=%(refname) %(committerdate:unix)',
4242 'refs/heads'
4243 ]:
4244 branches_and_committerdates = [
4245 'refs/heads/a 1',
4246 'refs/heads/b 2',
4247 'refs/heads/c 3',
4248 'refs/heads/d 4',
4249 'refs/heads/e 5',
4250 'refs/heads/f 6',
4251 ]
4252 return '\n'.join(branches_and_committerdates)
4253
4254 # Mock the status in such a way that the issue number gives us an
4255 # indication of the commit date (simplifies manual debugging).
4256 def _mock_get_cl_statuses(branches, fine_grained, max_processes):
4257 for c in branches:
4258 c.issue = (100 + int(c.GetCommitDate()))
4259 yield (c, 'open')
4260
4261 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4262 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4263 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4264 @mock.patch('git_cl.RunGit', _mock_run_git)
4265 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4266 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004267 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004268 @mock.patch('scm.GIT.GetBranch', return_value='a')
4269 def testStatus(self, *_mocks):
4270 self.assertEqual(0, git_cl.main(['status', '--no-branch-color']))
4271 self.maxDiff = None
4272 self.assertEqual(
4273 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4274 ' * a : https://crrev.com/c/101 (open)\n'
4275 ' b : https://crrev.com/c/102 (open)\n'
4276 ' c : https://crrev.com/c/103 (open)\n'
4277 ' d : https://crrev.com/c/104 (open)\n'
4278 ' e : https://crrev.com/c/105 (open)\n'
4279 ' f : https://crrev.com/c/106 (open)\n\n'
4280 'Current branch: a\n'
4281 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4282 'Issue description:\n'
4283 'x\n')
4284
4285 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4286 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4287 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4288 @mock.patch('git_cl.RunGit', _mock_run_git)
4289 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4290 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004291 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004292 @mock.patch('scm.GIT.GetBranch', return_value='a')
4293 def testStatusByDate(self, *_mocks):
4294 self.assertEqual(
4295 0, git_cl.main(['status', '--no-branch-color', '--date-order']))
4296 self.maxDiff = None
4297 self.assertEqual(
4298 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4299 ' f : https://crrev.com/c/106 (open)\n'
4300 ' e : https://crrev.com/c/105 (open)\n'
4301 ' d : https://crrev.com/c/104 (open)\n'
4302 ' c : https://crrev.com/c/103 (open)\n'
4303 ' b : https://crrev.com/c/102 (open)\n'
4304 ' * a : https://crrev.com/c/101 (open)\n\n'
4305 'Current branch: a\n'
4306 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4307 'Issue description:\n'
4308 'x\n')
4309
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004310 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4311 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4312 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4313 @mock.patch('git_cl.RunGit', _mock_run_git)
4314 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4315 @mock.patch('git_cl.Settings.GetRoot', return_value='')
4316 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=True)
4317 @mock.patch('scm.GIT.GetBranch', return_value='a')
4318 def testStatusByDate(self, *_mocks):
4319 self.assertEqual(
4320 0, git_cl.main(['status', '--no-branch-color']))
4321 self.maxDiff = None
4322 self.assertEqual(
4323 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4324 ' f : https://crrev.com/c/106 (open)\n'
4325 ' e : https://crrev.com/c/105 (open)\n'
4326 ' d : https://crrev.com/c/104 (open)\n'
4327 ' c : https://crrev.com/c/103 (open)\n'
4328 ' b : https://crrev.com/c/102 (open)\n'
4329 ' * a : https://crrev.com/c/101 (open)\n\n'
4330 'Current branch: a\n'
4331 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4332 'Issue description:\n'
4333 'x\n')
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004334
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004335class CMDOwnersTestCase(CMDTestCaseBase):
4336 def setUp(self):
4337 super(CMDOwnersTestCase, self).setUp()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004338 self.owners_by_path = {
4339 'foo': ['a@example.com'],
4340 'bar': ['b@example.com', 'c@example.com'],
4341 }
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004342 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
4343 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
4344 mock.patch(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004345 'git_cl.Changelist.GetAffectedFiles',
4346 return_value=list(self.owners_by_path)).start()
4347 mock.patch(
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004348 'git_cl.Changelist.GetCommonAncestorWithUpstream',
4349 return_value='upstream').start()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004350 mock.patch(
Edward Lesmese1576912021-02-16 21:53:34 +00004351 'git_cl.Changelist.GetGerritHost',
4352 return_value='host').start()
4353 mock.patch(
4354 'git_cl.Changelist.GetGerritProject',
4355 return_value='project').start()
4356 mock.patch(
4357 'git_cl.Changelist.GetRemoteBranch',
4358 return_value=('origin', 'refs/remotes/origin/main')).start()
4359 mock.patch(
4360 'owners_client.OwnersClient.BatchListOwners',
Edward Lesmes82b992a2021-01-11 23:24:55 +00004361 return_value=self.owners_by_path).start()
Edward Lesmes8170c292021-03-19 20:04:43 +00004362 mock.patch(
4363 'gerrit_util.IsCodeOwnersEnabledOnHost', return_value=True).start()
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004364 self.addCleanup(mock.patch.stopall)
4365
4366 def testShowAllNoArgs(self):
4367 self.assertEqual(0, git_cl.main(['owners', '--show-all']))
4368 self.assertEqual(
4369 'No files specified for --show-all. Nothing to do.\n',
4370 git_cl.sys.stdout.getvalue())
4371
4372 def testShowAll(self):
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004373 self.assertEqual(
4374 0,
4375 git_cl.main(['owners', '--show-all', 'foo', 'bar', 'baz']))
Edward Lesmese1576912021-02-16 21:53:34 +00004376 owners_client.OwnersClient.BatchListOwners.assert_called_once_with(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004377 ['foo', 'bar', 'baz'])
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004378 self.assertEqual(
4379 '\n'.join([
4380 'Owners for foo:',
4381 ' - a@example.com',
4382 'Owners for bar:',
4383 ' - b@example.com',
4384 ' - c@example.com',
4385 'Owners for baz:',
4386 ' - No owners found',
4387 '',
4388 ]),
4389 sys.stdout.getvalue())
4390
Edward Lesmes82b992a2021-01-11 23:24:55 +00004391 def testBatch(self):
4392 self.assertEqual(0, git_cl.main(['owners', '--batch']))
4393 self.assertIn('a@example.com', sys.stdout.getvalue())
4394 self.assertIn('b@example.com', sys.stdout.getvalue())
4395
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004396
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004397if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01004398 logging.basicConfig(
4399 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004400 unittest.main()