blob: 0aa29d98795f8aa72eb59e2ff88735b441f095f3 [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:
Anthony Polito8b955342019-09-24 19:01:36 +0000890 if force or not issue:
Anthony Polito8b955342019-09-24 19:01:36 +0000891 if not force:
892 calls += [
Anthony Polito8b955342019-09-24 19:01:36 +0000893 ((['RunEditor'],), description),
894 ]
Josipe827b0f2020-01-30 00:07:20 +0000895 # user wants to edit description
896 if edit_description:
897 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000898 ((['RunEditor'],), edit_description),
899 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000900 ref_to_push = 'abcdef0123456789'
901 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200902 ]
903
904 if custom_cl_base is None:
905 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000906 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000907 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200908 ]
909 parent = 'origin/master'
910 else:
911 calls += [
912 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
913 'refs/remotes/origin/master'],),
914 callError(1)), # Means not ancenstor.
915 (('ask_for_data',
916 'Do you take responsibility for cleaning up potential mess '
917 'resulting from proceeding with upload? Press Enter to upload, '
918 'or Ctrl+C to abort'), ''),
919 ]
920 parent = custom_cl_base
921
922 calls += [
923 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
924 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000925 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200926 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000927 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200928 ref_to_push),
929 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000930 else:
931 ref_to_push = 'HEAD'
932
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000933 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000934 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200935 ((['git', 'rev-list',
936 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
937 ref_to_push],),
938 '1hashPerLine\n'),
939 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000940
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000941 metrics_arguments = []
942
Aaron Gableafd52772017-06-27 16:40:10 -0700943 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700944 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000945 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700946 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400947 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700948 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000949 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700950 else:
951 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000952 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800953
Aaron Gable70f4e242017-06-26 10:45:59 -0700954 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700955 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000956 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000957
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000958 if short_hostname == 'chromium':
959 # All reviwers and ccs get into ref_suffix.
960 for r in sorted(reviewers):
961 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000962 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000963 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000964 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000965 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000966 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000967 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000968 reviewers, cc = [], []
969 else:
970 # TODO(crbug/877717): remove this case.
971 calls += [
972 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
973 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000974 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000975 {
976 e: {'email': e}
977 for e in (reviewers + ['joe@example.com'] + cc)
978 })
979 ]
980 for r in sorted(reviewers):
981 if r != 'bad-account-or-email':
982 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000983 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000984 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000985 if issue is None:
986 cc += ['joe@example.com']
987 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000988 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000989 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000990 if c in cc:
991 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000992
Edward Lemur687ca902018-12-05 02:30:30 +0000993 for k, v in sorted((labels or {}).items()):
994 ref_suffix += ',l=%s+%d' % (k, v)
995 metrics_arguments.append('l=%s+%d' % (k, v))
996
997 if tbr:
998 calls += [
999 (('GetCodeReviewTbrScore',
1000 '%s-review.googlesource.com' % short_hostname,
1001 'my/repo'),
1002 2,),
1003 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001004
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001005 calls += [
1006 (('time.time',), 1000,),
1007 ((['git', 'push',
1008 'https://%s.googlesource.com/my/repo' % short_hostname,
1009 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1010 (('remote:\n'
1011 'remote: Processing changes: (\)\n'
1012 'remote: Processing changes: (|)\n'
1013 'remote: Processing changes: (/)\n'
1014 'remote: Processing changes: (-)\n'
1015 'remote: Processing changes: new: 1 (/)\n'
1016 'remote: Processing changes: new: 1, done\n'
1017 'remote:\n'
1018 'remote: New Changes:\n'
1019 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1020 ' XXX\n'
1021 'remote:\n'
1022 'To https://%s.googlesource.com/my/repo\n'
1023 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1024 ) % (short_hostname, short_hostname)),),
1025 (('time.time',), 2000,),
1026 (('add_repeated',
1027 'sub_commands',
1028 {
1029 'execution_time': 1000,
1030 'command': 'git push',
1031 'exit_code': 0,
1032 'arguments': sorted(metrics_arguments),
1033 }),
1034 None,),
1035 ]
1036
Edward Lemur1b52d872019-05-09 21:12:12 +00001037 final_description = final_description or post_amend_description.strip()
1038 original_title = original_title or title or '<untitled>'
1039 # Trace-related calls
1040 calls += [
1041 # Write a description with context for the current trace.
1042 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001043 'Thu Mar 16 20:00:41 2017\n'
1044 '%(short_hostname)s-review.googlesource.com\n'
1045 '%(change_id)s\n'
1046 '%(title)s\n'
1047 '%(description)s\n'
1048 '1000\n'
1049 '0\n'
1050 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001051 'short_hostname': short_hostname,
1052 'change_id': change_id,
1053 'description': final_description,
1054 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001055 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001056 }],),
1057 None,
1058 ),
1059 # Read traces and shorten git hashes.
1060 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1061 True,
1062 ),
1063 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1064 ('git-hash: 0123456789012345678901234567890123456789\n'
1065 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1066 ),
1067 ((['FileWrite', 'TEMP_DIR/trace-packet',
1068 'git-hash: 012345\n'
1069 'git-hash: abcdea\n'],),
1070 None,
1071 ),
1072 # Make zip file for the git traces.
1073 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1074 'TEMP_DIR'],),
1075 None,
1076 ),
1077 # Collect git config and gitcookies.
1078 ((['git', 'config', '-l'],),
1079 'git-config-output',
1080 ),
1081 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1082 None,
1083 ),
1084 ((['os.path.isfile', '~/.gitcookies'],),
1085 gitcookies_exists,
1086 ),
1087 ]
1088 if gitcookies_exists:
1089 calls += [
1090 ((['FileRead', '~/.gitcookies'],),
1091 'gitcookies 1/SECRET',
1092 ),
1093 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1094 None,
1095 ),
1096 ]
1097 calls += [
1098 # Make zip file for the git config and gitcookies.
1099 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1100 'TEMP_DIR'],),
1101 None,
1102 ),
1103 ]
1104
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001105 # TODO(crbug/877717): this should never be used.
1106 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001107 calls += [
1108 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001109 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001110 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001111 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001112 notify),
1113 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001114 ]
Edward Lemur26964072020-02-19 19:18:51 +00001115 calls += [
1116 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1117 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001118 return calls
1119
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001120 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001121 self,
1122 upload_args,
1123 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001124 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001125 squash=True,
1126 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001127 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001128 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001129 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001130 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001131 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001132 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001133 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001134 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001135 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001136 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001137 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001138 labels=None,
1139 change_id=None,
1140 original_title=None,
1141 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001142 gitcookies_exists=True,
1143 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001144 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001145 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001146 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001147 if squash_mode is None:
1148 if '--no-squash' in upload_args:
1149 squash_mode = 'nosquash'
1150 elif '--squash' in upload_args:
1151 squash_mode = 'squash'
1152 else:
1153 squash_mode = 'default'
1154
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001155 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001156 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001157 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001158 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001159 same_auth=('git-owner.example.com', '', 'pass'))).start()
1160 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1161 lambda _, offer_removal: None).start()
1162 mock.patch('git_cl.gclient_utils.RunEditor',
1163 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1164 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1165 'DownloadGerritHook', force)).start()
1166 mock.patch('git_cl.gclient_utils.FileRead',
1167 lambda path: self._mocked_call(['FileRead', path])).start()
1168 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001169 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001170 ['FileWrite', path, contents])).start()
1171 mock.patch('git_cl.datetime_now',
1172 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1173 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1174 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1175 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001176 '%(now)s\n'
1177 '%(gerrit_host)s\n'
1178 '%(change_id)s\n'
1179 '%(title)s\n'
1180 '%(description)s\n'
1181 '%(execution_time)s\n'
1182 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001183 '%(trace_name)s').start()
1184 mock.patch('git_cl.shutil.make_archive',
1185 lambda *args: self._mocked_call(['make_archive'] +
1186 list(args))).start()
1187 mock.patch('os.path.isfile',
1188 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001189 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001190 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00001191 'git_cl._create_description_from_log', return_value=description).start()
1192 mock.patch(
1193 'git_cl.Changelist._AddChangeIdToCommitMessage',
1194 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001195 mock.patch(
1196 'git_cl.ask_for_data',
1197 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001198
Edward Lemur26964072020-02-19 19:18:51 +00001199 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001200 self.mockGit.config['branch.master.gerritissue'] = (
1201 str(issue) if issue else None)
1202 self.mockGit.config['remote.origin.url'] = (
1203 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001204 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001205
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001206 self.calls = self._gerrit_base_calls(
1207 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001208 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001209 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001210 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001211 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001212 short_hostname=short_hostname,
1213 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001214 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001215 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001216 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001217 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001218 self.calls += self._gerrit_upload_calls(
1219 description, reviewers, squash,
1220 squash_mode=squash_mode,
1221 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001222 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001223 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001224 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001225 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001226 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001227 labels=labels,
1228 change_id=change_id,
1229 original_title=original_title,
1230 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001231 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001232 force=force,
1233 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001234 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001235 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001236 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001237 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001238 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001239 self.assertEqual(
1240 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001241 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001242
Edward Lemur1b52d872019-05-09 21:12:12 +00001243 def test_gerrit_upload_traces_no_gitcookies(self):
1244 self._run_gerrit_upload_test(
1245 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001246 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001247 [],
1248 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001249 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001250 change_id='Ixxx',
1251 gitcookies_exists=False)
1252
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001253 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001254 self._run_gerrit_upload_test(
1255 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001256 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001257 [],
1258 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001259 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001260 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001261
1262 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001263 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001264 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001265 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001266 [],
tandriia60502f2016-06-20 02:01:53 -07001267 squash=False,
1268 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001269 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001270 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001271
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001272 def test_gerrit_no_reviewer(self):
1273 self._run_gerrit_upload_test(
1274 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001275 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001276 [],
1277 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001278 squash_mode='override_nosquash',
1279 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001280
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001281 def test_gerrit_no_reviewer_non_chromium_host(self):
1282 # TODO(crbug/877717): remove this test case.
1283 self._run_gerrit_upload_test(
1284 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001285 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001286 [],
1287 squash=False,
1288 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001289 short_hostname='other',
1290 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001291
Nick Carter8692b182017-11-06 16:30:38 -08001292 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001293 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001294 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001295 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001296 squash=False,
1297 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001298 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1299 change_id='I123456789',
1300 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001301
ukai@chromium.orge8077812012-02-03 03:41:46 +00001302 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001303 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001304 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001305 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001306 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001307 squash=False,
1308 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001309 notify=True,
1310 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001311 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001312 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001313
Anthony Polito8b955342019-09-24 19:01:36 +00001314 def test_gerrit_upload_force_sets_bug(self):
1315 self._run_gerrit_upload_test(
1316 ['-b', '10000', '-f'],
1317 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1318 [],
1319 force=True,
1320 expected_upstream_ref='origin/master',
1321 fetched_description='desc=\n\nChange-Id: Ixxx',
1322 original_title='Initial upload',
1323 change_id='Ixxx')
1324
1325 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1326 self._run_gerrit_upload_test(
1327 ['-b', '10000', '-f', '-m', 'Title'],
1328 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1329 [],
1330 force=True,
1331 issue='123456',
1332 expected_upstream_ref='origin/master',
1333 fetched_description='desc=\n\nChange-Id: Ixxxx',
1334 original_title='Title',
1335 title='Title',
1336 change_id='Izzzz')
1337
Dan Beamd8b04ca2019-10-10 21:23:26 +00001338 def test_gerrit_upload_force_sets_fixed(self):
1339 self._run_gerrit_upload_test(
1340 ['-x', '10000', '-f'],
1341 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1342 [],
1343 force=True,
1344 expected_upstream_ref='origin/master',
1345 fetched_description='desc=\n\nChange-Id: Ixxx',
1346 original_title='Initial upload',
1347 change_id='Ixxx')
1348
ukai@chromium.orge8077812012-02-03 03:41:46 +00001349 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001350 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1351 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001352 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001353 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001354 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001355 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001356 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001357 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001358 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001359 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001360 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001361 labels={'Code-Review': 2},
1362 change_id='123456789',
1363 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001364
1365 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001366 self._run_gerrit_upload_test(
1367 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001368 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001369 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001370 expected_upstream_ref='origin/master',
1371 change_id='123456789',
1372 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001373
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001374 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001375 self._run_gerrit_upload_test(
1376 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001377 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001378 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001379 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001380 expected_upstream_ref='origin/master',
1381 change_id='123456789',
1382 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001383
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001384 def test_gerrit_upload_squash_first_with_labels(self):
1385 self._run_gerrit_upload_test(
1386 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001387 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001388 [],
1389 squash=True,
1390 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001391 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1392 change_id='123456789',
1393 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001394
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001395 def test_gerrit_upload_squash_first_against_rev(self):
1396 custom_cl_base = 'custom_cl_base_rev_or_branch'
1397 self._run_gerrit_upload_test(
1398 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001399 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001400 [],
1401 squash=True,
1402 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001403 custom_cl_base=custom_cl_base,
1404 change_id='123456789',
1405 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001406 self.assertIn(
1407 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1408 sys.stdout.getvalue())
1409
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001410 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001411 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001412 self._run_gerrit_upload_test(
1413 ['--squash'],
1414 description,
1415 [],
1416 squash=True,
1417 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001418 issue=123456,
1419 change_id='123456789',
1420 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001421
Edward Lemurd55c5072020-02-20 01:09:07 +00001422 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001423 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001424 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001425 with self.assertRaises(SystemExitMock):
1426 self._run_gerrit_upload_test(
1427 ['--squash'],
1428 description,
1429 [],
1430 squash=True,
1431 expected_upstream_ref='origin/master',
1432 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001433 fetched_status='ABANDONED',
1434 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001435 self.assertEqual(
1436 'Change https://chromium-review.googlesource.com/123456 has been '
1437 'abandoned, new uploads are not allowed\n',
1438 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001439
Edward Lemurda4b6c62020-02-13 00:28:40 +00001440 @mock.patch(
1441 'gerrit_util.GetAccountDetails',
1442 return_value={'email': 'yet-another@example.com'})
1443 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001444 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001445 self._run_gerrit_upload_test(
1446 ['--squash'],
1447 description,
1448 [],
1449 squash=True,
1450 expected_upstream_ref='origin/master',
1451 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001452 other_cl_owner='other@example.com',
1453 change_id='123456789',
1454 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001455 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001456 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001457 'authenticate to Gerrit as yet-another@example.com.\n'
1458 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001459 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001460
Josipe827b0f2020-01-30 00:07:20 +00001461 def test_upload_change_description_editor(self):
1462 fetched_description = 'foo\n\nChange-Id: 123456789'
1463 description = 'bar\n\nChange-Id: 123456789'
1464 self._run_gerrit_upload_test(
1465 ['--squash', '--edit-description'],
1466 description,
1467 [],
1468 fetched_description=fetched_description,
1469 squash=True,
1470 expected_upstream_ref='origin/master',
1471 issue=123456,
1472 change_id='123456789',
1473 original_title='User input',
1474 edit_description=description)
1475
Edward Lemurda4b6c62020-02-13 00:28:40 +00001476 @mock.patch('git_cl.RunGit')
1477 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001478 @mock.patch('sys.stdin', StringIO('\n'))
1479 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001480 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001481 def mock_run_git(*args, **_kwargs):
1482 if args[0] == ['for-each-ref',
1483 '--format=%(refname:short) %(upstream:short)',
1484 'refs/heads']:
1485 # Create a local branch dependency tree that looks like this:
1486 # test1 -> test2 -> test3 -> test4 -> test5
1487 # -> test3.1
1488 # test6 -> test0
1489 branch_deps = [
1490 'test2 test1', # test1 -> test2
1491 'test3 test2', # test2 -> test3
1492 'test3.1 test2', # test2 -> test3.1
1493 'test4 test3', # test3 -> test4
1494 'test5 test4', # test4 -> test5
1495 'test6 test0', # test0 -> test6
1496 'test7', # test7
1497 ]
1498 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001499 git_cl.RunGit.side_effect = mock_run_git
1500 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001501
1502 class MockChangelist():
1503 def __init__(self):
1504 pass
1505 def GetBranch(self):
1506 return 'test1'
1507 def GetIssue(self):
1508 return '123'
1509 def GetPatchset(self):
1510 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001511 def IsGerrit(self):
1512 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001513
1514 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1515 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001516 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001517 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001518 'This command will checkout all dependent branches '
1519 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001520 'or Ctrl+C to abort',
1521 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001522 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001523
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001524 def test_gerrit_change_id(self):
1525 self.calls = [
1526 ((['git', 'write-tree'], ),
1527 'hashtree'),
1528 ((['git', 'rev-parse', 'HEAD~0'], ),
1529 'branch-parent'),
1530 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1531 'A B <a@b.org> 1456848326 +0100'),
1532 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1533 'C D <c@d.org> 1456858326 +0100'),
1534 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1535 'hashchange'),
1536 ]
1537 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1538 self.assertEqual(change_id, 'Ihashchange')
1539
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001540 def test_desecription_append_footer(self):
1541 for init_desc, footer_line, expected_desc in [
1542 # Use unique desc first lines for easy test failure identification.
1543 ('foo', 'R=one', 'foo\n\nR=one'),
1544 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1545 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1546 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1547 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1548 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1549 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1550 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1551 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1552 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1553 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1554 ]:
1555 desc = git_cl.ChangeDescription(init_desc)
1556 desc.append_footer(footer_line)
1557 self.assertEqual(desc.description, expected_desc)
1558
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001559 def test_update_reviewers(self):
1560 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001561 ('foo', [], [],
1562 'foo'),
1563 ('foo\nR=xx', [], [],
1564 'foo\nR=xx'),
1565 ('foo\nTBR=xx', [], [],
1566 'foo\nTBR=xx'),
1567 ('foo', ['a@c'], [],
1568 'foo\n\nR=a@c'),
1569 ('foo\nR=xx', ['a@c'], [],
1570 'foo\n\nR=a@c, xx'),
1571 ('foo\nTBR=xx', ['a@c'], [],
1572 'foo\n\nR=a@c\nTBR=xx'),
1573 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1574 'foo\n\nR=a@c, yy\nTBR=xx'),
1575 ('foo\nBUG=', ['a@c'], [],
1576 'foo\nBUG=\nR=a@c'),
1577 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1578 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1579 ('foo', ['a@c', 'b@c'], [],
1580 'foo\n\nR=a@c, b@c'),
1581 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1582 'foo\nBar\n\nR=c@c\nBUG='),
1583 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1584 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001585 # Same as the line before, but full of whitespaces.
1586 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001587 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001588 'foo\nBar\n\nR=c@c\n BUG =',
1589 ),
1590 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001591 ('foo BUG=allo R=joe ', ['c@c'], [],
1592 'foo BUG=allo R=joe\n\nR=c@c'),
1593 # Redundant TBRs get promoted to Rs
1594 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1595 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001596 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001597 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001598 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001599 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001600 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001601 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001602 actual.append(obj.description)
1603 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001604
Nodir Turakulov23b82142017-11-16 11:04:25 -08001605 def test_get_hash_tags(self):
1606 cases = [
1607 ('', []),
1608 ('a', []),
1609 ('[a]', ['a']),
1610 ('[aa]', ['aa']),
1611 ('[a ]', ['a']),
1612 ('[a- ]', ['a']),
1613 ('[a- b]', ['a-b']),
1614 ('[a--b]', ['a-b']),
1615 ('[a', []),
1616 ('[a]x', ['a']),
1617 ('[aa]x', ['aa']),
1618 ('[a b]', ['a-b']),
1619 ('[a b]', ['a-b']),
1620 ('[a__b]', ['a-b']),
1621 ('[a] x', ['a']),
1622 ('[a][b]', ['a', 'b']),
1623 ('[a] [b]', ['a', 'b']),
1624 ('[a][b]x', ['a', 'b']),
1625 ('[a][b] x', ['a', 'b']),
1626 ('[a]\n[b]', ['a']),
1627 ('[a\nb]', []),
1628 ('[a][', ['a']),
1629 ('Revert "[a] feature"', ['a']),
1630 ('Reland "[a] feature"', ['a']),
1631 ('Revert: [a] feature', ['a']),
1632 ('Reland: [a] feature', ['a']),
1633 ('Revert "Reland: [a] feature"', ['a']),
1634 ('Foo: feature', ['foo']),
1635 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001636 ('Change Foo::Bar', []),
1637 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001638 ('Revert "Foo bar: feature"', ['foo-bar']),
1639 ('Reland "Foo bar: feature"', ['foo-bar']),
1640 ]
1641 for desc, expected in cases:
1642 change_desc = git_cl.ChangeDescription(desc)
1643 actual = change_desc.get_hash_tags()
1644 self.assertEqual(
1645 actual,
1646 expected,
1647 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1648
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001649 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001650 self.assertEqual(None, git_cl.GetTargetRef(None,
1651 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001652 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001653
wittman@chromium.org455dc922015-01-26 20:15:50 +00001654 # Check default target refs for branches.
1655 self.assertEqual('refs/heads/master',
1656 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
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/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001660 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001661 self.assertEqual('refs/heads/master',
1662 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001663 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001664 self.assertEqual('refs/branch-heads/123',
1665 git_cl.GetTargetRef('origin',
1666 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001667 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001668 self.assertEqual('refs/diff/test',
1669 git_cl.GetTargetRef('origin',
1670 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001671 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001672 self.assertEqual('refs/heads/chrome/m42',
1673 git_cl.GetTargetRef('origin',
1674 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001675 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001676
1677 # Check target refs for user-specified target branch.
1678 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1679 'refs/remotes/branch-heads/123'):
1680 self.assertEqual('refs/branch-heads/123',
1681 git_cl.GetTargetRef('origin',
1682 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001683 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001684 for branch in ('origin/master', 'remotes/origin/master',
1685 'refs/remotes/origin/master'):
1686 self.assertEqual('refs/heads/master',
1687 git_cl.GetTargetRef('origin',
1688 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001689 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001690 for branch in ('master', 'heads/master', 'refs/heads/master'):
1691 self.assertEqual('refs/heads/master',
1692 git_cl.GetTargetRef('origin',
1693 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001694 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001695
Edward Lemurda4b6c62020-02-13 00:28:40 +00001696 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1697 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001698 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001699 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1700
Edward Lemur85153282020-02-14 22:06:29 +00001701 def assertIssueAndPatchset(
1702 self, branch='master', issue='123456', patchset='7',
1703 git_short_host='chromium'):
1704 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001705 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001706 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001707 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001708 self.assertEqual(
1709 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001710 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001711
Edward Lemur85153282020-02-14 22:06:29 +00001712 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001713 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001714 self.mockGit.config['remote.origin.url'] = (
1715 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001716 gerrit_util.GetChangeDetail.return_value = {
1717 'current_revision': '7777777777',
1718 'revisions': {
1719 '1111111111': {
1720 '_number': 1,
1721 'fetch': {'http': {
1722 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1723 'ref': 'refs/changes/56/123456/1',
1724 }},
1725 },
1726 '7777777777': {
1727 '_number': 7,
1728 'fetch': {'http': {
1729 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1730 'ref': 'refs/changes/56/123456/7',
1731 }},
1732 },
1733 },
1734 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001735
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001736 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001737 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001738 self.calls += [
1739 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1740 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001741 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001742 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001743 ]
1744 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001745 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001746
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001747 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001748 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001749 self.calls += [
1750 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1751 'refs/changes/56/123456/7'],), ''),
1752 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001753 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001754 ]
Edward Lemur85153282020-02-14 22:06:29 +00001755 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1756 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001757
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001758 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001759 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001760 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001761 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001762 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001763 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001764 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001765 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001766 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001767 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001768
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001769 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001770 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001771 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001772 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001773 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001774 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001775 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001776 ]
1777 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001778 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001779 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001780
Aaron Gable697a91b2018-01-19 15:20:15 -08001781 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001782 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001783 self.calls += [
1784 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1785 'refs/changes/56/123456/1'],), ''),
1786 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001787 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001788 ]
1789 self.assertEqual(git_cl.main(
1790 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1791 0)
Edward Lemur85153282020-02-14 22:06:29 +00001792 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001793
Edward Lemurd55c5072020-02-20 01:09:07 +00001794 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001795 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001796 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001797 self.calls += [
1798 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001799 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001800 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001801 ]
1802 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001803 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001804 self.assertEqual(
1805 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1806 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001807
Edward Lemurda4b6c62020-02-13 00:28:40 +00001808 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001809 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001810 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001811 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001812 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001813 self.mockGit.config['remote.origin.url'] = (
1814 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001815 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001816 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001817 self.assertEqual(
1818 'change 123456 at https://chromium-review.googlesource.com does not '
1819 'exist or you have no access to it\n',
1820 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001821
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001822 def _checkout_calls(self):
1823 return [
1824 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001825 'branch\\..*\\.gerritissue'], ),
1826 ('branch.ger-branch.gerritissue 123456\n'
1827 'branch.gbranch654.gerritissue 654321\n')),
1828 ]
1829
1830 def test_checkout_gerrit(self):
1831 """Tests git cl checkout <issue>."""
1832 self.calls = self._checkout_calls()
1833 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1834 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1835
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001836 def test_checkout_not_found(self):
1837 """Tests git cl checkout <issue>."""
1838 self.calls = self._checkout_calls()
1839 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1840
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001841 def test_checkout_no_branch_issues(self):
1842 """Tests git cl checkout <issue>."""
1843 self.calls = [
1844 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001845 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001846 ]
1847 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1848
Edward Lemur26964072020-02-19 19:18:51 +00001849 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001850 mock.patch(
1851 'git_cl.ask_for_data',
1852 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001853 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1854 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001855 self.mockGit.config['remote.origin.url'] = (
1856 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001857 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001858 cl.branch = 'master'
1859 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001860 return cl
1861
Edward Lemurd55c5072020-02-20 01:09:07 +00001862 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001863 def test_gerrit_ensure_authenticated_missing(self):
1864 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001865 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001866 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001867 with self.assertRaises(SystemExitMock):
1868 cl.EnsureAuthenticated(force=False)
1869 self.assertEqual(
1870 'Credentials for the following hosts are required:\n'
1871 ' chromium-review.googlesource.com\n'
1872 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1873 'You can (re)generate your credentials by visiting '
1874 'https://chromium-review.googlesource.com/new-password\n',
1875 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001876
1877 def test_gerrit_ensure_authenticated_conflict(self):
1878 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001879 'chromium.googlesource.com':
1880 ('git-one.example.com', None, 'secret1'),
1881 'chromium-review.googlesource.com':
1882 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001883 })
1884 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001885 (('ask_for_data', 'If you know what you are doing '
1886 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001887 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1888
1889 def test_gerrit_ensure_authenticated_ok(self):
1890 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001891 'chromium.googlesource.com':
1892 ('git-same.example.com', None, 'secret'),
1893 'chromium-review.googlesource.com':
1894 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001895 })
1896 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1897
tandrii@chromium.org28253532016-04-14 13:46:56 +00001898 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001899 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1900 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001901 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1902
Eric Boren2fb63102018-10-05 13:05:03 +00001903 def test_gerrit_ensure_authenticated_bearer_token(self):
1904 cl = self._test_gerrit_ensure_authenticated_common(auth={
1905 'chromium.googlesource.com':
1906 ('', None, 'secret'),
1907 'chromium-review.googlesource.com':
1908 ('', None, 'secret'),
1909 })
1910 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1911 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1912 'chromium.googlesource.com')
1913 self.assertTrue('Bearer' in header)
1914
Daniel Chengcf6269b2019-05-18 01:02:12 +00001915 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001916 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001917 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001918 (('logging.warning',
1919 'Ignoring branch %(branch)s with non-https remote '
1920 '%(remote)s', {
1921 'branch': 'master',
1922 'remote': 'custom-scheme://repo'}
1923 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001924 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001925 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1926 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1927 mock.patch('logging.warning',
1928 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001929 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001930 cl.branch = 'master'
1931 cl.branchref = 'refs/heads/master'
1932 cl.lookedup_issue = True
1933 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1934
Florian Mayerae510e82020-01-30 21:04:48 +00001935 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001936 self.mockGit.config['remote.origin.url'] = (
1937 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001938 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001939 (('logging.error',
1940 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1941 'but it doesn\'t exist.', {
1942 'remote': 'origin',
1943 'branch': 'master',
1944 'url': 'git@somehost.example:foo/bar.git'}
1945 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001946 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001947 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1948 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1949 mock.patch('logging.error',
1950 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001951 cl = git_cl.Changelist()
1952 cl.branch = 'master'
1953 cl.branchref = 'refs/heads/master'
1954 cl.lookedup_issue = True
1955 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1956
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001957 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001958 self.mockGit.config['branch.master.gerritissue'] = '123'
1959 self.mockGit.config['branch.master.gerritserver'] = (
1960 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001961 self.mockGit.config['remote.origin.url'] = (
1962 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001963 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001964 (('SetReview', 'chromium-review.googlesource.com',
1965 'infra%2Finfra~123', None,
1966 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001967 ]
tandriid9e5ce52016-07-13 02:32:59 -07001968
1969 def test_cmd_set_commit_gerrit_clear(self):
1970 self._cmd_set_commit_gerrit_common(0)
1971 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1972
1973 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001974 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001975 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1976
tandriid9e5ce52016-07-13 02:32:59 -07001977 def test_cmd_set_commit_gerrit(self):
1978 self._cmd_set_commit_gerrit_common(2)
1979 self.assertEqual(0, git_cl.main(['set-commit']))
1980
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001981 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001982 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001983 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001984
1985 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001986 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001987
Edward Lemurda4b6c62020-02-13 00:28:40 +00001988 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001989 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001990 try:
1991 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001992 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001993 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001994 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001995
1996 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001997 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001998 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001999 return 'foobar'
2000
Edward Lemurda4b6c62020-02-13 00:28:40 +00002001 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07002002 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002003 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002004 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002005 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002006
iannuccie53c9352016-08-17 14:40:40 -07002007 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002008
iannuccie53c9352016-08-17 14:40:40 -07002009 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002010 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002011 return 'foobar'
2012
Edward Lemurda4b6c62020-02-13 00:28:40 +00002013 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2014 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002015 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002016 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002017
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002018 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002019 self.mockGit.config['remote.origin.url'] = (
2020 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002021 gerrit_util.GetChangeDetail.return_value = {
2022 'current_revision': 'sha1',
2023 'revisions': {'sha1': {
2024 'commit': {'message': 'foobar'},
2025 }},
2026 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002027 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002028 'description',
2029 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2030 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002031 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002032
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002033 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002034 mock.patch('git_cl.Changelist', ChangelistMock).start()
2035 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002036
2037 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2038 self.assertEqual('hihi', ChangelistMock.desc)
2039
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002040 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002041 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002042
2043 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002044 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002045 '# Enter a description of the change.\n'
2046 '# This will be displayed on the codereview site.\n'
2047 '# The first line will also be used as the subject of the review.\n'
2048 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002049 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002050 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002051 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002052 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002053 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002054
Edward Lemur6c6827c2020-02-06 21:15:18 +00002055 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002056 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002057
Edward Lemurda4b6c62020-02-13 00:28:40 +00002058 mock.patch('git_cl.Changelist.FetchDescription',
2059 lambda *args: current_desc).start()
2060 mock.patch('git_cl.Changelist.UpdateDescription',
2061 UpdateDescription).start()
2062 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002063
Edward Lemur85153282020-02-14 22:06:29 +00002064 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002065 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002066
Dan Beamd8b04ca2019-10-10 21:23:26 +00002067 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2068 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2069
2070 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002071 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002072 '# Enter a description of the change.\n'
2073 '# This will be displayed on the codereview site.\n'
2074 '# The first line will also be used as the subject of the review.\n'
2075 '#--------------------This line is 72 characters long'
2076 '--------------------\n'
2077 'Some.\n\nFixed: 123\nChange-Id: xxx',
2078 desc)
2079 return desc
2080
Edward Lemurda4b6c62020-02-13 00:28:40 +00002081 mock.patch('git_cl.Changelist.FetchDescription',
2082 lambda *args: current_desc).start()
2083 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002084
Edward Lemur85153282020-02-14 22:06:29 +00002085 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002086 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002087
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002088 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002089 mock.patch('git_cl.Changelist', ChangelistMock).start()
2090 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002091
2092 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2093 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2094
kmarshall3bff56b2016-06-06 18:31:47 -07002095 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002096 self.calls = [
2097 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002098 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002099 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002100 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002101 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002102 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002103
Edward Lemurda4b6c62020-02-13 00:28:40 +00002104 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002105 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002106 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2107 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002108 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002109
2110 self.assertEqual(0, git_cl.main(['archive', '-f']))
2111
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002112 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002113 self.calls = [
2114 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2115 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2116 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2117 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002118 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2119 ((['git', 'branch', '-D', 'foo'],), '')
2120 ]
2121
Edward Lemurda4b6c62020-02-13 00:28:40 +00002122 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002123 lambda branches, fine_grained, max_processes:
2124 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2125 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002126 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002127
2128 self.assertEqual(0, git_cl.main(['archive', '-f']))
2129
kmarshall3bff56b2016-06-06 18:31:47 -07002130 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002131 self.calls = [
2132 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2133 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002134 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002135 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002136
Edward Lemurda4b6c62020-02-13 00:28:40 +00002137 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002138 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002139 [(MockChangelistWithBranchAndIssue('master', 1),
2140 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002141
2142 self.assertEqual(1, git_cl.main(['archive', '-f']))
2143
2144 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002145 self.calls = [
2146 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2147 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002148 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002149 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002150
Edward Lemurda4b6c62020-02-13 00:28:40 +00002151 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002152 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002153 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2154 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002155 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002156
kmarshall9249e012016-08-23 12:02:16 -07002157 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2158
2159 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002160 self.calls = [
2161 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2162 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002163 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002164 ((['git', 'branch', '-D', 'foo'],), '')
2165 ]
kmarshall9249e012016-08-23 12:02:16 -07002166
Edward Lemurda4b6c62020-02-13 00:28:40 +00002167 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002168 lambda branches, fine_grained, max_processes:
2169 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2170 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002171 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002172
2173 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002174
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002175 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002176 self.calls = [
2177 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2178 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2179 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002180 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2181 'refs/tags/git-cl-archived-456-foo'),
2182 ((['git', 'branch', '-D', 'foo'],), CERR1),
2183 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2184 'refs/tags/git-cl-archived-456-foo'),
2185 ]
2186
Edward Lemurda4b6c62020-02-13 00:28:40 +00002187 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002188 lambda branches, fine_grained, max_processes:
2189 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2190 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002191 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002192
2193 self.assertEqual(0, git_cl.main(['archive', '-f']))
2194
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002195 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002196 self.mockGit.config['branch.master.gerritissue'] = '123'
2197 self.mockGit.config['branch.master.gerritserver'] = (
2198 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002199 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002200 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002201 ]
2202 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002203 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2204 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002205
Aaron Gable400e9892017-07-12 15:31:21 -07002206 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002207 self.mockGit.config['branch.master.gerritissue'] = '123'
2208 self.mockGit.config['branch.master.gerritserver'] = (
2209 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002210 mock.patch('git_cl.Changelist.FetchDescription',
2211 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002212 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002213 ((['git', 'log', '-1', '--format=%B'],),
2214 'This is a description\n\nChange-Id: Ideadbeef'),
2215 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002216 ]
2217 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002218 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2219 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002220
phajdan.jre328cf92016-08-22 04:12:17 -07002221 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002222 self.mockGit.config['branch.master.gerritissue'] = '123'
2223 self.mockGit.config['branch.master.gerritserver'] = (
2224 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002225 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002226 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002227 {'issue': 123,
2228 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002229 ''),
2230 ]
2231 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2232
tandrii16e0b4e2016-06-07 10:34:28 -07002233 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002234 mock.patch(
2235 'git_cl.os.path.abspath',
2236 lambda path: self._mocked_call(['abspath', path])).start()
2237 mock.patch(
2238 'git_cl.os.path.exists',
2239 lambda path: self._mocked_call(['exists', path])).start()
2240 mock.patch(
2241 'git_cl.gclient_utils.FileRead',
2242 lambda path: self._mocked_call(['FileRead', path])).start()
2243 mock.patch(
2244 'git_cl.gclient_utils.rm_file_or_tree',
2245 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002246 mock.patch(
2247 'git_cl.ask_for_data',
2248 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002249 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002250
2251 def test_GerritCommitMsgHookCheck_custom_hook(self):
2252 cl = self._common_GerritCommitMsgHookCheck()
2253 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002254 ((['exists', '.git/hooks/commit-msg'],), True),
2255 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002256 '#!/bin/sh\necho "custom hook"')
2257 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002258 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002259
2260 def test_GerritCommitMsgHookCheck_not_exists(self):
2261 cl = self._common_GerritCommitMsgHookCheck()
2262 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002263 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002264 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002265 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002266
2267 def test_GerritCommitMsgHookCheck(self):
2268 cl = self._common_GerritCommitMsgHookCheck()
2269 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002270 ((['exists', '.git/hooks/commit-msg'],), True),
2271 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002272 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002273 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002274 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002275 ''),
2276 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002277 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002278
tandriic4344b52016-08-29 06:04:54 -07002279 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002280 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2281 self.mockGit.config['branch.master.gerritserver'] = (
2282 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002283 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002284 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002285 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002286 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002287 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002288 'labels': {},
2289 'current_revision': 'deadbeaf',
2290 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002291 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002292 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002293 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002294 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2295 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002296 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002297 self.assertEqual(0, cl.CMDLand(force=True,
2298 bypass_hooks=True,
2299 verbose=True,
2300 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002301 self.assertIn(
2302 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002303 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002304 self.assertIn(
2305 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002306 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002307
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002308 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002309 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002310
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002311 def test_gerrit_change_detail_cache_simple(self):
2312 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002313 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002314 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002315 cl1._cached_remote_url = (
2316 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002317 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002318 cl2._cached_remote_url = (
2319 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002320 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2321 self.assertEqual(cl1._GetChangeDetail(), 'a')
2322 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002323
2324 def test_gerrit_change_detail_cache_options(self):
2325 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002326 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002327 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002328 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002329 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2330 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2331 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2332 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2333 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2334 self.assertEqual(cl._GetChangeDetail(), 'cab')
2335
2336 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2337 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2338 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2339 self.assertEqual(cl._GetChangeDetail(), 'cab')
2340
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002341 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002342 gerrit_util.GetChangeDetail.return_value = {
2343 'current_revision': 'rev1',
2344 'revisions': {
2345 'rev1': {'commit': {'message': 'desc1'}},
2346 },
2347 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002348
2349 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002350 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002351 cl._cached_remote_url = (
2352 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002353 self.assertEqual(cl.FetchDescription(), 'desc1')
2354 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002355
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002356 def test_print_current_creds(self):
2357 class CookiesAuthenticatorMock(object):
2358 def __init__(self):
2359 self.gitcookies = {
2360 'host.googlesource.com': ('user', 'pass'),
2361 'host-review.googlesource.com': ('user', 'pass'),
2362 }
2363 self.netrc = self
2364 self.netrc.hosts = {
2365 'github.com': ('user2', None, 'pass2'),
2366 'host2.googlesource.com': ('user3', None, 'pass'),
2367 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002368 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2369 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002370 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2371 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2372 ' Host\t User\t Which file',
2373 '============================\t=====\t===========',
2374 'host-review.googlesource.com\t user\t.gitcookies',
2375 ' host.googlesource.com\t user\t.gitcookies',
2376 ' host2.googlesource.com\tuser3\t .netrc',
2377 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002378 sys.stdout.seek(0)
2379 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002380 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2381 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2382 ' Host\tUser\t Which file',
2383 '============================\t====\t===========',
2384 'host-review.googlesource.com\tuser\t.gitcookies',
2385 ' host.googlesource.com\tuser\t.gitcookies',
2386 ])
2387
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002388 def _common_creds_check_mocks(self):
2389 def exists_mock(path):
2390 dirname = os.path.dirname(path)
2391 if dirname == os.path.expanduser('~'):
2392 dirname = '~'
2393 base = os.path.basename(path)
2394 if base in ('.netrc', '.gitcookies'):
2395 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2396 # git cl also checks for existence other files not relevant to this test.
2397 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002398 mock.patch(
2399 'git_cl.ask_for_data',
2400 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002401 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002402
2403 def test_creds_check_gitcookies_not_configured(self):
2404 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002405 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2406 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002407 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002408 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002409 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2410 (('os.path.exists', '~/.netrc'), True),
2411 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2412 'or Ctrl+C to abort'), ''),
2413 ((['git', 'config', '--global', 'http.cookiefile',
2414 os.path.expanduser('~/.gitcookies')], ), ''),
2415 ]
2416 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002417 self.assertTrue(
2418 sys.stdout.getvalue().startswith(
2419 'You seem to be using outdated .netrc for git credentials:'))
2420 self.assertIn(
2421 '\nConfigured git to use .gitcookies from',
2422 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002423
2424 def test_creds_check_gitcookies_configured_custom_broken(self):
2425 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002426 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2427 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002428 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002429 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002430 ((['git', 'config', '--global', 'http.cookiefile'],),
2431 '/custom/.gitcookies'),
2432 (('os.path.exists', '/custom/.gitcookies'), False),
2433 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2434 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2435 ((['git', 'config', '--global', 'http.cookiefile',
2436 os.path.expanduser('~/.gitcookies')], ), ''),
2437 ]
2438 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002439 self.assertIn(
2440 'WARNING: You have configured custom path to .gitcookies: ',
2441 sys.stdout.getvalue())
2442 self.assertIn(
2443 'However, your configured .gitcookies file is missing.',
2444 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002445
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002446 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002447 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002448 self.mockGit.config['remote.origin.url'] = (
2449 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002450 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002451 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002452 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002453 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002454 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002455 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002456
Edward Lemurda4b6c62020-02-13 00:28:40 +00002457 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2458 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002459 self.mockGit.config['remote.origin.url'] = (
2460 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002461 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002462 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002463 'current_revision': 'ba5eba11',
2464 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002465 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002466 '_number': 1,
2467 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002468 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002469 '_number': 2,
2470 },
2471 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002472 'messages': [
2473 {
2474 u'_revision_number': 1,
2475 u'author': {
2476 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002477 u'email': u'could-be-anything@example.com',
2478 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002479 },
2480 u'date': u'2017-03-15 20:08:45.000000000',
2481 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002482 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002483 u'tag': u'autogenerated:cq:dry-run'
2484 },
2485 {
2486 u'_revision_number': 2,
2487 u'author': {
2488 u'_account_id': 11151243,
2489 u'email': u'owner@example.com',
2490 u'name': u'owner'
2491 },
2492 u'date': u'2017-03-16 20:00:41.000000000',
2493 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2494 u'message': u'PTAL',
2495 },
2496 {
2497 u'_revision_number': 2,
2498 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002499 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002500 u'email': u'reviewer@example.com',
2501 u'name': u'reviewer'
2502 },
2503 u'date': u'2017-03-17 05:19:37.500000000',
2504 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2505 u'message': u'Patch Set 2: Code-Review+1',
2506 },
2507 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002508 }
2509 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002510 (('GetChangeComments', 'chromium-review.googlesource.com',
2511 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002512 '/COMMIT_MSG': [
2513 {
2514 'author': {'email': u'reviewer@example.com'},
2515 'updated': u'2017-03-17 05:19:37.500000000',
2516 'patch_set': 2,
2517 'side': 'REVISION',
2518 'message': 'Please include a bug link',
2519 },
2520 ],
2521 'codereview.settings': [
2522 {
2523 'author': {'email': u'owner@example.com'},
2524 'updated': u'2017-03-16 20:00:41.000000000',
2525 'patch_set': 2,
2526 'side': 'PARENT',
2527 'line': 42,
2528 'message': 'I removed this because it is bad',
2529 },
2530 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002531 }),
2532 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2533 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002534 ] * 2 + [
2535 (('write_json', 'output.json', [
2536 {
2537 u'date': u'2017-03-16 20:00:41.000000',
2538 u'message': (
2539 u'PTAL\n' +
2540 u'\n' +
2541 u'codereview.settings\n' +
2542 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2543 u'c/1/2/codereview.settings#b42\n' +
2544 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002545 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002546 u'approval': False,
2547 u'disapproval': False,
2548 u'sender': u'owner@example.com'
2549 }, {
2550 u'date': u'2017-03-17 05:19:37.500000',
2551 u'message': (
2552 u'Patch Set 2: Code-Review+1\n' +
2553 u'\n' +
2554 u'/COMMIT_MSG\n' +
2555 u' PS2, File comment: https://chromium-review.googlesource' +
2556 u'.com/c/1/2//COMMIT_MSG#\n' +
2557 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002558 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002559 u'approval': False,
2560 u'disapproval': False,
2561 u'sender': u'reviewer@example.com'
2562 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002563 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002564 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002565 expected_comments_summary = [
2566 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002567 message=(
2568 u'PTAL\n' +
2569 u'\n' +
2570 u'codereview.settings\n' +
2571 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2572 u'c/1/2/codereview.settings#b42\n' +
2573 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002574 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002575 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002576 disapproval=False, approval=False, sender=u'owner@example.com'),
2577 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002578 message=(
2579 u'Patch Set 2: Code-Review+1\n' +
2580 u'\n' +
2581 u'/COMMIT_MSG\n' +
2582 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2583 u'c/1/2//COMMIT_MSG#\n' +
2584 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002585 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002586 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002587 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2588 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002589 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002590 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002591 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002592 self.assertEqual(
2593 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2594
2595 def test_git_cl_comments_robot_comments(self):
2596 # git cl comments also fetches robot comments (which are considered a type
2597 # of autogenerated comment), and unlike other types of comments, only robot
2598 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002599 self.mockGit.config['remote.origin.url'] = (
2600 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002601 gerrit_util.GetChangeDetail.return_value = {
2602 'owner': {'email': 'owner@example.com'},
2603 'current_revision': 'ba5eba11',
2604 'revisions': {
2605 'deadbeaf': {
2606 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002607 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002608 'ba5eba11': {
2609 '_number': 2,
2610 },
2611 },
2612 'messages': [
2613 {
2614 u'_revision_number': 1,
2615 u'author': {
2616 u'_account_id': 1111084,
2617 u'email': u'commit-bot@chromium.org',
2618 u'name': u'Commit Bot'
2619 },
2620 u'date': u'2017-03-15 20:08:45.000000000',
2621 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2622 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2623 u'tag': u'autogenerated:cq:dry-run'
2624 },
2625 {
2626 u'_revision_number': 1,
2627 u'author': {
2628 u'_account_id': 123,
2629 u'email': u'tricium@serviceaccount.com',
2630 u'name': u'Tricium'
2631 },
2632 u'date': u'2017-03-16 20:00:41.000000000',
2633 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2634 u'message': u'(1 comment)',
2635 u'tag': u'autogenerated:tricium',
2636 },
2637 {
2638 u'_revision_number': 1,
2639 u'author': {
2640 u'_account_id': 123,
2641 u'email': u'tricium@serviceaccount.com',
2642 u'name': u'Tricium'
2643 },
2644 u'date': u'2017-03-16 20:00:41.000000000',
2645 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2646 u'message': u'(1 comment)',
2647 u'tag': u'autogenerated:tricium',
2648 },
2649 {
2650 u'_revision_number': 2,
2651 u'author': {
2652 u'_account_id': 123,
2653 u'email': u'tricium@serviceaccount.com',
2654 u'name': u'reviewer'
2655 },
2656 u'date': u'2017-03-17 05:30:37.000000000',
2657 u'tag': u'autogenerated:tricium',
2658 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2659 u'message': u'(1 comment)',
2660 },
2661 ]
2662 }
2663 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002664 (('GetChangeComments', 'chromium-review.googlesource.com',
2665 'infra%2Finfra~1'), {}),
2666 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2667 'infra%2Finfra~1'), {
2668 'codereview.settings': [
2669 {
2670 u'author': {u'email': u'tricium@serviceaccount.com'},
2671 u'updated': u'2017-03-17 05:30:37.000000000',
2672 u'robot_run_id': u'5565031076855808',
2673 u'robot_id': u'Linter/Category',
2674 u'tag': u'autogenerated:tricium',
2675 u'patch_set': 2,
2676 u'side': u'REVISION',
2677 u'message': u'Linter warning message text',
2678 u'line': 32,
2679 },
2680 ],
2681 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002682 ]
2683 expected_comments_summary = [
2684 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2685 message=(
2686 u'(1 comment)\n\ncodereview.settings\n'
2687 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2688 u'c/1/2/codereview.settings#32\n'
2689 u' Linter warning message text\n'),
2690 sender=u'tricium@serviceaccount.com',
2691 autogenerated=True, approval=False, disapproval=False)
2692 ]
2693 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002694 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002695 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002696
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002697 def test_get_remote_url_with_mirror(self):
2698 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002699
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002700 def selective_os_path_isdir_mock(path):
2701 if path == '/cache/this-dir-exists':
2702 return self._mocked_call('os.path.isdir', path)
2703 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002704
Edward Lemurda4b6c62020-02-13 00:28:40 +00002705 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002706
2707 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002708 self.mockGit.config['remote.origin.url'] = (
2709 '/cache/this-dir-exists')
2710 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2711 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002712 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002713 (('os.path.isdir', '/cache/this-dir-exists'),
2714 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002715 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002716 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002717 self.assertEqual(cl.GetRemoteUrl(), url)
2718 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2719
Edward Lemur298f2cf2019-02-22 21:40:39 +00002720 def test_get_remote_url_non_existing_mirror(self):
2721 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002722
Edward Lemur298f2cf2019-02-22 21:40:39 +00002723 def selective_os_path_isdir_mock(path):
2724 if path == '/cache/this-dir-doesnt-exist':
2725 return self._mocked_call('os.path.isdir', path)
2726 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002727
Edward Lemurda4b6c62020-02-13 00:28:40 +00002728 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2729 mock.patch('logging.error',
2730 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002731
Edward Lemur26964072020-02-19 19:18:51 +00002732 self.mockGit.config['remote.origin.url'] = (
2733 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002734 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002735 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2736 False),
2737 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002738 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2739 'but it doesn\'t exist.', {
2740 'remote': 'origin',
2741 'branch': 'master',
2742 'url': '/cache/this-dir-doesnt-exist'}
2743 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002744 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002745 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002746 self.assertIsNone(cl.GetRemoteUrl())
2747
2748 def test_get_remote_url_misconfigured_mirror(self):
2749 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002750
Edward Lemur298f2cf2019-02-22 21:40:39 +00002751 def selective_os_path_isdir_mock(path):
2752 if path == '/cache/this-dir-exists':
2753 return self._mocked_call('os.path.isdir', path)
2754 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002755
Edward Lemurda4b6c62020-02-13 00:28:40 +00002756 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2757 mock.patch('logging.error',
2758 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002759
Edward Lemur26964072020-02-19 19:18:51 +00002760 self.mockGit.config['remote.origin.url'] = (
2761 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002762 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002763 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002764 (('logging.error',
2765 'Remote "%(remote)s" for branch "%(branch)s" points to '
2766 '"%(cache_path)s", but it is misconfigured.\n'
2767 '"%(cache_path)s" must be a git repo and must have a remote named '
2768 '"%(remote)s" pointing to the git host.', {
2769 'remote': 'origin',
2770 'cache_path': '/cache/this-dir-exists',
2771 'branch': 'master'}
2772 ), None),
2773 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002774 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002775 self.assertIsNone(cl.GetRemoteUrl())
2776
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002777 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002778 self.mockGit.config['remote.origin.url'] = (
2779 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002780 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002781 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2782
2783 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002784 mock.patch('logging.error',
2785 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002786
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002787 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002788 (('logging.error',
2789 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2790 'but it doesn\'t exist.', {
2791 'remote': 'origin',
2792 'branch': 'master',
2793 'url': ''}
2794 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002795 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002796 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002797 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002798
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002799
Edward Lemur9aa1a962020-02-25 00:58:38 +00002800class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002801 def setUp(self):
2802 super(ChangelistTest, self).setUp()
2803 mock.patch('gclient_utils.FileRead').start()
2804 mock.patch('gclient_utils.FileWrite').start()
2805 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2806 mock.patch(
2807 'git_cl.Changelist.GetCodereviewServer',
2808 return_value='https://chromium-review.googlesource.com').start()
2809 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2810 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2811 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2812 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2813 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2814 mock.patch('git_cl.time_time').start()
2815 mock.patch('metrics.collector').start()
2816 mock.patch('subprocess2.Popen').start()
2817 self.addCleanup(mock.patch.stopall)
2818 self.temp_count = 0
2819
Edward Lemur227d5102020-02-25 23:45:35 +00002820 def testRunHook(self):
2821 expected_results = {
2822 'more_cc': ['more@example.com', 'cc@example.com'],
2823 'should_continue': True,
2824 }
2825 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2826 git_cl.time_time.side_effect = [100, 200]
2827 mockProcess = mock.Mock()
2828 mockProcess.wait.return_value = 0
2829 subprocess2.Popen.return_value = mockProcess
2830
2831 cl = git_cl.Changelist()
2832 results = cl.RunHook(
2833 committing=True,
2834 may_prompt=True,
2835 verbose=2,
2836 parallel=True,
2837 upstream='upstream',
2838 description='description',
2839 all_files=True)
2840
2841 self.assertEqual(expected_results, results)
2842 subprocess2.Popen.assert_called_once_with([
2843 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002844 '--root', 'root',
2845 '--upstream', 'upstream',
2846 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002847 '--author', 'author',
2848 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002849 '--issue', '123456',
2850 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002851 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002852 '--may_prompt',
2853 '--parallel',
2854 '--all_files',
2855 '--json_output', '/tmp/fake-temp2',
2856 '--description_file', '/tmp/fake-temp1',
2857 ])
2858 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002859 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002860 metrics.collector.add_repeated('sub_commands', {
2861 'command': 'presubmit',
2862 'execution_time': 100,
2863 'exit_code': 0,
2864 })
2865
Edward Lemur99df04e2020-03-05 19:39:43 +00002866 def testRunHook_FewerOptions(self):
2867 expected_results = {
2868 'more_cc': ['more@example.com', 'cc@example.com'],
2869 'should_continue': True,
2870 }
2871 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2872 git_cl.time_time.side_effect = [100, 200]
2873 mockProcess = mock.Mock()
2874 mockProcess.wait.return_value = 0
2875 subprocess2.Popen.return_value = mockProcess
2876
2877 git_cl.Changelist.GetAuthor.return_value = None
2878 git_cl.Changelist.GetIssue.return_value = None
2879 git_cl.Changelist.GetPatchset.return_value = None
2880 git_cl.Changelist.GetCodereviewServer.return_value = None
2881
2882 cl = git_cl.Changelist()
2883 results = cl.RunHook(
2884 committing=False,
2885 may_prompt=False,
2886 verbose=0,
2887 parallel=False,
2888 upstream='upstream',
2889 description='description',
2890 all_files=False)
2891
2892 self.assertEqual(expected_results, results)
2893 subprocess2.Popen.assert_called_once_with([
2894 'vpython', 'PRESUBMIT_SUPPORT',
2895 '--root', 'root',
2896 '--upstream', 'upstream',
2897 '--upload',
2898 '--json_output', '/tmp/fake-temp2',
2899 '--description_file', '/tmp/fake-temp1',
2900 ])
2901 gclient_utils.FileWrite.assert_called_once_with(
2902 '/tmp/fake-temp1', 'description')
2903 metrics.collector.add_repeated('sub_commands', {
2904 'command': 'presubmit',
2905 'execution_time': 100,
2906 'exit_code': 0,
2907 })
2908
Edward Lemur227d5102020-02-25 23:45:35 +00002909 @mock.patch('sys.exit', side_effect=SystemExitMock)
2910 def testRunHook_Failure(self, _mock):
2911 git_cl.time_time.side_effect = [100, 200]
2912 mockProcess = mock.Mock()
2913 mockProcess.wait.return_value = 2
2914 subprocess2.Popen.return_value = mockProcess
2915
2916 cl = git_cl.Changelist()
2917 with self.assertRaises(SystemExitMock):
2918 cl.RunHook(
2919 committing=True,
2920 may_prompt=True,
2921 verbose=2,
2922 parallel=True,
2923 upstream='upstream',
2924 description='description',
2925 all_files=True)
2926
2927 sys.exit.assert_called_once_with(2)
2928
Edward Lemur75526302020-02-27 22:31:05 +00002929 def testRunPostUploadHook(self):
2930 cl = git_cl.Changelist()
2931 cl.RunPostUploadHook(2, 'upstream', 'description')
2932
2933 subprocess2.Popen.assert_called_once_with([
2934 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002935 '--root', 'root',
2936 '--upstream', 'upstream',
2937 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002938 '--author', 'author',
2939 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002940 '--issue', '123456',
2941 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002942 '--post_upload',
2943 '--description_file', '/tmp/fake-temp1',
2944 ])
2945 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002946 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002947
Edward Lemur9aa1a962020-02-25 00:58:38 +00002948
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002949class CMDTestCaseBase(unittest.TestCase):
2950 _STATUSES = [
2951 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2952 'INFRA_FAILURE', 'CANCELED',
2953 ]
2954 _CHANGE_DETAIL = {
2955 'project': 'depot_tools',
2956 'status': 'OPEN',
2957 'owner': {'email': 'owner@e.mail'},
2958 'current_revision': 'beeeeeef',
2959 'revisions': {
2960 'deadbeaf': {'_number': 6},
2961 'beeeeeef': {
2962 '_number': 7,
2963 'fetch': {'http': {
2964 'url': 'https://chromium.googlesource.com/depot_tools',
2965 'ref': 'refs/changes/56/123456/7'
2966 }},
2967 },
2968 },
2969 }
2970 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002971 'builds': [{
2972 'id': str(100 + idx),
2973 'builder': {
2974 'project': 'chromium',
2975 'bucket': 'try',
2976 'builder': 'bot_' + status.lower(),
2977 },
2978 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2979 'tags': [],
2980 'status': status,
2981 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002982 }
2983
Edward Lemur4c707a22019-09-24 21:13:43 +00002984 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002985 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002986 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002987 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2988 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002989 mock.patch(
2990 'git_cl.Changelist.GetCodereviewServer',
2991 return_value='https://chromium-review.googlesource.com').start()
2992 mock.patch(
2993 'git_cl.Changelist._GetGerritHost',
2994 return_value='chromium-review.googlesource.com').start()
2995 mock.patch(
2996 'git_cl.Changelist.GetMostRecentPatchset',
2997 return_value=7).start()
2998 mock.patch(
2999 'git_cl.Changelist.GetRemoteUrl',
3000 return_value='https://chromium.googlesource.com/depot_tools').start()
3001 mock.patch(
3002 'auth.Authenticator',
3003 return_value=AuthenticatorMock()).start()
3004 mock.patch(
3005 'gerrit_util.GetChangeDetail',
3006 return_value=self._CHANGE_DETAIL).start()
3007 mock.patch(
3008 'git_cl._call_buildbucket',
3009 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003010 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003011 self.addCleanup(mock.patch.stopall)
3012
Edward Lemur4c707a22019-09-24 21:13:43 +00003013
Edward Lemur9468eba2020-02-27 19:07:22 +00003014class CMDPresubmitTestCase(CMDTestCaseBase):
3015 def setUp(self):
3016 super(CMDPresubmitTestCase, self).setUp()
3017 mock.patch(
3018 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3019 return_value='upstream').start()
3020 mock.patch(
3021 'git_cl.Changelist.FetchDescription',
3022 return_value='fetch description').start()
3023 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003024 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003025 return_value='get description').start()
3026 mock.patch('git_cl.Changelist.RunHook').start()
3027
3028 def testDefaultCase(self):
3029 self.assertEqual(0, git_cl.main(['presubmit']))
3030 git_cl.Changelist.RunHook.assert_called_once_with(
3031 committing=True,
3032 may_prompt=False,
3033 verbose=0,
3034 parallel=None,
3035 upstream='upstream',
3036 description='fetch description',
3037 all_files=None)
3038
3039 def testNoIssue(self):
3040 git_cl.Changelist.GetIssue.return_value = None
3041 self.assertEqual(0, git_cl.main(['presubmit']))
3042 git_cl.Changelist.RunHook.assert_called_once_with(
3043 committing=True,
3044 may_prompt=False,
3045 verbose=0,
3046 parallel=None,
3047 upstream='upstream',
3048 description='get description',
3049 all_files=None)
3050
3051 def testCustomBranch(self):
3052 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3053 git_cl.Changelist.RunHook.assert_called_once_with(
3054 committing=True,
3055 may_prompt=False,
3056 verbose=0,
3057 parallel=None,
3058 upstream='custom_branch',
3059 description='fetch description',
3060 all_files=None)
3061
3062 def testOptions(self):
3063 self.assertEqual(
3064 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
3065 git_cl.Changelist.RunHook.assert_called_once_with(
3066 committing=False,
3067 may_prompt=False,
3068 verbose=2,
3069 parallel=True,
3070 upstream='upstream',
3071 description='fetch description',
3072 all_files=True)
3073
3074
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003075class CMDTryResultsTestCase(CMDTestCaseBase):
3076 _DEFAULT_REQUEST = {
3077 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003078 "gerritChanges": [{
3079 "project": "depot_tools",
3080 "host": "chromium-review.googlesource.com",
3081 "patchset": 7,
3082 "change": 123456,
3083 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003084 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003085 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3086 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003087 }
3088
3089 def testNoJobs(self):
3090 git_cl._call_buildbucket.return_value = {}
3091
3092 self.assertEqual(0, git_cl.main(['try-results']))
3093 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3094 git_cl._call_buildbucket.assert_called_once_with(
3095 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3096 self._DEFAULT_REQUEST)
3097
3098 def testPrintToStdout(self):
3099 self.assertEqual(0, git_cl.main(['try-results']))
3100 self.assertEqual([
3101 'Successes:',
3102 ' bot_success https://ci.chromium.org/b/103',
3103 'Infra Failures:',
3104 ' bot_infra_failure https://ci.chromium.org/b/105',
3105 'Failures:',
3106 ' bot_failure https://ci.chromium.org/b/104',
3107 'Canceled:',
3108 ' bot_canceled ',
3109 'Started:',
3110 ' bot_started https://ci.chromium.org/b/102',
3111 'Scheduled:',
3112 ' bot_scheduled id=101',
3113 'Other:',
3114 ' bot_status_unspecified id=100',
3115 'Total: 7 tryjobs',
3116 ], sys.stdout.getvalue().splitlines())
3117 git_cl._call_buildbucket.assert_called_once_with(
3118 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3119 self._DEFAULT_REQUEST)
3120
3121 def testPrintToStdoutWithMasters(self):
3122 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3123 self.assertEqual([
3124 'Successes:',
3125 ' try bot_success https://ci.chromium.org/b/103',
3126 'Infra Failures:',
3127 ' try bot_infra_failure https://ci.chromium.org/b/105',
3128 'Failures:',
3129 ' try bot_failure https://ci.chromium.org/b/104',
3130 'Canceled:',
3131 ' try bot_canceled ',
3132 'Started:',
3133 ' try bot_started https://ci.chromium.org/b/102',
3134 'Scheduled:',
3135 ' try bot_scheduled id=101',
3136 'Other:',
3137 ' try bot_status_unspecified id=100',
3138 'Total: 7 tryjobs',
3139 ], sys.stdout.getvalue().splitlines())
3140 git_cl._call_buildbucket.assert_called_once_with(
3141 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3142 self._DEFAULT_REQUEST)
3143
3144 @mock.patch('git_cl.write_json')
3145 def testWriteToJson(self, mockJsonDump):
3146 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3147 git_cl._call_buildbucket.assert_called_once_with(
3148 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3149 self._DEFAULT_REQUEST)
3150 mockJsonDump.assert_called_once_with(
3151 'file.json', self._DEFAULT_RESPONSE['builds'])
3152
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003153 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003154 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3155 self.assertEqual(
3156 [
3157 ('chromium', 'try', 'bot_failure'),
3158 ('chromium', 'try', 'bot_infra_failure'),
3159 ],
3160 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003161
3162 def test_filter_failed_for_retry_many_builds(self):
3163
3164 def _build(name, created_sec, status, experimental=False):
3165 assert 0 <= created_sec < 100, created_sec
3166 b = {
3167 'id': 112112,
3168 'builder': {
3169 'project': 'chromium',
3170 'bucket': 'try',
3171 'builder': name,
3172 },
3173 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3174 'status': status,
3175 'tags': [],
3176 }
3177 if experimental:
3178 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3179 return b
3180
3181 builds = [
3182 _build('flaky-last-green', 1, 'FAILURE'),
3183 _build('flaky-last-green', 2, 'SUCCESS'),
3184 _build('flaky', 1, 'SUCCESS'),
3185 _build('flaky', 2, 'FAILURE'),
3186 _build('running', 1, 'FAILED'),
3187 _build('running', 2, 'SCHEDULED'),
3188 _build('yep-still-running', 1, 'STARTED'),
3189 _build('yep-still-running', 2, 'FAILURE'),
3190 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3191 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3192
3193 # Simulate experimental in CQ builder, which developer decided
3194 # to retry manually which resulted in 2nd build non-experimental.
3195 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3196 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3197 ]
3198 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003199 self.assertEqual(
3200 [
3201 ('chromium', 'try', 'flaky'),
3202 ('chromium', 'try', 'sometimes-experimental'),
3203 ],
3204 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003205
3206
3207class CMDTryTestCase(CMDTestCaseBase):
3208
3209 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003210 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003211 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003212 self.assertEqual(0, git_cl.main(['try']))
3213 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3214 self.assertEqual(
3215 sys.stdout.getvalue(),
3216 'Scheduling CQ dry run on: '
3217 'https://chromium-review.googlesource.com/123456\n')
3218
Edward Lemur4c707a22019-09-24 21:13:43 +00003219 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003220 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003221 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003222
3223 self.assertEqual(0, git_cl.main([
3224 'try', '-B', 'luci.chromium.try', '-b', 'win',
3225 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3226 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003227 'Scheduling jobs on:\n'
3228 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003229 git_cl.sys.stdout.getvalue())
3230
3231 expected_request = {
3232 "requests": [{
3233 "scheduleBuild": {
3234 "requestId": "uuid4",
3235 "builder": {
3236 "project": "chromium",
3237 "builder": "win",
3238 "bucket": "try",
3239 },
3240 "gerritChanges": [{
3241 "project": "depot_tools",
3242 "host": "chromium-review.googlesource.com",
3243 "patchset": 7,
3244 "change": 123456,
3245 }],
3246 "properties": {
3247 "category": "git_cl_try",
3248 "json": [{"a": 1}, None],
3249 "key": "val",
3250 },
3251 "tags": [
3252 {"value": "win", "key": "builder"},
3253 {"value": "git_cl_try", "key": "user_agent"},
3254 ],
3255 },
3256 }],
3257 }
3258 mockCallBuildbucket.assert_called_with(
3259 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3260
Anthony Polito1a5fe232020-01-24 23:17:52 +00003261 @mock.patch('git_cl._call_buildbucket')
3262 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3263 mockCallBuildbucket.return_value = {}
3264
3265 self.assertEqual(0, git_cl.main([
3266 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3267 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3268 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3269 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003270 'Scheduling jobs on:\n'
3271 ' chromium/try: linux\n'
3272 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003273 git_cl.sys.stdout.getvalue())
3274
3275 expected_request = {
3276 "requests": [{
3277 "scheduleBuild": {
3278 "requestId": "uuid4",
3279 "builder": {
3280 "project": "chromium",
3281 "builder": "linux",
3282 "bucket": "try",
3283 },
3284 "gerritChanges": [{
3285 "project": "depot_tools",
3286 "host": "chromium-review.googlesource.com",
3287 "patchset": 7,
3288 "change": 123456,
3289 }],
3290 "properties": {
3291 "category": "git_cl_try",
3292 "json": [{"a": 1}, None],
3293 "key": "val",
3294 },
3295 "tags": [
3296 {"value": "linux", "key": "builder"},
3297 {"value": "git_cl_try", "key": "user_agent"},
3298 ],
3299 "gitilesCommit": {
3300 "host": "chromium-review.googlesource.com",
3301 "project": "depot_tools",
3302 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3303 }
3304 },
3305 },
3306 {
3307 "scheduleBuild": {
3308 "requestId": "uuid4",
3309 "builder": {
3310 "project": "chromium",
3311 "builder": "win",
3312 "bucket": "try",
3313 },
3314 "gerritChanges": [{
3315 "project": "depot_tools",
3316 "host": "chromium-review.googlesource.com",
3317 "patchset": 7,
3318 "change": 123456,
3319 }],
3320 "properties": {
3321 "category": "git_cl_try",
3322 "json": [{"a": 1}, None],
3323 "key": "val",
3324 },
3325 "tags": [
3326 {"value": "win", "key": "builder"},
3327 {"value": "git_cl_try", "key": "user_agent"},
3328 ],
3329 "gitilesCommit": {
3330 "host": "chromium-review.googlesource.com",
3331 "project": "depot_tools",
3332 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3333 }
3334 },
3335 }],
3336 }
3337 mockCallBuildbucket.assert_called_with(
3338 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3339
Edward Lemur45768512020-03-02 19:03:14 +00003340 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003341 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003342 with self.assertRaises(SystemExit):
3343 git_cl.main([
3344 'try', '-B', 'not-a-bucket', '-b', 'win',
3345 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003346 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003347 'Invalid bucket: not-a-bucket.',
3348 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003349
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003350 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003351 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003352 def testScheduleOnBuildbucketRetryFailed(
3353 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003354 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003355 7: [],
3356 6: [{
3357 'id': 112112,
3358 'builder': {
3359 'project': 'chromium',
3360 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003361 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003362 'createTime': '2019-10-09T08:00:01.854286Z',
3363 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003364 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003365 mockCallBuildbucket.return_value = {}
3366
3367 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3368 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003369 'Scheduling jobs on:\n'
3370 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003371 git_cl.sys.stdout.getvalue())
3372
3373 expected_request = {
3374 "requests": [{
3375 "scheduleBuild": {
3376 "requestId": "uuid4",
3377 "builder": {
3378 "project": "chromium",
3379 "bucket": "try",
3380 "builder": "linux",
3381 },
3382 "gerritChanges": [{
3383 "project": "depot_tools",
3384 "host": "chromium-review.googlesource.com",
3385 "patchset": 7,
3386 "change": 123456,
3387 }],
3388 "properties": {
3389 "category": "git_cl_try",
3390 },
3391 "tags": [
3392 {"value": "linux", "key": "builder"},
3393 {"value": "git_cl_try", "key": "user_agent"},
3394 {"value": "1", "key": "retry_failed"},
3395 ],
3396 },
3397 }],
3398 }
3399 mockCallBuildbucket.assert_called_with(
3400 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3401
Edward Lemur4c707a22019-09-24 21:13:43 +00003402 def test_parse_bucket(self):
3403 test_cases = [
3404 {
3405 'bucket': 'chromium/try',
3406 'result': ('chromium', 'try'),
3407 },
3408 {
3409 'bucket': 'luci.chromium.try',
3410 'result': ('chromium', 'try'),
3411 'has_warning': True,
3412 },
3413 {
3414 'bucket': 'skia.primary',
3415 'result': ('skia', 'skia.primary'),
3416 'has_warning': True,
3417 },
3418 {
3419 'bucket': 'not-a-bucket',
3420 'result': (None, None),
3421 },
3422 ]
3423
3424 for test_case in test_cases:
3425 git_cl.sys.stdout.truncate(0)
3426 self.assertEqual(
3427 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3428 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003429 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3430 test_case['result'])
3431 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003432
3433
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003434class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003435
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003436 def setUp(self):
3437 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003438 mock.patch('git_cl._fetch_tryjobs').start()
3439 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003440 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003441 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003442 self.addCleanup(mock.patch.stopall)
3443
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003444 def testWarmUpChangeDetailCache(self):
3445 self.assertEqual(0, git_cl.main(['upload']))
3446 gerrit_util.GetChangeDetail.assert_called_once_with(
3447 'chromium-review.googlesource.com', 'depot_tools~123456',
3448 frozenset([
3449 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3450 'CURRENT_COMMIT']))
3451
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003452 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003453 # This test mocks out the actual upload part, and just asserts that after
3454 # upload, if --retry-failed is added, then the tool will fetch try jobs
3455 # from the previous patchset and trigger the right builders on the latest
3456 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003457 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003458 # Latest patchset: No builds.
3459 [],
3460 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003461 [{
3462 'id': str(100 + idx),
3463 'builder': {
3464 'project': 'chromium',
3465 'bucket': 'try',
3466 'builder': 'bot_' + status.lower(),
3467 },
3468 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3469 'tags': [],
3470 'status': status,
3471 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003472 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003473
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003474 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003475 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003476 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3477 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003478 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003479 expected_buckets = [
3480 ('chromium', 'try', 'bot_failure'),
3481 ('chromium', 'try', 'bot_infra_failure'),
3482 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003483 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3484 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003485
Brian Sheedy59b06a82019-10-14 17:03:29 +00003486
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003487class MakeRequestsHelperTestCase(unittest.TestCase):
3488
3489 def exampleGerritChange(self):
3490 return {
3491 'host': 'chromium-review.googlesource.com',
3492 'project': 'depot_tools',
3493 'change': 1,
3494 'patchset': 2,
3495 }
3496
3497 def testMakeRequestsHelperNoOptions(self):
3498 # Basic test for the helper function _make_tryjob_schedule_requests;
3499 # it shouldn't throw AttributeError even when options doesn't have any
3500 # of the expected values; it will use default option values.
3501 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3502 jobs = [('chromium', 'try', 'my-builder')]
3503 options = optparse.Values()
3504 requests = git_cl._make_tryjob_schedule_requests(
3505 changelist, jobs, options, patchset=None)
3506
3507 # requestId is non-deterministic. Just assert that it's there and has
3508 # a particular length.
3509 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3510 self.assertEqual(requests, [{
3511 'scheduleBuild': {
3512 'builder': {
3513 'bucket': 'try',
3514 'builder': 'my-builder',
3515 'project': 'chromium'
3516 },
3517 'gerritChanges': [self.exampleGerritChange()],
3518 'properties': {
3519 'category': 'git_cl_try'
3520 },
3521 'tags': [{
3522 'key': 'builder',
3523 'value': 'my-builder'
3524 }, {
3525 'key': 'user_agent',
3526 'value': 'git_cl_try'
3527 }]
3528 }
3529 }])
3530
3531 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3532 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3533 jobs = [('chromium', 'try', 'presubmit')]
3534 options = optparse.Values()
3535 requests = git_cl._make_tryjob_schedule_requests(
3536 changelist, jobs, options, patchset=None)
3537 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3538 'category': 'git_cl_try',
3539 'dry_run': 'true'
3540 })
3541
3542 def testMakeRequestsHelperRevisionSet(self):
3543 # Gitiles commit is specified when revision is in options.
3544 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3545 jobs = [('chromium', 'try', 'my-builder')]
3546 options = optparse.Values({'revision': 'ba5eba11'})
3547 requests = git_cl._make_tryjob_schedule_requests(
3548 changelist, jobs, options, patchset=None)
3549 self.assertEqual(
3550 requests[0]['scheduleBuild']['gitilesCommit'], {
3551 'host': 'chromium-review.googlesource.com',
3552 'id': 'ba5eba11',
3553 'project': 'depot_tools'
3554 })
3555
3556 def testMakeRequestsHelperRetryFailedSet(self):
3557 # An extra tag is added when retry_failed is in options.
3558 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3559 jobs = [('chromium', 'try', 'my-builder')]
3560 options = optparse.Values({'retry_failed': 'true'})
3561 requests = git_cl._make_tryjob_schedule_requests(
3562 changelist, jobs, options, patchset=None)
3563 self.assertEqual(
3564 requests[0]['scheduleBuild']['tags'], [
3565 {
3566 'key': 'builder',
3567 'value': 'my-builder'
3568 },
3569 {
3570 'key': 'user_agent',
3571 'value': 'git_cl_try'
3572 },
3573 {
3574 'key': 'retry_failed',
3575 'value': '1'
3576 }
3577 ])
3578
3579 def testMakeRequestsHelperCategorySet(self):
3580 # The category property can be overriden with options.
3581 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3582 jobs = [('chromium', 'try', 'my-builder')]
3583 options = optparse.Values({'category': 'my-special-category'})
3584 requests = git_cl._make_tryjob_schedule_requests(
3585 changelist, jobs, options, patchset=None)
3586 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3587 {'category': 'my-special-category'})
3588
3589
Edward Lemurda4b6c62020-02-13 00:28:40 +00003590class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003591
3592 def setUp(self):
3593 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003594 mock.patch('git_cl.RunCommand').start()
3595 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3596 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3597 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003598 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003599 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003600
3601 def tearDown(self):
3602 shutil.rmtree(self._top_dir)
3603 super(CMDFormatTestCase, self).tearDown()
3604
Jamie Madill5e96ad12020-01-13 16:08:35 +00003605 def _make_temp_file(self, fname, contents):
3606 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3607 tf.write('\n'.join(contents))
3608
Brian Sheedy59b06a82019-10-14 17:03:29 +00003609 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003610 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003611
Brian Sheedyb4307d52019-12-02 19:18:17 +00003612 def _check_yapf_filtering(self, files, expected):
3613 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3614 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003615
Edward Lemur1a83da12020-03-04 21:18:36 +00003616 def _run_command_mock(self, return_value):
3617 def f(*args, **kwargs):
3618 if 'stdin' in kwargs:
3619 self.assertIsInstance(kwargs['stdin'], bytes)
3620 return return_value
3621 return f
3622
Jamie Madill5e96ad12020-01-13 16:08:35 +00003623 def testClangFormatDiffFull(self):
3624 self._make_temp_file('test.cc', ['// test'])
3625 git_cl.settings.GetFormatFullByDefault.return_value = False
3626 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3627 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3628
3629 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003630 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003631 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3632 self._top_dir, 'HEAD')
3633 self.assertEqual(2, return_value)
3634
3635 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003636 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003637 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3638 self._top_dir, 'HEAD')
3639 self.assertEqual(0, return_value)
3640
3641 def testClangFormatDiff(self):
3642 git_cl.settings.GetFormatFullByDefault.return_value = False
3643 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3644
3645 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003646 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3647 return_value = git_cl._RunClangFormatDiff(
3648 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003649 self.assertEqual(2, return_value)
3650
3651 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003652 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003653 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3654 'HEAD')
3655 self.assertEqual(0, return_value)
3656
Brian Sheedyb4307d52019-12-02 19:18:17 +00003657 def testYapfignoreExplicit(self):
3658 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3659 files = [
3660 'bar.py',
3661 'foo/bar.py',
3662 'foo/baz.py',
3663 'foo/bar/baz.py',
3664 'foo/bar/foobar.py',
3665 ]
3666 expected = [
3667 'bar.py',
3668 'foo/baz.py',
3669 'foo/bar/foobar.py',
3670 ]
3671 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003672
Brian Sheedyb4307d52019-12-02 19:18:17 +00003673 def testYapfignoreSingleWildcards(self):
3674 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3675 files = [
3676 'bar.py', # Matched by *bar.py.
3677 'bar.txt',
3678 'foobar.py', # Matched by *bar.py, foo*.
3679 'foobar.txt', # Matched by foo*.
3680 'bazbar.py', # Matched by *bar.py, baz*.py.
3681 'bazbar.txt',
3682 'foo/baz.txt', # Matched by foo*.
3683 'bar/bar.py', # Matched by *bar.py.
3684 'baz/foo.py', # Matched by baz*.py, foo*.
3685 'baz/foo.txt',
3686 ]
3687 expected = [
3688 'bar.txt',
3689 'bazbar.txt',
3690 'baz/foo.txt',
3691 ]
3692 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003693
Brian Sheedyb4307d52019-12-02 19:18:17 +00003694 def testYapfignoreMultiplewildcards(self):
3695 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3696 files = [
3697 'bar.py', # Matched by *bar*.
3698 'bar.txt', # Matched by *bar*.
3699 'abar.py', # Matched by *bar*.
3700 'foobaz.txt', # Matched by *foo*baz.txt.
3701 'foobaz.py',
3702 'afoobaz.txt', # Matched by *foo*baz.txt.
3703 ]
3704 expected = [
3705 'foobaz.py',
3706 ]
3707 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003708
3709 def testYapfignoreComments(self):
3710 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003711 files = [
3712 'test.py',
3713 'test2.py',
3714 ]
3715 expected = [
3716 'test2.py',
3717 ]
3718 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003719
3720 def testYapfignoreBlankLines(self):
3721 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003722 files = [
3723 'test.py',
3724 'test2.py',
3725 'test3.py',
3726 ]
3727 expected = [
3728 'test3.py',
3729 ]
3730 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003731
3732 def testYapfignoreWhitespace(self):
3733 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003734 files = [
3735 'test.py',
3736 'test2.py',
3737 ]
3738 expected = [
3739 'test2.py',
3740 ]
3741 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003742
Brian Sheedyb4307d52019-12-02 19:18:17 +00003743 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003744 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003745 self._check_yapf_filtering([], [])
3746
3747 def testYapfignoreMissingYapfignore(self):
3748 files = [
3749 'test.py',
3750 ]
3751 expected = [
3752 'test.py',
3753 ]
3754 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003755
3756
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003757if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003758 logging.basicConfig(
3759 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003760 unittest.main()