blob: 3ab59ba4e10ef76d390b1db62484155ecdfa6e9e [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 Lemurda4b6c62020-02-13 00:28:40 +0000480 mock.patch('sys.stdout', StringIO()).start()
481 mock.patch(
482 'git_cl.time_time',
483 lambda: self._mocked_call('time.time')).start()
484 mock.patch(
485 'git_cl.metrics.collector.add_repeated',
486 lambda *a: self._mocked_call('add_repeated', *a)).start()
487 mock.patch('subprocess2.call', self._mocked_call).start()
488 mock.patch('subprocess2.check_call', self._mocked_call).start()
489 mock.patch('subprocess2.check_output', self._mocked_call).start()
490 mock.patch(
491 'subprocess2.communicate',
492 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
493 mock.patch(
494 'git_cl.gclient_utils.CheckCallAndFilter',
495 self._mocked_call).start()
496 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
497 mock.patch(
498 'git_common.get_or_create_merge_base',
499 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000500 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
501 mock.patch(
502 'git_cl.SaveDescriptionBackup',
503 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
504 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000505 'git_cl.write_json',
506 lambda *a: self._mocked_call('write_json', *a)).start()
507 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000508 'git_cl.Changelist.RunHook',
509 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000510 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
511 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000512 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000513 mock.patch(
514 'git_cl.gerrit_util.GetChangeComments',
515 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
516 mock.patch(
517 'git_cl.gerrit_util.GetChangeRobotComments',
518 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
519 mock.patch(
520 'git_cl.gerrit_util.AddReviewers',
521 lambda *a: self._mocked_call('AddReviewers', *a)).start()
522 mock.patch(
523 'git_cl.gerrit_util.SetReview',
524 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
525 self._mocked_call(
526 'SetReview', h, i, msg, labels, notify, ready))).start()
527 mock.patch(
528 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
529 return_value=False).start()
530 mock.patch(
531 'git_cl.gerrit_util.GceAuthenticator.is_gce',
532 return_value=False).start()
533 mock.patch(
534 'git_cl.gerrit_util.ValidAccounts',
535 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000536 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000537 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000538 self.mockGit = GitMocks()
539 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
540 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
Edward Lesmese3a49aa2020-03-24 23:46:28 +0000541 mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
542 mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
Edward Lemur85153282020-02-14 22:06:29 +0000543 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000544 mock.patch(
545 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000546 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000547 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000548 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000549 mock.patch(
550 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000551 # It's important to reset settings to not have inter-tests interference.
552 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000553 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000554
555 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000556 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000557 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100558 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000559 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
560 if len(self.calls) > 5:
561 calls += ' ...\n'
562 self.fail(
563 '\n'
564 'There are un-consumed calls after this test has finished:\n' +
565 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000566 finally:
567 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000568
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000569 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000570 self.assertTrue(
571 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700572 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000573 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000574 expected_args, result = top
575
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000576 # Also logs otherwise it could get caught in a try/finally and be hard to
577 # diagnose.
578 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700579 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000580 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700581 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
582 for i, c in enumerate(self._calls_done[-N:]))
583 following_calls = '\n '.join(
584 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
585 for i, c in enumerate(self.calls[:N]))
586 extended_msg = (
587 'A few prior calls:\n %s\n\n'
588 'This (expected):\n @%d: %r\n'
589 'This (actual):\n @%d: %r\n\n'
590 'A few following expected calls:\n %s' %
591 (prior_calls, len(self._calls_done), expected_args,
592 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700593
tandrii99a72f22016-08-17 14:33:24 -0700594 self.fail('@%d\n'
595 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000596 ' Actual: %r\n'
597 '\n'
598 '%s' % (
599 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700600
601 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700602 if isinstance(result, Exception):
603 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000604 # stdout from git commands is supposed to be a bytestream. Convert it here
605 # instead of converting all test output in this file to bytes.
606 if args[0][0] == 'git' and not isinstance(result, bytes):
607 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000608 return result
609
Edward Lemur1a83da12020-03-04 21:18:36 +0000610 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
611 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100612 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100613 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000614 self.assertEqual(
615 'prompt [Yes/No]: Please, type yes or no: ',
616 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100617
tandrii48df5812016-10-17 03:55:37 -0700618 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000619 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700620 self.calls = [
621 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700622 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
623 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
624 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
625 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700626 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
627 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700628 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
629 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000630 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
631 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700632 ((['git', 'config', 'gerrit.host', 'true'],), ''),
633 ]
634 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
635
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000636 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100637 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200638 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000639 custom_cl_base=None, short_hostname='chromium',
640 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000641 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200642 if custom_cl_base:
643 ancestor_revision = custom_cl_base
644 else:
645 # Determine ancestor_revision to be merge base.
646 ancestor_revision = 'fake_ancestor_sha'
647 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000648 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
649 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200650 ]
651
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100652 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000653 gerrit_util.GetChangeDetail.return_value = {
654 'owner': {'email': (other_cl_owner or 'owner@example.com')},
655 'change_id': (change_id or '123456789'),
656 'current_revision': 'sha1_of_current_revision',
657 'revisions': {'sha1_of_current_revision': {
658 'commit': {'message': fetched_description},
659 }},
660 'status': fetched_status or 'NEW',
661 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100662 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100663 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100664 if other_cl_owner:
665 calls += [
666 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
667 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100668
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100669 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200670 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
671 ([custom_cl_base] if custom_cl_base else
672 [ancestor_revision, 'HEAD']),),
673 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100674 ]
Edward Lemur2c62b332020-03-12 22:12:33 +0000675
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100676 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000677
Edward Lemur26964072020-02-19 19:18:51 +0000678 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700679 squash_mode='default',
Aaron Gablefd238082017-06-07 13:42:34 -0700680 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100681 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000682 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000683 short_hostname='chromium',
Edward Lemur5a644f82020-03-18 16:44:57 +0000684 labels=None, change_id=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000685 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000686 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000687 if post_amend_description is None:
688 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700689 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200690
691 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000692
Edward Lemur26964072020-02-19 19:18:51 +0000693 if squash_mode in ('override_squash', 'override_nosquash'):
694 self.mockGit.config['gerrit.override-squash-uploads'] = (
695 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700696
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000697 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000698 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200699 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200700 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000701 if squash:
Edward Lemur5a644f82020-03-18 16:44:57 +0000702 if not issue and not force:
Edward Lemur5fb22242020-03-12 22:05:13 +0000703 calls += [
704 ((['RunEditor'],), description),
705 ]
Josipe827b0f2020-01-30 00:07:20 +0000706 # user wants to edit description
707 if edit_description:
708 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000709 ((['RunEditor'],), edit_description),
710 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000711 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200712
713 if custom_cl_base is None:
714 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000715 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000716 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200717 ]
718 parent = 'origin/master'
719 else:
720 calls += [
721 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
722 'refs/remotes/origin/master'],),
723 callError(1)), # Means not ancenstor.
724 (('ask_for_data',
725 'Do you take responsibility for cleaning up potential mess '
726 'resulting from proceeding with upload? Press Enter to upload, '
727 'or Ctrl+C to abort'), ''),
728 ]
729 parent = custom_cl_base
730
731 calls += [
732 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
733 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000734 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200735 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000736 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200737 ref_to_push),
738 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000739 else:
740 ref_to_push = 'HEAD'
Edward Lemur5a644f82020-03-18 16:44:57 +0000741 parent = 'origin/refs/heads/master'
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000742
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000743 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000744 (('SaveDescriptionBackup',), None),
Edward Lemur5a644f82020-03-18 16:44:57 +0000745 ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200746 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000747
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000748 metrics_arguments = []
749
Aaron Gableafd52772017-06-27 16:40:10 -0700750 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700751 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000752 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700753 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400754 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700755 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000756 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700757 else:
758 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000759 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800760
Edward Lemur5a644f82020-03-18 16:44:57 +0000761 # If issue is given, then description is fetched from Gerrit instead.
762 if issue is None:
763 if squash:
764 title = 'Initial upload'
765 else:
766 if not title:
767 calls += [
768 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
769 (('ask_for_data', 'Title for patchset []: '), 'User input'),
770 ]
771 title = 'User input'
Aaron Gable70f4e242017-06-26 10:45:59 -0700772 if title:
Edward Lemur5a644f82020-03-18 16:44:57 +0000773 ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000774 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000775
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000776 if short_hostname == 'chromium':
777 # All reviwers and ccs get into ref_suffix.
778 for r in sorted(reviewers):
779 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000780 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000781 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000782 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000783 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000784 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000785 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000786 reviewers, cc = [], []
787 else:
788 # TODO(crbug/877717): remove this case.
789 calls += [
790 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
791 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000792 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000793 {
794 e: {'email': e}
795 for e in (reviewers + ['joe@example.com'] + cc)
796 })
797 ]
798 for r in sorted(reviewers):
799 if r != 'bad-account-or-email':
800 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000801 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000802 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000803 if issue is None:
804 cc += ['joe@example.com']
805 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000806 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000807 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000808 if c in cc:
809 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000810
Edward Lemur687ca902018-12-05 02:30:30 +0000811 for k, v in sorted((labels or {}).items()):
812 ref_suffix += ',l=%s+%d' % (k, v)
813 metrics_arguments.append('l=%s+%d' % (k, v))
814
815 if tbr:
816 calls += [
817 (('GetCodeReviewTbrScore',
818 '%s-review.googlesource.com' % short_hostname,
819 'my/repo'),
820 2,),
821 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000822
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000823 calls += [
824 (('time.time',), 1000,),
825 ((['git', 'push',
826 'https://%s.googlesource.com/my/repo' % short_hostname,
827 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
828 (('remote:\n'
829 'remote: Processing changes: (\)\n'
830 'remote: Processing changes: (|)\n'
831 'remote: Processing changes: (/)\n'
832 'remote: Processing changes: (-)\n'
833 'remote: Processing changes: new: 1 (/)\n'
834 'remote: Processing changes: new: 1, done\n'
835 'remote:\n'
836 'remote: New Changes:\n'
837 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
838 ' XXX\n'
839 'remote:\n'
840 'To https://%s.googlesource.com/my/repo\n'
841 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
842 ) % (short_hostname, short_hostname)),),
843 (('time.time',), 2000,),
844 (('add_repeated',
845 'sub_commands',
846 {
847 'execution_time': 1000,
848 'command': 'git push',
849 'exit_code': 0,
850 'arguments': sorted(metrics_arguments),
851 }),
852 None,),
853 ]
854
Edward Lemur1b52d872019-05-09 21:12:12 +0000855 final_description = final_description or post_amend_description.strip()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000856
857 date_format = ('03/16/17 20:00:41'
858 if sys.platform == 'win32' and sys.version_info.major == 2
859 else 'Thu Mar 16 20:00:41 2017')
860 trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
861
Edward Lemur1b52d872019-05-09 21:12:12 +0000862 # Trace-related calls
863 calls += [
864 # Write a description with context for the current trace.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000865 (
866 ([
867 'FileWrite', trace_name + '-README',
868 '%(date)s\n'
869 '%(short_hostname)s-review.googlesource.com\n'
870 '%(change_id)s\n'
871 '%(title)s\n'
872 '%(description)s\n'
873 '1000\n'
874 '0\n'
875 '%(trace_name)s' % {
876 'date': date_format,
877 'short_hostname': short_hostname,
878 'change_id': change_id,
879 'description': final_description,
880 'title': title or '<untitled>',
881 'trace_name': trace_name,
882 }
883 ], ),
884 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000885 ),
886 # Read traces and shorten git hashes.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000887 (
888 (['os.path.isfile',
889 os.path.join('TEMP_DIR', 'trace-packet')], ),
890 True,
Edward Lemur1b52d872019-05-09 21:12:12 +0000891 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000892 (
893 (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
894 ('git-hash: 0123456789012345678901234567890123456789\n'
895 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
Edward Lemur1b52d872019-05-09 21:12:12 +0000896 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000897 (
898 ([
899 'FileWrite',
900 os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
901 'git-hash: abcdea\n'
902 ], ),
903 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000904 ),
905 # Make zip file for the git traces.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000906 (
907 (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
908 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000909 ),
910 # Collect git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000911 (
912 (['git', 'config', '-l'], ),
913 'git-config-output',
Edward Lemur1b52d872019-05-09 21:12:12 +0000914 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000915 (
916 ([
917 'FileWrite',
918 os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
919 ], ),
920 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000921 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000922 (
923 (['os.path.isfile',
924 os.path.join('~', '.gitcookies')], ),
925 gitcookies_exists,
Edward Lemur1b52d872019-05-09 21:12:12 +0000926 ),
927 ]
928 if gitcookies_exists:
929 calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000930 (
931 (['FileRead', os.path.join('~', '.gitcookies')], ),
932 'gitcookies 1/SECRET',
Edward Lemur1b52d872019-05-09 21:12:12 +0000933 ),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000934 (
935 ([
936 'FileWrite',
937 os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
938 ], ),
939 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000940 ),
941 ]
942 calls += [
943 # Make zip file for the git config and gitcookies.
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000944 (
945 (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
946 None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000947 ),
948 ]
949
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000950 # TODO(crbug/877717): this should never be used.
951 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000952 calls += [
953 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +0000954 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000955 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +0000956 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +0000957 notify),
958 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000959 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000960 return calls
961
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000962 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000963 self,
964 upload_args,
965 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000966 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700967 squash=True,
968 squash_mode=None,
Aaron Gable9b713dd2016-12-14 16:04:21 -0800969 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000970 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000971 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -0700972 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100973 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100974 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200975 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -0700976 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000977 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000978 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000979 labels=None,
980 change_id=None,
Edward Lemur1b52d872019-05-09 21:12:12 +0000981 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000982 gitcookies_exists=True,
983 force=False,
Josipe827b0f2020-01-30 00:07:20 +0000984 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000985 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000986 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700987 if squash_mode is None:
988 if '--no-squash' in upload_args:
989 squash_mode = 'nosquash'
990 elif '--squash' in upload_args:
991 squash_mode = 'squash'
992 else:
993 squash_mode = 'default'
994
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000995 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -0700996 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000997 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100998 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000999 same_auth=('git-owner.example.com', '', 'pass'))).start()
1000 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1001 lambda _, offer_removal: None).start()
1002 mock.patch('git_cl.gclient_utils.RunEditor',
1003 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1004 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1005 'DownloadGerritHook', force)).start()
1006 mock.patch('git_cl.gclient_utils.FileRead',
1007 lambda path: self._mocked_call(['FileRead', path])).start()
1008 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001009 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001010 ['FileWrite', path, contents])).start()
1011 mock.patch('git_cl.datetime_now',
1012 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1013 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1014 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1015 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001016 '%(now)s\n'
1017 '%(gerrit_host)s\n'
1018 '%(change_id)s\n'
1019 '%(title)s\n'
1020 '%(description)s\n'
1021 '%(execution_time)s\n'
1022 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001023 '%(trace_name)s').start()
1024 mock.patch('git_cl.shutil.make_archive',
1025 lambda *args: self._mocked_call(['make_archive'] +
1026 list(args))).start()
1027 mock.patch('os.path.isfile',
1028 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001029 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00001030 'git_cl._create_description_from_log', return_value=description).start()
1031 mock.patch(
1032 'git_cl.Changelist._AddChangeIdToCommitMessage',
1033 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001034 mock.patch(
Edward Lemur5a644f82020-03-18 16:44:57 +00001035 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
1036 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001037 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001038 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001039
Edward Lemur26964072020-02-19 19:18:51 +00001040 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001041 self.mockGit.config['branch.master.gerritissue'] = (
1042 str(issue) if issue else None)
1043 self.mockGit.config['remote.origin.url'] = (
1044 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001045 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001046
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001047 self.calls = self._gerrit_base_calls(
1048 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001049 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001050 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001051 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001052 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001053 short_hostname=short_hostname,
1054 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001055 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001056 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001057 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001058 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001059 self.calls += self._gerrit_upload_calls(
1060 description, reviewers, squash,
1061 squash_mode=squash_mode,
Aaron Gablefd238082017-06-07 13:42:34 -07001062 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001063 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001064 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001065 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001066 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001067 labels=labels,
1068 change_id=change_id,
Edward Lemur1b52d872019-05-09 21:12:12 +00001069 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001070 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001071 force=force,
1072 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001073 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001074 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001075 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001076 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001077 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001078 self.assertEqual(
1079 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001080 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001081
Edward Lemur1b52d872019-05-09 21:12:12 +00001082 def test_gerrit_upload_traces_no_gitcookies(self):
1083 self._run_gerrit_upload_test(
1084 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001085 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001086 [],
1087 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001088 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001089 change_id='Ixxx',
1090 gitcookies_exists=False)
1091
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001092 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001093 self._run_gerrit_upload_test(
Edward Lemur5a644f82020-03-18 16:44:57 +00001094 [],
1095 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
1096 [],
1097 change_id='Ixxx')
1098
1099 def test_gerrit_upload_without_change_id_nosquash(self):
1100 self._run_gerrit_upload_test(
tandriia60502f2016-06-20 02:01:53 -07001101 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001102 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001103 [],
1104 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001105 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001106 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001107
1108 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001109 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001110 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001111 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001112 [],
tandriia60502f2016-06-20 02:01:53 -07001113 squash=False,
1114 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001115 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001116 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001117
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001118 def test_gerrit_no_reviewer(self):
1119 self._run_gerrit_upload_test(
1120 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001121 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001122 [],
1123 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001124 squash_mode='override_nosquash',
1125 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001126
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001127 def test_gerrit_no_reviewer_non_chromium_host(self):
1128 # TODO(crbug/877717): remove this test case.
1129 self._run_gerrit_upload_test(
1130 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001131 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001132 [],
1133 squash=False,
1134 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001135 short_hostname='other',
1136 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001137
Nick Carter8692b182017-11-06 16:30:38 -08001138 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001139 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001140 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001141 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001142 squash=False,
1143 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001144 change_id='I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001145 title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001146
ukai@chromium.orge8077812012-02-03 03:41:46 +00001147 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001148 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001149 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001150 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Edward Lemur5a644f82020-03-18 16:44:57 +00001151 reviewers=['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001152 squash=False,
1153 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001154 notify=True,
1155 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001156 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001157 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001158
Anthony Polito8b955342019-09-24 19:01:36 +00001159 def test_gerrit_upload_force_sets_bug(self):
1160 self._run_gerrit_upload_test(
1161 ['-b', '10000', '-f'],
1162 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1163 [],
1164 force=True,
Anthony Polito8b955342019-09-24 19:01:36 +00001165 fetched_description='desc=\n\nChange-Id: Ixxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001166 change_id='Ixxx')
1167
Edward Lemur5fb22242020-03-12 22:05:13 +00001168 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001169 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001170 ['-b', '10000', '-m', 'Title', '--edit-description'],
1171 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001172 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001173 issue='123456',
Edward Lemur5fb22242020-03-12 22:05:13 +00001174 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001175 fetched_description='desc=\n\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001176 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001177 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001178
Dan Beamd8b04ca2019-10-10 21:23:26 +00001179 def test_gerrit_upload_force_sets_fixed(self):
1180 self._run_gerrit_upload_test(
1181 ['-x', '10000', '-f'],
1182 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1183 [],
1184 force=True,
Dan Beamd8b04ca2019-10-10 21:23:26 +00001185 fetched_description='desc=\n\nChange-Id: Ixxx',
Dan Beamd8b04ca2019-10-10 21:23:26 +00001186 change_id='Ixxx')
1187
ukai@chromium.orge8077812012-02-03 03:41:46 +00001188 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001189 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1190 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001191 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001192 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001193 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001194 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001195 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001196 ['reviewer@example.com', 'another@example.com'],
Aaron Gablefd238082017-06-07 13:42:34 -07001197 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001198 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001199 labels={'Code-Review': 2},
Edward Lemur5a644f82020-03-18 16:44:57 +00001200 change_id='123456789')
tandriia60502f2016-06-20 02:01:53 -07001201
1202 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001203 self._run_gerrit_upload_test(
1204 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001205 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001206 [],
Edward Lemur5a644f82020-03-18 16:44:57 +00001207 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001208
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001209 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001210 self._run_gerrit_upload_test(
1211 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001212 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001213 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001214 squash=True,
Edward Lemur5a644f82020-03-18 16:44:57 +00001215 change_id='123456789')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001216
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001217 def test_gerrit_upload_squash_first_with_labels(self):
1218 self._run_gerrit_upload_test(
1219 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001220 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001221 [],
1222 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001223 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
Edward Lemur5a644f82020-03-18 16:44:57 +00001224 change_id='123456789')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001225
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001226 def test_gerrit_upload_squash_first_against_rev(self):
1227 custom_cl_base = 'custom_cl_base_rev_or_branch'
1228 self._run_gerrit_upload_test(
1229 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001230 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001231 [],
1232 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001233 custom_cl_base=custom_cl_base,
Edward Lemur5a644f82020-03-18 16:44:57 +00001234 change_id='123456789')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001235 self.assertIn(
1236 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1237 sys.stdout.getvalue())
1238
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001239 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001240 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001241 self._run_gerrit_upload_test(
1242 ['--squash'],
1243 description,
1244 [],
1245 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001246 issue=123456,
Edward Lemur5a644f82020-03-18 16:44:57 +00001247 change_id='123456789')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001248
Edward Lemurd55c5072020-02-20 01:09:07 +00001249 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001250 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001251 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001252 with self.assertRaises(SystemExitMock):
1253 self._run_gerrit_upload_test(
1254 ['--squash'],
1255 description,
1256 [],
1257 squash=True,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001258 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001259 fetched_status='ABANDONED',
1260 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001261 self.assertEqual(
1262 'Change https://chromium-review.googlesource.com/123456 has been '
1263 'abandoned, new uploads are not allowed\n',
1264 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001265
Edward Lemurda4b6c62020-02-13 00:28:40 +00001266 @mock.patch(
1267 'gerrit_util.GetAccountDetails',
1268 return_value={'email': 'yet-another@example.com'})
1269 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001270 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001271 self._run_gerrit_upload_test(
1272 ['--squash'],
1273 description,
1274 [],
1275 squash=True,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001276 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001277 other_cl_owner='other@example.com',
Edward Lemur5a644f82020-03-18 16:44:57 +00001278 change_id='123456789')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001279 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001280 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001281 'authenticate to Gerrit as yet-another@example.com.\n'
1282 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001283 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001284
Josipe827b0f2020-01-30 00:07:20 +00001285 def test_upload_change_description_editor(self):
1286 fetched_description = 'foo\n\nChange-Id: 123456789'
1287 description = 'bar\n\nChange-Id: 123456789'
1288 self._run_gerrit_upload_test(
1289 ['--squash', '--edit-description'],
1290 description,
1291 [],
1292 fetched_description=fetched_description,
1293 squash=True,
Josipe827b0f2020-01-30 00:07:20 +00001294 issue=123456,
1295 change_id='123456789',
Josipe827b0f2020-01-30 00:07:20 +00001296 edit_description=description)
1297
Edward Lemurda4b6c62020-02-13 00:28:40 +00001298 @mock.patch('git_cl.RunGit')
1299 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001300 @mock.patch('sys.stdin', StringIO('\n'))
1301 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001302 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001303 def mock_run_git(*args, **_kwargs):
1304 if args[0] == ['for-each-ref',
1305 '--format=%(refname:short) %(upstream:short)',
1306 'refs/heads']:
1307 # Create a local branch dependency tree that looks like this:
1308 # test1 -> test2 -> test3 -> test4 -> test5
1309 # -> test3.1
1310 # test6 -> test0
1311 branch_deps = [
1312 'test2 test1', # test1 -> test2
1313 'test3 test2', # test2 -> test3
1314 'test3.1 test2', # test2 -> test3.1
1315 'test4 test3', # test3 -> test4
1316 'test5 test4', # test4 -> test5
1317 'test6 test0', # test0 -> test6
1318 'test7', # test7
1319 ]
1320 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001321 git_cl.RunGit.side_effect = mock_run_git
1322 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001323
1324 class MockChangelist():
1325 def __init__(self):
1326 pass
1327 def GetBranch(self):
1328 return 'test1'
1329 def GetIssue(self):
1330 return '123'
1331 def GetPatchset(self):
1332 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001333 def IsGerrit(self):
1334 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001335
1336 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1337 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001338 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001339 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001340 'This command will checkout all dependent branches '
1341 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001342 'or Ctrl+C to abort',
1343 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001344 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001345
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001346 def test_gerrit_change_id(self):
1347 self.calls = [
1348 ((['git', 'write-tree'], ),
1349 'hashtree'),
1350 ((['git', 'rev-parse', 'HEAD~0'], ),
1351 'branch-parent'),
1352 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1353 'A B <a@b.org> 1456848326 +0100'),
1354 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1355 'C D <c@d.org> 1456858326 +0100'),
1356 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1357 'hashchange'),
1358 ]
1359 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1360 self.assertEqual(change_id, 'Ihashchange')
1361
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001362 def test_desecription_append_footer(self):
1363 for init_desc, footer_line, expected_desc in [
1364 # Use unique desc first lines for easy test failure identification.
1365 ('foo', 'R=one', 'foo\n\nR=one'),
1366 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1367 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1368 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1369 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1370 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1371 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1372 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1373 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1374 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1375 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1376 ]:
1377 desc = git_cl.ChangeDescription(init_desc)
1378 desc.append_footer(footer_line)
1379 self.assertEqual(desc.description, expected_desc)
1380
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001381 def test_update_reviewers(self):
1382 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001383 ('foo', [], [],
1384 'foo'),
1385 ('foo\nR=xx', [], [],
1386 'foo\nR=xx'),
1387 ('foo\nTBR=xx', [], [],
1388 'foo\nTBR=xx'),
1389 ('foo', ['a@c'], [],
1390 'foo\n\nR=a@c'),
1391 ('foo\nR=xx', ['a@c'], [],
1392 'foo\n\nR=a@c, xx'),
1393 ('foo\nTBR=xx', ['a@c'], [],
1394 'foo\n\nR=a@c\nTBR=xx'),
1395 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1396 'foo\n\nR=a@c, yy\nTBR=xx'),
1397 ('foo\nBUG=', ['a@c'], [],
1398 'foo\nBUG=\nR=a@c'),
1399 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1400 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1401 ('foo', ['a@c', 'b@c'], [],
1402 'foo\n\nR=a@c, b@c'),
1403 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1404 'foo\nBar\n\nR=c@c\nBUG='),
1405 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1406 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001407 # Same as the line before, but full of whitespaces.
1408 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001409 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001410 'foo\nBar\n\nR=c@c\n BUG =',
1411 ),
1412 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001413 ('foo BUG=allo R=joe ', ['c@c'], [],
1414 'foo BUG=allo R=joe\n\nR=c@c'),
1415 # Redundant TBRs get promoted to Rs
1416 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1417 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001418 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001419 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001420 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001421 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001422 obj = git_cl.ChangeDescription(orig)
Edward Lemur2c62b332020-03-12 22:12:33 +00001423 obj.update_reviewers(reviewers, tbrs, None, None, None)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001424 actual.append(obj.description)
1425 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001426
Nodir Turakulov23b82142017-11-16 11:04:25 -08001427 def test_get_hash_tags(self):
1428 cases = [
1429 ('', []),
1430 ('a', []),
1431 ('[a]', ['a']),
1432 ('[aa]', ['aa']),
1433 ('[a ]', ['a']),
1434 ('[a- ]', ['a']),
1435 ('[a- b]', ['a-b']),
1436 ('[a--b]', ['a-b']),
1437 ('[a', []),
1438 ('[a]x', ['a']),
1439 ('[aa]x', ['aa']),
1440 ('[a b]', ['a-b']),
1441 ('[a b]', ['a-b']),
1442 ('[a__b]', ['a-b']),
1443 ('[a] x', ['a']),
1444 ('[a][b]', ['a', 'b']),
1445 ('[a] [b]', ['a', 'b']),
1446 ('[a][b]x', ['a', 'b']),
1447 ('[a][b] x', ['a', 'b']),
1448 ('[a]\n[b]', ['a']),
1449 ('[a\nb]', []),
1450 ('[a][', ['a']),
1451 ('Revert "[a] feature"', ['a']),
1452 ('Reland "[a] feature"', ['a']),
1453 ('Revert: [a] feature', ['a']),
1454 ('Reland: [a] feature', ['a']),
1455 ('Revert "Reland: [a] feature"', ['a']),
1456 ('Foo: feature', ['foo']),
1457 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001458 ('Change Foo::Bar', []),
1459 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001460 ('Revert "Foo bar: feature"', ['foo-bar']),
1461 ('Reland "Foo bar: feature"', ['foo-bar']),
1462 ]
1463 for desc, expected in cases:
1464 change_desc = git_cl.ChangeDescription(desc)
1465 actual = change_desc.get_hash_tags()
1466 self.assertEqual(
1467 actual,
1468 expected,
1469 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1470
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001471 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001472 self.assertEqual(None, git_cl.GetTargetRef(None,
1473 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001474 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001475
wittman@chromium.org455dc922015-01-26 20:15:50 +00001476 # Check default target refs for branches.
1477 self.assertEqual('refs/heads/master',
1478 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001479 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001480 self.assertEqual('refs/heads/master',
1481 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001482 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001483 self.assertEqual('refs/heads/master',
1484 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001485 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001486 self.assertEqual('refs/branch-heads/123',
1487 git_cl.GetTargetRef('origin',
1488 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001489 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001490 self.assertEqual('refs/diff/test',
1491 git_cl.GetTargetRef('origin',
1492 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001493 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001494 self.assertEqual('refs/heads/chrome/m42',
1495 git_cl.GetTargetRef('origin',
1496 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001497 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001498
1499 # Check target refs for user-specified target branch.
1500 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1501 'refs/remotes/branch-heads/123'):
1502 self.assertEqual('refs/branch-heads/123',
1503 git_cl.GetTargetRef('origin',
1504 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001505 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001506 for branch in ('origin/master', 'remotes/origin/master',
1507 'refs/remotes/origin/master'):
1508 self.assertEqual('refs/heads/master',
1509 git_cl.GetTargetRef('origin',
1510 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001511 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001512 for branch in ('master', 'heads/master', 'refs/heads/master'):
1513 self.assertEqual('refs/heads/master',
1514 git_cl.GetTargetRef('origin',
1515 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001516 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001517
Edward Lemurda4b6c62020-02-13 00:28:40 +00001518 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1519 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001520 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001521 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1522
Edward Lemur85153282020-02-14 22:06:29 +00001523 def assertIssueAndPatchset(
1524 self, branch='master', issue='123456', patchset='7',
1525 git_short_host='chromium'):
1526 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001527 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001528 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001529 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001530 self.assertEqual(
1531 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001532 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001533
Edward Lemur85153282020-02-14 22:06:29 +00001534 def _patch_common(self, git_short_host='chromium'):
Edward Lesmese3a49aa2020-03-24 23:46:28 +00001535 mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
Edward Lemur26964072020-02-19 19:18:51 +00001536 self.mockGit.config['remote.origin.url'] = (
1537 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001538 gerrit_util.GetChangeDetail.return_value = {
1539 'current_revision': '7777777777',
1540 'revisions': {
1541 '1111111111': {
1542 '_number': 1,
1543 'fetch': {'http': {
1544 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1545 'ref': 'refs/changes/56/123456/1',
1546 }},
1547 },
1548 '7777777777': {
1549 '_number': 7,
1550 'fetch': {'http': {
1551 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1552 'ref': 'refs/changes/56/123456/7',
1553 }},
1554 },
1555 },
1556 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001557
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001558 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001559 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001560 self.calls += [
1561 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1562 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001563 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001564 ]
1565 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001566 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001567
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001568 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001569 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001570 self.calls += [
1571 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1572 'refs/changes/56/123456/7'],), ''),
1573 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001574 ]
Edward Lemur85153282020-02-14 22:06:29 +00001575 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1576 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001577
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001578 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001579 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001580 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001581 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001582 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001583 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001584 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001585 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001586 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001587
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001588 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001589 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001590 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001591 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001592 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001593 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001594 ]
1595 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001596 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001597 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001598
Aaron Gable697a91b2018-01-19 15:20:15 -08001599 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001600 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001601 self.calls += [
1602 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1603 'refs/changes/56/123456/1'],), ''),
1604 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001605 ]
1606 self.assertEqual(git_cl.main(
1607 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1608 0)
Edward Lemur85153282020-02-14 22:06:29 +00001609 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001610
Edward Lemurd55c5072020-02-20 01:09:07 +00001611 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001612 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001613 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001614 self.calls += [
1615 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001616 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001617 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001618 ]
1619 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001620 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001621 self.assertEqual(
1622 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1623 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001624
Edward Lemurda4b6c62020-02-13 00:28:40 +00001625 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001626 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001627 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001628 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001629 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001630 self.mockGit.config['remote.origin.url'] = (
1631 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001632 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001633 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001634 self.assertEqual(
1635 'change 123456 at https://chromium-review.googlesource.com does not '
1636 'exist or you have no access to it\n',
1637 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001638
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001639 def _checkout_calls(self):
1640 return [
1641 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001642 'branch\\..*\\.gerritissue'], ),
1643 ('branch.ger-branch.gerritissue 123456\n'
1644 'branch.gbranch654.gerritissue 654321\n')),
1645 ]
1646
1647 def test_checkout_gerrit(self):
1648 """Tests git cl checkout <issue>."""
1649 self.calls = self._checkout_calls()
1650 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1651 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1652
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001653 def test_checkout_not_found(self):
1654 """Tests git cl checkout <issue>."""
1655 self.calls = self._checkout_calls()
1656 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1657
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001658 def test_checkout_no_branch_issues(self):
1659 """Tests git cl checkout <issue>."""
1660 self.calls = [
1661 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001662 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001663 ]
1664 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1665
Edward Lemur26964072020-02-19 19:18:51 +00001666 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001667 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00001668 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00001669 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001670 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1671 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001672 self.mockGit.config['remote.origin.url'] = (
1673 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001674 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001675 cl.branch = 'master'
1676 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001677 return cl
1678
Edward Lemurd55c5072020-02-20 01:09:07 +00001679 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001680 def test_gerrit_ensure_authenticated_missing(self):
1681 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001682 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001683 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001684 with self.assertRaises(SystemExitMock):
1685 cl.EnsureAuthenticated(force=False)
1686 self.assertEqual(
1687 'Credentials for the following hosts are required:\n'
1688 ' chromium-review.googlesource.com\n'
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001689 'These are read from ~%(sep)s.gitcookies '
1690 '(or legacy ~%(sep)s%(netrc)s)\n'
Edward Lemurd55c5072020-02-20 01:09:07 +00001691 'You can (re)generate your credentials by visiting '
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00001692 'https://chromium-review.googlesource.com/new-password\n' % {
1693 'sep': os.sep,
1694 'netrc': NETRC_FILENAME,
1695 }, sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001696
1697 def test_gerrit_ensure_authenticated_conflict(self):
1698 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001699 'chromium.googlesource.com':
1700 ('git-one.example.com', None, 'secret1'),
1701 'chromium-review.googlesource.com':
1702 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001703 })
1704 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001705 (('ask_for_data', 'If you know what you are doing '
1706 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001707 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1708
1709 def test_gerrit_ensure_authenticated_ok(self):
1710 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001711 'chromium.googlesource.com':
1712 ('git-same.example.com', None, 'secret'),
1713 'chromium-review.googlesource.com':
1714 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001715 })
1716 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1717
tandrii@chromium.org28253532016-04-14 13:46:56 +00001718 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001719 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1720 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001721 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1722
Eric Boren2fb63102018-10-05 13:05:03 +00001723 def test_gerrit_ensure_authenticated_bearer_token(self):
1724 cl = self._test_gerrit_ensure_authenticated_common(auth={
1725 'chromium.googlesource.com':
1726 ('', None, 'secret'),
1727 'chromium-review.googlesource.com':
1728 ('', None, 'secret'),
1729 })
1730 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1731 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1732 'chromium.googlesource.com')
1733 self.assertTrue('Bearer' in header)
1734
Daniel Chengcf6269b2019-05-18 01:02:12 +00001735 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001736 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001737 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001738 (('logging.warning',
1739 'Ignoring branch %(branch)s with non-https remote '
1740 '%(remote)s', {
1741 'branch': 'master',
1742 'remote': 'custom-scheme://repo'}
1743 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001744 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001745 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1746 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1747 mock.patch('logging.warning',
1748 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001749 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001750 cl.branch = 'master'
1751 cl.branchref = 'refs/heads/master'
1752 cl.lookedup_issue = True
1753 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1754
Florian Mayerae510e82020-01-30 21:04:48 +00001755 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001756 self.mockGit.config['remote.origin.url'] = (
1757 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001758 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001759 (('logging.error',
1760 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1761 'but it doesn\'t exist.', {
1762 'remote': 'origin',
1763 'branch': 'master',
1764 'url': 'git@somehost.example:foo/bar.git'}
1765 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001766 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001767 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1768 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1769 mock.patch('logging.error',
1770 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001771 cl = git_cl.Changelist()
1772 cl.branch = 'master'
1773 cl.branchref = 'refs/heads/master'
1774 cl.lookedup_issue = True
1775 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1776
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001777 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001778 self.mockGit.config['branch.master.gerritissue'] = '123'
1779 self.mockGit.config['branch.master.gerritserver'] = (
1780 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001781 self.mockGit.config['remote.origin.url'] = (
1782 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001783 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001784 (('SetReview', 'chromium-review.googlesource.com',
1785 'infra%2Finfra~123', None,
1786 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001787 ]
tandriid9e5ce52016-07-13 02:32:59 -07001788
1789 def test_cmd_set_commit_gerrit_clear(self):
1790 self._cmd_set_commit_gerrit_common(0)
1791 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1792
1793 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001794 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001795 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1796
tandriid9e5ce52016-07-13 02:32:59 -07001797 def test_cmd_set_commit_gerrit(self):
1798 self._cmd_set_commit_gerrit_common(2)
1799 self.assertEqual(0, git_cl.main(['set-commit']))
1800
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001801 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001802 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001803 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001804
1805 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001806 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001807
Edward Lemurda4b6c62020-02-13 00:28:40 +00001808 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001809 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001810 try:
1811 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001812 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001813 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001814 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001815
1816 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001817 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001818 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001819 return 'foobar'
1820
Edward Lemurda4b6c62020-02-13 00:28:40 +00001821 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001822 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001823 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001824 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001825 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001826
iannuccie53c9352016-08-17 14:40:40 -07001827 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001828
iannuccie53c9352016-08-17 14:40:40 -07001829 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001830 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001831 return 'foobar'
1832
Edward Lemurda4b6c62020-02-13 00:28:40 +00001833 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
1834 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07001835 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001836 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07001837
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001838 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00001839 self.mockGit.config['remote.origin.url'] = (
1840 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001841 gerrit_util.GetChangeDetail.return_value = {
1842 'current_revision': 'sha1',
1843 'revisions': {'sha1': {
1844 'commit': {'message': 'foobar'},
1845 }},
1846 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001847 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001848 'description',
1849 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
1850 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001851 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001852
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001853 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001854 mock.patch('git_cl.Changelist', ChangelistMock).start()
1855 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001856
1857 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1858 self.assertEqual('hihi', ChangelistMock.desc)
1859
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001860 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001861 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001862
1863 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001864 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001865 '# Enter a description of the change.\n'
1866 '# This will be displayed on the codereview site.\n'
1867 '# The first line will also be used as the subject of the review.\n'
1868 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001869 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07001870 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001871 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001872 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07001873 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001874
Edward Lemur6c6827c2020-02-06 21:15:18 +00001875 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001876 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001877
Edward Lemurda4b6c62020-02-13 00:28:40 +00001878 mock.patch('git_cl.Changelist.FetchDescription',
1879 lambda *args: current_desc).start()
1880 mock.patch('git_cl.Changelist.UpdateDescription',
1881 UpdateDescription).start()
1882 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001883
Edward Lemur85153282020-02-14 22:06:29 +00001884 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001885 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001886
Dan Beamd8b04ca2019-10-10 21:23:26 +00001887 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
1888 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
1889
1890 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001891 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00001892 '# Enter a description of the change.\n'
1893 '# This will be displayed on the codereview site.\n'
1894 '# The first line will also be used as the subject of the review.\n'
1895 '#--------------------This line is 72 characters long'
1896 '--------------------\n'
1897 'Some.\n\nFixed: 123\nChange-Id: xxx',
1898 desc)
1899 return desc
1900
Edward Lemurda4b6c62020-02-13 00:28:40 +00001901 mock.patch('git_cl.Changelist.FetchDescription',
1902 lambda *args: current_desc).start()
1903 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00001904
Edward Lemur85153282020-02-14 22:06:29 +00001905 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00001906 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00001907
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001908 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001909 mock.patch('git_cl.Changelist', ChangelistMock).start()
1910 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001911
1912 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1913 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1914
kmarshall3bff56b2016-06-06 18:31:47 -07001915 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001916 self.calls = [
1917 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00001918 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001919 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001920 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00001921 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001922 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001923
Edward Lemurda4b6c62020-02-13 00:28:40 +00001924 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001925 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001926 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1927 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001928 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001929
1930 self.assertEqual(0, git_cl.main(['archive', '-f']))
1931
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001932 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001933 self.calls = [
1934 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1935 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1936 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
1937 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001938 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
1939 ((['git', 'branch', '-D', 'foo'],), '')
1940 ]
1941
Edward Lemurda4b6c62020-02-13 00:28:40 +00001942 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001943 lambda branches, fine_grained, max_processes:
1944 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1945 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001946 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001947
1948 self.assertEqual(0, git_cl.main(['archive', '-f']))
1949
kmarshall3bff56b2016-06-06 18:31:47 -07001950 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001951 self.calls = [
1952 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1953 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001954 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001955 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001956
Edward Lemurda4b6c62020-02-13 00:28:40 +00001957 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001958 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00001959 [(MockChangelistWithBranchAndIssue('master', 1),
1960 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001961
1962 self.assertEqual(1, git_cl.main(['archive', '-f']))
1963
1964 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001965 self.calls = [
1966 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1967 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001968 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001969 ]
kmarshall3bff56b2016-06-06 18:31:47 -07001970
Edward Lemurda4b6c62020-02-13 00:28:40 +00001971 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07001972 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07001973 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1974 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001975 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07001976
kmarshall9249e012016-08-23 12:02:16 -07001977 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
1978
1979 def test_archive_no_tags(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 ((['git', 'branch', '-D', 'foo'],), '')
1985 ]
kmarshall9249e012016-08-23 12:02:16 -07001986
Edward Lemurda4b6c62020-02-13 00:28:40 +00001987 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07001988 lambda branches, fine_grained, max_processes:
1989 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
1990 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00001991 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07001992
1993 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07001994
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001995 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00001996 self.calls = [
1997 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1998 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1999 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002000 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2001 'refs/tags/git-cl-archived-456-foo'),
2002 ((['git', 'branch', '-D', 'foo'],), CERR1),
2003 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2004 'refs/tags/git-cl-archived-456-foo'),
2005 ]
2006
Edward Lemurda4b6c62020-02-13 00:28:40 +00002007 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002008 lambda branches, fine_grained, max_processes:
2009 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2010 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002011 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002012
2013 self.assertEqual(0, git_cl.main(['archive', '-f']))
2014
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002015 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002016 self.mockGit.config['branch.master.gerritissue'] = '123'
2017 self.mockGit.config['branch.master.gerritserver'] = (
2018 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002019 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002020 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002021 ]
2022 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002023 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2024 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002025
Aaron Gable400e9892017-07-12 15:31:21 -07002026 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002027 self.mockGit.config['branch.master.gerritissue'] = '123'
2028 self.mockGit.config['branch.master.gerritserver'] = (
2029 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002030 mock.patch('git_cl.Changelist.FetchDescription',
2031 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002032 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002033 ((['git', 'log', '-1', '--format=%B'],),
2034 'This is a description\n\nChange-Id: Ideadbeef'),
2035 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002036 ]
2037 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002038 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2039 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002040
phajdan.jre328cf92016-08-22 04:12:17 -07002041 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002042 self.mockGit.config['branch.master.gerritissue'] = '123'
2043 self.mockGit.config['branch.master.gerritserver'] = (
2044 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002045 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002046 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002047 {'issue': 123,
2048 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002049 ''),
2050 ]
2051 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2052
tandrii16e0b4e2016-06-07 10:34:28 -07002053 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002054 mock.patch(
2055 'git_cl.os.path.abspath',
2056 lambda path: self._mocked_call(['abspath', path])).start()
2057 mock.patch(
2058 'git_cl.os.path.exists',
2059 lambda path: self._mocked_call(['exists', path])).start()
2060 mock.patch(
2061 'git_cl.gclient_utils.FileRead',
2062 lambda path: self._mocked_call(['FileRead', path])).start()
2063 mock.patch(
2064 'git_cl.gclient_utils.rm_file_or_tree',
2065 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002066 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002067 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002068 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002069 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002070
2071 def test_GerritCommitMsgHookCheck_custom_hook(self):
2072 cl = self._common_GerritCommitMsgHookCheck()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002073 self.calls += [((['exists',
2074 os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2075 ((['FileRead',
2076 os.path.join('.git', 'hooks', 'commit-msg')], ),
2077 '#!/bin/sh\necho "custom hook"')]
Edward Lemur125d60a2019-09-13 18:25:41 +00002078 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002079
2080 def test_GerritCommitMsgHookCheck_not_exists(self):
2081 cl = self._common_GerritCommitMsgHookCheck()
2082 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002083 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002084 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002085 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002086
2087 def test_GerritCommitMsgHookCheck(self):
2088 cl = self._common_GerritCommitMsgHookCheck()
2089 self.calls += [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002090 ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
2091 ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
tandrii16e0b4e2016-06-07 10:34:28 -07002092 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002093 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002094 ((['rm_file_or_tree',
2095 os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
tandrii16e0b4e2016-06-07 10:34:28 -07002096 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002097 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002098
tandriic4344b52016-08-29 06:04:54 -07002099 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002100 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2101 self.mockGit.config['branch.master.gerritserver'] = (
2102 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002103 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002104 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002105 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002106 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002107 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002108 'labels': {},
2109 'current_revision': 'deadbeaf',
2110 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002111 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002112 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002113 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002114 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2115 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002116 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002117 self.assertEqual(0, cl.CMDLand(force=True,
2118 bypass_hooks=True,
2119 verbose=True,
2120 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002121 self.assertIn(
2122 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002123 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002124 self.assertIn(
2125 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002126 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002127
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002128 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002129 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002130
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002131 def test_gerrit_change_detail_cache_simple(self):
2132 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002133 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002134 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002135 cl1._cached_remote_url = (
2136 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002137 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002138 cl2._cached_remote_url = (
2139 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002140 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2141 self.assertEqual(cl1._GetChangeDetail(), 'a')
2142 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002143
2144 def test_gerrit_change_detail_cache_options(self):
2145 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002146 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002147 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002148 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002149 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2150 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2151 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2152 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2153 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2154 self.assertEqual(cl._GetChangeDetail(), 'cab')
2155
2156 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2157 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2158 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2159 self.assertEqual(cl._GetChangeDetail(), 'cab')
2160
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002161 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002162 gerrit_util.GetChangeDetail.return_value = {
2163 'current_revision': 'rev1',
2164 'revisions': {
2165 'rev1': {'commit': {'message': 'desc1'}},
2166 },
2167 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002168
2169 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002170 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002171 cl._cached_remote_url = (
2172 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002173 self.assertEqual(cl.FetchDescription(), 'desc1')
2174 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002175
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002176 def test_print_current_creds(self):
2177 class CookiesAuthenticatorMock(object):
2178 def __init__(self):
2179 self.gitcookies = {
2180 'host.googlesource.com': ('user', 'pass'),
2181 'host-review.googlesource.com': ('user', 'pass'),
2182 }
2183 self.netrc = self
2184 self.netrc.hosts = {
2185 'github.com': ('user2', None, 'pass2'),
2186 'host2.googlesource.com': ('user3', None, 'pass'),
2187 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002188 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2189 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002190 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2191 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2192 ' Host\t User\t Which file',
2193 '============================\t=====\t===========',
2194 'host-review.googlesource.com\t user\t.gitcookies',
2195 ' host.googlesource.com\t user\t.gitcookies',
2196 ' host2.googlesource.com\tuser3\t .netrc',
2197 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002198 sys.stdout.seek(0)
2199 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002200 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2201 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2202 ' Host\tUser\t Which file',
2203 '============================\t====\t===========',
2204 'host-review.googlesource.com\tuser\t.gitcookies',
2205 ' host.googlesource.com\tuser\t.gitcookies',
2206 ])
2207
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002208 def _common_creds_check_mocks(self):
2209 def exists_mock(path):
2210 dirname = os.path.dirname(path)
2211 if dirname == os.path.expanduser('~'):
2212 dirname = '~'
2213 base = os.path.basename(path)
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002214 if base in (NETRC_FILENAME, '.gitcookies'):
2215 return self._mocked_call('os.path.exists', os.path.join(dirname, base))
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002216 # git cl also checks for existence other files not relevant to this test.
2217 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002218 mock.patch(
Edward Lesmesae3586b2020-03-23 21:21:14 +00002219 'gclient_utils.AskForData',
Edward Lemur1a83da12020-03-04 21:18:36 +00002220 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002221 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002222
2223 def test_creds_check_gitcookies_not_configured(self):
2224 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002225 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2226 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002227 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002228 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2229 ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
2230 (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
2231 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2232 'or Ctrl+C to abort'), ''),
2233 (([
2234 'git', 'config', '--global', 'http.cookiefile',
2235 os.path.expanduser(os.path.join('~', '.gitcookies'))
2236 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002237 ]
2238 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002239 self.assertTrue(
2240 sys.stdout.getvalue().startswith(
2241 'You seem to be using outdated .netrc for git credentials:'))
2242 self.assertIn(
2243 '\nConfigured git to use .gitcookies from',
2244 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002245
2246 def test_creds_check_gitcookies_configured_custom_broken(self):
2247 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002248 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2249 lambda _, include_netrc=False: []).start()
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002250 custom_cookie_path = ('C:\\.gitcookies'
2251 if sys.platform == 'win32' else '/custom/.gitcookies')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002252 self.calls = [
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00002253 ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
2254 ((['git', 'config', '--global', 'http.cookiefile'], ),
2255 custom_cookie_path),
2256 (('os.path.exists', custom_cookie_path), False),
2257 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2258 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2259 (([
2260 'git', 'config', '--global', 'http.cookiefile',
2261 os.path.expanduser(os.path.join('~', '.gitcookies'))
2262 ], ), ''),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002263 ]
2264 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002265 self.assertIn(
2266 'WARNING: You have configured custom path to .gitcookies: ',
2267 sys.stdout.getvalue())
2268 self.assertIn(
2269 'However, your configured .gitcookies file is missing.',
2270 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002271
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002272 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002273 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002274 self.mockGit.config['remote.origin.url'] = (
2275 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002276 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002277 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002278 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002279 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002280 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002281 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002282
Edward Lemurda4b6c62020-02-13 00:28:40 +00002283 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2284 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002285 self.mockGit.config['remote.origin.url'] = (
2286 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002287 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002288 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002289 'current_revision': 'ba5eba11',
2290 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002291 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002292 '_number': 1,
2293 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002294 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002295 '_number': 2,
2296 },
2297 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002298 'messages': [
2299 {
2300 u'_revision_number': 1,
2301 u'author': {
2302 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002303 u'email': u'could-be-anything@example.com',
2304 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002305 },
2306 u'date': u'2017-03-15 20:08:45.000000000',
2307 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002308 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002309 u'tag': u'autogenerated:cq:dry-run'
2310 },
2311 {
2312 u'_revision_number': 2,
2313 u'author': {
2314 u'_account_id': 11151243,
2315 u'email': u'owner@example.com',
2316 u'name': u'owner'
2317 },
2318 u'date': u'2017-03-16 20:00:41.000000000',
2319 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2320 u'message': u'PTAL',
2321 },
2322 {
2323 u'_revision_number': 2,
2324 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002325 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002326 u'email': u'reviewer@example.com',
2327 u'name': u'reviewer'
2328 },
2329 u'date': u'2017-03-17 05:19:37.500000000',
2330 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2331 u'message': u'Patch Set 2: Code-Review+1',
2332 },
2333 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002334 }
2335 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002336 (('GetChangeComments', 'chromium-review.googlesource.com',
2337 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002338 '/COMMIT_MSG': [
2339 {
2340 'author': {'email': u'reviewer@example.com'},
2341 'updated': u'2017-03-17 05:19:37.500000000',
2342 'patch_set': 2,
2343 'side': 'REVISION',
2344 'message': 'Please include a bug link',
2345 },
2346 ],
2347 'codereview.settings': [
2348 {
2349 'author': {'email': u'owner@example.com'},
2350 'updated': u'2017-03-16 20:00:41.000000000',
2351 'patch_set': 2,
2352 'side': 'PARENT',
2353 'line': 42,
2354 'message': 'I removed this because it is bad',
2355 },
2356 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002357 }),
2358 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2359 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002360 ] * 2 + [
2361 (('write_json', 'output.json', [
2362 {
2363 u'date': u'2017-03-16 20:00:41.000000',
2364 u'message': (
2365 u'PTAL\n' +
2366 u'\n' +
2367 u'codereview.settings\n' +
2368 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2369 u'c/1/2/codereview.settings#b42\n' +
2370 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002371 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002372 u'approval': False,
2373 u'disapproval': False,
2374 u'sender': u'owner@example.com'
2375 }, {
2376 u'date': u'2017-03-17 05:19:37.500000',
2377 u'message': (
2378 u'Patch Set 2: Code-Review+1\n' +
2379 u'\n' +
2380 u'/COMMIT_MSG\n' +
2381 u' PS2, File comment: https://chromium-review.googlesource' +
2382 u'.com/c/1/2//COMMIT_MSG#\n' +
2383 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002384 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002385 u'approval': False,
2386 u'disapproval': False,
2387 u'sender': u'reviewer@example.com'
2388 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002389 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002390 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002391 expected_comments_summary = [
2392 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002393 message=(
2394 u'PTAL\n' +
2395 u'\n' +
2396 u'codereview.settings\n' +
2397 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2398 u'c/1/2/codereview.settings#b42\n' +
2399 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002400 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002401 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002402 disapproval=False, approval=False, sender=u'owner@example.com'),
2403 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002404 message=(
2405 u'Patch Set 2: Code-Review+1\n' +
2406 u'\n' +
2407 u'/COMMIT_MSG\n' +
2408 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2409 u'c/1/2//COMMIT_MSG#\n' +
2410 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002411 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002412 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002413 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2414 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002415 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002416 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002417 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002418 self.assertEqual(
2419 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2420
2421 def test_git_cl_comments_robot_comments(self):
2422 # git cl comments also fetches robot comments (which are considered a type
2423 # of autogenerated comment), and unlike other types of comments, only robot
2424 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002425 self.mockGit.config['remote.origin.url'] = (
2426 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002427 gerrit_util.GetChangeDetail.return_value = {
2428 'owner': {'email': 'owner@example.com'},
2429 'current_revision': 'ba5eba11',
2430 'revisions': {
2431 'deadbeaf': {
2432 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002433 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002434 'ba5eba11': {
2435 '_number': 2,
2436 },
2437 },
2438 'messages': [
2439 {
2440 u'_revision_number': 1,
2441 u'author': {
2442 u'_account_id': 1111084,
2443 u'email': u'commit-bot@chromium.org',
2444 u'name': u'Commit Bot'
2445 },
2446 u'date': u'2017-03-15 20:08:45.000000000',
2447 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2448 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2449 u'tag': u'autogenerated:cq:dry-run'
2450 },
2451 {
2452 u'_revision_number': 1,
2453 u'author': {
2454 u'_account_id': 123,
2455 u'email': u'tricium@serviceaccount.com',
2456 u'name': u'Tricium'
2457 },
2458 u'date': u'2017-03-16 20:00:41.000000000',
2459 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2460 u'message': u'(1 comment)',
2461 u'tag': u'autogenerated:tricium',
2462 },
2463 {
2464 u'_revision_number': 1,
2465 u'author': {
2466 u'_account_id': 123,
2467 u'email': u'tricium@serviceaccount.com',
2468 u'name': u'Tricium'
2469 },
2470 u'date': u'2017-03-16 20:00:41.000000000',
2471 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2472 u'message': u'(1 comment)',
2473 u'tag': u'autogenerated:tricium',
2474 },
2475 {
2476 u'_revision_number': 2,
2477 u'author': {
2478 u'_account_id': 123,
2479 u'email': u'tricium@serviceaccount.com',
2480 u'name': u'reviewer'
2481 },
2482 u'date': u'2017-03-17 05:30:37.000000000',
2483 u'tag': u'autogenerated:tricium',
2484 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2485 u'message': u'(1 comment)',
2486 },
2487 ]
2488 }
2489 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002490 (('GetChangeComments', 'chromium-review.googlesource.com',
2491 'infra%2Finfra~1'), {}),
2492 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2493 'infra%2Finfra~1'), {
2494 'codereview.settings': [
2495 {
2496 u'author': {u'email': u'tricium@serviceaccount.com'},
2497 u'updated': u'2017-03-17 05:30:37.000000000',
2498 u'robot_run_id': u'5565031076855808',
2499 u'robot_id': u'Linter/Category',
2500 u'tag': u'autogenerated:tricium',
2501 u'patch_set': 2,
2502 u'side': u'REVISION',
2503 u'message': u'Linter warning message text',
2504 u'line': 32,
2505 },
2506 ],
2507 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002508 ]
2509 expected_comments_summary = [
2510 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2511 message=(
2512 u'(1 comment)\n\ncodereview.settings\n'
2513 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2514 u'c/1/2/codereview.settings#32\n'
2515 u' Linter warning message text\n'),
2516 sender=u'tricium@serviceaccount.com',
2517 autogenerated=True, approval=False, disapproval=False)
2518 ]
2519 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002520 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002521 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002522
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002523 def test_get_remote_url_with_mirror(self):
2524 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002525
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002526 def selective_os_path_isdir_mock(path):
2527 if path == '/cache/this-dir-exists':
2528 return self._mocked_call('os.path.isdir', path)
2529 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002530
Edward Lemurda4b6c62020-02-13 00:28:40 +00002531 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002532
2533 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002534 self.mockGit.config['remote.origin.url'] = (
2535 '/cache/this-dir-exists')
2536 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2537 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002538 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002539 (('os.path.isdir', '/cache/this-dir-exists'),
2540 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002541 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002542 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002543 self.assertEqual(cl.GetRemoteUrl(), url)
2544 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2545
Edward Lemur298f2cf2019-02-22 21:40:39 +00002546 def test_get_remote_url_non_existing_mirror(self):
2547 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002548
Edward Lemur298f2cf2019-02-22 21:40:39 +00002549 def selective_os_path_isdir_mock(path):
2550 if path == '/cache/this-dir-doesnt-exist':
2551 return self._mocked_call('os.path.isdir', path)
2552 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002553
Edward Lemurda4b6c62020-02-13 00:28:40 +00002554 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2555 mock.patch('logging.error',
2556 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002557
Edward Lemur26964072020-02-19 19:18:51 +00002558 self.mockGit.config['remote.origin.url'] = (
2559 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002560 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002561 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2562 False),
2563 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002564 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2565 'but it doesn\'t exist.', {
2566 'remote': 'origin',
2567 'branch': 'master',
2568 'url': '/cache/this-dir-doesnt-exist'}
2569 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002570 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002571 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002572 self.assertIsNone(cl.GetRemoteUrl())
2573
2574 def test_get_remote_url_misconfigured_mirror(self):
2575 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002576
Edward Lemur298f2cf2019-02-22 21:40:39 +00002577 def selective_os_path_isdir_mock(path):
2578 if path == '/cache/this-dir-exists':
2579 return self._mocked_call('os.path.isdir', path)
2580 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002581
Edward Lemurda4b6c62020-02-13 00:28:40 +00002582 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2583 mock.patch('logging.error',
2584 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002585
Edward Lemur26964072020-02-19 19:18:51 +00002586 self.mockGit.config['remote.origin.url'] = (
2587 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002588 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002589 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002590 (('logging.error',
2591 'Remote "%(remote)s" for branch "%(branch)s" points to '
2592 '"%(cache_path)s", but it is misconfigured.\n'
2593 '"%(cache_path)s" must be a git repo and must have a remote named '
2594 '"%(remote)s" pointing to the git host.', {
2595 'remote': 'origin',
2596 'cache_path': '/cache/this-dir-exists',
2597 'branch': 'master'}
2598 ), None),
2599 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002600 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002601 self.assertIsNone(cl.GetRemoteUrl())
2602
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002603 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002604 self.mockGit.config['remote.origin.url'] = (
2605 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002606 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002607 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2608
2609 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002610 mock.patch('logging.error',
2611 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002612
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002613 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002614 (('logging.error',
2615 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2616 'but it doesn\'t exist.', {
2617 'remote': 'origin',
2618 'branch': 'master',
2619 'url': ''}
2620 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002621 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002622 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002623 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002624
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002625
Edward Lemur9aa1a962020-02-25 00:58:38 +00002626class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002627 def setUp(self):
2628 super(ChangelistTest, self).setUp()
2629 mock.patch('gclient_utils.FileRead').start()
2630 mock.patch('gclient_utils.FileWrite').start()
2631 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2632 mock.patch(
2633 'git_cl.Changelist.GetCodereviewServer',
2634 return_value='https://chromium-review.googlesource.com').start()
2635 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2636 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2637 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2638 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2639 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2640 mock.patch('git_cl.time_time').start()
2641 mock.patch('metrics.collector').start()
2642 mock.patch('subprocess2.Popen').start()
2643 self.addCleanup(mock.patch.stopall)
2644 self.temp_count = 0
2645
Edward Lemur227d5102020-02-25 23:45:35 +00002646 def testRunHook(self):
2647 expected_results = {
2648 'more_cc': ['more@example.com', 'cc@example.com'],
2649 'should_continue': True,
2650 }
2651 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2652 git_cl.time_time.side_effect = [100, 200]
2653 mockProcess = mock.Mock()
2654 mockProcess.wait.return_value = 0
2655 subprocess2.Popen.return_value = mockProcess
2656
2657 cl = git_cl.Changelist()
2658 results = cl.RunHook(
2659 committing=True,
2660 may_prompt=True,
2661 verbose=2,
2662 parallel=True,
2663 upstream='upstream',
2664 description='description',
2665 all_files=True)
2666
2667 self.assertEqual(expected_results, results)
2668 subprocess2.Popen.assert_called_once_with([
2669 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002670 '--root', 'root',
2671 '--upstream', 'upstream',
2672 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002673 '--author', 'author',
2674 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002675 '--issue', '123456',
2676 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002677 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002678 '--may_prompt',
2679 '--parallel',
2680 '--all_files',
2681 '--json_output', '/tmp/fake-temp2',
2682 '--description_file', '/tmp/fake-temp1',
2683 ])
2684 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002685 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002686 metrics.collector.add_repeated('sub_commands', {
2687 'command': 'presubmit',
2688 'execution_time': 100,
2689 'exit_code': 0,
2690 })
2691
Edward Lemur99df04e2020-03-05 19:39:43 +00002692 def testRunHook_FewerOptions(self):
2693 expected_results = {
2694 'more_cc': ['more@example.com', 'cc@example.com'],
2695 'should_continue': True,
2696 }
2697 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2698 git_cl.time_time.side_effect = [100, 200]
2699 mockProcess = mock.Mock()
2700 mockProcess.wait.return_value = 0
2701 subprocess2.Popen.return_value = mockProcess
2702
2703 git_cl.Changelist.GetAuthor.return_value = None
2704 git_cl.Changelist.GetIssue.return_value = None
2705 git_cl.Changelist.GetPatchset.return_value = None
2706 git_cl.Changelist.GetCodereviewServer.return_value = None
2707
2708 cl = git_cl.Changelist()
2709 results = cl.RunHook(
2710 committing=False,
2711 may_prompt=False,
2712 verbose=0,
2713 parallel=False,
2714 upstream='upstream',
2715 description='description',
2716 all_files=False)
2717
2718 self.assertEqual(expected_results, results)
2719 subprocess2.Popen.assert_called_once_with([
2720 'vpython', 'PRESUBMIT_SUPPORT',
2721 '--root', 'root',
2722 '--upstream', 'upstream',
2723 '--upload',
2724 '--json_output', '/tmp/fake-temp2',
2725 '--description_file', '/tmp/fake-temp1',
2726 ])
2727 gclient_utils.FileWrite.assert_called_once_with(
2728 '/tmp/fake-temp1', 'description')
2729 metrics.collector.add_repeated('sub_commands', {
2730 'command': 'presubmit',
2731 'execution_time': 100,
2732 'exit_code': 0,
2733 })
2734
Edward Lemur227d5102020-02-25 23:45:35 +00002735 @mock.patch('sys.exit', side_effect=SystemExitMock)
2736 def testRunHook_Failure(self, _mock):
2737 git_cl.time_time.side_effect = [100, 200]
2738 mockProcess = mock.Mock()
2739 mockProcess.wait.return_value = 2
2740 subprocess2.Popen.return_value = mockProcess
2741
2742 cl = git_cl.Changelist()
2743 with self.assertRaises(SystemExitMock):
2744 cl.RunHook(
2745 committing=True,
2746 may_prompt=True,
2747 verbose=2,
2748 parallel=True,
2749 upstream='upstream',
2750 description='description',
2751 all_files=True)
2752
2753 sys.exit.assert_called_once_with(2)
2754
Edward Lemur75526302020-02-27 22:31:05 +00002755 def testRunPostUploadHook(self):
2756 cl = git_cl.Changelist()
2757 cl.RunPostUploadHook(2, 'upstream', 'description')
2758
2759 subprocess2.Popen.assert_called_once_with([
2760 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002761 '--root', 'root',
2762 '--upstream', 'upstream',
2763 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002764 '--author', 'author',
2765 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002766 '--issue', '123456',
2767 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002768 '--post_upload',
2769 '--description_file', '/tmp/fake-temp1',
2770 ])
2771 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002772 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002773
Edward Lemur9aa1a962020-02-25 00:58:38 +00002774
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002775class CMDTestCaseBase(unittest.TestCase):
2776 _STATUSES = [
2777 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2778 'INFRA_FAILURE', 'CANCELED',
2779 ]
2780 _CHANGE_DETAIL = {
2781 'project': 'depot_tools',
2782 'status': 'OPEN',
2783 'owner': {'email': 'owner@e.mail'},
2784 'current_revision': 'beeeeeef',
2785 'revisions': {
2786 'deadbeaf': {'_number': 6},
2787 'beeeeeef': {
2788 '_number': 7,
2789 'fetch': {'http': {
2790 'url': 'https://chromium.googlesource.com/depot_tools',
2791 'ref': 'refs/changes/56/123456/7'
2792 }},
2793 },
2794 },
2795 }
2796 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002797 'builds': [{
2798 'id': str(100 + idx),
2799 'builder': {
2800 'project': 'chromium',
2801 'bucket': 'try',
2802 'builder': 'bot_' + status.lower(),
2803 },
2804 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2805 'tags': [],
2806 'status': status,
2807 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002808 }
2809
Edward Lemur4c707a22019-09-24 21:13:43 +00002810 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002811 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002812 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002813 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2814 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002815 mock.patch(
2816 'git_cl.Changelist.GetCodereviewServer',
2817 return_value='https://chromium-review.googlesource.com').start()
2818 mock.patch(
2819 'git_cl.Changelist._GetGerritHost',
2820 return_value='chromium-review.googlesource.com').start()
2821 mock.patch(
2822 'git_cl.Changelist.GetMostRecentPatchset',
2823 return_value=7).start()
2824 mock.patch(
2825 'git_cl.Changelist.GetRemoteUrl',
2826 return_value='https://chromium.googlesource.com/depot_tools').start()
2827 mock.patch(
2828 'auth.Authenticator',
2829 return_value=AuthenticatorMock()).start()
2830 mock.patch(
2831 'gerrit_util.GetChangeDetail',
2832 return_value=self._CHANGE_DETAIL).start()
2833 mock.patch(
2834 'git_cl._call_buildbucket',
2835 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002836 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002837 self.addCleanup(mock.patch.stopall)
2838
Edward Lemur4c707a22019-09-24 21:13:43 +00002839
Edward Lemur9468eba2020-02-27 19:07:22 +00002840class CMDPresubmitTestCase(CMDTestCaseBase):
2841 def setUp(self):
2842 super(CMDPresubmitTestCase, self).setUp()
2843 mock.patch(
2844 'git_cl.Changelist.GetCommonAncestorWithUpstream',
2845 return_value='upstream').start()
2846 mock.patch(
2847 'git_cl.Changelist.FetchDescription',
2848 return_value='fetch description').start()
2849 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00002850 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00002851 return_value='get description').start()
2852 mock.patch('git_cl.Changelist.RunHook').start()
2853
2854 def testDefaultCase(self):
2855 self.assertEqual(0, git_cl.main(['presubmit']))
2856 git_cl.Changelist.RunHook.assert_called_once_with(
2857 committing=True,
2858 may_prompt=False,
2859 verbose=0,
2860 parallel=None,
2861 upstream='upstream',
2862 description='fetch description',
2863 all_files=None)
2864
2865 def testNoIssue(self):
2866 git_cl.Changelist.GetIssue.return_value = None
2867 self.assertEqual(0, git_cl.main(['presubmit']))
2868 git_cl.Changelist.RunHook.assert_called_once_with(
2869 committing=True,
2870 may_prompt=False,
2871 verbose=0,
2872 parallel=None,
2873 upstream='upstream',
2874 description='get description',
2875 all_files=None)
2876
2877 def testCustomBranch(self):
2878 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
2879 git_cl.Changelist.RunHook.assert_called_once_with(
2880 committing=True,
2881 may_prompt=False,
2882 verbose=0,
2883 parallel=None,
2884 upstream='custom_branch',
2885 description='fetch description',
2886 all_files=None)
2887
2888 def testOptions(self):
2889 self.assertEqual(
2890 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
2891 git_cl.Changelist.RunHook.assert_called_once_with(
2892 committing=False,
2893 may_prompt=False,
2894 verbose=2,
2895 parallel=True,
2896 upstream='upstream',
2897 description='fetch description',
2898 all_files=True)
2899
2900
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002901class CMDTryResultsTestCase(CMDTestCaseBase):
2902 _DEFAULT_REQUEST = {
2903 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002904 "gerritChanges": [{
2905 "project": "depot_tools",
2906 "host": "chromium-review.googlesource.com",
2907 "patchset": 7,
2908 "change": 123456,
2909 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002910 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002911 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2912 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002913 }
2914
2915 def testNoJobs(self):
2916 git_cl._call_buildbucket.return_value = {}
2917
2918 self.assertEqual(0, git_cl.main(['try-results']))
2919 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2920 git_cl._call_buildbucket.assert_called_once_with(
2921 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2922 self._DEFAULT_REQUEST)
2923
2924 def testPrintToStdout(self):
2925 self.assertEqual(0, git_cl.main(['try-results']))
2926 self.assertEqual([
2927 'Successes:',
2928 ' bot_success https://ci.chromium.org/b/103',
2929 'Infra Failures:',
2930 ' bot_infra_failure https://ci.chromium.org/b/105',
2931 'Failures:',
2932 ' bot_failure https://ci.chromium.org/b/104',
2933 'Canceled:',
2934 ' bot_canceled ',
2935 'Started:',
2936 ' bot_started https://ci.chromium.org/b/102',
2937 'Scheduled:',
2938 ' bot_scheduled id=101',
2939 'Other:',
2940 ' bot_status_unspecified id=100',
2941 'Total: 7 tryjobs',
2942 ], sys.stdout.getvalue().splitlines())
2943 git_cl._call_buildbucket.assert_called_once_with(
2944 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2945 self._DEFAULT_REQUEST)
2946
2947 def testPrintToStdoutWithMasters(self):
2948 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2949 self.assertEqual([
2950 'Successes:',
2951 ' try bot_success https://ci.chromium.org/b/103',
2952 'Infra Failures:',
2953 ' try bot_infra_failure https://ci.chromium.org/b/105',
2954 'Failures:',
2955 ' try bot_failure https://ci.chromium.org/b/104',
2956 'Canceled:',
2957 ' try bot_canceled ',
2958 'Started:',
2959 ' try bot_started https://ci.chromium.org/b/102',
2960 'Scheduled:',
2961 ' try bot_scheduled id=101',
2962 'Other:',
2963 ' try bot_status_unspecified id=100',
2964 'Total: 7 tryjobs',
2965 ], sys.stdout.getvalue().splitlines())
2966 git_cl._call_buildbucket.assert_called_once_with(
2967 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2968 self._DEFAULT_REQUEST)
2969
2970 @mock.patch('git_cl.write_json')
2971 def testWriteToJson(self, mockJsonDump):
2972 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
2973 git_cl._call_buildbucket.assert_called_once_with(
2974 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2975 self._DEFAULT_REQUEST)
2976 mockJsonDump.assert_called_once_with(
2977 'file.json', self._DEFAULT_RESPONSE['builds'])
2978
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002979 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00002980 self.assertEqual([], git_cl._filter_failed_for_retry([]))
2981 self.assertEqual(
2982 [
2983 ('chromium', 'try', 'bot_failure'),
2984 ('chromium', 'try', 'bot_infra_failure'),
2985 ],
2986 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002987
2988 def test_filter_failed_for_retry_many_builds(self):
2989
2990 def _build(name, created_sec, status, experimental=False):
2991 assert 0 <= created_sec < 100, created_sec
2992 b = {
2993 'id': 112112,
2994 'builder': {
2995 'project': 'chromium',
2996 'bucket': 'try',
2997 'builder': name,
2998 },
2999 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3000 'status': status,
3001 'tags': [],
3002 }
3003 if experimental:
3004 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3005 return b
3006
3007 builds = [
3008 _build('flaky-last-green', 1, 'FAILURE'),
3009 _build('flaky-last-green', 2, 'SUCCESS'),
3010 _build('flaky', 1, 'SUCCESS'),
3011 _build('flaky', 2, 'FAILURE'),
3012 _build('running', 1, 'FAILED'),
3013 _build('running', 2, 'SCHEDULED'),
3014 _build('yep-still-running', 1, 'STARTED'),
3015 _build('yep-still-running', 2, 'FAILURE'),
3016 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3017 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3018
3019 # Simulate experimental in CQ builder, which developer decided
3020 # to retry manually which resulted in 2nd build non-experimental.
3021 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3022 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3023 ]
3024 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003025 self.assertEqual(
3026 [
3027 ('chromium', 'try', 'flaky'),
3028 ('chromium', 'try', 'sometimes-experimental'),
3029 ],
3030 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003031
3032
3033class CMDTryTestCase(CMDTestCaseBase):
3034
3035 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003036 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003037 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003038 self.assertEqual(0, git_cl.main(['try']))
3039 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3040 self.assertEqual(
3041 sys.stdout.getvalue(),
3042 'Scheduling CQ dry run on: '
3043 'https://chromium-review.googlesource.com/123456\n')
3044
Edward Lemur4c707a22019-09-24 21:13:43 +00003045 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003046 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003047 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003048
3049 self.assertEqual(0, git_cl.main([
3050 'try', '-B', 'luci.chromium.try', '-b', 'win',
3051 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3052 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003053 'Scheduling jobs on:\n'
3054 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003055 git_cl.sys.stdout.getvalue())
3056
3057 expected_request = {
3058 "requests": [{
3059 "scheduleBuild": {
3060 "requestId": "uuid4",
3061 "builder": {
3062 "project": "chromium",
3063 "builder": "win",
3064 "bucket": "try",
3065 },
3066 "gerritChanges": [{
3067 "project": "depot_tools",
3068 "host": "chromium-review.googlesource.com",
3069 "patchset": 7,
3070 "change": 123456,
3071 }],
3072 "properties": {
3073 "category": "git_cl_try",
3074 "json": [{"a": 1}, None],
3075 "key": "val",
3076 },
3077 "tags": [
3078 {"value": "win", "key": "builder"},
3079 {"value": "git_cl_try", "key": "user_agent"},
3080 ],
3081 },
3082 }],
3083 }
3084 mockCallBuildbucket.assert_called_with(
3085 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3086
Anthony Polito1a5fe232020-01-24 23:17:52 +00003087 @mock.patch('git_cl._call_buildbucket')
3088 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3089 mockCallBuildbucket.return_value = {}
3090
3091 self.assertEqual(0, git_cl.main([
3092 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3093 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3094 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3095 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003096 'Scheduling jobs on:\n'
3097 ' chromium/try: linux\n'
3098 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003099 git_cl.sys.stdout.getvalue())
3100
3101 expected_request = {
3102 "requests": [{
3103 "scheduleBuild": {
3104 "requestId": "uuid4",
3105 "builder": {
3106 "project": "chromium",
3107 "builder": "linux",
3108 "bucket": "try",
3109 },
3110 "gerritChanges": [{
3111 "project": "depot_tools",
3112 "host": "chromium-review.googlesource.com",
3113 "patchset": 7,
3114 "change": 123456,
3115 }],
3116 "properties": {
3117 "category": "git_cl_try",
3118 "json": [{"a": 1}, None],
3119 "key": "val",
3120 },
3121 "tags": [
3122 {"value": "linux", "key": "builder"},
3123 {"value": "git_cl_try", "key": "user_agent"},
3124 ],
3125 "gitilesCommit": {
3126 "host": "chromium-review.googlesource.com",
3127 "project": "depot_tools",
3128 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3129 }
3130 },
3131 },
3132 {
3133 "scheduleBuild": {
3134 "requestId": "uuid4",
3135 "builder": {
3136 "project": "chromium",
3137 "builder": "win",
3138 "bucket": "try",
3139 },
3140 "gerritChanges": [{
3141 "project": "depot_tools",
3142 "host": "chromium-review.googlesource.com",
3143 "patchset": 7,
3144 "change": 123456,
3145 }],
3146 "properties": {
3147 "category": "git_cl_try",
3148 "json": [{"a": 1}, None],
3149 "key": "val",
3150 },
3151 "tags": [
3152 {"value": "win", "key": "builder"},
3153 {"value": "git_cl_try", "key": "user_agent"},
3154 ],
3155 "gitilesCommit": {
3156 "host": "chromium-review.googlesource.com",
3157 "project": "depot_tools",
3158 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3159 }
3160 },
3161 }],
3162 }
3163 mockCallBuildbucket.assert_called_with(
3164 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3165
Edward Lemur45768512020-03-02 19:03:14 +00003166 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003167 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003168 with self.assertRaises(SystemExit):
3169 git_cl.main([
3170 'try', '-B', 'not-a-bucket', '-b', 'win',
3171 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003172 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003173 'Invalid bucket: not-a-bucket.',
3174 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003175
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003176 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003177 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003178 def testScheduleOnBuildbucketRetryFailed(
3179 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003180 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003181 7: [],
3182 6: [{
3183 'id': 112112,
3184 'builder': {
3185 'project': 'chromium',
3186 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003187 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003188 'createTime': '2019-10-09T08:00:01.854286Z',
3189 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003190 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003191 mockCallBuildbucket.return_value = {}
3192
3193 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3194 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003195 'Scheduling jobs on:\n'
3196 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003197 git_cl.sys.stdout.getvalue())
3198
3199 expected_request = {
3200 "requests": [{
3201 "scheduleBuild": {
3202 "requestId": "uuid4",
3203 "builder": {
3204 "project": "chromium",
3205 "bucket": "try",
3206 "builder": "linux",
3207 },
3208 "gerritChanges": [{
3209 "project": "depot_tools",
3210 "host": "chromium-review.googlesource.com",
3211 "patchset": 7,
3212 "change": 123456,
3213 }],
3214 "properties": {
3215 "category": "git_cl_try",
3216 },
3217 "tags": [
3218 {"value": "linux", "key": "builder"},
3219 {"value": "git_cl_try", "key": "user_agent"},
3220 {"value": "1", "key": "retry_failed"},
3221 ],
3222 },
3223 }],
3224 }
3225 mockCallBuildbucket.assert_called_with(
3226 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3227
Edward Lemur4c707a22019-09-24 21:13:43 +00003228 def test_parse_bucket(self):
3229 test_cases = [
3230 {
3231 'bucket': 'chromium/try',
3232 'result': ('chromium', 'try'),
3233 },
3234 {
3235 'bucket': 'luci.chromium.try',
3236 'result': ('chromium', 'try'),
3237 'has_warning': True,
3238 },
3239 {
3240 'bucket': 'skia.primary',
3241 'result': ('skia', 'skia.primary'),
3242 'has_warning': True,
3243 },
3244 {
3245 'bucket': 'not-a-bucket',
3246 'result': (None, None),
3247 },
3248 ]
3249
3250 for test_case in test_cases:
3251 git_cl.sys.stdout.truncate(0)
3252 self.assertEqual(
3253 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3254 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003255 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3256 test_case['result'])
3257 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003258
3259
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003260class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003261
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003262 def setUp(self):
3263 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003264 mock.patch('git_cl._fetch_tryjobs').start()
3265 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003266 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003267 self.addCleanup(mock.patch.stopall)
3268
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003269 def testWarmUpChangeDetailCache(self):
3270 self.assertEqual(0, git_cl.main(['upload']))
3271 gerrit_util.GetChangeDetail.assert_called_once_with(
3272 'chromium-review.googlesource.com', 'depot_tools~123456',
3273 frozenset([
3274 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3275 'CURRENT_COMMIT']))
3276
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003277 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003278 # This test mocks out the actual upload part, and just asserts that after
3279 # upload, if --retry-failed is added, then the tool will fetch try jobs
3280 # from the previous patchset and trigger the right builders on the latest
3281 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003282 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003283 # Latest patchset: No builds.
3284 [],
3285 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003286 [{
3287 'id': str(100 + idx),
3288 'builder': {
3289 'project': 'chromium',
3290 'bucket': 'try',
3291 'builder': 'bot_' + status.lower(),
3292 },
3293 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3294 'tags': [],
3295 'status': status,
3296 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003297 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003298
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003299 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003300 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003301 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3302 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003303 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003304 expected_buckets = [
3305 ('chromium', 'try', 'bot_failure'),
3306 ('chromium', 'try', 'bot_infra_failure'),
3307 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003308 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3309 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003310
Brian Sheedy59b06a82019-10-14 17:03:29 +00003311
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003312class MakeRequestsHelperTestCase(unittest.TestCase):
3313
3314 def exampleGerritChange(self):
3315 return {
3316 'host': 'chromium-review.googlesource.com',
3317 'project': 'depot_tools',
3318 'change': 1,
3319 'patchset': 2,
3320 }
3321
3322 def testMakeRequestsHelperNoOptions(self):
3323 # Basic test for the helper function _make_tryjob_schedule_requests;
3324 # it shouldn't throw AttributeError even when options doesn't have any
3325 # of the expected values; it will use default option values.
3326 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3327 jobs = [('chromium', 'try', 'my-builder')]
3328 options = optparse.Values()
3329 requests = git_cl._make_tryjob_schedule_requests(
3330 changelist, jobs, options, patchset=None)
3331
3332 # requestId is non-deterministic. Just assert that it's there and has
3333 # a particular length.
3334 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3335 self.assertEqual(requests, [{
3336 'scheduleBuild': {
3337 'builder': {
3338 'bucket': 'try',
3339 'builder': 'my-builder',
3340 'project': 'chromium'
3341 },
3342 'gerritChanges': [self.exampleGerritChange()],
3343 'properties': {
3344 'category': 'git_cl_try'
3345 },
3346 'tags': [{
3347 'key': 'builder',
3348 'value': 'my-builder'
3349 }, {
3350 'key': 'user_agent',
3351 'value': 'git_cl_try'
3352 }]
3353 }
3354 }])
3355
3356 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3357 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3358 jobs = [('chromium', 'try', 'presubmit')]
3359 options = optparse.Values()
3360 requests = git_cl._make_tryjob_schedule_requests(
3361 changelist, jobs, options, patchset=None)
3362 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3363 'category': 'git_cl_try',
3364 'dry_run': 'true'
3365 })
3366
3367 def testMakeRequestsHelperRevisionSet(self):
3368 # Gitiles commit is specified when revision is in options.
3369 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3370 jobs = [('chromium', 'try', 'my-builder')]
3371 options = optparse.Values({'revision': 'ba5eba11'})
3372 requests = git_cl._make_tryjob_schedule_requests(
3373 changelist, jobs, options, patchset=None)
3374 self.assertEqual(
3375 requests[0]['scheduleBuild']['gitilesCommit'], {
3376 'host': 'chromium-review.googlesource.com',
3377 'id': 'ba5eba11',
3378 'project': 'depot_tools'
3379 })
3380
3381 def testMakeRequestsHelperRetryFailedSet(self):
3382 # An extra tag is added when retry_failed is in options.
3383 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3384 jobs = [('chromium', 'try', 'my-builder')]
3385 options = optparse.Values({'retry_failed': 'true'})
3386 requests = git_cl._make_tryjob_schedule_requests(
3387 changelist, jobs, options, patchset=None)
3388 self.assertEqual(
3389 requests[0]['scheduleBuild']['tags'], [
3390 {
3391 'key': 'builder',
3392 'value': 'my-builder'
3393 },
3394 {
3395 'key': 'user_agent',
3396 'value': 'git_cl_try'
3397 },
3398 {
3399 'key': 'retry_failed',
3400 'value': '1'
3401 }
3402 ])
3403
3404 def testMakeRequestsHelperCategorySet(self):
3405 # The category property can be overriden with options.
3406 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3407 jobs = [('chromium', 'try', 'my-builder')]
3408 options = optparse.Values({'category': 'my-special-category'})
3409 requests = git_cl._make_tryjob_schedule_requests(
3410 changelist, jobs, options, patchset=None)
3411 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3412 {'category': 'my-special-category'})
3413
3414
Edward Lemurda4b6c62020-02-13 00:28:40 +00003415class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003416
3417 def setUp(self):
3418 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003419 mock.patch('git_cl.RunCommand').start()
3420 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3421 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3422 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003423 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003424 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003425
3426 def tearDown(self):
3427 shutil.rmtree(self._top_dir)
3428 super(CMDFormatTestCase, self).tearDown()
3429
Jamie Madill5e96ad12020-01-13 16:08:35 +00003430 def _make_temp_file(self, fname, contents):
3431 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3432 tf.write('\n'.join(contents))
3433
Brian Sheedy59b06a82019-10-14 17:03:29 +00003434 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003435 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003436
Brian Sheedyb4307d52019-12-02 19:18:17 +00003437 def _check_yapf_filtering(self, files, expected):
3438 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3439 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003440
Edward Lemur1a83da12020-03-04 21:18:36 +00003441 def _run_command_mock(self, return_value):
3442 def f(*args, **kwargs):
3443 if 'stdin' in kwargs:
3444 self.assertIsInstance(kwargs['stdin'], bytes)
3445 return return_value
3446 return f
3447
Jamie Madill5e96ad12020-01-13 16:08:35 +00003448 def testClangFormatDiffFull(self):
3449 self._make_temp_file('test.cc', ['// test'])
3450 git_cl.settings.GetFormatFullByDefault.return_value = False
3451 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3452 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3453
3454 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003455 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003456 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3457 self._top_dir, 'HEAD')
3458 self.assertEqual(2, return_value)
3459
3460 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003461 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003462 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3463 self._top_dir, 'HEAD')
3464 self.assertEqual(0, return_value)
3465
3466 def testClangFormatDiff(self):
3467 git_cl.settings.GetFormatFullByDefault.return_value = False
Josip Sokcevic464e9ff2020-03-18 23:48:55 +00003468 # A valid file is required, so use this test.
3469 clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
Jamie Madill5e96ad12020-01-13 16:08:35 +00003470 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3471
3472 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003473 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3474 return_value = git_cl._RunClangFormatDiff(
3475 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003476 self.assertEqual(2, return_value)
3477
3478 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003479 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003480 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3481 'HEAD')
3482 self.assertEqual(0, return_value)
3483
Brian Sheedyb4307d52019-12-02 19:18:17 +00003484 def testYapfignoreExplicit(self):
3485 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3486 files = [
3487 'bar.py',
3488 'foo/bar.py',
3489 'foo/baz.py',
3490 'foo/bar/baz.py',
3491 'foo/bar/foobar.py',
3492 ]
3493 expected = [
3494 'bar.py',
3495 'foo/baz.py',
3496 'foo/bar/foobar.py',
3497 ]
3498 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003499
Brian Sheedyb4307d52019-12-02 19:18:17 +00003500 def testYapfignoreSingleWildcards(self):
3501 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3502 files = [
3503 'bar.py', # Matched by *bar.py.
3504 'bar.txt',
3505 'foobar.py', # Matched by *bar.py, foo*.
3506 'foobar.txt', # Matched by foo*.
3507 'bazbar.py', # Matched by *bar.py, baz*.py.
3508 'bazbar.txt',
3509 'foo/baz.txt', # Matched by foo*.
3510 'bar/bar.py', # Matched by *bar.py.
3511 'baz/foo.py', # Matched by baz*.py, foo*.
3512 'baz/foo.txt',
3513 ]
3514 expected = [
3515 'bar.txt',
3516 'bazbar.txt',
3517 'baz/foo.txt',
3518 ]
3519 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003520
Brian Sheedyb4307d52019-12-02 19:18:17 +00003521 def testYapfignoreMultiplewildcards(self):
3522 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3523 files = [
3524 'bar.py', # Matched by *bar*.
3525 'bar.txt', # Matched by *bar*.
3526 'abar.py', # Matched by *bar*.
3527 'foobaz.txt', # Matched by *foo*baz.txt.
3528 'foobaz.py',
3529 'afoobaz.txt', # Matched by *foo*baz.txt.
3530 ]
3531 expected = [
3532 'foobaz.py',
3533 ]
3534 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003535
3536 def testYapfignoreComments(self):
3537 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003538 files = [
3539 'test.py',
3540 'test2.py',
3541 ]
3542 expected = [
3543 'test2.py',
3544 ]
3545 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003546
3547 def testYapfignoreBlankLines(self):
3548 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003549 files = [
3550 'test.py',
3551 'test2.py',
3552 'test3.py',
3553 ]
3554 expected = [
3555 'test3.py',
3556 ]
3557 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003558
3559 def testYapfignoreWhitespace(self):
3560 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003561 files = [
3562 'test.py',
3563 'test2.py',
3564 ]
3565 expected = [
3566 'test2.py',
3567 ]
3568 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003569
Brian Sheedyb4307d52019-12-02 19:18:17 +00003570 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003571 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003572 self._check_yapf_filtering([], [])
3573
3574 def testYapfignoreMissingYapfignore(self):
3575 files = [
3576 'test.py',
3577 ]
3578 expected = [
3579 'test.py',
3580 ]
3581 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003582
3583
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003584if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003585 logging.basicConfig(
3586 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003587 unittest.main()