blob: ad6adcf9e87495737bda23bf77054c6781fd7b8d [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
maruel@chromium.orgddd59412011-11-30 14:20:38 +000016import os
Edward Lemur85153282020-02-14 22:06:29 +000017import pprint
Brian Sheedy59b06a82019-10-14 17:03:29 +000018import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000019import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070020import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000021import unittest
22
Edward Lemura8145022020-01-06 18:47:54 +000023if sys.version_info.major == 2:
24 from StringIO import StringIO
25 import mock
26else:
27 from io import StringIO
28 from unittest import mock
29
maruel@chromium.orgddd59412011-11-30 14:20:38 +000030sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
31
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000032import metrics
33# We have to disable monitoring before importing git_cl.
34metrics.DISABLE_METRICS_COLLECTION = True
35
Edward Lemur1773f372020-02-22 00:27:14 +000036import contextlib
Jamie Madill5e96ad12020-01-13 16:08:35 +000037import clang_format
Edward Lemur1773f372020-02-22 00:27:14 +000038import gclient_utils
Eric Boren2fb63102018-10-05 13:05:03 +000039import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000040import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000041import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000042import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000043import git_new_branch
44import scm
maruel@chromium.orgddd59412011-11-30 14:20:38 +000045import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000046
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000047
Edward Lemur0db01f02019-11-12 22:01:51 +000048def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070049 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
50
51
Edward Lemur4c707a22019-09-24 21:13:43 +000052def _constantFn(return_value):
53 def f(*args, **kwargs):
54 return return_value
55 return f
56
57
tandrii5d48c322016-08-18 16:19:37 -070058CERR1 = callError(1)
59
60
Edward Lemur1773f372020-02-22 00:27:14 +000061class TemporaryFileMock(object):
62 def __init__(self):
63 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070064
Edward Lemur1773f372020-02-22 00:27:14 +000065 @contextlib.contextmanager
66 def __call__(self):
67 self.suffix += 1
68 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070069
70
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000071class ChangelistMock(object):
72 # A class variable so we can access it when we don't have access to the
73 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000074 desc = ''
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000075 def __init__(self, **kwargs):
76 pass
77 def GetIssue(self):
78 return 1
Edward Lemur6c6827c2020-02-06 21:15:18 +000079 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000080 return ChangelistMock.desc
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
tandrii5d48c322016-08-18 16:19:37 -070084
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000085class PresubmitMock(object):
86 def __init__(self, *args, **kwargs):
87 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080088 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
89
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000090 @staticmethod
91 def should_continue():
92 return True
93
94
Edward Lemur85153282020-02-14 22:06:29 +000095class GitMocks(object):
96 def __init__(self, config=None, branchref=None):
97 self.branchref = branchref or 'refs/heads/master'
98 self.config = config or {}
99
100 def GetBranchRef(self, _root):
101 return self.branchref
102
103 def NewBranch(self, branchref):
104 self.branchref = branchref
105
Edward Lemur26964072020-02-19 19:18:51 +0000106 def GetConfig(self, root, key, default=None):
107 if root != '':
108 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000109 return self.config.get(key, default)
110
Edward Lemur26964072020-02-19 19:18:51 +0000111 def SetConfig(self, root, key, value=None):
112 if root != '':
113 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000114 if value:
115 self.config[key] = value
116 return
117 if key not in self.config:
118 raise CERR1
119 del self.config[key]
120
121
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000122class WatchlistsMock(object):
123 def __init__(self, _):
124 pass
125 @staticmethod
126 def GetWatchersForPaths(_):
127 return ['joe@example.com']
128
129
Edward Lemur4c707a22019-09-24 21:13:43 +0000130class CodereviewSettingsFileMock(object):
131 def __init__(self):
132 pass
133 # pylint: disable=no-self-use
134 def read(self):
135 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
136 'GERRIT_HOST: True\n')
137
138
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000139class AuthenticatorMock(object):
140 def __init__(self, *_args):
141 pass
142 def has_cached_credentials(self):
143 return True
tandrii221ab252016-10-06 08:12:04 -0700144 def authorize(self, http):
145 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000146
147
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100148def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000149 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
150
151 Usage:
152 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100153 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000154
155 OR
156 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100157 CookiesAuthenticatorMockFactory(
158 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000159 """
160 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800161 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000162 # Intentionally not calling super() because it reads actual cookie files.
163 pass
164 @classmethod
165 def get_gitcookies_path(cls):
166 return '~/.gitcookies'
167 @classmethod
168 def get_netrc_path(cls):
169 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100170 def _get_auth_for_host(self, host):
171 if same_auth:
172 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000173 return (hosts_with_creds or {}).get(host)
174 return CookiesAuthenticatorMock
175
Aaron Gable9a03ae02017-11-03 11:31:07 -0700176
kmarshall9249e012016-08-23 12:02:16 -0700177class MockChangelistWithBranchAndIssue():
178 def __init__(self, branch, issue):
179 self.branch = branch
180 self.issue = issue
181 def GetBranch(self):
182 return self.branch
183 def GetIssue(self):
184 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000185
tandriic2405f52016-10-10 08:13:15 -0700186
187class SystemExitMock(Exception):
188 pass
189
190
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000191class TestGitClBasic(unittest.TestCase):
Edward Lemur6c6827c2020-02-06 21:15:18 +0000192 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000193 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100194 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000195 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700196
Edward Lemur61bf4172020-02-24 23:22:37 +0000197 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
198 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
199 def test_get_cl_statuses(self, *_mocks):
200 statuses = [
201 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
202 changes = []
203 for status in statuses:
204 cl = git_cl.Changelist()
205 cl.status = status
206 changes.append(cl)
207
208 actual = set(git_cl.get_cl_statuses(changes, True))
209 self.assertEqual(set(zip(changes, statuses)), actual)
210
211 def test_get_cl_statuses_no_changes(self):
212 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
213
214 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
215 @mock.patch('multiprocessing.pool.ThreadPool')
216 def test_get_cl_statuses_timeout(self, *_mocks):
217 changes = [git_cl.Changelist() for _ in range(2)]
218 pool = multiprocessing.pool.ThreadPool()
219 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
220 it.return_value.next.side_effect = [
221 (changes[0], 'lgtm'),
222 multiprocessing.TimeoutError,
223 ]
224
225 actual = list(git_cl.get_cl_statuses(changes, True))
226 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
227
228 @mock.patch('git_cl.Changelist.GetIssueURL')
229 def test_get_cl_statuses_not_finegrained(self, _mock):
230 changes = [git_cl.Changelist() for _ in range(2)]
231 urls = ['some-url', None]
232 git_cl.Changelist.GetIssueURL.side_effect = urls
233
234 actual = set(git_cl.get_cl_statuses(changes, False))
235 self.assertEqual(
236 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
237
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000238 def test_set_preserve_tryjobs(self):
239 d = git_cl.ChangeDescription('Simple.')
240 d.set_preserve_tryjobs()
241 self.assertEqual(d.description.splitlines(), [
242 'Simple.',
243 '',
244 'Cq-Do-Not-Cancel-Tryjobs: true',
245 ])
246 before = d.description
247 d.set_preserve_tryjobs()
248 self.assertEqual(before, d.description)
249
250 d = git_cl.ChangeDescription('\n'.join([
251 'One is enough',
252 '',
253 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
254 'Change-Id: Ideadbeef',
255 ]))
256 d.set_preserve_tryjobs()
257 self.assertEqual(d.description.splitlines(), [
258 'One is enough',
259 '',
260 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
261 'Change-Id: Ideadbeef',
262 'Cq-Do-Not-Cancel-Tryjobs: true',
263 ])
264
tandriif9aefb72016-07-01 09:06:51 -0700265 def test_get_bug_line_values(self):
266 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
267 self.assertEqual(f('', ''), [])
268 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
269 self.assertEqual(f('v8', '456'), ['v8:456'])
270 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
271 # Not nice, but not worth carying.
272 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
273 ['v8:456', 'chromium:123', 'v8:123'])
274
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100275 def _test_git_number(self, parent_msg, dest_ref, child_msg,
276 parent_hash='parenthash'):
277 desc = git_cl.ChangeDescription(child_msg)
278 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
279 return desc.description
280
281 def assertEqualByLine(self, actual, expected):
282 self.assertEqual(actual.splitlines(), expected.splitlines())
283
284 def test_git_number_bad_parent(self):
285 with self.assertRaises(ValueError):
286 self._test_git_number('Parent', 'refs/heads/master', 'Child')
287
288 def test_git_number_bad_parent_footer(self):
289 with self.assertRaises(AssertionError):
290 self._test_git_number(
291 'Parent\n'
292 '\n'
293 'Cr-Commit-Position: wrong',
294 'refs/heads/master', 'Child')
295
296 def test_git_number_bad_lineage_ignored(self):
297 actual = self._test_git_number(
298 'Parent\n'
299 '\n'
300 'Cr-Commit-Position: refs/heads/master@{#1}\n'
301 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
302 'refs/heads/master', 'Child')
303 self.assertEqualByLine(
304 actual,
305 'Child\n'
306 '\n'
307 'Cr-Commit-Position: refs/heads/master@{#2}\n'
308 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
309
310 def test_git_number_same_branch(self):
311 actual = self._test_git_number(
312 'Parent\n'
313 '\n'
314 'Cr-Commit-Position: refs/heads/master@{#12}',
315 dest_ref='refs/heads/master',
316 child_msg='Child')
317 self.assertEqualByLine(
318 actual,
319 'Child\n'
320 '\n'
321 'Cr-Commit-Position: refs/heads/master@{#13}')
322
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200323 def test_git_number_same_branch_mixed_footers(self):
324 actual = self._test_git_number(
325 'Parent\n'
326 '\n'
327 'Cr-Commit-Position: refs/heads/master@{#12}',
328 dest_ref='refs/heads/master',
329 child_msg='Child\n'
330 '\n'
331 'Broken-by: design\n'
332 'BUG=123')
333 self.assertEqualByLine(
334 actual,
335 'Child\n'
336 '\n'
337 'Broken-by: design\n'
338 'BUG=123\n'
339 'Cr-Commit-Position: refs/heads/master@{#13}')
340
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100341 def test_git_number_same_branch_with_originals(self):
342 actual = self._test_git_number(
343 'Parent\n'
344 '\n'
345 'Cr-Commit-Position: refs/heads/master@{#12}',
346 dest_ref='refs/heads/master',
347 child_msg='Child\n'
348 '\n'
349 'Some users are smart and insert their own footers\n'
350 '\n'
351 'Cr-Whatever: value\n'
352 'Cr-Commit-Position: refs/copy/paste@{#22}')
353 self.assertEqualByLine(
354 actual,
355 'Child\n'
356 '\n'
357 'Some users are smart and insert their own footers\n'
358 '\n'
359 'Cr-Original-Whatever: value\n'
360 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
361 'Cr-Commit-Position: refs/heads/master@{#13}')
362
363 def test_git_number_new_branch(self):
364 actual = self._test_git_number(
365 'Parent\n'
366 '\n'
367 'Cr-Commit-Position: refs/heads/master@{#12}',
368 dest_ref='refs/heads/branch',
369 child_msg='Child')
370 self.assertEqualByLine(
371 actual,
372 'Child\n'
373 '\n'
374 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
375 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
376
377 def test_git_number_lineage(self):
378 actual = self._test_git_number(
379 'Parent\n'
380 '\n'
381 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
382 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
383 dest_ref='refs/heads/branch',
384 child_msg='Child')
385 self.assertEqualByLine(
386 actual,
387 'Child\n'
388 '\n'
389 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
390 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
391
392 def test_git_number_moooooooore_lineage(self):
393 actual = self._test_git_number(
394 'Parent\n'
395 '\n'
396 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
397 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
398 dest_ref='refs/heads/mooore',
399 child_msg='Child')
400 self.assertEqualByLine(
401 actual,
402 'Child\n'
403 '\n'
404 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
405 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
406 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
407
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100408 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700409 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100410 actual = self._test_git_number(
411 'CQ commit on fresh new branch + numbering.\n'
412 '\n'
413 'NOTRY=True\n'
414 'NOPRESUBMIT=True\n'
415 'BUG=\n'
416 '\n'
417 'Review-Url: https://codereview.chromium.org/2577703003\n'
418 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
419 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
420 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
421 dest_ref='refs/heads/gnumb-test/cl',
422 child_msg='git cl on fresh new branch + numbering.\n'
423 '\n'
424 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
425 self.assertEqualByLine(
426 actual,
427 'git cl on fresh new branch + numbering.\n'
428 '\n'
429 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
430 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
431 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
432 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
433 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100434
435 def test_git_number_cherry_pick(self):
436 actual = self._test_git_number(
437 'Parent\n'
438 '\n'
439 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
440 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
441 dest_ref='refs/heads/branch',
442 child_msg='Child, which is cherry-pick from master\n'
443 '\n'
444 'Cr-Commit-Position: refs/heads/master@{#100}\n'
445 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
446 self.assertEqualByLine(
447 actual,
448 'Child, which is cherry-pick from master\n'
449 '\n'
450 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
451 '\n'
452 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
453 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
454 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
455
Edward Lemurda4b6c62020-02-13 00:28:40 +0000456 @mock.patch('gerrit_util.GetAccountDetails')
457 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000458 mock_per_account = {
459 'u1': None, # 404, doesn't exist.
460 'u2': {
461 '_account_id': 123124,
462 'avatars': [],
463 'email': 'u2@example.com',
464 'name': 'User Number 2',
465 'status': 'OOO',
466 },
467 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
468 }
469 def GetAccountDetailsMock(_, account):
470 # Poor-man's mock library's side_effect.
471 v = mock_per_account.pop(account)
472 if isinstance(v, Exception):
473 raise v
474 return v
475
Edward Lemurda4b6c62020-02-13 00:28:40 +0000476 mockGetAccountDetails.side_effect = GetAccountDetailsMock
477 actual = git_cl.gerrit_util.ValidAccounts(
478 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000479 self.assertEqual(actual, {
480 'u2': {
481 '_account_id': 123124,
482 'avatars': [],
483 'email': 'u2@example.com',
484 'name': 'User Number 2',
485 'status': 'OOO',
486 },
487 })
488
489
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200490class TestParseIssueURL(unittest.TestCase):
491 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000492 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200493 self.assertIsNotNone(parsed)
494 if fail:
495 self.assertFalse(parsed.valid)
496 return
497 self.assertTrue(parsed.valid)
498 self.assertEqual(parsed.issue, issue)
499 self.assertEqual(parsed.patchset, patchset)
500 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200501
Edward Lemur678a6842019-10-03 22:25:05 +0000502 def test_ParseIssueNumberArgument(self):
503 def test(arg, *args, **kwargs):
504 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200505
Edward Lemur678a6842019-10-03 22:25:05 +0000506 test('123', 123)
507 test('', fail=True)
508 test('abc', fail=True)
509 test('123/1', fail=True)
510 test('123a', fail=True)
511 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200512
Edward Lemur678a6842019-10-03 22:25:05 +0000513 test('https://codereview.source.com/123',
514 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200515 test('http://chrome-review.source.com/c/123',
516 123, None, 'chrome-review.source.com')
517 test('https://chrome-review.source.com/c/123/',
518 123, None, 'chrome-review.source.com')
519 test('https://chrome-review.source.com/c/123/4',
520 123, 4, 'chrome-review.source.com')
521 test('https://chrome-review.source.com/#/c/123/4',
522 123, 4, 'chrome-review.source.com')
523 test('https://chrome-review.source.com/c/123/4',
524 123, 4, 'chrome-review.source.com')
525 test('https://chrome-review.source.com/123',
526 123, None, 'chrome-review.source.com')
527 test('https://chrome-review.source.com/123/4',
528 123, 4, 'chrome-review.source.com')
529
Edward Lemur678a6842019-10-03 22:25:05 +0000530 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200531 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
532 test('https://chrome-review.source.com/c/abc/', fail=True)
533 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
534
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200535
536
Edward Lemurda4b6c62020-02-13 00:28:40 +0000537class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100538 def setUp(self):
539 super(GitCookiesCheckerTest, self).setUp()
540 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100541 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000542 mock.patch('sys.stdout', StringIO()).start()
543 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100544
545 def mock_hosts_creds(self, subhost_identity_pairs):
546 def ensure_googlesource(h):
547 if not h.endswith(self.c._GOOGLESOURCE):
548 assert not h.endswith('.')
549 return h + '.' + self.c._GOOGLESOURCE
550 return h
551 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
552 for h, i in subhost_identity_pairs]
553
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200554 def test_identity_parsing(self):
555 self.assertEqual(self.c._parse_identity('ldap.google.com'),
556 ('ldap', 'google.com'))
557 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
558 ('ldap', 'example.com'))
559 # Specical case because we know there are no subdomains in chromium.org.
560 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
561 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800562 # Pathological: ".period." can be either username OR domain, more likely
563 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200564 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
565 ('note', 'period.example.com'))
566
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100567 def test_analysis_nothing(self):
568 self.c._all_hosts = []
569 self.assertFalse(self.c.has_generic_host())
570 self.assertEqual(set(), self.c.get_conflicting_hosts())
571 self.assertEqual(set(), self.c.get_duplicated_hosts())
572 self.assertEqual(set(), self.c.get_partially_configured_hosts())
573 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
574
575 def test_analysis(self):
576 self.mock_hosts_creds([
577 ('.googlesource.com', 'git-example.chromium.org'),
578
579 ('chromium', 'git-example.google.com'),
580 ('chromium-review', 'git-example.google.com'),
581 ('chrome-internal', 'git-example.chromium.org'),
582 ('chrome-internal-review', 'git-example.chromium.org'),
583 ('conflict', 'git-example.google.com'),
584 ('conflict-review', 'git-example.chromium.org'),
585 ('dup', 'git-example.google.com'),
586 ('dup', 'git-example.google.com'),
587 ('dup-review', 'git-example.google.com'),
588 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200589 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100590 ])
591 self.assertTrue(self.c.has_generic_host())
592 self.assertEqual(set(['conflict.googlesource.com']),
593 self.c.get_conflicting_hosts())
594 self.assertEqual(set(['dup.googlesource.com']),
595 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200596 self.assertEqual(set(['partial.googlesource.com',
597 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100598 self.c.get_partially_configured_hosts())
599 self.assertEqual(set(['chromium.googlesource.com',
600 'chrome-internal.googlesource.com']),
601 self.c.get_hosts_with_wrong_identities())
602
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100603 def test_report_no_problems(self):
604 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100605 self.assertFalse(self.c.find_and_report_problems())
606 self.assertEqual(sys.stdout.getvalue(), '')
607
Edward Lemurda4b6c62020-02-13 00:28:40 +0000608 @mock.patch(
609 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
610 return_value='~/.gitcookies')
611 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100612 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100613 self.assertTrue(self.c.find_and_report_problems())
614 with open(os.path.join(os.path.dirname(__file__),
615 'git_cl_creds_check_report.txt')) as f:
616 expected = f.read()
617 def by_line(text):
618 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700619 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200620 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100621
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800622
Edward Lemurda4b6c62020-02-13 00:28:40 +0000623class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000624 def setUp(self):
625 super(TestGitCl, self).setUp()
626 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700627 self._calls_done = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000628 mock.patch('sys.stdout', StringIO()).start()
629 mock.patch(
630 'git_cl.time_time',
631 lambda: self._mocked_call('time.time')).start()
632 mock.patch(
633 'git_cl.metrics.collector.add_repeated',
634 lambda *a: self._mocked_call('add_repeated', *a)).start()
635 mock.patch('subprocess2.call', self._mocked_call).start()
636 mock.patch('subprocess2.check_call', self._mocked_call).start()
637 mock.patch('subprocess2.check_output', self._mocked_call).start()
638 mock.patch(
639 'subprocess2.communicate',
640 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
641 mock.patch(
642 'git_cl.gclient_utils.CheckCallAndFilter',
643 self._mocked_call).start()
644 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
645 mock.patch(
646 'git_common.get_or_create_merge_base',
647 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
648 mock.patch('git_cl.BranchExists', return_value=True).start()
649 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
650 mock.patch(
651 'git_cl.SaveDescriptionBackup',
652 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
653 mock.patch(
654 'git_cl.ask_for_data',
655 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
656 mock.patch(
657 'git_cl.write_json',
658 lambda *a: self._mocked_call('write_json', *a)).start()
659 mock.patch(
660 'git_cl.presubmit_support.DoPresubmitChecks', PresubmitMock).start()
661 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
662 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000663 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000664 mock.patch(
665 'git_cl.gerrit_util.GetChangeComments',
666 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
667 mock.patch(
668 'git_cl.gerrit_util.GetChangeRobotComments',
669 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
670 mock.patch(
671 'git_cl.gerrit_util.AddReviewers',
672 lambda *a: self._mocked_call('AddReviewers', *a)).start()
673 mock.patch(
674 'git_cl.gerrit_util.SetReview',
675 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
676 self._mocked_call(
677 'SetReview', h, i, msg, labels, notify, ready))).start()
678 mock.patch(
679 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
680 return_value=False).start()
681 mock.patch(
682 'git_cl.gerrit_util.GceAuthenticator.is_gce',
683 return_value=False).start()
684 mock.patch(
685 'git_cl.gerrit_util.ValidAccounts',
686 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000687 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000688 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000689 self.mockGit = GitMocks()
690 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
691 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
692 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000693 mock.patch(
694 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000695 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000696 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000697 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000698 mock.patch(
699 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000700 # It's important to reset settings to not have inter-tests interference.
701 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000702 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000703
704 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000705 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000706 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100707 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000708 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
709 if len(self.calls) > 5:
710 calls += ' ...\n'
711 self.fail(
712 '\n'
713 'There are un-consumed calls after this test has finished:\n' +
714 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000715 finally:
716 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000717
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000718 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000719 self.assertTrue(
720 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700721 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000722 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000723 expected_args, result = top
724
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000725 # Also logs otherwise it could get caught in a try/finally and be hard to
726 # diagnose.
727 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700728 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000729 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700730 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
731 for i, c in enumerate(self._calls_done[-N:]))
732 following_calls = '\n '.join(
733 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
734 for i, c in enumerate(self.calls[:N]))
735 extended_msg = (
736 'A few prior calls:\n %s\n\n'
737 'This (expected):\n @%d: %r\n'
738 'This (actual):\n @%d: %r\n\n'
739 'A few following expected calls:\n %s' %
740 (prior_calls, len(self._calls_done), expected_args,
741 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700742
tandrii99a72f22016-08-17 14:33:24 -0700743 self.fail('@%d\n'
744 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000745 ' Actual: %r\n'
746 '\n'
747 '%s' % (
748 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700749
750 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700751 if isinstance(result, Exception):
752 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000753 # stdout from git commands is supposed to be a bytestream. Convert it here
754 # instead of converting all test output in this file to bytes.
755 if args[0][0] == 'git' and not isinstance(result, bytes):
756 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000757 return result
758
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100759 def test_ask_for_explicit_yes_true(self):
760 self.calls = [
761 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
762 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
763 ]
764 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
765
tandrii48df5812016-10-17 03:55:37 -0700766 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000767 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700768 self.calls = [
769 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700770 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
771 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
772 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
773 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700774 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
775 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700776 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
777 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000778 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
779 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700780 ((['git', 'config', 'gerrit.host', 'true'],), ''),
781 ]
782 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
783
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000784 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100785 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200786 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000787 custom_cl_base=None, short_hostname='chromium',
788 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000789 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200790 if custom_cl_base:
791 ancestor_revision = custom_cl_base
792 else:
793 # Determine ancestor_revision to be merge base.
794 ancestor_revision = 'fake_ancestor_sha'
795 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000796 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
797 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200798 ]
799
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100800 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000801 gerrit_util.GetChangeDetail.return_value = {
802 'owner': {'email': (other_cl_owner or 'owner@example.com')},
803 'change_id': (change_id or '123456789'),
804 'current_revision': 'sha1_of_current_revision',
805 'revisions': {'sha1_of_current_revision': {
806 'commit': {'message': fetched_description},
807 }},
808 'status': fetched_status or 'NEW',
809 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100810 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100811 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100812 if other_cl_owner:
813 calls += [
814 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
815 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100816
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100817 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200818 ((['git', 'rev-parse', 'HEAD'],), '12345'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100819 ]
820
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100821 calls += [
Edward Lemur2c48f242019-06-04 16:14:09 +0000822 (('time.time',), 1000,),
823 (('time.time',), 3000,),
824 (('add_repeated', 'sub_commands', {
825 'execution_time': 2000,
826 'command': 'presubmit',
827 'exit_code': 0
828 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200829 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
830 ([custom_cl_base] if custom_cl_base else
831 [ancestor_revision, 'HEAD']),),
832 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100833 ]
834 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000835
Edward Lemur26964072020-02-19 19:18:51 +0000836 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700837 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000838 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700839 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100840 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000841 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000842 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000843 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000844 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000845 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000846 if post_amend_description is None:
847 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700848 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200849 # Determined in `_gerrit_base_calls`.
850 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
851
852 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000853
Edward Lemur26964072020-02-19 19:18:51 +0000854 if squash_mode in ('override_squash', 'override_nosquash'):
855 self.mockGit.config['gerrit.override-squash-uploads'] = (
856 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700857
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000858 # If issue is given, then description is fetched from Gerrit instead.
859 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000860 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200861 ((['git', 'log', '--pretty=format:%s\n\n%b',
862 ((custom_cl_base + '..') if custom_cl_base else
863 'fake_ancestor_sha..HEAD')],),
864 description),
865 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800866 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000867 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800868 else:
869 if not title:
870 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200871 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
872 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800873 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000874 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000875 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000876 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200877 (('DownloadGerritHook', False), ''),
878 # Amending of commit message to get the Change-Id.
879 ((['git', 'log', '--pretty=format:%s\n\n%b',
880 determined_ancestor_revision + '..HEAD'],),
881 description),
882 ((['git', 'commit', '--amend', '-m', description],), ''),
883 ((['git', 'log', '--pretty=format:%s\n\n%b',
884 determined_ancestor_revision + '..HEAD'],),
885 post_amend_description)
886 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000887 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000888 if force or not issue:
Anthony Polito8b955342019-09-24 19:01:36 +0000889 if not force:
890 calls += [
Anthony Polito8b955342019-09-24 19:01:36 +0000891 ((['RunEditor'],), description),
892 ]
Josipe827b0f2020-01-30 00:07:20 +0000893 # user wants to edit description
894 if edit_description:
895 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000896 ((['RunEditor'],), edit_description),
897 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000898 ref_to_push = 'abcdef0123456789'
899 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200900 ]
901
902 if custom_cl_base is None:
903 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000904 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000905 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200906 ]
907 parent = 'origin/master'
908 else:
909 calls += [
910 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
911 'refs/remotes/origin/master'],),
912 callError(1)), # Means not ancenstor.
913 (('ask_for_data',
914 'Do you take responsibility for cleaning up potential mess '
915 'resulting from proceeding with upload? Press Enter to upload, '
916 'or Ctrl+C to abort'), ''),
917 ]
918 parent = custom_cl_base
919
920 calls += [
921 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
922 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000923 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200924 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000925 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200926 ref_to_push),
927 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000928 else:
929 ref_to_push = 'HEAD'
930
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000931 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000932 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200933 ((['git', 'rev-list',
934 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
935 ref_to_push],),
936 '1hashPerLine\n'),
937 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000938
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000939 metrics_arguments = []
940
Aaron Gableafd52772017-06-27 16:40:10 -0700941 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700942 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000943 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700944 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400945 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700946 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000947 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700948 else:
949 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000950 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800951
Aaron Gable70f4e242017-06-26 10:45:59 -0700952 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700953 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000954 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000955
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000956 if short_hostname == 'chromium':
957 # All reviwers and ccs get into ref_suffix.
958 for r in sorted(reviewers):
959 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000960 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000961 if issue is None:
962 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
963 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000964 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000965 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000966 reviewers, cc = [], []
967 else:
968 # TODO(crbug/877717): remove this case.
969 calls += [
970 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
971 sorted(reviewers) + ['joe@example.com',
972 'chromium-reviews+test-more-cc@chromium.org'] + cc),
973 {
974 e: {'email': e}
975 for e in (reviewers + ['joe@example.com'] + cc)
976 })
977 ]
978 for r in sorted(reviewers):
979 if r != 'bad-account-or-email':
980 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000981 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000982 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000983 if issue is None:
984 cc += ['joe@example.com']
985 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000986 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000987 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000988 if c in cc:
989 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000990
Edward Lemur687ca902018-12-05 02:30:30 +0000991 for k, v in sorted((labels or {}).items()):
992 ref_suffix += ',l=%s+%d' % (k, v)
993 metrics_arguments.append('l=%s+%d' % (k, v))
994
995 if tbr:
996 calls += [
997 (('GetCodeReviewTbrScore',
998 '%s-review.googlesource.com' % short_hostname,
999 'my/repo'),
1000 2,),
1001 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001002
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001003 calls += [
1004 (('time.time',), 1000,),
1005 ((['git', 'push',
1006 'https://%s.googlesource.com/my/repo' % short_hostname,
1007 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1008 (('remote:\n'
1009 'remote: Processing changes: (\)\n'
1010 'remote: Processing changes: (|)\n'
1011 'remote: Processing changes: (/)\n'
1012 'remote: Processing changes: (-)\n'
1013 'remote: Processing changes: new: 1 (/)\n'
1014 'remote: Processing changes: new: 1, done\n'
1015 'remote:\n'
1016 'remote: New Changes:\n'
1017 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1018 ' XXX\n'
1019 'remote:\n'
1020 'To https://%s.googlesource.com/my/repo\n'
1021 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1022 ) % (short_hostname, short_hostname)),),
1023 (('time.time',), 2000,),
1024 (('add_repeated',
1025 'sub_commands',
1026 {
1027 'execution_time': 1000,
1028 'command': 'git push',
1029 'exit_code': 0,
1030 'arguments': sorted(metrics_arguments),
1031 }),
1032 None,),
1033 ]
1034
Edward Lemur1b52d872019-05-09 21:12:12 +00001035 final_description = final_description or post_amend_description.strip()
1036 original_title = original_title or title or '<untitled>'
1037 # Trace-related calls
1038 calls += [
1039 # Write a description with context for the current trace.
1040 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001041 'Thu Mar 16 20:00:41 2017\n'
1042 '%(short_hostname)s-review.googlesource.com\n'
1043 '%(change_id)s\n'
1044 '%(title)s\n'
1045 '%(description)s\n'
1046 '1000\n'
1047 '0\n'
1048 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001049 'short_hostname': short_hostname,
1050 'change_id': change_id,
1051 'description': final_description,
1052 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001053 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001054 }],),
1055 None,
1056 ),
1057 # Read traces and shorten git hashes.
1058 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1059 True,
1060 ),
1061 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1062 ('git-hash: 0123456789012345678901234567890123456789\n'
1063 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1064 ),
1065 ((['FileWrite', 'TEMP_DIR/trace-packet',
1066 'git-hash: 012345\n'
1067 'git-hash: abcdea\n'],),
1068 None,
1069 ),
1070 # Make zip file for the git traces.
1071 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1072 'TEMP_DIR'],),
1073 None,
1074 ),
1075 # Collect git config and gitcookies.
1076 ((['git', 'config', '-l'],),
1077 'git-config-output',
1078 ),
1079 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1080 None,
1081 ),
1082 ((['os.path.isfile', '~/.gitcookies'],),
1083 gitcookies_exists,
1084 ),
1085 ]
1086 if gitcookies_exists:
1087 calls += [
1088 ((['FileRead', '~/.gitcookies'],),
1089 'gitcookies 1/SECRET',
1090 ),
1091 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1092 None,
1093 ),
1094 ]
1095 calls += [
1096 # Make zip file for the git config and gitcookies.
1097 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1098 'TEMP_DIR'],),
1099 None,
1100 ),
1101 ]
1102
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001103 # TODO(crbug/877717): this should never be used.
1104 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001105 calls += [
1106 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001107 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001108 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001109 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1110 notify),
1111 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001112 ]
Edward Lemur26964072020-02-19 19:18:51 +00001113 calls += [
1114 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1115 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001116 return calls
1117
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001118 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001119 self,
1120 upload_args,
1121 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001122 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001123 squash=True,
1124 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001125 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001126 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001127 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001128 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001129 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001130 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001131 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001132 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001133 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001134 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001135 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001136 labels=None,
1137 change_id=None,
1138 original_title=None,
1139 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001140 gitcookies_exists=True,
1141 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001142 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001143 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001144 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001145 if squash_mode is None:
1146 if '--no-squash' in upload_args:
1147 squash_mode = 'nosquash'
1148 elif '--squash' in upload_args:
1149 squash_mode = 'squash'
1150 else:
1151 squash_mode = 'default'
1152
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001153 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001154 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001155 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001156 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001157 same_auth=('git-owner.example.com', '', 'pass'))).start()
1158 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1159 lambda _, offer_removal: None).start()
1160 mock.patch('git_cl.gclient_utils.RunEditor',
1161 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1162 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1163 'DownloadGerritHook', force)).start()
1164 mock.patch('git_cl.gclient_utils.FileRead',
1165 lambda path: self._mocked_call(['FileRead', path])).start()
1166 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001167 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001168 ['FileWrite', path, contents])).start()
1169 mock.patch('git_cl.datetime_now',
1170 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1171 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1172 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1173 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001174 '%(now)s\n'
1175 '%(gerrit_host)s\n'
1176 '%(change_id)s\n'
1177 '%(title)s\n'
1178 '%(description)s\n'
1179 '%(execution_time)s\n'
1180 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001181 '%(trace_name)s').start()
1182 mock.patch('git_cl.shutil.make_archive',
1183 lambda *args: self._mocked_call(['make_archive'] +
1184 list(args))).start()
1185 mock.patch('os.path.isfile',
1186 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001187 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001188 mock.patch(
1189 'git_cl.Changelist.GetLocalDescription', return_value='foo').start()
tandriia60502f2016-06-20 02:01:53 -07001190
Edward Lemur26964072020-02-19 19:18:51 +00001191 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001192 self.mockGit.config['branch.master.gerritissue'] = (
1193 str(issue) if issue else None)
1194 self.mockGit.config['remote.origin.url'] = (
1195 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001196 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001197
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001198 self.calls = self._gerrit_base_calls(
1199 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001200 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001201 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001202 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001203 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001204 short_hostname=short_hostname,
1205 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001206 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001207 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001208 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001209 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001210 self.calls += self._gerrit_upload_calls(
1211 description, reviewers, squash,
1212 squash_mode=squash_mode,
1213 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001214 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001215 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001216 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001217 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001218 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001219 labels=labels,
1220 change_id=change_id,
1221 original_title=original_title,
1222 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001223 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001224 force=force,
1225 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001226 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001227 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001228 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001229 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001230 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001231 self.assertEqual(
1232 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001233 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001234
Edward Lemur1b52d872019-05-09 21:12:12 +00001235 def test_gerrit_upload_traces_no_gitcookies(self):
1236 self._run_gerrit_upload_test(
1237 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001238 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001239 [],
1240 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001241 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001242 change_id='Ixxx',
1243 gitcookies_exists=False)
1244
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001245 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001246 self._run_gerrit_upload_test(
1247 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001248 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001249 [],
1250 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001251 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001252 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001253
1254 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001255 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001256 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001257 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001258 [],
tandriia60502f2016-06-20 02:01:53 -07001259 squash=False,
1260 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001261 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001262 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001263
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001264 def test_gerrit_no_reviewer(self):
1265 self._run_gerrit_upload_test(
1266 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001267 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001268 [],
1269 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001270 squash_mode='override_nosquash',
1271 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001272
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001273 def test_gerrit_no_reviewer_non_chromium_host(self):
1274 # TODO(crbug/877717): remove this test case.
1275 self._run_gerrit_upload_test(
1276 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001277 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001278 [],
1279 squash=False,
1280 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001281 short_hostname='other',
1282 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001283
Nick Carter8692b182017-11-06 16:30:38 -08001284 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001285 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001286 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001287 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001288 squash=False,
1289 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001290 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1291 change_id='I123456789',
1292 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001293
ukai@chromium.orge8077812012-02-03 03:41:46 +00001294 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001295 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001296 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001297 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001298 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001299 squash=False,
1300 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001301 notify=True,
1302 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001303 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001304 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001305
Anthony Polito8b955342019-09-24 19:01:36 +00001306 def test_gerrit_upload_force_sets_bug(self):
1307 self._run_gerrit_upload_test(
1308 ['-b', '10000', '-f'],
1309 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1310 [],
1311 force=True,
1312 expected_upstream_ref='origin/master',
1313 fetched_description='desc=\n\nChange-Id: Ixxx',
1314 original_title='Initial upload',
1315 change_id='Ixxx')
1316
1317 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1318 self._run_gerrit_upload_test(
1319 ['-b', '10000', '-f', '-m', 'Title'],
1320 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1321 [],
1322 force=True,
1323 issue='123456',
1324 expected_upstream_ref='origin/master',
1325 fetched_description='desc=\n\nChange-Id: Ixxxx',
1326 original_title='Title',
1327 title='Title',
1328 change_id='Izzzz')
1329
Dan Beamd8b04ca2019-10-10 21:23:26 +00001330 def test_gerrit_upload_force_sets_fixed(self):
1331 self._run_gerrit_upload_test(
1332 ['-x', '10000', '-f'],
1333 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1334 [],
1335 force=True,
1336 expected_upstream_ref='origin/master',
1337 fetched_description='desc=\n\nChange-Id: Ixxx',
1338 original_title='Initial upload',
1339 change_id='Ixxx')
1340
ukai@chromium.orge8077812012-02-03 03:41:46 +00001341 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001342 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1343 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001344 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001345 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001346 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001347 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001348 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001349 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001350 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001351 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001352 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001353 labels={'Code-Review': 2},
1354 change_id='123456789',
1355 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001356
1357 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001358 self._run_gerrit_upload_test(
1359 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001360 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001361 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001362 expected_upstream_ref='origin/master',
1363 change_id='123456789',
1364 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001365
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001366 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001367 self._run_gerrit_upload_test(
1368 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001369 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001370 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001371 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001372 expected_upstream_ref='origin/master',
1373 change_id='123456789',
1374 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001375
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001376 def test_gerrit_upload_squash_first_with_labels(self):
1377 self._run_gerrit_upload_test(
1378 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001379 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001380 [],
1381 squash=True,
1382 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001383 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1384 change_id='123456789',
1385 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001386
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001387 def test_gerrit_upload_squash_first_against_rev(self):
1388 custom_cl_base = 'custom_cl_base_rev_or_branch'
1389 self._run_gerrit_upload_test(
1390 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001391 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001392 [],
1393 squash=True,
1394 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001395 custom_cl_base=custom_cl_base,
1396 change_id='123456789',
1397 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001398 self.assertIn(
1399 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1400 sys.stdout.getvalue())
1401
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001402 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001403 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001404 self._run_gerrit_upload_test(
1405 ['--squash'],
1406 description,
1407 [],
1408 squash=True,
1409 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001410 issue=123456,
1411 change_id='123456789',
1412 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001413
Edward Lemurd55c5072020-02-20 01:09:07 +00001414 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001415 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001416 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001417 with self.assertRaises(SystemExitMock):
1418 self._run_gerrit_upload_test(
1419 ['--squash'],
1420 description,
1421 [],
1422 squash=True,
1423 expected_upstream_ref='origin/master',
1424 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001425 fetched_status='ABANDONED',
1426 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001427 self.assertEqual(
1428 'Change https://chromium-review.googlesource.com/123456 has been '
1429 'abandoned, new uploads are not allowed\n',
1430 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001431
Edward Lemurda4b6c62020-02-13 00:28:40 +00001432 @mock.patch(
1433 'gerrit_util.GetAccountDetails',
1434 return_value={'email': 'yet-another@example.com'})
1435 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001436 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001437 self._run_gerrit_upload_test(
1438 ['--squash'],
1439 description,
1440 [],
1441 squash=True,
1442 expected_upstream_ref='origin/master',
1443 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001444 other_cl_owner='other@example.com',
1445 change_id='123456789',
1446 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001447 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001448 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001449 'authenticate to Gerrit as yet-another@example.com.\n'
1450 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001451 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001452
Josipe827b0f2020-01-30 00:07:20 +00001453 def test_upload_change_description_editor(self):
1454 fetched_description = 'foo\n\nChange-Id: 123456789'
1455 description = 'bar\n\nChange-Id: 123456789'
1456 self._run_gerrit_upload_test(
1457 ['--squash', '--edit-description'],
1458 description,
1459 [],
1460 fetched_description=fetched_description,
1461 squash=True,
1462 expected_upstream_ref='origin/master',
1463 issue=123456,
1464 change_id='123456789',
1465 original_title='User input',
1466 edit_description=description)
1467
Edward Lemurda4b6c62020-02-13 00:28:40 +00001468 @mock.patch('git_cl.RunGit')
1469 @mock.patch('git_cl.CMDupload')
1470 @mock.patch('git_cl.ask_for_data')
1471 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001472 def mock_run_git(*args, **_kwargs):
1473 if args[0] == ['for-each-ref',
1474 '--format=%(refname:short) %(upstream:short)',
1475 'refs/heads']:
1476 # Create a local branch dependency tree that looks like this:
1477 # test1 -> test2 -> test3 -> test4 -> test5
1478 # -> test3.1
1479 # test6 -> test0
1480 branch_deps = [
1481 'test2 test1', # test1 -> test2
1482 'test3 test2', # test2 -> test3
1483 'test3.1 test2', # test2 -> test3.1
1484 'test4 test3', # test3 -> test4
1485 'test5 test4', # test4 -> test5
1486 'test6 test0', # test0 -> test6
1487 'test7', # test7
1488 ]
1489 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001490 git_cl.RunGit.side_effect = mock_run_git
1491 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001492
1493 class MockChangelist():
1494 def __init__(self):
1495 pass
1496 def GetBranch(self):
1497 return 'test1'
1498 def GetIssue(self):
1499 return '123'
1500 def GetPatchset(self):
1501 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001502 def IsGerrit(self):
1503 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001504
1505 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1506 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001507 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
1508 git_cl.ask_for_data.assert_called_once_with(
1509 'This command will checkout all dependent branches '
1510 'and run "git cl upload". Press Enter to continue, '
1511 'or Ctrl+C to abort')
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001512 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001513
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001514 def test_gerrit_change_id(self):
1515 self.calls = [
1516 ((['git', 'write-tree'], ),
1517 'hashtree'),
1518 ((['git', 'rev-parse', 'HEAD~0'], ),
1519 'branch-parent'),
1520 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1521 'A B <a@b.org> 1456848326 +0100'),
1522 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1523 'C D <c@d.org> 1456858326 +0100'),
1524 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1525 'hashchange'),
1526 ]
1527 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1528 self.assertEqual(change_id, 'Ihashchange')
1529
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001530 def test_desecription_append_footer(self):
1531 for init_desc, footer_line, expected_desc in [
1532 # Use unique desc first lines for easy test failure identification.
1533 ('foo', 'R=one', 'foo\n\nR=one'),
1534 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1535 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1536 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1537 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1538 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1539 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1540 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1541 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1542 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1543 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1544 ]:
1545 desc = git_cl.ChangeDescription(init_desc)
1546 desc.append_footer(footer_line)
1547 self.assertEqual(desc.description, expected_desc)
1548
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001549 def test_update_reviewers(self):
1550 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001551 ('foo', [], [],
1552 'foo'),
1553 ('foo\nR=xx', [], [],
1554 'foo\nR=xx'),
1555 ('foo\nTBR=xx', [], [],
1556 'foo\nTBR=xx'),
1557 ('foo', ['a@c'], [],
1558 'foo\n\nR=a@c'),
1559 ('foo\nR=xx', ['a@c'], [],
1560 'foo\n\nR=a@c, xx'),
1561 ('foo\nTBR=xx', ['a@c'], [],
1562 'foo\n\nR=a@c\nTBR=xx'),
1563 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1564 'foo\n\nR=a@c, yy\nTBR=xx'),
1565 ('foo\nBUG=', ['a@c'], [],
1566 'foo\nBUG=\nR=a@c'),
1567 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1568 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1569 ('foo', ['a@c', 'b@c'], [],
1570 'foo\n\nR=a@c, b@c'),
1571 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1572 'foo\nBar\n\nR=c@c\nBUG='),
1573 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1574 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001575 # Same as the line before, but full of whitespaces.
1576 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001577 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001578 'foo\nBar\n\nR=c@c\n BUG =',
1579 ),
1580 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001581 ('foo BUG=allo R=joe ', ['c@c'], [],
1582 'foo BUG=allo R=joe\n\nR=c@c'),
1583 # Redundant TBRs get promoted to Rs
1584 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1585 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001586 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001587 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001588 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001589 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001590 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001591 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001592 actual.append(obj.description)
1593 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001594
Nodir Turakulov23b82142017-11-16 11:04:25 -08001595 def test_get_hash_tags(self):
1596 cases = [
1597 ('', []),
1598 ('a', []),
1599 ('[a]', ['a']),
1600 ('[aa]', ['aa']),
1601 ('[a ]', ['a']),
1602 ('[a- ]', ['a']),
1603 ('[a- b]', ['a-b']),
1604 ('[a--b]', ['a-b']),
1605 ('[a', []),
1606 ('[a]x', ['a']),
1607 ('[aa]x', ['aa']),
1608 ('[a b]', ['a-b']),
1609 ('[a b]', ['a-b']),
1610 ('[a__b]', ['a-b']),
1611 ('[a] x', ['a']),
1612 ('[a][b]', ['a', 'b']),
1613 ('[a] [b]', ['a', 'b']),
1614 ('[a][b]x', ['a', 'b']),
1615 ('[a][b] x', ['a', 'b']),
1616 ('[a]\n[b]', ['a']),
1617 ('[a\nb]', []),
1618 ('[a][', ['a']),
1619 ('Revert "[a] feature"', ['a']),
1620 ('Reland "[a] feature"', ['a']),
1621 ('Revert: [a] feature', ['a']),
1622 ('Reland: [a] feature', ['a']),
1623 ('Revert "Reland: [a] feature"', ['a']),
1624 ('Foo: feature', ['foo']),
1625 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001626 ('Change Foo::Bar', []),
1627 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001628 ('Revert "Foo bar: feature"', ['foo-bar']),
1629 ('Reland "Foo bar: feature"', ['foo-bar']),
1630 ]
1631 for desc, expected in cases:
1632 change_desc = git_cl.ChangeDescription(desc)
1633 actual = change_desc.get_hash_tags()
1634 self.assertEqual(
1635 actual,
1636 expected,
1637 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1638
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001639 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001640 self.assertEqual(None, git_cl.GetTargetRef(None,
1641 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001642 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001643
wittman@chromium.org455dc922015-01-26 20:15:50 +00001644 # Check default target refs for branches.
1645 self.assertEqual('refs/heads/master',
1646 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001647 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001648 self.assertEqual('refs/heads/master',
1649 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001650 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001651 self.assertEqual('refs/heads/master',
1652 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001653 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001654 self.assertEqual('refs/branch-heads/123',
1655 git_cl.GetTargetRef('origin',
1656 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001657 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001658 self.assertEqual('refs/diff/test',
1659 git_cl.GetTargetRef('origin',
1660 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001661 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001662 self.assertEqual('refs/heads/chrome/m42',
1663 git_cl.GetTargetRef('origin',
1664 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001665 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001666
1667 # Check target refs for user-specified target branch.
1668 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1669 'refs/remotes/branch-heads/123'):
1670 self.assertEqual('refs/branch-heads/123',
1671 git_cl.GetTargetRef('origin',
1672 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001673 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001674 for branch in ('origin/master', 'remotes/origin/master',
1675 'refs/remotes/origin/master'):
1676 self.assertEqual('refs/heads/master',
1677 git_cl.GetTargetRef('origin',
1678 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001679 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001680 for branch in ('master', 'heads/master', 'refs/heads/master'):
1681 self.assertEqual('refs/heads/master',
1682 git_cl.GetTargetRef('origin',
1683 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001684 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001685
Edward Lemurda4b6c62020-02-13 00:28:40 +00001686 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1687 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001688 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001689 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1690
Edward Lemur85153282020-02-14 22:06:29 +00001691 def assertIssueAndPatchset(
1692 self, branch='master', issue='123456', patchset='7',
1693 git_short_host='chromium'):
1694 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001695 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001696 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001697 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001698 self.assertEqual(
1699 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001700 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001701
Edward Lemur85153282020-02-14 22:06:29 +00001702 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001703 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001704 self.mockGit.config['remote.origin.url'] = (
1705 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001706 gerrit_util.GetChangeDetail.return_value = {
1707 'current_revision': '7777777777',
1708 'revisions': {
1709 '1111111111': {
1710 '_number': 1,
1711 'fetch': {'http': {
1712 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1713 'ref': 'refs/changes/56/123456/1',
1714 }},
1715 },
1716 '7777777777': {
1717 '_number': 7,
1718 'fetch': {'http': {
1719 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1720 'ref': 'refs/changes/56/123456/7',
1721 }},
1722 },
1723 },
1724 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001725
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001726 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001727 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001728 self.calls += [
1729 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1730 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001731 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001732 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001733 ]
1734 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001735 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001736
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001737 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001738 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001739 self.calls += [
1740 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1741 'refs/changes/56/123456/7'],), ''),
1742 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001743 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001744 ]
Edward Lemur85153282020-02-14 22:06:29 +00001745 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1746 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001747
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001748 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001749 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001750 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001751 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001752 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001753 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001754 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001755 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001756 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001757 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001758
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001759 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001760 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001761 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001762 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001763 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001764 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001765 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001766 ]
1767 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001768 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001769 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001770
Aaron Gable697a91b2018-01-19 15:20:15 -08001771 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001772 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001773 self.calls += [
1774 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1775 'refs/changes/56/123456/1'],), ''),
1776 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001777 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001778 ]
1779 self.assertEqual(git_cl.main(
1780 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1781 0)
Edward Lemur85153282020-02-14 22:06:29 +00001782 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001783
Edward Lemurd55c5072020-02-20 01:09:07 +00001784 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001785 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001786 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001787 self.calls += [
1788 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001789 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001790 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001791 ]
1792 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001793 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001794 self.assertEqual(
1795 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1796 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001797
Edward Lemurda4b6c62020-02-13 00:28:40 +00001798 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001799 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001800 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001801 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001802 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001803 self.mockGit.config['remote.origin.url'] = (
1804 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001805 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001806 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001807 self.assertEqual(
1808 'change 123456 at https://chromium-review.googlesource.com does not '
1809 'exist or you have no access to it\n',
1810 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001811
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001812 def _checkout_calls(self):
1813 return [
1814 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001815 'branch\\..*\\.gerritissue'], ),
1816 ('branch.ger-branch.gerritissue 123456\n'
1817 'branch.gbranch654.gerritissue 654321\n')),
1818 ]
1819
1820 def test_checkout_gerrit(self):
1821 """Tests git cl checkout <issue>."""
1822 self.calls = self._checkout_calls()
1823 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1824 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1825
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001826 def test_checkout_not_found(self):
1827 """Tests git cl checkout <issue>."""
1828 self.calls = self._checkout_calls()
1829 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1830
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001831 def test_checkout_no_branch_issues(self):
1832 """Tests git cl checkout <issue>."""
1833 self.calls = [
1834 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001835 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001836 ]
1837 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1838
Edward Lemur26964072020-02-19 19:18:51 +00001839 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001840 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1841 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001842 self.mockGit.config['remote.origin.url'] = (
1843 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001844 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001845 cl.branch = 'master'
1846 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001847 return cl
1848
Edward Lemurd55c5072020-02-20 01:09:07 +00001849 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001850 def test_gerrit_ensure_authenticated_missing(self):
1851 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001852 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001853 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001854 with self.assertRaises(SystemExitMock):
1855 cl.EnsureAuthenticated(force=False)
1856 self.assertEqual(
1857 'Credentials for the following hosts are required:\n'
1858 ' chromium-review.googlesource.com\n'
1859 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1860 'You can (re)generate your credentials by visiting '
1861 'https://chromium-review.googlesource.com/new-password\n',
1862 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001863
1864 def test_gerrit_ensure_authenticated_conflict(self):
1865 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001866 'chromium.googlesource.com':
1867 ('git-one.example.com', None, 'secret1'),
1868 'chromium-review.googlesource.com':
1869 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001870 })
1871 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001872 (('ask_for_data', 'If you know what you are doing '
1873 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001874 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1875
1876 def test_gerrit_ensure_authenticated_ok(self):
1877 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001878 'chromium.googlesource.com':
1879 ('git-same.example.com', None, 'secret'),
1880 'chromium-review.googlesource.com':
1881 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001882 })
1883 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1884
tandrii@chromium.org28253532016-04-14 13:46:56 +00001885 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001886 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1887 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001888 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1889
Eric Boren2fb63102018-10-05 13:05:03 +00001890 def test_gerrit_ensure_authenticated_bearer_token(self):
1891 cl = self._test_gerrit_ensure_authenticated_common(auth={
1892 'chromium.googlesource.com':
1893 ('', None, 'secret'),
1894 'chromium-review.googlesource.com':
1895 ('', None, 'secret'),
1896 })
1897 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1898 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1899 'chromium.googlesource.com')
1900 self.assertTrue('Bearer' in header)
1901
Daniel Chengcf6269b2019-05-18 01:02:12 +00001902 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001903 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001904 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001905 (('logging.warning',
1906 'Ignoring branch %(branch)s with non-https remote '
1907 '%(remote)s', {
1908 'branch': 'master',
1909 'remote': 'custom-scheme://repo'}
1910 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001911 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001912 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1913 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1914 mock.patch('logging.warning',
1915 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001916 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001917 cl.branch = 'master'
1918 cl.branchref = 'refs/heads/master'
1919 cl.lookedup_issue = True
1920 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1921
Florian Mayerae510e82020-01-30 21:04:48 +00001922 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001923 self.mockGit.config['remote.origin.url'] = (
1924 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001925 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001926 (('logging.error',
1927 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1928 'but it doesn\'t exist.', {
1929 'remote': 'origin',
1930 'branch': 'master',
1931 'url': 'git@somehost.example:foo/bar.git'}
1932 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001933 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001934 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1935 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1936 mock.patch('logging.error',
1937 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001938 cl = git_cl.Changelist()
1939 cl.branch = 'master'
1940 cl.branchref = 'refs/heads/master'
1941 cl.lookedup_issue = True
1942 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1943
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001944 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001945 self.mockGit.config['branch.master.gerritissue'] = '123'
1946 self.mockGit.config['branch.master.gerritserver'] = (
1947 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001948 self.mockGit.config['remote.origin.url'] = (
1949 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001950 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001951 (('SetReview', 'chromium-review.googlesource.com',
1952 'infra%2Finfra~123', None,
1953 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001954 ]
tandriid9e5ce52016-07-13 02:32:59 -07001955
1956 def test_cmd_set_commit_gerrit_clear(self):
1957 self._cmd_set_commit_gerrit_common(0)
1958 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1959
1960 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001961 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001962 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1963
tandriid9e5ce52016-07-13 02:32:59 -07001964 def test_cmd_set_commit_gerrit(self):
1965 self._cmd_set_commit_gerrit_common(2)
1966 self.assertEqual(0, git_cl.main(['set-commit']))
1967
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001968 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001969 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001970 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001971
1972 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001973 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001974
Edward Lemurda4b6c62020-02-13 00:28:40 +00001975 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001976 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001977 try:
1978 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001979 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001980 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001981 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001982
1983 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001984 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001985 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001986 return 'foobar'
1987
Edward Lemurda4b6c62020-02-13 00:28:40 +00001988 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001989 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001990 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001991 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001992 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001993
iannuccie53c9352016-08-17 14:40:40 -07001994 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001995
iannuccie53c9352016-08-17 14:40:40 -07001996 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001997 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001998 return 'foobar'
1999
Edward Lemurda4b6c62020-02-13 00:28:40 +00002000 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2001 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002002 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002003 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002004
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002005 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002006 self.mockGit.config['remote.origin.url'] = (
2007 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002008 gerrit_util.GetChangeDetail.return_value = {
2009 'current_revision': 'sha1',
2010 'revisions': {'sha1': {
2011 'commit': {'message': 'foobar'},
2012 }},
2013 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002014 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002015 'description',
2016 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2017 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002018 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002019
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002020 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002021 mock.patch('git_cl.Changelist', ChangelistMock).start()
2022 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002023
2024 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2025 self.assertEqual('hihi', ChangelistMock.desc)
2026
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002027 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002028 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002029
2030 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002031 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002032 '# Enter a description of the change.\n'
2033 '# This will be displayed on the codereview site.\n'
2034 '# The first line will also be used as the subject of the review.\n'
2035 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002036 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002037 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002038 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002039 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002040 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002041
Edward Lemur6c6827c2020-02-06 21:15:18 +00002042 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002043 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002044
Edward Lemurda4b6c62020-02-13 00:28:40 +00002045 mock.patch('git_cl.Changelist.FetchDescription',
2046 lambda *args: current_desc).start()
2047 mock.patch('git_cl.Changelist.UpdateDescription',
2048 UpdateDescription).start()
2049 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002050
Edward Lemur85153282020-02-14 22:06:29 +00002051 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002052 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002053
Dan Beamd8b04ca2019-10-10 21:23:26 +00002054 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2055 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2056
2057 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002058 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002059 '# Enter a description of the change.\n'
2060 '# This will be displayed on the codereview site.\n'
2061 '# The first line will also be used as the subject of the review.\n'
2062 '#--------------------This line is 72 characters long'
2063 '--------------------\n'
2064 'Some.\n\nFixed: 123\nChange-Id: xxx',
2065 desc)
2066 return desc
2067
Edward Lemurda4b6c62020-02-13 00:28:40 +00002068 mock.patch('git_cl.Changelist.FetchDescription',
2069 lambda *args: current_desc).start()
2070 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002071
Edward Lemur85153282020-02-14 22:06:29 +00002072 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002073 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002074
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002075 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002076 mock.patch('git_cl.Changelist', ChangelistMock).start()
2077 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002078
2079 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2080 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2081
kmarshall3bff56b2016-06-06 18:31:47 -07002082 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002083 self.calls = [
2084 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002085 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002086 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002087 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002088 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002089 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002090
Edward Lemurda4b6c62020-02-13 00:28:40 +00002091 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002092 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002093 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2094 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002095 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002096
2097 self.assertEqual(0, git_cl.main(['archive', '-f']))
2098
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002099 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002100 self.calls = [
2101 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2102 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2103 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2104 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002105 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2106 ((['git', 'branch', '-D', 'foo'],), '')
2107 ]
2108
Edward Lemurda4b6c62020-02-13 00:28:40 +00002109 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002110 lambda branches, fine_grained, max_processes:
2111 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2112 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002113 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002114
2115 self.assertEqual(0, git_cl.main(['archive', '-f']))
2116
kmarshall3bff56b2016-06-06 18:31:47 -07002117 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002118 self.calls = [
2119 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2120 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002121 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002122 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002123
Edward Lemurda4b6c62020-02-13 00:28:40 +00002124 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002125 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002126 [(MockChangelistWithBranchAndIssue('master', 1),
2127 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002128
2129 self.assertEqual(1, git_cl.main(['archive', '-f']))
2130
2131 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002132 self.calls = [
2133 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2134 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002135 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002136 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002137
Edward Lemurda4b6c62020-02-13 00:28:40 +00002138 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002139 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002140 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2141 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002142 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002143
kmarshall9249e012016-08-23 12:02:16 -07002144 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2145
2146 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002147 self.calls = [
2148 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2149 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002150 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002151 ((['git', 'branch', '-D', 'foo'],), '')
2152 ]
kmarshall9249e012016-08-23 12:02:16 -07002153
Edward Lemurda4b6c62020-02-13 00:28:40 +00002154 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002155 lambda branches, fine_grained, max_processes:
2156 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2157 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002158 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002159
2160 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002161
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002162 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002163 self.calls = [
2164 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2165 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2166 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002167 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2168 'refs/tags/git-cl-archived-456-foo'),
2169 ((['git', 'branch', '-D', 'foo'],), CERR1),
2170 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2171 'refs/tags/git-cl-archived-456-foo'),
2172 ]
2173
Edward Lemurda4b6c62020-02-13 00:28:40 +00002174 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002175 lambda branches, fine_grained, max_processes:
2176 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2177 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002178 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002179
2180 self.assertEqual(0, git_cl.main(['archive', '-f']))
2181
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002182 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002183 self.mockGit.config['branch.master.gerritissue'] = '123'
2184 self.mockGit.config['branch.master.gerritserver'] = (
2185 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002186 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002187 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002188 ]
2189 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002190 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2191 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002192
Aaron Gable400e9892017-07-12 15:31:21 -07002193 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002194 self.mockGit.config['branch.master.gerritissue'] = '123'
2195 self.mockGit.config['branch.master.gerritserver'] = (
2196 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002197 mock.patch('git_cl.Changelist.FetchDescription',
2198 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002199 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002200 ((['git', 'log', '-1', '--format=%B'],),
2201 'This is a description\n\nChange-Id: Ideadbeef'),
2202 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002203 ]
2204 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002205 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2206 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002207
phajdan.jre328cf92016-08-22 04:12:17 -07002208 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002209 self.mockGit.config['branch.master.gerritissue'] = '123'
2210 self.mockGit.config['branch.master.gerritserver'] = (
2211 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002212 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002213 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002214 {'issue': 123,
2215 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002216 ''),
2217 ]
2218 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2219
tandrii16e0b4e2016-06-07 10:34:28 -07002220 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002221 mock.patch(
2222 'git_cl.os.path.abspath',
2223 lambda path: self._mocked_call(['abspath', path])).start()
2224 mock.patch(
2225 'git_cl.os.path.exists',
2226 lambda path: self._mocked_call(['exists', path])).start()
2227 mock.patch(
2228 'git_cl.gclient_utils.FileRead',
2229 lambda path: self._mocked_call(['FileRead', path])).start()
2230 mock.patch(
2231 'git_cl.gclient_utils.rm_file_or_tree',
2232 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002233 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002234
2235 def test_GerritCommitMsgHookCheck_custom_hook(self):
2236 cl = self._common_GerritCommitMsgHookCheck()
2237 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002238 ((['exists', '.git/hooks/commit-msg'],), True),
2239 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002240 '#!/bin/sh\necho "custom hook"')
2241 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002242 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002243
2244 def test_GerritCommitMsgHookCheck_not_exists(self):
2245 cl = self._common_GerritCommitMsgHookCheck()
2246 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002247 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002248 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002249 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002250
2251 def test_GerritCommitMsgHookCheck(self):
2252 cl = self._common_GerritCommitMsgHookCheck()
2253 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002254 ((['exists', '.git/hooks/commit-msg'],), True),
2255 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002256 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002257 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002258 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002259 ''),
2260 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002261 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002262
tandriic4344b52016-08-29 06:04:54 -07002263 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002264 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2265 self.mockGit.config['branch.master.gerritserver'] = (
2266 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002267 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002268 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002269 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002270 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002271 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002272 'labels': {},
2273 'current_revision': 'deadbeaf',
2274 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002275 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002276 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002277 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002278 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2279 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002280 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002281 self.assertEqual(0, cl.CMDLand(force=True,
2282 bypass_hooks=True,
2283 verbose=True,
2284 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002285 self.assertIn(
2286 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002287 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002288 self.assertIn(
2289 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002290 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002291
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002292 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002293 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002294
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002295 def test_gerrit_change_detail_cache_simple(self):
2296 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002297 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002298 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002299 cl1._cached_remote_url = (
2300 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002301 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002302 cl2._cached_remote_url = (
2303 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002304 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2305 self.assertEqual(cl1._GetChangeDetail(), 'a')
2306 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002307
2308 def test_gerrit_change_detail_cache_options(self):
2309 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002310 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002311 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002312 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002313 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2314 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2315 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2316 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2317 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2318 self.assertEqual(cl._GetChangeDetail(), 'cab')
2319
2320 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2321 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2322 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2323 self.assertEqual(cl._GetChangeDetail(), 'cab')
2324
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002325 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002326 gerrit_util.GetChangeDetail.return_value = {
2327 'current_revision': 'rev1',
2328 'revisions': {
2329 'rev1': {'commit': {'message': 'desc1'}},
2330 },
2331 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002332
2333 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002334 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002335 cl._cached_remote_url = (
2336 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002337 self.assertEqual(cl.FetchDescription(), 'desc1')
2338 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002339
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002340 def test_print_current_creds(self):
2341 class CookiesAuthenticatorMock(object):
2342 def __init__(self):
2343 self.gitcookies = {
2344 'host.googlesource.com': ('user', 'pass'),
2345 'host-review.googlesource.com': ('user', 'pass'),
2346 }
2347 self.netrc = self
2348 self.netrc.hosts = {
2349 'github.com': ('user2', None, 'pass2'),
2350 'host2.googlesource.com': ('user3', None, 'pass'),
2351 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002352 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2353 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002354 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2355 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2356 ' Host\t User\t Which file',
2357 '============================\t=====\t===========',
2358 'host-review.googlesource.com\t user\t.gitcookies',
2359 ' host.googlesource.com\t user\t.gitcookies',
2360 ' host2.googlesource.com\tuser3\t .netrc',
2361 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002362 sys.stdout.seek(0)
2363 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002364 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2365 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2366 ' Host\tUser\t Which file',
2367 '============================\t====\t===========',
2368 'host-review.googlesource.com\tuser\t.gitcookies',
2369 ' host.googlesource.com\tuser\t.gitcookies',
2370 ])
2371
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002372 def _common_creds_check_mocks(self):
2373 def exists_mock(path):
2374 dirname = os.path.dirname(path)
2375 if dirname == os.path.expanduser('~'):
2376 dirname = '~'
2377 base = os.path.basename(path)
2378 if base in ('.netrc', '.gitcookies'):
2379 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2380 # git cl also checks for existence other files not relevant to this test.
2381 return None
Edward Lemurda4b6c62020-02-13 00:28:40 +00002382 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002383
2384 def test_creds_check_gitcookies_not_configured(self):
2385 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002386 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2387 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002388 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002389 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002390 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2391 (('os.path.exists', '~/.netrc'), True),
2392 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2393 'or Ctrl+C to abort'), ''),
2394 ((['git', 'config', '--global', 'http.cookiefile',
2395 os.path.expanduser('~/.gitcookies')], ), ''),
2396 ]
2397 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002398 self.assertTrue(
2399 sys.stdout.getvalue().startswith(
2400 'You seem to be using outdated .netrc for git credentials:'))
2401 self.assertIn(
2402 '\nConfigured git to use .gitcookies from',
2403 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002404
2405 def test_creds_check_gitcookies_configured_custom_broken(self):
2406 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002407 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2408 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002409 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002410 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002411 ((['git', 'config', '--global', 'http.cookiefile'],),
2412 '/custom/.gitcookies'),
2413 (('os.path.exists', '/custom/.gitcookies'), False),
2414 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2415 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2416 ((['git', 'config', '--global', 'http.cookiefile',
2417 os.path.expanduser('~/.gitcookies')], ), ''),
2418 ]
2419 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002420 self.assertIn(
2421 'WARNING: You have configured custom path to .gitcookies: ',
2422 sys.stdout.getvalue())
2423 self.assertIn(
2424 'However, your configured .gitcookies file is missing.',
2425 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002426
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002427 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002428 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002429 self.mockGit.config['remote.origin.url'] = (
2430 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002431 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002432 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002433 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002434 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002435 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002436 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002437
Edward Lemurda4b6c62020-02-13 00:28:40 +00002438 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2439 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002440 self.mockGit.config['remote.origin.url'] = (
2441 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002442 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002443 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002444 'current_revision': 'ba5eba11',
2445 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002446 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002447 '_number': 1,
2448 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002449 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002450 '_number': 2,
2451 },
2452 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002453 'messages': [
2454 {
2455 u'_revision_number': 1,
2456 u'author': {
2457 u'_account_id': 1111084,
2458 u'email': u'commit-bot@chromium.org',
2459 u'name': u'Commit Bot'
2460 },
2461 u'date': u'2017-03-15 20:08:45.000000000',
2462 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002463 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002464 u'tag': u'autogenerated:cq:dry-run'
2465 },
2466 {
2467 u'_revision_number': 2,
2468 u'author': {
2469 u'_account_id': 11151243,
2470 u'email': u'owner@example.com',
2471 u'name': u'owner'
2472 },
2473 u'date': u'2017-03-16 20:00:41.000000000',
2474 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2475 u'message': u'PTAL',
2476 },
2477 {
2478 u'_revision_number': 2,
2479 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002480 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002481 u'email': u'reviewer@example.com',
2482 u'name': u'reviewer'
2483 },
2484 u'date': u'2017-03-17 05:19:37.500000000',
2485 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2486 u'message': u'Patch Set 2: Code-Review+1',
2487 },
2488 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002489 }
2490 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002491 (('GetChangeComments', 'chromium-review.googlesource.com',
2492 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002493 '/COMMIT_MSG': [
2494 {
2495 'author': {'email': u'reviewer@example.com'},
2496 'updated': u'2017-03-17 05:19:37.500000000',
2497 'patch_set': 2,
2498 'side': 'REVISION',
2499 'message': 'Please include a bug link',
2500 },
2501 ],
2502 'codereview.settings': [
2503 {
2504 'author': {'email': u'owner@example.com'},
2505 'updated': u'2017-03-16 20:00:41.000000000',
2506 'patch_set': 2,
2507 'side': 'PARENT',
2508 'line': 42,
2509 'message': 'I removed this because it is bad',
2510 },
2511 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002512 }),
2513 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2514 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002515 ] * 2 + [
2516 (('write_json', 'output.json', [
2517 {
2518 u'date': u'2017-03-16 20:00:41.000000',
2519 u'message': (
2520 u'PTAL\n' +
2521 u'\n' +
2522 u'codereview.settings\n' +
2523 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2524 u'c/1/2/codereview.settings#b42\n' +
2525 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002526 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002527 u'approval': False,
2528 u'disapproval': False,
2529 u'sender': u'owner@example.com'
2530 }, {
2531 u'date': u'2017-03-17 05:19:37.500000',
2532 u'message': (
2533 u'Patch Set 2: Code-Review+1\n' +
2534 u'\n' +
2535 u'/COMMIT_MSG\n' +
2536 u' PS2, File comment: https://chromium-review.googlesource' +
2537 u'.com/c/1/2//COMMIT_MSG#\n' +
2538 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002539 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002540 u'approval': False,
2541 u'disapproval': False,
2542 u'sender': u'reviewer@example.com'
2543 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002544 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002545 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002546 expected_comments_summary = [
2547 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002548 message=(
2549 u'PTAL\n' +
2550 u'\n' +
2551 u'codereview.settings\n' +
2552 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2553 u'c/1/2/codereview.settings#b42\n' +
2554 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002555 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002556 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002557 disapproval=False, approval=False, sender=u'owner@example.com'),
2558 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002559 message=(
2560 u'Patch Set 2: Code-Review+1\n' +
2561 u'\n' +
2562 u'/COMMIT_MSG\n' +
2563 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2564 u'c/1/2//COMMIT_MSG#\n' +
2565 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002566 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002567 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002568 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2569 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002570 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002571 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002572 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002573 self.assertEqual(
2574 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2575
2576 def test_git_cl_comments_robot_comments(self):
2577 # git cl comments also fetches robot comments (which are considered a type
2578 # of autogenerated comment), and unlike other types of comments, only robot
2579 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002580 self.mockGit.config['remote.origin.url'] = (
2581 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002582 gerrit_util.GetChangeDetail.return_value = {
2583 'owner': {'email': 'owner@example.com'},
2584 'current_revision': 'ba5eba11',
2585 'revisions': {
2586 'deadbeaf': {
2587 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002588 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002589 'ba5eba11': {
2590 '_number': 2,
2591 },
2592 },
2593 'messages': [
2594 {
2595 u'_revision_number': 1,
2596 u'author': {
2597 u'_account_id': 1111084,
2598 u'email': u'commit-bot@chromium.org',
2599 u'name': u'Commit Bot'
2600 },
2601 u'date': u'2017-03-15 20:08:45.000000000',
2602 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2603 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2604 u'tag': u'autogenerated:cq:dry-run'
2605 },
2606 {
2607 u'_revision_number': 1,
2608 u'author': {
2609 u'_account_id': 123,
2610 u'email': u'tricium@serviceaccount.com',
2611 u'name': u'Tricium'
2612 },
2613 u'date': u'2017-03-16 20:00:41.000000000',
2614 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2615 u'message': u'(1 comment)',
2616 u'tag': u'autogenerated:tricium',
2617 },
2618 {
2619 u'_revision_number': 1,
2620 u'author': {
2621 u'_account_id': 123,
2622 u'email': u'tricium@serviceaccount.com',
2623 u'name': u'Tricium'
2624 },
2625 u'date': u'2017-03-16 20:00:41.000000000',
2626 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2627 u'message': u'(1 comment)',
2628 u'tag': u'autogenerated:tricium',
2629 },
2630 {
2631 u'_revision_number': 2,
2632 u'author': {
2633 u'_account_id': 123,
2634 u'email': u'tricium@serviceaccount.com',
2635 u'name': u'reviewer'
2636 },
2637 u'date': u'2017-03-17 05:30:37.000000000',
2638 u'tag': u'autogenerated:tricium',
2639 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2640 u'message': u'(1 comment)',
2641 },
2642 ]
2643 }
2644 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002645 (('GetChangeComments', 'chromium-review.googlesource.com',
2646 'infra%2Finfra~1'), {}),
2647 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2648 'infra%2Finfra~1'), {
2649 'codereview.settings': [
2650 {
2651 u'author': {u'email': u'tricium@serviceaccount.com'},
2652 u'updated': u'2017-03-17 05:30:37.000000000',
2653 u'robot_run_id': u'5565031076855808',
2654 u'robot_id': u'Linter/Category',
2655 u'tag': u'autogenerated:tricium',
2656 u'patch_set': 2,
2657 u'side': u'REVISION',
2658 u'message': u'Linter warning message text',
2659 u'line': 32,
2660 },
2661 ],
2662 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002663 ]
2664 expected_comments_summary = [
2665 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2666 message=(
2667 u'(1 comment)\n\ncodereview.settings\n'
2668 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2669 u'c/1/2/codereview.settings#32\n'
2670 u' Linter warning message text\n'),
2671 sender=u'tricium@serviceaccount.com',
2672 autogenerated=True, approval=False, disapproval=False)
2673 ]
2674 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002675 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002676 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002677
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002678 def test_get_remote_url_with_mirror(self):
2679 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002680
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002681 def selective_os_path_isdir_mock(path):
2682 if path == '/cache/this-dir-exists':
2683 return self._mocked_call('os.path.isdir', path)
2684 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002685
Edward Lemurda4b6c62020-02-13 00:28:40 +00002686 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002687
2688 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002689 self.mockGit.config['remote.origin.url'] = (
2690 '/cache/this-dir-exists')
2691 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2692 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002693 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002694 (('os.path.isdir', '/cache/this-dir-exists'),
2695 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002696 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002697 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002698 self.assertEqual(cl.GetRemoteUrl(), url)
2699 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2700
Edward Lemur298f2cf2019-02-22 21:40:39 +00002701 def test_get_remote_url_non_existing_mirror(self):
2702 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002703
Edward Lemur298f2cf2019-02-22 21:40:39 +00002704 def selective_os_path_isdir_mock(path):
2705 if path == '/cache/this-dir-doesnt-exist':
2706 return self._mocked_call('os.path.isdir', path)
2707 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002708
Edward Lemurda4b6c62020-02-13 00:28:40 +00002709 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2710 mock.patch('logging.error',
2711 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002712
Edward Lemur26964072020-02-19 19:18:51 +00002713 self.mockGit.config['remote.origin.url'] = (
2714 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002715 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002716 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2717 False),
2718 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002719 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2720 'but it doesn\'t exist.', {
2721 'remote': 'origin',
2722 'branch': 'master',
2723 'url': '/cache/this-dir-doesnt-exist'}
2724 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002725 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002726 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002727 self.assertIsNone(cl.GetRemoteUrl())
2728
2729 def test_get_remote_url_misconfigured_mirror(self):
2730 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002731
Edward Lemur298f2cf2019-02-22 21:40:39 +00002732 def selective_os_path_isdir_mock(path):
2733 if path == '/cache/this-dir-exists':
2734 return self._mocked_call('os.path.isdir', path)
2735 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002736
Edward Lemurda4b6c62020-02-13 00:28:40 +00002737 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2738 mock.patch('logging.error',
2739 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002740
Edward Lemur26964072020-02-19 19:18:51 +00002741 self.mockGit.config['remote.origin.url'] = (
2742 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002743 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002744 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002745 (('logging.error',
2746 'Remote "%(remote)s" for branch "%(branch)s" points to '
2747 '"%(cache_path)s", but it is misconfigured.\n'
2748 '"%(cache_path)s" must be a git repo and must have a remote named '
2749 '"%(remote)s" pointing to the git host.', {
2750 'remote': 'origin',
2751 'cache_path': '/cache/this-dir-exists',
2752 'branch': 'master'}
2753 ), None),
2754 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002755 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002756 self.assertIsNone(cl.GetRemoteUrl())
2757
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002758 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002759 self.mockGit.config['remote.origin.url'] = (
2760 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002761 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002762 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2763
2764 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002765 mock.patch('logging.error',
2766 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002767
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002768 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002769 (('logging.error',
2770 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2771 'but it doesn\'t exist.', {
2772 'remote': 'origin',
2773 'branch': 'master',
2774 'url': ''}
2775 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002776 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002777 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002778 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002779
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002780
Edward Lemur9aa1a962020-02-25 00:58:38 +00002781class ChangelistTest(unittest.TestCase):
2782 @mock.patch('git_cl.RunGitWithCode')
2783 def testGetLocalDescription(self, _mock):
2784 git_cl.RunGitWithCode.return_value = (0, 'description')
2785 cl = git_cl.Changelist()
2786 self.assertEqual('description', cl.GetLocalDescription('branch'))
2787 self.assertEqual('description', cl.GetLocalDescription('branch'))
2788 git_cl.RunGitWithCode.assert_called_once_with(
2789 ['log', '--pretty=format:%s%n%n%b', 'branch...'])
2790
2791
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002792class CMDTestCaseBase(unittest.TestCase):
2793 _STATUSES = [
2794 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2795 'INFRA_FAILURE', 'CANCELED',
2796 ]
2797 _CHANGE_DETAIL = {
2798 'project': 'depot_tools',
2799 'status': 'OPEN',
2800 'owner': {'email': 'owner@e.mail'},
2801 'current_revision': 'beeeeeef',
2802 'revisions': {
2803 'deadbeaf': {'_number': 6},
2804 'beeeeeef': {
2805 '_number': 7,
2806 'fetch': {'http': {
2807 'url': 'https://chromium.googlesource.com/depot_tools',
2808 'ref': 'refs/changes/56/123456/7'
2809 }},
2810 },
2811 },
2812 }
2813 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002814 'builds': [{
2815 'id': str(100 + idx),
2816 'builder': {
2817 'project': 'chromium',
2818 'bucket': 'try',
2819 'builder': 'bot_' + status.lower(),
2820 },
2821 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2822 'tags': [],
2823 'status': status,
2824 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002825 }
2826
Edward Lemur4c707a22019-09-24 21:13:43 +00002827 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002828 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002829 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002830 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2831 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002832 mock.patch(
2833 'git_cl.Changelist.GetCodereviewServer',
2834 return_value='https://chromium-review.googlesource.com').start()
2835 mock.patch(
2836 'git_cl.Changelist._GetGerritHost',
2837 return_value='chromium-review.googlesource.com').start()
2838 mock.patch(
2839 'git_cl.Changelist.GetMostRecentPatchset',
2840 return_value=7).start()
2841 mock.patch(
2842 'git_cl.Changelist.GetRemoteUrl',
2843 return_value='https://chromium.googlesource.com/depot_tools').start()
2844 mock.patch(
2845 'auth.Authenticator',
2846 return_value=AuthenticatorMock()).start()
2847 mock.patch(
2848 'gerrit_util.GetChangeDetail',
2849 return_value=self._CHANGE_DETAIL).start()
2850 mock.patch(
2851 'git_cl._call_buildbucket',
2852 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002853 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002854 self.addCleanup(mock.patch.stopall)
2855
Edward Lemur4c707a22019-09-24 21:13:43 +00002856
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002857class CMDTryResultsTestCase(CMDTestCaseBase):
2858 _DEFAULT_REQUEST = {
2859 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002860 "gerritChanges": [{
2861 "project": "depot_tools",
2862 "host": "chromium-review.googlesource.com",
2863 "patchset": 7,
2864 "change": 123456,
2865 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002866 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002867 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2868 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002869 }
2870
2871 def testNoJobs(self):
2872 git_cl._call_buildbucket.return_value = {}
2873
2874 self.assertEqual(0, git_cl.main(['try-results']))
2875 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2876 git_cl._call_buildbucket.assert_called_once_with(
2877 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2878 self._DEFAULT_REQUEST)
2879
2880 def testPrintToStdout(self):
2881 self.assertEqual(0, git_cl.main(['try-results']))
2882 self.assertEqual([
2883 'Successes:',
2884 ' bot_success https://ci.chromium.org/b/103',
2885 'Infra Failures:',
2886 ' bot_infra_failure https://ci.chromium.org/b/105',
2887 'Failures:',
2888 ' bot_failure https://ci.chromium.org/b/104',
2889 'Canceled:',
2890 ' bot_canceled ',
2891 'Started:',
2892 ' bot_started https://ci.chromium.org/b/102',
2893 'Scheduled:',
2894 ' bot_scheduled id=101',
2895 'Other:',
2896 ' bot_status_unspecified id=100',
2897 'Total: 7 tryjobs',
2898 ], sys.stdout.getvalue().splitlines())
2899 git_cl._call_buildbucket.assert_called_once_with(
2900 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2901 self._DEFAULT_REQUEST)
2902
2903 def testPrintToStdoutWithMasters(self):
2904 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2905 self.assertEqual([
2906 'Successes:',
2907 ' try bot_success https://ci.chromium.org/b/103',
2908 'Infra Failures:',
2909 ' try bot_infra_failure https://ci.chromium.org/b/105',
2910 'Failures:',
2911 ' try bot_failure https://ci.chromium.org/b/104',
2912 'Canceled:',
2913 ' try bot_canceled ',
2914 'Started:',
2915 ' try bot_started https://ci.chromium.org/b/102',
2916 'Scheduled:',
2917 ' try bot_scheduled id=101',
2918 'Other:',
2919 ' try bot_status_unspecified id=100',
2920 'Total: 7 tryjobs',
2921 ], sys.stdout.getvalue().splitlines())
2922 git_cl._call_buildbucket.assert_called_once_with(
2923 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2924 self._DEFAULT_REQUEST)
2925
2926 @mock.patch('git_cl.write_json')
2927 def testWriteToJson(self, mockJsonDump):
2928 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
2929 git_cl._call_buildbucket.assert_called_once_with(
2930 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2931 self._DEFAULT_REQUEST)
2932 mockJsonDump.assert_called_once_with(
2933 'file.json', self._DEFAULT_RESPONSE['builds'])
2934
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002935 def test_filter_failed_for_one_simple(self):
2936 self.assertEqual({}, git_cl._filter_failed_for_retry([]))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002937 self.assertEqual({
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002938 'chromium/try': {
2939 'bot_failure': [],
2940 'bot_infra_failure': []
2941 },
2942 }, git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
2943
2944 def test_filter_failed_for_retry_many_builds(self):
2945
2946 def _build(name, created_sec, status, experimental=False):
2947 assert 0 <= created_sec < 100, created_sec
2948 b = {
2949 'id': 112112,
2950 'builder': {
2951 'project': 'chromium',
2952 'bucket': 'try',
2953 'builder': name,
2954 },
2955 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
2956 'status': status,
2957 'tags': [],
2958 }
2959 if experimental:
2960 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
2961 return b
2962
2963 builds = [
2964 _build('flaky-last-green', 1, 'FAILURE'),
2965 _build('flaky-last-green', 2, 'SUCCESS'),
2966 _build('flaky', 1, 'SUCCESS'),
2967 _build('flaky', 2, 'FAILURE'),
2968 _build('running', 1, 'FAILED'),
2969 _build('running', 2, 'SCHEDULED'),
2970 _build('yep-still-running', 1, 'STARTED'),
2971 _build('yep-still-running', 2, 'FAILURE'),
2972 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
2973 _build('cq-experimental', 2, 'FAILURE', experimental=True),
2974
2975 # Simulate experimental in CQ builder, which developer decided
2976 # to retry manually which resulted in 2nd build non-experimental.
2977 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
2978 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
2979 ]
2980 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
2981 self.assertEqual({
2982 'chromium/try': {
2983 'flaky': [],
2984 'sometimes-experimental': []
2985 },
2986 }, git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002987
2988
2989class CMDTryTestCase(CMDTestCaseBase):
2990
2991 @mock.patch('git_cl.Changelist.SetCQState')
2992 @mock.patch('git_cl._get_bucket_map', return_value={})
2993 def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
2994 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00002995 self.assertEqual(0, git_cl.main(['try']))
2996 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
2997 self.assertEqual(
2998 sys.stdout.getvalue(),
2999 'Scheduling CQ dry run on: '
3000 'https://chromium-review.googlesource.com/123456\n')
3001
Edward Lemur4c707a22019-09-24 21:13:43 +00003002 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003003 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003004 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003005
3006 self.assertEqual(0, git_cl.main([
3007 'try', '-B', 'luci.chromium.try', '-b', 'win',
3008 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3009 self.assertIn(
3010 'Scheduling jobs on:\nBucket: luci.chromium.try',
3011 git_cl.sys.stdout.getvalue())
3012
3013 expected_request = {
3014 "requests": [{
3015 "scheduleBuild": {
3016 "requestId": "uuid4",
3017 "builder": {
3018 "project": "chromium",
3019 "builder": "win",
3020 "bucket": "try",
3021 },
3022 "gerritChanges": [{
3023 "project": "depot_tools",
3024 "host": "chromium-review.googlesource.com",
3025 "patchset": 7,
3026 "change": 123456,
3027 }],
3028 "properties": {
3029 "category": "git_cl_try",
3030 "json": [{"a": 1}, None],
3031 "key": "val",
3032 },
3033 "tags": [
3034 {"value": "win", "key": "builder"},
3035 {"value": "git_cl_try", "key": "user_agent"},
3036 ],
3037 },
3038 }],
3039 }
3040 mockCallBuildbucket.assert_called_with(
3041 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3042
Anthony Polito1a5fe232020-01-24 23:17:52 +00003043 @mock.patch('git_cl._call_buildbucket')
3044 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3045 mockCallBuildbucket.return_value = {}
3046
3047 self.assertEqual(0, git_cl.main([
3048 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3049 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3050 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3051 self.assertIn(
3052 'Scheduling jobs on:\nBucket: luci.chromium.try',
3053 git_cl.sys.stdout.getvalue())
3054
3055 expected_request = {
3056 "requests": [{
3057 "scheduleBuild": {
3058 "requestId": "uuid4",
3059 "builder": {
3060 "project": "chromium",
3061 "builder": "linux",
3062 "bucket": "try",
3063 },
3064 "gerritChanges": [{
3065 "project": "depot_tools",
3066 "host": "chromium-review.googlesource.com",
3067 "patchset": 7,
3068 "change": 123456,
3069 }],
3070 "properties": {
3071 "category": "git_cl_try",
3072 "json": [{"a": 1}, None],
3073 "key": "val",
3074 },
3075 "tags": [
3076 {"value": "linux", "key": "builder"},
3077 {"value": "git_cl_try", "key": "user_agent"},
3078 ],
3079 "gitilesCommit": {
3080 "host": "chromium-review.googlesource.com",
3081 "project": "depot_tools",
3082 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3083 }
3084 },
3085 },
3086 {
3087 "scheduleBuild": {
3088 "requestId": "uuid4",
3089 "builder": {
3090 "project": "chromium",
3091 "builder": "win",
3092 "bucket": "try",
3093 },
3094 "gerritChanges": [{
3095 "project": "depot_tools",
3096 "host": "chromium-review.googlesource.com",
3097 "patchset": 7,
3098 "change": 123456,
3099 }],
3100 "properties": {
3101 "category": "git_cl_try",
3102 "json": [{"a": 1}, None],
3103 "key": "val",
3104 },
3105 "tags": [
3106 {"value": "win", "key": "builder"},
3107 {"value": "git_cl_try", "key": "user_agent"},
3108 ],
3109 "gitilesCommit": {
3110 "host": "chromium-review.googlesource.com",
3111 "project": "depot_tools",
3112 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3113 }
3114 },
3115 }],
3116 }
3117 mockCallBuildbucket.assert_called_with(
3118 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3119
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003120 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur4c707a22019-09-24 21:13:43 +00003121 self.assertEqual(0, git_cl.main([
3122 'try', '-B', 'not-a-bucket', '-b', 'win',
3123 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3124 self.assertIn(
3125 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3126 git_cl.sys.stdout.getvalue())
3127
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003128 @mock.patch('git_cl._call_buildbucket')
3129 @mock.patch('git_cl.fetch_try_jobs')
3130 def testScheduleOnBuildbucketRetryFailed(
3131 self, mockFetchTryJobs, mockCallBuildbucket):
3132
3133 git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
3134 7: [],
3135 6: [{
3136 'id': 112112,
3137 'builder': {
3138 'project': 'chromium',
3139 'bucket': 'try',
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003140 'builder': 'linux',},
3141 'createTime': '2019-10-09T08:00:01.854286Z',
3142 'tags': [],
3143 'status': 'FAILURE',}],}[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003144 mockCallBuildbucket.return_value = {}
3145
3146 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3147 self.assertIn(
3148 'Scheduling jobs on:\nBucket: chromium/try',
3149 git_cl.sys.stdout.getvalue())
3150
3151 expected_request = {
3152 "requests": [{
3153 "scheduleBuild": {
3154 "requestId": "uuid4",
3155 "builder": {
3156 "project": "chromium",
3157 "bucket": "try",
3158 "builder": "linux",
3159 },
3160 "gerritChanges": [{
3161 "project": "depot_tools",
3162 "host": "chromium-review.googlesource.com",
3163 "patchset": 7,
3164 "change": 123456,
3165 }],
3166 "properties": {
3167 "category": "git_cl_try",
3168 },
3169 "tags": [
3170 {"value": "linux", "key": "builder"},
3171 {"value": "git_cl_try", "key": "user_agent"},
3172 {"value": "1", "key": "retry_failed"},
3173 ],
3174 },
3175 }],
3176 }
3177 mockCallBuildbucket.assert_called_with(
3178 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3179
Edward Lemur4c707a22019-09-24 21:13:43 +00003180 def test_parse_bucket(self):
3181 test_cases = [
3182 {
3183 'bucket': 'chromium/try',
3184 'result': ('chromium', 'try'),
3185 },
3186 {
3187 'bucket': 'luci.chromium.try',
3188 'result': ('chromium', 'try'),
3189 'has_warning': True,
3190 },
3191 {
3192 'bucket': 'skia.primary',
3193 'result': ('skia', 'skia.primary'),
3194 'has_warning': True,
3195 },
3196 {
3197 'bucket': 'not-a-bucket',
3198 'result': (None, None),
3199 },
3200 ]
3201
3202 for test_case in test_cases:
3203 git_cl.sys.stdout.truncate(0)
3204 self.assertEqual(
3205 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3206 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003207 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3208 test_case['result'])
3209 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003210
3211
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003212class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003213 def setUp(self):
3214 super(CMDUploadTestCase, self).setUp()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003215 mock.patch('git_cl.fetch_try_jobs').start()
3216 mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
3217 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003218 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003219 self.addCleanup(mock.patch.stopall)
3220
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003221 def testWarmUpChangeDetailCache(self):
3222 self.assertEqual(0, git_cl.main(['upload']))
3223 gerrit_util.GetChangeDetail.assert_called_once_with(
3224 'chromium-review.googlesource.com', 'depot_tools~123456',
3225 frozenset([
3226 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3227 'CURRENT_COMMIT']))
3228
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003229 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003230 # This test mocks out the actual upload part, and just asserts that after
3231 # upload, if --retry-failed is added, then the tool will fetch try jobs
3232 # from the previous patchset and trigger the right builders on the latest
3233 # patchset.
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003234 git_cl.fetch_try_jobs.side_effect = [
3235 # Latest patchset: No builds.
3236 [],
3237 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003238 [{
3239 'id': str(100 + idx),
3240 'builder': {
3241 'project': 'chromium',
3242 'bucket': 'try',
3243 'builder': 'bot_' + status.lower(),
3244 },
3245 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3246 'tags': [],
3247 'status': status,
3248 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003249 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003250
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003251 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003252 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003253 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3254 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003255 ], git_cl.fetch_try_jobs.mock_calls)
3256 expected_buckets = {
3257 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
3258 }
3259 git_cl._trigger_try_jobs.assert_called_once_with(
Edward Lemur5b929a42019-10-21 17:57:39 +00003260 mock.ANY, expected_buckets, mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003261
Brian Sheedy59b06a82019-10-14 17:03:29 +00003262
Edward Lemurda4b6c62020-02-13 00:28:40 +00003263class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003264
3265 def setUp(self):
3266 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003267 mock.patch('git_cl.RunCommand').start()
3268 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3269 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3270 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003271 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003272 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003273
3274 def tearDown(self):
3275 shutil.rmtree(self._top_dir)
3276 super(CMDFormatTestCase, self).tearDown()
3277
Jamie Madill5e96ad12020-01-13 16:08:35 +00003278 def _make_temp_file(self, fname, contents):
3279 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3280 tf.write('\n'.join(contents))
3281
Brian Sheedy59b06a82019-10-14 17:03:29 +00003282 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003283 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003284
Brian Sheedyb4307d52019-12-02 19:18:17 +00003285 def _check_yapf_filtering(self, files, expected):
3286 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3287 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003288
Jamie Madill5e96ad12020-01-13 16:08:35 +00003289 def testClangFormatDiffFull(self):
3290 self._make_temp_file('test.cc', ['// test'])
3291 git_cl.settings.GetFormatFullByDefault.return_value = False
3292 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3293 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3294
3295 # Diff
3296 git_cl.RunCommand.return_value = ' // test'
3297 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3298 self._top_dir, 'HEAD')
3299 self.assertEqual(2, return_value)
3300
3301 # No diff
3302 git_cl.RunCommand.return_value = '// test'
3303 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3304 self._top_dir, 'HEAD')
3305 self.assertEqual(0, return_value)
3306
3307 def testClangFormatDiff(self):
3308 git_cl.settings.GetFormatFullByDefault.return_value = False
3309 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3310
3311 # Diff
3312 git_cl.RunCommand.return_value = 'error'
3313 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3314 'HEAD')
3315 self.assertEqual(2, return_value)
3316
3317 # No diff
3318 git_cl.RunCommand.return_value = ''
3319 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3320 'HEAD')
3321 self.assertEqual(0, return_value)
3322
Brian Sheedyb4307d52019-12-02 19:18:17 +00003323 def testYapfignoreExplicit(self):
3324 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3325 files = [
3326 'bar.py',
3327 'foo/bar.py',
3328 'foo/baz.py',
3329 'foo/bar/baz.py',
3330 'foo/bar/foobar.py',
3331 ]
3332 expected = [
3333 'bar.py',
3334 'foo/baz.py',
3335 'foo/bar/foobar.py',
3336 ]
3337 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003338
Brian Sheedyb4307d52019-12-02 19:18:17 +00003339 def testYapfignoreSingleWildcards(self):
3340 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3341 files = [
3342 'bar.py', # Matched by *bar.py.
3343 'bar.txt',
3344 'foobar.py', # Matched by *bar.py, foo*.
3345 'foobar.txt', # Matched by foo*.
3346 'bazbar.py', # Matched by *bar.py, baz*.py.
3347 'bazbar.txt',
3348 'foo/baz.txt', # Matched by foo*.
3349 'bar/bar.py', # Matched by *bar.py.
3350 'baz/foo.py', # Matched by baz*.py, foo*.
3351 'baz/foo.txt',
3352 ]
3353 expected = [
3354 'bar.txt',
3355 'bazbar.txt',
3356 'baz/foo.txt',
3357 ]
3358 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003359
Brian Sheedyb4307d52019-12-02 19:18:17 +00003360 def testYapfignoreMultiplewildcards(self):
3361 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3362 files = [
3363 'bar.py', # Matched by *bar*.
3364 'bar.txt', # Matched by *bar*.
3365 'abar.py', # Matched by *bar*.
3366 'foobaz.txt', # Matched by *foo*baz.txt.
3367 'foobaz.py',
3368 'afoobaz.txt', # Matched by *foo*baz.txt.
3369 ]
3370 expected = [
3371 'foobaz.py',
3372 ]
3373 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003374
3375 def testYapfignoreComments(self):
3376 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003377 files = [
3378 'test.py',
3379 'test2.py',
3380 ]
3381 expected = [
3382 'test2.py',
3383 ]
3384 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003385
3386 def testYapfignoreBlankLines(self):
3387 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003388 files = [
3389 'test.py',
3390 'test2.py',
3391 'test3.py',
3392 ]
3393 expected = [
3394 'test3.py',
3395 ]
3396 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003397
3398 def testYapfignoreWhitespace(self):
3399 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003400 files = [
3401 'test.py',
3402 'test2.py',
3403 ]
3404 expected = [
3405 'test2.py',
3406 ]
3407 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003408
Brian Sheedyb4307d52019-12-02 19:18:17 +00003409 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003410 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003411 self._check_yapf_filtering([], [])
3412
3413 def testYapfignoreMissingYapfignore(self):
3414 files = [
3415 'test.py',
3416 ]
3417 expected = [
3418 'test.py',
3419 ]
3420 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003421
3422
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003423if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003424 logging.basicConfig(
3425 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003426 unittest.main()