blob: 85dc4b7874cbdc0a6bc0b15f40c546a0d026677b [file] [log] [blame]
Edward Lemur0db01f02019-11-12 22:01:51 +00001#!/usr/bin/env vpython3
2# coding=utf-8
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00003# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Unit tests for git_cl.py."""
8
Edward Lemur85153282020-02-14 22:06:29 +00009from __future__ import print_function
Edward Lemur0db01f02019-11-12 22:01:51 +000010from __future__ import unicode_literals
11
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +010012import datetime
tandriide281ae2016-10-12 06:02:30 -070013import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010014import logging
Edward Lemur61bf4172020-02-24 23:22:37 +000015import multiprocessing
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000016import optparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000017import os
Edward Lemur85153282020-02-14 22:06:29 +000018import pprint
Brian Sheedy59b06a82019-10-14 17:03:29 +000019import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000020import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070021import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000022import unittest
23
Edward Lemura8145022020-01-06 18:47:54 +000024if sys.version_info.major == 2:
25 from StringIO import StringIO
26 import mock
27else:
28 from io import StringIO
29 from unittest import mock
30
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
32
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000033import metrics
34# We have to disable monitoring before importing git_cl.
35metrics.DISABLE_METRICS_COLLECTION = True
36
Jamie Madill5e96ad12020-01-13 16:08:35 +000037import clang_format
Edward Lemur227d5102020-02-25 23:45:35 +000038import contextlib
Edward Lemur1773f372020-02-22 00:27:14 +000039import gclient_utils
Eric Boren2fb63102018-10-05 13:05:03 +000040import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000041import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000042import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000043import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000044import git_new_branch
45import scm
maruel@chromium.orgddd59412011-11-30 14:20:38 +000046import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000047
Josip Sokcevic464e9ff2020-03-18 23:48:55 +000048NETRC_FILENAME = '_netrc' if sys.platform == 'win32' else '.netrc'
49
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000050
Edward Lemur0db01f02019-11-12 22:01:51 +000051def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070052 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
53
tandrii5d48c322016-08-18 16:19:37 -070054CERR1 = callError(1)
55
56
Edward Lemur1773f372020-02-22 00:27:14 +000057class TemporaryFileMock(object):
58 def __init__(self):
59 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070060
Edward Lemur1773f372020-02-22 00:27:14 +000061 @contextlib.contextmanager
62 def __call__(self):
63 self.suffix += 1
64 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070065
66
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000067class ChangelistMock(object):
68 # A class variable so we can access it when we don't have access to the
69 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000070 desc = ''
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000071
72 def __init__(self, gerrit_change=None, **kwargs):
73 self._gerrit_change = gerrit_change
74
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000075 def GetIssue(self):
76 return 1
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000077
Edward Lemur6c6827c2020-02-06 21:15:18 +000078 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000079 return ChangelistMock.desc
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000080
dsansomee2d6fd92016-09-08 00:10:47 -070081 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000082 ChangelistMock.desc = desc
83
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000084 def GetGerritChange(self, patchset=None, **kwargs):
85 del patchset
86 return self._gerrit_change
87
tandrii5d48c322016-08-18 16:19:37 -070088
Edward Lemur85153282020-02-14 22:06:29 +000089class GitMocks(object):
90 def __init__(self, config=None, branchref=None):
91 self.branchref = branchref or 'refs/heads/master'
92 self.config = config or {}
93
94 def GetBranchRef(self, _root):
95 return self.branchref
96
97 def NewBranch(self, branchref):
98 self.branchref = branchref
99
Edward Lemur26964072020-02-19 19:18:51 +0000100 def GetConfig(self, root, key, default=None):
101 if root != '':
102 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000103 return self.config.get(key, default)
104
Edward Lemur26964072020-02-19 19:18:51 +0000105 def SetConfig(self, root, key, value=None):
106 if root != '':
107 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000108 if value:
109 self.config[key] = value
110 return
111 if key not in self.config:
112 raise CERR1
113 del self.config[key]
114
115
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000116class WatchlistsMock(object):
117 def __init__(self, _):
118 pass
119 @staticmethod
120 def GetWatchersForPaths(_):
121 return ['joe@example.com']
122
123
Edward Lemur4c707a22019-09-24 21:13:43 +0000124class CodereviewSettingsFileMock(object):
125 def __init__(self):
126 pass
127 # pylint: disable=no-self-use
128 def read(self):
129 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
130 'GERRIT_HOST: True\n')
131
132
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000133class AuthenticatorMock(object):
134 def __init__(self, *_args):
135 pass
136 def has_cached_credentials(self):
137 return True
tandrii221ab252016-10-06 08:12:04 -0700138 def authorize(self, http):
139 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000140
141
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100142def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000143 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
144
145 Usage:
146 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100147 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000148
149 OR
150 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100151 CookiesAuthenticatorMockFactory(
152 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000153 """
154 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800155 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000156 # Intentionally not calling super() because it reads actual cookie files.
157 pass
158 @classmethod
159 def get_gitcookies_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000160 return os.path.join('~', '.gitcookies')
161
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000162 @classmethod
163 def get_netrc_path(cls):
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000164 return os.path.join('~', NETRC_FILENAME)
165
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100166 def _get_auth_for_host(self, host):
167 if same_auth:
168 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000169 return (hosts_with_creds or {}).get(host)
170 return CookiesAuthenticatorMock
171
Aaron Gable9a03ae02017-11-03 11:31:07 -0700172
kmarshall9249e012016-08-23 12:02:16 -0700173class MockChangelistWithBranchAndIssue():
174 def __init__(self, branch, issue):
175 self.branch = branch
176 self.issue = issue
177 def GetBranch(self):
178 return self.branch
179 def GetIssue(self):
180 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000181
tandriic2405f52016-10-10 08:13:15 -0700182
183class SystemExitMock(Exception):
184 pass
185
186
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000187class TestGitClBasic(unittest.TestCase):
Josip Sokcevic953278a2020-02-28 19:46:36 +0000188 def setUp(self):
189 mock.patch('sys.exit', side_effect=SystemExitMock).start()
190 mock.patch('sys.stdout', StringIO()).start()
191 mock.patch('sys.stderr', StringIO()).start()
192 self.addCleanup(mock.patch.stopall)
193
194 def test_die_with_error(self):
195 with self.assertRaises(SystemExitMock):
196 git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
197 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
198 self.assertTrue('saving CL description' in sys.stdout.getvalue())
199 self.assertTrue('Content of CL description' in sys.stdout.getvalue())
200 self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
201 sys.exit.assert_called_once_with(1)
202
203 def test_die_with_error_no_desc(self):
204 with self.assertRaises(SystemExitMock):
205 git_cl.DieWithError('foo')
206 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
207 self.assertEqual(sys.stdout.getvalue(), '')
208 sys.exit.assert_called_once_with(1)
209
Edward Lemur6c6827c2020-02-06 21:15:18 +0000210 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000211 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100212 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000213 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700214
Edward Lemur61bf4172020-02-24 23:22:37 +0000215 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
216 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
217 def test_get_cl_statuses(self, *_mocks):
218 statuses = [
219 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
220 changes = []
221 for status in statuses:
222 cl = git_cl.Changelist()
223 cl.status = status
224 changes.append(cl)
225
226 actual = set(git_cl.get_cl_statuses(changes, True))
227 self.assertEqual(set(zip(changes, statuses)), actual)
228
229 def test_get_cl_statuses_no_changes(self):
230 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
231
232 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
233 @mock.patch('multiprocessing.pool.ThreadPool')
234 def test_get_cl_statuses_timeout(self, *_mocks):
235 changes = [git_cl.Changelist() for _ in range(2)]
236 pool = multiprocessing.pool.ThreadPool()
237 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
238 it.return_value.next.side_effect = [
239 (changes[0], 'lgtm'),
240 multiprocessing.TimeoutError,
241 ]
242
243 actual = list(git_cl.get_cl_statuses(changes, True))
244 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
245
246 @mock.patch('git_cl.Changelist.GetIssueURL')
247 def test_get_cl_statuses_not_finegrained(self, _mock):
248 changes = [git_cl.Changelist() for _ in range(2)]
249 urls = ['some-url', None]
250 git_cl.Changelist.GetIssueURL.side_effect = urls
251
252 actual = set(git_cl.get_cl_statuses(changes, False))
253 self.assertEqual(
254 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
255
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000256 def test_get_issue_url(self):
257 cl = git_cl.Changelist(issue=123)
258 cl._gerrit_server = 'https://example.com'
259 self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
260 self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
261
262 cl = git_cl.Changelist(issue=123)
263 cl._gerrit_server = 'https://chromium-review.googlesource.com'
264 self.assertEqual(cl.GetIssueURL(),
265 'https://chromium-review.googlesource.com/123')
266 self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
267
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000268 def test_set_preserve_tryjobs(self):
269 d = git_cl.ChangeDescription('Simple.')
270 d.set_preserve_tryjobs()
271 self.assertEqual(d.description.splitlines(), [
272 'Simple.',
273 '',
274 'Cq-Do-Not-Cancel-Tryjobs: true',
275 ])
276 before = d.description
277 d.set_preserve_tryjobs()
278 self.assertEqual(before, d.description)
279
280 d = git_cl.ChangeDescription('\n'.join([
281 'One is enough',
282 '',
283 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
284 'Change-Id: Ideadbeef',
285 ]))
286 d.set_preserve_tryjobs()
287 self.assertEqual(d.description.splitlines(), [
288 'One is enough',
289 '',
290 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
291 'Change-Id: Ideadbeef',
292 'Cq-Do-Not-Cancel-Tryjobs: true',
293 ])
294
tandriif9aefb72016-07-01 09:06:51 -0700295 def test_get_bug_line_values(self):
296 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
297 self.assertEqual(f('', ''), [])
298 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
299 self.assertEqual(f('v8', '456'), ['v8:456'])
300 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
301 # Not nice, but not worth carying.
302 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
303 ['v8:456', 'chromium:123', 'v8:123'])
304
Edward Lemurda4b6c62020-02-13 00:28:40 +0000305 @mock.patch('gerrit_util.GetAccountDetails')
306 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000307 mock_per_account = {
308 'u1': None, # 404, doesn't exist.
309 'u2': {
310 '_account_id': 123124,
311 'avatars': [],
312 'email': 'u2@example.com',
313 'name': 'User Number 2',
314 'status': 'OOO',
315 },
316 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
317 }
318 def GetAccountDetailsMock(_, account):
319 # Poor-man's mock library's side_effect.
320 v = mock_per_account.pop(account)
321 if isinstance(v, Exception):
322 raise v
323 return v
324
Edward Lemurda4b6c62020-02-13 00:28:40 +0000325 mockGetAccountDetails.side_effect = GetAccountDetailsMock
326 actual = git_cl.gerrit_util.ValidAccounts(
327 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000328 self.assertEqual(actual, {
329 'u2': {
330 '_account_id': 123124,
331 'avatars': [],
332 'email': 'u2@example.com',
333 'name': 'User Number 2',
334 'status': 'OOO',
335 },
336 })
337
338
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200339class TestParseIssueURL(unittest.TestCase):
340 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000341 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200342 self.assertIsNotNone(parsed)
343 if fail:
344 self.assertFalse(parsed.valid)
345 return
346 self.assertTrue(parsed.valid)
347 self.assertEqual(parsed.issue, issue)
348 self.assertEqual(parsed.patchset, patchset)
349 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200350
Edward Lemur678a6842019-10-03 22:25:05 +0000351 def test_ParseIssueNumberArgument(self):
352 def test(arg, *args, **kwargs):
353 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200354
Edward Lemur678a6842019-10-03 22:25:05 +0000355 test('123', 123)
356 test('', fail=True)
357 test('abc', fail=True)
358 test('123/1', fail=True)
359 test('123a', fail=True)
360 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200361
Edward Lemur678a6842019-10-03 22:25:05 +0000362 test('https://codereview.source.com/123',
363 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200364 test('http://chrome-review.source.com/c/123',
365 123, None, 'chrome-review.source.com')
366 test('https://chrome-review.source.com/c/123/',
367 123, None, 'chrome-review.source.com')
368 test('https://chrome-review.source.com/c/123/4',
369 123, 4, 'chrome-review.source.com')
370 test('https://chrome-review.source.com/#/c/123/4',
371 123, 4, 'chrome-review.source.com')
372 test('https://chrome-review.source.com/c/123/4',
373 123, 4, 'chrome-review.source.com')
374 test('https://chrome-review.source.com/123',
375 123, None, 'chrome-review.source.com')
376 test('https://chrome-review.source.com/123/4',
377 123, 4, 'chrome-review.source.com')
378
Edward Lemur678a6842019-10-03 22:25:05 +0000379 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200380 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
381 test('https://chrome-review.source.com/c/abc/', fail=True)
382 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
383
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200384
385
Edward Lemurda4b6c62020-02-13 00:28:40 +0000386class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100387 def setUp(self):
388 super(GitCookiesCheckerTest, self).setUp()
389 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100390 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000391 mock.patch('sys.stdout', StringIO()).start()
392 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100393
394 def mock_hosts_creds(self, subhost_identity_pairs):
395 def ensure_googlesource(h):
396 if not h.endswith(self.c._GOOGLESOURCE):
397 assert not h.endswith('.')
398 return h + '.' + self.c._GOOGLESOURCE
399 return h
400 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
401 for h, i in subhost_identity_pairs]
402
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200403 def test_identity_parsing(self):
404 self.assertEqual(self.c._parse_identity('ldap.google.com'),
405 ('ldap', 'google.com'))
406 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
407 ('ldap', 'example.com'))
408 # Specical case because we know there are no subdomains in chromium.org.
409 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
410 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800411 # Pathological: ".period." can be either username OR domain, more likely
412 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200413 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
414 ('note', 'period.example.com'))
415
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100416 def test_analysis_nothing(self):
417 self.c._all_hosts = []
418 self.assertFalse(self.c.has_generic_host())
419 self.assertEqual(set(), self.c.get_conflicting_hosts())
420 self.assertEqual(set(), self.c.get_duplicated_hosts())
421 self.assertEqual(set(), self.c.get_partially_configured_hosts())
422 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
423
424 def test_analysis(self):
425 self.mock_hosts_creds([
426 ('.googlesource.com', 'git-example.chromium.org'),
427
428 ('chromium', 'git-example.google.com'),
429 ('chromium-review', 'git-example.google.com'),
430 ('chrome-internal', 'git-example.chromium.org'),
431 ('chrome-internal-review', 'git-example.chromium.org'),
432 ('conflict', 'git-example.google.com'),
433 ('conflict-review', 'git-example.chromium.org'),
434 ('dup', 'git-example.google.com'),
435 ('dup', 'git-example.google.com'),
436 ('dup-review', 'git-example.google.com'),
437 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200438 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100439 ])
440 self.assertTrue(self.c.has_generic_host())
441 self.assertEqual(set(['conflict.googlesource.com']),
442 self.c.get_conflicting_hosts())
443 self.assertEqual(set(['dup.googlesource.com']),
444 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200445 self.assertEqual(set(['partial.googlesource.com',
446 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100447 self.c.get_partially_configured_hosts())
448 self.assertEqual(set(['chromium.googlesource.com',
449 'chrome-internal.googlesource.com']),
450 self.c.get_hosts_with_wrong_identities())
451
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100452 def test_report_no_problems(self):
453 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100454 self.assertFalse(self.c.find_and_report_problems())
455 self.assertEqual(sys.stdout.getvalue(), '')
456
Edward Lemurda4b6c62020-02-13 00:28:40 +0000457 @mock.patch(
458 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000459 return_value=os.path.join('~', '.gitcookies'))
Edward Lemurda4b6c62020-02-13 00:28:40 +0000460 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100461 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100462 self.assertTrue(self.c.find_and_report_problems())
463 with open(os.path.join(os.path.dirname(__file__),
464 'git_cl_creds_check_report.txt')) as f:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000465 expected = f.read() % {
466 'sep': os.sep,
467 }
468
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100469 def by_line(text):
470 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700471 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200472 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100473
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800474
Edward Lemurda4b6c62020-02-13 00:28:40 +0000475class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000476 def setUp(self):
477 super(TestGitCl, self).setUp()
478 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700479 self._calls_done = []
Edward Lesmes0dd54822020-03-26 18:24:25 +0000480 self.failed = False
Edward Lemurda4b6c62020-02-13 00:28:40 +0000481 mock.patch('sys.stdout', StringIO()).start()
482 mock.patch(
483 'git_cl.time_time',
484 lambda: self._mocked_call('time.time')).start()
485 mock.patch(
486 'git_cl.metrics.collector.add_repeated',
487 lambda *a: self._mocked_call('add_repeated', *a)).start()
488 mock.patch('subprocess2.call', self._mocked_call).start()
489 mock.patch('subprocess2.check_call', self._mocked_call).start()
490 mock.patch('subprocess2.check_output', self._mocked_call).start()
491 mock.patch(
492 'subprocess2.communicate',
493 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
494 mock.patch(
495 'git_cl.gclient_utils.CheckCallAndFilter',
496 self._mocked_call).start()
497 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
498 mock.patch(
499 'git_common.get_or_create_merge_base',
500 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000501 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
502 mock.patch(
503 'git_cl.SaveDescriptionBackup',
504 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
505 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000506 'git_cl.write_json',
507 lambda *a: self._mocked_call('write_json', *a)).start()
508 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000509 'git_cl.Changelist.RunHook',
510 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000511 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
512 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000513 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000514 mock.patch(
515 'git_cl.gerrit_util.GetChangeComments',
516 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
517 mock.patch(
518 'git_cl.gerrit_util.GetChangeRobotComments',
519 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
520 mock.patch(
521 'git_cl.gerrit_util.AddReviewers',
522 lambda *a: self._mocked_call('AddReviewers', *a)).start()
523 mock.patch(
524 'git_cl.gerrit_util.SetReview',
525 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
526 self._mocked_call(
527 'SetReview', h, i, msg, labels, notify, ready))).start()
528 mock.patch(
529 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
530 return_value=False).start()
531 mock.patch(
532 'git_cl.gerrit_util.GceAuthenticator.is_gce',
533 return_value=False).start()
534 mock.patch(
535 'git_cl.gerrit_util.ValidAccounts',
536 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000537 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000538 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000539 self.mockGit = GitMocks()
540 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
541 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
Edward Lesmes50da7702020-03-30 19:23:43 +0000542 mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
543 mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
Edward Lemur85153282020-02-14 22:06:29 +0000544 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000545 mock.patch(
546 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000547 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000548 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000549 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000550 mock.patch(
551 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000552 # It's important to reset settings to not have inter-tests interference.
553 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000554 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000555
556 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000557 try:
Edward Lesmes0dd54822020-03-26 18:24:25 +0000558 if not self.failed:
559 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100560 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000561 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
562 if len(self.calls) > 5:
563 calls += ' ...\n'
564 self.fail(
565 '\n'
566 'There are un-consumed calls after this test has finished:\n' +
567 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000568 finally:
569 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000570
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000571 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000572 self.assertTrue(
573 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700574 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000575 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000576 expected_args, result = top
577
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000578 # Also logs otherwise it could get caught in a try/finally and be hard to
579 # diagnose.
580 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700581 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000582 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700583 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
584 for i, c in enumerate(self._calls_done[-N:]))
585 following_calls = '\n '.join(
586 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
587 for i, c in enumerate(self.calls[:N]))
588 extended_msg = (
589 'A few prior calls:\n %s\n\n'
590 'This (expected):\n @%d: %r\n'
591 'This (actual):\n @%d: %r\n\n'
592 'A few following expected calls:\n %s' %
593 (prior_calls, len(self._calls_done), expected_args,
594 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700595
Edward Lesmes0dd54822020-03-26 18:24:25 +0000596 self.failed = True
tandrii99a72f22016-08-17 14:33:24 -0700597 self.fail('@%d\n'
598 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000599 ' Actual: %r\n'
600 '\n'
601 '%s' % (
602 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700603
604 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700605 if isinstance(result, Exception):
606 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000607 # stdout from git commands is supposed to be a bytestream. Convert it here
608 # instead of converting all test output in this file to bytes.
609 if args[0][0] == 'git' and not isinstance(result, bytes):
610 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000611 return result
612
Edward Lemur1a83da12020-03-04 21:18:36 +0000613 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
614 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100615 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100616 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000617 self.assertEqual(
618 'prompt [Yes/No]: Please, type yes or no: ',
619 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100620
tandrii48df5812016-10-17 03:55:37 -0700621 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000622 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700623 self.calls = [
624 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700625 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
626 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
627 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
628 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700629 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
630 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700631 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
632 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000633 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
634 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700635 ((['git', 'config', 'gerrit.host', 'true'],), ''),
636 ]
637 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
638
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000639 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100640 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200641 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000642 custom_cl_base=None, short_hostname='chromium',
643 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000644 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200645 if custom_cl_base:
646 ancestor_revision = custom_cl_base
647 else:
648 # Determine ancestor_revision to be merge base.
649 ancestor_revision = 'fake_ancestor_sha'
650 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000651 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
652 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200653 ]
654
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100655 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000656 gerrit_util.GetChangeDetail.return_value = {
657 'owner': {'email': (other_cl_owner or 'owner@example.com')},
658 'change_id': (change_id or '123456789'),
659 'current_revision': 'sha1_of_current_revision',
660 'revisions': {'sha1_of_current_revision': {
661 'commit': {'message': fetched_description},
662 }},
663 'status': fetched_status or 'NEW',
664 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100665 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100666 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100667 if other_cl_owner:
668 calls += [
669 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
670 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100671
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100672 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200673 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
674 ([custom_cl_base] if custom_cl_base else
675 [ancestor_revision, 'HEAD']),),
676 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100677 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000678
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100679 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000680
Edward Lemur26964072020-02-19 19:18:51 +0000681 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700682 squash_mode='default',
Aaron Gablefd238082017-06-07 13:42:34 -0700683 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100684 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000685 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000686 short_hostname='chromium',
Edward Lemur5a644f82020-03-18 16:44:57 +0000687 labels=None, change_id=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000688 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000689 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000690 if post_amend_description is None:
691 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700692 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200693
694 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000695
Edward Lemur26964072020-02-19 19:18:51 +0000696 if squash_mode in ('override_squash', 'override_nosquash'):
697 self.mockGit.config['gerrit.override-squash-uploads'] = (
698 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700699
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000700 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000701 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200702 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200703 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000704 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000705 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000706 calls += [
707 ((['RunEditor'],), description),
708 ]
Josipe827b0f2020-01-30 00:07:20 +0000709 # user wants to edit description
710 if edit_description:
711 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000712 ((['RunEditor'],), edit_description),
713 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000714 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200715
716 if custom_cl_base is None:
717 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000718 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000719 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200720 ]
721 parent = 'origin/master'
722 else:
723 calls += [
724 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
725 'refs/remotes/origin/master'],),
726 callError(1)), # Means not ancenstor.
727 (('ask_for_data',
728 'Do you take responsibility for cleaning up potential mess '
729 'resulting from proceeding with upload? Press Enter to upload, '
730 'or Ctrl+C to abort'), ''),
731 ]
732 parent = custom_cl_base
733
734 calls += [
735 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
736 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000737 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200738 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000739 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200740 ref_to_push),
741 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000742 else:
743 ref_to_push = 'HEAD'
Edward Lemur5a644f82020-03-18 16:44:57 +0000744 parent = 'origin/refs/heads/master'
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000745
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000746 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000747 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000748 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200749 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000750
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000751 metrics_arguments = []
752
Aaron Gableafd52772017-06-27 16:40:10 -0700753 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700754 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000755 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700756 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400757 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700758 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000759 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700760 else:
761 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000762 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800763
Edward Lemur5a644f82020-03-18 16:44:57 +0000764 # If issue is given, then description is fetched from Gerrit instead.
765 if issue is None:
766 if squash:
767 title = 'Initial upload'
768 else:
769 if not title:
770 calls += [
771 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
772 (('ask_for_data', 'Title for patchset []: '), 'User input'),
773 ]
774 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700775 if title:
Edward Lemur5a644f82020-03-18 16:44:57 +0000776 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000777 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000778
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000779 if short_hostname == 'chromium':
780 # All reviwers and ccs get into ref_suffix.
781 for r in sorted(reviewers):
782 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000783 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000784 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000785 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000786 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000787 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000788 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000789 reviewers, cc = [], []
790 else:
791 # TODO(crbug/877717): remove this case.
792 calls += [
793 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
794 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000795 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000796 {
797 e: {'email': e}
798 for e in (reviewers + ['joe@example.com'] + cc)
799 })
800 ]
801 for r in sorted(reviewers):
802 if r != 'bad-account-or-email':
803 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000804 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000805 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000806 if issue is None:
807 cc += ['joe@example.com']
808 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000809 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000810 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000811 if c in cc:
812 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000813
Edward Lemur687ca902018-12-05 02:30:30 +0000814 for k, v in sorted((labels or {}).items()):
815 ref_suffix += ',l=%s+%d' % (k, v)
816 metrics_arguments.append('l=%s+%d' % (k, v))
817
818 if tbr:
819 calls += [
820 (('GetCodeReviewTbrScore',
821 '%s-review.googlesource.com' % short_hostname,
822 'my/repo'),
823 2,),
824 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000825
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000826 calls += [
827 (('time.time',), 1000,),
828 ((['git', 'push',
829 'https://%s.googlesource.com/my/repo' % short_hostname,
830 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
831 (('remote:\n'
832 'remote: Processing changes: (\)\n'
833 'remote: Processing changes: (|)\n'
834 'remote: Processing changes: (/)\n'
835 'remote: Processing changes: (-)\n'
836 'remote: Processing changes: new: 1 (/)\n'
837 'remote: Processing changes: new: 1, done\n'
838 'remote:\n'
839 'remote: New Changes:\n'
840 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
841 ' XXX\n'
842 'remote:\n'
843 'To https://%s.googlesource.com/my/repo\n'
844 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
845 ) % (short_hostname, short_hostname)),),
846 (('time.time',), 2000,),
847 (('add_repeated',
848 'sub_commands',
849 {
850 'execution_time': 1000,
851 'command': 'git push',
852 'exit_code': 0,
853 'arguments': sorted(metrics_arguments),
854 }),
855 None,),
856 ]
857
Edward Lemur1b52d872019-05-09 21:12:12 +0000858 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000859
860 date_format = ('03/16/17 20:00:41'
861 if sys.platform == 'win32' and sys.version_info.major == 2
862 else 'Thu Mar 16 20:00:41 2017')
863 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
864
Edward Lemur1b52d872019-05-09 21:12:12 +0000865 # Trace-related calls
866 calls += [
867 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000868 (
869 ([
870 'FileWrite', trace_name + '-README',
871 '%(date)s\n'
872 '%(short_hostname)s-review.googlesource.com\n'
873 '%(change_id)s\n'
874 '%(title)s\n'
875 '%(description)s\n'
876 '1000\n'
877 '0\n'
878 '%(trace_name)s' % {
879 'date': date_format,
880 'short_hostname': short_hostname,
881 'change_id': change_id,
882 'description': final_description,
883 'title': title or '<untitled>',
884 'trace_name': trace_name,
885 }
886 ], ),
887 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000888 ),
889 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000890 (
891 (['os.path.isfile',
892 os.path.join('TEMP_DIR', 'trace-packet')], ),
893 True,
Edward Lemur1b52d872019-05-09 21:12:12 +0000894 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000895 (
896 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
897 ('git-hash: 0123456789012345678901234567890123456789\n'
898 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +0000899 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000900 (
901 ([
902 'FileWrite',
903 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
904 'git-hash: abcdea\n'
905 ], ),
906 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000907 ),
908 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000909 (
910 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
911 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000912 ),
913 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000914 (
915 (['git', 'config', '-l'], ),
916 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +0000917 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000918 (
919 ([
920 'FileWrite',
921 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
922 ], ),
923 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000924 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000925 (
926 (['os.path.isfile',
927 os.path.join('~', '.gitcookies')], ),
928 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +0000929 ),
930 ]
931 if gitcookies_exists:
932 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000933 (
934 (['FileRead', os.path.join('~', '.gitcookies')], ),
935 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +0000936 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000937 (
938 ([
939 'FileWrite',
940 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
941 ], ),
942 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000943 ),
944 ]
945 calls += [
946 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000947 (
948 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
949 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000950 ),
951 ]
952
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000953 # TODO(crbug/877717): this should never be used.
954 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000955 calls += [
956 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +0000957 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000958 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +0000959 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +0000960 notify),
961 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000962 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000963 return calls
964
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000965 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000966 self,
967 upload_args,
968 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000969 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700970 squash=True,
971 squash_mode=None,
Aaron Gable9b713dd2016-12-14 16:04:21 -0800972 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000973 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000974 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -0700975 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100976 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100977 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200978 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -0700979 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000980 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000981 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000982 labels=None,
983 change_id=None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000984 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000985 gitcookies_exists=True,
986 force=False,
Edward Lesmes0dd54822020-03-26 18:24:25 +0000987 log_description=None,
Josipe827b0f2020-01-30 00:07:20 +0000988 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000989 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000990 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700991 if squash_mode is None:
992 if '--no-squash' in upload_args:
993 squash_mode = 'nosquash'
994 elif '--squash' in upload_args:
995 squash_mode = 'squash'
996 else:
997 squash_mode = 'default'
998
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000999 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001000 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001001 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001002 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001003 same_auth=('git-owner.example.com', '', 'pass'))).start()
1004 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1005 lambda _, offer_removal: None).start()
1006 mock.patch('git_cl.gclient_utils.RunEditor',
1007 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1008 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1009 'DownloadGerritHook', force)).start()
1010 mock.patch('git_cl.gclient_utils.FileRead',
1011 lambda path: self._mocked_call(['FileRead', path])).start()
1012 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001013 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001014 ['FileWrite', path, contents])).start()
1015 mock.patch('git_cl.datetime_now',
1016 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1017 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1018 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1019 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001020 '%(now)s\n'
1021 '%(gerrit_host)s\n'
1022 '%(change_id)s\n'
1023 '%(title)s\n'
1024 '%(description)s\n'
1025 '%(execution_time)s\n'
1026 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001027 '%(trace_name)s').start()
1028 mock.patch('git_cl.shutil.make_archive',
1029 lambda *args: self._mocked_call(['make_archive'] +
1030 list(args))).start()
1031 mock.patch('os.path.isfile',
1032 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001033 mock.patch(
Edward Lesmes0dd54822020-03-26 18:24:25 +00001034 'git_cl._create_description_from_log',
1035 return_value=log_description or description).start()
Edward Lemura12175c2020-03-09 16:58:26 +00001036 mock.patch(
1037 'git_cl.Changelist._AddChangeIdToCommitMessage',
1038 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001039 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001040 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1041 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001042 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001043 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001044
Edward Lemur26964072020-02-19 19:18:51 +00001045 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001046 self.mockGit.config['branch.master.gerritissue'] = (
1047 str(issue) if issue else None)
1048 self.mockGit.config['remote.origin.url'] = (
1049 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001050 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001051
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001052 self.calls = self._gerrit_base_calls(
1053 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001054 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001055 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001056 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001057 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001058 short_hostname=short_hostname,
1059 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001060 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001061 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001062 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001063 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001064 self.calls += self._gerrit_upload_calls(
1065 description, reviewers, squash,
1066 squash_mode=squash_mode,
Aaron Gablefd238082017-06-07 13:42:34 -07001067 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001068 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001069 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001070 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001071 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001072 labels=labels,
1073 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001074 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001075 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001076 force=force,
1077 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001078 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001079 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001080 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001081 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001082 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001083 self.assertEqual(
1084 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001085 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001086
Edward Lemur1b52d872019-05-09 21:12:12 +00001087 def test_gerrit_upload_traces_no_gitcookies(self):
1088 self._run_gerrit_upload_test(
1089 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001090 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001091 [],
1092 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001093 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001094 change_id='Ixxx',
1095 gitcookies_exists=False)
1096
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001097 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001098 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001099 [],
1100 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1101 [],
1102 change_id='Ixxx')
1103
1104 def test_gerrit_upload_without_change_id_nosquash(self):
1105 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001106 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001107 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001108 [],
1109 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001110 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001111 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001112
1113 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001114 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001115 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001116 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001117 [],
tandriia60502f2016-06-20 02:01:53 -07001118 squash=False,
1119 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001120 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001121 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001122
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001123 def test_gerrit_no_reviewer(self):
1124 self._run_gerrit_upload_test(
1125 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001126 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001127 [],
1128 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001129 squash_mode='override_nosquash',
1130 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001131
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001132 def test_gerrit_no_reviewer_non_chromium_host(self):
1133 # TODO(crbug/877717): remove this test case.
1134 self._run_gerrit_upload_test(
1135 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001136 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001137 [],
1138 squash=False,
1139 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001140 short_hostname='other',
1141 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001142
Edward Lesmes0dd54822020-03-26 18:24:25 +00001143 def test_gerrit_patchset_title_special_chars_nosquash(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001144 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001145 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001146 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001147 squash=False,
1148 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001149 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001150 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001151
ukai@chromium.orge8077812012-02-03 03:41:46 +00001152 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001153 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001154 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001155 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001156 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001157 squash=False,
1158 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001159 notify=True,
1160 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001161 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001162 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001163
Anthony Polito8b955342019-09-24 19:01:36 +00001164 def test_gerrit_upload_force_sets_bug(self):
1165 self._run_gerrit_upload_test(
1166 ['-b', '10000', '-f'],
1167 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1168 [],
1169 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001170 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001171 change_id='Ixxx')
1172
Edward Lemur5fb22242020-03-12 22:05:13 +00001173 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001174 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001175 ['-b', '10000', '-m', 'Title', '--edit-description'],
1176 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001177 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001178 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001179 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001180 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001181 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001182 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001183
Dan Beamd8b04ca2019-10-10 21:23:26 +00001184 def test_gerrit_upload_force_sets_fixed(self):
1185 self._run_gerrit_upload_test(
1186 ['-x', '10000', '-f'],
1187 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1188 [],
1189 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001190 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001191 change_id='Ixxx')
1192
ukai@chromium.orge8077812012-02-03 03:41:46 +00001193 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001194 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1195 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001196 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001197 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001198 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001199 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001200 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001201 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001202 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001203 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001204 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001205 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001206
1207 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001208 self._run_gerrit_upload_test(
1209 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001210 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001211 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001212 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001213
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001214 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001215 self._run_gerrit_upload_test(
1216 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001217 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001218 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001219 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001220 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001221
Edward Lesmes0dd54822020-03-26 18:24:25 +00001222 def test_gerrit_upload_squash_first_title(self):
1223 self._run_gerrit_upload_test(
1224 ['-f', '-t', 'title'],
1225 'title\n\ndesc\n\nChange-Id: 123456789',
1226 [],
1227 force=True,
1228 squash=True,
1229 log_description='desc',
1230 change_id='123456789')
1231
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001232 def test_gerrit_upload_squash_first_with_labels(self):
1233 self._run_gerrit_upload_test(
1234 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001235 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001236 [],
1237 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001238 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001239 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001240
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001241 def test_gerrit_upload_squash_first_against_rev(self):
1242 custom_cl_base = 'custom_cl_base_rev_or_branch'
1243 self._run_gerrit_upload_test(
1244 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001245 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001246 [],
1247 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001248 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001249 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001250 self.assertIn(
1251 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1252 sys.stdout.getvalue())
1253
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001254 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001255 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001256 self._run_gerrit_upload_test(
1257 ['--squash'],
1258 description,
1259 [],
1260 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001261 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001262 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001263
Edward Lemurd55c5072020-02-20 01:09:07 +00001264 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001265 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001266 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001267 with self.assertRaises(SystemExitMock):
1268 self._run_gerrit_upload_test(
1269 ['--squash'],
1270 description,
1271 [],
1272 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001273 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001274 fetched_status='ABANDONED',
1275 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001276 self.assertEqual(
1277 'Change https://chromium-review.googlesource.com/123456 has been '
1278 'abandoned, new uploads are not allowed\n',
1279 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001280
Edward Lemurda4b6c62020-02-13 00:28:40 +00001281 @mock.patch(
1282 'gerrit_util.GetAccountDetails',
1283 return_value={'email': 'yet-another@example.com'})
1284 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001285 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001286 self._run_gerrit_upload_test(
1287 ['--squash'],
1288 description,
1289 [],
1290 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001291 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001292 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001293 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001294 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001295 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001296 'authenticate to Gerrit as yet-another@example.com.\n'
1297 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001298 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001299
Josipe827b0f2020-01-30 00:07:20 +00001300 def test_upload_change_description_editor(self):
1301 fetched_description = 'foo\n\nChange-Id: 123456789'
1302 description = 'bar\n\nChange-Id: 123456789'
1303 self._run_gerrit_upload_test(
1304 ['--squash', '--edit-description'],
1305 description,
1306 [],
1307 fetched_description=fetched_description,
1308 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001309 issue=123456,
1310 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001311 edit_description=description)
1312
Edward Lemurda4b6c62020-02-13 00:28:40 +00001313 @mock.patch('git_cl.RunGit')
1314 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001315 @mock.patch('sys.stdin', StringIO('\n'))
1316 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001317 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001318 def mock_run_git(*args, **_kwargs):
1319 if args[0] == ['for-each-ref',
1320 '--format=%(refname:short) %(upstream:short)',
1321 'refs/heads']:
1322 # Create a local branch dependency tree that looks like this:
1323 # test1 -> test2 -> test3 -> test4 -> test5
1324 # -> test3.1
1325 # test6 -> test0
1326 branch_deps = [
1327 'test2 test1', # test1 -> test2
1328 'test3 test2', # test2 -> test3
1329 'test3.1 test2', # test2 -> test3.1
1330 'test4 test3', # test3 -> test4
1331 'test5 test4', # test4 -> test5
1332 'test6 test0', # test0 -> test6
1333 'test7', # test7
1334 ]
1335 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001336 git_cl.RunGit.side_effect = mock_run_git
1337 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001338
1339 class MockChangelist():
1340 def __init__(self):
1341 pass
1342 def GetBranch(self):
1343 return 'test1'
1344 def GetIssue(self):
1345 return '123'
1346 def GetPatchset(self):
1347 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001348 def IsGerrit(self):
1349 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001350
1351 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1352 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001353 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001354 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001355 'This command will checkout all dependent branches '
1356 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001357 'or Ctrl+C to abort',
1358 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001359 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001360
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001361 def test_gerrit_change_id(self):
1362 self.calls = [
1363 ((['git', 'write-tree'], ),
1364 'hashtree'),
1365 ((['git', 'rev-parse', 'HEAD~0'], ),
1366 'branch-parent'),
1367 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1368 'A B <a@b.org> 1456848326 +0100'),
1369 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1370 'C D <c@d.org> 1456858326 +0100'),
1371 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1372 'hashchange'),
1373 ]
1374 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1375 self.assertEqual(change_id, 'Ihashchange')
1376
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001377 def test_desecription_append_footer(self):
1378 for init_desc, footer_line, expected_desc in [
1379 # Use unique desc first lines for easy test failure identification.
1380 ('foo', 'R=one', 'foo\n\nR=one'),
1381 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1382 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1383 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1384 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1385 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1386 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1387 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1388 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1389 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1390 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1391 ]:
1392 desc = git_cl.ChangeDescription(init_desc)
1393 desc.append_footer(footer_line)
1394 self.assertEqual(desc.description, expected_desc)
1395
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001396 def test_update_reviewers(self):
1397 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001398 ('foo', [], [],
1399 'foo'),
1400 ('foo\nR=xx', [], [],
1401 'foo\nR=xx'),
1402 ('foo\nTBR=xx', [], [],
1403 'foo\nTBR=xx'),
1404 ('foo', ['a@c'], [],
1405 'foo\n\nR=a@c'),
1406 ('foo\nR=xx', ['a@c'], [],
1407 'foo\n\nR=a@c, xx'),
1408 ('foo\nTBR=xx', ['a@c'], [],
1409 'foo\n\nR=a@c\nTBR=xx'),
1410 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1411 'foo\n\nR=a@c, yy\nTBR=xx'),
1412 ('foo\nBUG=', ['a@c'], [],
1413 'foo\nBUG=\nR=a@c'),
1414 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1415 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1416 ('foo', ['a@c', 'b@c'], [],
1417 'foo\n\nR=a@c, b@c'),
1418 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1419 'foo\nBar\n\nR=c@c\nBUG='),
1420 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1421 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001422 # Same as the line before, but full of whitespaces.
1423 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001424 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001425 'foo\nBar\n\nR=c@c\n BUG =',
1426 ),
1427 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001428 ('foo BUG=allo R=joe ', ['c@c'], [],
1429 'foo BUG=allo R=joe\n\nR=c@c'),
1430 # Redundant TBRs get promoted to Rs
1431 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1432 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001433 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001434 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001435 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001436 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001437 obj = git_cl.ChangeDescription(orig)
Edward Lemur2c62b332020-03-12 22:12:33 +00001438 obj.update_reviewers(reviewers, tbrs, None, None, None)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001439 actual.append(obj.description)
1440 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001441
Nodir Turakulov23b82142017-11-16 11:04:25 -08001442 def test_get_hash_tags(self):
1443 cases = [
1444 ('', []),
1445 ('a', []),
1446 ('[a]', ['a']),
1447 ('[aa]', ['aa']),
1448 ('[a ]', ['a']),
1449 ('[a- ]', ['a']),
1450 ('[a- b]', ['a-b']),
1451 ('[a--b]', ['a-b']),
1452 ('[a', []),
1453 ('[a]x', ['a']),
1454 ('[aa]x', ['aa']),
1455 ('[a b]', ['a-b']),
1456 ('[a b]', ['a-b']),
1457 ('[a__b]', ['a-b']),
1458 ('[a] x', ['a']),
1459 ('[a][b]', ['a', 'b']),
1460 ('[a] [b]', ['a', 'b']),
1461 ('[a][b]x', ['a', 'b']),
1462 ('[a][b] x', ['a', 'b']),
1463 ('[a]\n[b]', ['a']),
1464 ('[a\nb]', []),
1465 ('[a][', ['a']),
1466 ('Revert "[a] feature"', ['a']),
1467 ('Reland "[a] feature"', ['a']),
1468 ('Revert: [a] feature', ['a']),
1469 ('Reland: [a] feature', ['a']),
1470 ('Revert "Reland: [a] feature"', ['a']),
1471 ('Foo: feature', ['foo']),
1472 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001473 ('Change Foo::Bar', []),
1474 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001475 ('Revert "Foo bar: feature"', ['foo-bar']),
1476 ('Reland "Foo bar: feature"', ['foo-bar']),
1477 ]
1478 for desc, expected in cases:
1479 change_desc = git_cl.ChangeDescription(desc)
1480 actual = change_desc.get_hash_tags()
1481 self.assertEqual(
1482 actual,
1483 expected,
1484 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1485
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001486 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001487 self.assertEqual(None, git_cl.GetTargetRef(None,
1488 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001489 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001490
wittman@chromium.org455dc922015-01-26 20:15:50 +00001491 # Check default target refs for branches.
1492 self.assertEqual('refs/heads/master',
1493 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001494 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001495 self.assertEqual('refs/heads/master',
1496 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001497 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001498 self.assertEqual('refs/heads/master',
1499 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001500 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001501 self.assertEqual('refs/branch-heads/123',
1502 git_cl.GetTargetRef('origin',
1503 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001504 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001505 self.assertEqual('refs/diff/test',
1506 git_cl.GetTargetRef('origin',
1507 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001508 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001509 self.assertEqual('refs/heads/chrome/m42',
1510 git_cl.GetTargetRef('origin',
1511 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001512 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001513
1514 # Check target refs for user-specified target branch.
1515 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1516 'refs/remotes/branch-heads/123'):
1517 self.assertEqual('refs/branch-heads/123',
1518 git_cl.GetTargetRef('origin',
1519 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001520 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001521 for branch in ('origin/master', 'remotes/origin/master',
1522 'refs/remotes/origin/master'):
1523 self.assertEqual('refs/heads/master',
1524 git_cl.GetTargetRef('origin',
1525 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001526 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001527 for branch in ('master', 'heads/master', 'refs/heads/master'):
1528 self.assertEqual('refs/heads/master',
1529 git_cl.GetTargetRef('origin',
1530 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001531 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001532
Edward Lemurda4b6c62020-02-13 00:28:40 +00001533 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1534 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001535 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001536 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1537
Edward Lemur85153282020-02-14 22:06:29 +00001538 def assertIssueAndPatchset(
1539 self, branch='master', issue='123456', patchset='7',
1540 git_short_host='chromium'):
1541 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001542 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001543 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001544 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001545 self.assertEqual(
1546 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001547 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001548
Edward Lemur85153282020-02-14 22:06:29 +00001549 def _patch_common(self, git_short_host='chromium'):
Edward Lesmes50da7702020-03-30 19:23:43 +00001550 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001551 self.mockGit.config['remote.origin.url'] = (
1552 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001553 gerrit_util.GetChangeDetail.return_value = {
1554 'current_revision': '7777777777',
1555 'revisions': {
1556 '1111111111': {
1557 '_number': 1,
1558 'fetch': {'http': {
1559 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1560 'ref': 'refs/changes/56/123456/1',
1561 }},
1562 },
1563 '7777777777': {
1564 '_number': 7,
1565 'fetch': {'http': {
1566 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1567 'ref': 'refs/changes/56/123456/7',
1568 }},
1569 },
1570 },
1571 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001572
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001573 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001574 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001575 self.calls += [
1576 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1577 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001578 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001579 ]
1580 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001581 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001582
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001583 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001584 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001585 self.calls += [
1586 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1587 'refs/changes/56/123456/7'],), ''),
1588 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001589 ]
Edward Lemur85153282020-02-14 22:06:29 +00001590 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1591 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001592
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001593 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001594 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001595 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001596 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001597 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001598 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001599 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001600 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001601 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001602
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001603 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001604 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001605 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001606 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001607 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001608 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001609 ]
1610 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001611 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001612 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001613
Aaron Gable697a91b2018-01-19 15:20:15 -08001614 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001615 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001616 self.calls += [
1617 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1618 'refs/changes/56/123456/1'],), ''),
1619 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001620 ]
1621 self.assertEqual(git_cl.main(
1622 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1623 0)
Edward Lemur85153282020-02-14 22:06:29 +00001624 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001625
Edward Lemurd55c5072020-02-20 01:09:07 +00001626 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001627 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001628 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001629 self.calls += [
1630 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001631 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001632 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001633 ]
1634 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001635 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001636 self.assertEqual(
1637 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1638 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001639
Edward Lemurda4b6c62020-02-13 00:28:40 +00001640 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001641 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001642 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001643 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001644 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001645 self.mockGit.config['remote.origin.url'] = (
1646 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001647 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001648 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001649 self.assertEqual(
1650 'change 123456 at https://chromium-review.googlesource.com does not '
1651 'exist or you have no access to it\n',
1652 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001653
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001654 def _checkout_calls(self):
1655 return [
1656 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001657 'branch\\..*\\.gerritissue'], ),
1658 ('branch.ger-branch.gerritissue 123456\n'
1659 'branch.gbranch654.gerritissue 654321\n')),
1660 ]
1661
1662 def test_checkout_gerrit(self):
1663 """Tests git cl checkout <issue>."""
1664 self.calls = self._checkout_calls()
1665 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1666 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1667
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001668 def test_checkout_not_found(self):
1669 """Tests git cl checkout <issue>."""
1670 self.calls = self._checkout_calls()
1671 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1672
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001673 def test_checkout_no_branch_issues(self):
1674 """Tests git cl checkout <issue>."""
1675 self.calls = [
1676 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001677 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001678 ]
1679 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1680
Edward Lemur26964072020-02-19 19:18:51 +00001681 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001682 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001683 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001684 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001685 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1686 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001687 self.mockGit.config['remote.origin.url'] = (
1688 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001689 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001690 cl.branch = 'master'
1691 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001692 return cl
1693
Edward Lemurd55c5072020-02-20 01:09:07 +00001694 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001695 def test_gerrit_ensure_authenticated_missing(self):
1696 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001697 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001698 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001699 with self.assertRaises(SystemExitMock):
1700 cl.EnsureAuthenticated(force=False)
1701 self.assertEqual(
1702 'Credentials for the following hosts are required:\n'
1703 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001704 'These are read from ~%(sep)s.gitcookies '
1705 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001706 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001707 'https://chromium-review.googlesource.com/new-password\n' % {
1708 'sep': os.sep,
1709 'netrc': NETRC_FILENAME,
1710 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001711
1712 def test_gerrit_ensure_authenticated_conflict(self):
1713 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001714 'chromium.googlesource.com':
1715 ('git-one.example.com', None, 'secret1'),
1716 'chromium-review.googlesource.com':
1717 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001718 })
1719 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001720 (('ask_for_data', 'If you know what you are doing '
1721 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001722 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1723
1724 def test_gerrit_ensure_authenticated_ok(self):
1725 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001726 'chromium.googlesource.com':
1727 ('git-same.example.com', None, 'secret'),
1728 'chromium-review.googlesource.com':
1729 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001730 })
1731 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1732
tandrii@chromium.org28253532016-04-14 13:46:56 +00001733 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001734 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1735 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001736 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1737
Eric Boren2fb63102018-10-05 13:05:03 +00001738 def test_gerrit_ensure_authenticated_bearer_token(self):
1739 cl = self._test_gerrit_ensure_authenticated_common(auth={
1740 'chromium.googlesource.com':
1741 ('', None, 'secret'),
1742 'chromium-review.googlesource.com':
1743 ('', None, 'secret'),
1744 })
1745 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1746 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1747 'chromium.googlesource.com')
1748 self.assertTrue('Bearer' in header)
1749
Daniel Chengcf6269b2019-05-18 01:02:12 +00001750 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001751 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001752 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001753 (('logging.warning',
1754 'Ignoring branch %(branch)s with non-https remote '
1755 '%(remote)s', {
1756 'branch': 'master',
1757 'remote': 'custom-scheme://repo'}
1758 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001759 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001760 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1761 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1762 mock.patch('logging.warning',
1763 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001764 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001765 cl.branch = 'master'
1766 cl.branchref = 'refs/heads/master'
1767 cl.lookedup_issue = True
1768 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1769
Florian Mayerae510e82020-01-30 21:04:48 +00001770 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001771 self.mockGit.config['remote.origin.url'] = (
1772 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001773 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001774 (('logging.error',
1775 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1776 'but it doesn\'t exist.', {
1777 'remote': 'origin',
1778 'branch': 'master',
1779 'url': 'git@somehost.example:foo/bar.git'}
1780 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001781 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001782 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1783 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1784 mock.patch('logging.error',
1785 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001786 cl = git_cl.Changelist()
1787 cl.branch = 'master'
1788 cl.branchref = 'refs/heads/master'
1789 cl.lookedup_issue = True
1790 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1791
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001792 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001793 self.mockGit.config['branch.master.gerritissue'] = '123'
1794 self.mockGit.config['branch.master.gerritserver'] = (
1795 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001796 self.mockGit.config['remote.origin.url'] = (
1797 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001798 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001799 (('SetReview', 'chromium-review.googlesource.com',
1800 'infra%2Finfra~123', None,
1801 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001802 ]
tandriid9e5ce52016-07-13 02:32:59 -07001803
1804 def test_cmd_set_commit_gerrit_clear(self):
1805 self._cmd_set_commit_gerrit_common(0)
1806 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1807
1808 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001809 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001810 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1811
tandriid9e5ce52016-07-13 02:32:59 -07001812 def test_cmd_set_commit_gerrit(self):
1813 self._cmd_set_commit_gerrit_common(2)
1814 self.assertEqual(0, git_cl.main(['set-commit']))
1815
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001816 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001817 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001818 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001819
1820 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001821 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001822
Edward Lemurda4b6c62020-02-13 00:28:40 +00001823 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001824 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001825 try:
1826 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001827 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001828 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001829 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001830
1831 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001832 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001833 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001834 return 'foobar'
1835
Edward Lemurda4b6c62020-02-13 00:28:40 +00001836 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001837 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001838 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001839 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001840 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001841
iannuccie53c9352016-08-17 14:40:40 -07001842 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001843
iannuccie53c9352016-08-17 14:40:40 -07001844 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001845 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001846 return 'foobar'
1847
Edward Lemurda4b6c62020-02-13 00:28:40 +00001848 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
1849 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07001850 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001851 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07001852
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001853 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00001854 self.mockGit.config['remote.origin.url'] = (
1855 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001856 gerrit_util.GetChangeDetail.return_value = {
1857 'current_revision': 'sha1',
1858 'revisions': {'sha1': {
1859 'commit': {'message': 'foobar'},
1860 }},
1861 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001862 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001863 'description',
1864 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
1865 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001866 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001867
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001868 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001869 mock.patch('git_cl.Changelist', ChangelistMock).start()
1870 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001871
1872 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1873 self.assertEqual('hihi', ChangelistMock.desc)
1874
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001875 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001876 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001877
1878 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001879 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001880 '# Enter a description of the change.\n'
1881 '# This will be displayed on the codereview site.\n'
1882 '# The first line will also be used as the subject of the review.\n'
1883 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001884 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07001885 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001886 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001887 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07001888 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001889
Edward Lemur6c6827c2020-02-06 21:15:18 +00001890 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001891 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001892
Edward Lemurda4b6c62020-02-13 00:28:40 +00001893 mock.patch('git_cl.Changelist.FetchDescription',
1894 lambda *args: current_desc).start()
1895 mock.patch('git_cl.Changelist.UpdateDescription',
1896 UpdateDescription).start()
1897 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001898
Edward Lemur85153282020-02-14 22:06:29 +00001899 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001900 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001901
Dan Beamd8b04ca2019-10-10 21:23:26 +00001902 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
1903 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
1904
1905 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001906 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00001907 '# Enter a description of the change.\n'
1908 '# This will be displayed on the codereview site.\n'
1909 '# The first line will also be used as the subject of the review.\n'
1910 '#--------------------This line is 72 characters long'
1911 '--------------------\n'
1912 'Some.\n\nFixed: 123\nChange-Id: xxx',
1913 desc)
1914 return desc
1915
Edward Lemurda4b6c62020-02-13 00:28:40 +00001916 mock.patch('git_cl.Changelist.FetchDescription',
1917 lambda *args: current_desc).start()
1918 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00001919
Edward Lemur85153282020-02-14 22:06:29 +00001920 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001921 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00001922
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001923 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001924 mock.patch('git_cl.Changelist', ChangelistMock).start()
1925 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001926
1927 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1928 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1929
kmarshall3bff56b2016-06-06 18:31:47 -07001930 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001931 self.calls = [
1932 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00001933 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001934 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001935 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00001936 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001937 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001938
Edward Lemurda4b6c62020-02-13 00:28:40 +00001939 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001940 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001941 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1942 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001943 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001944
1945 self.assertEqual(0, git_cl.main(['archive', '-f']))
1946
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001947 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001948 self.calls = [
1949 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1950 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1951 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
1952 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001953 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
1954 ((['git', 'branch', '-D', 'foo'],), '')
1955 ]
1956
Edward Lemurda4b6c62020-02-13 00:28:40 +00001957 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001958 lambda branches, fine_grained, max_processes:
1959 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1960 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001961 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001962
1963 self.assertEqual(0, git_cl.main(['archive', '-f']))
1964
kmarshall3bff56b2016-06-06 18:31:47 -07001965 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001966 self.calls = [
1967 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1968 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001969 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001970 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001971
Edward Lemurda4b6c62020-02-13 00:28:40 +00001972 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001973 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00001974 [(MockChangelistWithBranchAndIssue('master', 1),
1975 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001976
1977 self.assertEqual(1, git_cl.main(['archive', '-f']))
1978
1979 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001980 self.calls = [
1981 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1982 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001983 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001984 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001985
Edward Lemurda4b6c62020-02-13 00:28:40 +00001986 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001987 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001988 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1989 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001990 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001991
kmarshall9249e012016-08-23 12:02:16 -07001992 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
1993
1994 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001995 self.calls = [
1996 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1997 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001998 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001999 ((['git', 'branch', '-D', 'foo'],), '')
2000 ]
kmarshall9249e012016-08-23 12:02:16 -07002001
Edward Lemurda4b6c62020-02-13 00:28:40 +00002002 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002003 lambda branches, fine_grained, max_processes:
2004 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2005 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002006 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002007
2008 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002009
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002010 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002011 self.calls = [
2012 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2013 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2014 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002015 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2016 'refs/tags/git-cl-archived-456-foo'),
2017 ((['git', 'branch', '-D', 'foo'],), CERR1),
2018 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2019 'refs/tags/git-cl-archived-456-foo'),
2020 ]
2021
Edward Lemurda4b6c62020-02-13 00:28:40 +00002022 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002023 lambda branches, fine_grained, max_processes:
2024 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2025 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002026 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002027
2028 self.assertEqual(0, git_cl.main(['archive', '-f']))
2029
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00002030 def test_archive_with_format(self):
2031 self.calls = [
2032 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
2033 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2034 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
2035 ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
2036 ((['git', 'branch', '-D', 'foo'], ), ''),
2037 ]
2038
2039 mock.patch('git_cl.get_cl_statuses',
2040 lambda branches, fine_grained, max_processes:
2041 [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
2042
2043 self.assertEqual(
2044 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
2045
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002046 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002047 self.mockGit.config['branch.master.gerritissue'] = '123'
2048 self.mockGit.config['branch.master.gerritserver'] = (
2049 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002050 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002051 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002052 ]
2053 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002054 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2055 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002056
Aaron Gable400e9892017-07-12 15:31:21 -07002057 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002058 self.mockGit.config['branch.master.gerritissue'] = '123'
2059 self.mockGit.config['branch.master.gerritserver'] = (
2060 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002061 mock.patch('git_cl.Changelist.FetchDescription',
2062 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002063 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002064 ((['git', 'log', '-1', '--format=%B'],),
2065 'This is a description\n\nChange-Id: Ideadbeef'),
2066 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002067 ]
2068 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002069 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2070 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002071
phajdan.jre328cf92016-08-22 04:12:17 -07002072 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002073 self.mockGit.config['branch.master.gerritissue'] = '123'
2074 self.mockGit.config['branch.master.gerritserver'] = (
2075 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002076 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002077 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002078 {'issue': 123,
2079 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002080 ''),
2081 ]
2082 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2083
tandrii16e0b4e2016-06-07 10:34:28 -07002084 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002085 mock.patch(
2086 'git_cl.os.path.abspath',
2087 lambda path: self._mocked_call(['abspath', path])).start()
2088 mock.patch(
2089 'git_cl.os.path.exists',
2090 lambda path: self._mocked_call(['exists', path])).start()
2091 mock.patch(
2092 'git_cl.gclient_utils.FileRead',
2093 lambda path: self._mocked_call(['FileRead', path])).start()
2094 mock.patch(
2095 'git_cl.gclient_utils.rm_file_or_tree',
2096 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002097 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002098 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002099 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002100 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002101
2102 def test_GerritCommitMsgHookCheck_custom_hook(self):
2103 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002104 self.calls += [((['exists',
2105 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2106 ((['FileRead',
2107 os.path.join('.git', 'hooks', 'commit-msg')], ),
2108 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002109 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002110
2111 def test_GerritCommitMsgHookCheck_not_exists(self):
2112 cl = self._common_GerritCommitMsgHookCheck()
2113 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002114 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002115 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002116 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002117
2118 def test_GerritCommitMsgHookCheck(self):
2119 cl = self._common_GerritCommitMsgHookCheck()
2120 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002121 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2122 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002123 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002124 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002125 ((['rm_file_or_tree',
2126 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002127 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002128 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002129
tandriic4344b52016-08-29 06:04:54 -07002130 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002131 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2132 self.mockGit.config['branch.master.gerritserver'] = (
2133 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002134 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002135 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002136 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002137 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002138 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002139 'labels': {},
2140 'current_revision': 'deadbeaf',
2141 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002142 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002143 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002144 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002145 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2146 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002147 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002148 self.assertEqual(0, cl.CMDLand(force=True,
2149 bypass_hooks=True,
2150 verbose=True,
2151 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002152 self.assertIn(
2153 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002154 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002155 self.assertIn(
2156 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002157 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002158
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002159 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002160 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002161
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002162 def test_gerrit_change_detail_cache_simple(self):
2163 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002164 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002165 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002166 cl1._cached_remote_url = (
2167 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002168 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002169 cl2._cached_remote_url = (
2170 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002171 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2172 self.assertEqual(cl1._GetChangeDetail(), 'a')
2173 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002174
2175 def test_gerrit_change_detail_cache_options(self):
2176 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002177 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002178 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002179 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002180 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2181 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2182 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2183 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2184 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2185 self.assertEqual(cl._GetChangeDetail(), 'cab')
2186
2187 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2188 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2189 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2190 self.assertEqual(cl._GetChangeDetail(), 'cab')
2191
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002192 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002193 gerrit_util.GetChangeDetail.return_value = {
2194 'current_revision': 'rev1',
2195 'revisions': {
2196 'rev1': {'commit': {'message': 'desc1'}},
2197 },
2198 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002199
2200 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002201 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002202 cl._cached_remote_url = (
2203 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002204 self.assertEqual(cl.FetchDescription(), 'desc1')
2205 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002206
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002207 def test_print_current_creds(self):
2208 class CookiesAuthenticatorMock(object):
2209 def __init__(self):
2210 self.gitcookies = {
2211 'host.googlesource.com': ('user', 'pass'),
2212 'host-review.googlesource.com': ('user', 'pass'),
2213 }
2214 self.netrc = self
2215 self.netrc.hosts = {
2216 'github.com': ('user2', None, 'pass2'),
2217 'host2.googlesource.com': ('user3', None, 'pass'),
2218 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002219 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2220 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002221 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2222 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2223 ' Host\t User\t Which file',
2224 '============================\t=====\t===========',
2225 'host-review.googlesource.com\t user\t.gitcookies',
2226 ' host.googlesource.com\t user\t.gitcookies',
2227 ' host2.googlesource.com\tuser3\t .netrc',
2228 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002229 sys.stdout.seek(0)
2230 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002231 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2232 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2233 ' Host\tUser\t Which file',
2234 '============================\t====\t===========',
2235 'host-review.googlesource.com\tuser\t.gitcookies',
2236 ' host.googlesource.com\tuser\t.gitcookies',
2237 ])
2238
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002239 def _common_creds_check_mocks(self):
2240 def exists_mock(path):
2241 dirname = os.path.dirname(path)
2242 if dirname == os.path.expanduser('~'):
2243 dirname = '~'
2244 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002245 if base in (NETRC_FILENAME, '.gitcookies'):
2246 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002247 # git cl also checks for existence other files not relevant to this test.
2248 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002249 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002250 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002251 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002252 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002253
2254 def test_creds_check_gitcookies_not_configured(self):
2255 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002256 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2257 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002258 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002259 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2260 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2261 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2262 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2263 'or Ctrl+C to abort'), ''),
2264 (([
2265 'git', 'config', '--global', 'http.cookiefile',
2266 os.path.expanduser(os.path.join('~', '.gitcookies'))
2267 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002268 ]
2269 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002270 self.assertTrue(
2271 sys.stdout.getvalue().startswith(
2272 'You seem to be using outdated .netrc for git credentials:'))
2273 self.assertIn(
2274 '\nConfigured git to use .gitcookies from',
2275 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002276
2277 def test_creds_check_gitcookies_configured_custom_broken(self):
2278 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002279 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2280 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002281 custom_cookie_path = ('C:\\.gitcookies'
2282 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002283 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002284 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2285 ((['git', 'config', '--global', 'http.cookiefile'], ),
2286 custom_cookie_path),
2287 (('os.path.exists', custom_cookie_path), False),
2288 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2289 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2290 (([
2291 'git', 'config', '--global', 'http.cookiefile',
2292 os.path.expanduser(os.path.join('~', '.gitcookies'))
2293 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002294 ]
2295 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002296 self.assertIn(
2297 'WARNING: You have configured custom path to .gitcookies: ',
2298 sys.stdout.getvalue())
2299 self.assertIn(
2300 'However, your configured .gitcookies file is missing.',
2301 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002302
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002303 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002304 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002305 self.mockGit.config['remote.origin.url'] = (
2306 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002307 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002308 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002309 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002310 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002311 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002312 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002313
Edward Lemurda4b6c62020-02-13 00:28:40 +00002314 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2315 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002316 self.mockGit.config['remote.origin.url'] = (
2317 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002318 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002319 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002320 'current_revision': 'ba5eba11',
2321 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002322 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002323 '_number': 1,
2324 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002325 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002326 '_number': 2,
2327 },
2328 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002329 'messages': [
2330 {
2331 u'_revision_number': 1,
2332 u'author': {
2333 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002334 u'email': u'could-be-anything@example.com',
2335 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002336 },
2337 u'date': u'2017-03-15 20:08:45.000000000',
2338 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002339 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002340 u'tag': u'autogenerated:cq:dry-run'
2341 },
2342 {
2343 u'_revision_number': 2,
2344 u'author': {
2345 u'_account_id': 11151243,
2346 u'email': u'owner@example.com',
2347 u'name': u'owner'
2348 },
2349 u'date': u'2017-03-16 20:00:41.000000000',
2350 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2351 u'message': u'PTAL',
2352 },
2353 {
2354 u'_revision_number': 2,
2355 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002356 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002357 u'email': u'reviewer@example.com',
2358 u'name': u'reviewer'
2359 },
2360 u'date': u'2017-03-17 05:19:37.500000000',
2361 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2362 u'message': u'Patch Set 2: Code-Review+1',
2363 },
2364 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002365 }
2366 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002367 (('GetChangeComments', 'chromium-review.googlesource.com',
2368 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002369 '/COMMIT_MSG': [
2370 {
2371 'author': {'email': u'reviewer@example.com'},
2372 'updated': u'2017-03-17 05:19:37.500000000',
2373 'patch_set': 2,
2374 'side': 'REVISION',
2375 'message': 'Please include a bug link',
2376 },
2377 ],
2378 'codereview.settings': [
2379 {
2380 'author': {'email': u'owner@example.com'},
2381 'updated': u'2017-03-16 20:00:41.000000000',
2382 'patch_set': 2,
2383 'side': 'PARENT',
2384 'line': 42,
2385 'message': 'I removed this because it is bad',
2386 },
2387 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002388 }),
2389 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2390 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002391 ] * 2 + [
2392 (('write_json', 'output.json', [
2393 {
2394 u'date': u'2017-03-16 20:00:41.000000',
2395 u'message': (
2396 u'PTAL\n' +
2397 u'\n' +
2398 u'codereview.settings\n' +
2399 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2400 u'c/1/2/codereview.settings#b42\n' +
2401 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002402 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002403 u'approval': False,
2404 u'disapproval': False,
2405 u'sender': u'owner@example.com'
2406 }, {
2407 u'date': u'2017-03-17 05:19:37.500000',
2408 u'message': (
2409 u'Patch Set 2: Code-Review+1\n' +
2410 u'\n' +
2411 u'/COMMIT_MSG\n' +
2412 u' PS2, File comment: https://chromium-review.googlesource' +
2413 u'.com/c/1/2//COMMIT_MSG#\n' +
2414 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002415 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002416 u'approval': False,
2417 u'disapproval': False,
2418 u'sender': u'reviewer@example.com'
2419 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002420 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002421 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002422 expected_comments_summary = [
2423 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002424 message=(
2425 u'PTAL\n' +
2426 u'\n' +
2427 u'codereview.settings\n' +
2428 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2429 u'c/1/2/codereview.settings#b42\n' +
2430 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002431 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002432 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002433 disapproval=False, approval=False, sender=u'owner@example.com'),
2434 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002435 message=(
2436 u'Patch Set 2: Code-Review+1\n' +
2437 u'\n' +
2438 u'/COMMIT_MSG\n' +
2439 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2440 u'c/1/2//COMMIT_MSG#\n' +
2441 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002442 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002443 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002444 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2445 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002446 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002447 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002448 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002449 self.assertEqual(
2450 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2451
2452 def test_git_cl_comments_robot_comments(self):
2453 # git cl comments also fetches robot comments (which are considered a type
2454 # of autogenerated comment), and unlike other types of comments, only robot
2455 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002456 self.mockGit.config['remote.origin.url'] = (
2457 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002458 gerrit_util.GetChangeDetail.return_value = {
2459 'owner': {'email': 'owner@example.com'},
2460 'current_revision': 'ba5eba11',
2461 'revisions': {
2462 'deadbeaf': {
2463 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002464 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002465 'ba5eba11': {
2466 '_number': 2,
2467 },
2468 },
2469 'messages': [
2470 {
2471 u'_revision_number': 1,
2472 u'author': {
2473 u'_account_id': 1111084,
2474 u'email': u'commit-bot@chromium.org',
2475 u'name': u'Commit Bot'
2476 },
2477 u'date': u'2017-03-15 20:08:45.000000000',
2478 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2479 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2480 u'tag': u'autogenerated:cq:dry-run'
2481 },
2482 {
2483 u'_revision_number': 1,
2484 u'author': {
2485 u'_account_id': 123,
2486 u'email': u'tricium@serviceaccount.com',
2487 u'name': u'Tricium'
2488 },
2489 u'date': u'2017-03-16 20:00:41.000000000',
2490 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2491 u'message': u'(1 comment)',
2492 u'tag': u'autogenerated:tricium',
2493 },
2494 {
2495 u'_revision_number': 1,
2496 u'author': {
2497 u'_account_id': 123,
2498 u'email': u'tricium@serviceaccount.com',
2499 u'name': u'Tricium'
2500 },
2501 u'date': u'2017-03-16 20:00:41.000000000',
2502 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2503 u'message': u'(1 comment)',
2504 u'tag': u'autogenerated:tricium',
2505 },
2506 {
2507 u'_revision_number': 2,
2508 u'author': {
2509 u'_account_id': 123,
2510 u'email': u'tricium@serviceaccount.com',
2511 u'name': u'reviewer'
2512 },
2513 u'date': u'2017-03-17 05:30:37.000000000',
2514 u'tag': u'autogenerated:tricium',
2515 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2516 u'message': u'(1 comment)',
2517 },
2518 ]
2519 }
2520 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002521 (('GetChangeComments', 'chromium-review.googlesource.com',
2522 'infra%2Finfra~1'), {}),
2523 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2524 'infra%2Finfra~1'), {
2525 'codereview.settings': [
2526 {
2527 u'author': {u'email': u'tricium@serviceaccount.com'},
2528 u'updated': u'2017-03-17 05:30:37.000000000',
2529 u'robot_run_id': u'5565031076855808',
2530 u'robot_id': u'Linter/Category',
2531 u'tag': u'autogenerated:tricium',
2532 u'patch_set': 2,
2533 u'side': u'REVISION',
2534 u'message': u'Linter warning message text',
2535 u'line': 32,
2536 },
2537 ],
2538 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002539 ]
2540 expected_comments_summary = [
2541 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2542 message=(
2543 u'(1 comment)\n\ncodereview.settings\n'
2544 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2545 u'c/1/2/codereview.settings#32\n'
2546 u' Linter warning message text\n'),
2547 sender=u'tricium@serviceaccount.com',
2548 autogenerated=True, approval=False, disapproval=False)
2549 ]
2550 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002551 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002552 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002553
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002554 def test_get_remote_url_with_mirror(self):
2555 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002556
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002557 def selective_os_path_isdir_mock(path):
2558 if path == '/cache/this-dir-exists':
2559 return self._mocked_call('os.path.isdir', path)
2560 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002561
Edward Lemurda4b6c62020-02-13 00:28:40 +00002562 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002563
2564 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002565 self.mockGit.config['remote.origin.url'] = (
2566 '/cache/this-dir-exists')
2567 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2568 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002569 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002570 (('os.path.isdir', '/cache/this-dir-exists'),
2571 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002572 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002573 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002574 self.assertEqual(cl.GetRemoteUrl(), url)
2575 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2576
Edward Lemur298f2cf2019-02-22 21:40:39 +00002577 def test_get_remote_url_non_existing_mirror(self):
2578 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002579
Edward Lemur298f2cf2019-02-22 21:40:39 +00002580 def selective_os_path_isdir_mock(path):
2581 if path == '/cache/this-dir-doesnt-exist':
2582 return self._mocked_call('os.path.isdir', path)
2583 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002584
Edward Lemurda4b6c62020-02-13 00:28:40 +00002585 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2586 mock.patch('logging.error',
2587 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002588
Edward Lemur26964072020-02-19 19:18:51 +00002589 self.mockGit.config['remote.origin.url'] = (
2590 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002591 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002592 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2593 False),
2594 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002595 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2596 'but it doesn\'t exist.', {
2597 'remote': 'origin',
2598 'branch': 'master',
2599 'url': '/cache/this-dir-doesnt-exist'}
2600 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002601 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002602 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002603 self.assertIsNone(cl.GetRemoteUrl())
2604
2605 def test_get_remote_url_misconfigured_mirror(self):
2606 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002607
Edward Lemur298f2cf2019-02-22 21:40:39 +00002608 def selective_os_path_isdir_mock(path):
2609 if path == '/cache/this-dir-exists':
2610 return self._mocked_call('os.path.isdir', path)
2611 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002612
Edward Lemurda4b6c62020-02-13 00:28:40 +00002613 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2614 mock.patch('logging.error',
2615 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002616
Edward Lemur26964072020-02-19 19:18:51 +00002617 self.mockGit.config['remote.origin.url'] = (
2618 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002619 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002620 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002621 (('logging.error',
2622 'Remote "%(remote)s" for branch "%(branch)s" points to '
2623 '"%(cache_path)s", but it is misconfigured.\n'
2624 '"%(cache_path)s" must be a git repo and must have a remote named '
2625 '"%(remote)s" pointing to the git host.', {
2626 'remote': 'origin',
2627 'cache_path': '/cache/this-dir-exists',
2628 'branch': 'master'}
2629 ), None),
2630 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002631 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002632 self.assertIsNone(cl.GetRemoteUrl())
2633
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002634 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002635 self.mockGit.config['remote.origin.url'] = (
2636 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002637 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002638 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2639
2640 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002641 mock.patch('logging.error',
2642 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002643
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002644 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002645 (('logging.error',
2646 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2647 'but it doesn\'t exist.', {
2648 'remote': 'origin',
2649 'branch': 'master',
2650 'url': ''}
2651 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002652 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002653 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002654 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002655
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002656
Edward Lemur9aa1a962020-02-25 00:58:38 +00002657class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002658 def setUp(self):
2659 super(ChangelistTest, self).setUp()
2660 mock.patch('gclient_utils.FileRead').start()
2661 mock.patch('gclient_utils.FileWrite').start()
2662 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2663 mock.patch(
2664 'git_cl.Changelist.GetCodereviewServer',
2665 return_value='https://chromium-review.googlesource.com').start()
2666 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2667 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2668 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2669 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2670 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2671 mock.patch('git_cl.time_time').start()
2672 mock.patch('metrics.collector').start()
2673 mock.patch('subprocess2.Popen').start()
2674 self.addCleanup(mock.patch.stopall)
2675 self.temp_count = 0
2676
Edward Lemur227d5102020-02-25 23:45:35 +00002677 def testRunHook(self):
2678 expected_results = {
2679 'more_cc': ['more@example.com', 'cc@example.com'],
2680 'should_continue': True,
2681 }
2682 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2683 git_cl.time_time.side_effect = [100, 200]
2684 mockProcess = mock.Mock()
2685 mockProcess.wait.return_value = 0
2686 subprocess2.Popen.return_value = mockProcess
2687
2688 cl = git_cl.Changelist()
2689 results = cl.RunHook(
2690 committing=True,
2691 may_prompt=True,
2692 verbose=2,
2693 parallel=True,
2694 upstream='upstream',
2695 description='description',
2696 all_files=True)
2697
2698 self.assertEqual(expected_results, results)
2699 subprocess2.Popen.assert_called_once_with([
2700 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002701 '--root', 'root',
2702 '--upstream', 'upstream',
2703 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002704 '--author', 'author',
2705 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002706 '--issue', '123456',
2707 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002708 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002709 '--may_prompt',
2710 '--parallel',
2711 '--all_files',
2712 '--json_output', '/tmp/fake-temp2',
2713 '--description_file', '/tmp/fake-temp1',
2714 ])
2715 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002716 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002717 metrics.collector.add_repeated('sub_commands', {
2718 'command': 'presubmit',
2719 'execution_time': 100,
2720 'exit_code': 0,
2721 })
2722
Edward Lemur99df04e2020-03-05 19:39:43 +00002723 def testRunHook_FewerOptions(self):
2724 expected_results = {
2725 'more_cc': ['more@example.com', 'cc@example.com'],
2726 'should_continue': True,
2727 }
2728 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2729 git_cl.time_time.side_effect = [100, 200]
2730 mockProcess = mock.Mock()
2731 mockProcess.wait.return_value = 0
2732 subprocess2.Popen.return_value = mockProcess
2733
2734 git_cl.Changelist.GetAuthor.return_value = None
2735 git_cl.Changelist.GetIssue.return_value = None
2736 git_cl.Changelist.GetPatchset.return_value = None
2737 git_cl.Changelist.GetCodereviewServer.return_value = None
2738
2739 cl = git_cl.Changelist()
2740 results = cl.RunHook(
2741 committing=False,
2742 may_prompt=False,
2743 verbose=0,
2744 parallel=False,
2745 upstream='upstream',
2746 description='description',
2747 all_files=False)
2748
2749 self.assertEqual(expected_results, results)
2750 subprocess2.Popen.assert_called_once_with([
2751 'vpython', 'PRESUBMIT_SUPPORT',
2752 '--root', 'root',
2753 '--upstream', 'upstream',
2754 '--upload',
2755 '--json_output', '/tmp/fake-temp2',
2756 '--description_file', '/tmp/fake-temp1',
2757 ])
2758 gclient_utils.FileWrite.assert_called_once_with(
2759 '/tmp/fake-temp1', 'description')
2760 metrics.collector.add_repeated('sub_commands', {
2761 'command': 'presubmit',
2762 'execution_time': 100,
2763 'exit_code': 0,
2764 })
2765
Edward Lemur227d5102020-02-25 23:45:35 +00002766 @mock.patch('sys.exit', side_effect=SystemExitMock)
2767 def testRunHook_Failure(self, _mock):
2768 git_cl.time_time.side_effect = [100, 200]
2769 mockProcess = mock.Mock()
2770 mockProcess.wait.return_value = 2
2771 subprocess2.Popen.return_value = mockProcess
2772
2773 cl = git_cl.Changelist()
2774 with self.assertRaises(SystemExitMock):
2775 cl.RunHook(
2776 committing=True,
2777 may_prompt=True,
2778 verbose=2,
2779 parallel=True,
2780 upstream='upstream',
2781 description='description',
2782 all_files=True)
2783
2784 sys.exit.assert_called_once_with(2)
2785
Edward Lemur75526302020-02-27 22:31:05 +00002786 def testRunPostUploadHook(self):
2787 cl = git_cl.Changelist()
2788 cl.RunPostUploadHook(2, 'upstream', 'description')
2789
2790 subprocess2.Popen.assert_called_once_with([
2791 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002792 '--root', 'root',
2793 '--upstream', 'upstream',
2794 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002795 '--author', 'author',
2796 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002797 '--issue', '123456',
2798 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002799 '--post_upload',
2800 '--description_file', '/tmp/fake-temp1',
2801 ])
2802 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002803 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002804
Edward Lemur9aa1a962020-02-25 00:58:38 +00002805
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002806class CMDTestCaseBase(unittest.TestCase):
2807 _STATUSES = [
2808 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2809 'INFRA_FAILURE', 'CANCELED',
2810 ]
2811 _CHANGE_DETAIL = {
2812 'project': 'depot_tools',
2813 'status': 'OPEN',
2814 'owner': {'email': 'owner@e.mail'},
2815 'current_revision': 'beeeeeef',
2816 'revisions': {
2817 'deadbeaf': {'_number': 6},
2818 'beeeeeef': {
2819 '_number': 7,
2820 'fetch': {'http': {
2821 'url': 'https://chromium.googlesource.com/depot_tools',
2822 'ref': 'refs/changes/56/123456/7'
2823 }},
2824 },
2825 },
2826 }
2827 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002828 'builds': [{
2829 'id': str(100 + idx),
2830 'builder': {
2831 'project': 'chromium',
2832 'bucket': 'try',
2833 'builder': 'bot_' + status.lower(),
2834 },
2835 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2836 'tags': [],
2837 'status': status,
2838 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002839 }
2840
Edward Lemur4c707a22019-09-24 21:13:43 +00002841 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002842 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002843 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002844 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2845 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002846 mock.patch(
2847 'git_cl.Changelist.GetCodereviewServer',
2848 return_value='https://chromium-review.googlesource.com').start()
2849 mock.patch(
2850 'git_cl.Changelist._GetGerritHost',
2851 return_value='chromium-review.googlesource.com').start()
2852 mock.patch(
2853 'git_cl.Changelist.GetMostRecentPatchset',
2854 return_value=7).start()
2855 mock.patch(
2856 'git_cl.Changelist.GetRemoteUrl',
2857 return_value='https://chromium.googlesource.com/depot_tools').start()
2858 mock.patch(
2859 'auth.Authenticator',
2860 return_value=AuthenticatorMock()).start()
2861 mock.patch(
2862 'gerrit_util.GetChangeDetail',
2863 return_value=self._CHANGE_DETAIL).start()
2864 mock.patch(
2865 'git_cl._call_buildbucket',
2866 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002867 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002868 self.addCleanup(mock.patch.stopall)
2869
Edward Lemur4c707a22019-09-24 21:13:43 +00002870
Edward Lemur9468eba2020-02-27 19:07:22 +00002871class CMDPresubmitTestCase(CMDTestCaseBase):
2872 def setUp(self):
2873 super(CMDPresubmitTestCase, self).setUp()
2874 mock.patch(
2875 'git_cl.Changelist.GetCommonAncestorWithUpstream',
2876 return_value='upstream').start()
2877 mock.patch(
2878 'git_cl.Changelist.FetchDescription',
2879 return_value='fetch description').start()
2880 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00002881 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00002882 return_value='get description').start()
2883 mock.patch('git_cl.Changelist.RunHook').start()
2884
2885 def testDefaultCase(self):
2886 self.assertEqual(0, git_cl.main(['presubmit']))
2887 git_cl.Changelist.RunHook.assert_called_once_with(
2888 committing=True,
2889 may_prompt=False,
2890 verbose=0,
2891 parallel=None,
2892 upstream='upstream',
2893 description='fetch description',
2894 all_files=None)
2895
2896 def testNoIssue(self):
2897 git_cl.Changelist.GetIssue.return_value = None
2898 self.assertEqual(0, git_cl.main(['presubmit']))
2899 git_cl.Changelist.RunHook.assert_called_once_with(
2900 committing=True,
2901 may_prompt=False,
2902 verbose=0,
2903 parallel=None,
2904 upstream='upstream',
2905 description='get description',
2906 all_files=None)
2907
2908 def testCustomBranch(self):
2909 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
2910 git_cl.Changelist.RunHook.assert_called_once_with(
2911 committing=True,
2912 may_prompt=False,
2913 verbose=0,
2914 parallel=None,
2915 upstream='custom_branch',
2916 description='fetch description',
2917 all_files=None)
2918
2919 def testOptions(self):
2920 self.assertEqual(
2921 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
2922 git_cl.Changelist.RunHook.assert_called_once_with(
2923 committing=False,
2924 may_prompt=False,
2925 verbose=2,
2926 parallel=True,
2927 upstream='upstream',
2928 description='fetch description',
2929 all_files=True)
2930
2931
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002932class CMDTryResultsTestCase(CMDTestCaseBase):
2933 _DEFAULT_REQUEST = {
2934 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002935 "gerritChanges": [{
2936 "project": "depot_tools",
2937 "host": "chromium-review.googlesource.com",
2938 "patchset": 7,
2939 "change": 123456,
2940 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002941 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002942 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2943 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002944 }
2945
2946 def testNoJobs(self):
2947 git_cl._call_buildbucket.return_value = {}
2948
2949 self.assertEqual(0, git_cl.main(['try-results']))
2950 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2951 git_cl._call_buildbucket.assert_called_once_with(
2952 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2953 self._DEFAULT_REQUEST)
2954
2955 def testPrintToStdout(self):
2956 self.assertEqual(0, git_cl.main(['try-results']))
2957 self.assertEqual([
2958 'Successes:',
2959 ' bot_success https://ci.chromium.org/b/103',
2960 'Infra Failures:',
2961 ' bot_infra_failure https://ci.chromium.org/b/105',
2962 'Failures:',
2963 ' bot_failure https://ci.chromium.org/b/104',
2964 'Canceled:',
2965 ' bot_canceled ',
2966 'Started:',
2967 ' bot_started https://ci.chromium.org/b/102',
2968 'Scheduled:',
2969 ' bot_scheduled id=101',
2970 'Other:',
2971 ' bot_status_unspecified id=100',
2972 'Total: 7 tryjobs',
2973 ], sys.stdout.getvalue().splitlines())
2974 git_cl._call_buildbucket.assert_called_once_with(
2975 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2976 self._DEFAULT_REQUEST)
2977
2978 def testPrintToStdoutWithMasters(self):
2979 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2980 self.assertEqual([
2981 'Successes:',
2982 ' try bot_success https://ci.chromium.org/b/103',
2983 'Infra Failures:',
2984 ' try bot_infra_failure https://ci.chromium.org/b/105',
2985 'Failures:',
2986 ' try bot_failure https://ci.chromium.org/b/104',
2987 'Canceled:',
2988 ' try bot_canceled ',
2989 'Started:',
2990 ' try bot_started https://ci.chromium.org/b/102',
2991 'Scheduled:',
2992 ' try bot_scheduled id=101',
2993 'Other:',
2994 ' try bot_status_unspecified id=100',
2995 'Total: 7 tryjobs',
2996 ], sys.stdout.getvalue().splitlines())
2997 git_cl._call_buildbucket.assert_called_once_with(
2998 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2999 self._DEFAULT_REQUEST)
3000
3001 @mock.patch('git_cl.write_json')
3002 def testWriteToJson(self, mockJsonDump):
3003 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3004 git_cl._call_buildbucket.assert_called_once_with(
3005 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3006 self._DEFAULT_REQUEST)
3007 mockJsonDump.assert_called_once_with(
3008 'file.json', self._DEFAULT_RESPONSE['builds'])
3009
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003010 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003011 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3012 self.assertEqual(
3013 [
3014 ('chromium', 'try', 'bot_failure'),
3015 ('chromium', 'try', 'bot_infra_failure'),
3016 ],
3017 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003018
3019 def test_filter_failed_for_retry_many_builds(self):
3020
3021 def _build(name, created_sec, status, experimental=False):
3022 assert 0 <= created_sec < 100, created_sec
3023 b = {
3024 'id': 112112,
3025 'builder': {
3026 'project': 'chromium',
3027 'bucket': 'try',
3028 'builder': name,
3029 },
3030 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3031 'status': status,
3032 'tags': [],
3033 }
3034 if experimental:
3035 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3036 return b
3037
3038 builds = [
3039 _build('flaky-last-green', 1, 'FAILURE'),
3040 _build('flaky-last-green', 2, 'SUCCESS'),
3041 _build('flaky', 1, 'SUCCESS'),
3042 _build('flaky', 2, 'FAILURE'),
3043 _build('running', 1, 'FAILED'),
3044 _build('running', 2, 'SCHEDULED'),
3045 _build('yep-still-running', 1, 'STARTED'),
3046 _build('yep-still-running', 2, 'FAILURE'),
3047 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3048 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3049
3050 # Simulate experimental in CQ builder, which developer decided
3051 # to retry manually which resulted in 2nd build non-experimental.
3052 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3053 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3054 ]
3055 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003056 self.assertEqual(
3057 [
3058 ('chromium', 'try', 'flaky'),
3059 ('chromium', 'try', 'sometimes-experimental'),
3060 ],
3061 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003062
3063
3064class CMDTryTestCase(CMDTestCaseBase):
3065
3066 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003067 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003068 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003069 self.assertEqual(0, git_cl.main(['try']))
3070 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3071 self.assertEqual(
3072 sys.stdout.getvalue(),
3073 'Scheduling CQ dry run on: '
3074 'https://chromium-review.googlesource.com/123456\n')
3075
Edward Lemur4c707a22019-09-24 21:13:43 +00003076 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003077 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003078 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003079
3080 self.assertEqual(0, git_cl.main([
3081 'try', '-B', 'luci.chromium.try', '-b', 'win',
3082 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3083 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003084 'Scheduling jobs on:\n'
3085 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003086 git_cl.sys.stdout.getvalue())
3087
3088 expected_request = {
3089 "requests": [{
3090 "scheduleBuild": {
3091 "requestId": "uuid4",
3092 "builder": {
3093 "project": "chromium",
3094 "builder": "win",
3095 "bucket": "try",
3096 },
3097 "gerritChanges": [{
3098 "project": "depot_tools",
3099 "host": "chromium-review.googlesource.com",
3100 "patchset": 7,
3101 "change": 123456,
3102 }],
3103 "properties": {
3104 "category": "git_cl_try",
3105 "json": [{"a": 1}, None],
3106 "key": "val",
3107 },
3108 "tags": [
3109 {"value": "win", "key": "builder"},
3110 {"value": "git_cl_try", "key": "user_agent"},
3111 ],
3112 },
3113 }],
3114 }
3115 mockCallBuildbucket.assert_called_with(
3116 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3117
Anthony Polito1a5fe232020-01-24 23:17:52 +00003118 @mock.patch('git_cl._call_buildbucket')
3119 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3120 mockCallBuildbucket.return_value = {}
3121
3122 self.assertEqual(0, git_cl.main([
3123 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3124 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3125 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3126 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003127 'Scheduling jobs on:\n'
3128 ' chromium/try: linux\n'
3129 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003130 git_cl.sys.stdout.getvalue())
3131
3132 expected_request = {
3133 "requests": [{
3134 "scheduleBuild": {
3135 "requestId": "uuid4",
3136 "builder": {
3137 "project": "chromium",
3138 "builder": "linux",
3139 "bucket": "try",
3140 },
3141 "gerritChanges": [{
3142 "project": "depot_tools",
3143 "host": "chromium-review.googlesource.com",
3144 "patchset": 7,
3145 "change": 123456,
3146 }],
3147 "properties": {
3148 "category": "git_cl_try",
3149 "json": [{"a": 1}, None],
3150 "key": "val",
3151 },
3152 "tags": [
3153 {"value": "linux", "key": "builder"},
3154 {"value": "git_cl_try", "key": "user_agent"},
3155 ],
3156 "gitilesCommit": {
3157 "host": "chromium-review.googlesource.com",
3158 "project": "depot_tools",
3159 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3160 }
3161 },
3162 },
3163 {
3164 "scheduleBuild": {
3165 "requestId": "uuid4",
3166 "builder": {
3167 "project": "chromium",
3168 "builder": "win",
3169 "bucket": "try",
3170 },
3171 "gerritChanges": [{
3172 "project": "depot_tools",
3173 "host": "chromium-review.googlesource.com",
3174 "patchset": 7,
3175 "change": 123456,
3176 }],
3177 "properties": {
3178 "category": "git_cl_try",
3179 "json": [{"a": 1}, None],
3180 "key": "val",
3181 },
3182 "tags": [
3183 {"value": "win", "key": "builder"},
3184 {"value": "git_cl_try", "key": "user_agent"},
3185 ],
3186 "gitilesCommit": {
3187 "host": "chromium-review.googlesource.com",
3188 "project": "depot_tools",
3189 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3190 }
3191 },
3192 }],
3193 }
3194 mockCallBuildbucket.assert_called_with(
3195 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3196
Edward Lemur45768512020-03-02 19:03:14 +00003197 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003198 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003199 with self.assertRaises(SystemExit):
3200 git_cl.main([
3201 'try', '-B', 'not-a-bucket', '-b', 'win',
3202 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003203 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003204 'Invalid bucket: not-a-bucket.',
3205 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003206
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003207 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003208 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003209 def testScheduleOnBuildbucketRetryFailed(
3210 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003211 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003212 7: [],
3213 6: [{
3214 'id': 112112,
3215 'builder': {
3216 'project': 'chromium',
3217 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003218 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003219 'createTime': '2019-10-09T08:00:01.854286Z',
3220 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003221 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003222 mockCallBuildbucket.return_value = {}
3223
3224 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3225 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003226 'Scheduling jobs on:\n'
3227 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003228 git_cl.sys.stdout.getvalue())
3229
3230 expected_request = {
3231 "requests": [{
3232 "scheduleBuild": {
3233 "requestId": "uuid4",
3234 "builder": {
3235 "project": "chromium",
3236 "bucket": "try",
3237 "builder": "linux",
3238 },
3239 "gerritChanges": [{
3240 "project": "depot_tools",
3241 "host": "chromium-review.googlesource.com",
3242 "patchset": 7,
3243 "change": 123456,
3244 }],
3245 "properties": {
3246 "category": "git_cl_try",
3247 },
3248 "tags": [
3249 {"value": "linux", "key": "builder"},
3250 {"value": "git_cl_try", "key": "user_agent"},
3251 {"value": "1", "key": "retry_failed"},
3252 ],
3253 },
3254 }],
3255 }
3256 mockCallBuildbucket.assert_called_with(
3257 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3258
Edward Lemur4c707a22019-09-24 21:13:43 +00003259 def test_parse_bucket(self):
3260 test_cases = [
3261 {
3262 'bucket': 'chromium/try',
3263 'result': ('chromium', 'try'),
3264 },
3265 {
3266 'bucket': 'luci.chromium.try',
3267 'result': ('chromium', 'try'),
3268 'has_warning': True,
3269 },
3270 {
3271 'bucket': 'skia.primary',
3272 'result': ('skia', 'skia.primary'),
3273 'has_warning': True,
3274 },
3275 {
3276 'bucket': 'not-a-bucket',
3277 'result': (None, None),
3278 },
3279 ]
3280
3281 for test_case in test_cases:
3282 git_cl.sys.stdout.truncate(0)
3283 self.assertEqual(
3284 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3285 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003286 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3287 test_case['result'])
3288 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003289
3290
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003291class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003292
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003293 def setUp(self):
3294 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003295 mock.patch('git_cl._fetch_tryjobs').start()
3296 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003297 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Edward Lesmes0dd54822020-03-26 18:24:25 +00003298 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
3299 mock.patch(
3300 'git_cl.Settings.GetSquashGerritUploads',
3301 return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003302 self.addCleanup(mock.patch.stopall)
3303
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003304 def testWarmUpChangeDetailCache(self):
3305 self.assertEqual(0, git_cl.main(['upload']))
3306 gerrit_util.GetChangeDetail.assert_called_once_with(
3307 'chromium-review.googlesource.com', 'depot_tools~123456',
3308 frozenset([
3309 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3310 'CURRENT_COMMIT']))
3311
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003312 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003313 # This test mocks out the actual upload part, and just asserts that after
3314 # upload, if --retry-failed is added, then the tool will fetch try jobs
3315 # from the previous patchset and trigger the right builders on the latest
3316 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003317 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003318 # Latest patchset: No builds.
3319 [],
3320 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003321 [{
3322 'id': str(100 + idx),
3323 'builder': {
3324 'project': 'chromium',
3325 'bucket': 'try',
3326 'builder': 'bot_' + status.lower(),
3327 },
3328 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3329 'tags': [],
3330 'status': status,
3331 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003332 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003333
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003334 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003335 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003336 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3337 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003338 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003339 expected_buckets = [
3340 ('chromium', 'try', 'bot_failure'),
3341 ('chromium', 'try', 'bot_infra_failure'),
3342 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003343 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3344 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003345
Brian Sheedy59b06a82019-10-14 17:03:29 +00003346
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003347class MakeRequestsHelperTestCase(unittest.TestCase):
3348
3349 def exampleGerritChange(self):
3350 return {
3351 'host': 'chromium-review.googlesource.com',
3352 'project': 'depot_tools',
3353 'change': 1,
3354 'patchset': 2,
3355 }
3356
3357 def testMakeRequestsHelperNoOptions(self):
3358 # Basic test for the helper function _make_tryjob_schedule_requests;
3359 # it shouldn't throw AttributeError even when options doesn't have any
3360 # of the expected values; it will use default option values.
3361 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3362 jobs = [('chromium', 'try', 'my-builder')]
3363 options = optparse.Values()
3364 requests = git_cl._make_tryjob_schedule_requests(
3365 changelist, jobs, options, patchset=None)
3366
3367 # requestId is non-deterministic. Just assert that it's there and has
3368 # a particular length.
3369 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3370 self.assertEqual(requests, [{
3371 'scheduleBuild': {
3372 'builder': {
3373 'bucket': 'try',
3374 'builder': 'my-builder',
3375 'project': 'chromium'
3376 },
3377 'gerritChanges': [self.exampleGerritChange()],
3378 'properties': {
3379 'category': 'git_cl_try'
3380 },
3381 'tags': [{
3382 'key': 'builder',
3383 'value': 'my-builder'
3384 }, {
3385 'key': 'user_agent',
3386 'value': 'git_cl_try'
3387 }]
3388 }
3389 }])
3390
3391 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3392 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3393 jobs = [('chromium', 'try', 'presubmit')]
3394 options = optparse.Values()
3395 requests = git_cl._make_tryjob_schedule_requests(
3396 changelist, jobs, options, patchset=None)
3397 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3398 'category': 'git_cl_try',
3399 'dry_run': 'true'
3400 })
3401
3402 def testMakeRequestsHelperRevisionSet(self):
3403 # Gitiles commit is specified when revision is in options.
3404 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3405 jobs = [('chromium', 'try', 'my-builder')]
3406 options = optparse.Values({'revision': 'ba5eba11'})
3407 requests = git_cl._make_tryjob_schedule_requests(
3408 changelist, jobs, options, patchset=None)
3409 self.assertEqual(
3410 requests[0]['scheduleBuild']['gitilesCommit'], {
3411 'host': 'chromium-review.googlesource.com',
3412 'id': 'ba5eba11',
3413 'project': 'depot_tools'
3414 })
3415
3416 def testMakeRequestsHelperRetryFailedSet(self):
3417 # An extra tag is added when retry_failed is in options.
3418 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3419 jobs = [('chromium', 'try', 'my-builder')]
3420 options = optparse.Values({'retry_failed': 'true'})
3421 requests = git_cl._make_tryjob_schedule_requests(
3422 changelist, jobs, options, patchset=None)
3423 self.assertEqual(
3424 requests[0]['scheduleBuild']['tags'], [
3425 {
3426 'key': 'builder',
3427 'value': 'my-builder'
3428 },
3429 {
3430 'key': 'user_agent',
3431 'value': 'git_cl_try'
3432 },
3433 {
3434 'key': 'retry_failed',
3435 'value': '1'
3436 }
3437 ])
3438
3439 def testMakeRequestsHelperCategorySet(self):
3440 # The category property can be overriden with options.
3441 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3442 jobs = [('chromium', 'try', 'my-builder')]
3443 options = optparse.Values({'category': 'my-special-category'})
3444 requests = git_cl._make_tryjob_schedule_requests(
3445 changelist, jobs, options, patchset=None)
3446 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3447 {'category': 'my-special-category'})
3448
3449
Edward Lemurda4b6c62020-02-13 00:28:40 +00003450class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003451
3452 def setUp(self):
3453 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003454 mock.patch('git_cl.RunCommand').start()
3455 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3456 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3457 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003458 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003459 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003460
3461 def tearDown(self):
3462 shutil.rmtree(self._top_dir)
3463 super(CMDFormatTestCase, self).tearDown()
3464
Jamie Madill5e96ad12020-01-13 16:08:35 +00003465 def _make_temp_file(self, fname, contents):
3466 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3467 tf.write('\n'.join(contents))
3468
Brian Sheedy59b06a82019-10-14 17:03:29 +00003469 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003470 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003471
Brian Sheedyb4307d52019-12-02 19:18:17 +00003472 def _check_yapf_filtering(self, files, expected):
3473 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3474 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003475
Edward Lemur1a83da12020-03-04 21:18:36 +00003476 def _run_command_mock(self, return_value):
3477 def f(*args, **kwargs):
3478 if 'stdin' in kwargs:
3479 self.assertIsInstance(kwargs['stdin'], bytes)
3480 return return_value
3481 return f
3482
Jamie Madill5e96ad12020-01-13 16:08:35 +00003483 def testClangFormatDiffFull(self):
3484 self._make_temp_file('test.cc', ['// test'])
3485 git_cl.settings.GetFormatFullByDefault.return_value = False
3486 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3487 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3488
3489 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003490 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003491 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3492 self._top_dir, 'HEAD')
3493 self.assertEqual(2, return_value)
3494
3495 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003496 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003497 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3498 self._top_dir, 'HEAD')
3499 self.assertEqual(0, return_value)
3500
3501 def testClangFormatDiff(self):
3502 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00003503 # A valid file is required, so use this test.
3504 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00003505 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3506
3507 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003508 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3509 return_value = git_cl._RunClangFormatDiff(
3510 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003511 self.assertEqual(2, return_value)
3512
3513 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003514 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003515 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3516 'HEAD')
3517 self.assertEqual(0, return_value)
3518
Brian Sheedyb4307d52019-12-02 19:18:17 +00003519 def testYapfignoreExplicit(self):
3520 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3521 files = [
3522 'bar.py',
3523 'foo/bar.py',
3524 'foo/baz.py',
3525 'foo/bar/baz.py',
3526 'foo/bar/foobar.py',
3527 ]
3528 expected = [
3529 'bar.py',
3530 'foo/baz.py',
3531 'foo/bar/foobar.py',
3532 ]
3533 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003534
Brian Sheedyb4307d52019-12-02 19:18:17 +00003535 def testYapfignoreSingleWildcards(self):
3536 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3537 files = [
3538 'bar.py', # Matched by *bar.py.
3539 'bar.txt',
3540 'foobar.py', # Matched by *bar.py, foo*.
3541 'foobar.txt', # Matched by foo*.
3542 'bazbar.py', # Matched by *bar.py, baz*.py.
3543 'bazbar.txt',
3544 'foo/baz.txt', # Matched by foo*.
3545 'bar/bar.py', # Matched by *bar.py.
3546 'baz/foo.py', # Matched by baz*.py, foo*.
3547 'baz/foo.txt',
3548 ]
3549 expected = [
3550 'bar.txt',
3551 'bazbar.txt',
3552 'baz/foo.txt',
3553 ]
3554 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003555
Brian Sheedyb4307d52019-12-02 19:18:17 +00003556 def testYapfignoreMultiplewildcards(self):
3557 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3558 files = [
3559 'bar.py', # Matched by *bar*.
3560 'bar.txt', # Matched by *bar*.
3561 'abar.py', # Matched by *bar*.
3562 'foobaz.txt', # Matched by *foo*baz.txt.
3563 'foobaz.py',
3564 'afoobaz.txt', # Matched by *foo*baz.txt.
3565 ]
3566 expected = [
3567 'foobaz.py',
3568 ]
3569 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003570
3571 def testYapfignoreComments(self):
3572 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003573 files = [
3574 'test.py',
3575 'test2.py',
3576 ]
3577 expected = [
3578 'test2.py',
3579 ]
3580 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003581
3582 def testYapfignoreBlankLines(self):
3583 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003584 files = [
3585 'test.py',
3586 'test2.py',
3587 'test3.py',
3588 ]
3589 expected = [
3590 'test3.py',
3591 ]
3592 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003593
3594 def testYapfignoreWhitespace(self):
3595 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003596 files = [
3597 'test.py',
3598 'test2.py',
3599 ]
3600 expected = [
3601 'test2.py',
3602 ]
3603 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003604
Brian Sheedyb4307d52019-12-02 19:18:17 +00003605 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003606 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003607 self._check_yapf_filtering([], [])
3608
3609 def testYapfignoreMissingYapfignore(self):
3610 files = [
3611 'test.py',
3612 ]
3613 expected = [
3614 'test.py',
3615 ]
3616 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003617
3618
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003619if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003620 logging.basicConfig(
3621 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003622 unittest.main()