blob: 653b940c468de00a893bf5b3a9fc4bda8db5e849 [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
479
Edward Lemurda4b6c62020-02-13 00:28:40 +0000480class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100481 def setUp(self):
482 super(GitCookiesCheckerTest, self).setUp()
483 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100484 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000485 mock.patch('sys.stdout', StringIO()).start()
486 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100487
488 def mock_hosts_creds(self, subhost_identity_pairs):
489 def ensure_googlesource(h):
490 if not h.endswith(self.c._GOOGLESOURCE):
491 assert not h.endswith('.')
492 return h + '.' + self.c._GOOGLESOURCE
493 return h
494 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
495 for h, i in subhost_identity_pairs]
496
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200497 def test_identity_parsing(self):
498 self.assertEqual(self.c._parse_identity('ldap.google.com'),
499 ('ldap', 'google.com'))
500 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
501 ('ldap', 'example.com'))
502 # Specical case because we know there are no subdomains in chromium.org.
503 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
504 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800505 # Pathological: ".period." can be either username OR domain, more likely
506 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200507 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
508 ('note', 'period.example.com'))
509
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100510 def test_analysis_nothing(self):
511 self.c._all_hosts = []
512 self.assertFalse(self.c.has_generic_host())
513 self.assertEqual(set(), self.c.get_conflicting_hosts())
514 self.assertEqual(set(), self.c.get_duplicated_hosts())
515 self.assertEqual(set(), self.c.get_partially_configured_hosts())
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100516
517 def test_analysis(self):
518 self.mock_hosts_creds([
519 ('.googlesource.com', 'git-example.chromium.org'),
520
521 ('chromium', 'git-example.google.com'),
522 ('chromium-review', 'git-example.google.com'),
523 ('chrome-internal', 'git-example.chromium.org'),
524 ('chrome-internal-review', 'git-example.chromium.org'),
525 ('conflict', 'git-example.google.com'),
526 ('conflict-review', 'git-example.chromium.org'),
527 ('dup', 'git-example.google.com'),
528 ('dup', 'git-example.google.com'),
529 ('dup-review', 'git-example.google.com'),
530 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200531 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100532 ])
533 self.assertTrue(self.c.has_generic_host())
534 self.assertEqual(set(['conflict.googlesource.com']),
535 self.c.get_conflicting_hosts())
536 self.assertEqual(set(['dup.googlesource.com']),
537 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200538 self.assertEqual(set(['partial.googlesource.com',
539 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100540 self.c.get_partially_configured_hosts())
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100541
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100542 def test_report_no_problems(self):
543 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100544 self.assertFalse(self.c.find_and_report_problems())
545 self.assertEqual(sys.stdout.getvalue(), '')
546
Edward Lemurda4b6c62020-02-13 00:28:40 +0000547 @mock.patch(
548 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000549 return_value=os.path.join('~', '.gitcookies'))
Edward Lemurda4b6c62020-02-13 00:28:40 +0000550 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100551 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100552 self.assertTrue(self.c.find_and_report_problems())
553 with open(os.path.join(os.path.dirname(__file__),
554 'git_cl_creds_check_report.txt')) as f:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000555 expected = f.read() % {
556 'sep': os.sep,
557 }
558
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100559 def by_line(text):
560 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700561 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200562 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100563
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800564
Edward Lemurda4b6c62020-02-13 00:28:40 +0000565class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000566 def setUp(self):
567 super(TestGitCl, self).setUp()
568 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700569 self._calls_done = []
Edward Lesmes0dd54822020-03-26 18:24:25 +0000570 self.failed = False
Edward Lemurda4b6c62020-02-13 00:28:40 +0000571 mock.patch('sys.stdout', StringIO()).start()
572 mock.patch(
573 'git_cl.time_time',
574 lambda: self._mocked_call('time.time')).start()
575 mock.patch(
576 'git_cl.metrics.collector.add_repeated',
577 lambda *a: self._mocked_call('add_repeated', *a)).start()
578 mock.patch('subprocess2.call', self._mocked_call).start()
579 mock.patch('subprocess2.check_call', self._mocked_call).start()
580 mock.patch('subprocess2.check_output', self._mocked_call).start()
581 mock.patch(
582 'subprocess2.communicate',
583 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
584 mock.patch(
585 'git_cl.gclient_utils.CheckCallAndFilter',
586 self._mocked_call).start()
587 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000588 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
589 mock.patch(
590 'git_cl.SaveDescriptionBackup',
591 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
592 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000593 'git_cl.write_json',
594 lambda *a: self._mocked_call('write_json', *a)).start()
595 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000596 'git_cl.Changelist.RunHook',
597 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000598 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
599 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000600 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000601 mock.patch(
602 'git_cl.gerrit_util.GetChangeComments',
603 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
604 mock.patch(
605 'git_cl.gerrit_util.GetChangeRobotComments',
606 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
607 mock.patch(
608 'git_cl.gerrit_util.AddReviewers',
609 lambda *a: self._mocked_call('AddReviewers', *a)).start()
610 mock.patch(
611 'git_cl.gerrit_util.SetReview',
612 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
613 self._mocked_call(
614 'SetReview', h, i, msg, labels, notify, ready))).start()
615 mock.patch(
616 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
617 return_value=False).start()
618 mock.patch(
619 'git_cl.gerrit_util.GceAuthenticator.is_gce',
620 return_value=False).start()
621 mock.patch(
622 'git_cl.gerrit_util.ValidAccounts',
623 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000624 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000625 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000626 self.mockGit = GitMocks()
627 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
628 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
Edward Lesmes50da7702020-03-30 19:23:43 +0000629 mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
630 mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
Edward Lemur85153282020-02-14 22:06:29 +0000631 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000632 mock.patch(
633 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000634 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000635 'scm.GIT.FetchUpstreamTuple',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000636 return_value=('origin', 'refs/heads/main')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000637 mock.patch(
638 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000639 # It's important to reset settings to not have inter-tests interference.
640 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000641 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000642
643 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000644 try:
Edward Lesmes0dd54822020-03-26 18:24:25 +0000645 if not self.failed:
646 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100647 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000648 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
649 if len(self.calls) > 5:
650 calls += ' ...\n'
651 self.fail(
652 '\n'
653 'There are un-consumed calls after this test has finished:\n' +
654 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000655 finally:
656 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000657
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000658 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000659 self.assertTrue(
660 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700661 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000662 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000663 expected_args, result = top
664
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000665 # Also logs otherwise it could get caught in a try/finally and be hard to
666 # diagnose.
667 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700668 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000669 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700670 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
671 for i, c in enumerate(self._calls_done[-N:]))
672 following_calls = '\n '.join(
673 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
674 for i, c in enumerate(self.calls[:N]))
675 extended_msg = (
676 'A few prior calls:\n %s\n\n'
677 'This (expected):\n @%d: %r\n'
678 'This (actual):\n @%d: %r\n\n'
679 'A few following expected calls:\n %s' %
680 (prior_calls, len(self._calls_done), expected_args,
681 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700682
Edward Lesmes0dd54822020-03-26 18:24:25 +0000683 self.failed = True
tandrii99a72f22016-08-17 14:33:24 -0700684 self.fail('@%d\n'
685 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000686 ' Actual: %r\n'
687 '\n'
688 '%s' % (
689 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700690
691 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700692 if isinstance(result, Exception):
693 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000694 # stdout from git commands is supposed to be a bytestream. Convert it here
695 # instead of converting all test output in this file to bytes.
696 if args[0][0] == 'git' and not isinstance(result, bytes):
697 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000698 return result
699
Edward Lemur1a83da12020-03-04 21:18:36 +0000700 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
701 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100702 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100703 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000704 self.assertEqual(
705 'prompt [Yes/No]: Please, type yes or no: ',
706 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100707
tandrii48df5812016-10-17 03:55:37 -0700708 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000709 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700710 self.calls = [
711 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700712 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
713 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
714 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
715 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700716 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
717 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700718 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
719 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000720 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
721 CERR1),
Dirk Pranke6f0df682021-06-25 00:42:33 +0000722 ((['git', 'config', '--unset-all', 'rietveld.use-python3'],),
723 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700724 ((['git', 'config', 'gerrit.host', 'true'],), ''),
725 ]
726 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
727
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000728 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100729 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200730 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000731 custom_cl_base=None, short_hostname='chromium',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000732 change_id=None, default_branch='main'):
Edward Lemur26964072020-02-19 19:18:51 +0000733 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200734 if custom_cl_base:
735 ancestor_revision = custom_cl_base
736 else:
737 # Determine ancestor_revision to be merge base.
Edward Lesmes8c43c3f2021-01-20 00:20:26 +0000738 ancestor_revision = 'origin/' + default_branch
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200739
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100740 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000741 gerrit_util.GetChangeDetail.return_value = {
742 'owner': {'email': (other_cl_owner or 'owner@example.com')},
743 'change_id': (change_id or '123456789'),
744 'current_revision': 'sha1_of_current_revision',
745 'revisions': {'sha1_of_current_revision': {
746 'commit': {'message': fetched_description},
747 }},
748 'status': fetched_status or 'NEW',
749 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100750 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100751 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100752 if other_cl_owner:
753 calls += [
754 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
755 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100756
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100757 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200758 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
759 ([custom_cl_base] if custom_cl_base else
760 [ancestor_revision, 'HEAD']),),
761 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100762 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000763
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100764 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000765
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000766 def _gerrit_upload_calls(self,
767 description,
768 reviewers,
769 squash,
tandriia60502f2016-06-20 02:01:53 -0700770 squash_mode='default',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000771 title=None,
772 notify=False,
773 post_amend_description=None,
774 issue=None,
775 cc=None,
776 custom_cl_base=None,
777 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000778 short_hostname='chromium',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000779 labels=None,
780 change_id=None,
781 final_description=None,
782 gitcookies_exists=True,
783 force=False,
784 edit_description=None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000785 default_branch='main',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000786 push_opts=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000787 if post_amend_description is None:
788 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700789 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200790
791 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000792
Edward Lesmes4de54132020-05-05 19:41:33 +0000793 if squash_mode in ('override_squash', 'override_nosquash'):
794 self.mockGit.config['gerrit.override-squash-uploads'] = (
795 'true' if squash_mode == 'override_squash' else 'false')
796
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000797 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000798 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200799 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200800 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000801 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000802 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000803 calls += [
804 ((['RunEditor'],), description),
805 ]
Josipe827b0f2020-01-30 00:07:20 +0000806 # user wants to edit description
807 if edit_description:
808 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000809 ((['RunEditor'],), edit_description),
810 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000811 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200812
813 if custom_cl_base is None:
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000814 parent = 'origin/' + default_branch
Edward Lesmes8c43c3f2021-01-20 00:20:26 +0000815 git_common.get_or_create_merge_base.return_value = parent
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200816 else:
817 calls += [
818 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000819 'refs/remotes/origin/' + default_branch],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200820 callError(1)), # Means not ancenstor.
821 (('ask_for_data',
822 'Do you take responsibility for cleaning up potential mess '
823 'resulting from proceeding with upload? Press Enter to upload, '
824 'or Ctrl+C to abort'), ''),
825 ]
826 parent = custom_cl_base
827
828 calls += [
829 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
830 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000831 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200832 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000833 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200834 ref_to_push),
835 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000836 else:
837 ref_to_push = 'HEAD'
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000838 parent = 'origin/refs/heads/' + default_branch
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000839
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000840 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000841 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000842 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200843 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000844
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000845 metrics_arguments = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000846
Aaron Gableafd52772017-06-27 16:40:10 -0700847 if notify:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000848 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000849 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700850 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400851 if not issue and squash:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000852 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000853 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700854 else:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000855 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000856 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800857
Edward Lemur5a644f82020-03-18 16:44:57 +0000858 # If issue is given, then description is fetched from Gerrit instead.
859 if issue is None:
860 if squash:
861 title = 'Initial upload'
862 else:
863 if not title:
864 calls += [
865 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
866 (('ask_for_data', 'Title for patchset []: '), 'User input'),
867 ]
868 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700869 if title:
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000870 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000871 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000872
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000873 if short_hostname == 'chromium':
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000874 # All reviewers and ccs get into ref_suffix.
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000875 for r in sorted(reviewers):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000876 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000877 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000878 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000879 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000880 for c in sorted(cc):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000881 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000882 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000883 reviewers, cc = [], []
884 else:
885 # TODO(crbug/877717): remove this case.
886 calls += [
887 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
888 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000889 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000890 {
891 e: {'email': e}
892 for e in (reviewers + ['joe@example.com'] + cc)
893 })
894 ]
895 for r in sorted(reviewers):
896 if r != 'bad-account-or-email':
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000897 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000898 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000899 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000900 if issue is None:
901 cc += ['joe@example.com']
902 for c in sorted(cc):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000903 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000904 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000905 if c in cc:
906 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000907
Edward Lemur687ca902018-12-05 02:30:30 +0000908 for k, v in sorted((labels or {}).items()):
Josip Sokcevicd0ba91f2021-03-29 20:12:09 +0000909 ref_suffix += ',l=%s+%d' % (k, v)
Edward Lemur687ca902018-12-05 02:30:30 +0000910 metrics_arguments.append('l=%s+%d' % (k, v))
911
912 if tbr:
913 calls += [
914 (('GetCodeReviewTbrScore',
915 '%s-review.googlesource.com' % short_hostname,
916 'my/repo'),
917 2,),
918 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000919
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000920 calls += [
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +0000921 (
922 ('time.time', ),
923 1000,
924 ),
925 (
926 ([
927 'git', 'push',
928 'https://%s.googlesource.com/my/repo' % short_hostname,
929 ref_to_push + ':refs/for/refs/heads/' + default_branch +
930 ref_suffix
931 ] + (push_opts if push_opts else []), ),
932 (('remote:\n'
933 'remote: Processing changes: (\)\n'
934 'remote: Processing changes: (|)\n'
935 'remote: Processing changes: (/)\n'
936 'remote: Processing changes: (-)\n'
937 'remote: Processing changes: new: 1 (/)\n'
938 'remote: Processing changes: new: 1, done\n'
939 'remote:\n'
940 'remote: New Changes:\n'
941 'remote: '
942 'https://%s-review.googlesource.com/#/c/my/repo/+/123456'
943 ' XXX\n'
944 'remote:\n'
945 'To https://%s.googlesource.com/my/repo\n'
946 ' * [new branch] hhhh -> refs/for/refs/heads/%s\n') %
947 (short_hostname, short_hostname, default_branch)),
948 ),
949 (
950 ('time.time', ),
951 2000,
952 ),
953 (
954 ('add_repeated', 'sub_commands', {
955 'execution_time': 1000,
956 'command': 'git push',
957 'exit_code': 0,
958 'arguments': sorted(metrics_arguments),
959 }),
960 None,
961 ),
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000962 ]
963
Edward Lemur1b52d872019-05-09 21:12:12 +0000964 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000965
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000966 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
967
Edward Lemur1b52d872019-05-09 21:12:12 +0000968 # Trace-related calls
969 calls += [
970 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000971 (
972 ([
973 'FileWrite', trace_name + '-README',
974 '%(date)s\n'
975 '%(short_hostname)s-review.googlesource.com\n'
976 '%(change_id)s\n'
977 '%(title)s\n'
978 '%(description)s\n'
979 '1000\n'
980 '0\n'
981 '%(trace_name)s' % {
Josip Sokcevic5e18b602020-04-23 21:47:00 +0000982 'date': '2017-03-16T20:00:41.000000',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000983 'short_hostname': short_hostname,
984 'change_id': change_id,
985 'description': final_description,
986 'title': title or '<untitled>',
987 'trace_name': trace_name,
988 }
989 ], ),
990 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000991 ),
992 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000993 (
994 (['os.path.isfile',
995 os.path.join('TEMP_DIR', 'trace-packet')], ),
996 True,
Edward Lemur1b52d872019-05-09 21:12:12 +0000997 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000998 (
999 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
1000 ('git-hash: 0123456789012345678901234567890123456789\n'
1001 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +00001002 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001003 (
1004 ([
1005 'FileWrite',
1006 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
1007 'git-hash: abcdea\n'
1008 ], ),
1009 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001010 ),
1011 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001012 (
1013 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
1014 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001015 ),
1016 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001017 (
1018 (['git', 'config', '-l'], ),
1019 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +00001020 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001021 (
1022 ([
1023 'FileWrite',
1024 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
1025 ], ),
1026 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001027 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001028 (
1029 (['os.path.isfile',
1030 os.path.join('~', '.gitcookies')], ),
1031 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +00001032 ),
1033 ]
1034 if gitcookies_exists:
1035 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001036 (
1037 (['FileRead', os.path.join('~', '.gitcookies')], ),
1038 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +00001039 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001040 (
1041 ([
1042 'FileWrite',
1043 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
1044 ], ),
1045 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001046 ),
1047 ]
1048 calls += [
1049 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001050 (
1051 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
1052 None,
Edward Lemur1b52d872019-05-09 21:12:12 +00001053 ),
1054 ]
1055
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001056 # TODO(crbug/877717): this should never be used.
1057 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001058 calls += [
1059 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001060 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001061 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001062 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001063 notify),
1064 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001065 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001066 return calls
1067
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001068 def _run_gerrit_upload_test(self,
1069 upload_args,
1070 description,
1071 reviewers=None,
1072 squash=True,
1073 squash_mode=None,
1074 title=None,
1075 notify=False,
1076 post_amend_description=None,
1077 issue=None,
1078 cc=None,
1079 fetched_status=None,
1080 other_cl_owner=None,
1081 custom_cl_base=None,
1082 tbr=None,
1083 short_hostname='chromium',
1084 labels=None,
1085 change_id=None,
1086 final_description=None,
1087 gitcookies_exists=True,
1088 force=False,
1089 log_description=None,
1090 edit_description=None,
1091 fetched_description=None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001092 default_branch='main',
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001093 push_opts=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001094 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001095 if squash_mode is None:
1096 if '--no-squash' in upload_args:
1097 squash_mode = 'nosquash'
1098 elif '--squash' in upload_args:
1099 squash_mode = 'squash'
1100 else:
1101 squash_mode = 'default'
1102
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001103 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001104 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001105 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001106 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001107 same_auth=('git-owner.example.com', '', 'pass'))).start()
1108 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1109 lambda _, offer_removal: None).start()
1110 mock.patch('git_cl.gclient_utils.RunEditor',
1111 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1112 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001113 'DownloadGerritHook', force)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001114 mock.patch('git_cl.gclient_utils.FileRead',
1115 lambda path: self._mocked_call(['FileRead', path])).start()
1116 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001117 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001118 ['FileWrite', path, contents])).start()
1119 mock.patch('git_cl.datetime_now',
1120 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1121 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1122 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1123 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001124 '%(now)s\n'
1125 '%(gerrit_host)s\n'
1126 '%(change_id)s\n'
1127 '%(title)s\n'
1128 '%(description)s\n'
1129 '%(execution_time)s\n'
1130 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001131 '%(trace_name)s').start()
1132 mock.patch('git_cl.shutil.make_archive',
1133 lambda *args: self._mocked_call(['make_archive'] +
1134 list(args))).start()
1135 mock.patch('os.path.isfile',
1136 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001137 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001138 'git_cl._create_description_from_log',
1139 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001140 mock.patch(
1141 'git_cl.Changelist._AddChangeIdToCommitMessage',
1142 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001143 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001144 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1145 mock.patch(
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001146 'git_common.get_or_create_merge_base',
1147 return_value='origin/' + default_branch).start()
1148 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001149 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001150 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001151
Edward Lemur26964072020-02-19 19:18:51 +00001152 self.mockGit.config['gerrit.host'] = 'true'
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001153 self.mockGit.config['branch.main.gerritissue'] = (
Edward Lemur85153282020-02-14 22:06:29 +00001154 str(issue) if issue else None)
1155 self.mockGit.config['remote.origin.url'] = (
1156 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001157 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001158
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001159 self.calls = self._gerrit_base_calls(
1160 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001161 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001162 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001163 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001164 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001165 short_hostname=short_hostname,
Josip Sokcevicc39ab992020-09-24 20:09:15 +00001166 change_id=change_id,
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001167 default_branch=default_branch)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001168 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001169 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001170 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001171 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001172 self.calls += self._gerrit_upload_calls(
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001173 description,
1174 reviewers,
1175 squash,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001176 squash_mode=squash_mode,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001177 title=title,
1178 notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001179 post_amend_description=post_amend_description,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001180 issue=issue,
1181 cc=cc,
1182 custom_cl_base=custom_cl_base,
1183 tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001184 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001185 labels=labels,
1186 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001187 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001188 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001189 force=force,
Josip Sokcevicc39ab992020-09-24 20:09:15 +00001190 edit_description=edit_description,
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001191 default_branch=default_branch,
1192 push_opts=push_opts)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001193 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001194 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001195 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001196 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001197 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001198 self.assertEqual(
1199 'abcdef0123456789',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001200 scm.GIT.GetBranchConfig('', 'main', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001201
Edward Lemur1b52d872019-05-09 21:12:12 +00001202 def test_gerrit_upload_traces_no_gitcookies(self):
1203 self._run_gerrit_upload_test(
1204 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001205 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001206 [],
1207 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001208 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001209 change_id='Ixxx',
1210 gitcookies_exists=False)
1211
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001212 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001213 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001214 [],
1215 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1216 [],
1217 change_id='Ixxx')
1218
1219 def test_gerrit_upload_without_change_id_nosquash(self):
1220 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001221 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001222 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001223 [],
1224 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001225 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001226 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001227
Edward Lesmes4de54132020-05-05 19:41:33 +00001228 def test_gerrit_upload_without_change_id_override_nosquash(self):
1229 self._run_gerrit_upload_test(
1230 [],
1231 'desc ✔\n\nBUG=\n',
1232 [],
1233 squash=False,
1234 squash_mode='override_nosquash',
1235 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1236 change_id='Ixxx')
1237
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001238 def test_gerrit_no_reviewer(self):
1239 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001240 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001241 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001242 [],
1243 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001244 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001245 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001246
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001247 def test_gerrit_push_opts(self):
1248 self._run_gerrit_upload_test(['-o', 'wip'],
1249 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
1250 [],
1251 squash=False,
1252 squash_mode='override_nosquash',
1253 change_id='I123456789',
1254 push_opts=['-o', 'wip'])
1255
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001256 def test_gerrit_no_reviewer_non_chromium_host(self):
1257 # TODO(crbug/877717): remove this test case.
Josip Sokcevicf2cfd3d2021-03-30 18:39:18 +00001258 self._run_gerrit_upload_test([],
1259 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
1260 [],
1261 squash=False,
1262 squash_mode='override_nosquash',
1263 short_hostname='other',
1264 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001265
Edward Lesmes0dd54822020-03-26 18:24:25 +00001266 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001267 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001268 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001269 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001270 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001271 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001272 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001273 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001274
ukai@chromium.orge8077812012-02-03 03:41:46 +00001275 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001276 self._run_gerrit_upload_test(
Edward Lesmes4de54132020-05-05 19:41:33 +00001277 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001278 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001279 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001280 squash=False,
Edward Lesmes4de54132020-05-05 19:41:33 +00001281 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001282 notify=True,
1283 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001284 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001285 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001286
Anthony Polito8b955342019-09-24 19:01:36 +00001287 def test_gerrit_upload_force_sets_bug(self):
1288 self._run_gerrit_upload_test(
1289 ['-b', '10000', '-f'],
1290 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1291 [],
1292 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001293 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001294 change_id='Ixxx')
1295
Edward Lemur5fb22242020-03-12 22:05:13 +00001296 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001297 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001298 ['-b', '10000', '-m', 'Title', '--edit-description'],
1299 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001300 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001301 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001302 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001303 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001304 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001305 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001306
Dan Beamd8b04ca2019-10-10 21:23:26 +00001307 def test_gerrit_upload_force_sets_fixed(self):
1308 self._run_gerrit_upload_test(
1309 ['-x', '10000', '-f'],
1310 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1311 [],
1312 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001313 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001314 change_id='Ixxx')
1315
ukai@chromium.orge8077812012-02-03 03:41:46 +00001316 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001317 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1318 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001319 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001320 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001321 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001322 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001323 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001324 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001325 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001326 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001327 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001328 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001329
1330 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001331 self._run_gerrit_upload_test(
1332 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001333 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001334 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001335 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001336
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001337 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001338 self._run_gerrit_upload_test(
1339 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001340 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001341 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001342 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001343 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001344
Edward Lesmes0dd54822020-03-26 18:24:25 +00001345 def test_gerrit_upload_squash_first_title(self):
1346 self._run_gerrit_upload_test(
1347 ['-f', '-t', 'title'],
1348 'title\n\ndesc\n\nChange-Id: 123456789',
1349 [],
1350 force=True,
1351 squash=True,
1352 log_description='desc',
1353 change_id='123456789')
1354
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001355 def test_gerrit_upload_squash_first_with_labels(self):
1356 self._run_gerrit_upload_test(
1357 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001358 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001359 [],
1360 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001361 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001362 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001363
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001364 def test_gerrit_upload_squash_first_against_rev(self):
1365 custom_cl_base = 'custom_cl_base_rev_or_branch'
1366 self._run_gerrit_upload_test(
1367 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001368 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001369 [],
1370 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001371 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001372 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001373 self.assertIn(
1374 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1375 sys.stdout.getvalue())
1376
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001377 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001378 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001379 self._run_gerrit_upload_test(
1380 ['--squash'],
1381 description,
1382 [],
1383 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001384 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001385 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001386
Edward Lemurd55c5072020-02-20 01:09:07 +00001387 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001388 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001389 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001390 with self.assertRaises(SystemExitMock):
1391 self._run_gerrit_upload_test(
1392 ['--squash'],
1393 description,
1394 [],
1395 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001396 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001397 fetched_status='ABANDONED',
1398 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001399 self.assertEqual(
1400 'Change https://chromium-review.googlesource.com/123456 has been '
1401 'abandoned, new uploads are not allowed\n',
1402 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001403
Edward Lemurda4b6c62020-02-13 00:28:40 +00001404 @mock.patch(
1405 'gerrit_util.GetAccountDetails',
1406 return_value={'email': 'yet-another@example.com'})
1407 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001408 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001409 self._run_gerrit_upload_test(
1410 ['--squash'],
1411 description,
1412 [],
1413 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001414 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001415 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001416 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001417 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001418 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001419 'authenticate to Gerrit as yet-another@example.com.\n'
1420 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001421 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001422
Josipe827b0f2020-01-30 00:07:20 +00001423 def test_upload_change_description_editor(self):
1424 fetched_description = 'foo\n\nChange-Id: 123456789'
1425 description = 'bar\n\nChange-Id: 123456789'
1426 self._run_gerrit_upload_test(
1427 ['--squash', '--edit-description'],
1428 description,
1429 [],
1430 fetched_description=fetched_description,
1431 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001432 issue=123456,
1433 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001434 edit_description=description)
1435
Edward Lemurda4b6c62020-02-13 00:28:40 +00001436 @mock.patch('git_cl.RunGit')
1437 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001438 @mock.patch('sys.stdin', StringIO('\n'))
1439 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001440 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001441 def mock_run_git(*args, **_kwargs):
1442 if args[0] == ['for-each-ref',
1443 '--format=%(refname:short) %(upstream:short)',
1444 'refs/heads']:
1445 # Create a local branch dependency tree that looks like this:
1446 # test1 -> test2 -> test3 -> test4 -> test5
1447 # -> test3.1
1448 # test6 -> test0
1449 branch_deps = [
1450 'test2 test1', # test1 -> test2
1451 'test3 test2', # test2 -> test3
1452 'test3.1 test2', # test2 -> test3.1
1453 'test4 test3', # test3 -> test4
1454 'test5 test4', # test4 -> test5
1455 'test6 test0', # test0 -> test6
1456 'test7', # test7
1457 ]
1458 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001459 git_cl.RunGit.side_effect = mock_run_git
1460 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001461
1462 class MockChangelist():
1463 def __init__(self):
1464 pass
1465 def GetBranch(self):
1466 return 'test1'
1467 def GetIssue(self):
1468 return '123'
1469 def GetPatchset(self):
1470 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001471 def IsGerrit(self):
1472 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001473
1474 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1475 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001476 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001477 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001478 'This command will checkout all dependent branches '
1479 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001480 'or Ctrl+C to abort',
1481 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001482 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001483
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001484 def test_gerrit_change_id(self):
1485 self.calls = [
1486 ((['git', 'write-tree'], ),
1487 'hashtree'),
1488 ((['git', 'rev-parse', 'HEAD~0'], ),
1489 'branch-parent'),
1490 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1491 'A B <a@b.org> 1456848326 +0100'),
1492 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1493 'C D <c@d.org> 1456858326 +0100'),
1494 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1495 'hashchange'),
1496 ]
1497 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1498 self.assertEqual(change_id, 'Ihashchange')
1499
Edward Lesmes8170c292021-03-19 20:04:43 +00001500 @mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001501 @mock.patch('git_cl.Settings.GetBugPrefix')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001502 @mock.patch('git_cl.Changelist.FetchDescription')
1503 @mock.patch('git_cl.Changelist.GetBranch')
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001504 @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
Edward Lesmese1576912021-02-16 21:53:34 +00001505 @mock.patch('git_cl.Changelist.GetGerritHost')
1506 @mock.patch('git_cl.Changelist.GetGerritProject')
1507 @mock.patch('git_cl.Changelist.GetRemoteBranch')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001508 @mock.patch('owners_client.OwnersClient.BatchListOwners')
1509 def getDescriptionForUploadTest(
Edward Lesmese1576912021-02-16 21:53:34 +00001510 self, mockBatchListOwners=None, mockGetRemoteBranch=None,
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001511 mockGetGerritProject=None, mockGetGerritHost=None,
1512 mockGetCommonAncestorWithUpstream=None, mockGetBranch=None,
Edward Lesmese1576912021-02-16 21:53:34 +00001513 mockFetchDescription=None, mockGetBugPrefix=None,
Edward Lesmes8170c292021-03-19 20:04:43 +00001514 mockIsCodeOwnersEnabledOnHost=None,
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001515 initial_description='desc', bug=None, fixed=None, branch='branch',
1516 reviewers=None, tbrs=None, add_owners_to=None,
1517 expected_description='desc'):
1518 reviewers = reviewers or []
1519 tbrs = tbrs or []
1520 owners_by_path = {
1521 'a': ['a@example.com'],
1522 'b': ['b@example.com'],
1523 'c': ['c@example.com'],
1524 }
Edward Lesmes8170c292021-03-19 20:04:43 +00001525 mockIsCodeOwnersEnabledOnHost.return_value = True
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001526 mockGetBranch.return_value = branch
1527 mockGetBugPrefix.return_value = 'prefix'
Edward Lesmes1eaaab52021-03-02 23:52:54 +00001528 mockGetCommonAncestorWithUpstream.return_value = 'upstream'
Edward Lesmese1576912021-02-16 21:53:34 +00001529 mockGetRemoteBranch.return_value = ('origin', 'refs/remotes/origin/main')
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001530 mockFetchDescription.return_value = 'desc'
1531 mockBatchListOwners.side_effect = lambda ps: {
1532 p: owners_by_path.get(p)
1533 for p in ps
1534 }
1535
1536 cl = git_cl.Changelist(issue=1234)
Josip Sokcevic340edc32021-07-08 17:01:46 +00001537 actual = cl._GetDescriptionForUpload(options=mock.Mock(
1538 bug=bug,
1539 fixed=fixed,
1540 reviewers=reviewers,
1541 tbrs=tbrs,
1542 add_owners_to=add_owners_to,
1543 message=initial_description),
1544 git_diff_args=None,
1545 files=list(owners_by_path))
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001546 self.assertEqual(expected_description, actual.description)
1547
1548 def testGetDescriptionForUpload(self):
1549 self.getDescriptionForUploadTest()
1550
1551 def testGetDescriptionForUpload_Bug(self):
1552 self.getDescriptionForUploadTest(
1553 bug='1234',
1554 expected_description='\n'.join([
1555 'desc',
1556 '',
1557 'Bug: prefix:1234',
1558 ]))
1559
1560 def testGetDescriptionForUpload_Fixed(self):
1561 self.getDescriptionForUploadTest(
1562 fixed='1234',
1563 expected_description='\n'.join([
1564 'desc',
1565 '',
1566 'Fixed: prefix:1234',
1567 ]))
1568
Josip Sokcevic340edc32021-07-08 17:01:46 +00001569 @mock.patch('git_cl.Changelist.GetIssue')
1570 def testGetDescriptionForUpload_BugFromBranch(self, mockGetIssue):
1571 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001572 self.getDescriptionForUploadTest(
1573 branch='bug-1234',
1574 expected_description='\n'.join([
1575 'desc',
1576 '',
1577 'Bug: prefix:1234',
1578 ]))
1579
Josip Sokcevic340edc32021-07-08 17:01:46 +00001580 @mock.patch('git_cl.Changelist.GetIssue')
1581 def testGetDescriptionForUpload_FixedFromBranch(self, mockGetIssue):
1582 mockGetIssue.return_value = None
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001583 self.getDescriptionForUploadTest(
1584 branch='fix-1234',
1585 expected_description='\n'.join([
1586 'desc',
1587 '',
1588 'Fixed: prefix:1234',
1589 ]))
1590
Josip Sokcevic340edc32021-07-08 17:01:46 +00001591 def testGetDescriptionForUpload_SkipBugFromBranchIfAlreadyUploaded(self):
1592 self.getDescriptionForUploadTest(
1593 branch='bug-1234',
1594 expected_description='desc',
1595 )
1596
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001597 def testGetDescriptionForUpload_AddOwnersToR(self):
1598 self.getDescriptionForUploadTest(
1599 reviewers=['a@example.com'],
1600 tbrs=['b@example.com'],
1601 add_owners_to='R',
1602 expected_description='\n'.join([
1603 'desc',
1604 '',
1605 'R=a@example.com, c@example.com',
1606 'TBR=b@example.com',
1607 ]))
1608
1609 def testGetDescriptionForUpload_AddOwnersToTBR(self):
1610 self.getDescriptionForUploadTest(
1611 reviewers=['a@example.com'],
1612 tbrs=['b@example.com'],
1613 add_owners_to='TBR',
1614 expected_description='\n'.join([
1615 'desc',
1616 '',
1617 'R=a@example.com',
1618 'TBR=b@example.com, c@example.com',
1619 ]))
1620
1621 def testGetDescriptionForUpload_AddOwnersToNoOwnersNeeded(self):
1622 self.getDescriptionForUploadTest(
1623 reviewers=['a@example.com', 'c@example.com'],
1624 tbrs=['b@example.com'],
1625 add_owners_to='TBR',
1626 expected_description='\n'.join([
1627 'desc',
1628 '',
1629 'R=a@example.com, c@example.com',
1630 'TBR=b@example.com',
1631 ]))
1632
1633 def testGetDescriptionForUpload_Reviewers(self):
1634 self.getDescriptionForUploadTest(
1635 reviewers=['a@example.com', 'b@example.com'],
1636 expected_description='\n'.join([
1637 'desc',
1638 '',
1639 'R=a@example.com, b@example.com',
1640 ]))
1641
1642 def testGetDescriptionForUpload_TBRs(self):
1643 self.getDescriptionForUploadTest(
1644 tbrs=['a@example.com', 'b@example.com'],
1645 expected_description='\n'.join([
1646 'desc',
1647 '',
1648 'TBR=a@example.com, b@example.com',
1649 ]))
1650
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001651 def test_desecription_append_footer(self):
1652 for init_desc, footer_line, expected_desc in [
1653 # Use unique desc first lines for easy test failure identification.
1654 ('foo', 'R=one', 'foo\n\nR=one'),
1655 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1656 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1657 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1658 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1659 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1660 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1661 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1662 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1663 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1664 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1665 ]:
1666 desc = git_cl.ChangeDescription(init_desc)
1667 desc.append_footer(footer_line)
1668 self.assertEqual(desc.description, expected_desc)
1669
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001670 def test_update_reviewers(self):
1671 data = [
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001672 ('foo', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001673 'foo'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001674 ('foo\nR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001675 'foo\nR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001676 ('foo\nTBR=xx', [], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001677 'foo\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001678 ('foo', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001679 'foo\n\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001680 ('foo\nR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001681 'foo\n\nR=a@c, xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001682 ('foo\nTBR=xx', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001683 'foo\n\nR=a@c\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001684 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001685 'foo\n\nR=a@c, yy\nTBR=xx'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001686 ('foo\nBUG=', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001687 'foo\nBUG=\nR=a@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001688 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001689 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001690 ('foo', ['a@c', 'b@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001691 'foo\n\nR=a@c, b@c'),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001692 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001693 'foo\nBar\n\nR=c@c\nBUG='),
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001694 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001695 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001696 # Same as the line before, but full of whitespaces.
1697 (
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001698 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001699 'foo\nBar\n\nR=c@c\n BUG =',
1700 ),
1701 # Whitespaces aren't interpreted as new lines.
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001702 ('foo BUG=allo R=joe ', ['c@c'], [],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001703 'foo BUG=allo R=joe\n\nR=c@c'),
1704 # Redundant TBRs get promoted to Rs
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001705 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001706 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001707 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001708 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001709 actual = []
Stephen Martinis1c3c9392021-01-07 02:42:33 +00001710 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001711 obj = git_cl.ChangeDescription(orig)
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00001712 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001713 actual.append(obj.description)
1714 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001715
Nodir Turakulov23b82142017-11-16 11:04:25 -08001716 def test_get_hash_tags(self):
1717 cases = [
1718 ('', []),
1719 ('a', []),
1720 ('[a]', ['a']),
1721 ('[aa]', ['aa']),
1722 ('[a ]', ['a']),
1723 ('[a- ]', ['a']),
1724 ('[a- b]', ['a-b']),
1725 ('[a--b]', ['a-b']),
1726 ('[a', []),
1727 ('[a]x', ['a']),
1728 ('[aa]x', ['aa']),
1729 ('[a b]', ['a-b']),
1730 ('[a b]', ['a-b']),
1731 ('[a__b]', ['a-b']),
1732 ('[a] x', ['a']),
1733 ('[a][b]', ['a', 'b']),
1734 ('[a] [b]', ['a', 'b']),
1735 ('[a][b]x', ['a', 'b']),
1736 ('[a][b] x', ['a', 'b']),
1737 ('[a]\n[b]', ['a']),
1738 ('[a\nb]', []),
1739 ('[a][', ['a']),
1740 ('Revert "[a] feature"', ['a']),
1741 ('Reland "[a] feature"', ['a']),
1742 ('Revert: [a] feature', ['a']),
1743 ('Reland: [a] feature', ['a']),
1744 ('Revert "Reland: [a] feature"', ['a']),
1745 ('Foo: feature', ['foo']),
1746 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001747 ('Change Foo::Bar', []),
1748 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001749 ('Revert "Foo bar: feature"', ['foo-bar']),
1750 ('Reland "Foo bar: feature"', ['foo-bar']),
1751 ]
1752 for desc, expected in cases:
1753 change_desc = git_cl.ChangeDescription(desc)
1754 actual = change_desc.get_hash_tags()
1755 self.assertEqual(
1756 actual,
1757 expected,
1758 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1759
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001760 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'main'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001761 self.assertEqual(None, git_cl.GetTargetRef(None,
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001762 'refs/remotes/origin/main',
1763 'main'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001764
wittman@chromium.org455dc922015-01-26 20:15:50 +00001765 # Check default target refs for branches.
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001766 self.assertEqual('refs/heads/main',
1767 git_cl.GetTargetRef('origin', 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001768 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001769 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001770 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001771 None))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001772 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001773 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001774 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001775 self.assertEqual('refs/branch-heads/123',
1776 git_cl.GetTargetRef('origin',
1777 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001778 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001779 self.assertEqual('refs/diff/test',
1780 git_cl.GetTargetRef('origin',
1781 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001782 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001783 self.assertEqual('refs/heads/chrome/m42',
1784 git_cl.GetTargetRef('origin',
1785 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001786 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001787
1788 # Check target refs for user-specified target branch.
1789 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1790 'refs/remotes/branch-heads/123'):
1791 self.assertEqual('refs/branch-heads/123',
1792 git_cl.GetTargetRef('origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001793 'refs/remotes/origin/main',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001794 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001795 for branch in ('origin/main', 'remotes/origin/main',
1796 'refs/remotes/origin/main'):
1797 self.assertEqual('refs/heads/main',
wittman@chromium.org455dc922015-01-26 20:15:50 +00001798 git_cl.GetTargetRef('origin',
1799 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001800 branch))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001801 for branch in ('main', 'heads/main', 'refs/heads/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))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001806
Edward Lemurda4b6c62020-02-13 00:28:40 +00001807 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1808 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001809 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001810 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1811
Edward Lemur85153282020-02-14 22:06:29 +00001812 def assertIssueAndPatchset(
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001813 self, branch='main', issue='123456', patchset='7',
Edward Lemur85153282020-02-14 22:06:29 +00001814 git_short_host='chromium'):
1815 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001816 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001817 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001818 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001819 self.assertEqual(
1820 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001821 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001822
Edward Lemur85153282020-02-14 22:06:29 +00001823 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001824 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001825 self.mockGit.config['remote.origin.url'] = (
1826 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001827 gerrit_util.GetChangeDetail.return_value = {
1828 'current_revision': '7777777777',
1829 'revisions': {
1830 '1111111111': {
1831 '_number': 1,
1832 'fetch': {'http': {
1833 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1834 'ref': 'refs/changes/56/123456/1',
1835 }},
1836 },
1837 '7777777777': {
1838 '_number': 7,
1839 'fetch': {'http': {
1840 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1841 'ref': 'refs/changes/56/123456/7',
1842 }},
1843 },
1844 },
1845 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001846
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001847 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001848 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001849 self.calls += [
1850 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1851 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001852 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001853 ]
1854 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001855 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001856
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001857 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001858 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001859 self.calls += [
1860 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1861 'refs/changes/56/123456/7'],), ''),
1862 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001863 ]
Edward Lemur85153282020-02-14 22:06:29 +00001864 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1865 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001866
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001867 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001868 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001869 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001870 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001871 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001872 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001873 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001874 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001875 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001876
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001877 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001878 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001879 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001880 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001881 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001882 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001883 ]
1884 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001885 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001886 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001887
Aaron Gable697a91b2018-01-19 15:20:15 -08001888 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001889 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001890 self.calls += [
1891 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1892 'refs/changes/56/123456/1'],), ''),
1893 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001894 ]
1895 self.assertEqual(git_cl.main(
1896 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1897 0)
Edward Lemur85153282020-02-14 22:06:29 +00001898 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001899
Edward Lemurd55c5072020-02-20 01:09:07 +00001900 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001901 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001902 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001903 self.calls += [
1904 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001905 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001906 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001907 ]
1908 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001909 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001910 self.assertEqual(
1911 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1912 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001913
Edward Lemurda4b6c62020-02-13 00:28:40 +00001914 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001915 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001916 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001917 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001918 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001919 self.mockGit.config['remote.origin.url'] = (
1920 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001921 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001922 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001923 self.assertEqual(
1924 'change 123456 at https://chromium-review.googlesource.com does not '
1925 'exist or you have no access to it\n',
1926 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001927
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001928 def _checkout_calls(self):
1929 return [
1930 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001931 'branch\\..*\\.gerritissue'], ),
1932 ('branch.ger-branch.gerritissue 123456\n'
1933 'branch.gbranch654.gerritissue 654321\n')),
1934 ]
1935
1936 def test_checkout_gerrit(self):
1937 """Tests git cl checkout <issue>."""
1938 self.calls = self._checkout_calls()
1939 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1940 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1941
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001942 def test_checkout_not_found(self):
1943 """Tests git cl checkout <issue>."""
1944 self.calls = self._checkout_calls()
1945 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1946
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001947 def test_checkout_no_branch_issues(self):
1948 """Tests git cl checkout <issue>."""
1949 self.calls = [
1950 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001951 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001952 ]
1953 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1954
Edward Lemur26964072020-02-19 19:18:51 +00001955 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001956 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001957 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001958 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001959 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1960 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001961 self.mockGit.config['remote.origin.url'] = (
1962 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001963 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00001964 cl.branch = 'main'
1965 cl.branchref = 'refs/heads/main'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001966 return cl
1967
Edward Lemurd55c5072020-02-20 01:09:07 +00001968 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001969 def test_gerrit_ensure_authenticated_missing(self):
1970 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001971 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001972 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001973 with self.assertRaises(SystemExitMock):
1974 cl.EnsureAuthenticated(force=False)
1975 self.assertEqual(
1976 'Credentials for the following hosts are required:\n'
1977 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001978 'These are read from ~%(sep)s.gitcookies '
1979 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001980 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001981 'https://chromium-review.googlesource.com/new-password\n' % {
1982 'sep': os.sep,
1983 'netrc': NETRC_FILENAME,
1984 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001985
1986 def test_gerrit_ensure_authenticated_conflict(self):
1987 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001988 'chromium.googlesource.com':
1989 ('git-one.example.com', None, 'secret1'),
1990 'chromium-review.googlesource.com':
1991 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001992 })
1993 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001994 (('ask_for_data', 'If you know what you are doing '
1995 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001996 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1997
1998 def test_gerrit_ensure_authenticated_ok(self):
1999 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002000 'chromium.googlesource.com':
2001 ('git-same.example.com', None, 'secret'),
2002 'chromium-review.googlesource.com':
2003 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002004 })
2005 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2006
tandrii@chromium.org28253532016-04-14 13:46:56 +00002007 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00002008 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
2009 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00002010 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2011
Eric Boren2fb63102018-10-05 13:05:03 +00002012 def test_gerrit_ensure_authenticated_bearer_token(self):
2013 cl = self._test_gerrit_ensure_authenticated_common(auth={
2014 'chromium.googlesource.com':
2015 ('', None, 'secret'),
2016 'chromium-review.googlesource.com':
2017 ('', None, 'secret'),
2018 })
2019 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2020 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2021 'chromium.googlesource.com')
2022 self.assertTrue('Bearer' in header)
2023
Daniel Chengcf6269b2019-05-18 01:02:12 +00002024 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00002025 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002026 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002027 (('logging.warning',
2028 'Ignoring branch %(branch)s with non-https remote '
2029 '%(remote)s', {
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002030 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002031 'remote': 'custom-scheme://repo'}
2032 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00002033 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002034 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2035 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2036 mock.patch('logging.warning',
2037 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002038 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002039 cl.branch = 'main'
2040 cl.branchref = 'refs/heads/main'
Daniel Chengcf6269b2019-05-18 01:02:12 +00002041 cl.lookedup_issue = True
2042 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2043
Florian Mayerae510e82020-01-30 21:04:48 +00002044 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00002045 self.mockGit.config['remote.origin.url'] = (
2046 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00002047 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002048 (('logging.error',
2049 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2050 'but it doesn\'t exist.', {
2051 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002052 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002053 'url': 'git@somehost.example:foo/bar.git'}
2054 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00002055 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00002056 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2057 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
2058 mock.patch('logging.error',
2059 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00002060 cl = git_cl.Changelist()
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002061 cl.branch = 'main'
2062 cl.branchref = 'refs/heads/main'
Florian Mayerae510e82020-01-30 21:04:48 +00002063 cl.lookedup_issue = True
2064 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2065
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002066 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002067 self.mockGit.config['branch.main.gerritissue'] = '123'
2068 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002069 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00002070 self.mockGit.config['remote.origin.url'] = (
2071 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002072 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00002073 (('SetReview', 'chromium-review.googlesource.com',
2074 'infra%2Finfra~123', None,
2075 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002076 ]
tandriid9e5ce52016-07-13 02:32:59 -07002077
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002078 def _cmd_set_quick_run_gerrit(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002079 self.mockGit.config['branch.main.gerritissue'] = '123'
2080 self.mockGit.config['branch.main.gerritserver'] = (
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002081 'https://chromium-review.googlesource.com')
2082 self.mockGit.config['remote.origin.url'] = (
2083 'https://chromium.googlesource.com/infra/infra')
2084 self.calls = [
2085 (('SetReview', 'chromium-review.googlesource.com',
2086 'infra%2Finfra~123', None,
2087 {'Commit-Queue': 1, 'Quick-Run': 1}, None, None), ''),
2088 ]
2089
tandriid9e5ce52016-07-13 02:32:59 -07002090 def test_cmd_set_commit_gerrit_clear(self):
2091 self._cmd_set_commit_gerrit_common(0)
2092 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2093
2094 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002095 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002096 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2097
tandriid9e5ce52016-07-13 02:32:59 -07002098 def test_cmd_set_commit_gerrit(self):
2099 self._cmd_set_commit_gerrit_common(2)
2100 self.assertEqual(0, git_cl.main(['set-commit']))
2101
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00002102 def test_cmd_set_quick_run_gerrit(self):
2103 self._cmd_set_quick_run_gerrit()
2104 self.assertEqual(0, git_cl.main(['set-commit', '-q']))
2105
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002106 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002107 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002108 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002109
2110 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002111 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002112
Edward Lemurda4b6c62020-02-13 00:28:40 +00002113 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07002114 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07002115 try:
2116 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00002117 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00002118 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00002119 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07002120
2121 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07002122 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002123 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002124 return 'foobar'
2125
Edward Lemurda4b6c62020-02-13 00:28:40 +00002126 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07002127 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002128 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002129 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002130 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002131
iannuccie53c9352016-08-17 14:40:40 -07002132 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002133
iannuccie53c9352016-08-17 14:40:40 -07002134 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002135 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002136 return 'foobar'
2137
Edward Lemurda4b6c62020-02-13 00:28:40 +00002138 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2139 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002140 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002141 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002142
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002143 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002144 self.mockGit.config['remote.origin.url'] = (
2145 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002146 gerrit_util.GetChangeDetail.return_value = {
2147 'current_revision': 'sha1',
2148 'revisions': {'sha1': {
2149 'commit': {'message': 'foobar'},
2150 }},
2151 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002152 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002153 'description',
2154 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2155 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002156 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002157
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002158 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002159 mock.patch('git_cl.Changelist', ChangelistMock).start()
2160 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002161
2162 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2163 self.assertEqual('hihi', ChangelistMock.desc)
2164
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002165 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002166 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002167
2168 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002169 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002170 '# Enter a description of the change.\n'
2171 '# This will be displayed on the codereview site.\n'
2172 '# The first line will also be used as the subject of the review.\n'
2173 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002174 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002175 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002176 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002177 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002178 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002179
Edward Lemur6c6827c2020-02-06 21:15:18 +00002180 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002181 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002182
Edward Lemurda4b6c62020-02-13 00:28:40 +00002183 mock.patch('git_cl.Changelist.FetchDescription',
2184 lambda *args: current_desc).start()
2185 mock.patch('git_cl.Changelist.UpdateDescription',
2186 UpdateDescription).start()
2187 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002188
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002189 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002190 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002191
Dan Beamd8b04ca2019-10-10 21:23:26 +00002192 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2193 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2194
2195 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002196 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002197 '# Enter a description of the change.\n'
2198 '# This will be displayed on the codereview site.\n'
2199 '# The first line will also be used as the subject of the review.\n'
2200 '#--------------------This line is 72 characters long'
2201 '--------------------\n'
2202 'Some.\n\nFixed: 123\nChange-Id: xxx',
2203 desc)
2204 return desc
2205
Edward Lemurda4b6c62020-02-13 00:28:40 +00002206 mock.patch('git_cl.Changelist.FetchDescription',
2207 lambda *args: current_desc).start()
2208 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002209
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002210 self.mockGit.config['branch.main.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002211 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002212
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002213 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002214 mock.patch('git_cl.Changelist', ChangelistMock).start()
2215 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002216
2217 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2218 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2219
kmarshall3bff56b2016-06-06 18:31:47 -07002220 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002221 self.calls = [
2222 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002223 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002224 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002225 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002226 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002227 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002228
Edward Lemurda4b6c62020-02-13 00:28:40 +00002229 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002230 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002231 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002232 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002233 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002234
2235 self.assertEqual(0, git_cl.main(['archive', '-f']))
2236
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002237 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002238 self.calls = [
2239 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002240 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002241 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2242 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002243 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2244 ((['git', 'branch', '-D', 'foo'],), '')
2245 ]
2246
Edward Lemurda4b6c62020-02-13 00:28:40 +00002247 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002248 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002249 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002250 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002251 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002252
2253 self.assertEqual(0, git_cl.main(['archive', '-f']))
2254
kmarshall3bff56b2016-06-06 18:31:47 -07002255 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002256 self.calls = [
2257 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002258 'refs/heads/main'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002259 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002260 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002261
Edward Lemurda4b6c62020-02-13 00:28:40 +00002262 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002263 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002264 [(MockChangelistWithBranchAndIssue('main', 1),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002265 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002266
2267 self.assertEqual(1, git_cl.main(['archive', '-f']))
2268
2269 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002270 self.calls = [
2271 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002272 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002273 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002274 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002275
Edward Lemurda4b6c62020-02-13 00:28:40 +00002276 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002277 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002278 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002279 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002280 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002281
kmarshall9249e012016-08-23 12:02:16 -07002282 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2283
2284 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002285 self.calls = [
2286 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002287 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002288 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002289 ((['git', 'branch', '-D', 'foo'],), '')
2290 ]
kmarshall9249e012016-08-23 12:02:16 -07002291
Edward Lemurda4b6c62020-02-13 00:28:40 +00002292 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002293 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002294 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
kmarshall9249e012016-08-23 12:02:16 -07002295 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002296 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002297
2298 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002299
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002300 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002301 self.calls = [
2302 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002303 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002304 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002305 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2306 'refs/tags/git-cl-archived-456-foo'),
2307 ((['git', 'branch', '-D', 'foo'],), CERR1),
2308 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2309 'refs/tags/git-cl-archived-456-foo'),
2310 ]
2311
Edward Lemurda4b6c62020-02-13 00:28:40 +00002312 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002313 lambda branches, fine_grained, max_processes:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002314 [(MockChangelistWithBranchAndIssue('main', 1), 'open'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002315 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002316 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002317
2318 self.assertEqual(0, git_cl.main(['archive', '-f']))
2319
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002320 def test_archive_with_format(self):
2321 self.calls = [
2322 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002323 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002324 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2325 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2326 ((['git', 'branch', '-D', 'foo'], ), ''),
2327 ]
2328
2329 mock.patch('git_cl.get_cl_statuses',
2330 lambda branches, fine_grained, max_processes:
2331 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2332
2333 self.assertEqual(
2334 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2335
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002336 def test_cmd_issue_erase_existing(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002337 self.mockGit.config['branch.main.gerritissue'] = '123'
2338 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002339 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002340 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002341 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002342 ]
2343 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002344 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2345 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002346
Aaron Gable400e9892017-07-12 15:31:21 -07002347 def test_cmd_issue_erase_existing_with_change_id(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002348 self.mockGit.config['branch.main.gerritissue'] = '123'
2349 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002350 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002351 mock.patch('git_cl.Changelist.FetchDescription',
2352 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002353 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002354 ((['git', 'log', '-1', '--format=%B'],),
2355 'This is a description\n\nChange-Id: Ideadbeef'),
2356 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002357 ]
2358 self.assertEqual(0, git_cl.main(['issue', '0']))
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002359 self.assertNotIn('branch.main.gerritissue', self.mockGit.config)
2360 self.assertNotIn('branch.main.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002361
phajdan.jre328cf92016-08-22 04:12:17 -07002362 def test_cmd_issue_json(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002363 self.mockGit.config['branch.main.gerritissue'] = '123'
2364 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002365 'https://chromium-review.googlesource.com')
Nodir Turakulov27379632021-03-17 18:53:29 +00002366 self.mockGit.config['remote.origin.url'] = (
2367 'https://chromium.googlesource.com/chromium/src'
2368 )
2369 self.calls = [(
2370 (
2371 'write_json',
2372 'output.json',
2373 {
2374 'issue': 123,
2375 'issue_url': 'https://chromium-review.googlesource.com/123',
2376 'gerrit_host': 'chromium-review.googlesource.com',
2377 'gerrit_project': 'chromium/src',
2378 },
2379 ),
2380 '',
2381 )]
phajdan.jre328cf92016-08-22 04:12:17 -07002382 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2383
tandrii16e0b4e2016-06-07 10:34:28 -07002384 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002385 mock.patch(
2386 'git_cl.os.path.abspath',
2387 lambda path: self._mocked_call(['abspath', path])).start()
2388 mock.patch(
2389 'git_cl.os.path.exists',
2390 lambda path: self._mocked_call(['exists', path])).start()
2391 mock.patch(
2392 'git_cl.gclient_utils.FileRead',
2393 lambda path: self._mocked_call(['FileRead', path])).start()
2394 mock.patch(
2395 'git_cl.gclient_utils.rm_file_or_tree',
2396 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002397 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002398 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002399 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002400 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002401
2402 def test_GerritCommitMsgHookCheck_custom_hook(self):
2403 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002404 self.calls += [((['exists',
2405 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2406 ((['FileRead',
2407 os.path.join('.git', 'hooks', 'commit-msg')], ),
2408 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002409 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002410
2411 def test_GerritCommitMsgHookCheck_not_exists(self):
2412 cl = self._common_GerritCommitMsgHookCheck()
2413 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002414 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002415 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002416 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002417
2418 def test_GerritCommitMsgHookCheck(self):
2419 cl = self._common_GerritCommitMsgHookCheck()
2420 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002421 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2422 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002423 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002424 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002425 ((['rm_file_or_tree',
2426 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002427 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002428 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002429
tandriic4344b52016-08-29 06:04:54 -07002430 def test_GerritCmdLand(self):
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002431 self.mockGit.config['branch.main.gerritsquashhash'] = 'deadbeaf'
2432 self.mockGit.config['branch.main.gerritserver'] = (
Edward Lemur85153282020-02-14 22:06:29 +00002433 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002434 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002435 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002436 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002437 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002438 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002439 'labels': {},
2440 'current_revision': 'deadbeaf',
2441 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002442 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002443 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002444 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002445 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2446 }
Xinan Lin1bd4ffa2021-07-28 00:54:22 +00002447 cl.SubmitIssue = lambda: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002448 self.assertEqual(0, cl.CMDLand(force=True,
2449 bypass_hooks=True,
2450 verbose=True,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00002451 parallel=False,
2452 resultdb=False,
2453 realm=None))
Edward Lemur73c76702020-02-06 23:57:18 +00002454 self.assertIn(
2455 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002456 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002457 self.assertIn(
2458 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002459 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002460
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002461 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lesmeseeca9c62020-11-20 00:00:17 +00002462 mock.patch('git_cl.Changelist.GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002463
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002464 def test_gerrit_change_detail_cache_simple(self):
2465 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002466 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002467 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002468 cl1._cached_remote_url = (
2469 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002470 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002471 cl2._cached_remote_url = (
2472 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002473 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2474 self.assertEqual(cl1._GetChangeDetail(), 'a')
2475 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002476
2477 def test_gerrit_change_detail_cache_options(self):
2478 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002479 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002480 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002481 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002482 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2483 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2484 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2485 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2486 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2487 self.assertEqual(cl._GetChangeDetail(), 'cab')
2488
2489 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2490 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2491 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2492 self.assertEqual(cl._GetChangeDetail(), 'cab')
2493
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002494 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002495 gerrit_util.GetChangeDetail.return_value = {
2496 'current_revision': 'rev1',
2497 'revisions': {
2498 'rev1': {'commit': {'message': 'desc1'}},
2499 },
2500 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002501
2502 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002503 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002504 cl._cached_remote_url = (
2505 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002506 self.assertEqual(cl.FetchDescription(), 'desc1')
2507 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002508
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002509 def test_print_current_creds(self):
2510 class CookiesAuthenticatorMock(object):
2511 def __init__(self):
2512 self.gitcookies = {
2513 'host.googlesource.com': ('user', 'pass'),
2514 'host-review.googlesource.com': ('user', 'pass'),
2515 }
2516 self.netrc = self
2517 self.netrc.hosts = {
2518 'github.com': ('user2', None, 'pass2'),
2519 'host2.googlesource.com': ('user3', None, 'pass'),
2520 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002521 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2522 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002523 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2524 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2525 ' Host\t User\t Which file',
2526 '============================\t=====\t===========',
2527 'host-review.googlesource.com\t user\t.gitcookies',
2528 ' host.googlesource.com\t user\t.gitcookies',
2529 ' host2.googlesource.com\tuser3\t .netrc',
2530 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002531 sys.stdout.seek(0)
2532 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002533 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2534 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2535 ' Host\tUser\t Which file',
2536 '============================\t====\t===========',
2537 'host-review.googlesource.com\tuser\t.gitcookies',
2538 ' host.googlesource.com\tuser\t.gitcookies',
2539 ])
2540
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002541 def _common_creds_check_mocks(self):
2542 def exists_mock(path):
2543 dirname = os.path.dirname(path)
2544 if dirname == os.path.expanduser('~'):
2545 dirname = '~'
2546 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002547 if base in (NETRC_FILENAME, '.gitcookies'):
2548 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002549 # git cl also checks for existence other files not relevant to this test.
2550 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002551 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002552 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002553 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002554 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002555
2556 def test_creds_check_gitcookies_not_configured(self):
2557 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002558 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2559 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002560 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002561 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2562 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2563 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2564 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2565 'or Ctrl+C to abort'), ''),
2566 (([
2567 'git', 'config', '--global', 'http.cookiefile',
2568 os.path.expanduser(os.path.join('~', '.gitcookies'))
2569 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002570 ]
2571 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002572 self.assertTrue(
2573 sys.stdout.getvalue().startswith(
2574 'You seem to be using outdated .netrc for git credentials:'))
2575 self.assertIn(
2576 '\nConfigured git to use .gitcookies from',
2577 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002578
2579 def test_creds_check_gitcookies_configured_custom_broken(self):
2580 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002581 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2582 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002583 custom_cookie_path = ('C:\\.gitcookies'
2584 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002585 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002586 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2587 ((['git', 'config', '--global', 'http.cookiefile'], ),
2588 custom_cookie_path),
2589 (('os.path.exists', custom_cookie_path), False),
2590 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2591 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2592 (([
2593 'git', 'config', '--global', 'http.cookiefile',
2594 os.path.expanduser(os.path.join('~', '.gitcookies'))
2595 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002596 ]
2597 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002598 self.assertIn(
2599 'WARNING: You have configured custom path to .gitcookies: ',
2600 sys.stdout.getvalue())
2601 self.assertIn(
2602 'However, your configured .gitcookies file is missing.',
2603 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002604
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002605 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002606 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002607 self.mockGit.config['remote.origin.url'] = (
2608 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002609 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002610 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002611 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002612 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002613 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002614 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002615
Edward Lemurda4b6c62020-02-13 00:28:40 +00002616 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2617 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002618 self.mockGit.config['remote.origin.url'] = (
2619 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002620 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002621 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002622 'current_revision': 'ba5eba11',
2623 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002624 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002625 '_number': 1,
2626 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002627 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002628 '_number': 2,
2629 },
2630 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002631 'messages': [
2632 {
2633 u'_revision_number': 1,
2634 u'author': {
2635 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002636 u'email': u'could-be-anything@example.com',
2637 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002638 },
2639 u'date': u'2017-03-15 20:08:45.000000000',
2640 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002641 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov899785a2021-07-09 12:45:37 +00002642 u'tag': u'autogenerated:cv:dry-run'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002643 },
2644 {
2645 u'_revision_number': 2,
2646 u'author': {
2647 u'_account_id': 11151243,
2648 u'email': u'owner@example.com',
2649 u'name': u'owner'
2650 },
2651 u'date': u'2017-03-16 20:00:41.000000000',
2652 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2653 u'message': u'PTAL',
2654 },
2655 {
2656 u'_revision_number': 2,
2657 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002658 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002659 u'email': u'reviewer@example.com',
2660 u'name': u'reviewer'
2661 },
2662 u'date': u'2017-03-17 05:19:37.500000000',
2663 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2664 u'message': u'Patch Set 2: Code-Review+1',
2665 },
2666 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002667 }
2668 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002669 (('GetChangeComments', 'chromium-review.googlesource.com',
2670 'infra%2Finfra~1'), {
2671 '/COMMIT_MSG': [
2672 {
2673 'author': {
2674 'email': u'reviewer@example.com'
2675 },
2676 'updated': u'2017-03-17 05:19:37.500000000',
2677 'patch_set': 2,
2678 'side': 'REVISION',
2679 'message': 'Please include a bug link',
2680 },
2681 ],
2682 'codereview.settings': [
2683 {
2684 'author': {
2685 'email': u'owner@example.com'
2686 },
2687 'updated': u'2017-03-16 20:00:41.000000000',
2688 'patch_set': 2,
2689 'side': 'PARENT',
2690 'line': 42,
2691 'message': 'I removed this because it is bad',
2692 },
2693 ]
2694 }),
2695 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2696 'infra%2Finfra~1'), {}),
2697 ] * 2 + [(('write_json', 'output.json', [{
2698 u'date':
2699 u'2017-03-16 20:00:41.000000',
2700 u'message': (u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2701 u' Base, Line 42: https://crrev.com/c/1/2/'
2702 u'codereview.settings#b42\n' +
2703 u' I removed this because it is bad\n'),
2704 u'autogenerated':
2705 False,
2706 u'approval':
2707 False,
2708 u'disapproval':
2709 False,
2710 u'sender':
2711 u'owner@example.com'
2712 }, {
2713 u'date':
2714 u'2017-03-17 05:19:37.500000',
2715 u'message':
2716 (u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2717 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
2718 u' Please include a bug link\n'),
2719 u'autogenerated':
2720 False,
2721 u'approval':
2722 False,
2723 u'disapproval':
2724 False,
2725 u'sender':
2726 u'reviewer@example.com'
2727 }]), '')]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002728 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002729 git_cl._CommentSummary(
2730 message=(u'PTAL\n' + u'\n' + u'codereview.settings\n' +
2731 u' Base, Line 42: https://crrev.com/c/1/2/' +
2732 u'codereview.settings#b42\n' +
2733 u' I removed this because it is bad\n'),
2734 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
2735 autogenerated=False,
2736 disapproval=False,
2737 approval=False,
2738 sender=u'owner@example.com'),
2739 git_cl._CommentSummary(message=(
2740 u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
2741 u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002742 u' Please include a bug link\n'),
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002743 date=datetime.datetime(2017, 3, 17, 5, 19, 37,
2744 500000),
2745 autogenerated=False,
2746 disapproval=False,
2747 approval=False,
2748 sender=u'reviewer@example.com'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002749 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002750 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002751 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002752 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002753 self.assertEqual(
2754 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2755
2756 def test_git_cl_comments_robot_comments(self):
2757 # git cl comments also fetches robot comments (which are considered a type
2758 # of autogenerated comment), and unlike other types of comments, only robot
2759 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002760 self.mockGit.config['remote.origin.url'] = (
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002761 'https://x.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002762 gerrit_util.GetChangeDetail.return_value = {
2763 'owner': {'email': 'owner@example.com'},
2764 'current_revision': 'ba5eba11',
2765 'revisions': {
2766 'deadbeaf': {
2767 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002768 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002769 'ba5eba11': {
2770 '_number': 2,
2771 },
2772 },
2773 'messages': [
2774 {
2775 u'_revision_number': 1,
2776 u'author': {
2777 u'_account_id': 1111084,
2778 u'email': u'commit-bot@chromium.org',
2779 u'name': u'Commit Bot'
2780 },
2781 u'date': u'2017-03-15 20:08:45.000000000',
2782 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2783 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2784 u'tag': u'autogenerated:cq:dry-run'
2785 },
2786 {
2787 u'_revision_number': 1,
2788 u'author': {
2789 u'_account_id': 123,
2790 u'email': u'tricium@serviceaccount.com',
2791 u'name': u'Tricium'
2792 },
2793 u'date': u'2017-03-16 20:00:41.000000000',
2794 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2795 u'message': u'(1 comment)',
2796 u'tag': u'autogenerated:tricium',
2797 },
2798 {
2799 u'_revision_number': 1,
2800 u'author': {
2801 u'_account_id': 123,
2802 u'email': u'tricium@serviceaccount.com',
2803 u'name': u'Tricium'
2804 },
2805 u'date': u'2017-03-16 20:00:41.000000000',
2806 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2807 u'message': u'(1 comment)',
2808 u'tag': u'autogenerated:tricium',
2809 },
2810 {
2811 u'_revision_number': 2,
2812 u'author': {
2813 u'_account_id': 123,
2814 u'email': u'tricium@serviceaccount.com',
2815 u'name': u'reviewer'
2816 },
2817 u'date': u'2017-03-17 05:30:37.000000000',
2818 u'tag': u'autogenerated:tricium',
2819 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2820 u'message': u'(1 comment)',
2821 },
2822 ]
2823 }
2824 self.calls = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002825 (('GetChangeComments', 'x-review.googlesource.com', 'infra%2Finfra~1'),
2826 {}),
2827 (('GetChangeRobotComments', 'x-review.googlesource.com',
2828 'infra%2Finfra~1'), {
2829 'codereview.settings': [
2830 {
2831 u'author': {
2832 u'email': u'tricium@serviceaccount.com'
2833 },
2834 u'updated': u'2017-03-17 05:30:37.000000000',
2835 u'robot_run_id': u'5565031076855808',
2836 u'robot_id': u'Linter/Category',
2837 u'tag': u'autogenerated:tricium',
2838 u'patch_set': 2,
2839 u'side': u'REVISION',
2840 u'message': u'Linter warning message text',
2841 u'line': 32,
2842 },
2843 ],
2844 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002845 ]
2846 expected_comments_summary = [
Andrii Shyshkalova3762a92020-11-25 10:20:42 +00002847 git_cl._CommentSummary(
2848 date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2849 message=(u'(1 comment)\n\ncodereview.settings\n'
2850 u' PS2, Line 32: https://x-review.googlesource.com/c/1/2/'
2851 u'codereview.settings#32\n'
2852 u' Linter warning message text\n'),
2853 sender=u'tricium@serviceaccount.com',
2854 autogenerated=True,
2855 approval=False,
2856 disapproval=False)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002857 ]
2858 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002859 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002860 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002861
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002862 def test_get_remote_url_with_mirror(self):
2863 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002864
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002865 def selective_os_path_isdir_mock(path):
2866 if path == '/cache/this-dir-exists':
2867 return self._mocked_call('os.path.isdir', path)
2868 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002869
Edward Lemurda4b6c62020-02-13 00:28:40 +00002870 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002871
2872 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002873 self.mockGit.config['remote.origin.url'] = (
2874 '/cache/this-dir-exists')
2875 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2876 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002877 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002878 (('os.path.isdir', '/cache/this-dir-exists'),
2879 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002880 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002881 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002882 self.assertEqual(cl.GetRemoteUrl(), url)
2883 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2884
Edward Lemur298f2cf2019-02-22 21:40:39 +00002885 def test_get_remote_url_non_existing_mirror(self):
2886 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002887
Edward Lemur298f2cf2019-02-22 21:40:39 +00002888 def selective_os_path_isdir_mock(path):
2889 if path == '/cache/this-dir-doesnt-exist':
2890 return self._mocked_call('os.path.isdir', path)
2891 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002892
Edward Lemurda4b6c62020-02-13 00:28:40 +00002893 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2894 mock.patch('logging.error',
2895 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002896
Edward Lemur26964072020-02-19 19:18:51 +00002897 self.mockGit.config['remote.origin.url'] = (
2898 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002899 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002900 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2901 False),
2902 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002903 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2904 'but it doesn\'t exist.', {
2905 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002906 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002907 'url': '/cache/this-dir-doesnt-exist'}
2908 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002909 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002910 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002911 self.assertIsNone(cl.GetRemoteUrl())
2912
2913 def test_get_remote_url_misconfigured_mirror(self):
2914 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002915
Edward Lemur298f2cf2019-02-22 21:40:39 +00002916 def selective_os_path_isdir_mock(path):
2917 if path == '/cache/this-dir-exists':
2918 return self._mocked_call('os.path.isdir', path)
2919 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002920
Edward Lemurda4b6c62020-02-13 00:28:40 +00002921 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2922 mock.patch('logging.error',
2923 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002924
Edward Lemur26964072020-02-19 19:18:51 +00002925 self.mockGit.config['remote.origin.url'] = (
2926 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002927 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002928 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002929 (('logging.error',
2930 'Remote "%(remote)s" for branch "%(branch)s" points to '
2931 '"%(cache_path)s", but it is misconfigured.\n'
2932 '"%(cache_path)s" must be a git repo and must have a remote named '
2933 '"%(remote)s" pointing to the git host.', {
2934 'remote': 'origin',
2935 'cache_path': '/cache/this-dir-exists',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002936 'branch': 'main'}
Edward Lemur298f2cf2019-02-22 21:40:39 +00002937 ), None),
2938 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002939 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002940 self.assertIsNone(cl.GetRemoteUrl())
2941
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002942 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002943 self.mockGit.config['remote.origin.url'] = (
2944 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002945 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002946 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2947
2948 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002949 mock.patch('logging.error',
2950 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002951
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002952 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002953 (('logging.error',
2954 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2955 'but it doesn\'t exist.', {
2956 'remote': 'origin',
Josip Sokcevic7e133ff2021-07-13 17:44:53 +00002957 'branch': 'main',
Josip906bfde2020-01-31 22:38:49 +00002958 'url': ''}
2959 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002960 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002961 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002962 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002963
Josip Sokcevicc39ab992020-09-24 20:09:15 +00002964 def test_gerrit_new_default(self):
2965 self._run_gerrit_upload_test(
2966 [],
2967 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
2968 [],
2969 squash=False,
2970 squash_mode='override_nosquash',
2971 change_id='I123456789',
Edward Lesmes8c43c3f2021-01-20 00:20:26 +00002972 default_branch='main')
Josip Sokcevicc39ab992020-09-24 20:09:15 +00002973
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002974
Edward Lemur9aa1a962020-02-25 00:58:38 +00002975class ChangelistTest(unittest.TestCase):
mlcui3da91712021-05-05 10:00:30 +00002976 LAST_COMMIT_SUBJECT = 'Fixes goat teleporter destination to be Australia'
2977
2978 def _mock_run_git(commands):
2979 if commands == ['show', '-s', '--format=%s', 'HEAD']:
2980 return ChangelistTest.LAST_COMMIT_SUBJECT
2981
Edward Lemur227d5102020-02-25 23:45:35 +00002982 def setUp(self):
2983 super(ChangelistTest, self).setUp()
2984 mock.patch('gclient_utils.FileRead').start()
2985 mock.patch('gclient_utils.FileWrite').start()
2986 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2987 mock.patch(
2988 'git_cl.Changelist.GetCodereviewServer',
2989 return_value='https://chromium-review.googlesource.com').start()
2990 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2991 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2992 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
Dirk Pranke6f0df682021-06-25 00:42:33 +00002993 mock.patch('git_cl.Changelist.GetUsePython3', return_value=False).start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00002994 mock.patch(
2995 'git_cl.Changelist.GetRemoteBranch',
2996 return_value=('origin', 'refs/remotes/origin/main')).start()
Edward Lemur227d5102020-02-25 23:45:35 +00002997 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2998 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2999 mock.patch('git_cl.time_time').start()
3000 mock.patch('metrics.collector').start()
3001 mock.patch('subprocess2.Popen').start()
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003002 mock.patch(
3003 'git_cl.Changelist.GetGerritProject', return_value='project').start()
Edward Lemur227d5102020-02-25 23:45:35 +00003004 self.addCleanup(mock.patch.stopall)
3005 self.temp_count = 0
3006
Edward Lemur227d5102020-02-25 23:45:35 +00003007 def testRunHook(self):
3008 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003009 'more_cc': ['cc@example.com', 'more@example.com'],
3010 'errors': [],
3011 'notifications': [],
3012 'warnings': [],
Edward Lemur227d5102020-02-25 23:45:35 +00003013 }
3014 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003015 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur227d5102020-02-25 23:45:35 +00003016 mockProcess = mock.Mock()
3017 mockProcess.wait.return_value = 0
3018 subprocess2.Popen.return_value = mockProcess
3019
3020 cl = git_cl.Changelist()
3021 results = cl.RunHook(
3022 committing=True,
3023 may_prompt=True,
3024 verbose=2,
3025 parallel=True,
3026 upstream='upstream',
3027 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003028 all_files=True,
3029 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003030
3031 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003032 subprocess2.Popen.assert_any_call([
Edward Lemur227d5102020-02-25 23:45:35 +00003033 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00003034 '--root', 'root',
3035 '--upstream', 'upstream',
3036 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00003037 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003038 '--gerrit_project', 'project',
3039 '--gerrit_branch', 'refs/heads/main',
3040 '--author', 'author',
Edward Lemur227d5102020-02-25 23:45:35 +00003041 '--issue', '123456',
3042 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00003043 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00003044 '--may_prompt',
3045 '--parallel',
3046 '--all_files',
3047 '--json_output', '/tmp/fake-temp2',
3048 '--description_file', '/tmp/fake-temp1',
3049 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003050 subprocess2.Popen.assert_any_call([
3051 'vpython3', 'PRESUBMIT_SUPPORT',
3052 '--root', 'root',
3053 '--upstream', 'upstream',
3054 '--verbose', '--verbose',
3055 '--gerrit_url', 'https://chromium-review.googlesource.com',
3056 '--gerrit_project', 'project',
3057 '--gerrit_branch', 'refs/heads/main',
3058 '--author', 'author',
3059 '--issue', '123456',
3060 '--patchset', '7',
3061 '--commit',
3062 '--may_prompt',
3063 '--parallel',
3064 '--all_files',
3065 '--json_output', '/tmp/fake-temp4',
3066 '--description_file', '/tmp/fake-temp3',
3067 ])
3068 gclient_utils.FileWrite.assert_any_call(
Edward Lemur1a83da12020-03-04 21:18:36 +00003069 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00003070 metrics.collector.add_repeated('sub_commands', {
3071 'command': 'presubmit',
3072 'execution_time': 100,
3073 'exit_code': 0,
3074 })
3075
Edward Lemur99df04e2020-03-05 19:39:43 +00003076 def testRunHook_FewerOptions(self):
3077 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003078 'more_cc': ['cc@example.com', 'more@example.com'],
3079 'errors': [],
3080 'notifications': [],
3081 'warnings': [],
Edward Lemur99df04e2020-03-05 19:39:43 +00003082 }
3083 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003084 git_cl.time_time.side_effect = [100, 200, 300, 400]
Edward Lemur99df04e2020-03-05 19:39:43 +00003085 mockProcess = mock.Mock()
3086 mockProcess.wait.return_value = 0
3087 subprocess2.Popen.return_value = mockProcess
3088
3089 git_cl.Changelist.GetAuthor.return_value = None
3090 git_cl.Changelist.GetIssue.return_value = None
3091 git_cl.Changelist.GetPatchset.return_value = None
Edward Lemur99df04e2020-03-05 19:39:43 +00003092
3093 cl = git_cl.Changelist()
3094 results = cl.RunHook(
3095 committing=False,
3096 may_prompt=False,
3097 verbose=0,
3098 parallel=False,
3099 upstream='upstream',
3100 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003101 all_files=False,
3102 resultdb=False)
Edward Lemur99df04e2020-03-05 19:39:43 +00003103
3104 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003105 subprocess2.Popen.assert_any_call([
Edward Lemur99df04e2020-03-05 19:39:43 +00003106 'vpython', 'PRESUBMIT_SUPPORT',
3107 '--root', 'root',
3108 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003109 '--gerrit_url', 'https://chromium-review.googlesource.com',
3110 '--gerrit_project', 'project',
3111 '--gerrit_branch', 'refs/heads/main',
Edward Lemur99df04e2020-03-05 19:39:43 +00003112 '--upload',
3113 '--json_output', '/tmp/fake-temp2',
3114 '--description_file', '/tmp/fake-temp1',
3115 ])
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003116 gclient_utils.FileWrite.assert_any_call(
Edward Lemur99df04e2020-03-05 19:39:43 +00003117 '/tmp/fake-temp1', 'description')
3118 metrics.collector.add_repeated('sub_commands', {
3119 'command': 'presubmit',
3120 'execution_time': 100,
3121 'exit_code': 0,
3122 })
3123
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003124 def testRunHook_FewerOptionsResultDB(self):
3125 expected_results = {
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003126 'more_cc': ['cc@example.com', 'more@example.com'],
3127 'errors': [],
3128 'notifications': [],
3129 'warnings': [],
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003130 }
3131 gclient_utils.FileRead.return_value = json.dumps(expected_results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003132 git_cl.time_time.side_effect = [100, 200, 300, 400]
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003133 mockProcess = mock.Mock()
3134 mockProcess.wait.return_value = 0
3135 subprocess2.Popen.return_value = mockProcess
3136
3137 git_cl.Changelist.GetAuthor.return_value = None
3138 git_cl.Changelist.GetIssue.return_value = None
3139 git_cl.Changelist.GetPatchset.return_value = None
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003140
3141 cl = git_cl.Changelist()
3142 results = cl.RunHook(
3143 committing=False,
3144 may_prompt=False,
3145 verbose=0,
3146 parallel=False,
3147 upstream='upstream',
3148 description='description',
3149 all_files=False,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003150 resultdb=True,
3151 realm='chromium:public')
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003152
3153 self.assertEqual(expected_results, results)
Dirk Pranke61bf6e82021-04-23 00:50:21 +00003154 subprocess2.Popen.assert_any_call([
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003155 'rdb', 'stream', '-new', '-realm', 'chromium:public', '--',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003156 'vpython', 'PRESUBMIT_SUPPORT',
3157 '--root', 'root',
3158 '--upstream', 'upstream',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003159 '--gerrit_url', 'https://chromium-review.googlesource.com',
3160 '--gerrit_project', 'project',
3161 '--gerrit_branch', 'refs/heads/main',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003162 '--upload',
3163 '--json_output', '/tmp/fake-temp2',
3164 '--description_file', '/tmp/fake-temp1',
3165 ])
3166
Edward Lemur227d5102020-02-25 23:45:35 +00003167 @mock.patch('sys.exit', side_effect=SystemExitMock)
3168 def testRunHook_Failure(self, _mock):
3169 git_cl.time_time.side_effect = [100, 200]
3170 mockProcess = mock.Mock()
3171 mockProcess.wait.return_value = 2
3172 subprocess2.Popen.return_value = mockProcess
3173
3174 cl = git_cl.Changelist()
3175 with self.assertRaises(SystemExitMock):
3176 cl.RunHook(
3177 committing=True,
3178 may_prompt=True,
3179 verbose=2,
3180 parallel=True,
3181 upstream='upstream',
3182 description='description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003183 all_files=True,
3184 resultdb=False)
Edward Lemur227d5102020-02-25 23:45:35 +00003185
3186 sys.exit.assert_called_once_with(2)
3187
Edward Lemur75526302020-02-27 22:31:05 +00003188 def testRunPostUploadHook(self):
3189 cl = git_cl.Changelist()
3190 cl.RunPostUploadHook(2, 'upstream', 'description')
3191
3192 subprocess2.Popen.assert_called_once_with([
3193 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00003194 '--root', 'root',
3195 '--upstream', 'upstream',
3196 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00003197 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lesmeseb1bd622021-03-01 19:54:07 +00003198 '--gerrit_project', 'project',
3199 '--gerrit_branch', 'refs/heads/main',
3200 '--author', 'author',
Edward Lemur75526302020-02-27 22:31:05 +00003201 '--issue', '123456',
3202 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00003203 '--post_upload',
3204 '--description_file', '/tmp/fake-temp1',
3205 ])
3206 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00003207 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00003208
mlcui3da91712021-05-05 10:00:30 +00003209 @mock.patch('git_cl.RunGit', _mock_run_git)
3210 def testDefaultTitleEmptyMessage(self):
3211 cl = git_cl.Changelist()
3212 cl.issue = 100
3213 options = optparse.Values({
3214 'squash': True,
3215 'title': None,
3216 'message': None,
3217 'force': None,
3218 'skip_title': None
3219 })
3220
3221 mock.patch('gclient_utils.AskForData', lambda _: user_title).start()
3222 for user_title in ['', 'y', 'Y']:
3223 self.assertEqual(cl._GetTitleForUpload(options), self.LAST_COMMIT_SUBJECT)
3224
3225 for user_title in ['not empty', 'yes', 'YES']:
3226 self.assertEqual(cl._GetTitleForUpload(options), user_title)
3227
Edward Lemur9aa1a962020-02-25 00:58:38 +00003228
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003229class CMDTestCaseBase(unittest.TestCase):
3230 _STATUSES = [
3231 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3232 'INFRA_FAILURE', 'CANCELED',
3233 ]
3234 _CHANGE_DETAIL = {
3235 'project': 'depot_tools',
3236 'status': 'OPEN',
3237 'owner': {'email': 'owner@e.mail'},
3238 'current_revision': 'beeeeeef',
3239 'revisions': {
Gavin Make61ccc52020-11-13 00:12:57 +00003240 'deadbeaf': {
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00003241 '_number': 6,
Gavin Make61ccc52020-11-13 00:12:57 +00003242 'kind': 'REWORK',
3243 },
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003244 'beeeeeef': {
3245 '_number': 7,
Gavin Make61ccc52020-11-13 00:12:57 +00003246 'kind': 'NO_CODE_CHANGE',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003247 'fetch': {'http': {
3248 'url': 'https://chromium.googlesource.com/depot_tools',
3249 'ref': 'refs/changes/56/123456/7'
3250 }},
3251 },
3252 },
3253 }
3254 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003255 'builds': [{
3256 'id': str(100 + idx),
3257 'builder': {
3258 'project': 'chromium',
3259 'bucket': 'try',
3260 'builder': 'bot_' + status.lower(),
3261 },
3262 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3263 'tags': [],
3264 'status': status,
3265 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003266 }
3267
Edward Lemur4c707a22019-09-24 21:13:43 +00003268 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003269 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00003270 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003271 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3272 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003273 mock.patch(
3274 'git_cl.Changelist.GetCodereviewServer',
3275 return_value='https://chromium-review.googlesource.com').start()
3276 mock.patch(
Edward Lesmeseeca9c62020-11-20 00:00:17 +00003277 'git_cl.Changelist.GetGerritHost',
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003278 return_value='chromium-review.googlesource.com').start()
3279 mock.patch(
3280 'git_cl.Changelist.GetMostRecentPatchset',
3281 return_value=7).start()
3282 mock.patch(
Gavin Make61ccc52020-11-13 00:12:57 +00003283 'git_cl.Changelist.GetMostRecentDryRunPatchset',
3284 return_value=6).start()
3285 mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003286 'git_cl.Changelist.GetRemoteUrl',
3287 return_value='https://chromium.googlesource.com/depot_tools').start()
3288 mock.patch(
3289 'auth.Authenticator',
3290 return_value=AuthenticatorMock()).start()
3291 mock.patch(
3292 'gerrit_util.GetChangeDetail',
3293 return_value=self._CHANGE_DETAIL).start()
3294 mock.patch(
3295 'git_cl._call_buildbucket',
3296 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003297 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003298 self.addCleanup(mock.patch.stopall)
3299
Edward Lemur4c707a22019-09-24 21:13:43 +00003300
Edward Lemur9468eba2020-02-27 19:07:22 +00003301class CMDPresubmitTestCase(CMDTestCaseBase):
3302 def setUp(self):
3303 super(CMDPresubmitTestCase, self).setUp()
3304 mock.patch(
3305 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3306 return_value='upstream').start()
3307 mock.patch(
3308 'git_cl.Changelist.FetchDescription',
3309 return_value='fetch description').start()
3310 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003311 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003312 return_value='get description').start()
3313 mock.patch('git_cl.Changelist.RunHook').start()
3314
3315 def testDefaultCase(self):
3316 self.assertEqual(0, git_cl.main(['presubmit']))
3317 git_cl.Changelist.RunHook.assert_called_once_with(
3318 committing=True,
3319 may_prompt=False,
3320 verbose=0,
3321 parallel=None,
3322 upstream='upstream',
3323 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003324 all_files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003325 resultdb=None,
3326 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003327
3328 def testNoIssue(self):
3329 git_cl.Changelist.GetIssue.return_value = None
3330 self.assertEqual(0, git_cl.main(['presubmit']))
3331 git_cl.Changelist.RunHook.assert_called_once_with(
3332 committing=True,
3333 may_prompt=False,
3334 verbose=0,
3335 parallel=None,
3336 upstream='upstream',
3337 description='get description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003338 all_files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003339 resultdb=None,
3340 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003341
3342 def testCustomBranch(self):
3343 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3344 git_cl.Changelist.RunHook.assert_called_once_with(
3345 committing=True,
3346 may_prompt=False,
3347 verbose=0,
3348 parallel=None,
3349 upstream='custom_branch',
3350 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003351 all_files=None,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003352 resultdb=None,
3353 realm=None)
Edward Lemur9468eba2020-02-27 19:07:22 +00003354
3355 def testOptions(self):
3356 self.assertEqual(
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003357 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u',
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003358 '--resultdb', '--realm', 'chromium:public']))
Edward Lemur9468eba2020-02-27 19:07:22 +00003359 git_cl.Changelist.RunHook.assert_called_once_with(
3360 committing=False,
3361 may_prompt=False,
3362 verbose=2,
3363 parallel=True,
3364 upstream='upstream',
3365 description='fetch description',
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00003366 all_files=True,
Saagar Sanghavi03b15132020-08-10 16:43:41 +00003367 resultdb=True,
3368 realm='chromium:public')
Edward Lemur9468eba2020-02-27 19:07:22 +00003369
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003370class CMDTryResultsTestCase(CMDTestCaseBase):
3371 _DEFAULT_REQUEST = {
3372 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003373 "gerritChanges": [{
3374 "project": "depot_tools",
3375 "host": "chromium-review.googlesource.com",
Gavin Make61ccc52020-11-13 00:12:57 +00003376 "patchset": 6,
3377 "change": 123456,
3378 }],
3379 },
3380 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3381 ',builds.*.createTime,builds.*.tags'),
3382 }
3383
3384 _TRIVIAL_REQUEST = {
3385 'predicate': {
3386 "gerritChanges": [{
3387 "project": "depot_tools",
3388 "host": "chromium-review.googlesource.com",
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003389 "patchset": 7,
3390 "change": 123456,
3391 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003392 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003393 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3394 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003395 }
3396
3397 def testNoJobs(self):
3398 git_cl._call_buildbucket.return_value = {}
3399
3400 self.assertEqual(0, git_cl.main(['try-results']))
3401 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3402 git_cl._call_buildbucket.assert_called_once_with(
3403 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3404 self._DEFAULT_REQUEST)
3405
Gavin Make61ccc52020-11-13 00:12:57 +00003406 def testTrivialCommits(self):
3407 self.assertEqual(0, git_cl.main(['try-results']))
3408 git_cl._call_buildbucket.assert_called_with(
3409 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3410 self._DEFAULT_REQUEST)
3411
3412 git_cl._call_buildbucket.return_value = {}
3413 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '7']))
3414 git_cl._call_buildbucket.assert_called_with(
3415 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3416 self._TRIVIAL_REQUEST)
3417 self.assertEqual([
3418 'Successes:',
3419 ' bot_success https://ci.chromium.org/b/103',
3420 'Infra Failures:',
3421 ' bot_infra_failure https://ci.chromium.org/b/105',
3422 'Failures:',
3423 ' bot_failure https://ci.chromium.org/b/104',
3424 'Canceled:',
3425 ' bot_canceled ',
3426 'Started:',
3427 ' bot_started https://ci.chromium.org/b/102',
3428 'Scheduled:',
3429 ' bot_scheduled id=101',
3430 'Other:',
3431 ' bot_status_unspecified id=100',
3432 'Total: 7 tryjobs',
3433 'No tryjobs scheduled.',
3434 ], sys.stdout.getvalue().splitlines())
3435
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003436 def testPrintToStdout(self):
3437 self.assertEqual(0, git_cl.main(['try-results']))
3438 self.assertEqual([
3439 'Successes:',
3440 ' bot_success https://ci.chromium.org/b/103',
3441 'Infra Failures:',
3442 ' bot_infra_failure https://ci.chromium.org/b/105',
3443 'Failures:',
3444 ' bot_failure https://ci.chromium.org/b/104',
3445 'Canceled:',
3446 ' bot_canceled ',
3447 'Started:',
3448 ' bot_started https://ci.chromium.org/b/102',
3449 'Scheduled:',
3450 ' bot_scheduled id=101',
3451 'Other:',
3452 ' bot_status_unspecified id=100',
3453 'Total: 7 tryjobs',
3454 ], sys.stdout.getvalue().splitlines())
3455 git_cl._call_buildbucket.assert_called_once_with(
3456 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3457 self._DEFAULT_REQUEST)
3458
3459 def testPrintToStdoutWithMasters(self):
3460 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3461 self.assertEqual([
3462 'Successes:',
3463 ' try bot_success https://ci.chromium.org/b/103',
3464 'Infra Failures:',
3465 ' try bot_infra_failure https://ci.chromium.org/b/105',
3466 'Failures:',
3467 ' try bot_failure https://ci.chromium.org/b/104',
3468 'Canceled:',
3469 ' try bot_canceled ',
3470 'Started:',
3471 ' try bot_started https://ci.chromium.org/b/102',
3472 'Scheduled:',
3473 ' try bot_scheduled id=101',
3474 'Other:',
3475 ' try bot_status_unspecified id=100',
3476 'Total: 7 tryjobs',
3477 ], sys.stdout.getvalue().splitlines())
3478 git_cl._call_buildbucket.assert_called_once_with(
3479 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3480 self._DEFAULT_REQUEST)
3481
3482 @mock.patch('git_cl.write_json')
3483 def testWriteToJson(self, mockJsonDump):
3484 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3485 git_cl._call_buildbucket.assert_called_once_with(
3486 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3487 self._DEFAULT_REQUEST)
3488 mockJsonDump.assert_called_once_with(
3489 'file.json', self._DEFAULT_RESPONSE['builds'])
3490
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003491 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003492 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3493 self.assertEqual(
3494 [
3495 ('chromium', 'try', 'bot_failure'),
3496 ('chromium', 'try', 'bot_infra_failure'),
3497 ],
3498 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003499
3500 def test_filter_failed_for_retry_many_builds(self):
3501
3502 def _build(name, created_sec, status, experimental=False):
3503 assert 0 <= created_sec < 100, created_sec
3504 b = {
3505 'id': 112112,
3506 'builder': {
3507 'project': 'chromium',
3508 'bucket': 'try',
3509 'builder': name,
3510 },
3511 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3512 'status': status,
3513 'tags': [],
3514 }
3515 if experimental:
3516 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3517 return b
3518
3519 builds = [
3520 _build('flaky-last-green', 1, 'FAILURE'),
3521 _build('flaky-last-green', 2, 'SUCCESS'),
3522 _build('flaky', 1, 'SUCCESS'),
3523 _build('flaky', 2, 'FAILURE'),
3524 _build('running', 1, 'FAILED'),
3525 _build('running', 2, 'SCHEDULED'),
3526 _build('yep-still-running', 1, 'STARTED'),
3527 _build('yep-still-running', 2, 'FAILURE'),
3528 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3529 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3530
3531 # Simulate experimental in CQ builder, which developer decided
3532 # to retry manually which resulted in 2nd build non-experimental.
3533 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3534 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3535 ]
3536 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003537 self.assertEqual(
3538 [
3539 ('chromium', 'try', 'flaky'),
3540 ('chromium', 'try', 'sometimes-experimental'),
3541 ],
3542 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003543
3544
3545class CMDTryTestCase(CMDTestCaseBase):
3546
3547 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003548 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003549 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003550 self.assertEqual(0, git_cl.main(['try']))
3551 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3552 self.assertEqual(
3553 sys.stdout.getvalue(),
3554 'Scheduling CQ dry run on: '
3555 'https://chromium-review.googlesource.com/123456\n')
3556
Greg Gutermanbe5fccd2021-06-14 17:58:20 +00003557 @mock.patch('git_cl.Changelist.SetCQState')
3558 def testSetCQQuickRunByDefault(self, mockSetCQState):
3559 mockSetCQState.return_value = 0
3560 self.assertEqual(0, git_cl.main(['try', '-q']))
3561 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.QUICK_RUN)
3562 self.assertEqual(
3563 sys.stdout.getvalue(),
3564 'Scheduling CQ quick run on: '
3565 'https://chromium-review.googlesource.com/123456\n')
3566
Edward Lemur4c707a22019-09-24 21:13:43 +00003567 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003568 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003569 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003570
3571 self.assertEqual(0, git_cl.main([
3572 'try', '-B', 'luci.chromium.try', '-b', 'win',
3573 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3574 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003575 'Scheduling jobs on:\n'
3576 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003577 git_cl.sys.stdout.getvalue())
3578
3579 expected_request = {
3580 "requests": [{
3581 "scheduleBuild": {
3582 "requestId": "uuid4",
3583 "builder": {
3584 "project": "chromium",
3585 "builder": "win",
3586 "bucket": "try",
3587 },
3588 "gerritChanges": [{
3589 "project": "depot_tools",
3590 "host": "chromium-review.googlesource.com",
3591 "patchset": 7,
3592 "change": 123456,
3593 }],
3594 "properties": {
3595 "category": "git_cl_try",
3596 "json": [{"a": 1}, None],
3597 "key": "val",
3598 },
3599 "tags": [
3600 {"value": "win", "key": "builder"},
3601 {"value": "git_cl_try", "key": "user_agent"},
3602 ],
3603 },
3604 }],
3605 }
3606 mockCallBuildbucket.assert_called_with(
3607 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3608
Anthony Polito1a5fe232020-01-24 23:17:52 +00003609 @mock.patch('git_cl._call_buildbucket')
3610 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3611 mockCallBuildbucket.return_value = {}
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003612 mock.patch('git_cl.Changelist.GetRemoteBranch',
3613 return_value=('origin', 'refs/remotes/origin/main')).start()
Anthony Polito1a5fe232020-01-24 23:17:52 +00003614
3615 self.assertEqual(0, git_cl.main([
3616 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3617 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3618 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3619 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003620 'Scheduling jobs on:\n'
3621 ' chromium/try: linux\n'
3622 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003623 git_cl.sys.stdout.getvalue())
3624
3625 expected_request = {
3626 "requests": [{
3627 "scheduleBuild": {
3628 "requestId": "uuid4",
3629 "builder": {
3630 "project": "chromium",
3631 "builder": "linux",
3632 "bucket": "try",
3633 },
3634 "gerritChanges": [{
3635 "project": "depot_tools",
3636 "host": "chromium-review.googlesource.com",
3637 "patchset": 7,
3638 "change": 123456,
3639 }],
3640 "properties": {
3641 "category": "git_cl_try",
3642 "json": [{"a": 1}, None],
3643 "key": "val",
3644 },
3645 "tags": [
3646 {"value": "linux", "key": "builder"},
3647 {"value": "git_cl_try", "key": "user_agent"},
3648 ],
3649 "gitilesCommit": {
3650 "host": "chromium-review.googlesource.com",
3651 "project": "depot_tools",
3652 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003653 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003654 }
3655 },
3656 },
3657 {
3658 "scheduleBuild": {
3659 "requestId": "uuid4",
3660 "builder": {
3661 "project": "chromium",
3662 "builder": "win",
3663 "bucket": "try",
3664 },
3665 "gerritChanges": [{
3666 "project": "depot_tools",
3667 "host": "chromium-review.googlesource.com",
3668 "patchset": 7,
3669 "change": 123456,
3670 }],
3671 "properties": {
3672 "category": "git_cl_try",
3673 "json": [{"a": 1}, None],
3674 "key": "val",
3675 },
3676 "tags": [
3677 {"value": "win", "key": "builder"},
3678 {"value": "git_cl_try", "key": "user_agent"},
3679 ],
3680 "gitilesCommit": {
3681 "host": "chromium-review.googlesource.com",
3682 "project": "depot_tools",
3683 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003684 "ref": "refs/heads/main",
Anthony Polito1a5fe232020-01-24 23:17:52 +00003685 }
3686 },
3687 }],
3688 }
3689 mockCallBuildbucket.assert_called_with(
3690 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3691
Edward Lemur45768512020-03-02 19:03:14 +00003692 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003693 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003694 with self.assertRaises(SystemExit):
3695 git_cl.main([
3696 'try', '-B', 'not-a-bucket', '-b', 'win',
3697 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003698 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003699 'Invalid bucket: not-a-bucket.',
3700 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003701
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003702 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003703 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003704 def testScheduleOnBuildbucketRetryFailed(
3705 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003706 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003707 7: [],
3708 6: [{
3709 'id': 112112,
3710 'builder': {
3711 'project': 'chromium',
3712 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003713 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003714 'createTime': '2019-10-09T08:00:01.854286Z',
3715 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003716 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003717 mockCallBuildbucket.return_value = {}
3718
3719 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3720 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003721 'Scheduling jobs on:\n'
3722 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003723 git_cl.sys.stdout.getvalue())
3724
3725 expected_request = {
3726 "requests": [{
3727 "scheduleBuild": {
3728 "requestId": "uuid4",
3729 "builder": {
3730 "project": "chromium",
3731 "bucket": "try",
3732 "builder": "linux",
3733 },
3734 "gerritChanges": [{
3735 "project": "depot_tools",
3736 "host": "chromium-review.googlesource.com",
3737 "patchset": 7,
3738 "change": 123456,
3739 }],
3740 "properties": {
3741 "category": "git_cl_try",
3742 },
3743 "tags": [
3744 {"value": "linux", "key": "builder"},
3745 {"value": "git_cl_try", "key": "user_agent"},
3746 {"value": "1", "key": "retry_failed"},
3747 ],
3748 },
3749 }],
3750 }
3751 mockCallBuildbucket.assert_called_with(
3752 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3753
Edward Lemur4c707a22019-09-24 21:13:43 +00003754 def test_parse_bucket(self):
3755 test_cases = [
3756 {
3757 'bucket': 'chromium/try',
3758 'result': ('chromium', 'try'),
3759 },
3760 {
3761 'bucket': 'luci.chromium.try',
3762 'result': ('chromium', 'try'),
3763 'has_warning': True,
3764 },
3765 {
3766 'bucket': 'skia.primary',
3767 'result': ('skia', 'skia.primary'),
3768 'has_warning': True,
3769 },
3770 {
3771 'bucket': 'not-a-bucket',
3772 'result': (None, None),
3773 },
3774 ]
3775
3776 for test_case in test_cases:
3777 git_cl.sys.stdout.truncate(0)
3778 self.assertEqual(
3779 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3780 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003781 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3782 test_case['result'])
3783 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003784
3785
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003786class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003787
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003788 def setUp(self):
3789 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003790 mock.patch('git_cl._fetch_tryjobs').start()
3791 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003792 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003793 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3794 mock.patch(
3795 'git_cl.Settings.GetSquashGerritUploads',
3796 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003797 self.addCleanup(mock.patch.stopall)
3798
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003799 def testWarmUpChangeDetailCache(self):
3800 self.assertEqual(0, git_cl.main(['upload']))
3801 gerrit_util.GetChangeDetail.assert_called_once_with(
3802 'chromium-review.googlesource.com', 'depot_tools~123456',
3803 frozenset([
3804 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3805 'CURRENT_COMMIT']))
3806
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003807 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003808 # This test mocks out the actual upload part, and just asserts that after
3809 # upload, if --retry-failed is added, then the tool will fetch try jobs
3810 # from the previous patchset and trigger the right builders on the latest
3811 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003812 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003813 # Latest patchset: No builds.
3814 [],
3815 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003816 [{
3817 'id': str(100 + idx),
3818 'builder': {
3819 'project': 'chromium',
3820 'bucket': 'try',
3821 'builder': 'bot_' + status.lower(),
3822 },
3823 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3824 'tags': [],
3825 'status': status,
3826 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003827 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003828
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003829 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003830 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003831 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3832 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003833 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003834 expected_buckets = [
3835 ('chromium', 'try', 'bot_failure'),
3836 ('chromium', 'try', 'bot_infra_failure'),
3837 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003838 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3839 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003840
Brian Sheedy59b06a82019-10-14 17:03:29 +00003841
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003842class MakeRequestsHelperTestCase(unittest.TestCase):
3843
3844 def exampleGerritChange(self):
3845 return {
3846 'host': 'chromium-review.googlesource.com',
3847 'project': 'depot_tools',
3848 'change': 1,
3849 'patchset': 2,
3850 }
3851
3852 def testMakeRequestsHelperNoOptions(self):
3853 # Basic test for the helper function _make_tryjob_schedule_requests;
3854 # it shouldn't throw AttributeError even when options doesn't have any
3855 # of the expected values; it will use default option values.
3856 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3857 jobs = [('chromium', 'try', 'my-builder')]
3858 options = optparse.Values()
3859 requests = git_cl._make_tryjob_schedule_requests(
3860 changelist, jobs, options, patchset=None)
3861
3862 # requestId is non-deterministic. Just assert that it's there and has
3863 # a particular length.
3864 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3865 self.assertEqual(requests, [{
3866 'scheduleBuild': {
3867 'builder': {
3868 'bucket': 'try',
3869 'builder': 'my-builder',
3870 'project': 'chromium'
3871 },
3872 'gerritChanges': [self.exampleGerritChange()],
3873 'properties': {
3874 'category': 'git_cl_try'
3875 },
3876 'tags': [{
3877 'key': 'builder',
3878 'value': 'my-builder'
3879 }, {
3880 'key': 'user_agent',
3881 'value': 'git_cl_try'
3882 }]
3883 }
3884 }])
3885
3886 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3887 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3888 jobs = [('chromium', 'try', 'presubmit')]
3889 options = optparse.Values()
3890 requests = git_cl._make_tryjob_schedule_requests(
3891 changelist, jobs, options, patchset=None)
3892 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3893 'category': 'git_cl_try',
3894 'dry_run': 'true'
3895 })
3896
3897 def testMakeRequestsHelperRevisionSet(self):
3898 # Gitiles commit is specified when revision is in options.
3899 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3900 jobs = [('chromium', 'try', 'my-builder')]
3901 options = optparse.Values({'revision': 'ba5eba11'})
3902 requests = git_cl._make_tryjob_schedule_requests(
3903 changelist, jobs, options, patchset=None)
3904 self.assertEqual(
3905 requests[0]['scheduleBuild']['gitilesCommit'], {
3906 'host': 'chromium-review.googlesource.com',
3907 'id': 'ba5eba11',
Josip Sokcevic9011a5b2021-02-12 18:59:44 +00003908 'project': 'depot_tools',
3909 'ref': 'refs/heads/main',
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003910 })
3911
3912 def testMakeRequestsHelperRetryFailedSet(self):
3913 # An extra tag is added when retry_failed is in options.
3914 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3915 jobs = [('chromium', 'try', 'my-builder')]
3916 options = optparse.Values({'retry_failed': 'true'})
3917 requests = git_cl._make_tryjob_schedule_requests(
3918 changelist, jobs, options, patchset=None)
3919 self.assertEqual(
3920 requests[0]['scheduleBuild']['tags'], [
3921 {
3922 'key': 'builder',
3923 'value': 'my-builder'
3924 },
3925 {
3926 'key': 'user_agent',
3927 'value': 'git_cl_try'
3928 },
3929 {
3930 'key': 'retry_failed',
3931 'value': '1'
3932 }
3933 ])
3934
3935 def testMakeRequestsHelperCategorySet(self):
Quinten Yearsley925cedb2020-04-13 17:49:39 +00003936 # The category property can be overridden with options.
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003937 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3938 jobs = [('chromium', 'try', 'my-builder')]
3939 options = optparse.Values({'category': 'my-special-category'})
3940 requests = git_cl._make_tryjob_schedule_requests(
3941 changelist, jobs, options, patchset=None)
3942 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3943 {'category': 'my-special-category'})
3944
3945
Edward Lemurda4b6c62020-02-13 00:28:40 +00003946class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003947
3948 def setUp(self):
3949 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003950 mock.patch('git_cl.RunCommand').start()
3951 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3952 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3953 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003954 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003955 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003956
3957 def tearDown(self):
3958 shutil.rmtree(self._top_dir)
3959 super(CMDFormatTestCase, self).tearDown()
3960
Jamie Madill5e96ad12020-01-13 16:08:35 +00003961 def _make_temp_file(self, fname, contents):
Anthony Politoc64e3902021-04-30 21:55:25 +00003962 gclient_utils.FileWrite(os.path.join(self._top_dir, fname),
3963 ('\n'.join(contents)))
Jamie Madill5e96ad12020-01-13 16:08:35 +00003964
Brian Sheedy59b06a82019-10-14 17:03:29 +00003965 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003966 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003967
Brian Sheedyb4307d52019-12-02 19:18:17 +00003968 def _check_yapf_filtering(self, files, expected):
3969 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3970 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003971
Edward Lemur1a83da12020-03-04 21:18:36 +00003972 def _run_command_mock(self, return_value):
3973 def f(*args, **kwargs):
3974 if 'stdin' in kwargs:
3975 self.assertIsInstance(kwargs['stdin'], bytes)
3976 return return_value
3977 return f
3978
Jamie Madill5e96ad12020-01-13 16:08:35 +00003979 def testClangFormatDiffFull(self):
3980 self._make_temp_file('test.cc', ['// test'])
3981 git_cl.settings.GetFormatFullByDefault.return_value = False
3982 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3983 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3984
3985 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003986 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003987 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3988 self._top_dir, 'HEAD')
3989 self.assertEqual(2, return_value)
3990
3991 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003992 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003993 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3994 self._top_dir, 'HEAD')
3995 self.assertEqual(0, return_value)
3996
3997 def testClangFormatDiff(self):
3998 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00003999 # A valid file is required, so use this test.
4000 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00004001 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
4002
4003 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004004 git_cl.RunCommand.side_effect = self._run_command_mock('error')
4005 return_value = git_cl._RunClangFormatDiff(
4006 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004007 self.assertEqual(2, return_value)
4008
4009 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00004010 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004011 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
4012 'HEAD')
4013 self.assertEqual(0, return_value)
4014
Brian Sheedyb4307d52019-12-02 19:18:17 +00004015 def testYapfignoreExplicit(self):
4016 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
4017 files = [
4018 'bar.py',
4019 'foo/bar.py',
4020 'foo/baz.py',
4021 'foo/bar/baz.py',
4022 'foo/bar/foobar.py',
4023 ]
4024 expected = [
4025 'bar.py',
4026 'foo/baz.py',
4027 'foo/bar/foobar.py',
4028 ]
4029 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004030
Brian Sheedyb4307d52019-12-02 19:18:17 +00004031 def testYapfignoreSingleWildcards(self):
4032 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
4033 files = [
4034 'bar.py', # Matched by *bar.py.
4035 'bar.txt',
4036 'foobar.py', # Matched by *bar.py, foo*.
4037 'foobar.txt', # Matched by foo*.
4038 'bazbar.py', # Matched by *bar.py, baz*.py.
4039 'bazbar.txt',
4040 'foo/baz.txt', # Matched by foo*.
4041 'bar/bar.py', # Matched by *bar.py.
4042 'baz/foo.py', # Matched by baz*.py, foo*.
4043 'baz/foo.txt',
4044 ]
4045 expected = [
4046 'bar.txt',
4047 'bazbar.txt',
4048 'baz/foo.txt',
4049 ]
4050 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004051
Brian Sheedyb4307d52019-12-02 19:18:17 +00004052 def testYapfignoreMultiplewildcards(self):
4053 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
4054 files = [
4055 'bar.py', # Matched by *bar*.
4056 'bar.txt', # Matched by *bar*.
4057 'abar.py', # Matched by *bar*.
4058 'foobaz.txt', # Matched by *foo*baz.txt.
4059 'foobaz.py',
4060 'afoobaz.txt', # Matched by *foo*baz.txt.
4061 ]
4062 expected = [
4063 'foobaz.py',
4064 ]
4065 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004066
4067 def testYapfignoreComments(self):
4068 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004069 files = [
4070 'test.py',
4071 'test2.py',
4072 ]
4073 expected = [
4074 'test2.py',
4075 ]
4076 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004077
Anthony Politoc64e3902021-04-30 21:55:25 +00004078 def testYapfHandleUtf8(self):
4079 self._make_yapfignore(['test.py', 'test_🌐.py'])
4080 files = [
4081 'test.py',
4082 'test_🌐.py',
4083 'test2.py',
4084 ]
4085 expected = [
4086 'test2.py',
4087 ]
4088 self._check_yapf_filtering(files, expected)
4089
Brian Sheedy59b06a82019-10-14 17:03:29 +00004090 def testYapfignoreBlankLines(self):
4091 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004092 files = [
4093 'test.py',
4094 'test2.py',
4095 'test3.py',
4096 ]
4097 expected = [
4098 'test3.py',
4099 ]
4100 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004101
4102 def testYapfignoreWhitespace(self):
4103 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004104 files = [
4105 'test.py',
4106 'test2.py',
4107 ]
4108 expected = [
4109 'test2.py',
4110 ]
4111 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004112
Brian Sheedyb4307d52019-12-02 19:18:17 +00004113 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00004114 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00004115 self._check_yapf_filtering([], [])
4116
4117 def testYapfignoreMissingYapfignore(self):
4118 files = [
4119 'test.py',
4120 ]
4121 expected = [
4122 'test.py',
4123 ]
4124 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00004125
4126
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004127class CMDStatusTestCase(CMDTestCaseBase):
4128 # Return branch names a,..,f with comitterdates in increasing order, i.e.
4129 # 'f' is the most-recently changed branch.
4130 def _mock_run_git(commands):
4131 if commands == [
4132 'for-each-ref', '--format=%(refname) %(committerdate:unix)',
4133 'refs/heads'
4134 ]:
4135 branches_and_committerdates = [
4136 'refs/heads/a 1',
4137 'refs/heads/b 2',
4138 'refs/heads/c 3',
4139 'refs/heads/d 4',
4140 'refs/heads/e 5',
4141 'refs/heads/f 6',
4142 ]
4143 return '\n'.join(branches_and_committerdates)
4144
4145 # Mock the status in such a way that the issue number gives us an
4146 # indication of the commit date (simplifies manual debugging).
4147 def _mock_get_cl_statuses(branches, fine_grained, max_processes):
4148 for c in branches:
4149 c.issue = (100 + int(c.GetCommitDate()))
4150 yield (c, 'open')
4151
4152 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4153 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4154 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4155 @mock.patch('git_cl.RunGit', _mock_run_git)
4156 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4157 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004158 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004159 @mock.patch('scm.GIT.GetBranch', return_value='a')
4160 def testStatus(self, *_mocks):
4161 self.assertEqual(0, git_cl.main(['status', '--no-branch-color']))
4162 self.maxDiff = None
4163 self.assertEqual(
4164 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4165 ' * a : https://crrev.com/c/101 (open)\n'
4166 ' b : https://crrev.com/c/102 (open)\n'
4167 ' c : https://crrev.com/c/103 (open)\n'
4168 ' d : https://crrev.com/c/104 (open)\n'
4169 ' e : https://crrev.com/c/105 (open)\n'
4170 ' f : https://crrev.com/c/106 (open)\n\n'
4171 'Current branch: a\n'
4172 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4173 'Issue description:\n'
4174 'x\n')
4175
4176 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4177 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4178 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4179 @mock.patch('git_cl.RunGit', _mock_run_git)
4180 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4181 @mock.patch('git_cl.Settings.GetRoot', return_value='')
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004182 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004183 @mock.patch('scm.GIT.GetBranch', return_value='a')
4184 def testStatusByDate(self, *_mocks):
4185 self.assertEqual(
4186 0, git_cl.main(['status', '--no-branch-color', '--date-order']))
4187 self.maxDiff = None
4188 self.assertEqual(
4189 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4190 ' f : https://crrev.com/c/106 (open)\n'
4191 ' e : https://crrev.com/c/105 (open)\n'
4192 ' d : https://crrev.com/c/104 (open)\n'
4193 ' c : https://crrev.com/c/103 (open)\n'
4194 ' b : https://crrev.com/c/102 (open)\n'
4195 ' * a : https://crrev.com/c/101 (open)\n\n'
4196 'Current branch: a\n'
4197 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4198 'Issue description:\n'
4199 'x\n')
4200
Sigurd Schneider1bfda8e2021-06-30 14:46:25 +00004201 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
4202 @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
4203 @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
4204 @mock.patch('git_cl.RunGit', _mock_run_git)
4205 @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
4206 @mock.patch('git_cl.Settings.GetRoot', return_value='')
4207 @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=True)
4208 @mock.patch('scm.GIT.GetBranch', return_value='a')
4209 def testStatusByDate(self, *_mocks):
4210 self.assertEqual(
4211 0, git_cl.main(['status', '--no-branch-color']))
4212 self.maxDiff = None
4213 self.assertEqual(
4214 sys.stdout.getvalue(), 'Branches associated with reviews:\n'
4215 ' f : https://crrev.com/c/106 (open)\n'
4216 ' e : https://crrev.com/c/105 (open)\n'
4217 ' d : https://crrev.com/c/104 (open)\n'
4218 ' c : https://crrev.com/c/103 (open)\n'
4219 ' b : https://crrev.com/c/102 (open)\n'
4220 ' * a : https://crrev.com/c/101 (open)\n\n'
4221 'Current branch: a\n'
4222 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
4223 'Issue description:\n'
4224 'x\n')
Sigurd Schneider9abde8c2020-11-17 08:44:52 +00004225
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004226class CMDOwnersTestCase(CMDTestCaseBase):
4227 def setUp(self):
4228 super(CMDOwnersTestCase, self).setUp()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004229 self.owners_by_path = {
4230 'foo': ['a@example.com'],
4231 'bar': ['b@example.com', 'c@example.com'],
4232 }
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004233 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
4234 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
4235 mock.patch(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004236 'git_cl.Changelist.GetAffectedFiles',
4237 return_value=list(self.owners_by_path)).start()
4238 mock.patch(
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004239 'git_cl.Changelist.GetCommonAncestorWithUpstream',
4240 return_value='upstream').start()
Edward Lesmes82b992a2021-01-11 23:24:55 +00004241 mock.patch(
Edward Lesmese1576912021-02-16 21:53:34 +00004242 'git_cl.Changelist.GetGerritHost',
4243 return_value='host').start()
4244 mock.patch(
4245 'git_cl.Changelist.GetGerritProject',
4246 return_value='project').start()
4247 mock.patch(
4248 'git_cl.Changelist.GetRemoteBranch',
4249 return_value=('origin', 'refs/remotes/origin/main')).start()
4250 mock.patch(
4251 'owners_client.OwnersClient.BatchListOwners',
Edward Lesmes82b992a2021-01-11 23:24:55 +00004252 return_value=self.owners_by_path).start()
Edward Lesmes8170c292021-03-19 20:04:43 +00004253 mock.patch(
4254 'gerrit_util.IsCodeOwnersEnabledOnHost', return_value=True).start()
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004255 self.addCleanup(mock.patch.stopall)
4256
4257 def testShowAllNoArgs(self):
4258 self.assertEqual(0, git_cl.main(['owners', '--show-all']))
4259 self.assertEqual(
4260 'No files specified for --show-all. Nothing to do.\n',
4261 git_cl.sys.stdout.getvalue())
4262
4263 def testShowAll(self):
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004264 self.assertEqual(
4265 0,
4266 git_cl.main(['owners', '--show-all', 'foo', 'bar', 'baz']))
Edward Lesmese1576912021-02-16 21:53:34 +00004267 owners_client.OwnersClient.BatchListOwners.assert_called_once_with(
Edward Lesmes82b992a2021-01-11 23:24:55 +00004268 ['foo', 'bar', 'baz'])
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004269 self.assertEqual(
4270 '\n'.join([
4271 'Owners for foo:',
4272 ' - a@example.com',
4273 'Owners for bar:',
4274 ' - b@example.com',
4275 ' - c@example.com',
4276 'Owners for baz:',
4277 ' - No owners found',
4278 '',
4279 ]),
4280 sys.stdout.getvalue())
4281
Edward Lesmes82b992a2021-01-11 23:24:55 +00004282 def testBatch(self):
4283 self.assertEqual(0, git_cl.main(['owners', '--batch']))
4284 self.assertIn('a@example.com', sys.stdout.getvalue())
4285 self.assertIn('b@example.com', sys.stdout.getvalue())
4286
Edward Lesmes0e4e5ae2021-01-08 18:28:46 +00004287
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004288if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01004289 logging.basicConfig(
4290 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004291 unittest.main()