blob: a75e81496b7e9d99cad177002785e772e4e5689a [file] [log] [blame]
Edward Lemur0db01f02019-11-12 22:01:51 +00001#!/usr/bin/env vpython3
2# coding=utf-8
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00003# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Unit tests for git_cl.py."""
8
Edward Lemur85153282020-02-14 22:06:29 +00009from __future__ import print_function
Edward Lemur0db01f02019-11-12 22:01:51 +000010from __future__ import unicode_literals
11
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +010012import datetime
tandriide281ae2016-10-12 06:02:30 -070013import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010014import logging
Edward Lemur61bf4172020-02-24 23:22:37 +000015import multiprocessing
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000016import optparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000017import os
Edward Lemur85153282020-02-14 22:06:29 +000018import pprint
Brian Sheedy59b06a82019-10-14 17:03:29 +000019import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000020import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070021import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000022import unittest
23
Edward Lemura8145022020-01-06 18:47:54 +000024if sys.version_info.major == 2:
25 from StringIO import StringIO
26 import mock
27else:
28 from io import StringIO
29 from unittest import mock
30
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
32
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000033import metrics
34# We have to disable monitoring before importing git_cl.
35metrics.DISABLE_METRICS_COLLECTION = True
36
Jamie Madill5e96ad12020-01-13 16:08:35 +000037import clang_format
Edward Lemur227d5102020-02-25 23:45:35 +000038import contextlib
Edward Lemur1773f372020-02-22 00:27:14 +000039import gclient_utils
Eric Boren2fb63102018-10-05 13:05:03 +000040import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000041import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000042import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000043import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000044import git_new_branch
45import scm
maruel@chromium.orgddd59412011-11-30 14:20:38 +000046import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000047
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000048
Edward Lemur0db01f02019-11-12 22:01:51 +000049def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070050 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
51
tandrii5d48c322016-08-18 16:19:37 -070052CERR1 = callError(1)
53
54
Edward Lemur1773f372020-02-22 00:27:14 +000055class TemporaryFileMock(object):
56 def __init__(self):
57 self.suffix = 0
Aaron Gable9a03ae02017-11-03 11:31:07 -070058
Edward Lemur1773f372020-02-22 00:27:14 +000059 @contextlib.contextmanager
60 def __call__(self):
61 self.suffix += 1
62 yield '/tmp/fake-temp' + str(self.suffix)
Aaron Gable9a03ae02017-11-03 11:31:07 -070063
64
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000065class ChangelistMock(object):
66 # A class variable so we can access it when we don't have access to the
67 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000068 desc = ''
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000069
70 def __init__(self, gerrit_change=None, **kwargs):
71 self._gerrit_change = gerrit_change
72
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000073 def GetIssue(self):
74 return 1
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000075
Edward Lemur6c6827c2020-02-06 21:15:18 +000076 def FetchDescription(self):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000077 return ChangelistMock.desc
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000078
dsansomee2d6fd92016-09-08 00:10:47 -070079 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000080 ChangelistMock.desc = desc
81
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +000082 def GetGerritChange(self, patchset=None, **kwargs):
83 del patchset
84 return self._gerrit_change
85
tandrii5d48c322016-08-18 16:19:37 -070086
Edward Lemur85153282020-02-14 22:06:29 +000087class GitMocks(object):
88 def __init__(self, config=None, branchref=None):
89 self.branchref = branchref or 'refs/heads/master'
90 self.config = config or {}
91
92 def GetBranchRef(self, _root):
93 return self.branchref
94
95 def NewBranch(self, branchref):
96 self.branchref = branchref
97
Edward Lemur26964072020-02-19 19:18:51 +000098 def GetConfig(self, root, key, default=None):
99 if root != '':
100 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000101 return self.config.get(key, default)
102
Edward Lemur26964072020-02-19 19:18:51 +0000103 def SetConfig(self, root, key, value=None):
104 if root != '':
105 key = '%s:%s' % (root, key)
Edward Lemur85153282020-02-14 22:06:29 +0000106 if value:
107 self.config[key] = value
108 return
109 if key not in self.config:
110 raise CERR1
111 del self.config[key]
112
113
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000114class WatchlistsMock(object):
115 def __init__(self, _):
116 pass
117 @staticmethod
118 def GetWatchersForPaths(_):
119 return ['joe@example.com']
120
121
Edward Lemur4c707a22019-09-24 21:13:43 +0000122class CodereviewSettingsFileMock(object):
123 def __init__(self):
124 pass
125 # pylint: disable=no-self-use
126 def read(self):
127 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
128 'GERRIT_HOST: True\n')
129
130
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000131class AuthenticatorMock(object):
132 def __init__(self, *_args):
133 pass
134 def has_cached_credentials(self):
135 return True
tandrii221ab252016-10-06 08:12:04 -0700136 def authorize(self, http):
137 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000138
139
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100140def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000141 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
142
143 Usage:
144 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100145 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000146
147 OR
148 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100149 CookiesAuthenticatorMockFactory(
150 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000151 """
152 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800153 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000154 # Intentionally not calling super() because it reads actual cookie files.
155 pass
156 @classmethod
157 def get_gitcookies_path(cls):
158 return '~/.gitcookies'
159 @classmethod
160 def get_netrc_path(cls):
161 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100162 def _get_auth_for_host(self, host):
163 if same_auth:
164 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000165 return (hosts_with_creds or {}).get(host)
166 return CookiesAuthenticatorMock
167
Aaron Gable9a03ae02017-11-03 11:31:07 -0700168
kmarshall9249e012016-08-23 12:02:16 -0700169class MockChangelistWithBranchAndIssue():
170 def __init__(self, branch, issue):
171 self.branch = branch
172 self.issue = issue
173 def GetBranch(self):
174 return self.branch
175 def GetIssue(self):
176 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000177
tandriic2405f52016-10-10 08:13:15 -0700178
179class SystemExitMock(Exception):
180 pass
181
182
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000183class TestGitClBasic(unittest.TestCase):
Josip Sokcevic953278a2020-02-28 19:46:36 +0000184 def setUp(self):
185 mock.patch('sys.exit', side_effect=SystemExitMock).start()
186 mock.patch('sys.stdout', StringIO()).start()
187 mock.patch('sys.stderr', StringIO()).start()
188 self.addCleanup(mock.patch.stopall)
189
190 def test_die_with_error(self):
191 with self.assertRaises(SystemExitMock):
192 git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
193 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
194 self.assertTrue('saving CL description' in sys.stdout.getvalue())
195 self.assertTrue('Content of CL description' in sys.stdout.getvalue())
196 self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
197 sys.exit.assert_called_once_with(1)
198
199 def test_die_with_error_no_desc(self):
200 with self.assertRaises(SystemExitMock):
201 git_cl.DieWithError('foo')
202 self.assertEqual(sys.stderr.getvalue(), 'foo\n')
203 self.assertEqual(sys.stdout.getvalue(), '')
204 sys.exit.assert_called_once_with(1)
205
Edward Lemur6c6827c2020-02-06 21:15:18 +0000206 def test_fetch_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000207 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100208 cl.description = 'x'
Edward Lemur6c6827c2020-02-06 21:15:18 +0000209 self.assertEqual(cl.FetchDescription(), 'x')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700210
Edward Lemur61bf4172020-02-24 23:22:37 +0000211 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
212 @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
213 def test_get_cl_statuses(self, *_mocks):
214 statuses = [
215 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
216 changes = []
217 for status in statuses:
218 cl = git_cl.Changelist()
219 cl.status = status
220 changes.append(cl)
221
222 actual = set(git_cl.get_cl_statuses(changes, True))
223 self.assertEqual(set(zip(changes, statuses)), actual)
224
225 def test_get_cl_statuses_no_changes(self):
226 self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
227
228 @mock.patch('git_cl.Changelist.EnsureAuthenticated')
229 @mock.patch('multiprocessing.pool.ThreadPool')
230 def test_get_cl_statuses_timeout(self, *_mocks):
231 changes = [git_cl.Changelist() for _ in range(2)]
232 pool = multiprocessing.pool.ThreadPool()
233 it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
234 it.return_value.next.side_effect = [
235 (changes[0], 'lgtm'),
236 multiprocessing.TimeoutError,
237 ]
238
239 actual = list(git_cl.get_cl_statuses(changes, True))
240 self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
241
242 @mock.patch('git_cl.Changelist.GetIssueURL')
243 def test_get_cl_statuses_not_finegrained(self, _mock):
244 changes = [git_cl.Changelist() for _ in range(2)]
245 urls = ['some-url', None]
246 git_cl.Changelist.GetIssueURL.side_effect = urls
247
248 actual = set(git_cl.get_cl_statuses(changes, False))
249 self.assertEqual(
250 set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
251
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000252 def test_get_issue_url(self):
253 cl = git_cl.Changelist(issue=123)
254 cl._gerrit_server = 'https://example.com'
255 self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
256 self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
257
258 cl = git_cl.Changelist(issue=123)
259 cl._gerrit_server = 'https://chromium-review.googlesource.com'
260 self.assertEqual(cl.GetIssueURL(),
261 'https://chromium-review.googlesource.com/123')
262 self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
263
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000264 def test_set_preserve_tryjobs(self):
265 d = git_cl.ChangeDescription('Simple.')
266 d.set_preserve_tryjobs()
267 self.assertEqual(d.description.splitlines(), [
268 'Simple.',
269 '',
270 'Cq-Do-Not-Cancel-Tryjobs: true',
271 ])
272 before = d.description
273 d.set_preserve_tryjobs()
274 self.assertEqual(before, d.description)
275
276 d = git_cl.ChangeDescription('\n'.join([
277 'One is enough',
278 '',
279 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
280 'Change-Id: Ideadbeef',
281 ]))
282 d.set_preserve_tryjobs()
283 self.assertEqual(d.description.splitlines(), [
284 'One is enough',
285 '',
286 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
287 'Change-Id: Ideadbeef',
288 'Cq-Do-Not-Cancel-Tryjobs: true',
289 ])
290
tandriif9aefb72016-07-01 09:06:51 -0700291 def test_get_bug_line_values(self):
292 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
293 self.assertEqual(f('', ''), [])
294 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
295 self.assertEqual(f('v8', '456'), ['v8:456'])
296 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
297 # Not nice, but not worth carying.
298 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
299 ['v8:456', 'chromium:123', 'v8:123'])
300
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100301 def _test_git_number(self, parent_msg, dest_ref, child_msg,
302 parent_hash='parenthash'):
303 desc = git_cl.ChangeDescription(child_msg)
304 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
305 return desc.description
306
307 def assertEqualByLine(self, actual, expected):
308 self.assertEqual(actual.splitlines(), expected.splitlines())
309
310 def test_git_number_bad_parent(self):
311 with self.assertRaises(ValueError):
312 self._test_git_number('Parent', 'refs/heads/master', 'Child')
313
314 def test_git_number_bad_parent_footer(self):
315 with self.assertRaises(AssertionError):
316 self._test_git_number(
317 'Parent\n'
318 '\n'
319 'Cr-Commit-Position: wrong',
320 'refs/heads/master', 'Child')
321
322 def test_git_number_bad_lineage_ignored(self):
323 actual = self._test_git_number(
324 'Parent\n'
325 '\n'
326 'Cr-Commit-Position: refs/heads/master@{#1}\n'
327 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
328 'refs/heads/master', 'Child')
329 self.assertEqualByLine(
330 actual,
331 'Child\n'
332 '\n'
333 'Cr-Commit-Position: refs/heads/master@{#2}\n'
334 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
335
336 def test_git_number_same_branch(self):
337 actual = self._test_git_number(
338 'Parent\n'
339 '\n'
340 'Cr-Commit-Position: refs/heads/master@{#12}',
341 dest_ref='refs/heads/master',
342 child_msg='Child')
343 self.assertEqualByLine(
344 actual,
345 'Child\n'
346 '\n'
347 'Cr-Commit-Position: refs/heads/master@{#13}')
348
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200349 def test_git_number_same_branch_mixed_footers(self):
350 actual = self._test_git_number(
351 'Parent\n'
352 '\n'
353 'Cr-Commit-Position: refs/heads/master@{#12}',
354 dest_ref='refs/heads/master',
355 child_msg='Child\n'
356 '\n'
357 'Broken-by: design\n'
358 'BUG=123')
359 self.assertEqualByLine(
360 actual,
361 'Child\n'
362 '\n'
363 'Broken-by: design\n'
364 'BUG=123\n'
365 'Cr-Commit-Position: refs/heads/master@{#13}')
366
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100367 def test_git_number_same_branch_with_originals(self):
368 actual = self._test_git_number(
369 'Parent\n'
370 '\n'
371 'Cr-Commit-Position: refs/heads/master@{#12}',
372 dest_ref='refs/heads/master',
373 child_msg='Child\n'
374 '\n'
375 'Some users are smart and insert their own footers\n'
376 '\n'
377 'Cr-Whatever: value\n'
378 'Cr-Commit-Position: refs/copy/paste@{#22}')
379 self.assertEqualByLine(
380 actual,
381 'Child\n'
382 '\n'
383 'Some users are smart and insert their own footers\n'
384 '\n'
385 'Cr-Original-Whatever: value\n'
386 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
387 'Cr-Commit-Position: refs/heads/master@{#13}')
388
389 def test_git_number_new_branch(self):
390 actual = self._test_git_number(
391 'Parent\n'
392 '\n'
393 'Cr-Commit-Position: refs/heads/master@{#12}',
394 dest_ref='refs/heads/branch',
395 child_msg='Child')
396 self.assertEqualByLine(
397 actual,
398 'Child\n'
399 '\n'
400 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
401 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
402
403 def test_git_number_lineage(self):
404 actual = self._test_git_number(
405 'Parent\n'
406 '\n'
407 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
408 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
409 dest_ref='refs/heads/branch',
410 child_msg='Child')
411 self.assertEqualByLine(
412 actual,
413 'Child\n'
414 '\n'
415 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
416 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
417
418 def test_git_number_moooooooore_lineage(self):
419 actual = self._test_git_number(
420 'Parent\n'
421 '\n'
422 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
423 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
424 dest_ref='refs/heads/mooore',
425 child_msg='Child')
426 self.assertEqualByLine(
427 actual,
428 'Child\n'
429 '\n'
430 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
431 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
432 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
433
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100434 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700435 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100436 actual = self._test_git_number(
437 'CQ commit on fresh new branch + numbering.\n'
438 '\n'
439 'NOTRY=True\n'
440 'NOPRESUBMIT=True\n'
441 'BUG=\n'
442 '\n'
443 'Review-Url: https://codereview.chromium.org/2577703003\n'
444 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
445 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
446 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
447 dest_ref='refs/heads/gnumb-test/cl',
448 child_msg='git cl on fresh new branch + numbering.\n'
449 '\n'
450 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
451 self.assertEqualByLine(
452 actual,
453 'git cl on fresh new branch + numbering.\n'
454 '\n'
455 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
456 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
457 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
458 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
459 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100460
461 def test_git_number_cherry_pick(self):
462 actual = self._test_git_number(
463 'Parent\n'
464 '\n'
465 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
466 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
467 dest_ref='refs/heads/branch',
468 child_msg='Child, which is cherry-pick from master\n'
469 '\n'
470 'Cr-Commit-Position: refs/heads/master@{#100}\n'
471 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
472 self.assertEqualByLine(
473 actual,
474 'Child, which is cherry-pick from master\n'
475 '\n'
476 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
477 '\n'
478 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
479 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
480 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
481
Edward Lemurda4b6c62020-02-13 00:28:40 +0000482 @mock.patch('gerrit_util.GetAccountDetails')
483 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000484 mock_per_account = {
485 'u1': None, # 404, doesn't exist.
486 'u2': {
487 '_account_id': 123124,
488 'avatars': [],
489 'email': 'u2@example.com',
490 'name': 'User Number 2',
491 'status': 'OOO',
492 },
493 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
494 }
495 def GetAccountDetailsMock(_, account):
496 # Poor-man's mock library's side_effect.
497 v = mock_per_account.pop(account)
498 if isinstance(v, Exception):
499 raise v
500 return v
501
Edward Lemurda4b6c62020-02-13 00:28:40 +0000502 mockGetAccountDetails.side_effect = GetAccountDetailsMock
503 actual = git_cl.gerrit_util.ValidAccounts(
504 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000505 self.assertEqual(actual, {
506 'u2': {
507 '_account_id': 123124,
508 'avatars': [],
509 'email': 'u2@example.com',
510 'name': 'User Number 2',
511 'status': 'OOO',
512 },
513 })
514
515
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200516class TestParseIssueURL(unittest.TestCase):
517 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000518 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200519 self.assertIsNotNone(parsed)
520 if fail:
521 self.assertFalse(parsed.valid)
522 return
523 self.assertTrue(parsed.valid)
524 self.assertEqual(parsed.issue, issue)
525 self.assertEqual(parsed.patchset, patchset)
526 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200527
Edward Lemur678a6842019-10-03 22:25:05 +0000528 def test_ParseIssueNumberArgument(self):
529 def test(arg, *args, **kwargs):
530 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200531
Edward Lemur678a6842019-10-03 22:25:05 +0000532 test('123', 123)
533 test('', fail=True)
534 test('abc', fail=True)
535 test('123/1', fail=True)
536 test('123a', fail=True)
537 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200538
Edward Lemur678a6842019-10-03 22:25:05 +0000539 test('https://codereview.source.com/123',
540 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200541 test('http://chrome-review.source.com/c/123',
542 123, None, 'chrome-review.source.com')
543 test('https://chrome-review.source.com/c/123/',
544 123, None, 'chrome-review.source.com')
545 test('https://chrome-review.source.com/c/123/4',
546 123, 4, 'chrome-review.source.com')
547 test('https://chrome-review.source.com/#/c/123/4',
548 123, 4, 'chrome-review.source.com')
549 test('https://chrome-review.source.com/c/123/4',
550 123, 4, 'chrome-review.source.com')
551 test('https://chrome-review.source.com/123',
552 123, None, 'chrome-review.source.com')
553 test('https://chrome-review.source.com/123/4',
554 123, 4, 'chrome-review.source.com')
555
Edward Lemur678a6842019-10-03 22:25:05 +0000556 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200557 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
558 test('https://chrome-review.source.com/c/abc/', fail=True)
559 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
560
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200561
562
Edward Lemurda4b6c62020-02-13 00:28:40 +0000563class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100564 def setUp(self):
565 super(GitCookiesCheckerTest, self).setUp()
566 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100567 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000568 mock.patch('sys.stdout', StringIO()).start()
569 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100570
571 def mock_hosts_creds(self, subhost_identity_pairs):
572 def ensure_googlesource(h):
573 if not h.endswith(self.c._GOOGLESOURCE):
574 assert not h.endswith('.')
575 return h + '.' + self.c._GOOGLESOURCE
576 return h
577 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
578 for h, i in subhost_identity_pairs]
579
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200580 def test_identity_parsing(self):
581 self.assertEqual(self.c._parse_identity('ldap.google.com'),
582 ('ldap', 'google.com'))
583 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
584 ('ldap', 'example.com'))
585 # Specical case because we know there are no subdomains in chromium.org.
586 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
587 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800588 # Pathological: ".period." can be either username OR domain, more likely
589 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200590 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
591 ('note', 'period.example.com'))
592
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100593 def test_analysis_nothing(self):
594 self.c._all_hosts = []
595 self.assertFalse(self.c.has_generic_host())
596 self.assertEqual(set(), self.c.get_conflicting_hosts())
597 self.assertEqual(set(), self.c.get_duplicated_hosts())
598 self.assertEqual(set(), self.c.get_partially_configured_hosts())
599 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
600
601 def test_analysis(self):
602 self.mock_hosts_creds([
603 ('.googlesource.com', 'git-example.chromium.org'),
604
605 ('chromium', 'git-example.google.com'),
606 ('chromium-review', 'git-example.google.com'),
607 ('chrome-internal', 'git-example.chromium.org'),
608 ('chrome-internal-review', 'git-example.chromium.org'),
609 ('conflict', 'git-example.google.com'),
610 ('conflict-review', 'git-example.chromium.org'),
611 ('dup', 'git-example.google.com'),
612 ('dup', 'git-example.google.com'),
613 ('dup-review', 'git-example.google.com'),
614 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200615 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100616 ])
617 self.assertTrue(self.c.has_generic_host())
618 self.assertEqual(set(['conflict.googlesource.com']),
619 self.c.get_conflicting_hosts())
620 self.assertEqual(set(['dup.googlesource.com']),
621 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200622 self.assertEqual(set(['partial.googlesource.com',
623 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100624 self.c.get_partially_configured_hosts())
625 self.assertEqual(set(['chromium.googlesource.com',
626 'chrome-internal.googlesource.com']),
627 self.c.get_hosts_with_wrong_identities())
628
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100629 def test_report_no_problems(self):
630 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100631 self.assertFalse(self.c.find_and_report_problems())
632 self.assertEqual(sys.stdout.getvalue(), '')
633
Edward Lemurda4b6c62020-02-13 00:28:40 +0000634 @mock.patch(
635 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
636 return_value='~/.gitcookies')
637 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100638 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100639 self.assertTrue(self.c.find_and_report_problems())
640 with open(os.path.join(os.path.dirname(__file__),
641 'git_cl_creds_check_report.txt')) as f:
642 expected = f.read()
643 def by_line(text):
644 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700645 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200646 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100647
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800648
Edward Lemurda4b6c62020-02-13 00:28:40 +0000649class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000650 def setUp(self):
651 super(TestGitCl, self).setUp()
652 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700653 self._calls_done = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000654 mock.patch('sys.stdout', StringIO()).start()
655 mock.patch(
656 'git_cl.time_time',
657 lambda: self._mocked_call('time.time')).start()
658 mock.patch(
659 'git_cl.metrics.collector.add_repeated',
660 lambda *a: self._mocked_call('add_repeated', *a)).start()
661 mock.patch('subprocess2.call', self._mocked_call).start()
662 mock.patch('subprocess2.check_call', self._mocked_call).start()
663 mock.patch('subprocess2.check_output', self._mocked_call).start()
664 mock.patch(
665 'subprocess2.communicate',
666 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
667 mock.patch(
668 'git_cl.gclient_utils.CheckCallAndFilter',
669 self._mocked_call).start()
670 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
671 mock.patch(
672 'git_common.get_or_create_merge_base',
673 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
674 mock.patch('git_cl.BranchExists', return_value=True).start()
675 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
676 mock.patch(
677 'git_cl.SaveDescriptionBackup',
678 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
679 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000680 'git_cl.write_json',
681 lambda *a: self._mocked_call('write_json', *a)).start()
682 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000683 'git_cl.Changelist.RunHook',
684 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000685 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
686 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000687 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000688 mock.patch(
689 'git_cl.gerrit_util.GetChangeComments',
690 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
691 mock.patch(
692 'git_cl.gerrit_util.GetChangeRobotComments',
693 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
694 mock.patch(
695 'git_cl.gerrit_util.AddReviewers',
696 lambda *a: self._mocked_call('AddReviewers', *a)).start()
697 mock.patch(
698 'git_cl.gerrit_util.SetReview',
699 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
700 self._mocked_call(
701 'SetReview', h, i, msg, labels, notify, ready))).start()
702 mock.patch(
703 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
704 return_value=False).start()
705 mock.patch(
706 'git_cl.gerrit_util.GceAuthenticator.is_gce',
707 return_value=False).start()
708 mock.patch(
709 'git_cl.gerrit_util.ValidAccounts',
710 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000711 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000712 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000713 self.mockGit = GitMocks()
714 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
715 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
716 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000717 mock.patch(
718 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000719 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000720 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000721 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000722 mock.patch(
723 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000724 # It's important to reset settings to not have inter-tests interference.
725 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000726 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000727
728 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000729 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000730 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100731 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000732 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
733 if len(self.calls) > 5:
734 calls += ' ...\n'
735 self.fail(
736 '\n'
737 'There are un-consumed calls after this test has finished:\n' +
738 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000739 finally:
740 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000741
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000742 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000743 self.assertTrue(
744 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700745 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000746 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000747 expected_args, result = top
748
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000749 # Also logs otherwise it could get caught in a try/finally and be hard to
750 # diagnose.
751 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700752 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000753 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700754 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
755 for i, c in enumerate(self._calls_done[-N:]))
756 following_calls = '\n '.join(
757 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
758 for i, c in enumerate(self.calls[:N]))
759 extended_msg = (
760 'A few prior calls:\n %s\n\n'
761 'This (expected):\n @%d: %r\n'
762 'This (actual):\n @%d: %r\n\n'
763 'A few following expected calls:\n %s' %
764 (prior_calls, len(self._calls_done), expected_args,
765 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700766
tandrii99a72f22016-08-17 14:33:24 -0700767 self.fail('@%d\n'
768 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000769 ' Actual: %r\n'
770 '\n'
771 '%s' % (
772 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700773
774 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700775 if isinstance(result, Exception):
776 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000777 # stdout from git commands is supposed to be a bytestream. Convert it here
778 # instead of converting all test output in this file to bytes.
779 if args[0][0] == 'git' and not isinstance(result, bytes):
780 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000781 return result
782
Edward Lemur1a83da12020-03-04 21:18:36 +0000783 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
784 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100785 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100786 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000787 self.assertEqual(
788 'prompt [Yes/No]: Please, type yes or no: ',
789 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100790
tandrii48df5812016-10-17 03:55:37 -0700791 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000792 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700793 self.calls = [
794 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700795 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
796 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
797 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
798 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700799 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
800 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700801 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
802 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000803 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
804 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700805 ((['git', 'config', 'gerrit.host', 'true'],), ''),
806 ]
807 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
808
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000809 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100810 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200811 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000812 custom_cl_base=None, short_hostname='chromium',
813 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000814 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200815 if custom_cl_base:
816 ancestor_revision = custom_cl_base
817 else:
818 # Determine ancestor_revision to be merge base.
819 ancestor_revision = 'fake_ancestor_sha'
820 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000821 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
822 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200823 ]
824
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100825 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000826 gerrit_util.GetChangeDetail.return_value = {
827 'owner': {'email': (other_cl_owner or 'owner@example.com')},
828 'change_id': (change_id or '123456789'),
829 'current_revision': 'sha1_of_current_revision',
830 'revisions': {'sha1_of_current_revision': {
831 'commit': {'message': fetched_description},
832 }},
833 'status': fetched_status or 'NEW',
834 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100835 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100836 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100837 if other_cl_owner:
838 calls += [
839 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
840 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100841
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100842 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200843 ((['git', 'rev-parse', 'HEAD'],), '12345'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100844 ]
845
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100846 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200847 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
848 ([custom_cl_base] if custom_cl_base else
849 [ancestor_revision, 'HEAD']),),
850 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100851 ]
852 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000853
Edward Lemur26964072020-02-19 19:18:51 +0000854 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700855 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000856 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700857 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100858 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000859 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000860 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000861 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000862 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000863 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000864 if post_amend_description is None:
865 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700866 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200867
868 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000869
Edward Lemur26964072020-02-19 19:18:51 +0000870 if squash_mode in ('override_squash', 'override_nosquash'):
871 self.mockGit.config['gerrit.override-squash-uploads'] = (
872 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700873
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000874 # If issue is given, then description is fetched from Gerrit instead.
875 if issue is None:
Aaron Gableb56ad332017-01-06 15:24:31 -0800876 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000877 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800878 else:
879 if not title:
880 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200881 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
882 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800883 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000884 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000885 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000886 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200887 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200888 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000889 if squash:
Edward Lemur5fb22242020-03-12 22:05:13 +0000890 if not force and not issue:
891 calls += [
892 ((['RunEditor'],), description),
893 ]
Josipe827b0f2020-01-30 00:07:20 +0000894 # user wants to edit description
895 if edit_description:
896 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000897 ((['RunEditor'],), edit_description),
898 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000899 ref_to_push = 'abcdef0123456789'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200900
901 if custom_cl_base is None:
902 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000903 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000904 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200905 ]
906 parent = 'origin/master'
907 else:
908 calls += [
909 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
910 'refs/remotes/origin/master'],),
911 callError(1)), # Means not ancenstor.
912 (('ask_for_data',
913 'Do you take responsibility for cleaning up potential mess '
914 'resulting from proceeding with upload? Press Enter to upload, '
915 'or Ctrl+C to abort'), ''),
916 ]
917 parent = custom_cl_base
918
919 calls += [
920 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
921 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000922 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200923 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000924 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200925 ref_to_push),
926 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000927 else:
928 ref_to_push = 'HEAD'
929
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000930 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000931 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200932 ((['git', 'rev-list',
933 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
934 ref_to_push],),
935 '1hashPerLine\n'),
936 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000937
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000938 metrics_arguments = []
939
Aaron Gableafd52772017-06-27 16:40:10 -0700940 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700941 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000942 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700943 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400944 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700945 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000946 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700947 else:
948 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000949 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800950
Aaron Gable70f4e242017-06-26 10:45:59 -0700951 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700952 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000953 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000954
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000955 if short_hostname == 'chromium':
956 # All reviwers and ccs get into ref_suffix.
957 for r in sorted(reviewers):
958 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000959 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000960 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000961 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000962 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000963 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000964 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000965 reviewers, cc = [], []
966 else:
967 # TODO(crbug/877717): remove this case.
968 calls += [
969 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
970 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000971 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000972 {
973 e: {'email': e}
974 for e in (reviewers + ['joe@example.com'] + cc)
975 })
976 ]
977 for r in sorted(reviewers):
978 if r != 'bad-account-or-email':
979 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000980 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000981 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000982 if issue is None:
983 cc += ['joe@example.com']
984 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000985 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000986 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000987 if c in cc:
988 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000989
Edward Lemur687ca902018-12-05 02:30:30 +0000990 for k, v in sorted((labels or {}).items()):
991 ref_suffix += ',l=%s+%d' % (k, v)
992 metrics_arguments.append('l=%s+%d' % (k, v))
993
994 if tbr:
995 calls += [
996 (('GetCodeReviewTbrScore',
997 '%s-review.googlesource.com' % short_hostname,
998 'my/repo'),
999 2,),
1000 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001001
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001002 calls += [
1003 (('time.time',), 1000,),
1004 ((['git', 'push',
1005 'https://%s.googlesource.com/my/repo' % short_hostname,
1006 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1007 (('remote:\n'
1008 'remote: Processing changes: (\)\n'
1009 'remote: Processing changes: (|)\n'
1010 'remote: Processing changes: (/)\n'
1011 'remote: Processing changes: (-)\n'
1012 'remote: Processing changes: new: 1 (/)\n'
1013 'remote: Processing changes: new: 1, done\n'
1014 'remote:\n'
1015 'remote: New Changes:\n'
1016 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1017 ' XXX\n'
1018 'remote:\n'
1019 'To https://%s.googlesource.com/my/repo\n'
1020 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1021 ) % (short_hostname, short_hostname)),),
1022 (('time.time',), 2000,),
1023 (('add_repeated',
1024 'sub_commands',
1025 {
1026 'execution_time': 1000,
1027 'command': 'git push',
1028 'exit_code': 0,
1029 'arguments': sorted(metrics_arguments),
1030 }),
1031 None,),
1032 ]
1033
Edward Lemur1b52d872019-05-09 21:12:12 +00001034 final_description = final_description or post_amend_description.strip()
1035 original_title = original_title or title or '<untitled>'
1036 # Trace-related calls
1037 calls += [
1038 # Write a description with context for the current trace.
1039 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001040 'Thu Mar 16 20:00:41 2017\n'
1041 '%(short_hostname)s-review.googlesource.com\n'
1042 '%(change_id)s\n'
1043 '%(title)s\n'
1044 '%(description)s\n'
1045 '1000\n'
1046 '0\n'
1047 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001048 'short_hostname': short_hostname,
1049 'change_id': change_id,
1050 'description': final_description,
1051 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001052 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001053 }],),
1054 None,
1055 ),
1056 # Read traces and shorten git hashes.
1057 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1058 True,
1059 ),
1060 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1061 ('git-hash: 0123456789012345678901234567890123456789\n'
1062 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1063 ),
1064 ((['FileWrite', 'TEMP_DIR/trace-packet',
1065 'git-hash: 012345\n'
1066 'git-hash: abcdea\n'],),
1067 None,
1068 ),
1069 # Make zip file for the git traces.
1070 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1071 'TEMP_DIR'],),
1072 None,
1073 ),
1074 # Collect git config and gitcookies.
1075 ((['git', 'config', '-l'],),
1076 'git-config-output',
1077 ),
1078 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1079 None,
1080 ),
1081 ((['os.path.isfile', '~/.gitcookies'],),
1082 gitcookies_exists,
1083 ),
1084 ]
1085 if gitcookies_exists:
1086 calls += [
1087 ((['FileRead', '~/.gitcookies'],),
1088 'gitcookies 1/SECRET',
1089 ),
1090 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1091 None,
1092 ),
1093 ]
1094 calls += [
1095 # Make zip file for the git config and gitcookies.
1096 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1097 'TEMP_DIR'],),
1098 None,
1099 ),
1100 ]
1101
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001102 # TODO(crbug/877717): this should never be used.
1103 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001104 calls += [
1105 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001106 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001107 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001108 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001109 notify),
1110 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001111 ]
Edward Lemur26964072020-02-19 19:18:51 +00001112 calls += [
1113 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1114 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001115 return calls
1116
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001117 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001118 self,
1119 upload_args,
1120 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001121 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001122 squash=True,
1123 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001124 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001125 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001126 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001127 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001128 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001129 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001130 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001131 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001132 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001133 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001134 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001135 labels=None,
1136 change_id=None,
1137 original_title=None,
1138 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001139 gitcookies_exists=True,
1140 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001141 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001142 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001143 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001144 if squash_mode is None:
1145 if '--no-squash' in upload_args:
1146 squash_mode = 'nosquash'
1147 elif '--squash' in upload_args:
1148 squash_mode = 'squash'
1149 else:
1150 squash_mode = 'default'
1151
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001152 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001153 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001154 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001155 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001156 same_auth=('git-owner.example.com', '', 'pass'))).start()
1157 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1158 lambda _, offer_removal: None).start()
1159 mock.patch('git_cl.gclient_utils.RunEditor',
1160 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1161 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1162 'DownloadGerritHook', force)).start()
1163 mock.patch('git_cl.gclient_utils.FileRead',
1164 lambda path: self._mocked_call(['FileRead', path])).start()
1165 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001166 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001167 ['FileWrite', path, contents])).start()
1168 mock.patch('git_cl.datetime_now',
1169 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1170 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1171 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1172 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001173 '%(now)s\n'
1174 '%(gerrit_host)s\n'
1175 '%(change_id)s\n'
1176 '%(title)s\n'
1177 '%(description)s\n'
1178 '%(execution_time)s\n'
1179 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001180 '%(trace_name)s').start()
1181 mock.patch('git_cl.shutil.make_archive',
1182 lambda *args: self._mocked_call(['make_archive'] +
1183 list(args))).start()
1184 mock.patch('os.path.isfile',
1185 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001186 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001187 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00001188 'git_cl._create_description_from_log', return_value=description).start()
1189 mock.patch(
1190 'git_cl.Changelist._AddChangeIdToCommitMessage',
1191 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001192 mock.patch(
1193 'git_cl.ask_for_data',
1194 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001195
Edward Lemur26964072020-02-19 19:18:51 +00001196 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001197 self.mockGit.config['branch.master.gerritissue'] = (
1198 str(issue) if issue else None)
1199 self.mockGit.config['remote.origin.url'] = (
1200 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001201 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001202
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001203 self.calls = self._gerrit_base_calls(
1204 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001205 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001206 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001207 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001208 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001209 short_hostname=short_hostname,
1210 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001211 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001212 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001213 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001214 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001215 self.calls += self._gerrit_upload_calls(
1216 description, reviewers, squash,
1217 squash_mode=squash_mode,
1218 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001219 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001220 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001221 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001222 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001223 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001224 labels=labels,
1225 change_id=change_id,
1226 original_title=original_title,
1227 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001228 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001229 force=force,
1230 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001231 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001232 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001233 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001234 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001235 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001236 self.assertEqual(
1237 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001238 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001239
Edward Lemur1b52d872019-05-09 21:12:12 +00001240 def test_gerrit_upload_traces_no_gitcookies(self):
1241 self._run_gerrit_upload_test(
1242 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001243 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001244 [],
1245 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001246 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001247 change_id='Ixxx',
1248 gitcookies_exists=False)
1249
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001250 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001251 self._run_gerrit_upload_test(
1252 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001253 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001254 [],
1255 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001256 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001257 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001258
1259 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001260 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001261 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001262 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001263 [],
tandriia60502f2016-06-20 02:01:53 -07001264 squash=False,
1265 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001266 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001267 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001268
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001269 def test_gerrit_no_reviewer(self):
1270 self._run_gerrit_upload_test(
1271 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001272 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001273 [],
1274 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001275 squash_mode='override_nosquash',
1276 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001277
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001278 def test_gerrit_no_reviewer_non_chromium_host(self):
1279 # TODO(crbug/877717): remove this test case.
1280 self._run_gerrit_upload_test(
1281 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001282 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001283 [],
1284 squash=False,
1285 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001286 short_hostname='other',
1287 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001288
Nick Carter8692b182017-11-06 16:30:38 -08001289 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001290 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001291 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001292 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001293 squash=False,
1294 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001295 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1296 change_id='I123456789',
1297 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001298
ukai@chromium.orge8077812012-02-03 03:41:46 +00001299 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001300 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001301 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001302 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001303 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001304 squash=False,
1305 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001306 notify=True,
1307 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001308 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001309 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001310
Anthony Polito8b955342019-09-24 19:01:36 +00001311 def test_gerrit_upload_force_sets_bug(self):
1312 self._run_gerrit_upload_test(
1313 ['-b', '10000', '-f'],
1314 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1315 [],
1316 force=True,
1317 expected_upstream_ref='origin/master',
1318 fetched_description='desc=\n\nChange-Id: Ixxx',
1319 original_title='Initial upload',
1320 change_id='Ixxx')
1321
Edward Lemur5fb22242020-03-12 22:05:13 +00001322 def test_gerrit_upload_corrects_wrong_change_id(self):
Anthony Polito8b955342019-09-24 19:01:36 +00001323 self._run_gerrit_upload_test(
Edward Lemur5fb22242020-03-12 22:05:13 +00001324 ['-b', '10000', '-m', 'Title', '--edit-description'],
1325 u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
Anthony Polito8b955342019-09-24 19:01:36 +00001326 [],
Anthony Polito8b955342019-09-24 19:01:36 +00001327 issue='123456',
1328 expected_upstream_ref='origin/master',
Edward Lemur5fb22242020-03-12 22:05:13 +00001329 edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
Anthony Polito8b955342019-09-24 19:01:36 +00001330 fetched_description='desc=\n\nChange-Id: Ixxxx',
1331 original_title='Title',
1332 title='Title',
Edward Lemur5fb22242020-03-12 22:05:13 +00001333 change_id='Ixxxx')
Anthony Polito8b955342019-09-24 19:01:36 +00001334
Dan Beamd8b04ca2019-10-10 21:23:26 +00001335 def test_gerrit_upload_force_sets_fixed(self):
1336 self._run_gerrit_upload_test(
1337 ['-x', '10000', '-f'],
1338 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1339 [],
1340 force=True,
1341 expected_upstream_ref='origin/master',
1342 fetched_description='desc=\n\nChange-Id: Ixxx',
1343 original_title='Initial upload',
1344 change_id='Ixxx')
1345
ukai@chromium.orge8077812012-02-03 03:41:46 +00001346 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001347 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1348 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001349 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001350 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001351 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001352 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001353 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001354 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001355 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001356 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001357 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001358 labels={'Code-Review': 2},
1359 change_id='123456789',
1360 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001361
1362 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001363 self._run_gerrit_upload_test(
1364 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001365 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001366 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001367 expected_upstream_ref='origin/master',
1368 change_id='123456789',
1369 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001370
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001371 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001372 self._run_gerrit_upload_test(
1373 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001374 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001375 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001376 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001377 expected_upstream_ref='origin/master',
1378 change_id='123456789',
1379 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001380
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001381 def test_gerrit_upload_squash_first_with_labels(self):
1382 self._run_gerrit_upload_test(
1383 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001384 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001385 [],
1386 squash=True,
1387 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001388 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1389 change_id='123456789',
1390 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001391
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001392 def test_gerrit_upload_squash_first_against_rev(self):
1393 custom_cl_base = 'custom_cl_base_rev_or_branch'
1394 self._run_gerrit_upload_test(
1395 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001396 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001397 [],
1398 squash=True,
1399 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001400 custom_cl_base=custom_cl_base,
1401 change_id='123456789',
1402 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001403 self.assertIn(
1404 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1405 sys.stdout.getvalue())
1406
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001407 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001408 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001409 self._run_gerrit_upload_test(
1410 ['--squash'],
1411 description,
1412 [],
1413 squash=True,
1414 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001415 issue=123456,
1416 change_id='123456789',
1417 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001418
Edward Lemurd55c5072020-02-20 01:09:07 +00001419 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001420 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001421 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001422 with self.assertRaises(SystemExitMock):
1423 self._run_gerrit_upload_test(
1424 ['--squash'],
1425 description,
1426 [],
1427 squash=True,
1428 expected_upstream_ref='origin/master',
1429 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001430 fetched_status='ABANDONED',
1431 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001432 self.assertEqual(
1433 'Change https://chromium-review.googlesource.com/123456 has been '
1434 'abandoned, new uploads are not allowed\n',
1435 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001436
Edward Lemurda4b6c62020-02-13 00:28:40 +00001437 @mock.patch(
1438 'gerrit_util.GetAccountDetails',
1439 return_value={'email': 'yet-another@example.com'})
1440 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001441 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001442 self._run_gerrit_upload_test(
1443 ['--squash'],
1444 description,
1445 [],
1446 squash=True,
1447 expected_upstream_ref='origin/master',
1448 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001449 other_cl_owner='other@example.com',
1450 change_id='123456789',
1451 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001452 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001453 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001454 'authenticate to Gerrit as yet-another@example.com.\n'
1455 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001456 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001457
Josipe827b0f2020-01-30 00:07:20 +00001458 def test_upload_change_description_editor(self):
1459 fetched_description = 'foo\n\nChange-Id: 123456789'
1460 description = 'bar\n\nChange-Id: 123456789'
1461 self._run_gerrit_upload_test(
1462 ['--squash', '--edit-description'],
1463 description,
1464 [],
1465 fetched_description=fetched_description,
1466 squash=True,
1467 expected_upstream_ref='origin/master',
1468 issue=123456,
1469 change_id='123456789',
1470 original_title='User input',
1471 edit_description=description)
1472
Edward Lemurda4b6c62020-02-13 00:28:40 +00001473 @mock.patch('git_cl.RunGit')
1474 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001475 @mock.patch('sys.stdin', StringIO('\n'))
1476 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001477 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))
Edward Lemur1a83da12020-03-04 21:18:36 +00001514 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001515 'This command will checkout all dependent branches '
1516 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001517 'or Ctrl+C to abort',
1518 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001519 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001520
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001521 def test_gerrit_change_id(self):
1522 self.calls = [
1523 ((['git', 'write-tree'], ),
1524 'hashtree'),
1525 ((['git', 'rev-parse', 'HEAD~0'], ),
1526 'branch-parent'),
1527 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1528 'A B <a@b.org> 1456848326 +0100'),
1529 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1530 'C D <c@d.org> 1456858326 +0100'),
1531 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1532 'hashchange'),
1533 ]
1534 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1535 self.assertEqual(change_id, 'Ihashchange')
1536
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001537 def test_desecription_append_footer(self):
1538 for init_desc, footer_line, expected_desc in [
1539 # Use unique desc first lines for easy test failure identification.
1540 ('foo', 'R=one', 'foo\n\nR=one'),
1541 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1542 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1543 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1544 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1545 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1546 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1547 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1548 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1549 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1550 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1551 ]:
1552 desc = git_cl.ChangeDescription(init_desc)
1553 desc.append_footer(footer_line)
1554 self.assertEqual(desc.description, expected_desc)
1555
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001556 def test_update_reviewers(self):
1557 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001558 ('foo', [], [],
1559 'foo'),
1560 ('foo\nR=xx', [], [],
1561 'foo\nR=xx'),
1562 ('foo\nTBR=xx', [], [],
1563 'foo\nTBR=xx'),
1564 ('foo', ['a@c'], [],
1565 'foo\n\nR=a@c'),
1566 ('foo\nR=xx', ['a@c'], [],
1567 'foo\n\nR=a@c, xx'),
1568 ('foo\nTBR=xx', ['a@c'], [],
1569 'foo\n\nR=a@c\nTBR=xx'),
1570 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1571 'foo\n\nR=a@c, yy\nTBR=xx'),
1572 ('foo\nBUG=', ['a@c'], [],
1573 'foo\nBUG=\nR=a@c'),
1574 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1575 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1576 ('foo', ['a@c', 'b@c'], [],
1577 'foo\n\nR=a@c, b@c'),
1578 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1579 'foo\nBar\n\nR=c@c\nBUG='),
1580 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1581 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001582 # Same as the line before, but full of whitespaces.
1583 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001584 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001585 'foo\nBar\n\nR=c@c\n BUG =',
1586 ),
1587 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001588 ('foo BUG=allo R=joe ', ['c@c'], [],
1589 'foo BUG=allo R=joe\n\nR=c@c'),
1590 # Redundant TBRs get promoted to Rs
1591 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1592 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001593 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001594 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001595 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001596 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001597 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001598 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001599 actual.append(obj.description)
1600 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001601
Nodir Turakulov23b82142017-11-16 11:04:25 -08001602 def test_get_hash_tags(self):
1603 cases = [
1604 ('', []),
1605 ('a', []),
1606 ('[a]', ['a']),
1607 ('[aa]', ['aa']),
1608 ('[a ]', ['a']),
1609 ('[a- ]', ['a']),
1610 ('[a- b]', ['a-b']),
1611 ('[a--b]', ['a-b']),
1612 ('[a', []),
1613 ('[a]x', ['a']),
1614 ('[aa]x', ['aa']),
1615 ('[a b]', ['a-b']),
1616 ('[a b]', ['a-b']),
1617 ('[a__b]', ['a-b']),
1618 ('[a] x', ['a']),
1619 ('[a][b]', ['a', 'b']),
1620 ('[a] [b]', ['a', 'b']),
1621 ('[a][b]x', ['a', 'b']),
1622 ('[a][b] x', ['a', 'b']),
1623 ('[a]\n[b]', ['a']),
1624 ('[a\nb]', []),
1625 ('[a][', ['a']),
1626 ('Revert "[a] feature"', ['a']),
1627 ('Reland "[a] feature"', ['a']),
1628 ('Revert: [a] feature', ['a']),
1629 ('Reland: [a] feature', ['a']),
1630 ('Revert "Reland: [a] feature"', ['a']),
1631 ('Foo: feature', ['foo']),
1632 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001633 ('Change Foo::Bar', []),
1634 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001635 ('Revert "Foo bar: feature"', ['foo-bar']),
1636 ('Reland "Foo bar: feature"', ['foo-bar']),
1637 ]
1638 for desc, expected in cases:
1639 change_desc = git_cl.ChangeDescription(desc)
1640 actual = change_desc.get_hash_tags()
1641 self.assertEqual(
1642 actual,
1643 expected,
1644 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1645
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001646 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001647 self.assertEqual(None, git_cl.GetTargetRef(None,
1648 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001649 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001650
wittman@chromium.org455dc922015-01-26 20:15:50 +00001651 # Check default target refs for branches.
1652 self.assertEqual('refs/heads/master',
1653 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001654 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001655 self.assertEqual('refs/heads/master',
1656 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001657 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001658 self.assertEqual('refs/heads/master',
1659 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001660 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001661 self.assertEqual('refs/branch-heads/123',
1662 git_cl.GetTargetRef('origin',
1663 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001664 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001665 self.assertEqual('refs/diff/test',
1666 git_cl.GetTargetRef('origin',
1667 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001668 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001669 self.assertEqual('refs/heads/chrome/m42',
1670 git_cl.GetTargetRef('origin',
1671 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001672 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001673
1674 # Check target refs for user-specified target branch.
1675 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1676 'refs/remotes/branch-heads/123'):
1677 self.assertEqual('refs/branch-heads/123',
1678 git_cl.GetTargetRef('origin',
1679 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001680 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001681 for branch in ('origin/master', 'remotes/origin/master',
1682 'refs/remotes/origin/master'):
1683 self.assertEqual('refs/heads/master',
1684 git_cl.GetTargetRef('origin',
1685 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001686 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001687 for branch in ('master', 'heads/master', 'refs/heads/master'):
1688 self.assertEqual('refs/heads/master',
1689 git_cl.GetTargetRef('origin',
1690 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001691 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001692
Edward Lemurda4b6c62020-02-13 00:28:40 +00001693 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1694 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001695 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001696 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1697
Edward Lemur85153282020-02-14 22:06:29 +00001698 def assertIssueAndPatchset(
1699 self, branch='master', issue='123456', patchset='7',
1700 git_short_host='chromium'):
1701 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001702 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001703 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001704 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001705 self.assertEqual(
1706 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001707 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001708
Edward Lemur85153282020-02-14 22:06:29 +00001709 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001710 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001711 self.mockGit.config['remote.origin.url'] = (
1712 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001713 gerrit_util.GetChangeDetail.return_value = {
1714 'current_revision': '7777777777',
1715 'revisions': {
1716 '1111111111': {
1717 '_number': 1,
1718 'fetch': {'http': {
1719 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1720 'ref': 'refs/changes/56/123456/1',
1721 }},
1722 },
1723 '7777777777': {
1724 '_number': 7,
1725 'fetch': {'http': {
1726 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1727 'ref': 'refs/changes/56/123456/7',
1728 }},
1729 },
1730 },
1731 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001732
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001733 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001734 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001735 self.calls += [
1736 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1737 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001738 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001739 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001740 ]
1741 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001742 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001743
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001744 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001745 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001746 self.calls += [
1747 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1748 'refs/changes/56/123456/7'],), ''),
1749 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001750 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001751 ]
Edward Lemur85153282020-02-14 22:06:29 +00001752 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1753 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001754
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001755 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001756 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001757 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001758 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001759 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001760 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001761 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001762 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001763 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001764 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001765
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001766 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001767 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001768 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001769 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001770 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001771 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001772 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001773 ]
1774 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001775 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001776 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001777
Aaron Gable697a91b2018-01-19 15:20:15 -08001778 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001779 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001780 self.calls += [
1781 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1782 'refs/changes/56/123456/1'],), ''),
1783 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001784 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001785 ]
1786 self.assertEqual(git_cl.main(
1787 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1788 0)
Edward Lemur85153282020-02-14 22:06:29 +00001789 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001790
Edward Lemurd55c5072020-02-20 01:09:07 +00001791 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001792 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001793 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001794 self.calls += [
1795 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001796 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001797 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001798 ]
1799 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001800 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001801 self.assertEqual(
1802 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1803 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001804
Edward Lemurda4b6c62020-02-13 00:28:40 +00001805 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001806 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001807 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001808 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001809 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001810 self.mockGit.config['remote.origin.url'] = (
1811 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001812 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001813 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001814 self.assertEqual(
1815 'change 123456 at https://chromium-review.googlesource.com does not '
1816 'exist or you have no access to it\n',
1817 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001818
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001819 def _checkout_calls(self):
1820 return [
1821 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001822 'branch\\..*\\.gerritissue'], ),
1823 ('branch.ger-branch.gerritissue 123456\n'
1824 'branch.gbranch654.gerritissue 654321\n')),
1825 ]
1826
1827 def test_checkout_gerrit(self):
1828 """Tests git cl checkout <issue>."""
1829 self.calls = self._checkout_calls()
1830 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1831 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1832
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001833 def test_checkout_not_found(self):
1834 """Tests git cl checkout <issue>."""
1835 self.calls = self._checkout_calls()
1836 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1837
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001838 def test_checkout_no_branch_issues(self):
1839 """Tests git cl checkout <issue>."""
1840 self.calls = [
1841 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001842 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001843 ]
1844 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1845
Edward Lemur26964072020-02-19 19:18:51 +00001846 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001847 mock.patch(
1848 'git_cl.ask_for_data',
1849 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001850 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1851 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001852 self.mockGit.config['remote.origin.url'] = (
1853 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001854 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001855 cl.branch = 'master'
1856 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001857 return cl
1858
Edward Lemurd55c5072020-02-20 01:09:07 +00001859 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001860 def test_gerrit_ensure_authenticated_missing(self):
1861 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001862 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001863 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001864 with self.assertRaises(SystemExitMock):
1865 cl.EnsureAuthenticated(force=False)
1866 self.assertEqual(
1867 'Credentials for the following hosts are required:\n'
1868 ' chromium-review.googlesource.com\n'
1869 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1870 'You can (re)generate your credentials by visiting '
1871 'https://chromium-review.googlesource.com/new-password\n',
1872 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001873
1874 def test_gerrit_ensure_authenticated_conflict(self):
1875 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001876 'chromium.googlesource.com':
1877 ('git-one.example.com', None, 'secret1'),
1878 'chromium-review.googlesource.com':
1879 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001880 })
1881 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001882 (('ask_for_data', 'If you know what you are doing '
1883 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001884 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1885
1886 def test_gerrit_ensure_authenticated_ok(self):
1887 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001888 'chromium.googlesource.com':
1889 ('git-same.example.com', None, 'secret'),
1890 'chromium-review.googlesource.com':
1891 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001892 })
1893 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1894
tandrii@chromium.org28253532016-04-14 13:46:56 +00001895 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001896 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1897 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001898 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1899
Eric Boren2fb63102018-10-05 13:05:03 +00001900 def test_gerrit_ensure_authenticated_bearer_token(self):
1901 cl = self._test_gerrit_ensure_authenticated_common(auth={
1902 'chromium.googlesource.com':
1903 ('', None, 'secret'),
1904 'chromium-review.googlesource.com':
1905 ('', None, 'secret'),
1906 })
1907 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1908 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1909 'chromium.googlesource.com')
1910 self.assertTrue('Bearer' in header)
1911
Daniel Chengcf6269b2019-05-18 01:02:12 +00001912 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001913 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001914 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001915 (('logging.warning',
1916 'Ignoring branch %(branch)s with non-https remote '
1917 '%(remote)s', {
1918 'branch': 'master',
1919 'remote': 'custom-scheme://repo'}
1920 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001921 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001922 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1923 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1924 mock.patch('logging.warning',
1925 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001926 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001927 cl.branch = 'master'
1928 cl.branchref = 'refs/heads/master'
1929 cl.lookedup_issue = True
1930 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1931
Florian Mayerae510e82020-01-30 21:04:48 +00001932 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001933 self.mockGit.config['remote.origin.url'] = (
1934 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001935 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001936 (('logging.error',
1937 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1938 'but it doesn\'t exist.', {
1939 'remote': 'origin',
1940 'branch': 'master',
1941 'url': 'git@somehost.example:foo/bar.git'}
1942 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001943 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001944 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1945 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1946 mock.patch('logging.error',
1947 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001948 cl = git_cl.Changelist()
1949 cl.branch = 'master'
1950 cl.branchref = 'refs/heads/master'
1951 cl.lookedup_issue = True
1952 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1953
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001954 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001955 self.mockGit.config['branch.master.gerritissue'] = '123'
1956 self.mockGit.config['branch.master.gerritserver'] = (
1957 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001958 self.mockGit.config['remote.origin.url'] = (
1959 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001960 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001961 (('SetReview', 'chromium-review.googlesource.com',
1962 'infra%2Finfra~123', None,
1963 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001964 ]
tandriid9e5ce52016-07-13 02:32:59 -07001965
1966 def test_cmd_set_commit_gerrit_clear(self):
1967 self._cmd_set_commit_gerrit_common(0)
1968 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1969
1970 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001971 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001972 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1973
tandriid9e5ce52016-07-13 02:32:59 -07001974 def test_cmd_set_commit_gerrit(self):
1975 self._cmd_set_commit_gerrit_common(2)
1976 self.assertEqual(0, git_cl.main(['set-commit']))
1977
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001978 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001979 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001980 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001981
1982 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001983 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001984
Edward Lemurda4b6c62020-02-13 00:28:40 +00001985 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001986 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001987 try:
1988 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001989 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001990 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001991 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001992
1993 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001994 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001995 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001996 return 'foobar'
1997
Edward Lemurda4b6c62020-02-13 00:28:40 +00001998 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001999 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002000 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002001 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002002 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002003
iannuccie53c9352016-08-17 14:40:40 -07002004 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002005
iannuccie53c9352016-08-17 14:40:40 -07002006 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002007 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002008 return 'foobar'
2009
Edward Lemurda4b6c62020-02-13 00:28:40 +00002010 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2011 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002012 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002013 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002014
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002015 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002016 self.mockGit.config['remote.origin.url'] = (
2017 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002018 gerrit_util.GetChangeDetail.return_value = {
2019 'current_revision': 'sha1',
2020 'revisions': {'sha1': {
2021 'commit': {'message': 'foobar'},
2022 }},
2023 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002024 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002025 'description',
2026 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2027 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002028 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002029
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002030 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002031 mock.patch('git_cl.Changelist', ChangelistMock).start()
2032 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002033
2034 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2035 self.assertEqual('hihi', ChangelistMock.desc)
2036
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002037 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002038 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002039
2040 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002041 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002042 '# Enter a description of the change.\n'
2043 '# This will be displayed on the codereview site.\n'
2044 '# The first line will also be used as the subject of the review.\n'
2045 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002046 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002047 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002048 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002049 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002050 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002051
Edward Lemur6c6827c2020-02-06 21:15:18 +00002052 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002053 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002054
Edward Lemurda4b6c62020-02-13 00:28:40 +00002055 mock.patch('git_cl.Changelist.FetchDescription',
2056 lambda *args: current_desc).start()
2057 mock.patch('git_cl.Changelist.UpdateDescription',
2058 UpdateDescription).start()
2059 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002060
Edward Lemur85153282020-02-14 22:06:29 +00002061 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002062 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002063
Dan Beamd8b04ca2019-10-10 21:23:26 +00002064 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2065 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2066
2067 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002068 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002069 '# Enter a description of the change.\n'
2070 '# This will be displayed on the codereview site.\n'
2071 '# The first line will also be used as the subject of the review.\n'
2072 '#--------------------This line is 72 characters long'
2073 '--------------------\n'
2074 'Some.\n\nFixed: 123\nChange-Id: xxx',
2075 desc)
2076 return desc
2077
Edward Lemurda4b6c62020-02-13 00:28:40 +00002078 mock.patch('git_cl.Changelist.FetchDescription',
2079 lambda *args: current_desc).start()
2080 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002081
Edward Lemur85153282020-02-14 22:06:29 +00002082 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002083 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002084
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002085 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002086 mock.patch('git_cl.Changelist', ChangelistMock).start()
2087 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002088
2089 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2090 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2091
kmarshall3bff56b2016-06-06 18:31:47 -07002092 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002093 self.calls = [
2094 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002095 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002096 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002097 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002098 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002099 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002100
Edward Lemurda4b6c62020-02-13 00:28:40 +00002101 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002102 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002103 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2104 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002105 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002106
2107 self.assertEqual(0, git_cl.main(['archive', '-f']))
2108
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002109 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002110 self.calls = [
2111 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2112 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2113 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2114 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002115 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2116 ((['git', 'branch', '-D', 'foo'],), '')
2117 ]
2118
Edward Lemurda4b6c62020-02-13 00:28:40 +00002119 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002120 lambda branches, fine_grained, max_processes:
2121 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2122 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002123 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002124
2125 self.assertEqual(0, git_cl.main(['archive', '-f']))
2126
kmarshall3bff56b2016-06-06 18:31:47 -07002127 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002128 self.calls = [
2129 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2130 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002131 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002132 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002133
Edward Lemurda4b6c62020-02-13 00:28:40 +00002134 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002135 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002136 [(MockChangelistWithBranchAndIssue('master', 1),
2137 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002138
2139 self.assertEqual(1, git_cl.main(['archive', '-f']))
2140
2141 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002142 self.calls = [
2143 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2144 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002145 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002146 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002147
Edward Lemurda4b6c62020-02-13 00:28:40 +00002148 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002149 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002150 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2151 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002152 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002153
kmarshall9249e012016-08-23 12:02:16 -07002154 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2155
2156 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002157 self.calls = [
2158 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2159 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002160 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002161 ((['git', 'branch', '-D', 'foo'],), '')
2162 ]
kmarshall9249e012016-08-23 12:02:16 -07002163
Edward Lemurda4b6c62020-02-13 00:28:40 +00002164 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002165 lambda branches, fine_grained, max_processes:
2166 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2167 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002168 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002169
2170 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002171
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002172 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002173 self.calls = [
2174 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2175 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2176 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002177 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2178 'refs/tags/git-cl-archived-456-foo'),
2179 ((['git', 'branch', '-D', 'foo'],), CERR1),
2180 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2181 'refs/tags/git-cl-archived-456-foo'),
2182 ]
2183
Edward Lemurda4b6c62020-02-13 00:28:40 +00002184 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002185 lambda branches, fine_grained, max_processes:
2186 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2187 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002188 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002189
2190 self.assertEqual(0, git_cl.main(['archive', '-f']))
2191
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002192 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002193 self.mockGit.config['branch.master.gerritissue'] = '123'
2194 self.mockGit.config['branch.master.gerritserver'] = (
2195 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002196 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002197 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002198 ]
2199 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002200 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2201 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002202
Aaron Gable400e9892017-07-12 15:31:21 -07002203 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002204 self.mockGit.config['branch.master.gerritissue'] = '123'
2205 self.mockGit.config['branch.master.gerritserver'] = (
2206 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002207 mock.patch('git_cl.Changelist.FetchDescription',
2208 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002209 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002210 ((['git', 'log', '-1', '--format=%B'],),
2211 'This is a description\n\nChange-Id: Ideadbeef'),
2212 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002213 ]
2214 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002215 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2216 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002217
phajdan.jre328cf92016-08-22 04:12:17 -07002218 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002219 self.mockGit.config['branch.master.gerritissue'] = '123'
2220 self.mockGit.config['branch.master.gerritserver'] = (
2221 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002222 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002223 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002224 {'issue': 123,
2225 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002226 ''),
2227 ]
2228 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2229
tandrii16e0b4e2016-06-07 10:34:28 -07002230 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002231 mock.patch(
2232 'git_cl.os.path.abspath',
2233 lambda path: self._mocked_call(['abspath', path])).start()
2234 mock.patch(
2235 'git_cl.os.path.exists',
2236 lambda path: self._mocked_call(['exists', path])).start()
2237 mock.patch(
2238 'git_cl.gclient_utils.FileRead',
2239 lambda path: self._mocked_call(['FileRead', path])).start()
2240 mock.patch(
2241 'git_cl.gclient_utils.rm_file_or_tree',
2242 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002243 mock.patch(
2244 'git_cl.ask_for_data',
2245 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002246 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002247
2248 def test_GerritCommitMsgHookCheck_custom_hook(self):
2249 cl = self._common_GerritCommitMsgHookCheck()
2250 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002251 ((['exists', '.git/hooks/commit-msg'],), True),
2252 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002253 '#!/bin/sh\necho "custom hook"')
2254 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002255 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002256
2257 def test_GerritCommitMsgHookCheck_not_exists(self):
2258 cl = self._common_GerritCommitMsgHookCheck()
2259 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002260 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002261 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002262 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002263
2264 def test_GerritCommitMsgHookCheck(self):
2265 cl = self._common_GerritCommitMsgHookCheck()
2266 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002267 ((['exists', '.git/hooks/commit-msg'],), True),
2268 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002269 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002270 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002271 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002272 ''),
2273 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002274 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002275
tandriic4344b52016-08-29 06:04:54 -07002276 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002277 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2278 self.mockGit.config['branch.master.gerritserver'] = (
2279 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002280 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002281 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002282 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002283 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002284 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002285 'labels': {},
2286 'current_revision': 'deadbeaf',
2287 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002288 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002289 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002290 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002291 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2292 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002293 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002294 self.assertEqual(0, cl.CMDLand(force=True,
2295 bypass_hooks=True,
2296 verbose=True,
2297 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002298 self.assertIn(
2299 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002300 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002301 self.assertIn(
2302 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002303 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002304
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002305 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002306 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002307
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002308 def test_gerrit_change_detail_cache_simple(self):
2309 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002310 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002311 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002312 cl1._cached_remote_url = (
2313 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002314 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002315 cl2._cached_remote_url = (
2316 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002317 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2318 self.assertEqual(cl1._GetChangeDetail(), 'a')
2319 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002320
2321 def test_gerrit_change_detail_cache_options(self):
2322 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002323 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002324 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002325 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002326 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2327 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2328 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2329 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2330 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2331 self.assertEqual(cl._GetChangeDetail(), 'cab')
2332
2333 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2334 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2335 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2336 self.assertEqual(cl._GetChangeDetail(), 'cab')
2337
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002338 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002339 gerrit_util.GetChangeDetail.return_value = {
2340 'current_revision': 'rev1',
2341 'revisions': {
2342 'rev1': {'commit': {'message': 'desc1'}},
2343 },
2344 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002345
2346 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002347 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002348 cl._cached_remote_url = (
2349 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002350 self.assertEqual(cl.FetchDescription(), 'desc1')
2351 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002352
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002353 def test_print_current_creds(self):
2354 class CookiesAuthenticatorMock(object):
2355 def __init__(self):
2356 self.gitcookies = {
2357 'host.googlesource.com': ('user', 'pass'),
2358 'host-review.googlesource.com': ('user', 'pass'),
2359 }
2360 self.netrc = self
2361 self.netrc.hosts = {
2362 'github.com': ('user2', None, 'pass2'),
2363 'host2.googlesource.com': ('user3', None, 'pass'),
2364 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002365 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2366 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002367 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2368 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2369 ' Host\t User\t Which file',
2370 '============================\t=====\t===========',
2371 'host-review.googlesource.com\t user\t.gitcookies',
2372 ' host.googlesource.com\t user\t.gitcookies',
2373 ' host2.googlesource.com\tuser3\t .netrc',
2374 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002375 sys.stdout.seek(0)
2376 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002377 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2378 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2379 ' Host\tUser\t Which file',
2380 '============================\t====\t===========',
2381 'host-review.googlesource.com\tuser\t.gitcookies',
2382 ' host.googlesource.com\tuser\t.gitcookies',
2383 ])
2384
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002385 def _common_creds_check_mocks(self):
2386 def exists_mock(path):
2387 dirname = os.path.dirname(path)
2388 if dirname == os.path.expanduser('~'):
2389 dirname = '~'
2390 base = os.path.basename(path)
2391 if base in ('.netrc', '.gitcookies'):
2392 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2393 # git cl also checks for existence other files not relevant to this test.
2394 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002395 mock.patch(
2396 'git_cl.ask_for_data',
2397 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002398 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002399
2400 def test_creds_check_gitcookies_not_configured(self):
2401 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002402 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2403 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002404 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002405 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002406 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2407 (('os.path.exists', '~/.netrc'), True),
2408 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2409 'or Ctrl+C to abort'), ''),
2410 ((['git', 'config', '--global', 'http.cookiefile',
2411 os.path.expanduser('~/.gitcookies')], ), ''),
2412 ]
2413 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002414 self.assertTrue(
2415 sys.stdout.getvalue().startswith(
2416 'You seem to be using outdated .netrc for git credentials:'))
2417 self.assertIn(
2418 '\nConfigured git to use .gitcookies from',
2419 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002420
2421 def test_creds_check_gitcookies_configured_custom_broken(self):
2422 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002423 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2424 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002425 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002426 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002427 ((['git', 'config', '--global', 'http.cookiefile'],),
2428 '/custom/.gitcookies'),
2429 (('os.path.exists', '/custom/.gitcookies'), False),
2430 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2431 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2432 ((['git', 'config', '--global', 'http.cookiefile',
2433 os.path.expanduser('~/.gitcookies')], ), ''),
2434 ]
2435 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002436 self.assertIn(
2437 'WARNING: You have configured custom path to .gitcookies: ',
2438 sys.stdout.getvalue())
2439 self.assertIn(
2440 'However, your configured .gitcookies file is missing.',
2441 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002442
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002443 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002444 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002445 self.mockGit.config['remote.origin.url'] = (
2446 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002447 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002448 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002449 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002450 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002451 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002452 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002453
Edward Lemurda4b6c62020-02-13 00:28:40 +00002454 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2455 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002456 self.mockGit.config['remote.origin.url'] = (
2457 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002458 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002459 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002460 'current_revision': 'ba5eba11',
2461 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002462 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002463 '_number': 1,
2464 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002465 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002466 '_number': 2,
2467 },
2468 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002469 'messages': [
2470 {
2471 u'_revision_number': 1,
2472 u'author': {
2473 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002474 u'email': u'could-be-anything@example.com',
2475 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002476 },
2477 u'date': u'2017-03-15 20:08:45.000000000',
2478 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002479 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002480 u'tag': u'autogenerated:cq:dry-run'
2481 },
2482 {
2483 u'_revision_number': 2,
2484 u'author': {
2485 u'_account_id': 11151243,
2486 u'email': u'owner@example.com',
2487 u'name': u'owner'
2488 },
2489 u'date': u'2017-03-16 20:00:41.000000000',
2490 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2491 u'message': u'PTAL',
2492 },
2493 {
2494 u'_revision_number': 2,
2495 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002496 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002497 u'email': u'reviewer@example.com',
2498 u'name': u'reviewer'
2499 },
2500 u'date': u'2017-03-17 05:19:37.500000000',
2501 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2502 u'message': u'Patch Set 2: Code-Review+1',
2503 },
2504 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002505 }
2506 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002507 (('GetChangeComments', 'chromium-review.googlesource.com',
2508 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002509 '/COMMIT_MSG': [
2510 {
2511 'author': {'email': u'reviewer@example.com'},
2512 'updated': u'2017-03-17 05:19:37.500000000',
2513 'patch_set': 2,
2514 'side': 'REVISION',
2515 'message': 'Please include a bug link',
2516 },
2517 ],
2518 'codereview.settings': [
2519 {
2520 'author': {'email': u'owner@example.com'},
2521 'updated': u'2017-03-16 20:00:41.000000000',
2522 'patch_set': 2,
2523 'side': 'PARENT',
2524 'line': 42,
2525 'message': 'I removed this because it is bad',
2526 },
2527 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002528 }),
2529 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2530 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002531 ] * 2 + [
2532 (('write_json', 'output.json', [
2533 {
2534 u'date': u'2017-03-16 20:00:41.000000',
2535 u'message': (
2536 u'PTAL\n' +
2537 u'\n' +
2538 u'codereview.settings\n' +
2539 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2540 u'c/1/2/codereview.settings#b42\n' +
2541 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002542 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002543 u'approval': False,
2544 u'disapproval': False,
2545 u'sender': u'owner@example.com'
2546 }, {
2547 u'date': u'2017-03-17 05:19:37.500000',
2548 u'message': (
2549 u'Patch Set 2: Code-Review+1\n' +
2550 u'\n' +
2551 u'/COMMIT_MSG\n' +
2552 u' PS2, File comment: https://chromium-review.googlesource' +
2553 u'.com/c/1/2//COMMIT_MSG#\n' +
2554 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002555 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002556 u'approval': False,
2557 u'disapproval': False,
2558 u'sender': u'reviewer@example.com'
2559 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002560 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002561 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002562 expected_comments_summary = [
2563 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002564 message=(
2565 u'PTAL\n' +
2566 u'\n' +
2567 u'codereview.settings\n' +
2568 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2569 u'c/1/2/codereview.settings#b42\n' +
2570 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002571 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002572 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002573 disapproval=False, approval=False, sender=u'owner@example.com'),
2574 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002575 message=(
2576 u'Patch Set 2: Code-Review+1\n' +
2577 u'\n' +
2578 u'/COMMIT_MSG\n' +
2579 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2580 u'c/1/2//COMMIT_MSG#\n' +
2581 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002582 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002583 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002584 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2585 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002586 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002587 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002588 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002589 self.assertEqual(
2590 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2591
2592 def test_git_cl_comments_robot_comments(self):
2593 # git cl comments also fetches robot comments (which are considered a type
2594 # of autogenerated comment), and unlike other types of comments, only robot
2595 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002596 self.mockGit.config['remote.origin.url'] = (
2597 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002598 gerrit_util.GetChangeDetail.return_value = {
2599 'owner': {'email': 'owner@example.com'},
2600 'current_revision': 'ba5eba11',
2601 'revisions': {
2602 'deadbeaf': {
2603 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002604 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002605 'ba5eba11': {
2606 '_number': 2,
2607 },
2608 },
2609 'messages': [
2610 {
2611 u'_revision_number': 1,
2612 u'author': {
2613 u'_account_id': 1111084,
2614 u'email': u'commit-bot@chromium.org',
2615 u'name': u'Commit Bot'
2616 },
2617 u'date': u'2017-03-15 20:08:45.000000000',
2618 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2619 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2620 u'tag': u'autogenerated:cq:dry-run'
2621 },
2622 {
2623 u'_revision_number': 1,
2624 u'author': {
2625 u'_account_id': 123,
2626 u'email': u'tricium@serviceaccount.com',
2627 u'name': u'Tricium'
2628 },
2629 u'date': u'2017-03-16 20:00:41.000000000',
2630 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2631 u'message': u'(1 comment)',
2632 u'tag': u'autogenerated:tricium',
2633 },
2634 {
2635 u'_revision_number': 1,
2636 u'author': {
2637 u'_account_id': 123,
2638 u'email': u'tricium@serviceaccount.com',
2639 u'name': u'Tricium'
2640 },
2641 u'date': u'2017-03-16 20:00:41.000000000',
2642 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2643 u'message': u'(1 comment)',
2644 u'tag': u'autogenerated:tricium',
2645 },
2646 {
2647 u'_revision_number': 2,
2648 u'author': {
2649 u'_account_id': 123,
2650 u'email': u'tricium@serviceaccount.com',
2651 u'name': u'reviewer'
2652 },
2653 u'date': u'2017-03-17 05:30:37.000000000',
2654 u'tag': u'autogenerated:tricium',
2655 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2656 u'message': u'(1 comment)',
2657 },
2658 ]
2659 }
2660 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002661 (('GetChangeComments', 'chromium-review.googlesource.com',
2662 'infra%2Finfra~1'), {}),
2663 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2664 'infra%2Finfra~1'), {
2665 'codereview.settings': [
2666 {
2667 u'author': {u'email': u'tricium@serviceaccount.com'},
2668 u'updated': u'2017-03-17 05:30:37.000000000',
2669 u'robot_run_id': u'5565031076855808',
2670 u'robot_id': u'Linter/Category',
2671 u'tag': u'autogenerated:tricium',
2672 u'patch_set': 2,
2673 u'side': u'REVISION',
2674 u'message': u'Linter warning message text',
2675 u'line': 32,
2676 },
2677 ],
2678 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002679 ]
2680 expected_comments_summary = [
2681 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2682 message=(
2683 u'(1 comment)\n\ncodereview.settings\n'
2684 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2685 u'c/1/2/codereview.settings#32\n'
2686 u' Linter warning message text\n'),
2687 sender=u'tricium@serviceaccount.com',
2688 autogenerated=True, approval=False, disapproval=False)
2689 ]
2690 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002691 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002692 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002693
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002694 def test_get_remote_url_with_mirror(self):
2695 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002696
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002697 def selective_os_path_isdir_mock(path):
2698 if path == '/cache/this-dir-exists':
2699 return self._mocked_call('os.path.isdir', path)
2700 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002701
Edward Lemurda4b6c62020-02-13 00:28:40 +00002702 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002703
2704 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002705 self.mockGit.config['remote.origin.url'] = (
2706 '/cache/this-dir-exists')
2707 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2708 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002709 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002710 (('os.path.isdir', '/cache/this-dir-exists'),
2711 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002712 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002713 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002714 self.assertEqual(cl.GetRemoteUrl(), url)
2715 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2716
Edward Lemur298f2cf2019-02-22 21:40:39 +00002717 def test_get_remote_url_non_existing_mirror(self):
2718 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002719
Edward Lemur298f2cf2019-02-22 21:40:39 +00002720 def selective_os_path_isdir_mock(path):
2721 if path == '/cache/this-dir-doesnt-exist':
2722 return self._mocked_call('os.path.isdir', path)
2723 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002724
Edward Lemurda4b6c62020-02-13 00:28:40 +00002725 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2726 mock.patch('logging.error',
2727 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002728
Edward Lemur26964072020-02-19 19:18:51 +00002729 self.mockGit.config['remote.origin.url'] = (
2730 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002731 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002732 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2733 False),
2734 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002735 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2736 'but it doesn\'t exist.', {
2737 'remote': 'origin',
2738 'branch': 'master',
2739 'url': '/cache/this-dir-doesnt-exist'}
2740 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002741 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002742 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002743 self.assertIsNone(cl.GetRemoteUrl())
2744
2745 def test_get_remote_url_misconfigured_mirror(self):
2746 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002747
Edward Lemur298f2cf2019-02-22 21:40:39 +00002748 def selective_os_path_isdir_mock(path):
2749 if path == '/cache/this-dir-exists':
2750 return self._mocked_call('os.path.isdir', path)
2751 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002752
Edward Lemurda4b6c62020-02-13 00:28:40 +00002753 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2754 mock.patch('logging.error',
2755 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002756
Edward Lemur26964072020-02-19 19:18:51 +00002757 self.mockGit.config['remote.origin.url'] = (
2758 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002759 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002760 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002761 (('logging.error',
2762 'Remote "%(remote)s" for branch "%(branch)s" points to '
2763 '"%(cache_path)s", but it is misconfigured.\n'
2764 '"%(cache_path)s" must be a git repo and must have a remote named '
2765 '"%(remote)s" pointing to the git host.', {
2766 'remote': 'origin',
2767 'cache_path': '/cache/this-dir-exists',
2768 'branch': 'master'}
2769 ), None),
2770 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002771 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002772 self.assertIsNone(cl.GetRemoteUrl())
2773
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002774 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002775 self.mockGit.config['remote.origin.url'] = (
2776 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002777 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002778 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2779
2780 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002781 mock.patch('logging.error',
2782 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002783
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002784 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002785 (('logging.error',
2786 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2787 'but it doesn\'t exist.', {
2788 'remote': 'origin',
2789 'branch': 'master',
2790 'url': ''}
2791 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002792 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002793 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002794 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002795
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002796
Edward Lemur9aa1a962020-02-25 00:58:38 +00002797class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002798 def setUp(self):
2799 super(ChangelistTest, self).setUp()
2800 mock.patch('gclient_utils.FileRead').start()
2801 mock.patch('gclient_utils.FileWrite').start()
2802 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2803 mock.patch(
2804 'git_cl.Changelist.GetCodereviewServer',
2805 return_value='https://chromium-review.googlesource.com').start()
2806 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2807 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2808 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2809 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2810 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2811 mock.patch('git_cl.time_time').start()
2812 mock.patch('metrics.collector').start()
2813 mock.patch('subprocess2.Popen').start()
2814 self.addCleanup(mock.patch.stopall)
2815 self.temp_count = 0
2816
Edward Lemur227d5102020-02-25 23:45:35 +00002817 def testRunHook(self):
2818 expected_results = {
2819 'more_cc': ['more@example.com', 'cc@example.com'],
2820 'should_continue': True,
2821 }
2822 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2823 git_cl.time_time.side_effect = [100, 200]
2824 mockProcess = mock.Mock()
2825 mockProcess.wait.return_value = 0
2826 subprocess2.Popen.return_value = mockProcess
2827
2828 cl = git_cl.Changelist()
2829 results = cl.RunHook(
2830 committing=True,
2831 may_prompt=True,
2832 verbose=2,
2833 parallel=True,
2834 upstream='upstream',
2835 description='description',
2836 all_files=True)
2837
2838 self.assertEqual(expected_results, results)
2839 subprocess2.Popen.assert_called_once_with([
2840 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002841 '--root', 'root',
2842 '--upstream', 'upstream',
2843 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002844 '--author', 'author',
2845 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002846 '--issue', '123456',
2847 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002848 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002849 '--may_prompt',
2850 '--parallel',
2851 '--all_files',
2852 '--json_output', '/tmp/fake-temp2',
2853 '--description_file', '/tmp/fake-temp1',
2854 ])
2855 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002856 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002857 metrics.collector.add_repeated('sub_commands', {
2858 'command': 'presubmit',
2859 'execution_time': 100,
2860 'exit_code': 0,
2861 })
2862
Edward Lemur99df04e2020-03-05 19:39:43 +00002863 def testRunHook_FewerOptions(self):
2864 expected_results = {
2865 'more_cc': ['more@example.com', 'cc@example.com'],
2866 'should_continue': True,
2867 }
2868 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2869 git_cl.time_time.side_effect = [100, 200]
2870 mockProcess = mock.Mock()
2871 mockProcess.wait.return_value = 0
2872 subprocess2.Popen.return_value = mockProcess
2873
2874 git_cl.Changelist.GetAuthor.return_value = None
2875 git_cl.Changelist.GetIssue.return_value = None
2876 git_cl.Changelist.GetPatchset.return_value = None
2877 git_cl.Changelist.GetCodereviewServer.return_value = None
2878
2879 cl = git_cl.Changelist()
2880 results = cl.RunHook(
2881 committing=False,
2882 may_prompt=False,
2883 verbose=0,
2884 parallel=False,
2885 upstream='upstream',
2886 description='description',
2887 all_files=False)
2888
2889 self.assertEqual(expected_results, results)
2890 subprocess2.Popen.assert_called_once_with([
2891 'vpython', 'PRESUBMIT_SUPPORT',
2892 '--root', 'root',
2893 '--upstream', 'upstream',
2894 '--upload',
2895 '--json_output', '/tmp/fake-temp2',
2896 '--description_file', '/tmp/fake-temp1',
2897 ])
2898 gclient_utils.FileWrite.assert_called_once_with(
2899 '/tmp/fake-temp1', 'description')
2900 metrics.collector.add_repeated('sub_commands', {
2901 'command': 'presubmit',
2902 'execution_time': 100,
2903 'exit_code': 0,
2904 })
2905
Edward Lemur227d5102020-02-25 23:45:35 +00002906 @mock.patch('sys.exit', side_effect=SystemExitMock)
2907 def testRunHook_Failure(self, _mock):
2908 git_cl.time_time.side_effect = [100, 200]
2909 mockProcess = mock.Mock()
2910 mockProcess.wait.return_value = 2
2911 subprocess2.Popen.return_value = mockProcess
2912
2913 cl = git_cl.Changelist()
2914 with self.assertRaises(SystemExitMock):
2915 cl.RunHook(
2916 committing=True,
2917 may_prompt=True,
2918 verbose=2,
2919 parallel=True,
2920 upstream='upstream',
2921 description='description',
2922 all_files=True)
2923
2924 sys.exit.assert_called_once_with(2)
2925
Edward Lemur75526302020-02-27 22:31:05 +00002926 def testRunPostUploadHook(self):
2927 cl = git_cl.Changelist()
2928 cl.RunPostUploadHook(2, 'upstream', 'description')
2929
2930 subprocess2.Popen.assert_called_once_with([
2931 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002932 '--root', 'root',
2933 '--upstream', 'upstream',
2934 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002935 '--author', 'author',
2936 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002937 '--issue', '123456',
2938 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002939 '--post_upload',
2940 '--description_file', '/tmp/fake-temp1',
2941 ])
2942 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002943 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002944
Edward Lemur9aa1a962020-02-25 00:58:38 +00002945
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002946class CMDTestCaseBase(unittest.TestCase):
2947 _STATUSES = [
2948 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2949 'INFRA_FAILURE', 'CANCELED',
2950 ]
2951 _CHANGE_DETAIL = {
2952 'project': 'depot_tools',
2953 'status': 'OPEN',
2954 'owner': {'email': 'owner@e.mail'},
2955 'current_revision': 'beeeeeef',
2956 'revisions': {
2957 'deadbeaf': {'_number': 6},
2958 'beeeeeef': {
2959 '_number': 7,
2960 'fetch': {'http': {
2961 'url': 'https://chromium.googlesource.com/depot_tools',
2962 'ref': 'refs/changes/56/123456/7'
2963 }},
2964 },
2965 },
2966 }
2967 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002968 'builds': [{
2969 'id': str(100 + idx),
2970 'builder': {
2971 'project': 'chromium',
2972 'bucket': 'try',
2973 'builder': 'bot_' + status.lower(),
2974 },
2975 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2976 'tags': [],
2977 'status': status,
2978 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002979 }
2980
Edward Lemur4c707a22019-09-24 21:13:43 +00002981 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002982 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002983 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002984 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2985 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002986 mock.patch(
2987 'git_cl.Changelist.GetCodereviewServer',
2988 return_value='https://chromium-review.googlesource.com').start()
2989 mock.patch(
2990 'git_cl.Changelist._GetGerritHost',
2991 return_value='chromium-review.googlesource.com').start()
2992 mock.patch(
2993 'git_cl.Changelist.GetMostRecentPatchset',
2994 return_value=7).start()
2995 mock.patch(
2996 'git_cl.Changelist.GetRemoteUrl',
2997 return_value='https://chromium.googlesource.com/depot_tools').start()
2998 mock.patch(
2999 'auth.Authenticator',
3000 return_value=AuthenticatorMock()).start()
3001 mock.patch(
3002 'gerrit_util.GetChangeDetail',
3003 return_value=self._CHANGE_DETAIL).start()
3004 mock.patch(
3005 'git_cl._call_buildbucket',
3006 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003007 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003008 self.addCleanup(mock.patch.stopall)
3009
Edward Lemur4c707a22019-09-24 21:13:43 +00003010
Edward Lemur9468eba2020-02-27 19:07:22 +00003011class CMDPresubmitTestCase(CMDTestCaseBase):
3012 def setUp(self):
3013 super(CMDPresubmitTestCase, self).setUp()
3014 mock.patch(
3015 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3016 return_value='upstream').start()
3017 mock.patch(
3018 'git_cl.Changelist.FetchDescription',
3019 return_value='fetch description').start()
3020 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003021 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003022 return_value='get description').start()
3023 mock.patch('git_cl.Changelist.RunHook').start()
3024
3025 def testDefaultCase(self):
3026 self.assertEqual(0, git_cl.main(['presubmit']))
3027 git_cl.Changelist.RunHook.assert_called_once_with(
3028 committing=True,
3029 may_prompt=False,
3030 verbose=0,
3031 parallel=None,
3032 upstream='upstream',
3033 description='fetch description',
3034 all_files=None)
3035
3036 def testNoIssue(self):
3037 git_cl.Changelist.GetIssue.return_value = None
3038 self.assertEqual(0, git_cl.main(['presubmit']))
3039 git_cl.Changelist.RunHook.assert_called_once_with(
3040 committing=True,
3041 may_prompt=False,
3042 verbose=0,
3043 parallel=None,
3044 upstream='upstream',
3045 description='get description',
3046 all_files=None)
3047
3048 def testCustomBranch(self):
3049 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3050 git_cl.Changelist.RunHook.assert_called_once_with(
3051 committing=True,
3052 may_prompt=False,
3053 verbose=0,
3054 parallel=None,
3055 upstream='custom_branch',
3056 description='fetch description',
3057 all_files=None)
3058
3059 def testOptions(self):
3060 self.assertEqual(
3061 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
3062 git_cl.Changelist.RunHook.assert_called_once_with(
3063 committing=False,
3064 may_prompt=False,
3065 verbose=2,
3066 parallel=True,
3067 upstream='upstream',
3068 description='fetch description',
3069 all_files=True)
3070
3071
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003072class CMDTryResultsTestCase(CMDTestCaseBase):
3073 _DEFAULT_REQUEST = {
3074 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003075 "gerritChanges": [{
3076 "project": "depot_tools",
3077 "host": "chromium-review.googlesource.com",
3078 "patchset": 7,
3079 "change": 123456,
3080 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003081 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003082 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3083 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003084 }
3085
3086 def testNoJobs(self):
3087 git_cl._call_buildbucket.return_value = {}
3088
3089 self.assertEqual(0, git_cl.main(['try-results']))
3090 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3091 git_cl._call_buildbucket.assert_called_once_with(
3092 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3093 self._DEFAULT_REQUEST)
3094
3095 def testPrintToStdout(self):
3096 self.assertEqual(0, git_cl.main(['try-results']))
3097 self.assertEqual([
3098 'Successes:',
3099 ' bot_success https://ci.chromium.org/b/103',
3100 'Infra Failures:',
3101 ' bot_infra_failure https://ci.chromium.org/b/105',
3102 'Failures:',
3103 ' bot_failure https://ci.chromium.org/b/104',
3104 'Canceled:',
3105 ' bot_canceled ',
3106 'Started:',
3107 ' bot_started https://ci.chromium.org/b/102',
3108 'Scheduled:',
3109 ' bot_scheduled id=101',
3110 'Other:',
3111 ' bot_status_unspecified id=100',
3112 'Total: 7 tryjobs',
3113 ], sys.stdout.getvalue().splitlines())
3114 git_cl._call_buildbucket.assert_called_once_with(
3115 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3116 self._DEFAULT_REQUEST)
3117
3118 def testPrintToStdoutWithMasters(self):
3119 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3120 self.assertEqual([
3121 'Successes:',
3122 ' try bot_success https://ci.chromium.org/b/103',
3123 'Infra Failures:',
3124 ' try bot_infra_failure https://ci.chromium.org/b/105',
3125 'Failures:',
3126 ' try bot_failure https://ci.chromium.org/b/104',
3127 'Canceled:',
3128 ' try bot_canceled ',
3129 'Started:',
3130 ' try bot_started https://ci.chromium.org/b/102',
3131 'Scheduled:',
3132 ' try bot_scheduled id=101',
3133 'Other:',
3134 ' try bot_status_unspecified id=100',
3135 'Total: 7 tryjobs',
3136 ], sys.stdout.getvalue().splitlines())
3137 git_cl._call_buildbucket.assert_called_once_with(
3138 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3139 self._DEFAULT_REQUEST)
3140
3141 @mock.patch('git_cl.write_json')
3142 def testWriteToJson(self, mockJsonDump):
3143 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3144 git_cl._call_buildbucket.assert_called_once_with(
3145 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3146 self._DEFAULT_REQUEST)
3147 mockJsonDump.assert_called_once_with(
3148 'file.json', self._DEFAULT_RESPONSE['builds'])
3149
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003150 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003151 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3152 self.assertEqual(
3153 [
3154 ('chromium', 'try', 'bot_failure'),
3155 ('chromium', 'try', 'bot_infra_failure'),
3156 ],
3157 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003158
3159 def test_filter_failed_for_retry_many_builds(self):
3160
3161 def _build(name, created_sec, status, experimental=False):
3162 assert 0 <= created_sec < 100, created_sec
3163 b = {
3164 'id': 112112,
3165 'builder': {
3166 'project': 'chromium',
3167 'bucket': 'try',
3168 'builder': name,
3169 },
3170 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3171 'status': status,
3172 'tags': [],
3173 }
3174 if experimental:
3175 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3176 return b
3177
3178 builds = [
3179 _build('flaky-last-green', 1, 'FAILURE'),
3180 _build('flaky-last-green', 2, 'SUCCESS'),
3181 _build('flaky', 1, 'SUCCESS'),
3182 _build('flaky', 2, 'FAILURE'),
3183 _build('running', 1, 'FAILED'),
3184 _build('running', 2, 'SCHEDULED'),
3185 _build('yep-still-running', 1, 'STARTED'),
3186 _build('yep-still-running', 2, 'FAILURE'),
3187 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3188 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3189
3190 # Simulate experimental in CQ builder, which developer decided
3191 # to retry manually which resulted in 2nd build non-experimental.
3192 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3193 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3194 ]
3195 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003196 self.assertEqual(
3197 [
3198 ('chromium', 'try', 'flaky'),
3199 ('chromium', 'try', 'sometimes-experimental'),
3200 ],
3201 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003202
3203
3204class CMDTryTestCase(CMDTestCaseBase):
3205
3206 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003207 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003208 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003209 self.assertEqual(0, git_cl.main(['try']))
3210 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3211 self.assertEqual(
3212 sys.stdout.getvalue(),
3213 'Scheduling CQ dry run on: '
3214 'https://chromium-review.googlesource.com/123456\n')
3215
Edward Lemur4c707a22019-09-24 21:13:43 +00003216 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003217 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003218 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003219
3220 self.assertEqual(0, git_cl.main([
3221 'try', '-B', 'luci.chromium.try', '-b', 'win',
3222 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3223 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003224 'Scheduling jobs on:\n'
3225 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003226 git_cl.sys.stdout.getvalue())
3227
3228 expected_request = {
3229 "requests": [{
3230 "scheduleBuild": {
3231 "requestId": "uuid4",
3232 "builder": {
3233 "project": "chromium",
3234 "builder": "win",
3235 "bucket": "try",
3236 },
3237 "gerritChanges": [{
3238 "project": "depot_tools",
3239 "host": "chromium-review.googlesource.com",
3240 "patchset": 7,
3241 "change": 123456,
3242 }],
3243 "properties": {
3244 "category": "git_cl_try",
3245 "json": [{"a": 1}, None],
3246 "key": "val",
3247 },
3248 "tags": [
3249 {"value": "win", "key": "builder"},
3250 {"value": "git_cl_try", "key": "user_agent"},
3251 ],
3252 },
3253 }],
3254 }
3255 mockCallBuildbucket.assert_called_with(
3256 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3257
Anthony Polito1a5fe232020-01-24 23:17:52 +00003258 @mock.patch('git_cl._call_buildbucket')
3259 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3260 mockCallBuildbucket.return_value = {}
3261
3262 self.assertEqual(0, git_cl.main([
3263 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3264 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3265 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3266 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003267 'Scheduling jobs on:\n'
3268 ' chromium/try: linux\n'
3269 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003270 git_cl.sys.stdout.getvalue())
3271
3272 expected_request = {
3273 "requests": [{
3274 "scheduleBuild": {
3275 "requestId": "uuid4",
3276 "builder": {
3277 "project": "chromium",
3278 "builder": "linux",
3279 "bucket": "try",
3280 },
3281 "gerritChanges": [{
3282 "project": "depot_tools",
3283 "host": "chromium-review.googlesource.com",
3284 "patchset": 7,
3285 "change": 123456,
3286 }],
3287 "properties": {
3288 "category": "git_cl_try",
3289 "json": [{"a": 1}, None],
3290 "key": "val",
3291 },
3292 "tags": [
3293 {"value": "linux", "key": "builder"},
3294 {"value": "git_cl_try", "key": "user_agent"},
3295 ],
3296 "gitilesCommit": {
3297 "host": "chromium-review.googlesource.com",
3298 "project": "depot_tools",
3299 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3300 }
3301 },
3302 },
3303 {
3304 "scheduleBuild": {
3305 "requestId": "uuid4",
3306 "builder": {
3307 "project": "chromium",
3308 "builder": "win",
3309 "bucket": "try",
3310 },
3311 "gerritChanges": [{
3312 "project": "depot_tools",
3313 "host": "chromium-review.googlesource.com",
3314 "patchset": 7,
3315 "change": 123456,
3316 }],
3317 "properties": {
3318 "category": "git_cl_try",
3319 "json": [{"a": 1}, None],
3320 "key": "val",
3321 },
3322 "tags": [
3323 {"value": "win", "key": "builder"},
3324 {"value": "git_cl_try", "key": "user_agent"},
3325 ],
3326 "gitilesCommit": {
3327 "host": "chromium-review.googlesource.com",
3328 "project": "depot_tools",
3329 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3330 }
3331 },
3332 }],
3333 }
3334 mockCallBuildbucket.assert_called_with(
3335 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3336
Edward Lemur45768512020-03-02 19:03:14 +00003337 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003338 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003339 with self.assertRaises(SystemExit):
3340 git_cl.main([
3341 'try', '-B', 'not-a-bucket', '-b', 'win',
3342 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003343 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003344 'Invalid bucket: not-a-bucket.',
3345 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003346
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003347 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003348 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003349 def testScheduleOnBuildbucketRetryFailed(
3350 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003351 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003352 7: [],
3353 6: [{
3354 'id': 112112,
3355 'builder': {
3356 'project': 'chromium',
3357 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003358 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003359 'createTime': '2019-10-09T08:00:01.854286Z',
3360 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003361 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003362 mockCallBuildbucket.return_value = {}
3363
3364 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3365 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003366 'Scheduling jobs on:\n'
3367 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003368 git_cl.sys.stdout.getvalue())
3369
3370 expected_request = {
3371 "requests": [{
3372 "scheduleBuild": {
3373 "requestId": "uuid4",
3374 "builder": {
3375 "project": "chromium",
3376 "bucket": "try",
3377 "builder": "linux",
3378 },
3379 "gerritChanges": [{
3380 "project": "depot_tools",
3381 "host": "chromium-review.googlesource.com",
3382 "patchset": 7,
3383 "change": 123456,
3384 }],
3385 "properties": {
3386 "category": "git_cl_try",
3387 },
3388 "tags": [
3389 {"value": "linux", "key": "builder"},
3390 {"value": "git_cl_try", "key": "user_agent"},
3391 {"value": "1", "key": "retry_failed"},
3392 ],
3393 },
3394 }],
3395 }
3396 mockCallBuildbucket.assert_called_with(
3397 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3398
Edward Lemur4c707a22019-09-24 21:13:43 +00003399 def test_parse_bucket(self):
3400 test_cases = [
3401 {
3402 'bucket': 'chromium/try',
3403 'result': ('chromium', 'try'),
3404 },
3405 {
3406 'bucket': 'luci.chromium.try',
3407 'result': ('chromium', 'try'),
3408 'has_warning': True,
3409 },
3410 {
3411 'bucket': 'skia.primary',
3412 'result': ('skia', 'skia.primary'),
3413 'has_warning': True,
3414 },
3415 {
3416 'bucket': 'not-a-bucket',
3417 'result': (None, None),
3418 },
3419 ]
3420
3421 for test_case in test_cases:
3422 git_cl.sys.stdout.truncate(0)
3423 self.assertEqual(
3424 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3425 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003426 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3427 test_case['result'])
3428 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003429
3430
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003431class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003432
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003433 def setUp(self):
3434 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003435 mock.patch('git_cl._fetch_tryjobs').start()
3436 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003437 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003438 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003439 self.addCleanup(mock.patch.stopall)
3440
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003441 def testWarmUpChangeDetailCache(self):
3442 self.assertEqual(0, git_cl.main(['upload']))
3443 gerrit_util.GetChangeDetail.assert_called_once_with(
3444 'chromium-review.googlesource.com', 'depot_tools~123456',
3445 frozenset([
3446 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3447 'CURRENT_COMMIT']))
3448
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003449 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003450 # This test mocks out the actual upload part, and just asserts that after
3451 # upload, if --retry-failed is added, then the tool will fetch try jobs
3452 # from the previous patchset and trigger the right builders on the latest
3453 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003454 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003455 # Latest patchset: No builds.
3456 [],
3457 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003458 [{
3459 'id': str(100 + idx),
3460 'builder': {
3461 'project': 'chromium',
3462 'bucket': 'try',
3463 'builder': 'bot_' + status.lower(),
3464 },
3465 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3466 'tags': [],
3467 'status': status,
3468 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003469 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003470
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003471 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003472 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003473 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3474 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003475 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003476 expected_buckets = [
3477 ('chromium', 'try', 'bot_failure'),
3478 ('chromium', 'try', 'bot_infra_failure'),
3479 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003480 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3481 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003482
Brian Sheedy59b06a82019-10-14 17:03:29 +00003483
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003484class MakeRequestsHelperTestCase(unittest.TestCase):
3485
3486 def exampleGerritChange(self):
3487 return {
3488 'host': 'chromium-review.googlesource.com',
3489 'project': 'depot_tools',
3490 'change': 1,
3491 'patchset': 2,
3492 }
3493
3494 def testMakeRequestsHelperNoOptions(self):
3495 # Basic test for the helper function _make_tryjob_schedule_requests;
3496 # it shouldn't throw AttributeError even when options doesn't have any
3497 # of the expected values; it will use default option values.
3498 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3499 jobs = [('chromium', 'try', 'my-builder')]
3500 options = optparse.Values()
3501 requests = git_cl._make_tryjob_schedule_requests(
3502 changelist, jobs, options, patchset=None)
3503
3504 # requestId is non-deterministic. Just assert that it's there and has
3505 # a particular length.
3506 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3507 self.assertEqual(requests, [{
3508 'scheduleBuild': {
3509 'builder': {
3510 'bucket': 'try',
3511 'builder': 'my-builder',
3512 'project': 'chromium'
3513 },
3514 'gerritChanges': [self.exampleGerritChange()],
3515 'properties': {
3516 'category': 'git_cl_try'
3517 },
3518 'tags': [{
3519 'key': 'builder',
3520 'value': 'my-builder'
3521 }, {
3522 'key': 'user_agent',
3523 'value': 'git_cl_try'
3524 }]
3525 }
3526 }])
3527
3528 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3529 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3530 jobs = [('chromium', 'try', 'presubmit')]
3531 options = optparse.Values()
3532 requests = git_cl._make_tryjob_schedule_requests(
3533 changelist, jobs, options, patchset=None)
3534 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3535 'category': 'git_cl_try',
3536 'dry_run': 'true'
3537 })
3538
3539 def testMakeRequestsHelperRevisionSet(self):
3540 # Gitiles commit is specified when revision is in options.
3541 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3542 jobs = [('chromium', 'try', 'my-builder')]
3543 options = optparse.Values({'revision': 'ba5eba11'})
3544 requests = git_cl._make_tryjob_schedule_requests(
3545 changelist, jobs, options, patchset=None)
3546 self.assertEqual(
3547 requests[0]['scheduleBuild']['gitilesCommit'], {
3548 'host': 'chromium-review.googlesource.com',
3549 'id': 'ba5eba11',
3550 'project': 'depot_tools'
3551 })
3552
3553 def testMakeRequestsHelperRetryFailedSet(self):
3554 # An extra tag is added when retry_failed is in options.
3555 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3556 jobs = [('chromium', 'try', 'my-builder')]
3557 options = optparse.Values({'retry_failed': 'true'})
3558 requests = git_cl._make_tryjob_schedule_requests(
3559 changelist, jobs, options, patchset=None)
3560 self.assertEqual(
3561 requests[0]['scheduleBuild']['tags'], [
3562 {
3563 'key': 'builder',
3564 'value': 'my-builder'
3565 },
3566 {
3567 'key': 'user_agent',
3568 'value': 'git_cl_try'
3569 },
3570 {
3571 'key': 'retry_failed',
3572 'value': '1'
3573 }
3574 ])
3575
3576 def testMakeRequestsHelperCategorySet(self):
3577 # The category property can be overriden with options.
3578 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3579 jobs = [('chromium', 'try', 'my-builder')]
3580 options = optparse.Values({'category': 'my-special-category'})
3581 requests = git_cl._make_tryjob_schedule_requests(
3582 changelist, jobs, options, patchset=None)
3583 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3584 {'category': 'my-special-category'})
3585
3586
Edward Lemurda4b6c62020-02-13 00:28:40 +00003587class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003588
3589 def setUp(self):
3590 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003591 mock.patch('git_cl.RunCommand').start()
3592 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3593 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3594 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003595 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003596 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003597
3598 def tearDown(self):
3599 shutil.rmtree(self._top_dir)
3600 super(CMDFormatTestCase, self).tearDown()
3601
Jamie Madill5e96ad12020-01-13 16:08:35 +00003602 def _make_temp_file(self, fname, contents):
3603 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3604 tf.write('\n'.join(contents))
3605
Brian Sheedy59b06a82019-10-14 17:03:29 +00003606 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003607 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003608
Brian Sheedyb4307d52019-12-02 19:18:17 +00003609 def _check_yapf_filtering(self, files, expected):
3610 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3611 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003612
Edward Lemur1a83da12020-03-04 21:18:36 +00003613 def _run_command_mock(self, return_value):
3614 def f(*args, **kwargs):
3615 if 'stdin' in kwargs:
3616 self.assertIsInstance(kwargs['stdin'], bytes)
3617 return return_value
3618 return f
3619
Jamie Madill5e96ad12020-01-13 16:08:35 +00003620 def testClangFormatDiffFull(self):
3621 self._make_temp_file('test.cc', ['// test'])
3622 git_cl.settings.GetFormatFullByDefault.return_value = False
3623 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3624 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3625
3626 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003627 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003628 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3629 self._top_dir, 'HEAD')
3630 self.assertEqual(2, return_value)
3631
3632 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003633 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003634 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3635 self._top_dir, 'HEAD')
3636 self.assertEqual(0, return_value)
3637
3638 def testClangFormatDiff(self):
3639 git_cl.settings.GetFormatFullByDefault.return_value = False
3640 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3641
3642 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003643 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3644 return_value = git_cl._RunClangFormatDiff(
3645 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003646 self.assertEqual(2, return_value)
3647
3648 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003649 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003650 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3651 'HEAD')
3652 self.assertEqual(0, return_value)
3653
Brian Sheedyb4307d52019-12-02 19:18:17 +00003654 def testYapfignoreExplicit(self):
3655 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3656 files = [
3657 'bar.py',
3658 'foo/bar.py',
3659 'foo/baz.py',
3660 'foo/bar/baz.py',
3661 'foo/bar/foobar.py',
3662 ]
3663 expected = [
3664 'bar.py',
3665 'foo/baz.py',
3666 'foo/bar/foobar.py',
3667 ]
3668 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003669
Brian Sheedyb4307d52019-12-02 19:18:17 +00003670 def testYapfignoreSingleWildcards(self):
3671 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3672 files = [
3673 'bar.py', # Matched by *bar.py.
3674 'bar.txt',
3675 'foobar.py', # Matched by *bar.py, foo*.
3676 'foobar.txt', # Matched by foo*.
3677 'bazbar.py', # Matched by *bar.py, baz*.py.
3678 'bazbar.txt',
3679 'foo/baz.txt', # Matched by foo*.
3680 'bar/bar.py', # Matched by *bar.py.
3681 'baz/foo.py', # Matched by baz*.py, foo*.
3682 'baz/foo.txt',
3683 ]
3684 expected = [
3685 'bar.txt',
3686 'bazbar.txt',
3687 'baz/foo.txt',
3688 ]
3689 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003690
Brian Sheedyb4307d52019-12-02 19:18:17 +00003691 def testYapfignoreMultiplewildcards(self):
3692 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3693 files = [
3694 'bar.py', # Matched by *bar*.
3695 'bar.txt', # Matched by *bar*.
3696 'abar.py', # Matched by *bar*.
3697 'foobaz.txt', # Matched by *foo*baz.txt.
3698 'foobaz.py',
3699 'afoobaz.txt', # Matched by *foo*baz.txt.
3700 ]
3701 expected = [
3702 'foobaz.py',
3703 ]
3704 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003705
3706 def testYapfignoreComments(self):
3707 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003708 files = [
3709 'test.py',
3710 'test2.py',
3711 ]
3712 expected = [
3713 'test2.py',
3714 ]
3715 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003716
3717 def testYapfignoreBlankLines(self):
3718 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003719 files = [
3720 'test.py',
3721 'test2.py',
3722 'test3.py',
3723 ]
3724 expected = [
3725 'test3.py',
3726 ]
3727 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003728
3729 def testYapfignoreWhitespace(self):
3730 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003731 files = [
3732 'test.py',
3733 'test2.py',
3734 ]
3735 expected = [
3736 'test2.py',
3737 ]
3738 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003739
Brian Sheedyb4307d52019-12-02 19:18:17 +00003740 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003741 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003742 self._check_yapf_filtering([], [])
3743
3744 def testYapfignoreMissingYapfignore(self):
3745 files = [
3746 'test.py',
3747 ]
3748 expected = [
3749 'test.py',
3750 ]
3751 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003752
3753
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003754if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003755 logging.basicConfig(
3756 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003757 unittest.main()