blob: 399c4fcdfbea62b8a1ccab0d9e30e59da749edf9 [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',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000737 change_id=None, default_branch='main'):
Edward Lemur26964072020-02-19 19:18:51 +0000738 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200739 if custom_cl_base:
740 ancestor_revision = custom_cl_base
741 else:
742 # Determine ancestor_revision to be merge base.
Edward Lesmes8c43c3f2021-01-20 00:20:26 +0000743 ancestor_revision = 'origin/' + default_branch
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200744
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100745 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000746 gerrit_util.GetChangeDetail.return_value = {
747 'owner': {'email': (other_cl_owner or 'owner@example.com')},
748 'change_id': (change_id or '123456789'),
749 'current_revision': 'sha1_of_current_revision',
750 'revisions': {'sha1_of_current_revision': {
751 'commit': {'message': fetched_description},
752 }},
753 'status': fetched_status or 'NEW',
754 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100755 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100756 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100757 if other_cl_owner:
758 calls += [
759 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
760 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100761
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100762 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200763 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
764 ([custom_cl_base] if custom_cl_base else
765 [ancestor_revision, 'HEAD']),),
766 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100767 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000768
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100769 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000770
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000771 def _gerrit_upload_calls(self,
772 description,
773 reviewers,
774 squash,
tandriia60502f2016-06-20 02:01:53 -0700775 squash_mode='default',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000776 title=None,
777 notify=False,
778 post_amend_description=None,
779 issue=None,
780 cc=None,
781 custom_cl_base=None,
782 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000783 short_hostname='chromium',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000784 labels=None,
785 change_id=None,
786 final_description=None,
787 gitcookies_exists=True,
788 force=False,
789 edit_description=None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000790 default_branch='main',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000791 push_opts=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000792 if post_amend_description is None:
793 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700794 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200795
796 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000797
Edward Lesmes4de54132020-05-05 19:41:33 +0000798 if squash_mode in ('override_squash', 'override_nosquash'):
799 self.mockGit.config['gerrit.override-squash-uploads'] = (
800 'true' if squash_mode == 'override_squash' else 'false')
801
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000802 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000803 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200804 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200805 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000806 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000807 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000808 calls += [
809 ((['RunEditor'],), description),
810 ]
Josipe827b0f2020-01-30 00:07:20 +0000811 # user wants to edit description
812 if edit_description:
813 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000814 ((['RunEditor'],), edit_description),
815 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000816 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200817
818 if custom_cl_base is None:
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000819 parent = 'origin/' + default_branch
Edward Lesmes8c43c3f2021-01-20 00:20:26 +0000820 git_common.get_or_create_merge_base.return_value = parent
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200821 else:
822 calls += [
823 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000824 'refs/remotes/origin/' + default_branch],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200825 callError(1)), # Means not ancenstor.
826 (('ask_for_data',
827 'Do you take responsibility for cleaning up potential mess '
828 'resulting from proceeding with upload? Press Enter to upload, '
829 'or Ctrl+C to abort'), ''),
830 ]
831 parent = custom_cl_base
832
833 calls += [
834 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
835 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000836 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200837 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000838 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200839 ref_to_push),
840 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000841 else:
842 ref_to_push = 'HEAD'
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000843 parent = 'origin/refs/heads/' + default_branch
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000844
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000845 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000846 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000847 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200848 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000849
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000850 metrics_arguments = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000851
Aaron Gableafd52772017-06-27 16:40:10 -0700852 if notify:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000853 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000854 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700855 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400856 if not issue and squash:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000857 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000858 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700859 else:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000860 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000861 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800862
Edward Lemur5a644f82020-03-18 16:44:57 +0000863 # If issue is given, then description is fetched from Gerrit instead.
864 if issue is None:
865 if squash:
866 title = 'Initial upload'
867 else:
868 if not title:
869 calls += [
870 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
871 (('ask_for_data', 'Title for patchset []: '), 'User input'),
872 ]
873 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700874 if title:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000875 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000876 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000877
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000878 if short_hostname == 'chromium':
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000879 # All reviewers and ccs get into ref_suffix.
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000880 for r in sorted(reviewers):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000881 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000882 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000883 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000884 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000885 for c in sorted(cc):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000886 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000887 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000888 reviewers, cc = [], []
889 else:
890 # TODO(crbug/877717): remove this case.
891 calls += [
892 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
893 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000894 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000895 {
896 e: {'email': e}
897 for e in (reviewers + ['joe@example.com'] + cc)
898 })
899 ]
900 for r in sorted(reviewers):
901 if r != 'bad-account-or-email':
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000902 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000903 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000904 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000905 if issue is None:
906 cc += ['joe@example.com']
907 for c in sorted(cc):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000908 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000909 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000910 if c in cc:
911 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000912
Edward Lemur687ca902018-12-05 02:30:30 +0000913 for k, v in sorted((labels or {}).items()):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000914 ref_suffix += ',l=%s+%d' % (k, v)
Edward Lemur687ca902018-12-05 02:30:30 +0000915 metrics_arguments.append('l=%s+%d' % (k, v))
916
917 if tbr:
918 calls += [
919 (('GetCodeReviewTbrScore',
920 '%s-review.googlesource.com' % short_hostname,
921 'my/repo'),
922 2,),
923 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000924
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000925 calls += [
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000926 (
927 ('time.time', ),
928 1000,
929 ),
930 (
931 ([
932 'git', 'push',
933 'https://%s.googlesource.com/my/repo' % short_hostname,
934 ref_to_push + ':refs/for/refs/heads/' + default_branch +
935 ref_suffix
936 ] + (push_opts if push_opts else []), ),
937 (('remote:\n'
938 'remote: Processing changes: (\)\n'
939 'remote: Processing changes: (|)\n'
940 'remote: Processing changes: (/)\n'
941 'remote: Processing changes: (-)\n'
942 'remote: Processing changes: new: 1 (/)\n'
943 'remote: Processing changes: new: 1, done\n'
944 'remote:\n'
945 'remote: New Changes:\n'
946 'remote: '
947 'https://%s-review.googlesource.com/#/c/my/repo/+/123456'
948 ' XXX\n'
949 'remote:\n'
950 'To https://%s.googlesource.com/my/repo\n'
951 ' * [new branch] hhhh -> refs/for/refs/heads/%s\n') %
952 (short_hostname, short_hostname, default_branch)),
953 ),
954 (
955 ('time.time', ),
956 2000,
957 ),
958 (
959 ('add_repeated', 'sub_commands', {
960 'execution_time': 1000,
961 'command': 'git push',
962 'exit_code': 0,
963 'arguments': sorted(metrics_arguments),
964 }),
965 None,
966 ),
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000967 ]
968
Edward Lemur1b52d872019-05-09 21:12:12 +0000969 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000970
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000971 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
972
Edward Lemur1b52d872019-05-09 21:12:12 +0000973 # Trace-related calls
974 calls += [
975 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000976 (
977 ([
978 'FileWrite', trace_name + '-README',
979 '%(date)s\n'
980 '%(short_hostname)s-review.googlesource.com\n'
981 '%(change_id)s\n'
982 '%(title)s\n'
983 '%(description)s\n'
984 '1000\n'
985 '0\n'
986 '%(trace_name)s' % {
Josip Sokcevic5e18b602020-04-23 21:47:00 +0000987 'date': '2017-03-16T20:00:41.000000',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000988 'short_hostname': short_hostname,
989 'change_id': change_id,
990 'description': final_description,
991 'title': title or '<untitled>',
992 'trace_name': trace_name,
993 }
994 ], ),
995 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000996 ),
997 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000998 (
999 (['os.path.isfile',
1000 os.path.join('TEMP_DIR', 'trace-packet')], ),
1001 True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001002 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001003 (
1004 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
1005 ('git-hash: 0123456789012345678901234567890123456789\n'
1006 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +00001007 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001008 (
1009 ([
1010 'FileWrite',
1011 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
1012 'git-hash: abcdea\n'
1013 ], ),
1014 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001015 ),
1016 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001017 (
1018 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
1019 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001020 ),
1021 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001022 (
1023 (['git', 'config', '-l'], ),
1024 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +00001025 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001026 (
1027 ([
1028 'FileWrite',
1029 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
1030 ], ),
1031 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001032 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001033 (
1034 (['os.path.isfile',
1035 os.path.join('~', '.gitcookies')], ),
1036 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +00001037 ),
1038 ]
1039 if gitcookies_exists:
1040 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001041 (
1042 (['FileRead', os.path.join('~', '.gitcookies')], ),
1043 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +00001044 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001045 (
1046 ([
1047 'FileWrite',
1048 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
1049 ], ),
1050 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001051 ),
1052 ]
1053 calls += [
1054 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001055 (
1056 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
1057 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001058 ),
1059 ]
1060
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001061 # TODO(crbug/877717): this should never be used.
1062 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001063 calls += [
1064 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001065 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001066 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001067 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001068 notify),
1069 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001070 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001071 return calls
1072
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001073 def _run_gerrit_upload_test(self,
1074 upload_args,
1075 description,
1076 reviewers=None,
1077 squash=True,
1078 squash_mode=None,
1079 title=None,
1080 notify=False,
1081 post_amend_description=None,
1082 issue=None,
1083 cc=None,
1084 fetched_status=None,
1085 other_cl_owner=None,
1086 custom_cl_base=None,
1087 tbr=None,
1088 short_hostname='chromium',
1089 labels=None,
1090 change_id=None,
1091 final_description=None,
1092 gitcookies_exists=True,
1093 force=False,
1094 log_description=None,
1095 edit_description=None,
1096 fetched_description=None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001097 default_branch='main',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001098 push_opts=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001099 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001100 if squash_mode is None:
1101 if '--no-squash' in upload_args:
1102 squash_mode = 'nosquash'
1103 elif '--squash' in upload_args:
1104 squash_mode = 'squash'
1105 else:
1106 squash_mode = 'default'
1107
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001108 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001109 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001110 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001111 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001112 same_auth=('git-owner.example.com', '', 'pass'))).start()
1113 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1114 lambda _, offer_removal: None).start()
1115 mock.patch('git_cl.gclient_utils.RunEditor',
1116 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1117 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001118 'DownloadGerritHook', force)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001119 mock.patch('git_cl.gclient_utils.FileRead',
1120 lambda path: self._mocked_call(['FileRead', path])).start()
1121 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001122 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001123 ['FileWrite', path, contents])).start()
1124 mock.patch('git_cl.datetime_now',
1125 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1126 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1127 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1128 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001129 '%(now)s\n'
1130 '%(gerrit_host)s\n'
1131 '%(change_id)s\n'
1132 '%(title)s\n'
1133 '%(description)s\n'
1134 '%(execution_time)s\n'
1135 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001136 '%(trace_name)s').start()
1137 mock.patch('git_cl.shutil.make_archive',
1138 lambda *args: self._mocked_call(['make_archive'] +
1139 list(args))).start()
1140 mock.patch('os.path.isfile',
1141 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001142 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001143 'git_cl._create_description_from_log',
1144 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001145 mock.patch(
1146 'git_cl.Changelist._AddChangeIdToCommitMessage',
1147 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001148 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001149 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1150 mock.patch(
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001151 'git_common.get_or_create_merge_base',
1152 return_value='origin/' + default_branch).start()
1153 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001154 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001155 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001156
Edward Lemur26964072020-02-19 19:18:51 +00001157 self.mockGit.config['gerrit.host'] = 'true'
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001158 self.mockGit.config['branch.main.gerritissue'] = (
Edward Lemur85153282020-02-14 22:06:29 +00001159 str(issue) if issue else None)
1160 self.mockGit.config['remote.origin.url'] = (
1161 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001162 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001163
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001164 self.calls = self._gerrit_base_calls(
1165 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001166 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001167 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001168 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001169 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001170 short_hostname=short_hostname,
Josip Sokcevicc39ab992020-09-24 20:09:15 +00001171 change_id=change_id,
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001172 default_branch=default_branch)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001173 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001174 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001175 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001176 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001177 self.calls += self._gerrit_upload_calls(
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001178 description,
1179 reviewers,
1180 squash,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001181 squash_mode=squash_mode,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001182 title=title,
1183 notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001184 post_amend_description=post_amend_description,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001185 issue=issue,
1186 cc=cc,
1187 custom_cl_base=custom_cl_base,
1188 tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001189 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001190 labels=labels,
1191 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001192 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001193 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001194 force=force,
Josip Sokcevicc39ab992020-09-24 20:09:15 +00001195 edit_description=edit_description,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001196 default_branch=default_branch,
1197 push_opts=push_opts)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001198 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001199 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001200 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001201 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001202 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001203 self.assertEqual(
1204 'abcdef0123456789',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001205 scm.GIT.GetBranchConfig('', 'main', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001206
Edward Lemur1b52d872019-05-09 21:12:12 +00001207 def test_gerrit_upload_traces_no_gitcookies(self):
1208 self._run_gerrit_upload_test(
1209 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001210 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001211 [],
1212 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001213 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001214 change_id='Ixxx',
1215 gitcookies_exists=False)
1216
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001217 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001218 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001219 [],
1220 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1221 [],
1222 change_id='Ixxx')
1223
1224 def test_gerrit_upload_without_change_id_nosquash(self):
1225 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001226 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001227 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001228 [],
1229 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001230 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001231 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001232
Edward Lesmes4de54132020-05-05 19:41:33 +00001233 def test_gerrit_upload_without_change_id_override_nosquash(self):
1234 self._run_gerrit_upload_test(
1235 [],
1236 'desc ✔\n\nBUG=\n',
1237 [],
1238 squash=False,
1239 squash_mode='override_nosquash',
1240 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1241 change_id='Ixxx')
1242
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001243 def test_gerrit_no_reviewer(self):
1244 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001245 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001246 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001247 [],
1248 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001249 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001250 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001251
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001252 def test_gerrit_push_opts(self):
1253 self._run_gerrit_upload_test(['-o', 'wip'],
1254 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
1255 [],
1256 squash=False,
1257 squash_mode='override_nosquash',
1258 change_id='I123456789',
1259 push_opts=['-o', 'wip'])
1260
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001261 def test_gerrit_no_reviewer_non_chromium_host(self):
1262 # TODO(crbug/877717): remove this test case.
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001263 self._run_gerrit_upload_test([],
1264 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
1265 [],
1266 squash=False,
1267 squash_mode='override_nosquash',
1268 short_hostname='other',
1269 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001270
Edward Lesmes0dd54822020-03-26 18:24:25 +00001271 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001272 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001273 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001274 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001275 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001276 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001277 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001278 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001279
ukai@chromium.orge8077812012-02-03 03:41:46 +00001280 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001281 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001282 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001283 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001284 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001285 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001286 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001287 notify=True,
1288 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001289 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001290 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001291
Anthony Polito8b955342019-09-24 19:01:36 +00001292 def test_gerrit_upload_force_sets_bug(self):
1293 self._run_gerrit_upload_test(
1294 ['-b', '10000', '-f'],
1295 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1296 [],
1297 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001298 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001299 change_id='Ixxx')
1300
Edward Lemur5fb22242020-03-12 22:05:13 +00001301 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001302 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001303 ['-b', '10000', '-m', 'Title', '--edit-description'],
1304 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001305 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001306 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001307 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001308 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001309 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001310 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001311
Dan Beamd8b04ca2019-10-10 21:23:26 +00001312 def test_gerrit_upload_force_sets_fixed(self):
1313 self._run_gerrit_upload_test(
1314 ['-x', '10000', '-f'],
1315 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1316 [],
1317 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001318 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001319 change_id='Ixxx')
1320
ukai@chromium.orge8077812012-02-03 03:41:46 +00001321 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001322 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1323 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001324 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001325 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001326 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001327 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001328 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001329 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001330 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001331 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001332 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001333 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001334
1335 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001336 self._run_gerrit_upload_test(
1337 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001338 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001339 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001340 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001341
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001342 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001343 self._run_gerrit_upload_test(
1344 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001345 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001346 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001347 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001348 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001349
Edward Lesmes0dd54822020-03-26 18:24:25 +00001350 def test_gerrit_upload_squash_first_title(self):
1351 self._run_gerrit_upload_test(
1352 ['-f', '-t', 'title'],
1353 'title\n\ndesc\n\nChange-Id: 123456789',
1354 [],
1355 force=True,
1356 squash=True,
1357 log_description='desc',
1358 change_id='123456789')
1359
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001360 def test_gerrit_upload_squash_first_with_labels(self):
1361 self._run_gerrit_upload_test(
1362 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001363 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001364 [],
1365 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001366 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001367 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001368
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001369 def test_gerrit_upload_squash_first_against_rev(self):
1370 custom_cl_base = 'custom_cl_base_rev_or_branch'
1371 self._run_gerrit_upload_test(
1372 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001373 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001374 [],
1375 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001376 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001377 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001378 self.assertIn(
1379 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1380 sys.stdout.getvalue())
1381
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001382 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001383 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001384 self._run_gerrit_upload_test(
1385 ['--squash'],
1386 description,
1387 [],
1388 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001389 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001390 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001391
Edward Lemurd55c5072020-02-20 01:09:07 +00001392 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001393 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001394 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001395 with self.assertRaises(SystemExitMock):
1396 self._run_gerrit_upload_test(
1397 ['--squash'],
1398 description,
1399 [],
1400 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001401 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001402 fetched_status='ABANDONED',
1403 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001404 self.assertEqual(
1405 'Change https://chromium-review.googlesource.com/123456 has been '
1406 'abandoned, new uploads are not allowed\n',
1407 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001408
Edward Lemurda4b6c62020-02-13 00:28:40 +00001409 @mock.patch(
1410 'gerrit_util.GetAccountDetails',
1411 return_value={'email': 'yet-another@example.com'})
1412 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001413 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001414 self._run_gerrit_upload_test(
1415 ['--squash'],
1416 description,
1417 [],
1418 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001419 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001420 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001421 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001422 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001423 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001424 'authenticate to Gerrit as yet-another@example.com.\n'
1425 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001426 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001427
Josipe827b0f2020-01-30 00:07:20 +00001428 def test_upload_change_description_editor(self):
1429 fetched_description = 'foo\n\nChange-Id: 123456789'
1430 description = 'bar\n\nChange-Id: 123456789'
1431 self._run_gerrit_upload_test(
1432 ['--squash', '--edit-description'],
1433 description,
1434 [],
1435 fetched_description=fetched_description,
1436 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001437 issue=123456,
1438 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001439 edit_description=description)
1440
Edward Lemurda4b6c62020-02-13 00:28:40 +00001441 @mock.patch('git_cl.RunGit')
1442 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001443 @mock.patch('sys.stdin', StringIO('\n'))
1444 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001445 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001446 def mock_run_git(*args, **_kwargs):
1447 if args[0] == ['for-each-ref',
1448 '--format=%(refname:short) %(upstream:short)',
1449 'refs/heads']:
1450 # Create a local branch dependency tree that looks like this:
1451 # test1 -> test2 -> test3 -> test4 -> test5
1452 # -> test3.1
1453 # test6 -> test0
1454 branch_deps = [
1455 'test2 test1', # test1 -> test2
1456 'test3 test2', # test2 -> test3
1457 'test3.1 test2', # test2 -> test3.1
1458 'test4 test3', # test3 -> test4
1459 'test5 test4', # test4 -> test5
1460 'test6 test0', # test0 -> test6
1461 'test7', # test7
1462 ]
1463 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001464 git_cl.RunGit.side_effect = mock_run_git
1465 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001466
1467 class MockChangelist():
1468 def __init__(self):
1469 pass
1470 def GetBranch(self):
1471 return 'test1'
1472 def GetIssue(self):
1473 return '123'
1474 def GetPatchset(self):
1475 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001476 def IsGerrit(self):
1477 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001478
1479 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1480 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001481 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001482 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001483 'This command will checkout all dependent branches '
1484 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001485 'or Ctrl+C to abort',
1486 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001487 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001488
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001489 def test_gerrit_change_id(self):
1490 self.calls = [
1491 ((['git', 'write-tree'], ),
1492 'hashtree'),
1493 ((['git', 'rev-parse', 'HEAD~0'], ),
1494 'branch-parent'),
1495 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1496 'A B <a@b.org> 1456848326 +0100'),
1497 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1498 'C D <c@d.org> 1456858326 +0100'),
1499 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1500 'hashchange'),
1501 ]
1502 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1503 self.assertEqual(change_id, 'Ihashchange')
1504
Edward Lesmes8170c292021-03-19 20:04:43 +00001505 @mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001506 @mock.patch('git_cl.Settings.GetBugPrefix')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001507 @mock.patch('git_cl.Changelist.FetchDescription')
1508 @mock.patch('git_cl.Changelist.GetBranch')
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001509 @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
Edward Lesmese1576912021-02-16 21:53:34 +00001510 @mock.patch('git_cl.Changelist.GetGerritHost')
1511 @mock.patch('git_cl.Changelist.GetGerritProject')
1512 @mock.patch('git_cl.Changelist.GetRemoteBranch')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001513 @mock.patch('owners_client.OwnersClient.BatchListOwners')
1514 def getDescriptionForUploadTest(
Edward Lesmese1576912021-02-16 21:53:34 +00001515 self, mockBatchListOwners=None, mockGetRemoteBranch=None,
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001516 mockGetGerritProject=None, mockGetGerritHost=None,
1517 mockGetCommonAncestorWithUpstream=None, mockGetBranch=None,
Edward Lesmese1576912021-02-16 21:53:34 +00001518 mockFetchDescription=None, mockGetBugPrefix=None,
Edward Lesmes8170c292021-03-19 20:04:43 +00001519 mockIsCodeOwnersEnabledOnHost=None,
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001520 initial_description='desc', bug=None, fixed=None, branch='branch',
1521 reviewers=None, tbrs=None, add_owners_to=None,
1522 expected_description='desc'):
1523 reviewers = reviewers or []
1524 tbrs = tbrs or []
1525 owners_by_path = {
1526 'a': ['a@example.com'],
1527 'b': ['b@example.com'],
1528 'c': ['c@example.com'],
1529 }
Edward Lesmes8170c292021-03-19 20:04:43 +00001530 mockIsCodeOwnersEnabledOnHost.return_value = True
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001531 mockGetBranch.return_value = branch
1532 mockGetBugPrefix.return_value = 'prefix'
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001533 mockGetCommonAncestorWithUpstream.return_value = 'upstream'
Edward Lesmese1576912021-02-16 21:53:34 +00001534 mockGetRemoteBranch.return_value = ('origin', 'refs/remotes/origin/main')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001535 mockFetchDescription.return_value = 'desc'
1536 mockBatchListOwners.side_effect = lambda ps: {
1537 p: owners_by_path.get(p)
1538 for p in ps
1539 }
1540
1541 cl = git_cl.Changelist(issue=1234)
Josip Sokcevic340edc32021-07-08 17:01:46 +00001542 actual = cl._GetDescriptionForUpload(options=mock.Mock(
1543 bug=bug,
1544 fixed=fixed,
1545 reviewers=reviewers,
1546 tbrs=tbrs,
1547 add_owners_to=add_owners_to,
1548 message=initial_description),
1549 git_diff_args=None,
1550 files=list(owners_by_path))
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001551 self.assertEqual(expected_description, actual.description)
1552
1553 def testGetDescriptionForUpload(self):
1554 self.getDescriptionForUploadTest()
1555
1556 def testGetDescriptionForUpload_Bug(self):
1557 self.getDescriptionForUploadTest(
1558 bug='1234',
1559 expected_description='\n'.join([
1560 'desc',
1561 '',
1562 'Bug: prefix:1234',
1563 ]))
1564
1565 def testGetDescriptionForUpload_Fixed(self):
1566 self.getDescriptionForUploadTest(
1567 fixed='1234',
1568 expected_description='\n'.join([
1569 'desc',
1570 '',
1571 'Fixed: prefix:1234',
1572 ]))
1573
Josip Sokcevic340edc32021-07-08 17:01:46 +00001574 @mock.patch('git_cl.Changelist.GetIssue')
1575 def testGetDescriptionForUpload_BugFromBranch(self, mockGetIssue):
1576 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001577 self.getDescriptionForUploadTest(
1578 branch='bug-1234',
1579 expected_description='\n'.join([
1580 'desc',
1581 '',
1582 'Bug: prefix:1234',
1583 ]))
1584
Josip Sokcevic340edc32021-07-08 17:01:46 +00001585 @mock.patch('git_cl.Changelist.GetIssue')
1586 def testGetDescriptionForUpload_FixedFromBranch(self, mockGetIssue):
1587 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001588 self.getDescriptionForUploadTest(
1589 branch='fix-1234',
1590 expected_description='\n'.join([
1591 'desc',
1592 '',
1593 'Fixed: prefix:1234',
1594 ]))
1595
Josip Sokcevic340edc32021-07-08 17:01:46 +00001596 def testGetDescriptionForUpload_SkipBugFromBranchIfAlreadyUploaded(self):
1597 self.getDescriptionForUploadTest(
1598 branch='bug-1234',
1599 expected_description='desc',
1600 )
1601
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001602 def testGetDescriptionForUpload_AddOwnersToR(self):
1603 self.getDescriptionForUploadTest(
1604 reviewers=['a@example.com'],
1605 tbrs=['b@example.com'],
1606 add_owners_to='R',
1607 expected_description='\n'.join([
1608 'desc',
1609 '',
1610 'R=a@example.com, c@example.com',
1611 'TBR=b@example.com',
1612 ]))
1613
1614 def testGetDescriptionForUpload_AddOwnersToTBR(self):
1615 self.getDescriptionForUploadTest(
1616 reviewers=['a@example.com'],
1617 tbrs=['b@example.com'],
1618 add_owners_to='TBR',
1619 expected_description='\n'.join([
1620 'desc',
1621 '',
1622 'R=a@example.com',
1623 'TBR=b@example.com, c@example.com',
1624 ]))
1625
1626 def testGetDescriptionForUpload_AddOwnersToNoOwnersNeeded(self):
1627 self.getDescriptionForUploadTest(
1628 reviewers=['a@example.com', 'c@example.com'],
1629 tbrs=['b@example.com'],
1630 add_owners_to='TBR',
1631 expected_description='\n'.join([
1632 'desc',
1633 '',
1634 'R=a@example.com, c@example.com',
1635 'TBR=b@example.com',
1636 ]))
1637
1638 def testGetDescriptionForUpload_Reviewers(self):
1639 self.getDescriptionForUploadTest(
1640 reviewers=['a@example.com', 'b@example.com'],
1641 expected_description='\n'.join([
1642 'desc',
1643 '',
1644 'R=a@example.com, b@example.com',
1645 ]))
1646
1647 def testGetDescriptionForUpload_TBRs(self):
1648 self.getDescriptionForUploadTest(
1649 tbrs=['a@example.com', 'b@example.com'],
1650 expected_description='\n'.join([
1651 'desc',
1652 '',
1653 'TBR=a@example.com, b@example.com',
1654 ]))
1655
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001656 def test_desecription_append_footer(self):
1657 for init_desc, footer_line, expected_desc in [
1658 # Use unique desc first lines for easy test failure identification.
1659 ('foo', 'R=one', 'foo\n\nR=one'),
1660 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1661 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1662 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1663 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1664 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1665 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1666 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1667 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1668 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1669 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1670 ]:
1671 desc = git_cl.ChangeDescription(init_desc)
1672 desc.append_footer(footer_line)
1673 self.assertEqual(desc.description, expected_desc)
1674
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001675 def test_update_reviewers(self):
1676 data = [
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001677 ('foo', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001678 'foo'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001679 ('foo\nR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001680 'foo\nR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001681 ('foo\nTBR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001682 'foo\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001683 ('foo', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001684 'foo\n\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001685 ('foo\nR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001686 'foo\n\nR=a@c, xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001687 ('foo\nTBR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001688 'foo\n\nR=a@c\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001689 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001690 'foo\n\nR=a@c, yy\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001691 ('foo\nBUG=', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001692 'foo\nBUG=\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001693 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001694 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001695 ('foo', ['a@c', 'b@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001696 'foo\n\nR=a@c, b@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001697 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001698 'foo\nBar\n\nR=c@c\nBUG='),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001699 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001700 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001701 # Same as the line before, but full of whitespaces.
1702 (
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001703 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001704 'foo\nBar\n\nR=c@c\n BUG =',
1705 ),
1706 # Whitespaces aren't interpreted as new lines.
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001707 ('foo BUG=allo R=joe ', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001708 'foo BUG=allo R=joe\n\nR=c@c'),
1709 # Redundant TBRs get promoted to Rs
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001710 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001711 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001712 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001713 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001714 actual = []
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001715 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001716 obj = git_cl.ChangeDescription(orig)
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001717 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001718 actual.append(obj.description)
1719 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001720
Nodir Turakulov23b82142017-11-16 11:04:25 -08001721 def test_get_hash_tags(self):
1722 cases = [
1723 ('', []),
1724 ('a', []),
1725 ('[a]', ['a']),
1726 ('[aa]', ['aa']),
1727 ('[a ]', ['a']),
1728 ('[a- ]', ['a']),
1729 ('[a- b]', ['a-b']),
1730 ('[a--b]', ['a-b']),
1731 ('[a', []),
1732 ('[a]x', ['a']),
1733 ('[aa]x', ['aa']),
1734 ('[a b]', ['a-b']),
1735 ('[a b]', ['a-b']),
1736 ('[a__b]', ['a-b']),
1737 ('[a] x', ['a']),
1738 ('[a][b]', ['a', 'b']),
1739 ('[a] [b]', ['a', 'b']),
1740 ('[a][b]x', ['a', 'b']),
1741 ('[a][b] x', ['a', 'b']),
1742 ('[a]\n[b]', ['a']),
1743 ('[a\nb]', []),
1744 ('[a][', ['a']),
1745 ('Revert "[a] feature"', ['a']),
1746 ('Reland "[a] feature"', ['a']),
1747 ('Revert: [a] feature', ['a']),
1748 ('Reland: [a] feature', ['a']),
1749 ('Revert "Reland: [a] feature"', ['a']),
1750 ('Foo: feature', ['foo']),
1751 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001752 ('Change Foo::Bar', []),
1753 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001754 ('Revert "Foo bar: feature"', ['foo-bar']),
1755 ('Reland "Foo bar: feature"', ['foo-bar']),
1756 ]
1757 for desc, expected in cases:
1758 change_desc = git_cl.ChangeDescription(desc)
1759 actual = change_desc.get_hash_tags()
1760 self.assertEqual(
1761 actual,
1762 expected,
1763 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1764
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001765 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'main'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001766 self.assertEqual(None, git_cl.GetTargetRef(None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001767 'refs/remotes/origin/main',
1768 'main'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001769
wittman@chromium.org455dc922015-01-26 20:15:50 +00001770 # Check default target refs for branches.
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001771 self.assertEqual('refs/heads/main',
1772 git_cl.GetTargetRef('origin', 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001773 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001774 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001775 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001776 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001777 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001778 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001779 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001780 self.assertEqual('refs/branch-heads/123',
1781 git_cl.GetTargetRef('origin',
1782 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001783 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001784 self.assertEqual('refs/diff/test',
1785 git_cl.GetTargetRef('origin',
1786 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001787 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001788 self.assertEqual('refs/heads/chrome/m42',
1789 git_cl.GetTargetRef('origin',
1790 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001791 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001792
1793 # Check target refs for user-specified target branch.
1794 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1795 'refs/remotes/branch-heads/123'):
1796 self.assertEqual('refs/branch-heads/123',
1797 git_cl.GetTargetRef('origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001798 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001799 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001800 for branch in ('origin/main', 'remotes/origin/main',
1801 'refs/remotes/origin/main'):
1802 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001803 git_cl.GetTargetRef('origin',
1804 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001805 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001806 for branch in ('main', 'heads/main', 'refs/heads/main'):
1807 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001808 git_cl.GetTargetRef('origin',
1809 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001810 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001811
Edward Lemurda4b6c62020-02-13 00:28:40 +00001812 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1813 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001814 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001815 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1816
Edward Lemur85153282020-02-14 22:06:29 +00001817 def assertIssueAndPatchset(
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001818 self, branch='main', issue='123456', patchset='7',
Edward Lemur85153282020-02-14 22:06:29 +00001819 git_short_host='chromium'):
1820 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001821 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001822 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001823 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001824 self.assertEqual(
1825 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001826 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001827
Edward Lemur85153282020-02-14 22:06:29 +00001828 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001829 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001830 self.mockGit.config['remote.origin.url'] = (
1831 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001832 gerrit_util.GetChangeDetail.return_value = {
1833 'current_revision': '7777777777',
1834 'revisions': {
1835 '1111111111': {
1836 '_number': 1,
1837 'fetch': {'http': {
1838 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1839 'ref': 'refs/changes/56/123456/1',
1840 }},
1841 },
1842 '7777777777': {
1843 '_number': 7,
1844 'fetch': {'http': {
1845 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1846 'ref': 'refs/changes/56/123456/7',
1847 }},
1848 },
1849 },
1850 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001851
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001852 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001853 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001854 self.calls += [
1855 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1856 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001857 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001858 ]
1859 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001860 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001861
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001862 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001863 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001864 self.calls += [
1865 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1866 'refs/changes/56/123456/7'],), ''),
1867 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001868 ]
Edward Lemur85153282020-02-14 22:06:29 +00001869 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1870 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001871
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001872 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001873 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001874 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001875 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001876 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001877 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001878 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001879 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001880 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001881
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001882 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001883 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001884 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001885 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001886 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001887 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001888 ]
1889 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001890 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001891 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001892
Aaron Gable697a91b2018-01-19 15:20:15 -08001893 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001894 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001895 self.calls += [
1896 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1897 'refs/changes/56/123456/1'],), ''),
1898 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001899 ]
1900 self.assertEqual(git_cl.main(
1901 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1902 0)
Edward Lemur85153282020-02-14 22:06:29 +00001903 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001904
Edward Lemurd55c5072020-02-20 01:09:07 +00001905 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001906 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001907 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001908 self.calls += [
1909 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001910 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001911 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001912 ]
1913 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001914 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001915 self.assertEqual(
1916 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1917 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001918
Edward Lemurda4b6c62020-02-13 00:28:40 +00001919 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001920 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001921 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001922 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001923 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001924 self.mockGit.config['remote.origin.url'] = (
1925 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001926 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001927 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001928 self.assertEqual(
1929 'change 123456 at https://chromium-review.googlesource.com does not '
1930 'exist or you have no access to it\n',
1931 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001932
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001933 def _checkout_calls(self):
1934 return [
1935 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001936 'branch\\..*\\.gerritissue'], ),
1937 ('branch.ger-branch.gerritissue 123456\n'
1938 'branch.gbranch654.gerritissue 654321\n')),
1939 ]
1940
1941 def test_checkout_gerrit(self):
1942 """Tests git cl checkout <issue>."""
1943 self.calls = self._checkout_calls()
1944 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1945 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1946
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001947 def test_checkout_not_found(self):
1948 """Tests git cl checkout <issue>."""
1949 self.calls = self._checkout_calls()
1950 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1951
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001952 def test_checkout_no_branch_issues(self):
1953 """Tests git cl checkout <issue>."""
1954 self.calls = [
1955 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001956 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001957 ]
1958 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1959
Edward Lemur26964072020-02-19 19:18:51 +00001960 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001961 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001962 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001963 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001964 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1965 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001966 self.mockGit.config['remote.origin.url'] = (
1967 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001968 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001969 cl.branch = 'main'
1970 cl.branchref = 'refs/heads/main'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001971 return cl
1972
Edward Lemurd55c5072020-02-20 01:09:07 +00001973 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001974 def test_gerrit_ensure_authenticated_missing(self):
1975 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001976 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001977 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001978 with self.assertRaises(SystemExitMock):
1979 cl.EnsureAuthenticated(force=False)
1980 self.assertEqual(
1981 'Credentials for the following hosts are required:\n'
1982 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001983 'These are read from ~%(sep)s.gitcookies '
1984 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001985 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001986 'https://chromium-review.googlesource.com/new-password\n' % {
1987 'sep': os.sep,
1988 'netrc': NETRC_FILENAME,
1989 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001990
1991 def test_gerrit_ensure_authenticated_conflict(self):
1992 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001993 'chromium.googlesource.com':
1994 ('git-one.example.com', None, 'secret1'),
1995 'chromium-review.googlesource.com':
1996 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001997 })
1998 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001999 (('ask_for_data', 'If you know what you are doing '
2000 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002001 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2002
2003 def test_gerrit_ensure_authenticated_ok(self):
2004 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002005 'chromium.googlesource.com':
2006 ('git-same.example.com', None, 'secret'),
2007 'chromium-review.googlesource.com':
2008 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002009 })
2010 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2011
tandrii@chromium.org28253532016-04-14 13:46:56 +00002012 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00002013 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
2014 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00002015 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2016
Eric Boren2fb63102018-10-05 13:05:03 +00002017 def test_gerrit_ensure_authenticated_bearer_token(self):
2018 cl = self._test_gerrit_ensure_authenticated_common(auth={
2019 'chromium.googlesource.com':
2020 ('', None, 'secret'),
2021 'chromium-review.googlesource.com':
2022 ('', None, 'secret'),
2023 })
2024 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2025 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2026 'chromium.googlesource.com')
2027 self.assertTrue('Bearer' in header)
2028
Daniel Chengcf6269b2019-05-18 01:02:12 +00002029 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00002030 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002031 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002032 (('logging.warning',
2033 'Ignoring branch %(branch)s with non-https remote '
2034 '%(remote)s', {
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002035 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002036 'remote': 'custom-scheme://repo'}
2037 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00002038 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002039 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2040 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2041 mock.patch('logging.warning',
2042 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002043 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002044 cl.branch = 'main'
2045 cl.branchref = 'refs/heads/main'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002046 cl.lookedup_issue = True
2047 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2048
Florian Mayerae510e82020-01-30 21:04:48 +00002049 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00002050 self.mockGit.config['remote.origin.url'] = (
2051 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00002052 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002053 (('logging.error',
2054 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2055 'but it doesn\'t exist.', {
2056 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002057 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002058 'url': 'git@somehost.example:foo/bar.git'}
2059 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00002060 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002061 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2062 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2063 mock.patch('logging.error',
2064 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00002065 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002066 cl.branch = 'main'
2067 cl.branchref = 'refs/heads/main'
Florian Mayerae510e82020-01-30 21:04:48 +00002068 cl.lookedup_issue = True
2069 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2070
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002071 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002072 self.mockGit.config['branch.main.gerritissue'] = '123'
2073 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002074 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00002075 self.mockGit.config['remote.origin.url'] = (
2076 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002077 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00002078 (('SetReview', 'chromium-review.googlesource.com',
2079 'infra%2Finfra~123', None,
2080 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002081 ]
tandriid9e5ce52016-07-13 02:32:59 -07002082
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002083 def _cmd_set_quick_run_gerrit(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002084 self.mockGit.config['branch.main.gerritissue'] = '123'
2085 self.mockGit.config['branch.main.gerritserver'] = (
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002086 'https://chromium-review.googlesource.com')
2087 self.mockGit.config['remote.origin.url'] = (
2088 'https://chromium.googlesource.com/infra/infra')
2089 self.calls = [
2090 (('SetReview', 'chromium-review.googlesource.com',
2091 'infra%2Finfra~123', None,
2092 {'Commit-Queue': 1, 'Quick-Run': 1}, None, None), ''),
2093 ]
2094
tandriid9e5ce52016-07-13 02:32:59 -07002095 def test_cmd_set_commit_gerrit_clear(self):
2096 self._cmd_set_commit_gerrit_common(0)
2097 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2098
2099 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002100 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002101 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2102
tandriid9e5ce52016-07-13 02:32:59 -07002103 def test_cmd_set_commit_gerrit(self):
2104 self._cmd_set_commit_gerrit_common(2)
2105 self.assertEqual(0, git_cl.main(['set-commit']))
2106
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002107 def test_cmd_set_quick_run_gerrit(self):
2108 self._cmd_set_quick_run_gerrit()
2109 self.assertEqual(0, git_cl.main(['set-commit', '-q']))
2110
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002111 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002112 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002113 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002114
2115 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002116 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002117
Edward Lemurda4b6c62020-02-13 00:28:40 +00002118 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07002119 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07002120 try:
2121 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00002122 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00002123 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00002124 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07002125
2126 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07002127 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002128 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002129 return 'foobar'
2130
Edward Lemurda4b6c62020-02-13 00:28:40 +00002131 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07002132 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002133 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002134 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002135 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002136
iannuccie53c9352016-08-17 14:40:40 -07002137 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002138
iannuccie53c9352016-08-17 14:40:40 -07002139 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002140 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002141 return 'foobar'
2142
Edward Lemurda4b6c62020-02-13 00:28:40 +00002143 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2144 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002145 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002146 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002147
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002148 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002149 self.mockGit.config['remote.origin.url'] = (
2150 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002151 gerrit_util.GetChangeDetail.return_value = {
2152 'current_revision': 'sha1',
2153 'revisions': {'sha1': {
2154 'commit': {'message': 'foobar'},
2155 }},
2156 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002157 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002158 'description',
2159 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2160 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002161 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002162
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002163 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002164 mock.patch('git_cl.Changelist', ChangelistMock).start()
2165 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002166
2167 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2168 self.assertEqual('hihi', ChangelistMock.desc)
2169
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002170 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002171 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002172
2173 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002174 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002175 '# Enter a description of the change.\n'
2176 '# This will be displayed on the codereview site.\n'
2177 '# The first line will also be used as the subject of the review.\n'
2178 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002179 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002180 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002181 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002182 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002183 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002184
Edward Lemur6c6827c2020-02-06 21:15:18 +00002185 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002186 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002187
Edward Lemurda4b6c62020-02-13 00:28:40 +00002188 mock.patch('git_cl.Changelist.FetchDescription',
2189 lambda *args: current_desc).start()
2190 mock.patch('git_cl.Changelist.UpdateDescription',
2191 UpdateDescription).start()
2192 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002193
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002194 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002195 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002196
Dan Beamd8b04ca2019-10-10 21:23:26 +00002197 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2198 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2199
2200 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002201 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002202 '# Enter a description of the change.\n'
2203 '# This will be displayed on the codereview site.\n'
2204 '# The first line will also be used as the subject of the review.\n'
2205 '#--------------------This line is 72 characters long'
2206 '--------------------\n'
2207 'Some.\n\nFixed: 123\nChange-Id: xxx',
2208 desc)
2209 return desc
2210
Edward Lemurda4b6c62020-02-13 00:28:40 +00002211 mock.patch('git_cl.Changelist.FetchDescription',
2212 lambda *args: current_desc).start()
2213 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002214
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002215 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002216 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002217
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002218 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002219 mock.patch('git_cl.Changelist', ChangelistMock).start()
2220 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002221
2222 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2223 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2224
kmarshall3bff56b2016-06-06 18:31:47 -07002225 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002226 self.calls = [
2227 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002228 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002229 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002230 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002231 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002232 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002233
Edward Lemurda4b6c62020-02-13 00:28:40 +00002234 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002235 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002236 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002237 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002238 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002239
2240 self.assertEqual(0, git_cl.main(['archive', '-f']))
2241
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002242 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002243 self.calls = [
2244 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002245 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002246 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2247 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002248 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2249 ((['git', 'branch', '-D', 'foo'],), '')
2250 ]
2251
Edward Lemurda4b6c62020-02-13 00:28:40 +00002252 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002253 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002254 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002255 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002256 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002257
2258 self.assertEqual(0, git_cl.main(['archive', '-f']))
2259
kmarshall3bff56b2016-06-06 18:31:47 -07002260 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002261 self.calls = [
2262 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002263 'refs/heads/main'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002264 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002265 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002266
Edward Lemurda4b6c62020-02-13 00:28:40 +00002267 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002268 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002269 [(MockChangelistWithBranchAndIssue('main', 1),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002270 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002271
2272 self.assertEqual(1, git_cl.main(['archive', '-f']))
2273
2274 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002275 self.calls = [
2276 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002277 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002278 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002279 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002280
Edward Lemurda4b6c62020-02-13 00:28:40 +00002281 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002282 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002283 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002284 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002285 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002286
kmarshall9249e012016-08-23 12:02:16 -07002287 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2288
2289 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002290 self.calls = [
2291 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002292 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002293 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002294 ((['git', 'branch', '-D', 'foo'],), '')
2295 ]
kmarshall9249e012016-08-23 12:02:16 -07002296
Edward Lemurda4b6c62020-02-13 00:28:40 +00002297 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002298 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002299 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002300 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002301 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002302
2303 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002304
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002305 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002306 self.calls = [
2307 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002308 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002309 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002310 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2311 'refs/tags/git-cl-archived-456-foo'),
2312 ((['git', 'branch', '-D', 'foo'],), CERR1),
2313 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2314 'refs/tags/git-cl-archived-456-foo'),
2315 ]
2316
Edward Lemurda4b6c62020-02-13 00:28:40 +00002317 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002318 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002319 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002320 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002321 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002322
2323 self.assertEqual(0, git_cl.main(['archive', '-f']))
2324
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002325 def test_archive_with_format(self):
2326 self.calls = [
2327 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002328 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002329 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2330 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2331 ((['git', 'branch', '-D', 'foo'], ), ''),
2332 ]
2333
2334 mock.patch('git_cl.get_cl_statuses',
2335 lambda branches, fine_grained, max_processes:
2336 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2337
2338 self.assertEqual(
2339 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2340
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002341 def test_cmd_issue_erase_existing(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002342 self.mockGit.config['branch.main.gerritissue'] = '123'
2343 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002344 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002345 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002346 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002347 ]
2348 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002349 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2350 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002351
Aaron Gable400e9892017-07-12 15:31:21 -07002352 def test_cmd_issue_erase_existing_with_change_id(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002353 self.mockGit.config['branch.main.gerritissue'] = '123'
2354 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002355 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002356 mock.patch('git_cl.Changelist.FetchDescription',
2357 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002358 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002359 ((['git', 'log', '-1', '--format=%B'],),
2360 'This is a description\n\nChange-Id: Ideadbeef'),
2361 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002362 ]
2363 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002364 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2365 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002366
phajdan.jre328cf92016-08-22 04:12:17 -07002367 def test_cmd_issue_json(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002368 self.mockGit.config['branch.main.gerritissue'] = '123'
2369 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002370 'https://chromium-review.googlesource.com')
Nodir Turakulov27379632021-03-17 18:53:29 +00002371 self.mockGit.config['remote.origin.url'] = (
2372 'https://chromium.googlesource.com/chromium/src'
2373 )
2374 self.calls = [(
2375 (
2376 'write_json',
2377 'output.json',
2378 {
2379 'issue': 123,
2380 'issue_url': 'https://chromium-review.googlesource.com/123',
2381 'gerrit_host': 'chromium-review.googlesource.com',
2382 'gerrit_project': 'chromium/src',
2383 },
2384 ),
2385 '',
2386 )]
phajdan.jre328cf92016-08-22 04:12:17 -07002387 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2388
tandrii16e0b4e2016-06-07 10:34:28 -07002389 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002390 mock.patch(
2391 'git_cl.os.path.abspath',
2392 lambda path: self._mocked_call(['abspath', path])).start()
2393 mock.patch(
2394 'git_cl.os.path.exists',
2395 lambda path: self._mocked_call(['exists', path])).start()
2396 mock.patch(
2397 'git_cl.gclient_utils.FileRead',
2398 lambda path: self._mocked_call(['FileRead', path])).start()
2399 mock.patch(
2400 'git_cl.gclient_utils.rm_file_or_tree',
2401 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002402 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002403 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002404 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002405 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002406
2407 def test_GerritCommitMsgHookCheck_custom_hook(self):
2408 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002409 self.calls += [((['exists',
2410 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2411 ((['FileRead',
2412 os.path.join('.git', 'hooks', 'commit-msg')], ),
2413 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002414 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002415
2416 def test_GerritCommitMsgHookCheck_not_exists(self):
2417 cl = self._common_GerritCommitMsgHookCheck()
2418 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002419 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002420 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002421 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002422
2423 def test_GerritCommitMsgHookCheck(self):
2424 cl = self._common_GerritCommitMsgHookCheck()
2425 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002426 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2427 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002428 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002429 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002430 ((['rm_file_or_tree',
2431 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002432 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002433 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002434
tandriic4344b52016-08-29 06:04:54 -07002435 def test_GerritCmdLand(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002436 self.mockGit.config['branch.main.gerritsquashhash'] = 'deadbeaf'
2437 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002438 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002439 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002440 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002441 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002442 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002443 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002444 'labels': {},
2445 'current_revision': 'deadbeaf',
2446 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002447 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002448 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002449 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002450 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2451 }
Xinan Lin1bd4ffa2021-07-28 00:54:22 +00002452 cl.SubmitIssue = lambda: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002453 self.assertEqual(0, cl.CMDLand(force=True,
2454 bypass_hooks=True,
2455 verbose=True,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00002456 parallel=False,
2457 resultdb=False,
2458 realm=None))
Edward Lemur73c76702020-02-06 23:57:18 +00002459 self.assertIn(
2460 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002461 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002462 self.assertIn(
2463 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002464 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002465
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002466 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lesmeseeca9c62020-11-20 00:00:17 +00002467 mock.patch('git_cl.Changelist.GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002468
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002469 def test_gerrit_change_detail_cache_simple(self):
2470 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002471 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002472 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002473 cl1._cached_remote_url = (
2474 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002475 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002476 cl2._cached_remote_url = (
2477 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002478 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2479 self.assertEqual(cl1._GetChangeDetail(), 'a')
2480 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002481
2482 def test_gerrit_change_detail_cache_options(self):
2483 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002484 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002485 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002486 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002487 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2488 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2489 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2490 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2491 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2492 self.assertEqual(cl._GetChangeDetail(), 'cab')
2493
2494 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2495 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2496 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2497 self.assertEqual(cl._GetChangeDetail(), 'cab')
2498
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002499 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002500 gerrit_util.GetChangeDetail.return_value = {
2501 'current_revision': 'rev1',
2502 'revisions': {
2503 'rev1': {'commit': {'message': 'desc1'}},
2504 },
2505 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002506
2507 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002508 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002509 cl._cached_remote_url = (
2510 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002511 self.assertEqual(cl.FetchDescription(), 'desc1')
2512 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002513
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002514 def test_print_current_creds(self):
2515 class CookiesAuthenticatorMock(object):
2516 def __init__(self):
2517 self.gitcookies = {
2518 'host.googlesource.com': ('user', 'pass'),
2519 'host-review.googlesource.com': ('user', 'pass'),
2520 }
2521 self.netrc = self
2522 self.netrc.hosts = {
2523 'github.com': ('user2', None, 'pass2'),
2524 'host2.googlesource.com': ('user3', None, 'pass'),
2525 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002526 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2527 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002528 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2529 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2530 ' Host\t User\t Which file',
2531 '============================\t=====\t===========',
2532 'host-review.googlesource.com\t user\t.gitcookies',
2533 ' host.googlesource.com\t user\t.gitcookies',
2534 ' host2.googlesource.com\tuser3\t .netrc',
2535 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002536 sys.stdout.seek(0)
2537 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002538 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2539 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2540 ' Host\tUser\t Which file',
2541 '============================\t====\t===========',
2542 'host-review.googlesource.com\tuser\t.gitcookies',
2543 ' host.googlesource.com\tuser\t.gitcookies',
2544 ])
2545
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002546 def _common_creds_check_mocks(self):
2547 def exists_mock(path):
2548 dirname = os.path.dirname(path)
2549 if dirname == os.path.expanduser('~'):
2550 dirname = '~'
2551 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002552 if base in (NETRC_FILENAME, '.gitcookies'):
2553 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002554 # git cl also checks for existence other files not relevant to this test.
2555 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002556 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002557 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002558 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002559 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002560
2561 def test_creds_check_gitcookies_not_configured(self):
2562 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002563 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2564 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002565 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002566 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2567 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2568 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2569 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2570 'or Ctrl+C to abort'), ''),
2571 (([
2572 'git', 'config', '--global', 'http.cookiefile',
2573 os.path.expanduser(os.path.join('~', '.gitcookies'))
2574 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002575 ]
2576 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002577 self.assertTrue(
2578 sys.stdout.getvalue().startswith(
2579 'You seem to be using outdated .netrc for git credentials:'))
2580 self.assertIn(
2581 '\nConfigured git to use .gitcookies from',
2582 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002583
2584 def test_creds_check_gitcookies_configured_custom_broken(self):
2585 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002586 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2587 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002588 custom_cookie_path = ('C:\\.gitcookies'
2589 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002590 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002591 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2592 ((['git', 'config', '--global', 'http.cookiefile'], ),
2593 custom_cookie_path),
2594 (('os.path.exists', custom_cookie_path), False),
2595 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2596 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2597 (([
2598 'git', 'config', '--global', 'http.cookiefile',
2599 os.path.expanduser(os.path.join('~', '.gitcookies'))
2600 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002601 ]
2602 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002603 self.assertIn(
2604 'WARNING: You have configured custom path to .gitcookies: ',
2605 sys.stdout.getvalue())
2606 self.assertIn(
2607 'However, your configured .gitcookies file is missing.',
2608 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002609
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002610 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002611 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002612 self.mockGit.config['remote.origin.url'] = (
2613 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002614 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002615 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002616 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002617 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002618 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002619 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002620
Edward Lemurda4b6c62020-02-13 00:28:40 +00002621 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2622 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002623 self.mockGit.config['remote.origin.url'] = (
2624 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002625 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002626 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002627 'current_revision': 'ba5eba11',
2628 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002629 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002630 '_number': 1,
2631 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002632 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002633 '_number': 2,
2634 },
2635 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002636 'messages': [
2637 {
2638 u'_revision_number': 1,
2639 u'author': {
2640 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002641 u'email': u'could-be-anything@example.com',
2642 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002643 },
2644 u'date': u'2017-03-15 20:08:45.000000000',
2645 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002646 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov899785a2021-07-09 12:45:37 +00002647 u'tag': u'autogenerated:cv:dry-run'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002648 },
2649 {
2650 u'_revision_number': 2,
2651 u'author': {
2652 u'_account_id': 11151243,
2653 u'email': u'owner@example.com',
2654 u'name': u'owner'
2655 },
2656 u'date': u'2017-03-16 20:00:41.000000000',
2657 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2658 u'message': u'PTAL',
2659 },
2660 {
2661 u'_revision_number': 2,
2662 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002663 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002664 u'email': u'reviewer@example.com',
2665 u'name': u'reviewer'
2666 },
2667 u'date': u'2017-03-17 05:19:37.500000000',
2668 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2669 u'message': u'Patch Set 2: Code-Review+1',
2670 },
Josip Sokcevic266129c2021-11-09 00:22:00 +00002671 {
2672 u'_revision_number': 2,
2673 u'author': {
2674 u'_account_id': 42,
2675 u'name': u'reviewer'
2676 },
2677 u'date': u'2017-03-17 05:19:37.900000000',
2678 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d0000',
2679 u'message': u'A bot with no email set',
2680 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002681 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002682 }
2683 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002684 (('GetChangeComments', 'chromium-review.googlesource.com',
2685 'infra%2Finfra~1'), {
2686 '/COMMIT_MSG': [
2687 {
2688 'author': {
2689 'email': u'reviewer@example.com'
2690 },
2691 'updated': u'2017-03-17 05:19:37.500000000',
2692 'patch_set': 2,
2693 'side': 'REVISION',
2694 'message': 'Please include a bug link',
2695 },
2696 ],
2697 'codereview.settings': [
2698 {
2699 'author': {
2700 'email': u'owner@example.com'
2701 },
2702 'updated': u'2017-03-16 20:00:41.000000000',
2703 'patch_set': 2,
2704 'side': 'PARENT',
2705 'line': 42,
2706 'message': 'I removed this because it is bad',
2707 },
2708 ]
2709 }),
2710 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2711 'infra%2Finfra~1'), {}),
2712 ] * 2 + [(('write_json', 'output.json', [{
2713 u'date':
2714 u'2017-03-16 20:00:41.000000',
2715 u'message': (u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2716 u' Base, Line 42: https://crrev.com/c/1/2/'
2717 u'codereview.settings#b42\n' +
2718 u' I removed this because it is bad\n'),
2719 u'autogenerated':
2720 False,
2721 u'approval':
2722 False,
2723 u'disapproval':
2724 False,
2725 u'sender':
2726 u'owner@example.com'
2727 }, {
2728 u'date':
2729 u'2017-03-17 05:19:37.500000',
2730 u'message':
2731 (u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2732 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
2733 u' Please include a bug link\n'),
2734 u'autogenerated':
2735 False,
2736 u'approval':
2737 False,
2738 u'disapproval':
2739 False,
2740 u'sender':
2741 u'reviewer@example.com'
2742 }]), '')]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002743 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002744 git_cl._CommentSummary(
2745 message=(u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2746 u' Base, Line 42: https://crrev.com/c/1/2/' +
2747 u'codereview.settings#b42\n' +
2748 u' I removed this because it is bad\n'),
2749 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
2750 autogenerated=False,
2751 disapproval=False,
2752 approval=False,
2753 sender=u'owner@example.com'),
2754 git_cl._CommentSummary(message=(
2755 u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2756 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002757 u' Please include a bug link\n'),
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002758 date=datetime.datetime(2017, 3, 17, 5, 19, 37,
2759 500000),
2760 autogenerated=False,
2761 disapproval=False,
2762 approval=False,
2763 sender=u'reviewer@example.com'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002764 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002765 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002766 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002767 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002768 self.assertEqual(
2769 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2770
2771 def test_git_cl_comments_robot_comments(self):
2772 # git cl comments also fetches robot comments (which are considered a type
2773 # of autogenerated comment), and unlike other types of comments, only robot
2774 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002775 self.mockGit.config['remote.origin.url'] = (
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002776 'https://x.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002777 gerrit_util.GetChangeDetail.return_value = {
2778 'owner': {'email': 'owner@example.com'},
2779 'current_revision': 'ba5eba11',
2780 'revisions': {
2781 'deadbeaf': {
2782 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002783 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002784 'ba5eba11': {
2785 '_number': 2,
2786 },
2787 },
2788 'messages': [
2789 {
2790 u'_revision_number': 1,
2791 u'author': {
2792 u'_account_id': 1111084,
2793 u'email': u'commit-bot@chromium.org',
2794 u'name': u'Commit Bot'
2795 },
2796 u'date': u'2017-03-15 20:08:45.000000000',
2797 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2798 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2799 u'tag': u'autogenerated:cq:dry-run'
2800 },
2801 {
2802 u'_revision_number': 1,
2803 u'author': {
2804 u'_account_id': 123,
2805 u'email': u'tricium@serviceaccount.com',
2806 u'name': u'Tricium'
2807 },
2808 u'date': u'2017-03-16 20:00:41.000000000',
2809 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2810 u'message': u'(1 comment)',
2811 u'tag': u'autogenerated:tricium',
2812 },
2813 {
2814 u'_revision_number': 1,
2815 u'author': {
2816 u'_account_id': 123,
2817 u'email': u'tricium@serviceaccount.com',
2818 u'name': u'Tricium'
2819 },
2820 u'date': u'2017-03-16 20:00:41.000000000',
2821 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2822 u'message': u'(1 comment)',
2823 u'tag': u'autogenerated:tricium',
2824 },
2825 {
2826 u'_revision_number': 2,
2827 u'author': {
2828 u'_account_id': 123,
2829 u'email': u'tricium@serviceaccount.com',
2830 u'name': u'reviewer'
2831 },
2832 u'date': u'2017-03-17 05:30:37.000000000',
2833 u'tag': u'autogenerated:tricium',
2834 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2835 u'message': u'(1 comment)',
2836 },
2837 ]
2838 }
2839 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002840 (('GetChangeComments', 'x-review.googlesource.com', 'infra%2Finfra~1'),
2841 {}),
2842 (('GetChangeRobotComments', 'x-review.googlesource.com',
2843 'infra%2Finfra~1'), {
2844 'codereview.settings': [
2845 {
2846 u'author': {
2847 u'email': u'tricium@serviceaccount.com'
2848 },
2849 u'updated': u'2017-03-17 05:30:37.000000000',
2850 u'robot_run_id': u'5565031076855808',
2851 u'robot_id': u'Linter/Category',
2852 u'tag': u'autogenerated:tricium',
2853 u'patch_set': 2,
2854 u'side': u'REVISION',
2855 u'message': u'Linter warning message text',
2856 u'line': 32,
2857 },
2858 ],
2859 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002860 ]
2861 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002862 git_cl._CommentSummary(
2863 date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2864 message=(u'(1 comment)\n\ncodereview.settings\n'
2865 u' PS2, Line 32: https://x-review.googlesource.com/c/1/2/'
2866 u'codereview.settings#32\n'
2867 u' Linter warning message text\n'),
2868 sender=u'tricium@serviceaccount.com',
2869 autogenerated=True,
2870 approval=False,
2871 disapproval=False)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002872 ]
2873 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002874 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002875 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002876
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002877 def test_get_remote_url_with_mirror(self):
2878 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002879
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002880 def selective_os_path_isdir_mock(path):
2881 if path == '/cache/this-dir-exists':
2882 return self._mocked_call('os.path.isdir', path)
2883 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002884
Edward Lemurda4b6c62020-02-13 00:28:40 +00002885 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002886
2887 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002888 self.mockGit.config['remote.origin.url'] = (
2889 '/cache/this-dir-exists')
2890 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2891 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002892 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002893 (('os.path.isdir', '/cache/this-dir-exists'),
2894 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002895 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002896 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002897 self.assertEqual(cl.GetRemoteUrl(), url)
2898 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2899
Edward Lemur298f2cf2019-02-22 21:40:39 +00002900 def test_get_remote_url_non_existing_mirror(self):
2901 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002902
Edward Lemur298f2cf2019-02-22 21:40:39 +00002903 def selective_os_path_isdir_mock(path):
2904 if path == '/cache/this-dir-doesnt-exist':
2905 return self._mocked_call('os.path.isdir', path)
2906 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002907
Edward Lemurda4b6c62020-02-13 00:28:40 +00002908 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2909 mock.patch('logging.error',
2910 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002911
Edward Lemur26964072020-02-19 19:18:51 +00002912 self.mockGit.config['remote.origin.url'] = (
2913 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002914 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002915 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2916 False),
2917 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002918 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2919 'but it doesn\'t exist.', {
2920 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002921 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002922 'url': '/cache/this-dir-doesnt-exist'}
2923 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002924 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002925 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002926 self.assertIsNone(cl.GetRemoteUrl())
2927
2928 def test_get_remote_url_misconfigured_mirror(self):
2929 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002930
Edward Lemur298f2cf2019-02-22 21:40:39 +00002931 def selective_os_path_isdir_mock(path):
2932 if path == '/cache/this-dir-exists':
2933 return self._mocked_call('os.path.isdir', path)
2934 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002935
Edward Lemurda4b6c62020-02-13 00:28:40 +00002936 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2937 mock.patch('logging.error',
2938 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002939
Edward Lemur26964072020-02-19 19:18:51 +00002940 self.mockGit.config['remote.origin.url'] = (
2941 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002942 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002943 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002944 (('logging.error',
2945 'Remote "%(remote)s" for branch "%(branch)s" points to '
2946 '"%(cache_path)s", but it is misconfigured.\n'
2947 '"%(cache_path)s" must be a git repo and must have a remote named '
2948 '"%(remote)s" pointing to the git host.', {
2949 'remote': 'origin',
2950 'cache_path': '/cache/this-dir-exists',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002951 'branch': 'main'}
Edward Lemur298f2cf2019-02-22 21:40:39 +00002952 ), None),
2953 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002954 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002955 self.assertIsNone(cl.GetRemoteUrl())
2956
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002957 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002958 self.mockGit.config['remote.origin.url'] = (
2959 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002960 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002961 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2962
2963 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002964 mock.patch('logging.error',
2965 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002966
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002967 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002968 (('logging.error',
2969 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2970 'but it doesn\'t exist.', {
2971 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002972 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002973 'url': ''}
2974 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002975 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002976 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002977 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002978
Josip Sokcevicc39ab992020-09-24 20:09:15 +00002979 def test_gerrit_new_default(self):
2980 self._run_gerrit_upload_test(
2981 [],
2982 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
2983 [],
2984 squash=False,
2985 squash_mode='override_nosquash',
2986 change_id='I123456789',
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00002987 default_branch='main')
Josip Sokcevicc39ab992020-09-24 20:09:15 +00002988
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002989
Edward Lemur9aa1a962020-02-25 00:58:38 +00002990class ChangelistTest(unittest.TestCase):
mlcui3da91712021-05-05 10:00:30 +00002991 LAST_COMMIT_SUBJECT = 'Fixes goat teleporter destination to be Australia'
2992
2993 def _mock_run_git(commands):
2994 if commands == ['show', '-s', '--format=%s', 'HEAD']:
2995 return ChangelistTest.LAST_COMMIT_SUBJECT
2996
Edward Lemur227d5102020-02-25 23:45:35 +00002997 def setUp(self):
2998 super(ChangelistTest, self).setUp()
2999 mock.patch('gclient_utils.FileRead').start()
3000 mock.patch('gclient_utils.FileWrite').start()
3001 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
3002 mock.patch(
3003 'git_cl.Changelist.GetCodereviewServer',
3004 return_value='https://chromium-review.googlesource.com').start()
3005 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
3006 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
3007 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
Dirk Pranke6f0df682021-06-25 00:42:33 +00003008 mock.patch('git_cl.Changelist.GetUsePython3', return_value=False).start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003009 mock.patch(
3010 'git_cl.Changelist.GetRemoteBranch',
3011 return_value=('origin', 'refs/remotes/origin/main')).start()
Edward Lemur227d5102020-02-25 23:45:35 +00003012 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
3013 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
3014 mock.patch('git_cl.time_time').start()
3015 mock.patch('metrics.collector').start()
3016 mock.patch('subprocess2.Popen').start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003017 mock.patch(
3018 'git_cl.Changelist.GetGerritProject', return_value='project').start()
Edward Lemur227d5102020-02-25 23:45:35 +00003019 self.addCleanup(mock.patch.stopall)
3020 self.temp_count = 0
3021
Edward Lemur227d5102020-02-25 23:45:35 +00003022 def testRunHook(self):
3023 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003024 'more_cc': ['cc@example.com', 'more@example.com'],
3025 'errors': [],
3026 'notifications': [],
3027 'warnings': [],
Edward Lemur227d5102020-02-25 23:45:35 +00003028 }
3029 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003030 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur227d5102020-02-25 23:45:35 +00003031 mockProcess = mock.Mock()
3032 mockProcess.wait.return_value = 0
3033 subprocess2.Popen.return_value = mockProcess
3034
3035 cl = git_cl.Changelist()
3036 results = cl.RunHook(
3037 committing=True,
3038 may_prompt=True,
3039 verbose=2,
3040 parallel=True,
3041 upstream='upstream',
3042 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003043 all_files=True,
3044 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003045
3046 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003047 subprocess2.Popen.assert_any_call([
Edward Lemur227d5102020-02-25 23:45:35 +00003048 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00003049 '--root', 'root',
3050 '--upstream', 'upstream',
3051 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00003052 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003053 '--gerrit_project', 'project',
3054 '--gerrit_branch', 'refs/heads/main',
3055 '--author', 'author',
Edward Lemur227d5102020-02-25 23:45:35 +00003056 '--issue', '123456',
3057 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00003058 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00003059 '--may_prompt',
3060 '--parallel',
3061 '--all_files',
3062 '--json_output', '/tmp/fake-temp2',
3063 '--description_file', '/tmp/fake-temp1',
3064 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003065 subprocess2.Popen.assert_any_call([
3066 'vpython3', 'PRESUBMIT_SUPPORT',
3067 '--root', 'root',
3068 '--upstream', 'upstream',
3069 '--verbose', '--verbose',
3070 '--gerrit_url', 'https://chromium-review.googlesource.com',
3071 '--gerrit_project', 'project',
3072 '--gerrit_branch', 'refs/heads/main',
3073 '--author', 'author',
3074 '--issue', '123456',
3075 '--patchset', '7',
3076 '--commit',
3077 '--may_prompt',
3078 '--parallel',
3079 '--all_files',
3080 '--json_output', '/tmp/fake-temp4',
3081 '--description_file', '/tmp/fake-temp3',
3082 ])
3083 gclient_utils.FileWrite.assert_any_call(
Edward Lemur1a83da12020-03-04 21:18:36 +00003084 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00003085 metrics.collector.add_repeated('sub_commands', {
3086 'command': 'presubmit',
3087 'execution_time': 100,
3088 'exit_code': 0,
3089 })
3090
Edward Lemur99df04e2020-03-05 19:39:43 +00003091 def testRunHook_FewerOptions(self):
3092 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003093 'more_cc': ['cc@example.com', 'more@example.com'],
3094 'errors': [],
3095 'notifications': [],
3096 'warnings': [],
Edward Lemur99df04e2020-03-05 19:39:43 +00003097 }
3098 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003099 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur99df04e2020-03-05 19:39:43 +00003100 mockProcess = mock.Mock()
3101 mockProcess.wait.return_value = 0
3102 subprocess2.Popen.return_value = mockProcess
3103
3104 git_cl.Changelist.GetAuthor.return_value = None
3105 git_cl.Changelist.GetIssue.return_value = None
3106 git_cl.Changelist.GetPatchset.return_value = None
Edward Lemur99df04e2020-03-05 19:39:43 +00003107
3108 cl = git_cl.Changelist()
3109 results = cl.RunHook(
3110 committing=False,
3111 may_prompt=False,
3112 verbose=0,
3113 parallel=False,
3114 upstream='upstream',
3115 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003116 all_files=False,
3117 resultdb=False)
Edward Lemur99df04e2020-03-05 19:39:43 +00003118
3119 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003120 subprocess2.Popen.assert_any_call([
Edward Lemur99df04e2020-03-05 19:39:43 +00003121 'vpython', 'PRESUBMIT_SUPPORT',
3122 '--root', 'root',
3123 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003124 '--gerrit_url', 'https://chromium-review.googlesource.com',
3125 '--gerrit_project', 'project',
3126 '--gerrit_branch', 'refs/heads/main',
Edward Lemur99df04e2020-03-05 19:39:43 +00003127 '--upload',
3128 '--json_output', '/tmp/fake-temp2',
3129 '--description_file', '/tmp/fake-temp1',
3130 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003131 gclient_utils.FileWrite.assert_any_call(
Edward Lemur99df04e2020-03-05 19:39:43 +00003132 '/tmp/fake-temp1', 'description')
3133 metrics.collector.add_repeated('sub_commands', {
3134 'command': 'presubmit',
3135 'execution_time': 100,
3136 'exit_code': 0,
3137 })
3138
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003139 def testRunHook_FewerOptionsResultDB(self):
3140 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003141 'more_cc': ['cc@example.com', 'more@example.com'],
3142 'errors': [],
3143 'notifications': [],
3144 'warnings': [],
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003145 }
3146 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003147 git_cl.time_time.side_effect = [100, 200, 300, 400]
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003148 mockProcess = mock.Mock()
3149 mockProcess.wait.return_value = 0
3150 subprocess2.Popen.return_value = mockProcess
3151
3152 git_cl.Changelist.GetAuthor.return_value = None
3153 git_cl.Changelist.GetIssue.return_value = None
3154 git_cl.Changelist.GetPatchset.return_value = None
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003155
3156 cl = git_cl.Changelist()
3157 results = cl.RunHook(
3158 committing=False,
3159 may_prompt=False,
3160 verbose=0,
3161 parallel=False,
3162 upstream='upstream',
3163 description='description',
3164 all_files=False,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003165 resultdb=True,
3166 realm='chromium:public')
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003167
3168 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003169 subprocess2.Popen.assert_any_call([
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003170 'rdb', 'stream', '-new', '-realm', 'chromium:public', '--',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003171 'vpython', 'PRESUBMIT_SUPPORT',
3172 '--root', 'root',
3173 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003174 '--gerrit_url', 'https://chromium-review.googlesource.com',
3175 '--gerrit_project', 'project',
3176 '--gerrit_branch', 'refs/heads/main',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003177 '--upload',
3178 '--json_output', '/tmp/fake-temp2',
3179 '--description_file', '/tmp/fake-temp1',
3180 ])
3181
Edward Lemur227d5102020-02-25 23:45:35 +00003182 @mock.patch('sys.exit', side_effect=SystemExitMock)
3183 def testRunHook_Failure(self, _mock):
3184 git_cl.time_time.side_effect = [100, 200]
3185 mockProcess = mock.Mock()
3186 mockProcess.wait.return_value = 2
3187 subprocess2.Popen.return_value = mockProcess
3188
3189 cl = git_cl.Changelist()
3190 with self.assertRaises(SystemExitMock):
3191 cl.RunHook(
3192 committing=True,
3193 may_prompt=True,
3194 verbose=2,
3195 parallel=True,
3196 upstream='upstream',
3197 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003198 all_files=True,
3199 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003200
3201 sys.exit.assert_called_once_with(2)
3202
Edward Lemur75526302020-02-27 22:31:05 +00003203 def testRunPostUploadHook(self):
3204 cl = git_cl.Changelist()
3205 cl.RunPostUploadHook(2, 'upstream', 'description')
3206
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003207 subprocess2.Popen.assert_any_call([
3208 'vpython',
3209 'PRESUBMIT_SUPPORT',
3210 '--root',
3211 'root',
3212 '--upstream',
3213 'upstream',
3214 '--verbose',
3215 '--verbose',
3216 '--gerrit_url',
3217 'https://chromium-review.googlesource.com',
3218 '--gerrit_project',
3219 'project',
3220 '--gerrit_branch',
3221 'refs/heads/main',
3222 '--author',
3223 'author',
3224 '--issue',
3225 '123456',
3226 '--patchset',
3227 '7',
Edward Lemur75526302020-02-27 22:31:05 +00003228 '--post_upload',
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003229 '--description_file',
3230 '/tmp/fake-temp1',
Edward Lemur75526302020-02-27 22:31:05 +00003231 ])
Josip Sokcevice293d3d2022-02-16 22:52:15 +00003232 subprocess2.Popen.assert_called_with([
3233 'vpython3',
3234 'PRESUBMIT_SUPPORT',
3235 '--root',
3236 'root',
3237 '--upstream',
3238 'upstream',
3239 '--verbose',
3240 '--verbose',
3241 '--gerrit_url',
3242 'https://chromium-review.googlesource.com',
3243 '--gerrit_project',
3244 'project',
3245 '--gerrit_branch',
3246 'refs/heads/main',
3247 '--author',
3248 'author',
3249 '--issue',
3250 '123456',
3251 '--patchset',
3252 '7',
3253 '--post_upload',
3254 '--description_file',
3255 '/tmp/fake-temp1',
3256 '--use-python3',
3257 ])
3258
Edward Lemur75526302020-02-27 22:31:05 +00003259 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00003260 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00003261
mlcui3da91712021-05-05 10:00:30 +00003262 @mock.patch('git_cl.RunGit', _mock_run_git)
3263 def testDefaultTitleEmptyMessage(self):
3264 cl = git_cl.Changelist()
3265 cl.issue = 100
3266 options = optparse.Values({
3267 'squash': True,
3268 'title': None,
3269 'message': None,
3270 'force': None,
3271 'skip_title': None
3272 })
3273
3274 mock.patch('gclient_utils.AskForData', lambda _: user_title).start()
3275 for user_title in ['', 'y', 'Y']:
3276 self.assertEqual(cl._GetTitleForUpload(options), self.LAST_COMMIT_SUBJECT)
3277
3278 for user_title in ['not empty', 'yes', 'YES']:
3279 self.assertEqual(cl._GetTitleForUpload(options), user_title)
3280
Edward Lemur9aa1a962020-02-25 00:58:38 +00003281
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003282class CMDTestCaseBase(unittest.TestCase):
3283 _STATUSES = [
3284 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3285 'INFRA_FAILURE', 'CANCELED',
3286 ]
3287 _CHANGE_DETAIL = {
3288 'project': 'depot_tools',
3289 'status': 'OPEN',
3290 'owner': {'email': 'owner@e.mail'},
3291 'current_revision': 'beeeeeef',
3292 'revisions': {
Gavin Make61ccc52020-11-13 00:12:57 +00003293 'deadbeaf': {
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00003294 '_number': 6,
Gavin Make61ccc52020-11-13 00:12:57 +00003295 'kind': 'REWORK',
3296 },
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003297 'beeeeeef': {
3298 '_number': 7,
Gavin Make61ccc52020-11-13 00:12:57 +00003299 'kind': 'NO_CODE_CHANGE',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003300 'fetch': {'http': {
3301 'url': 'https://chromium.googlesource.com/depot_tools',
3302 'ref': 'refs/changes/56/123456/7'
3303 }},
3304 },
3305 },
3306 }
3307 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003308 'builds': [{
3309 'id': str(100 + idx),
3310 'builder': {
3311 'project': 'chromium',
3312 'bucket': 'try',
3313 'builder': 'bot_' + status.lower(),
3314 },
3315 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3316 'tags': [],
3317 'status': status,
3318 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003319 }
3320
Edward Lemur4c707a22019-09-24 21:13:43 +00003321 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003322 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00003323 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003324 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3325 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003326 mock.patch(
3327 'git_cl.Changelist.GetCodereviewServer',
3328 return_value='https://chromium-review.googlesource.com').start()
3329 mock.patch(
Edward Lesmeseeca9c62020-11-20 00:00:17 +00003330 'git_cl.Changelist.GetGerritHost',
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003331 return_value='chromium-review.googlesource.com').start()
3332 mock.patch(
3333 'git_cl.Changelist.GetMostRecentPatchset',
3334 return_value=7).start()
3335 mock.patch(
Gavin Make61ccc52020-11-13 00:12:57 +00003336 'git_cl.Changelist.GetMostRecentDryRunPatchset',
3337 return_value=6).start()
3338 mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003339 'git_cl.Changelist.GetRemoteUrl',
3340 return_value='https://chromium.googlesource.com/depot_tools').start()
3341 mock.patch(
3342 'auth.Authenticator',
3343 return_value=AuthenticatorMock()).start()
3344 mock.patch(
3345 'gerrit_util.GetChangeDetail',
3346 return_value=self._CHANGE_DETAIL).start()
3347 mock.patch(
3348 'git_cl._call_buildbucket',
3349 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003350 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003351 self.addCleanup(mock.patch.stopall)
3352
Edward Lemur4c707a22019-09-24 21:13:43 +00003353
Edward Lemur9468eba2020-02-27 19:07:22 +00003354class CMDPresubmitTestCase(CMDTestCaseBase):
3355 def setUp(self):
3356 super(CMDPresubmitTestCase, self).setUp()
3357 mock.patch(
3358 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3359 return_value='upstream').start()
3360 mock.patch(
3361 'git_cl.Changelist.FetchDescription',
3362 return_value='fetch description').start()
3363 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003364 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003365 return_value='get description').start()
3366 mock.patch('git_cl.Changelist.RunHook').start()
3367
3368 def testDefaultCase(self):
3369 self.assertEqual(0, git_cl.main(['presubmit']))
3370 git_cl.Changelist.RunHook.assert_called_once_with(
3371 committing=True,
3372 may_prompt=False,
3373 verbose=0,
3374 parallel=None,
3375 upstream='upstream',
3376 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003377 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003378 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003379 resultdb=None,
3380 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003381
3382 def testNoIssue(self):
3383 git_cl.Changelist.GetIssue.return_value = None
3384 self.assertEqual(0, git_cl.main(['presubmit']))
3385 git_cl.Changelist.RunHook.assert_called_once_with(
3386 committing=True,
3387 may_prompt=False,
3388 verbose=0,
3389 parallel=None,
3390 upstream='upstream',
3391 description='get description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003392 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003393 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003394 resultdb=None,
3395 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003396
3397 def testCustomBranch(self):
3398 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3399 git_cl.Changelist.RunHook.assert_called_once_with(
3400 committing=True,
3401 may_prompt=False,
3402 verbose=0,
3403 parallel=None,
3404 upstream='custom_branch',
3405 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003406 all_files=None,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003407 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003408 resultdb=None,
3409 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003410
3411 def testOptions(self):
3412 self.assertEqual(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003413 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u',
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003414 '--resultdb', '--realm', 'chromium:public']))
Edward Lemur9468eba2020-02-27 19:07:22 +00003415 git_cl.Changelist.RunHook.assert_called_once_with(
3416 committing=False,
3417 may_prompt=False,
3418 verbose=2,
3419 parallel=True,
3420 upstream='upstream',
3421 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003422 all_files=True,
Josip Sokcevic017544d2022-03-31 23:47:53 +00003423 files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003424 resultdb=True,
3425 realm='chromium:public')
Edward Lemur9468eba2020-02-27 19:07:22 +00003426
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003427class CMDTryResultsTestCase(CMDTestCaseBase):
3428 _DEFAULT_REQUEST = {
3429 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003430 "gerritChanges": [{
3431 "project": "depot_tools",
3432 "host": "chromium-review.googlesource.com",
Gavin Make61ccc52020-11-13 00:12:57 +00003433 "patchset": 6,
3434 "change": 123456,
3435 }],
3436 },
3437 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3438 ',builds.*.createTime,builds.*.tags'),
3439 }
3440
3441 _TRIVIAL_REQUEST = {
3442 'predicate': {
3443 "gerritChanges": [{
3444 "project": "depot_tools",
3445 "host": "chromium-review.googlesource.com",
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003446 "patchset": 7,
3447 "change": 123456,
3448 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003449 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003450 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3451 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003452 }
3453
3454 def testNoJobs(self):
3455 git_cl._call_buildbucket.return_value = {}
3456
3457 self.assertEqual(0, git_cl.main(['try-results']))
3458 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3459 git_cl._call_buildbucket.assert_called_once_with(
3460 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3461 self._DEFAULT_REQUEST)
3462
Gavin Make61ccc52020-11-13 00:12:57 +00003463 def testTrivialCommits(self):
3464 self.assertEqual(0, git_cl.main(['try-results']))
3465 git_cl._call_buildbucket.assert_called_with(
3466 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3467 self._DEFAULT_REQUEST)
3468
3469 git_cl._call_buildbucket.return_value = {}
3470 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '7']))
3471 git_cl._call_buildbucket.assert_called_with(
3472 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3473 self._TRIVIAL_REQUEST)
3474 self.assertEqual([
3475 'Successes:',
3476 ' bot_success https://ci.chromium.org/b/103',
3477 'Infra Failures:',
3478 ' bot_infra_failure https://ci.chromium.org/b/105',
3479 'Failures:',
3480 ' bot_failure https://ci.chromium.org/b/104',
3481 'Canceled:',
3482 ' bot_canceled ',
3483 'Started:',
3484 ' bot_started https://ci.chromium.org/b/102',
3485 'Scheduled:',
3486 ' bot_scheduled id=101',
3487 'Other:',
3488 ' bot_status_unspecified id=100',
3489 'Total: 7 tryjobs',
3490 'No tryjobs scheduled.',
3491 ], sys.stdout.getvalue().splitlines())
3492
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003493 def testPrintToStdout(self):
3494 self.assertEqual(0, git_cl.main(['try-results']))
3495 self.assertEqual([
3496 'Successes:',
3497 ' bot_success https://ci.chromium.org/b/103',
3498 'Infra Failures:',
3499 ' bot_infra_failure https://ci.chromium.org/b/105',
3500 'Failures:',
3501 ' bot_failure https://ci.chromium.org/b/104',
3502 'Canceled:',
3503 ' bot_canceled ',
3504 'Started:',
3505 ' bot_started https://ci.chromium.org/b/102',
3506 'Scheduled:',
3507 ' bot_scheduled id=101',
3508 'Other:',
3509 ' bot_status_unspecified id=100',
3510 'Total: 7 tryjobs',
3511 ], sys.stdout.getvalue().splitlines())
3512 git_cl._call_buildbucket.assert_called_once_with(
3513 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3514 self._DEFAULT_REQUEST)
3515
3516 def testPrintToStdoutWithMasters(self):
3517 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3518 self.assertEqual([
3519 'Successes:',
3520 ' try bot_success https://ci.chromium.org/b/103',
3521 'Infra Failures:',
3522 ' try bot_infra_failure https://ci.chromium.org/b/105',
3523 'Failures:',
3524 ' try bot_failure https://ci.chromium.org/b/104',
3525 'Canceled:',
3526 ' try bot_canceled ',
3527 'Started:',
3528 ' try bot_started https://ci.chromium.org/b/102',
3529 'Scheduled:',
3530 ' try bot_scheduled id=101',
3531 'Other:',
3532 ' try bot_status_unspecified id=100',
3533 'Total: 7 tryjobs',
3534 ], sys.stdout.getvalue().splitlines())
3535 git_cl._call_buildbucket.assert_called_once_with(
3536 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3537 self._DEFAULT_REQUEST)
3538
3539 @mock.patch('git_cl.write_json')
3540 def testWriteToJson(self, mockJsonDump):
3541 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3542 git_cl._call_buildbucket.assert_called_once_with(
3543 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3544 self._DEFAULT_REQUEST)
3545 mockJsonDump.assert_called_once_with(
3546 'file.json', self._DEFAULT_RESPONSE['builds'])
3547
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003548 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003549 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3550 self.assertEqual(
3551 [
3552 ('chromium', 'try', 'bot_failure'),
3553 ('chromium', 'try', 'bot_infra_failure'),
3554 ],
3555 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003556
3557 def test_filter_failed_for_retry_many_builds(self):
3558
3559 def _build(name, created_sec, status, experimental=False):
3560 assert 0 <= created_sec < 100, created_sec
3561 b = {
3562 'id': 112112,
3563 'builder': {
3564 'project': 'chromium',
3565 'bucket': 'try',
3566 'builder': name,
3567 },
3568 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3569 'status': status,
3570 'tags': [],
3571 }
3572 if experimental:
3573 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3574 return b
3575
3576 builds = [
3577 _build('flaky-last-green', 1, 'FAILURE'),
3578 _build('flaky-last-green', 2, 'SUCCESS'),
3579 _build('flaky', 1, 'SUCCESS'),
3580 _build('flaky', 2, 'FAILURE'),
3581 _build('running', 1, 'FAILED'),
3582 _build('running', 2, 'SCHEDULED'),
3583 _build('yep-still-running', 1, 'STARTED'),
3584 _build('yep-still-running', 2, 'FAILURE'),
3585 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3586 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3587
3588 # Simulate experimental in CQ builder, which developer decided
3589 # to retry manually which resulted in 2nd build non-experimental.
3590 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3591 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3592 ]
3593 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003594 self.assertEqual(
3595 [
3596 ('chromium', 'try', 'flaky'),
3597 ('chromium', 'try', 'sometimes-experimental'),
3598 ],
3599 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003600
3601
3602class CMDTryTestCase(CMDTestCaseBase):
3603
3604 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003605 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003606 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003607 self.assertEqual(0, git_cl.main(['try']))
3608 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3609 self.assertEqual(
3610 sys.stdout.getvalue(),
3611 'Scheduling CQ dry run on: '
3612 'https://chromium-review.googlesource.com/123456\n')
3613
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00003614 @mock.patch('git_cl.Changelist.SetCQState')
3615 def testSetCQQuickRunByDefault(self, mockSetCQState):
3616 mockSetCQState.return_value = 0
3617 self.assertEqual(0, git_cl.main(['try', '-q']))
3618 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.QUICK_RUN)
3619 self.assertEqual(
3620 sys.stdout.getvalue(),
3621 'Scheduling CQ quick run on: '
3622 'https://chromium-review.googlesource.com/123456\n')
3623
Edward Lemur4c707a22019-09-24 21:13:43 +00003624 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003625 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003626 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003627
3628 self.assertEqual(0, git_cl.main([
3629 'try', '-B', 'luci.chromium.try', '-b', 'win',
3630 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3631 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003632 'Scheduling jobs on:\n'
3633 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003634 git_cl.sys.stdout.getvalue())
3635
3636 expected_request = {
3637 "requests": [{
3638 "scheduleBuild": {
3639 "requestId": "uuid4",
3640 "builder": {
3641 "project": "chromium",
3642 "builder": "win",
3643 "bucket": "try",
3644 },
3645 "gerritChanges": [{
3646 "project": "depot_tools",
3647 "host": "chromium-review.googlesource.com",
3648 "patchset": 7,
3649 "change": 123456,
3650 }],
3651 "properties": {
3652 "category": "git_cl_try",
3653 "json": [{"a": 1}, None],
3654 "key": "val",
3655 },
3656 "tags": [
3657 {"value": "win", "key": "builder"},
3658 {"value": "git_cl_try", "key": "user_agent"},
3659 ],
3660 },
3661 }],
3662 }
3663 mockCallBuildbucket.assert_called_with(
3664 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3665
Anthony Polito1a5fe232020-01-24 23:17:52 +00003666 @mock.patch('git_cl._call_buildbucket')
3667 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3668 mockCallBuildbucket.return_value = {}
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003669 mock.patch('git_cl.Changelist.GetRemoteBranch',
3670 return_value=('origin', 'refs/remotes/origin/main')).start()
Anthony Polito1a5fe232020-01-24 23:17:52 +00003671
3672 self.assertEqual(0, git_cl.main([
3673 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3674 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3675 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3676 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003677 'Scheduling jobs on:\n'
3678 ' chromium/try: linux\n'
3679 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003680 git_cl.sys.stdout.getvalue())
3681
3682 expected_request = {
3683 "requests": [{
3684 "scheduleBuild": {
3685 "requestId": "uuid4",
3686 "builder": {
3687 "project": "chromium",
3688 "builder": "linux",
3689 "bucket": "try",
3690 },
3691 "gerritChanges": [{
3692 "project": "depot_tools",
3693 "host": "chromium-review.googlesource.com",
3694 "patchset": 7,
3695 "change": 123456,
3696 }],
3697 "properties": {
3698 "category": "git_cl_try",
3699 "json": [{"a": 1}, None],
3700 "key": "val",
3701 },
3702 "tags": [
3703 {"value": "linux", "key": "builder"},
3704 {"value": "git_cl_try", "key": "user_agent"},
3705 ],
3706 "gitilesCommit": {
3707 "host": "chromium-review.googlesource.com",
3708 "project": "depot_tools",
3709 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003710 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003711 }
3712 },
3713 },
3714 {
3715 "scheduleBuild": {
3716 "requestId": "uuid4",
3717 "builder": {
3718 "project": "chromium",
3719 "builder": "win",
3720 "bucket": "try",
3721 },
3722 "gerritChanges": [{
3723 "project": "depot_tools",
3724 "host": "chromium-review.googlesource.com",
3725 "patchset": 7,
3726 "change": 123456,
3727 }],
3728 "properties": {
3729 "category": "git_cl_try",
3730 "json": [{"a": 1}, None],
3731 "key": "val",
3732 },
3733 "tags": [
3734 {"value": "win", "key": "builder"},
3735 {"value": "git_cl_try", "key": "user_agent"},
3736 ],
3737 "gitilesCommit": {
3738 "host": "chromium-review.googlesource.com",
3739 "project": "depot_tools",
3740 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003741 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003742 }
3743 },
3744 }],
3745 }
3746 mockCallBuildbucket.assert_called_with(
3747 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3748
Edward Lemur45768512020-03-02 19:03:14 +00003749 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003750 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003751 with self.assertRaises(SystemExit):
3752 git_cl.main([
3753 'try', '-B', 'not-a-bucket', '-b', 'win',
3754 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003755 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003756 'Invalid bucket: not-a-bucket.',
3757 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003758
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003759 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003760 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003761 def testScheduleOnBuildbucketRetryFailed(
3762 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003763 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003764 7: [],
3765 6: [{
3766 'id': 112112,
3767 'builder': {
3768 'project': 'chromium',
3769 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003770 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003771 'createTime': '2019-10-09T08:00:01.854286Z',
3772 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003773 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003774 mockCallBuildbucket.return_value = {}
3775
3776 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3777 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003778 'Scheduling jobs on:\n'
3779 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003780 git_cl.sys.stdout.getvalue())
3781
3782 expected_request = {
3783 "requests": [{
3784 "scheduleBuild": {
3785 "requestId": "uuid4",
3786 "builder": {
3787 "project": "chromium",
3788 "bucket": "try",
3789 "builder": "linux",
3790 },
3791 "gerritChanges": [{
3792 "project": "depot_tools",
3793 "host": "chromium-review.googlesource.com",
3794 "patchset": 7,
3795 "change": 123456,
3796 }],
3797 "properties": {
3798 "category": "git_cl_try",
3799 },
3800 "tags": [
3801 {"value": "linux", "key": "builder"},
3802 {"value": "git_cl_try", "key": "user_agent"},
3803 {"value": "1", "key": "retry_failed"},
3804 ],
3805 },
3806 }],
3807 }
3808 mockCallBuildbucket.assert_called_with(
3809 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3810
Edward Lemur4c707a22019-09-24 21:13:43 +00003811 def test_parse_bucket(self):
3812 test_cases = [
3813 {
3814 'bucket': 'chromium/try',
3815 'result': ('chromium', 'try'),
3816 },
3817 {
3818 'bucket': 'luci.chromium.try',
3819 'result': ('chromium', 'try'),
3820 'has_warning': True,
3821 },
3822 {
3823 'bucket': 'skia.primary',
3824 'result': ('skia', 'skia.primary'),
3825 'has_warning': True,
3826 },
3827 {
3828 'bucket': 'not-a-bucket',
3829 'result': (None, None),
3830 },
3831 ]
3832
3833 for test_case in test_cases:
3834 git_cl.sys.stdout.truncate(0)
3835 self.assertEqual(
3836 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3837 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003838 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3839 test_case['result'])
3840 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003841
3842
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003843class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003844
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003845 def setUp(self):
3846 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003847 mock.patch('git_cl._fetch_tryjobs').start()
3848 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003849 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003850 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3851 mock.patch(
3852 'git_cl.Settings.GetSquashGerritUploads',
3853 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003854 self.addCleanup(mock.patch.stopall)
3855
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003856 def testWarmUpChangeDetailCache(self):
3857 self.assertEqual(0, git_cl.main(['upload']))
3858 gerrit_util.GetChangeDetail.assert_called_once_with(
3859 'chromium-review.googlesource.com', 'depot_tools~123456',
3860 frozenset([
3861 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3862 'CURRENT_COMMIT']))
3863
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003864 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003865 # This test mocks out the actual upload part, and just asserts that after
3866 # upload, if --retry-failed is added, then the tool will fetch try jobs
3867 # from the previous patchset and trigger the right builders on the latest
3868 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003869 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003870 # Latest patchset: No builds.
3871 [],
3872 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003873 [{
3874 'id': str(100 + idx),
3875 'builder': {
3876 'project': 'chromium',
3877 'bucket': 'try',
3878 'builder': 'bot_' + status.lower(),
3879 },
3880 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3881 'tags': [],
3882 'status': status,
3883 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003884 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003885
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003886 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003887 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003888 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3889 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003890 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003891 expected_buckets = [
3892 ('chromium', 'try', 'bot_failure'),
3893 ('chromium', 'try', 'bot_infra_failure'),
3894 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003895 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3896 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003897
Brian Sheedy59b06a82019-10-14 17:03:29 +00003898
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003899class MakeRequestsHelperTestCase(unittest.TestCase):
3900
3901 def exampleGerritChange(self):
3902 return {
3903 'host': 'chromium-review.googlesource.com',
3904 'project': 'depot_tools',
3905 'change': 1,
3906 'patchset': 2,
3907 }
3908
3909 def testMakeRequestsHelperNoOptions(self):
3910 # Basic test for the helper function _make_tryjob_schedule_requests;
3911 # it shouldn't throw AttributeError even when options doesn't have any
3912 # of the expected values; it will use default option values.
3913 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3914 jobs = [('chromium', 'try', 'my-builder')]
3915 options = optparse.Values()
3916 requests = git_cl._make_tryjob_schedule_requests(
3917 changelist, jobs, options, patchset=None)
3918
3919 # requestId is non-deterministic. Just assert that it's there and has
3920 # a particular length.
3921 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3922 self.assertEqual(requests, [{
3923 'scheduleBuild': {
3924 'builder': {
3925 'bucket': 'try',
3926 'builder': 'my-builder',
3927 'project': 'chromium'
3928 },
3929 'gerritChanges': [self.exampleGerritChange()],
3930 'properties': {
3931 'category': 'git_cl_try'
3932 },
3933 'tags': [{
3934 'key': 'builder',
3935 'value': 'my-builder'
3936 }, {
3937 'key': 'user_agent',
3938 'value': 'git_cl_try'
3939 }]
3940 }
3941 }])
3942
3943 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3944 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3945 jobs = [('chromium', 'try', 'presubmit')]
3946 options = optparse.Values()
3947 requests = git_cl._make_tryjob_schedule_requests(
3948 changelist, jobs, options, patchset=None)
3949 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3950 'category': 'git_cl_try',
3951 'dry_run': 'true'
3952 })
3953
3954 def testMakeRequestsHelperRevisionSet(self):
3955 # Gitiles commit is specified when revision is in options.
3956 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3957 jobs = [('chromium', 'try', 'my-builder')]
3958 options = optparse.Values({'revision': 'ba5eba11'})
3959 requests = git_cl._make_tryjob_schedule_requests(
3960 changelist, jobs, options, patchset=None)
3961 self.assertEqual(
3962 requests[0]['scheduleBuild']['gitilesCommit'], {
3963 'host': 'chromium-review.googlesource.com',
3964 'id': 'ba5eba11',
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003965 'project': 'depot_tools',
3966 'ref': 'refs/heads/main',
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003967 })
3968
3969 def testMakeRequestsHelperRetryFailedSet(self):
3970 # An extra tag is added when retry_failed is in options.
3971 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3972 jobs = [('chromium', 'try', 'my-builder')]
3973 options = optparse.Values({'retry_failed': 'true'})
3974 requests = git_cl._make_tryjob_schedule_requests(
3975 changelist, jobs, options, patchset=None)
3976 self.assertEqual(
3977 requests[0]['scheduleBuild']['tags'], [
3978 {
3979 'key': 'builder',
3980 'value': 'my-builder'
3981 },
3982 {
3983 'key': 'user_agent',
3984 'value': 'git_cl_try'
3985 },
3986 {
3987 'key': 'retry_failed',
3988 'value': '1'
3989 }
3990 ])
3991
3992 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00003993 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003994 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3995 jobs = [('chromium', 'try', 'my-builder')]
3996 options = optparse.Values({'category': 'my-special-category'})
3997 requests = git_cl._make_tryjob_schedule_requests(
3998 changelist, jobs, options, patchset=None)
3999 self.assertEqual(requests[0]['scheduleBuild']['properties'],
4000 {'category': 'my-special-category'})
4001
4002
Edward Lemurda4b6c62020-02-13 00:28:40 +00004003class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004004
4005 def setUp(self):
4006 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00004007 mock.patch('git_cl.RunCommand').start()
4008 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
4009 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
4010 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00004011 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00004012 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004013
4014 def tearDown(self):
4015 shutil.rmtree(self._top_dir)
4016 super(CMDFormatTestCase, self).tearDown()
4017
Jamie Madill5e96ad12020-01-13 16:08:35 +00004018 def _make_temp_file(self, fname, contents):
Anthony Politoc64e3902021-04-30 21:55:25 +00004019 gclient_utils.FileWrite(os.path.join(self._top_dir, fname),
4020 ('\n'.join(contents)))
Jamie Madill5e96ad12020-01-13 16:08:35 +00004021
Brian Sheedy59b06a82019-10-14 17:03:29 +00004022 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00004023 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004024
Brian Sheedyb4307d52019-12-02 19:18:17 +00004025 def _check_yapf_filtering(self, files, expected):
4026 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
4027 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00004028
Edward Lemur1a83da12020-03-04 21:18:36 +00004029 def _run_command_mock(self, return_value):
4030 def f(*args, **kwargs):
4031 if 'stdin' in kwargs:
4032 self.assertIsInstance(kwargs['stdin'], bytes)
4033 return return_value
4034 return f
4035
Jamie Madill5e96ad12020-01-13 16:08:35 +00004036 def testClangFormatDiffFull(self):
4037 self._make_temp_file('test.cc', ['// test'])
4038 git_cl.settings.GetFormatFullByDefault.return_value = False
4039 diff_file = [os.path.join(self._top_dir, 'test.cc')]
4040 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
4041
4042 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004043 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004044 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
4045 self._top_dir, 'HEAD')
4046 self.assertEqual(2, return_value)
4047
4048 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004049 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004050 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
4051 self._top_dir, 'HEAD')
4052 self.assertEqual(0, return_value)
4053
4054 def testClangFormatDiff(self):
4055 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00004056 # A valid file is required, so use this test.
4057 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00004058 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
4059
4060 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004061 git_cl.RunCommand.side_effect = self._run_command_mock('error')
4062 return_value = git_cl._RunClangFormatDiff(
4063 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004064 self.assertEqual(2, return_value)
4065
4066 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004067 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004068 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
4069 'HEAD')
4070 self.assertEqual(0, return_value)
4071
Brian Sheedyb4307d52019-12-02 19:18:17 +00004072 def testYapfignoreExplicit(self):
4073 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
4074 files = [
4075 'bar.py',
4076 'foo/bar.py',
4077 'foo/baz.py',
4078 'foo/bar/baz.py',
4079 'foo/bar/foobar.py',
4080 ]
4081 expected = [
4082 'bar.py',
4083 'foo/baz.py',
4084 'foo/bar/foobar.py',
4085 ]
4086 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004087
Brian Sheedyb4307d52019-12-02 19:18:17 +00004088 def testYapfignoreSingleWildcards(self):
4089 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
4090 files = [
4091 'bar.py', # Matched by *bar.py.
4092 'bar.txt',
4093 'foobar.py', # Matched by *bar.py, foo*.
4094 'foobar.txt', # Matched by foo*.
4095 'bazbar.py', # Matched by *bar.py, baz*.py.
4096 'bazbar.txt',
4097 'foo/baz.txt', # Matched by foo*.
4098 'bar/bar.py', # Matched by *bar.py.
4099 'baz/foo.py', # Matched by baz*.py, foo*.
4100 'baz/foo.txt',
4101 ]
4102 expected = [
4103 'bar.txt',
4104 'bazbar.txt',
4105 'baz/foo.txt',
4106 ]
4107 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004108
Brian Sheedyb4307d52019-12-02 19:18:17 +00004109 def testYapfignoreMultiplewildcards(self):
4110 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
4111 files = [
4112 'bar.py', # Matched by *bar*.
4113 'bar.txt', # Matched by *bar*.
4114 'abar.py', # Matched by *bar*.
4115 'foobaz.txt', # Matched by *foo*baz.txt.
4116 'foobaz.py',
4117 'afoobaz.txt', # Matched by *foo*baz.txt.
4118 ]
4119 expected = [
4120 'foobaz.py',
4121 ]
4122 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004123
4124 def testYapfignoreComments(self):
4125 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004126 files = [
4127 'test.py',
4128 'test2.py',
4129 ]
4130 expected = [
4131 'test2.py',
4132 ]
4133 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004134
Anthony Politoc64e3902021-04-30 21:55:25 +00004135 def testYapfHandleUtf8(self):
4136 self._make_yapfignore(['test.py', 'test_🌐.py'])
4137 files = [
4138 'test.py',
4139 'test_🌐.py',
4140 'test2.py',
4141 ]
4142 expected = [
4143 'test2.py',
4144 ]
4145 self._check_yapf_filtering(files, expected)
4146
Brian Sheedy59b06a82019-10-14 17:03:29 +00004147 def testYapfignoreBlankLines(self):
4148 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004149 files = [
4150 'test.py',
4151 'test2.py',
4152 'test3.py',
4153 ]
4154 expected = [
4155 'test3.py',
4156 ]
4157 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004158
4159 def testYapfignoreWhitespace(self):
4160 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004161 files = [
4162 'test.py',
4163 'test2.py',
4164 ]
4165 expected = [
4166 'test2.py',
4167 ]
4168 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004169
Brian Sheedyb4307d52019-12-02 19:18:17 +00004170 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004171 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004172 self._check_yapf_filtering([], [])
4173
4174 def testYapfignoreMissingYapfignore(self):
4175 files = [
4176 'test.py',
4177 ]
4178 expected = [
4179 'test.py',
4180 ]
4181 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004182
4183
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004184class CMDStatusTestCase(CMDTestCaseBase):
4185 # Return branch names a,..,f with comitterdates in increasing order, i.e.
4186 # 'f' is the most-recently changed branch.
4187 def _mock_run_git(commands):
4188 if commands == [
4189 'for-each-ref', '--format=%(refname) %(committerdate:unix)',
4190 'refs/heads'
4191 ]:
4192 branches_and_committerdates = [
4193 'refs/heads/a 1',
4194 'refs/heads/b 2',
4195 'refs/heads/c 3',
4196 'refs/heads/d 4',
4197 'refs/heads/e 5',
4198 'refs/heads/f 6',
4199 ]
4200 return '\n'.join(branches_and_committerdates)
4201
4202 # Mock the status in such a way that the issue number gives us an
4203 # indication of the commit date (simplifies manual debugging).
4204 def _mock_get_cl_statuses(branches, fine_grained, max_processes):
4205 for c in branches:
4206 c.issue = (100 + int(c.GetCommitDate()))
4207 yield (c, 'open')
4208
4209 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4210 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4211 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4212 @mock.patch('git_cl.RunGit', _mock_run_git)
4213 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4214 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004215 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004216 @mock.patch('scm.GIT.GetBranch', return_value='a')
4217 def testStatus(self, *_mocks):
4218 self.assertEqual(0, git_cl.main(['status', '--no-branch-color']))
4219 self.maxDiff = None
4220 self.assertEqual(
4221 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4222 ' * a : https://crrev.com/c/101 (open)\n'
4223 ' b : https://crrev.com/c/102 (open)\n'
4224 ' c : https://crrev.com/c/103 (open)\n'
4225 ' d : https://crrev.com/c/104 (open)\n'
4226 ' e : https://crrev.com/c/105 (open)\n'
4227 ' f : https://crrev.com/c/106 (open)\n\n'
4228 'Current branch: a\n'
4229 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4230 'Issue description:\n'
4231 'x\n')
4232
4233 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4234 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4235 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4236 @mock.patch('git_cl.RunGit', _mock_run_git)
4237 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4238 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004239 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004240 @mock.patch('scm.GIT.GetBranch', return_value='a')
4241 def testStatusByDate(self, *_mocks):
4242 self.assertEqual(
4243 0, git_cl.main(['status', '--no-branch-color', '--date-order']))
4244 self.maxDiff = None
4245 self.assertEqual(
4246 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4247 ' f : https://crrev.com/c/106 (open)\n'
4248 ' e : https://crrev.com/c/105 (open)\n'
4249 ' d : https://crrev.com/c/104 (open)\n'
4250 ' c : https://crrev.com/c/103 (open)\n'
4251 ' b : https://crrev.com/c/102 (open)\n'
4252 ' * a : https://crrev.com/c/101 (open)\n\n'
4253 'Current branch: a\n'
4254 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4255 'Issue description:\n'
4256 'x\n')
4257
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004258 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4259 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4260 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4261 @mock.patch('git_cl.RunGit', _mock_run_git)
4262 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4263 @mock.patch('git_cl.Settings.GetRoot', return_value='')
4264 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=True)
4265 @mock.patch('scm.GIT.GetBranch', return_value='a')
4266 def testStatusByDate(self, *_mocks):
4267 self.assertEqual(
4268 0, git_cl.main(['status', '--no-branch-color']))
4269 self.maxDiff = None
4270 self.assertEqual(
4271 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4272 ' f : https://crrev.com/c/106 (open)\n'
4273 ' e : https://crrev.com/c/105 (open)\n'
4274 ' d : https://crrev.com/c/104 (open)\n'
4275 ' c : https://crrev.com/c/103 (open)\n'
4276 ' b : https://crrev.com/c/102 (open)\n'
4277 ' * a : https://crrev.com/c/101 (open)\n\n'
4278 'Current branch: a\n'
4279 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4280 'Issue description:\n'
4281 'x\n')
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004282
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004283class CMDOwnersTestCase(CMDTestCaseBase):
4284 def setUp(self):
4285 super(CMDOwnersTestCase, self).setUp()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004286 self.owners_by_path = {
4287 'foo': ['a@example.com'],
4288 'bar': ['b@example.com', 'c@example.com'],
4289 }
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004290 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
4291 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
4292 mock.patch(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004293 'git_cl.Changelist.GetAffectedFiles',
4294 return_value=list(self.owners_by_path)).start()
4295 mock.patch(
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004296 'git_cl.Changelist.GetCommonAncestorWithUpstream',
4297 return_value='upstream').start()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004298 mock.patch(
Edward Lesmese1576912021-02-16 21:53:34 +00004299 'git_cl.Changelist.GetGerritHost',
4300 return_value='host').start()
4301 mock.patch(
4302 'git_cl.Changelist.GetGerritProject',
4303 return_value='project').start()
4304 mock.patch(
4305 'git_cl.Changelist.GetRemoteBranch',
4306 return_value=('origin', 'refs/remotes/origin/main')).start()
4307 mock.patch(
4308 'owners_client.OwnersClient.BatchListOwners',
Edward Lesmes82b992a2021-01-11 23:24:55 +00004309 return_value=self.owners_by_path).start()
Edward Lesmes8170c292021-03-19 20:04:43 +00004310 mock.patch(
4311 'gerrit_util.IsCodeOwnersEnabledOnHost', return_value=True).start()
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004312 self.addCleanup(mock.patch.stopall)
4313
4314 def testShowAllNoArgs(self):
4315 self.assertEqual(0, git_cl.main(['owners', '--show-all']))
4316 self.assertEqual(
4317 'No files specified for --show-all. Nothing to do.\n',
4318 git_cl.sys.stdout.getvalue())
4319
4320 def testShowAll(self):
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004321 self.assertEqual(
4322 0,
4323 git_cl.main(['owners', '--show-all', 'foo', 'bar', 'baz']))
Edward Lesmese1576912021-02-16 21:53:34 +00004324 owners_client.OwnersClient.BatchListOwners.assert_called_once_with(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004325 ['foo', 'bar', 'baz'])
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004326 self.assertEqual(
4327 '\n'.join([
4328 'Owners for foo:',
4329 ' - a@example.com',
4330 'Owners for bar:',
4331 ' - b@example.com',
4332 ' - c@example.com',
4333 'Owners for baz:',
4334 ' - No owners found',
4335 '',
4336 ]),
4337 sys.stdout.getvalue())
4338
Edward Lesmes82b992a2021-01-11 23:24:55 +00004339 def testBatch(self):
4340 self.assertEqual(0, git_cl.main(['owners', '--batch']))
4341 self.assertIn('a@example.com', sys.stdout.getvalue())
4342 self.assertIn('b@example.com', sys.stdout.getvalue())
4343
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004344
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004345if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01004346 logging.basicConfig(
4347 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004348 unittest.main()