blob: 4a780b45be052e5dbc49af97c33c575d188d9d2c [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'
195 cl.has_description = True
Edward Lemur6c6827c2020-02-06 21:15:18 +0000196 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700197
Edward Lemur61bf4172020-02-24 23:22:37 +0000198 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
199 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
200 def test_get_cl_statuses(self, *_mocks):
201 statuses = [
202 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
203 changes = []
204 for status in statuses:
205 cl = git_cl.Changelist()
206 cl.status = status
207 changes.append(cl)
208
209 actual = set(git_cl.get_cl_statuses(changes, True))
210 self.assertEqual(set(zip(changes, statuses)), actual)
211
212 def test_get_cl_statuses_no_changes(self):
213 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
214
215 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
216 @mock.patch('multiprocessing.pool.ThreadPool')
217 def test_get_cl_statuses_timeout(self, *_mocks):
218 changes = [git_cl.Changelist() for _ in range(2)]
219 pool = multiprocessing.pool.ThreadPool()
220 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
221 it.return_value.next.side_effect = [
222 (changes[0], 'lgtm'),
223 multiprocessing.TimeoutError,
224 ]
225
226 actual = list(git_cl.get_cl_statuses(changes, True))
227 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
228
229 @mock.patch('git_cl.Changelist.GetIssueURL')
230 def test_get_cl_statuses_not_finegrained(self, _mock):
231 changes = [git_cl.Changelist() for _ in range(2)]
232 urls = ['some-url', None]
233 git_cl.Changelist.GetIssueURL.side_effect = urls
234
235 actual = set(git_cl.get_cl_statuses(changes, False))
236 self.assertEqual(
237 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
238
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000239 def test_set_preserve_tryjobs(self):
240 d = git_cl.ChangeDescription('Simple.')
241 d.set_preserve_tryjobs()
242 self.assertEqual(d.description.splitlines(), [
243 'Simple.',
244 '',
245 'Cq-Do-Not-Cancel-Tryjobs: true',
246 ])
247 before = d.description
248 d.set_preserve_tryjobs()
249 self.assertEqual(before, d.description)
250
251 d = git_cl.ChangeDescription('\n'.join([
252 'One is enough',
253 '',
254 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
255 'Change-Id: Ideadbeef',
256 ]))
257 d.set_preserve_tryjobs()
258 self.assertEqual(d.description.splitlines(), [
259 'One is enough',
260 '',
261 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
262 'Change-Id: Ideadbeef',
263 'Cq-Do-Not-Cancel-Tryjobs: true',
264 ])
265
tandriif9aefb72016-07-01 09:06:51 -0700266 def test_get_bug_line_values(self):
267 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
268 self.assertEqual(f('', ''), [])
269 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
270 self.assertEqual(f('v8', '456'), ['v8:456'])
271 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
272 # Not nice, but not worth carying.
273 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
274 ['v8:456', 'chromium:123', 'v8:123'])
275
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100276 def _test_git_number(self, parent_msg, dest_ref, child_msg,
277 parent_hash='parenthash'):
278 desc = git_cl.ChangeDescription(child_msg)
279 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
280 return desc.description
281
282 def assertEqualByLine(self, actual, expected):
283 self.assertEqual(actual.splitlines(), expected.splitlines())
284
285 def test_git_number_bad_parent(self):
286 with self.assertRaises(ValueError):
287 self._test_git_number('Parent', 'refs/heads/master', 'Child')
288
289 def test_git_number_bad_parent_footer(self):
290 with self.assertRaises(AssertionError):
291 self._test_git_number(
292 'Parent\n'
293 '\n'
294 'Cr-Commit-Position: wrong',
295 'refs/heads/master', 'Child')
296
297 def test_git_number_bad_lineage_ignored(self):
298 actual = self._test_git_number(
299 'Parent\n'
300 '\n'
301 'Cr-Commit-Position: refs/heads/master@{#1}\n'
302 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
303 'refs/heads/master', 'Child')
304 self.assertEqualByLine(
305 actual,
306 'Child\n'
307 '\n'
308 'Cr-Commit-Position: refs/heads/master@{#2}\n'
309 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
310
311 def test_git_number_same_branch(self):
312 actual = self._test_git_number(
313 'Parent\n'
314 '\n'
315 'Cr-Commit-Position: refs/heads/master@{#12}',
316 dest_ref='refs/heads/master',
317 child_msg='Child')
318 self.assertEqualByLine(
319 actual,
320 'Child\n'
321 '\n'
322 'Cr-Commit-Position: refs/heads/master@{#13}')
323
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200324 def test_git_number_same_branch_mixed_footers(self):
325 actual = self._test_git_number(
326 'Parent\n'
327 '\n'
328 'Cr-Commit-Position: refs/heads/master@{#12}',
329 dest_ref='refs/heads/master',
330 child_msg='Child\n'
331 '\n'
332 'Broken-by: design\n'
333 'BUG=123')
334 self.assertEqualByLine(
335 actual,
336 'Child\n'
337 '\n'
338 'Broken-by: design\n'
339 'BUG=123\n'
340 'Cr-Commit-Position: refs/heads/master@{#13}')
341
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100342 def test_git_number_same_branch_with_originals(self):
343 actual = self._test_git_number(
344 'Parent\n'
345 '\n'
346 'Cr-Commit-Position: refs/heads/master@{#12}',
347 dest_ref='refs/heads/master',
348 child_msg='Child\n'
349 '\n'
350 'Some users are smart and insert their own footers\n'
351 '\n'
352 'Cr-Whatever: value\n'
353 'Cr-Commit-Position: refs/copy/paste@{#22}')
354 self.assertEqualByLine(
355 actual,
356 'Child\n'
357 '\n'
358 'Some users are smart and insert their own footers\n'
359 '\n'
360 'Cr-Original-Whatever: value\n'
361 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
362 'Cr-Commit-Position: refs/heads/master@{#13}')
363
364 def test_git_number_new_branch(self):
365 actual = self._test_git_number(
366 'Parent\n'
367 '\n'
368 'Cr-Commit-Position: refs/heads/master@{#12}',
369 dest_ref='refs/heads/branch',
370 child_msg='Child')
371 self.assertEqualByLine(
372 actual,
373 'Child\n'
374 '\n'
375 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
376 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
377
378 def test_git_number_lineage(self):
379 actual = self._test_git_number(
380 'Parent\n'
381 '\n'
382 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
383 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
384 dest_ref='refs/heads/branch',
385 child_msg='Child')
386 self.assertEqualByLine(
387 actual,
388 'Child\n'
389 '\n'
390 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
391 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
392
393 def test_git_number_moooooooore_lineage(self):
394 actual = self._test_git_number(
395 'Parent\n'
396 '\n'
397 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
398 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
399 dest_ref='refs/heads/mooore',
400 child_msg='Child')
401 self.assertEqualByLine(
402 actual,
403 'Child\n'
404 '\n'
405 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
406 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
407 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
408
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100409 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700410 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100411 actual = self._test_git_number(
412 'CQ commit on fresh new branch + numbering.\n'
413 '\n'
414 'NOTRY=True\n'
415 'NOPRESUBMIT=True\n'
416 'BUG=\n'
417 '\n'
418 'Review-Url: https://codereview.chromium.org/2577703003\n'
419 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
420 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
421 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
422 dest_ref='refs/heads/gnumb-test/cl',
423 child_msg='git cl on fresh new branch + numbering.\n'
424 '\n'
425 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
426 self.assertEqualByLine(
427 actual,
428 'git cl on fresh new branch + numbering.\n'
429 '\n'
430 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
431 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
432 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
433 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
434 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100435
436 def test_git_number_cherry_pick(self):
437 actual = self._test_git_number(
438 'Parent\n'
439 '\n'
440 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
441 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
442 dest_ref='refs/heads/branch',
443 child_msg='Child, which is cherry-pick from master\n'
444 '\n'
445 'Cr-Commit-Position: refs/heads/master@{#100}\n'
446 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
447 self.assertEqualByLine(
448 actual,
449 'Child, which is cherry-pick from master\n'
450 '\n'
451 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
452 '\n'
453 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
454 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
455 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
456
Edward Lemurda4b6c62020-02-13 00:28:40 +0000457 @mock.patch('gerrit_util.GetAccountDetails')
458 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000459 mock_per_account = {
460 'u1': None, # 404, doesn't exist.
461 'u2': {
462 '_account_id': 123124,
463 'avatars': [],
464 'email': 'u2@example.com',
465 'name': 'User Number 2',
466 'status': 'OOO',
467 },
468 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
469 }
470 def GetAccountDetailsMock(_, account):
471 # Poor-man's mock library's side_effect.
472 v = mock_per_account.pop(account)
473 if isinstance(v, Exception):
474 raise v
475 return v
476
Edward Lemurda4b6c62020-02-13 00:28:40 +0000477 mockGetAccountDetails.side_effect = GetAccountDetailsMock
478 actual = git_cl.gerrit_util.ValidAccounts(
479 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000480 self.assertEqual(actual, {
481 'u2': {
482 '_account_id': 123124,
483 'avatars': [],
484 'email': 'u2@example.com',
485 'name': 'User Number 2',
486 'status': 'OOO',
487 },
488 })
489
490
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200491class TestParseIssueURL(unittest.TestCase):
492 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000493 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200494 self.assertIsNotNone(parsed)
495 if fail:
496 self.assertFalse(parsed.valid)
497 return
498 self.assertTrue(parsed.valid)
499 self.assertEqual(parsed.issue, issue)
500 self.assertEqual(parsed.patchset, patchset)
501 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200502
Edward Lemur678a6842019-10-03 22:25:05 +0000503 def test_ParseIssueNumberArgument(self):
504 def test(arg, *args, **kwargs):
505 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200506
Edward Lemur678a6842019-10-03 22:25:05 +0000507 test('123', 123)
508 test('', fail=True)
509 test('abc', fail=True)
510 test('123/1', fail=True)
511 test('123a', fail=True)
512 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200513
Edward Lemur678a6842019-10-03 22:25:05 +0000514 test('https://codereview.source.com/123',
515 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200516 test('http://chrome-review.source.com/c/123',
517 123, None, 'chrome-review.source.com')
518 test('https://chrome-review.source.com/c/123/',
519 123, None, 'chrome-review.source.com')
520 test('https://chrome-review.source.com/c/123/4',
521 123, 4, 'chrome-review.source.com')
522 test('https://chrome-review.source.com/#/c/123/4',
523 123, 4, 'chrome-review.source.com')
524 test('https://chrome-review.source.com/c/123/4',
525 123, 4, 'chrome-review.source.com')
526 test('https://chrome-review.source.com/123',
527 123, None, 'chrome-review.source.com')
528 test('https://chrome-review.source.com/123/4',
529 123, 4, 'chrome-review.source.com')
530
Edward Lemur678a6842019-10-03 22:25:05 +0000531 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200532 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
533 test('https://chrome-review.source.com/c/abc/', fail=True)
534 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
535
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200536
537
Edward Lemurda4b6c62020-02-13 00:28:40 +0000538class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100539 def setUp(self):
540 super(GitCookiesCheckerTest, self).setUp()
541 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100542 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000543 mock.patch('sys.stdout', StringIO()).start()
544 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100545
546 def mock_hosts_creds(self, subhost_identity_pairs):
547 def ensure_googlesource(h):
548 if not h.endswith(self.c._GOOGLESOURCE):
549 assert not h.endswith('.')
550 return h + '.' + self.c._GOOGLESOURCE
551 return h
552 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
553 for h, i in subhost_identity_pairs]
554
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200555 def test_identity_parsing(self):
556 self.assertEqual(self.c._parse_identity('ldap.google.com'),
557 ('ldap', 'google.com'))
558 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
559 ('ldap', 'example.com'))
560 # Specical case because we know there are no subdomains in chromium.org.
561 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
562 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800563 # Pathological: ".period." can be either username OR domain, more likely
564 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200565 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
566 ('note', 'period.example.com'))
567
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100568 def test_analysis_nothing(self):
569 self.c._all_hosts = []
570 self.assertFalse(self.c.has_generic_host())
571 self.assertEqual(set(), self.c.get_conflicting_hosts())
572 self.assertEqual(set(), self.c.get_duplicated_hosts())
573 self.assertEqual(set(), self.c.get_partially_configured_hosts())
574 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
575
576 def test_analysis(self):
577 self.mock_hosts_creds([
578 ('.googlesource.com', 'git-example.chromium.org'),
579
580 ('chromium', 'git-example.google.com'),
581 ('chromium-review', 'git-example.google.com'),
582 ('chrome-internal', 'git-example.chromium.org'),
583 ('chrome-internal-review', 'git-example.chromium.org'),
584 ('conflict', 'git-example.google.com'),
585 ('conflict-review', 'git-example.chromium.org'),
586 ('dup', 'git-example.google.com'),
587 ('dup', 'git-example.google.com'),
588 ('dup-review', 'git-example.google.com'),
589 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200590 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100591 ])
592 self.assertTrue(self.c.has_generic_host())
593 self.assertEqual(set(['conflict.googlesource.com']),
594 self.c.get_conflicting_hosts())
595 self.assertEqual(set(['dup.googlesource.com']),
596 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200597 self.assertEqual(set(['partial.googlesource.com',
598 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100599 self.c.get_partially_configured_hosts())
600 self.assertEqual(set(['chromium.googlesource.com',
601 'chrome-internal.googlesource.com']),
602 self.c.get_hosts_with_wrong_identities())
603
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100604 def test_report_no_problems(self):
605 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100606 self.assertFalse(self.c.find_and_report_problems())
607 self.assertEqual(sys.stdout.getvalue(), '')
608
Edward Lemurda4b6c62020-02-13 00:28:40 +0000609 @mock.patch(
610 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
611 return_value='~/.gitcookies')
612 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100613 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100614 self.assertTrue(self.c.find_and_report_problems())
615 with open(os.path.join(os.path.dirname(__file__),
616 'git_cl_creds_check_report.txt')) as f:
617 expected = f.read()
618 def by_line(text):
619 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700620 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200621 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100622
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800623
Edward Lemurda4b6c62020-02-13 00:28:40 +0000624class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000625 def setUp(self):
626 super(TestGitCl, self).setUp()
627 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700628 self._calls_done = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000629 mock.patch('sys.stdout', StringIO()).start()
630 mock.patch(
631 'git_cl.time_time',
632 lambda: self._mocked_call('time.time')).start()
633 mock.patch(
634 'git_cl.metrics.collector.add_repeated',
635 lambda *a: self._mocked_call('add_repeated', *a)).start()
636 mock.patch('subprocess2.call', self._mocked_call).start()
637 mock.patch('subprocess2.check_call', self._mocked_call).start()
638 mock.patch('subprocess2.check_output', self._mocked_call).start()
639 mock.patch(
640 'subprocess2.communicate',
641 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
642 mock.patch(
643 'git_cl.gclient_utils.CheckCallAndFilter',
644 self._mocked_call).start()
645 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
646 mock.patch(
647 'git_common.get_or_create_merge_base',
648 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
649 mock.patch('git_cl.BranchExists', return_value=True).start()
650 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
651 mock.patch(
652 'git_cl.SaveDescriptionBackup',
653 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
654 mock.patch(
655 'git_cl.ask_for_data',
656 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
657 mock.patch(
658 'git_cl.write_json',
659 lambda *a: self._mocked_call('write_json', *a)).start()
660 mock.patch(
661 'git_cl.presubmit_support.DoPresubmitChecks', PresubmitMock).start()
662 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
663 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000664 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000665 mock.patch(
666 'git_cl.gerrit_util.GetChangeComments',
667 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
668 mock.patch(
669 'git_cl.gerrit_util.GetChangeRobotComments',
670 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
671 mock.patch(
672 'git_cl.gerrit_util.AddReviewers',
673 lambda *a: self._mocked_call('AddReviewers', *a)).start()
674 mock.patch(
675 'git_cl.gerrit_util.SetReview',
676 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
677 self._mocked_call(
678 'SetReview', h, i, msg, labels, notify, ready))).start()
679 mock.patch(
680 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
681 return_value=False).start()
682 mock.patch(
683 'git_cl.gerrit_util.GceAuthenticator.is_gce',
684 return_value=False).start()
685 mock.patch(
686 'git_cl.gerrit_util.ValidAccounts',
687 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000688 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000689 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000690 self.mockGit = GitMocks()
691 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
692 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
693 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000694 mock.patch(
695 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000696 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000697 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000698 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000699 mock.patch(
700 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000701 # It's important to reset settings to not have inter-tests interference.
702 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000703 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000704
705 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000706 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000707 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100708 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000709 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
710 if len(self.calls) > 5:
711 calls += ' ...\n'
712 self.fail(
713 '\n'
714 'There are un-consumed calls after this test has finished:\n' +
715 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000716 finally:
717 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000718
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000719 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000720 self.assertTrue(
721 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700722 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000723 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000724 expected_args, result = top
725
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000726 # Also logs otherwise it could get caught in a try/finally and be hard to
727 # diagnose.
728 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700729 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000730 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700731 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
732 for i, c in enumerate(self._calls_done[-N:]))
733 following_calls = '\n '.join(
734 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
735 for i, c in enumerate(self.calls[:N]))
736 extended_msg = (
737 'A few prior calls:\n %s\n\n'
738 'This (expected):\n @%d: %r\n'
739 'This (actual):\n @%d: %r\n\n'
740 'A few following expected calls:\n %s' %
741 (prior_calls, len(self._calls_done), expected_args,
742 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700743
tandrii99a72f22016-08-17 14:33:24 -0700744 self.fail('@%d\n'
745 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000746 ' Actual: %r\n'
747 '\n'
748 '%s' % (
749 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700750
751 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700752 if isinstance(result, Exception):
753 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000754 # stdout from git commands is supposed to be a bytestream. Convert it here
755 # instead of converting all test output in this file to bytes.
756 if args[0][0] == 'git' and not isinstance(result, bytes):
757 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000758 return result
759
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100760 def test_ask_for_explicit_yes_true(self):
761 self.calls = [
762 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
763 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
764 ]
765 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
766
tandrii48df5812016-10-17 03:55:37 -0700767 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000768 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700769 self.calls = [
770 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700771 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
772 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
773 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
774 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700775 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
776 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700777 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
778 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000779 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
780 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700781 ((['git', 'config', 'gerrit.host', 'true'],), ''),
782 ]
783 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
784
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000785 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100786 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200787 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000788 custom_cl_base=None, short_hostname='chromium',
789 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000790 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200791 if custom_cl_base:
792 ancestor_revision = custom_cl_base
793 else:
794 # Determine ancestor_revision to be merge base.
795 ancestor_revision = 'fake_ancestor_sha'
796 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000797 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
798 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200799 ]
800
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100801 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000802 gerrit_util.GetChangeDetail.return_value = {
803 'owner': {'email': (other_cl_owner or 'owner@example.com')},
804 'change_id': (change_id or '123456789'),
805 'current_revision': 'sha1_of_current_revision',
806 'revisions': {'sha1_of_current_revision': {
807 'commit': {'message': fetched_description},
808 }},
809 'status': fetched_status or 'NEW',
810 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100811 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100812 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100813 if other_cl_owner:
814 calls += [
815 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
816 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100817
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100818 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200819 ((['git', 'rev-parse', 'HEAD'],), '12345'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100820 ]
821
822 if not issue:
823 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200824 ((['git', 'log', '--pretty=format:%s%n%n%b',
825 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000826 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100827 ]
828
829 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200830 ((['git', 'config', 'user.email'],), 'me@example.com'),
Edward Lemur2c48f242019-06-04 16:14:09 +0000831 (('time.time',), 1000,),
832 (('time.time',), 3000,),
833 (('add_repeated', 'sub_commands', {
834 'execution_time': 2000,
835 'command': 'presubmit',
836 'exit_code': 0
837 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200838 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
839 ([custom_cl_base] if custom_cl_base else
840 [ancestor_revision, 'HEAD']),),
841 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100842 ]
843 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000844
Edward Lemur26964072020-02-19 19:18:51 +0000845 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700846 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000847 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700848 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100849 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000850 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000851 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000852 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000853 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000854 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000855 if post_amend_description is None:
856 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700857 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200858 # Determined in `_gerrit_base_calls`.
859 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
860
861 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000862
Edward Lemur26964072020-02-19 19:18:51 +0000863 if squash_mode in ('override_squash', 'override_nosquash'):
864 self.mockGit.config['gerrit.override-squash-uploads'] = (
865 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700866
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000867 # If issue is given, then description is fetched from Gerrit instead.
868 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000869 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200870 ((['git', 'log', '--pretty=format:%s\n\n%b',
871 ((custom_cl_base + '..') if custom_cl_base else
872 'fake_ancestor_sha..HEAD')],),
873 description),
874 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800875 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000876 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800877 else:
878 if not title:
879 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200880 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
881 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800882 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000883 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000884 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000885 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200886 (('DownloadGerritHook', False), ''),
887 # Amending of commit message to get the Change-Id.
888 ((['git', 'log', '--pretty=format:%s\n\n%b',
889 determined_ancestor_revision + '..HEAD'],),
890 description),
891 ((['git', 'commit', '--amend', '-m', description],), ''),
892 ((['git', 'log', '--pretty=format:%s\n\n%b',
893 determined_ancestor_revision + '..HEAD'],),
894 post_amend_description)
895 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000896 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000897 if force or not issue:
Anthony Polito8b955342019-09-24 19:01:36 +0000898 if not force:
899 calls += [
Anthony Polito8b955342019-09-24 19:01:36 +0000900 ((['RunEditor'],), description),
901 ]
Josipe827b0f2020-01-30 00:07:20 +0000902 # user wants to edit description
903 if edit_description:
904 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000905 ((['RunEditor'],), edit_description),
906 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000907 ref_to_push = 'abcdef0123456789'
908 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200909 ]
910
911 if custom_cl_base is None:
912 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000913 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000914 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200915 ]
916 parent = 'origin/master'
917 else:
918 calls += [
919 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
920 'refs/remotes/origin/master'],),
921 callError(1)), # Means not ancenstor.
922 (('ask_for_data',
923 'Do you take responsibility for cleaning up potential mess '
924 'resulting from proceeding with upload? Press Enter to upload, '
925 'or Ctrl+C to abort'), ''),
926 ]
927 parent = custom_cl_base
928
929 calls += [
930 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
931 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000932 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200933 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000934 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200935 ref_to_push),
936 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000937 else:
938 ref_to_push = 'HEAD'
939
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000940 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000941 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200942 ((['git', 'rev-list',
943 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
944 ref_to_push],),
945 '1hashPerLine\n'),
946 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000947
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000948 metrics_arguments = []
949
Aaron Gableafd52772017-06-27 16:40:10 -0700950 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700951 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000952 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700953 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400954 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700955 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000956 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700957 else:
958 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000959 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800960
Aaron Gable70f4e242017-06-26 10:45:59 -0700961 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700962 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000963 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000964
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000965 if short_hostname == 'chromium':
966 # All reviwers and ccs get into ref_suffix.
967 for r in sorted(reviewers):
968 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000969 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000970 if issue is None:
971 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
972 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000973 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000974 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000975 reviewers, cc = [], []
976 else:
977 # TODO(crbug/877717): remove this case.
978 calls += [
979 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
980 sorted(reviewers) + ['joe@example.com',
981 'chromium-reviews+test-more-cc@chromium.org'] + cc),
982 {
983 e: {'email': e}
984 for e in (reviewers + ['joe@example.com'] + cc)
985 })
986 ]
987 for r in sorted(reviewers):
988 if r != 'bad-account-or-email':
989 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000990 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000991 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000992 if issue is None:
993 cc += ['joe@example.com']
994 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000995 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000996 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000997 if c in cc:
998 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000999
Edward Lemur687ca902018-12-05 02:30:30 +00001000 for k, v in sorted((labels or {}).items()):
1001 ref_suffix += ',l=%s+%d' % (k, v)
1002 metrics_arguments.append('l=%s+%d' % (k, v))
1003
1004 if tbr:
1005 calls += [
1006 (('GetCodeReviewTbrScore',
1007 '%s-review.googlesource.com' % short_hostname,
1008 'my/repo'),
1009 2,),
1010 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001011
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001012 calls += [
1013 (('time.time',), 1000,),
1014 ((['git', 'push',
1015 'https://%s.googlesource.com/my/repo' % short_hostname,
1016 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1017 (('remote:\n'
1018 'remote: Processing changes: (\)\n'
1019 'remote: Processing changes: (|)\n'
1020 'remote: Processing changes: (/)\n'
1021 'remote: Processing changes: (-)\n'
1022 'remote: Processing changes: new: 1 (/)\n'
1023 'remote: Processing changes: new: 1, done\n'
1024 'remote:\n'
1025 'remote: New Changes:\n'
1026 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1027 ' XXX\n'
1028 'remote:\n'
1029 'To https://%s.googlesource.com/my/repo\n'
1030 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1031 ) % (short_hostname, short_hostname)),),
1032 (('time.time',), 2000,),
1033 (('add_repeated',
1034 'sub_commands',
1035 {
1036 'execution_time': 1000,
1037 'command': 'git push',
1038 'exit_code': 0,
1039 'arguments': sorted(metrics_arguments),
1040 }),
1041 None,),
1042 ]
1043
Edward Lemur1b52d872019-05-09 21:12:12 +00001044 final_description = final_description or post_amend_description.strip()
1045 original_title = original_title or title or '<untitled>'
1046 # Trace-related calls
1047 calls += [
1048 # Write a description with context for the current trace.
1049 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001050 'Thu Mar 16 20:00:41 2017\n'
1051 '%(short_hostname)s-review.googlesource.com\n'
1052 '%(change_id)s\n'
1053 '%(title)s\n'
1054 '%(description)s\n'
1055 '1000\n'
1056 '0\n'
1057 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001058 'short_hostname': short_hostname,
1059 'change_id': change_id,
1060 'description': final_description,
1061 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001062 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001063 }],),
1064 None,
1065 ),
1066 # Read traces and shorten git hashes.
1067 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1068 True,
1069 ),
1070 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1071 ('git-hash: 0123456789012345678901234567890123456789\n'
1072 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1073 ),
1074 ((['FileWrite', 'TEMP_DIR/trace-packet',
1075 'git-hash: 012345\n'
1076 'git-hash: abcdea\n'],),
1077 None,
1078 ),
1079 # Make zip file for the git traces.
1080 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1081 'TEMP_DIR'],),
1082 None,
1083 ),
1084 # Collect git config and gitcookies.
1085 ((['git', 'config', '-l'],),
1086 'git-config-output',
1087 ),
1088 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1089 None,
1090 ),
1091 ((['os.path.isfile', '~/.gitcookies'],),
1092 gitcookies_exists,
1093 ),
1094 ]
1095 if gitcookies_exists:
1096 calls += [
1097 ((['FileRead', '~/.gitcookies'],),
1098 'gitcookies 1/SECRET',
1099 ),
1100 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1101 None,
1102 ),
1103 ]
1104 calls += [
1105 # Make zip file for the git config and gitcookies.
1106 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1107 'TEMP_DIR'],),
1108 None,
1109 ),
1110 ]
1111
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001112 # TODO(crbug/877717): this should never be used.
1113 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001114 calls += [
1115 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001116 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001117 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001118 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1119 notify),
1120 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001121 ]
Edward Lemur26964072020-02-19 19:18:51 +00001122 calls += [
1123 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1124 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001125 return calls
1126
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001127 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001128 self,
1129 upload_args,
1130 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001131 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001132 squash=True,
1133 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001134 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001135 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001136 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001137 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001138 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001139 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001140 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001141 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001142 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001143 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001144 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001145 labels=None,
1146 change_id=None,
1147 original_title=None,
1148 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001149 gitcookies_exists=True,
1150 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001151 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001152 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001153 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001154 if squash_mode is None:
1155 if '--no-squash' in upload_args:
1156 squash_mode = 'nosquash'
1157 elif '--squash' in upload_args:
1158 squash_mode = 'squash'
1159 else:
1160 squash_mode = 'default'
1161
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001162 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001163 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001164 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001165 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001166 same_auth=('git-owner.example.com', '', 'pass'))).start()
1167 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1168 lambda _, offer_removal: None).start()
1169 mock.patch('git_cl.gclient_utils.RunEditor',
1170 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1171 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1172 'DownloadGerritHook', force)).start()
1173 mock.patch('git_cl.gclient_utils.FileRead',
1174 lambda path: self._mocked_call(['FileRead', path])).start()
1175 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001176 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001177 ['FileWrite', path, contents])).start()
1178 mock.patch('git_cl.datetime_now',
1179 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1180 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1181 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1182 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001183 '%(now)s\n'
1184 '%(gerrit_host)s\n'
1185 '%(change_id)s\n'
1186 '%(title)s\n'
1187 '%(description)s\n'
1188 '%(execution_time)s\n'
1189 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001190 '%(trace_name)s').start()
1191 mock.patch('git_cl.shutil.make_archive',
1192 lambda *args: self._mocked_call(['make_archive'] +
1193 list(args))).start()
1194 mock.patch('os.path.isfile',
1195 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001196 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
tandriia60502f2016-06-20 02:01:53 -07001197
Edward Lemur26964072020-02-19 19:18:51 +00001198 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001199 self.mockGit.config['branch.master.gerritissue'] = (
1200 str(issue) if issue else None)
1201 self.mockGit.config['remote.origin.url'] = (
1202 'https://%s.googlesource.com/my/repo' % short_hostname)
1203
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001204 self.calls = self._gerrit_base_calls(
1205 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001206 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001207 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001208 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001209 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001210 short_hostname=short_hostname,
1211 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001212 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001213 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001214 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001215 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001216 self.calls += self._gerrit_upload_calls(
1217 description, reviewers, squash,
1218 squash_mode=squash_mode,
1219 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001220 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001221 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001222 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001223 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001224 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001225 labels=labels,
1226 change_id=change_id,
1227 original_title=original_title,
1228 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001229 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001230 force=force,
1231 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001232 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001233 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001234 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001235 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001236 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001237 self.assertEqual(
1238 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001239 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001240
Edward Lemur1b52d872019-05-09 21:12:12 +00001241 def test_gerrit_upload_traces_no_gitcookies(self):
1242 self._run_gerrit_upload_test(
1243 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001244 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001245 [],
1246 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001247 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001248 change_id='Ixxx',
1249 gitcookies_exists=False)
1250
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001251 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001252 self._run_gerrit_upload_test(
1253 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001254 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001255 [],
1256 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001257 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001258 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001259
1260 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001261 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001262 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001263 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001264 [],
tandriia60502f2016-06-20 02:01:53 -07001265 squash=False,
1266 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001267 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001268 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001269
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001270 def test_gerrit_no_reviewer(self):
1271 self._run_gerrit_upload_test(
1272 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001273 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001274 [],
1275 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001276 squash_mode='override_nosquash',
1277 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001278
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001279 def test_gerrit_no_reviewer_non_chromium_host(self):
1280 # TODO(crbug/877717): remove this test case.
1281 self._run_gerrit_upload_test(
1282 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001283 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001284 [],
1285 squash=False,
1286 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001287 short_hostname='other',
1288 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001289
Nick Carter8692b182017-11-06 16:30:38 -08001290 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001291 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001292 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001293 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001294 squash=False,
1295 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001296 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1297 change_id='I123456789',
1298 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001299
ukai@chromium.orge8077812012-02-03 03:41:46 +00001300 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001301 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001302 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001303 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001304 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001305 squash=False,
1306 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001307 notify=True,
1308 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001309 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001310 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001311
Anthony Polito8b955342019-09-24 19:01:36 +00001312 def test_gerrit_upload_force_sets_bug(self):
1313 self._run_gerrit_upload_test(
1314 ['-b', '10000', '-f'],
1315 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1316 [],
1317 force=True,
1318 expected_upstream_ref='origin/master',
1319 fetched_description='desc=\n\nChange-Id: Ixxx',
1320 original_title='Initial upload',
1321 change_id='Ixxx')
1322
1323 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1324 self._run_gerrit_upload_test(
1325 ['-b', '10000', '-f', '-m', 'Title'],
1326 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1327 [],
1328 force=True,
1329 issue='123456',
1330 expected_upstream_ref='origin/master',
1331 fetched_description='desc=\n\nChange-Id: Ixxxx',
1332 original_title='Title',
1333 title='Title',
1334 change_id='Izzzz')
1335
Dan Beamd8b04ca2019-10-10 21:23:26 +00001336 def test_gerrit_upload_force_sets_fixed(self):
1337 self._run_gerrit_upload_test(
1338 ['-x', '10000', '-f'],
1339 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1340 [],
1341 force=True,
1342 expected_upstream_ref='origin/master',
1343 fetched_description='desc=\n\nChange-Id: Ixxx',
1344 original_title='Initial upload',
1345 change_id='Ixxx')
1346
ukai@chromium.orge8077812012-02-03 03:41:46 +00001347 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001348 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1349 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001350 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001351 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001352 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001353 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001354 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001355 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001356 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001357 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001358 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001359 labels={'Code-Review': 2},
1360 change_id='123456789',
1361 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001362
1363 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001364 self._run_gerrit_upload_test(
1365 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001366 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001367 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001368 expected_upstream_ref='origin/master',
1369 change_id='123456789',
1370 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001371
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001372 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001373 self._run_gerrit_upload_test(
1374 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001375 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001376 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001377 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001378 expected_upstream_ref='origin/master',
1379 change_id='123456789',
1380 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001381
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001382 def test_gerrit_upload_squash_first_with_labels(self):
1383 self._run_gerrit_upload_test(
1384 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001385 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001386 [],
1387 squash=True,
1388 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001389 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1390 change_id='123456789',
1391 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001392
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001393 def test_gerrit_upload_squash_first_against_rev(self):
1394 custom_cl_base = 'custom_cl_base_rev_or_branch'
1395 self._run_gerrit_upload_test(
1396 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001397 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001398 [],
1399 squash=True,
1400 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001401 custom_cl_base=custom_cl_base,
1402 change_id='123456789',
1403 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001404 self.assertIn(
1405 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1406 sys.stdout.getvalue())
1407
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001408 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001409 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001410 self._run_gerrit_upload_test(
1411 ['--squash'],
1412 description,
1413 [],
1414 squash=True,
1415 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001416 issue=123456,
1417 change_id='123456789',
1418 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001419
Edward Lemurd55c5072020-02-20 01:09:07 +00001420 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001421 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001422 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001423 with self.assertRaises(SystemExitMock):
1424 self._run_gerrit_upload_test(
1425 ['--squash'],
1426 description,
1427 [],
1428 squash=True,
1429 expected_upstream_ref='origin/master',
1430 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001431 fetched_status='ABANDONED',
1432 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001433 self.assertEqual(
1434 'Change https://chromium-review.googlesource.com/123456 has been '
1435 'abandoned, new uploads are not allowed\n',
1436 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001437
Edward Lemurda4b6c62020-02-13 00:28:40 +00001438 @mock.patch(
1439 'gerrit_util.GetAccountDetails',
1440 return_value={'email': 'yet-another@example.com'})
1441 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001442 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001443 self._run_gerrit_upload_test(
1444 ['--squash'],
1445 description,
1446 [],
1447 squash=True,
1448 expected_upstream_ref='origin/master',
1449 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001450 other_cl_owner='other@example.com',
1451 change_id='123456789',
1452 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001453 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001454 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001455 'authenticate to Gerrit as yet-another@example.com.\n'
1456 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001457 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001458
Josipe827b0f2020-01-30 00:07:20 +00001459 def test_upload_change_description_editor(self):
1460 fetched_description = 'foo\n\nChange-Id: 123456789'
1461 description = 'bar\n\nChange-Id: 123456789'
1462 self._run_gerrit_upload_test(
1463 ['--squash', '--edit-description'],
1464 description,
1465 [],
1466 fetched_description=fetched_description,
1467 squash=True,
1468 expected_upstream_ref='origin/master',
1469 issue=123456,
1470 change_id='123456789',
1471 original_title='User input',
1472 edit_description=description)
1473
Edward Lemurda4b6c62020-02-13 00:28:40 +00001474 @mock.patch('git_cl.RunGit')
1475 @mock.patch('git_cl.CMDupload')
1476 @mock.patch('git_cl.ask_for_data')
1477 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001478 def mock_run_git(*args, **_kwargs):
1479 if args[0] == ['for-each-ref',
1480 '--format=%(refname:short) %(upstream:short)',
1481 'refs/heads']:
1482 # Create a local branch dependency tree that looks like this:
1483 # test1 -> test2 -> test3 -> test4 -> test5
1484 # -> test3.1
1485 # test6 -> test0
1486 branch_deps = [
1487 'test2 test1', # test1 -> test2
1488 'test3 test2', # test2 -> test3
1489 'test3.1 test2', # test2 -> test3.1
1490 'test4 test3', # test3 -> test4
1491 'test5 test4', # test4 -> test5
1492 'test6 test0', # test0 -> test6
1493 'test7', # test7
1494 ]
1495 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001496 git_cl.RunGit.side_effect = mock_run_git
1497 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001498
1499 class MockChangelist():
1500 def __init__(self):
1501 pass
1502 def GetBranch(self):
1503 return 'test1'
1504 def GetIssue(self):
1505 return '123'
1506 def GetPatchset(self):
1507 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001508 def IsGerrit(self):
1509 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001510
1511 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1512 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001513 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
1514 git_cl.ask_for_data.assert_called_once_with(
1515 'This command will checkout all dependent branches '
1516 'and run "git cl upload". Press Enter to continue, '
1517 'or Ctrl+C to abort')
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001518 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001519
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001520 def test_gerrit_change_id(self):
1521 self.calls = [
1522 ((['git', 'write-tree'], ),
1523 'hashtree'),
1524 ((['git', 'rev-parse', 'HEAD~0'], ),
1525 'branch-parent'),
1526 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1527 'A B <a@b.org> 1456848326 +0100'),
1528 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1529 'C D <c@d.org> 1456858326 +0100'),
1530 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1531 'hashchange'),
1532 ]
1533 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1534 self.assertEqual(change_id, 'Ihashchange')
1535
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001536 def test_desecription_append_footer(self):
1537 for init_desc, footer_line, expected_desc in [
1538 # Use unique desc first lines for easy test failure identification.
1539 ('foo', 'R=one', 'foo\n\nR=one'),
1540 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1541 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1542 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1543 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1544 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1545 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1546 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1547 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1548 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1549 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1550 ]:
1551 desc = git_cl.ChangeDescription(init_desc)
1552 desc.append_footer(footer_line)
1553 self.assertEqual(desc.description, expected_desc)
1554
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001555 def test_update_reviewers(self):
1556 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001557 ('foo', [], [],
1558 'foo'),
1559 ('foo\nR=xx', [], [],
1560 'foo\nR=xx'),
1561 ('foo\nTBR=xx', [], [],
1562 'foo\nTBR=xx'),
1563 ('foo', ['a@c'], [],
1564 'foo\n\nR=a@c'),
1565 ('foo\nR=xx', ['a@c'], [],
1566 'foo\n\nR=a@c, xx'),
1567 ('foo\nTBR=xx', ['a@c'], [],
1568 'foo\n\nR=a@c\nTBR=xx'),
1569 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1570 'foo\n\nR=a@c, yy\nTBR=xx'),
1571 ('foo\nBUG=', ['a@c'], [],
1572 'foo\nBUG=\nR=a@c'),
1573 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1574 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1575 ('foo', ['a@c', 'b@c'], [],
1576 'foo\n\nR=a@c, b@c'),
1577 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1578 'foo\nBar\n\nR=c@c\nBUG='),
1579 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1580 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001581 # Same as the line before, but full of whitespaces.
1582 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001583 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001584 'foo\nBar\n\nR=c@c\n BUG =',
1585 ),
1586 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001587 ('foo BUG=allo R=joe ', ['c@c'], [],
1588 'foo BUG=allo R=joe\n\nR=c@c'),
1589 # Redundant TBRs get promoted to Rs
1590 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1591 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001592 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001593 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001594 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001595 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001596 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001597 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001598 actual.append(obj.description)
1599 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001600
Nodir Turakulov23b82142017-11-16 11:04:25 -08001601 def test_get_hash_tags(self):
1602 cases = [
1603 ('', []),
1604 ('a', []),
1605 ('[a]', ['a']),
1606 ('[aa]', ['aa']),
1607 ('[a ]', ['a']),
1608 ('[a- ]', ['a']),
1609 ('[a- b]', ['a-b']),
1610 ('[a--b]', ['a-b']),
1611 ('[a', []),
1612 ('[a]x', ['a']),
1613 ('[aa]x', ['aa']),
1614 ('[a b]', ['a-b']),
1615 ('[a b]', ['a-b']),
1616 ('[a__b]', ['a-b']),
1617 ('[a] x', ['a']),
1618 ('[a][b]', ['a', 'b']),
1619 ('[a] [b]', ['a', 'b']),
1620 ('[a][b]x', ['a', 'b']),
1621 ('[a][b] x', ['a', 'b']),
1622 ('[a]\n[b]', ['a']),
1623 ('[a\nb]', []),
1624 ('[a][', ['a']),
1625 ('Revert "[a] feature"', ['a']),
1626 ('Reland "[a] feature"', ['a']),
1627 ('Revert: [a] feature', ['a']),
1628 ('Reland: [a] feature', ['a']),
1629 ('Revert "Reland: [a] feature"', ['a']),
1630 ('Foo: feature', ['foo']),
1631 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001632 ('Change Foo::Bar', []),
1633 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001634 ('Revert "Foo bar: feature"', ['foo-bar']),
1635 ('Reland "Foo bar: feature"', ['foo-bar']),
1636 ]
1637 for desc, expected in cases:
1638 change_desc = git_cl.ChangeDescription(desc)
1639 actual = change_desc.get_hash_tags()
1640 self.assertEqual(
1641 actual,
1642 expected,
1643 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1644
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001645 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001646 self.assertEqual(None, git_cl.GetTargetRef(None,
1647 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001648 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001649
wittman@chromium.org455dc922015-01-26 20:15:50 +00001650 # Check default target refs for branches.
1651 self.assertEqual('refs/heads/master',
1652 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001653 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001654 self.assertEqual('refs/heads/master',
1655 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001656 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001657 self.assertEqual('refs/heads/master',
1658 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001659 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001660 self.assertEqual('refs/branch-heads/123',
1661 git_cl.GetTargetRef('origin',
1662 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001663 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001664 self.assertEqual('refs/diff/test',
1665 git_cl.GetTargetRef('origin',
1666 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001667 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001668 self.assertEqual('refs/heads/chrome/m42',
1669 git_cl.GetTargetRef('origin',
1670 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001671 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001672
1673 # Check target refs for user-specified target branch.
1674 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1675 'refs/remotes/branch-heads/123'):
1676 self.assertEqual('refs/branch-heads/123',
1677 git_cl.GetTargetRef('origin',
1678 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001679 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001680 for branch in ('origin/master', 'remotes/origin/master',
1681 'refs/remotes/origin/master'):
1682 self.assertEqual('refs/heads/master',
1683 git_cl.GetTargetRef('origin',
1684 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001685 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001686 for branch in ('master', 'heads/master', 'refs/heads/master'):
1687 self.assertEqual('refs/heads/master',
1688 git_cl.GetTargetRef('origin',
1689 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001690 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001691
Edward Lemurda4b6c62020-02-13 00:28:40 +00001692 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1693 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001694 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001695 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1696
Edward Lemur85153282020-02-14 22:06:29 +00001697 def assertIssueAndPatchset(
1698 self, branch='master', issue='123456', patchset='7',
1699 git_short_host='chromium'):
1700 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001701 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001702 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001703 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001704 self.assertEqual(
1705 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001706 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001707
Edward Lemur85153282020-02-14 22:06:29 +00001708 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001709 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001710 self.mockGit.config['remote.origin.url'] = (
1711 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001712 gerrit_util.GetChangeDetail.return_value = {
1713 'current_revision': '7777777777',
1714 'revisions': {
1715 '1111111111': {
1716 '_number': 1,
1717 'fetch': {'http': {
1718 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1719 'ref': 'refs/changes/56/123456/1',
1720 }},
1721 },
1722 '7777777777': {
1723 '_number': 7,
1724 'fetch': {'http': {
1725 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1726 'ref': 'refs/changes/56/123456/7',
1727 }},
1728 },
1729 },
1730 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001731
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001732 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001733 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001734 self.calls += [
1735 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1736 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001737 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001738 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001739 ]
1740 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001741 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001742
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001743 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001744 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001745 self.calls += [
1746 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1747 'refs/changes/56/123456/7'],), ''),
1748 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001749 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001750 ]
Edward Lemur85153282020-02-14 22:06:29 +00001751 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1752 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001753
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001754 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001755 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001756 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001757 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001758 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001759 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001760 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001761 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001762 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001763 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001764
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001765 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001766 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001767 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001768 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001769 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001770 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001771 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001772 ]
1773 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001774 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001775 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001776
Aaron Gable697a91b2018-01-19 15:20:15 -08001777 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001778 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001779 self.calls += [
1780 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1781 'refs/changes/56/123456/1'],), ''),
1782 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001783 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001784 ]
1785 self.assertEqual(git_cl.main(
1786 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1787 0)
Edward Lemur85153282020-02-14 22:06:29 +00001788 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001789
Edward Lemurd55c5072020-02-20 01:09:07 +00001790 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001791 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001792 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001793 self.calls += [
1794 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001795 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001796 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001797 ]
1798 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001799 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001800 self.assertEqual(
1801 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1802 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001803
Edward Lemurda4b6c62020-02-13 00:28:40 +00001804 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001805 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001806 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001807 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001808 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001809 self.mockGit.config['remote.origin.url'] = (
1810 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001811 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001812 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001813 self.assertEqual(
1814 'change 123456 at https://chromium-review.googlesource.com does not '
1815 'exist or you have no access to it\n',
1816 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001817
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001818 def _checkout_calls(self):
1819 return [
1820 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001821 'branch\\..*\\.gerritissue'], ),
1822 ('branch.ger-branch.gerritissue 123456\n'
1823 'branch.gbranch654.gerritissue 654321\n')),
1824 ]
1825
1826 def test_checkout_gerrit(self):
1827 """Tests git cl checkout <issue>."""
1828 self.calls = self._checkout_calls()
1829 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1830 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1831
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001832 def test_checkout_not_found(self):
1833 """Tests git cl checkout <issue>."""
1834 self.calls = self._checkout_calls()
1835 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1836
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001837 def test_checkout_no_branch_issues(self):
1838 """Tests git cl checkout <issue>."""
1839 self.calls = [
1840 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001841 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001842 ]
1843 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1844
Edward Lemur26964072020-02-19 19:18:51 +00001845 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001846 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1847 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001848 self.mockGit.config['remote.origin.url'] = (
1849 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001850 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001851 cl.branch = 'master'
1852 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001853 return cl
1854
Edward Lemurd55c5072020-02-20 01:09:07 +00001855 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001856 def test_gerrit_ensure_authenticated_missing(self):
1857 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001858 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001859 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001860 with self.assertRaises(SystemExitMock):
1861 cl.EnsureAuthenticated(force=False)
1862 self.assertEqual(
1863 'Credentials for the following hosts are required:\n'
1864 ' chromium-review.googlesource.com\n'
1865 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1866 'You can (re)generate your credentials by visiting '
1867 'https://chromium-review.googlesource.com/new-password\n',
1868 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001869
1870 def test_gerrit_ensure_authenticated_conflict(self):
1871 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001872 'chromium.googlesource.com':
1873 ('git-one.example.com', None, 'secret1'),
1874 'chromium-review.googlesource.com':
1875 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001876 })
1877 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001878 (('ask_for_data', 'If you know what you are doing '
1879 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001880 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1881
1882 def test_gerrit_ensure_authenticated_ok(self):
1883 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001884 'chromium.googlesource.com':
1885 ('git-same.example.com', None, 'secret'),
1886 'chromium-review.googlesource.com':
1887 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001888 })
1889 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1890
tandrii@chromium.org28253532016-04-14 13:46:56 +00001891 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001892 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1893 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001894 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1895
Eric Boren2fb63102018-10-05 13:05:03 +00001896 def test_gerrit_ensure_authenticated_bearer_token(self):
1897 cl = self._test_gerrit_ensure_authenticated_common(auth={
1898 'chromium.googlesource.com':
1899 ('', None, 'secret'),
1900 'chromium-review.googlesource.com':
1901 ('', None, 'secret'),
1902 })
1903 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1904 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1905 'chromium.googlesource.com')
1906 self.assertTrue('Bearer' in header)
1907
Daniel Chengcf6269b2019-05-18 01:02:12 +00001908 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001909 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001910 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001911 (('logging.warning',
1912 'Ignoring branch %(branch)s with non-https remote '
1913 '%(remote)s', {
1914 'branch': 'master',
1915 'remote': 'custom-scheme://repo'}
1916 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001917 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001918 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1919 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1920 mock.patch('logging.warning',
1921 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001922 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001923 cl.branch = 'master'
1924 cl.branchref = 'refs/heads/master'
1925 cl.lookedup_issue = True
1926 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1927
Florian Mayerae510e82020-01-30 21:04:48 +00001928 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001929 self.mockGit.config['remote.origin.url'] = (
1930 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001931 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001932 (('logging.error',
1933 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1934 'but it doesn\'t exist.', {
1935 'remote': 'origin',
1936 'branch': 'master',
1937 'url': 'git@somehost.example:foo/bar.git'}
1938 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001939 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001940 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1941 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1942 mock.patch('logging.error',
1943 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001944 cl = git_cl.Changelist()
1945 cl.branch = 'master'
1946 cl.branchref = 'refs/heads/master'
1947 cl.lookedup_issue = True
1948 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1949
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001950 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001951 self.mockGit.config['branch.master.gerritissue'] = '123'
1952 self.mockGit.config['branch.master.gerritserver'] = (
1953 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001954 self.mockGit.config['remote.origin.url'] = (
1955 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001956 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001957 (('SetReview', 'chromium-review.googlesource.com',
1958 'infra%2Finfra~123', None,
1959 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001960 ]
tandriid9e5ce52016-07-13 02:32:59 -07001961
1962 def test_cmd_set_commit_gerrit_clear(self):
1963 self._cmd_set_commit_gerrit_common(0)
1964 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1965
1966 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001967 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001968 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1969
tandriid9e5ce52016-07-13 02:32:59 -07001970 def test_cmd_set_commit_gerrit(self):
1971 self._cmd_set_commit_gerrit_common(2)
1972 self.assertEqual(0, git_cl.main(['set-commit']))
1973
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001974 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001975 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001976 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001977
1978 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001979 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001980
Edward Lemurda4b6c62020-02-13 00:28:40 +00001981 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001982 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001983 try:
1984 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001985 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001986 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001987 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001988
1989 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001990 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001991 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001992 return 'foobar'
1993
Edward Lemurda4b6c62020-02-13 00:28:40 +00001994 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001995 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001996 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001997 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001998 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001999
iannuccie53c9352016-08-17 14:40:40 -07002000 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002001
iannuccie53c9352016-08-17 14:40:40 -07002002 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002003 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002004 return 'foobar'
2005
Edward Lemurda4b6c62020-02-13 00:28:40 +00002006 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2007 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002008 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002009 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002010
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002011 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002012 self.mockGit.config['remote.origin.url'] = (
2013 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002014 gerrit_util.GetChangeDetail.return_value = {
2015 'current_revision': 'sha1',
2016 'revisions': {'sha1': {
2017 'commit': {'message': 'foobar'},
2018 }},
2019 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002020 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002021 'description',
2022 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2023 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002024 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002025
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002026 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002027 mock.patch('git_cl.Changelist', ChangelistMock).start()
2028 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002029
2030 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2031 self.assertEqual('hihi', ChangelistMock.desc)
2032
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002033 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002034 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002035
2036 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002037 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002038 '# Enter a description of the change.\n'
2039 '# This will be displayed on the codereview site.\n'
2040 '# The first line will also be used as the subject of the review.\n'
2041 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002042 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002043 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002044 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002045 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002046 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002047
Edward Lemur6c6827c2020-02-06 21:15:18 +00002048 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002049 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002050
Edward Lemurda4b6c62020-02-13 00:28:40 +00002051 mock.patch('git_cl.Changelist.FetchDescription',
2052 lambda *args: current_desc).start()
2053 mock.patch('git_cl.Changelist.UpdateDescription',
2054 UpdateDescription).start()
2055 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002056
Edward Lemur85153282020-02-14 22:06:29 +00002057 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002058 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002059
Dan Beamd8b04ca2019-10-10 21:23:26 +00002060 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2061 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2062
2063 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002064 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002065 '# Enter a description of the change.\n'
2066 '# This will be displayed on the codereview site.\n'
2067 '# The first line will also be used as the subject of the review.\n'
2068 '#--------------------This line is 72 characters long'
2069 '--------------------\n'
2070 'Some.\n\nFixed: 123\nChange-Id: xxx',
2071 desc)
2072 return desc
2073
Edward Lemurda4b6c62020-02-13 00:28:40 +00002074 mock.patch('git_cl.Changelist.FetchDescription',
2075 lambda *args: current_desc).start()
2076 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002077
Edward Lemur85153282020-02-14 22:06:29 +00002078 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002079 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002080
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002081 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002082 mock.patch('git_cl.Changelist', ChangelistMock).start()
2083 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002084
2085 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2086 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2087
kmarshall3bff56b2016-06-06 18:31:47 -07002088 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002089 self.calls = [
2090 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002091 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002092 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002093 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002094 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002095 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002096
Edward Lemurda4b6c62020-02-13 00:28:40 +00002097 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002098 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002099 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2100 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002101 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002102
2103 self.assertEqual(0, git_cl.main(['archive', '-f']))
2104
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002105 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002106 self.calls = [
2107 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2108 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2109 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2110 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002111 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2112 ((['git', 'branch', '-D', 'foo'],), '')
2113 ]
2114
Edward Lemurda4b6c62020-02-13 00:28:40 +00002115 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002116 lambda branches, fine_grained, max_processes:
2117 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2118 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002119 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002120
2121 self.assertEqual(0, git_cl.main(['archive', '-f']))
2122
kmarshall3bff56b2016-06-06 18:31:47 -07002123 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002124 self.calls = [
2125 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2126 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002127 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002128 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002129
Edward Lemurda4b6c62020-02-13 00:28:40 +00002130 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002131 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002132 [(MockChangelistWithBranchAndIssue('master', 1),
2133 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002134
2135 self.assertEqual(1, git_cl.main(['archive', '-f']))
2136
2137 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002138 self.calls = [
2139 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2140 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002141 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002142 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002143
Edward Lemurda4b6c62020-02-13 00:28:40 +00002144 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002145 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002146 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2147 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002148 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002149
kmarshall9249e012016-08-23 12:02:16 -07002150 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2151
2152 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002153 self.calls = [
2154 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2155 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002156 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002157 ((['git', 'branch', '-D', 'foo'],), '')
2158 ]
kmarshall9249e012016-08-23 12:02:16 -07002159
Edward Lemurda4b6c62020-02-13 00:28:40 +00002160 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002161 lambda branches, fine_grained, max_processes:
2162 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2163 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002164 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002165
2166 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002167
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002168 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002169 self.calls = [
2170 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2171 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2172 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002173 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2174 'refs/tags/git-cl-archived-456-foo'),
2175 ((['git', 'branch', '-D', 'foo'],), CERR1),
2176 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2177 'refs/tags/git-cl-archived-456-foo'),
2178 ]
2179
Edward Lemurda4b6c62020-02-13 00:28:40 +00002180 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002181 lambda branches, fine_grained, max_processes:
2182 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2183 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002184 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002185
2186 self.assertEqual(0, git_cl.main(['archive', '-f']))
2187
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002188 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002189 self.mockGit.config['branch.master.gerritissue'] = '123'
2190 self.mockGit.config['branch.master.gerritserver'] = (
2191 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002192 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002193 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002194 ]
2195 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002196 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2197 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002198
Aaron Gable400e9892017-07-12 15:31:21 -07002199 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002200 self.mockGit.config['branch.master.gerritissue'] = '123'
2201 self.mockGit.config['branch.master.gerritserver'] = (
2202 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002203 mock.patch('git_cl.Changelist.FetchDescription',
2204 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002205 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002206 ((['git', 'log', '-1', '--format=%B'],),
2207 'This is a description\n\nChange-Id: Ideadbeef'),
2208 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002209 ]
2210 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002211 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2212 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002213
phajdan.jre328cf92016-08-22 04:12:17 -07002214 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002215 self.mockGit.config['branch.master.gerritissue'] = '123'
2216 self.mockGit.config['branch.master.gerritserver'] = (
2217 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002218 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002219 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002220 {'issue': 123,
2221 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002222 ''),
2223 ]
2224 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2225
tandrii16e0b4e2016-06-07 10:34:28 -07002226 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002227 mock.patch(
2228 'git_cl.os.path.abspath',
2229 lambda path: self._mocked_call(['abspath', path])).start()
2230 mock.patch(
2231 'git_cl.os.path.exists',
2232 lambda path: self._mocked_call(['exists', path])).start()
2233 mock.patch(
2234 'git_cl.gclient_utils.FileRead',
2235 lambda path: self._mocked_call(['FileRead', path])).start()
2236 mock.patch(
2237 'git_cl.gclient_utils.rm_file_or_tree',
2238 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002239 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002240
2241 def test_GerritCommitMsgHookCheck_custom_hook(self):
2242 cl = self._common_GerritCommitMsgHookCheck()
2243 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002244 ((['exists', '.git/hooks/commit-msg'],), True),
2245 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002246 '#!/bin/sh\necho "custom hook"')
2247 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002248 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002249
2250 def test_GerritCommitMsgHookCheck_not_exists(self):
2251 cl = self._common_GerritCommitMsgHookCheck()
2252 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002253 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002254 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002255 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002256
2257 def test_GerritCommitMsgHookCheck(self):
2258 cl = self._common_GerritCommitMsgHookCheck()
2259 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002260 ((['exists', '.git/hooks/commit-msg'],), True),
2261 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002262 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002263 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002264 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002265 ''),
2266 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002267 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002268
tandriic4344b52016-08-29 06:04:54 -07002269 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002270 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2271 self.mockGit.config['branch.master.gerritserver'] = (
2272 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002273 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002274 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002275 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002276 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002277 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002278 'labels': {},
2279 'current_revision': 'deadbeaf',
2280 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002281 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002282 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002283 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002284 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2285 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002286 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002287 self.assertEqual(0, cl.CMDLand(force=True,
2288 bypass_hooks=True,
2289 verbose=True,
2290 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002291 self.assertIn(
2292 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002293 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002294 self.assertIn(
2295 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002296 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002297
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002298 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002299 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002300
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002301 def test_gerrit_change_detail_cache_simple(self):
2302 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002303 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002304 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002305 cl1._cached_remote_url = (
2306 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002307 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002308 cl2._cached_remote_url = (
2309 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002310 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2311 self.assertEqual(cl1._GetChangeDetail(), 'a')
2312 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002313
2314 def test_gerrit_change_detail_cache_options(self):
2315 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002316 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002317 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002318 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002319 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2320 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2321 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2322 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2323 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2324 self.assertEqual(cl._GetChangeDetail(), 'cab')
2325
2326 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2327 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2328 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2329 self.assertEqual(cl._GetChangeDetail(), 'cab')
2330
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002331 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002332 gerrit_util.GetChangeDetail.return_value = {
2333 'current_revision': 'rev1',
2334 'revisions': {
2335 'rev1': {'commit': {'message': 'desc1'}},
2336 },
2337 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002338
2339 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002340 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002341 cl._cached_remote_url = (
2342 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002343 self.assertEqual(cl.FetchDescription(), 'desc1')
2344 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002345
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002346 def test_print_current_creds(self):
2347 class CookiesAuthenticatorMock(object):
2348 def __init__(self):
2349 self.gitcookies = {
2350 'host.googlesource.com': ('user', 'pass'),
2351 'host-review.googlesource.com': ('user', 'pass'),
2352 }
2353 self.netrc = self
2354 self.netrc.hosts = {
2355 'github.com': ('user2', None, 'pass2'),
2356 'host2.googlesource.com': ('user3', None, 'pass'),
2357 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002358 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2359 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002360 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2361 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2362 ' Host\t User\t Which file',
2363 '============================\t=====\t===========',
2364 'host-review.googlesource.com\t user\t.gitcookies',
2365 ' host.googlesource.com\t user\t.gitcookies',
2366 ' host2.googlesource.com\tuser3\t .netrc',
2367 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002368 sys.stdout.seek(0)
2369 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002370 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2371 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2372 ' Host\tUser\t Which file',
2373 '============================\t====\t===========',
2374 'host-review.googlesource.com\tuser\t.gitcookies',
2375 ' host.googlesource.com\tuser\t.gitcookies',
2376 ])
2377
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002378 def _common_creds_check_mocks(self):
2379 def exists_mock(path):
2380 dirname = os.path.dirname(path)
2381 if dirname == os.path.expanduser('~'):
2382 dirname = '~'
2383 base = os.path.basename(path)
2384 if base in ('.netrc', '.gitcookies'):
2385 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2386 # git cl also checks for existence other files not relevant to this test.
2387 return None
Edward Lemurda4b6c62020-02-13 00:28:40 +00002388 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002389
2390 def test_creds_check_gitcookies_not_configured(self):
2391 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002392 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2393 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002394 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002395 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002396 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2397 (('os.path.exists', '~/.netrc'), True),
2398 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2399 'or Ctrl+C to abort'), ''),
2400 ((['git', 'config', '--global', 'http.cookiefile',
2401 os.path.expanduser('~/.gitcookies')], ), ''),
2402 ]
2403 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002404 self.assertTrue(
2405 sys.stdout.getvalue().startswith(
2406 'You seem to be using outdated .netrc for git credentials:'))
2407 self.assertIn(
2408 '\nConfigured git to use .gitcookies from',
2409 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002410
2411 def test_creds_check_gitcookies_configured_custom_broken(self):
2412 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002413 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2414 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002415 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002416 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002417 ((['git', 'config', '--global', 'http.cookiefile'],),
2418 '/custom/.gitcookies'),
2419 (('os.path.exists', '/custom/.gitcookies'), False),
2420 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2421 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2422 ((['git', 'config', '--global', 'http.cookiefile',
2423 os.path.expanduser('~/.gitcookies')], ), ''),
2424 ]
2425 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002426 self.assertIn(
2427 'WARNING: You have configured custom path to .gitcookies: ',
2428 sys.stdout.getvalue())
2429 self.assertIn(
2430 'However, your configured .gitcookies file is missing.',
2431 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002432
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002433 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002434 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002435 self.mockGit.config['remote.origin.url'] = (
2436 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002437 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002438 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002439 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002440 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002441 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002442 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002443
Edward Lemurda4b6c62020-02-13 00:28:40 +00002444 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2445 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002446 self.mockGit.config['remote.origin.url'] = (
2447 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002448 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002449 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002450 'current_revision': 'ba5eba11',
2451 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002452 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002453 '_number': 1,
2454 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002455 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002456 '_number': 2,
2457 },
2458 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002459 'messages': [
2460 {
2461 u'_revision_number': 1,
2462 u'author': {
2463 u'_account_id': 1111084,
2464 u'email': u'commit-bot@chromium.org',
2465 u'name': u'Commit Bot'
2466 },
2467 u'date': u'2017-03-15 20:08:45.000000000',
2468 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002469 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002470 u'tag': u'autogenerated:cq:dry-run'
2471 },
2472 {
2473 u'_revision_number': 2,
2474 u'author': {
2475 u'_account_id': 11151243,
2476 u'email': u'owner@example.com',
2477 u'name': u'owner'
2478 },
2479 u'date': u'2017-03-16 20:00:41.000000000',
2480 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2481 u'message': u'PTAL',
2482 },
2483 {
2484 u'_revision_number': 2,
2485 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002486 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002487 u'email': u'reviewer@example.com',
2488 u'name': u'reviewer'
2489 },
2490 u'date': u'2017-03-17 05:19:37.500000000',
2491 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2492 u'message': u'Patch Set 2: Code-Review+1',
2493 },
2494 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002495 }
2496 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002497 (('GetChangeComments', 'chromium-review.googlesource.com',
2498 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002499 '/COMMIT_MSG': [
2500 {
2501 'author': {'email': u'reviewer@example.com'},
2502 'updated': u'2017-03-17 05:19:37.500000000',
2503 'patch_set': 2,
2504 'side': 'REVISION',
2505 'message': 'Please include a bug link',
2506 },
2507 ],
2508 'codereview.settings': [
2509 {
2510 'author': {'email': u'owner@example.com'},
2511 'updated': u'2017-03-16 20:00:41.000000000',
2512 'patch_set': 2,
2513 'side': 'PARENT',
2514 'line': 42,
2515 'message': 'I removed this because it is bad',
2516 },
2517 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002518 }),
2519 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2520 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002521 ] * 2 + [
2522 (('write_json', 'output.json', [
2523 {
2524 u'date': u'2017-03-16 20:00:41.000000',
2525 u'message': (
2526 u'PTAL\n' +
2527 u'\n' +
2528 u'codereview.settings\n' +
2529 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2530 u'c/1/2/codereview.settings#b42\n' +
2531 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002532 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002533 u'approval': False,
2534 u'disapproval': False,
2535 u'sender': u'owner@example.com'
2536 }, {
2537 u'date': u'2017-03-17 05:19:37.500000',
2538 u'message': (
2539 u'Patch Set 2: Code-Review+1\n' +
2540 u'\n' +
2541 u'/COMMIT_MSG\n' +
2542 u' PS2, File comment: https://chromium-review.googlesource' +
2543 u'.com/c/1/2//COMMIT_MSG#\n' +
2544 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002545 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002546 u'approval': False,
2547 u'disapproval': False,
2548 u'sender': u'reviewer@example.com'
2549 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002550 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002551 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002552 expected_comments_summary = [
2553 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002554 message=(
2555 u'PTAL\n' +
2556 u'\n' +
2557 u'codereview.settings\n' +
2558 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2559 u'c/1/2/codereview.settings#b42\n' +
2560 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002561 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002562 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002563 disapproval=False, approval=False, sender=u'owner@example.com'),
2564 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002565 message=(
2566 u'Patch Set 2: Code-Review+1\n' +
2567 u'\n' +
2568 u'/COMMIT_MSG\n' +
2569 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2570 u'c/1/2//COMMIT_MSG#\n' +
2571 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002572 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002573 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002574 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2575 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002576 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002577 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002578 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002579 self.assertEqual(
2580 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2581
2582 def test_git_cl_comments_robot_comments(self):
2583 # git cl comments also fetches robot comments (which are considered a type
2584 # of autogenerated comment), and unlike other types of comments, only robot
2585 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002586 self.mockGit.config['remote.origin.url'] = (
2587 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002588 gerrit_util.GetChangeDetail.return_value = {
2589 'owner': {'email': 'owner@example.com'},
2590 'current_revision': 'ba5eba11',
2591 'revisions': {
2592 'deadbeaf': {
2593 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002594 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002595 'ba5eba11': {
2596 '_number': 2,
2597 },
2598 },
2599 'messages': [
2600 {
2601 u'_revision_number': 1,
2602 u'author': {
2603 u'_account_id': 1111084,
2604 u'email': u'commit-bot@chromium.org',
2605 u'name': u'Commit Bot'
2606 },
2607 u'date': u'2017-03-15 20:08:45.000000000',
2608 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2609 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2610 u'tag': u'autogenerated:cq:dry-run'
2611 },
2612 {
2613 u'_revision_number': 1,
2614 u'author': {
2615 u'_account_id': 123,
2616 u'email': u'tricium@serviceaccount.com',
2617 u'name': u'Tricium'
2618 },
2619 u'date': u'2017-03-16 20:00:41.000000000',
2620 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2621 u'message': u'(1 comment)',
2622 u'tag': u'autogenerated:tricium',
2623 },
2624 {
2625 u'_revision_number': 1,
2626 u'author': {
2627 u'_account_id': 123,
2628 u'email': u'tricium@serviceaccount.com',
2629 u'name': u'Tricium'
2630 },
2631 u'date': u'2017-03-16 20:00:41.000000000',
2632 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2633 u'message': u'(1 comment)',
2634 u'tag': u'autogenerated:tricium',
2635 },
2636 {
2637 u'_revision_number': 2,
2638 u'author': {
2639 u'_account_id': 123,
2640 u'email': u'tricium@serviceaccount.com',
2641 u'name': u'reviewer'
2642 },
2643 u'date': u'2017-03-17 05:30:37.000000000',
2644 u'tag': u'autogenerated:tricium',
2645 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2646 u'message': u'(1 comment)',
2647 },
2648 ]
2649 }
2650 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002651 (('GetChangeComments', 'chromium-review.googlesource.com',
2652 'infra%2Finfra~1'), {}),
2653 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2654 'infra%2Finfra~1'), {
2655 'codereview.settings': [
2656 {
2657 u'author': {u'email': u'tricium@serviceaccount.com'},
2658 u'updated': u'2017-03-17 05:30:37.000000000',
2659 u'robot_run_id': u'5565031076855808',
2660 u'robot_id': u'Linter/Category',
2661 u'tag': u'autogenerated:tricium',
2662 u'patch_set': 2,
2663 u'side': u'REVISION',
2664 u'message': u'Linter warning message text',
2665 u'line': 32,
2666 },
2667 ],
2668 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002669 ]
2670 expected_comments_summary = [
2671 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2672 message=(
2673 u'(1 comment)\n\ncodereview.settings\n'
2674 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2675 u'c/1/2/codereview.settings#32\n'
2676 u' Linter warning message text\n'),
2677 sender=u'tricium@serviceaccount.com',
2678 autogenerated=True, approval=False, disapproval=False)
2679 ]
2680 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002681 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002682 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002683
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002684 def test_get_remote_url_with_mirror(self):
2685 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002686
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002687 def selective_os_path_isdir_mock(path):
2688 if path == '/cache/this-dir-exists':
2689 return self._mocked_call('os.path.isdir', path)
2690 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002691
Edward Lemurda4b6c62020-02-13 00:28:40 +00002692 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002693
2694 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002695 self.mockGit.config['remote.origin.url'] = (
2696 '/cache/this-dir-exists')
2697 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2698 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002699 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002700 (('os.path.isdir', '/cache/this-dir-exists'),
2701 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002702 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002703 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002704 self.assertEqual(cl.GetRemoteUrl(), url)
2705 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2706
Edward Lemur298f2cf2019-02-22 21:40:39 +00002707 def test_get_remote_url_non_existing_mirror(self):
2708 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002709
Edward Lemur298f2cf2019-02-22 21:40:39 +00002710 def selective_os_path_isdir_mock(path):
2711 if path == '/cache/this-dir-doesnt-exist':
2712 return self._mocked_call('os.path.isdir', path)
2713 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002714
Edward Lemurda4b6c62020-02-13 00:28:40 +00002715 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2716 mock.patch('logging.error',
2717 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002718
Edward Lemur26964072020-02-19 19:18:51 +00002719 self.mockGit.config['remote.origin.url'] = (
2720 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002721 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002722 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2723 False),
2724 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002725 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2726 'but it doesn\'t exist.', {
2727 'remote': 'origin',
2728 'branch': 'master',
2729 'url': '/cache/this-dir-doesnt-exist'}
2730 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002731 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002732 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002733 self.assertIsNone(cl.GetRemoteUrl())
2734
2735 def test_get_remote_url_misconfigured_mirror(self):
2736 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002737
Edward Lemur298f2cf2019-02-22 21:40:39 +00002738 def selective_os_path_isdir_mock(path):
2739 if path == '/cache/this-dir-exists':
2740 return self._mocked_call('os.path.isdir', path)
2741 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002742
Edward Lemurda4b6c62020-02-13 00:28:40 +00002743 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2744 mock.patch('logging.error',
2745 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002746
Edward Lemur26964072020-02-19 19:18:51 +00002747 self.mockGit.config['remote.origin.url'] = (
2748 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002749 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002750 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002751 (('logging.error',
2752 'Remote "%(remote)s" for branch "%(branch)s" points to '
2753 '"%(cache_path)s", but it is misconfigured.\n'
2754 '"%(cache_path)s" must be a git repo and must have a remote named '
2755 '"%(remote)s" pointing to the git host.', {
2756 'remote': 'origin',
2757 'cache_path': '/cache/this-dir-exists',
2758 'branch': 'master'}
2759 ), None),
2760 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002761 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002762 self.assertIsNone(cl.GetRemoteUrl())
2763
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002764 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002765 self.mockGit.config['remote.origin.url'] = (
2766 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002767 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002768 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2769
2770 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002771 mock.patch('logging.error',
2772 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002773
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002774 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002775 (('logging.error',
2776 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2777 'but it doesn\'t exist.', {
2778 'remote': 'origin',
2779 'branch': 'master',
2780 'url': ''}
2781 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002782 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002783 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002784 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002785
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002786
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002787class CMDTestCaseBase(unittest.TestCase):
2788 _STATUSES = [
2789 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2790 'INFRA_FAILURE', 'CANCELED',
2791 ]
2792 _CHANGE_DETAIL = {
2793 'project': 'depot_tools',
2794 'status': 'OPEN',
2795 'owner': {'email': 'owner@e.mail'},
2796 'current_revision': 'beeeeeef',
2797 'revisions': {
2798 'deadbeaf': {'_number': 6},
2799 'beeeeeef': {
2800 '_number': 7,
2801 'fetch': {'http': {
2802 'url': 'https://chromium.googlesource.com/depot_tools',
2803 'ref': 'refs/changes/56/123456/7'
2804 }},
2805 },
2806 },
2807 }
2808 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002809 'builds': [{
2810 'id': str(100 + idx),
2811 'builder': {
2812 'project': 'chromium',
2813 'bucket': 'try',
2814 'builder': 'bot_' + status.lower(),
2815 },
2816 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2817 'tags': [],
2818 'status': status,
2819 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002820 }
2821
Edward Lemur4c707a22019-09-24 21:13:43 +00002822 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002823 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002824 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002825 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2826 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002827 mock.patch(
2828 'git_cl.Changelist.GetCodereviewServer',
2829 return_value='https://chromium-review.googlesource.com').start()
2830 mock.patch(
2831 'git_cl.Changelist._GetGerritHost',
2832 return_value='chromium-review.googlesource.com').start()
2833 mock.patch(
2834 'git_cl.Changelist.GetMostRecentPatchset',
2835 return_value=7).start()
2836 mock.patch(
2837 'git_cl.Changelist.GetRemoteUrl',
2838 return_value='https://chromium.googlesource.com/depot_tools').start()
2839 mock.patch(
2840 'auth.Authenticator',
2841 return_value=AuthenticatorMock()).start()
2842 mock.patch(
2843 'gerrit_util.GetChangeDetail',
2844 return_value=self._CHANGE_DETAIL).start()
2845 mock.patch(
2846 'git_cl._call_buildbucket',
2847 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002848 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002849 self.addCleanup(mock.patch.stopall)
2850
Edward Lemur4c707a22019-09-24 21:13:43 +00002851
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002852class CMDTryResultsTestCase(CMDTestCaseBase):
2853 _DEFAULT_REQUEST = {
2854 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002855 "gerritChanges": [{
2856 "project": "depot_tools",
2857 "host": "chromium-review.googlesource.com",
2858 "patchset": 7,
2859 "change": 123456,
2860 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002861 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002862 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
2863 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002864 }
2865
2866 def testNoJobs(self):
2867 git_cl._call_buildbucket.return_value = {}
2868
2869 self.assertEqual(0, git_cl.main(['try-results']))
2870 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
2871 git_cl._call_buildbucket.assert_called_once_with(
2872 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2873 self._DEFAULT_REQUEST)
2874
2875 def testPrintToStdout(self):
2876 self.assertEqual(0, git_cl.main(['try-results']))
2877 self.assertEqual([
2878 'Successes:',
2879 ' bot_success https://ci.chromium.org/b/103',
2880 'Infra Failures:',
2881 ' bot_infra_failure https://ci.chromium.org/b/105',
2882 'Failures:',
2883 ' bot_failure https://ci.chromium.org/b/104',
2884 'Canceled:',
2885 ' bot_canceled ',
2886 'Started:',
2887 ' bot_started https://ci.chromium.org/b/102',
2888 'Scheduled:',
2889 ' bot_scheduled id=101',
2890 'Other:',
2891 ' bot_status_unspecified id=100',
2892 'Total: 7 tryjobs',
2893 ], sys.stdout.getvalue().splitlines())
2894 git_cl._call_buildbucket.assert_called_once_with(
2895 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2896 self._DEFAULT_REQUEST)
2897
2898 def testPrintToStdoutWithMasters(self):
2899 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
2900 self.assertEqual([
2901 'Successes:',
2902 ' try bot_success https://ci.chromium.org/b/103',
2903 'Infra Failures:',
2904 ' try bot_infra_failure https://ci.chromium.org/b/105',
2905 'Failures:',
2906 ' try bot_failure https://ci.chromium.org/b/104',
2907 'Canceled:',
2908 ' try bot_canceled ',
2909 'Started:',
2910 ' try bot_started https://ci.chromium.org/b/102',
2911 'Scheduled:',
2912 ' try bot_scheduled id=101',
2913 'Other:',
2914 ' try bot_status_unspecified id=100',
2915 'Total: 7 tryjobs',
2916 ], sys.stdout.getvalue().splitlines())
2917 git_cl._call_buildbucket.assert_called_once_with(
2918 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2919 self._DEFAULT_REQUEST)
2920
2921 @mock.patch('git_cl.write_json')
2922 def testWriteToJson(self, mockJsonDump):
2923 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
2924 git_cl._call_buildbucket.assert_called_once_with(
2925 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
2926 self._DEFAULT_REQUEST)
2927 mockJsonDump.assert_called_once_with(
2928 'file.json', self._DEFAULT_RESPONSE['builds'])
2929
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002930 def test_filter_failed_for_one_simple(self):
2931 self.assertEqual({}, git_cl._filter_failed_for_retry([]))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002932 self.assertEqual({
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002933 'chromium/try': {
2934 'bot_failure': [],
2935 'bot_infra_failure': []
2936 },
2937 }, git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
2938
2939 def test_filter_failed_for_retry_many_builds(self):
2940
2941 def _build(name, created_sec, status, experimental=False):
2942 assert 0 <= created_sec < 100, created_sec
2943 b = {
2944 'id': 112112,
2945 'builder': {
2946 'project': 'chromium',
2947 'bucket': 'try',
2948 'builder': name,
2949 },
2950 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
2951 'status': status,
2952 'tags': [],
2953 }
2954 if experimental:
2955 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
2956 return b
2957
2958 builds = [
2959 _build('flaky-last-green', 1, 'FAILURE'),
2960 _build('flaky-last-green', 2, 'SUCCESS'),
2961 _build('flaky', 1, 'SUCCESS'),
2962 _build('flaky', 2, 'FAILURE'),
2963 _build('running', 1, 'FAILED'),
2964 _build('running', 2, 'SCHEDULED'),
2965 _build('yep-still-running', 1, 'STARTED'),
2966 _build('yep-still-running', 2, 'FAILURE'),
2967 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
2968 _build('cq-experimental', 2, 'FAILURE', experimental=True),
2969
2970 # Simulate experimental in CQ builder, which developer decided
2971 # to retry manually which resulted in 2nd build non-experimental.
2972 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
2973 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
2974 ]
2975 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
2976 self.assertEqual({
2977 'chromium/try': {
2978 'flaky': [],
2979 'sometimes-experimental': []
2980 },
2981 }, git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002982
2983
2984class CMDTryTestCase(CMDTestCaseBase):
2985
2986 @mock.patch('git_cl.Changelist.SetCQState')
2987 @mock.patch('git_cl._get_bucket_map', return_value={})
2988 def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
2989 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00002990 self.assertEqual(0, git_cl.main(['try']))
2991 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
2992 self.assertEqual(
2993 sys.stdout.getvalue(),
2994 'Scheduling CQ dry run on: '
2995 'https://chromium-review.googlesource.com/123456\n')
2996
Edward Lemur4c707a22019-09-24 21:13:43 +00002997 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002998 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00002999 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003000
3001 self.assertEqual(0, git_cl.main([
3002 'try', '-B', 'luci.chromium.try', '-b', 'win',
3003 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3004 self.assertIn(
3005 'Scheduling jobs on:\nBucket: luci.chromium.try',
3006 git_cl.sys.stdout.getvalue())
3007
3008 expected_request = {
3009 "requests": [{
3010 "scheduleBuild": {
3011 "requestId": "uuid4",
3012 "builder": {
3013 "project": "chromium",
3014 "builder": "win",
3015 "bucket": "try",
3016 },
3017 "gerritChanges": [{
3018 "project": "depot_tools",
3019 "host": "chromium-review.googlesource.com",
3020 "patchset": 7,
3021 "change": 123456,
3022 }],
3023 "properties": {
3024 "category": "git_cl_try",
3025 "json": [{"a": 1}, None],
3026 "key": "val",
3027 },
3028 "tags": [
3029 {"value": "win", "key": "builder"},
3030 {"value": "git_cl_try", "key": "user_agent"},
3031 ],
3032 },
3033 }],
3034 }
3035 mockCallBuildbucket.assert_called_with(
3036 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3037
Anthony Polito1a5fe232020-01-24 23:17:52 +00003038 @mock.patch('git_cl._call_buildbucket')
3039 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3040 mockCallBuildbucket.return_value = {}
3041
3042 self.assertEqual(0, git_cl.main([
3043 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3044 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3045 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3046 self.assertIn(
3047 'Scheduling jobs on:\nBucket: luci.chromium.try',
3048 git_cl.sys.stdout.getvalue())
3049
3050 expected_request = {
3051 "requests": [{
3052 "scheduleBuild": {
3053 "requestId": "uuid4",
3054 "builder": {
3055 "project": "chromium",
3056 "builder": "linux",
3057 "bucket": "try",
3058 },
3059 "gerritChanges": [{
3060 "project": "depot_tools",
3061 "host": "chromium-review.googlesource.com",
3062 "patchset": 7,
3063 "change": 123456,
3064 }],
3065 "properties": {
3066 "category": "git_cl_try",
3067 "json": [{"a": 1}, None],
3068 "key": "val",
3069 },
3070 "tags": [
3071 {"value": "linux", "key": "builder"},
3072 {"value": "git_cl_try", "key": "user_agent"},
3073 ],
3074 "gitilesCommit": {
3075 "host": "chromium-review.googlesource.com",
3076 "project": "depot_tools",
3077 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3078 }
3079 },
3080 },
3081 {
3082 "scheduleBuild": {
3083 "requestId": "uuid4",
3084 "builder": {
3085 "project": "chromium",
3086 "builder": "win",
3087 "bucket": "try",
3088 },
3089 "gerritChanges": [{
3090 "project": "depot_tools",
3091 "host": "chromium-review.googlesource.com",
3092 "patchset": 7,
3093 "change": 123456,
3094 }],
3095 "properties": {
3096 "category": "git_cl_try",
3097 "json": [{"a": 1}, None],
3098 "key": "val",
3099 },
3100 "tags": [
3101 {"value": "win", "key": "builder"},
3102 {"value": "git_cl_try", "key": "user_agent"},
3103 ],
3104 "gitilesCommit": {
3105 "host": "chromium-review.googlesource.com",
3106 "project": "depot_tools",
3107 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3108 }
3109 },
3110 }],
3111 }
3112 mockCallBuildbucket.assert_called_with(
3113 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3114
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003115 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur4c707a22019-09-24 21:13:43 +00003116 self.assertEqual(0, git_cl.main([
3117 'try', '-B', 'not-a-bucket', '-b', 'win',
3118 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3119 self.assertIn(
3120 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3121 git_cl.sys.stdout.getvalue())
3122
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003123 @mock.patch('git_cl._call_buildbucket')
3124 @mock.patch('git_cl.fetch_try_jobs')
3125 def testScheduleOnBuildbucketRetryFailed(
3126 self, mockFetchTryJobs, mockCallBuildbucket):
3127
3128 git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
3129 7: [],
3130 6: [{
3131 'id': 112112,
3132 'builder': {
3133 'project': 'chromium',
3134 'bucket': 'try',
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003135 'builder': 'linux',},
3136 'createTime': '2019-10-09T08:00:01.854286Z',
3137 'tags': [],
3138 'status': 'FAILURE',}],}[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003139 mockCallBuildbucket.return_value = {}
3140
3141 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3142 self.assertIn(
3143 'Scheduling jobs on:\nBucket: chromium/try',
3144 git_cl.sys.stdout.getvalue())
3145
3146 expected_request = {
3147 "requests": [{
3148 "scheduleBuild": {
3149 "requestId": "uuid4",
3150 "builder": {
3151 "project": "chromium",
3152 "bucket": "try",
3153 "builder": "linux",
3154 },
3155 "gerritChanges": [{
3156 "project": "depot_tools",
3157 "host": "chromium-review.googlesource.com",
3158 "patchset": 7,
3159 "change": 123456,
3160 }],
3161 "properties": {
3162 "category": "git_cl_try",
3163 },
3164 "tags": [
3165 {"value": "linux", "key": "builder"},
3166 {"value": "git_cl_try", "key": "user_agent"},
3167 {"value": "1", "key": "retry_failed"},
3168 ],
3169 },
3170 }],
3171 }
3172 mockCallBuildbucket.assert_called_with(
3173 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3174
Edward Lemur4c707a22019-09-24 21:13:43 +00003175 def test_parse_bucket(self):
3176 test_cases = [
3177 {
3178 'bucket': 'chromium/try',
3179 'result': ('chromium', 'try'),
3180 },
3181 {
3182 'bucket': 'luci.chromium.try',
3183 'result': ('chromium', 'try'),
3184 'has_warning': True,
3185 },
3186 {
3187 'bucket': 'skia.primary',
3188 'result': ('skia', 'skia.primary'),
3189 'has_warning': True,
3190 },
3191 {
3192 'bucket': 'not-a-bucket',
3193 'result': (None, None),
3194 },
3195 ]
3196
3197 for test_case in test_cases:
3198 git_cl.sys.stdout.truncate(0)
3199 self.assertEqual(
3200 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3201 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003202 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3203 test_case['result'])
3204 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003205
3206
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003207class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003208 def setUp(self):
3209 super(CMDUploadTestCase, self).setUp()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003210 mock.patch('git_cl.fetch_try_jobs').start()
3211 mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
3212 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003213 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003214 self.addCleanup(mock.patch.stopall)
3215
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003216 def testWarmUpChangeDetailCache(self):
3217 self.assertEqual(0, git_cl.main(['upload']))
3218 gerrit_util.GetChangeDetail.assert_called_once_with(
3219 'chromium-review.googlesource.com', 'depot_tools~123456',
3220 frozenset([
3221 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3222 'CURRENT_COMMIT']))
3223
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003224 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003225 # This test mocks out the actual upload part, and just asserts that after
3226 # upload, if --retry-failed is added, then the tool will fetch try jobs
3227 # from the previous patchset and trigger the right builders on the latest
3228 # patchset.
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003229 git_cl.fetch_try_jobs.side_effect = [
3230 # Latest patchset: No builds.
3231 [],
3232 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003233 [{
3234 'id': str(100 + idx),
3235 'builder': {
3236 'project': 'chromium',
3237 'bucket': 'try',
3238 'builder': 'bot_' + status.lower(),
3239 },
3240 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3241 'tags': [],
3242 'status': status,
3243 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003244 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003245
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003246 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003247 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003248 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3249 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003250 ], git_cl.fetch_try_jobs.mock_calls)
3251 expected_buckets = {
3252 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
3253 }
3254 git_cl._trigger_try_jobs.assert_called_once_with(
Edward Lemur5b929a42019-10-21 17:57:39 +00003255 mock.ANY, expected_buckets, mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003256
Brian Sheedy59b06a82019-10-14 17:03:29 +00003257
Edward Lemurda4b6c62020-02-13 00:28:40 +00003258class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003259
3260 def setUp(self):
3261 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003262 mock.patch('git_cl.RunCommand').start()
3263 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3264 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3265 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003266 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003267 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003268
3269 def tearDown(self):
3270 shutil.rmtree(self._top_dir)
3271 super(CMDFormatTestCase, self).tearDown()
3272
Jamie Madill5e96ad12020-01-13 16:08:35 +00003273 def _make_temp_file(self, fname, contents):
3274 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3275 tf.write('\n'.join(contents))
3276
Brian Sheedy59b06a82019-10-14 17:03:29 +00003277 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003278 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003279
Brian Sheedyb4307d52019-12-02 19:18:17 +00003280 def _check_yapf_filtering(self, files, expected):
3281 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3282 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003283
Jamie Madill5e96ad12020-01-13 16:08:35 +00003284 def testClangFormatDiffFull(self):
3285 self._make_temp_file('test.cc', ['// test'])
3286 git_cl.settings.GetFormatFullByDefault.return_value = False
3287 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3288 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3289
3290 # Diff
3291 git_cl.RunCommand.return_value = ' // test'
3292 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3293 self._top_dir, 'HEAD')
3294 self.assertEqual(2, return_value)
3295
3296 # No diff
3297 git_cl.RunCommand.return_value = '// test'
3298 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3299 self._top_dir, 'HEAD')
3300 self.assertEqual(0, return_value)
3301
3302 def testClangFormatDiff(self):
3303 git_cl.settings.GetFormatFullByDefault.return_value = False
3304 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3305
3306 # Diff
3307 git_cl.RunCommand.return_value = 'error'
3308 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3309 'HEAD')
3310 self.assertEqual(2, return_value)
3311
3312 # No diff
3313 git_cl.RunCommand.return_value = ''
3314 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3315 'HEAD')
3316 self.assertEqual(0, return_value)
3317
Brian Sheedyb4307d52019-12-02 19:18:17 +00003318 def testYapfignoreExplicit(self):
3319 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3320 files = [
3321 'bar.py',
3322 'foo/bar.py',
3323 'foo/baz.py',
3324 'foo/bar/baz.py',
3325 'foo/bar/foobar.py',
3326 ]
3327 expected = [
3328 'bar.py',
3329 'foo/baz.py',
3330 'foo/bar/foobar.py',
3331 ]
3332 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003333
Brian Sheedyb4307d52019-12-02 19:18:17 +00003334 def testYapfignoreSingleWildcards(self):
3335 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3336 files = [
3337 'bar.py', # Matched by *bar.py.
3338 'bar.txt',
3339 'foobar.py', # Matched by *bar.py, foo*.
3340 'foobar.txt', # Matched by foo*.
3341 'bazbar.py', # Matched by *bar.py, baz*.py.
3342 'bazbar.txt',
3343 'foo/baz.txt', # Matched by foo*.
3344 'bar/bar.py', # Matched by *bar.py.
3345 'baz/foo.py', # Matched by baz*.py, foo*.
3346 'baz/foo.txt',
3347 ]
3348 expected = [
3349 'bar.txt',
3350 'bazbar.txt',
3351 'baz/foo.txt',
3352 ]
3353 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003354
Brian Sheedyb4307d52019-12-02 19:18:17 +00003355 def testYapfignoreMultiplewildcards(self):
3356 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3357 files = [
3358 'bar.py', # Matched by *bar*.
3359 'bar.txt', # Matched by *bar*.
3360 'abar.py', # Matched by *bar*.
3361 'foobaz.txt', # Matched by *foo*baz.txt.
3362 'foobaz.py',
3363 'afoobaz.txt', # Matched by *foo*baz.txt.
3364 ]
3365 expected = [
3366 'foobaz.py',
3367 ]
3368 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003369
3370 def testYapfignoreComments(self):
3371 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003372 files = [
3373 'test.py',
3374 'test2.py',
3375 ]
3376 expected = [
3377 'test2.py',
3378 ]
3379 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003380
3381 def testYapfignoreBlankLines(self):
3382 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003383 files = [
3384 'test.py',
3385 'test2.py',
3386 'test3.py',
3387 ]
3388 expected = [
3389 'test3.py',
3390 ]
3391 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003392
3393 def testYapfignoreWhitespace(self):
3394 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003395 files = [
3396 'test.py',
3397 'test2.py',
3398 ]
3399 expected = [
3400 'test2.py',
3401 ]
3402 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003403
Brian Sheedyb4307d52019-12-02 19:18:17 +00003404 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003405 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003406 self._check_yapf_filtering([], [])
3407
3408 def testYapfignoreMissingYapfignore(self):
3409 files = [
3410 'test.py',
3411 ]
3412 expected = [
3413 'test.py',
3414 ]
3415 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003416
3417
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003418if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003419 logging.basicConfig(
3420 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003421 unittest.main()