blob: 85ab7243bdb2f7cd9f492fe65a9778c99e0de317 [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 Shyshkalov71f0da32019-07-15 22:45:18 +0000252 def test_set_preserve_tryjobs(self):
253 d = git_cl.ChangeDescription('Simple.')
254 d.set_preserve_tryjobs()
255 self.assertEqual(d.description.splitlines(), [
256 'Simple.',
257 '',
258 'Cq-Do-Not-Cancel-Tryjobs: true',
259 ])
260 before = d.description
261 d.set_preserve_tryjobs()
262 self.assertEqual(before, d.description)
263
264 d = git_cl.ChangeDescription('\n'.join([
265 'One is enough',
266 '',
267 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
268 'Change-Id: Ideadbeef',
269 ]))
270 d.set_preserve_tryjobs()
271 self.assertEqual(d.description.splitlines(), [
272 'One is enough',
273 '',
274 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
275 'Change-Id: Ideadbeef',
276 'Cq-Do-Not-Cancel-Tryjobs: true',
277 ])
278
tandriif9aefb72016-07-01 09:06:51 -0700279 def test_get_bug_line_values(self):
280 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
281 self.assertEqual(f('', ''), [])
282 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
283 self.assertEqual(f('v8', '456'), ['v8:456'])
284 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
285 # Not nice, but not worth carying.
286 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
287 ['v8:456', 'chromium:123', 'v8:123'])
288
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100289 def _test_git_number(self, parent_msg, dest_ref, child_msg,
290 parent_hash='parenthash'):
291 desc = git_cl.ChangeDescription(child_msg)
292 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
293 return desc.description
294
295 def assertEqualByLine(self, actual, expected):
296 self.assertEqual(actual.splitlines(), expected.splitlines())
297
298 def test_git_number_bad_parent(self):
299 with self.assertRaises(ValueError):
300 self._test_git_number('Parent', 'refs/heads/master', 'Child')
301
302 def test_git_number_bad_parent_footer(self):
303 with self.assertRaises(AssertionError):
304 self._test_git_number(
305 'Parent\n'
306 '\n'
307 'Cr-Commit-Position: wrong',
308 'refs/heads/master', 'Child')
309
310 def test_git_number_bad_lineage_ignored(self):
311 actual = self._test_git_number(
312 'Parent\n'
313 '\n'
314 'Cr-Commit-Position: refs/heads/master@{#1}\n'
315 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
316 'refs/heads/master', 'Child')
317 self.assertEqualByLine(
318 actual,
319 'Child\n'
320 '\n'
321 'Cr-Commit-Position: refs/heads/master@{#2}\n'
322 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
323
324 def test_git_number_same_branch(self):
325 actual = self._test_git_number(
326 'Parent\n'
327 '\n'
328 'Cr-Commit-Position: refs/heads/master@{#12}',
329 dest_ref='refs/heads/master',
330 child_msg='Child')
331 self.assertEqualByLine(
332 actual,
333 'Child\n'
334 '\n'
335 'Cr-Commit-Position: refs/heads/master@{#13}')
336
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200337 def test_git_number_same_branch_mixed_footers(self):
338 actual = self._test_git_number(
339 'Parent\n'
340 '\n'
341 'Cr-Commit-Position: refs/heads/master@{#12}',
342 dest_ref='refs/heads/master',
343 child_msg='Child\n'
344 '\n'
345 'Broken-by: design\n'
346 'BUG=123')
347 self.assertEqualByLine(
348 actual,
349 'Child\n'
350 '\n'
351 'Broken-by: design\n'
352 'BUG=123\n'
353 'Cr-Commit-Position: refs/heads/master@{#13}')
354
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100355 def test_git_number_same_branch_with_originals(self):
356 actual = self._test_git_number(
357 'Parent\n'
358 '\n'
359 'Cr-Commit-Position: refs/heads/master@{#12}',
360 dest_ref='refs/heads/master',
361 child_msg='Child\n'
362 '\n'
363 'Some users are smart and insert their own footers\n'
364 '\n'
365 'Cr-Whatever: value\n'
366 'Cr-Commit-Position: refs/copy/paste@{#22}')
367 self.assertEqualByLine(
368 actual,
369 'Child\n'
370 '\n'
371 'Some users are smart and insert their own footers\n'
372 '\n'
373 'Cr-Original-Whatever: value\n'
374 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
375 'Cr-Commit-Position: refs/heads/master@{#13}')
376
377 def test_git_number_new_branch(self):
378 actual = self._test_git_number(
379 'Parent\n'
380 '\n'
381 'Cr-Commit-Position: refs/heads/master@{#12}',
382 dest_ref='refs/heads/branch',
383 child_msg='Child')
384 self.assertEqualByLine(
385 actual,
386 'Child\n'
387 '\n'
388 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
389 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
390
391 def test_git_number_lineage(self):
392 actual = self._test_git_number(
393 'Parent\n'
394 '\n'
395 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
396 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
397 dest_ref='refs/heads/branch',
398 child_msg='Child')
399 self.assertEqualByLine(
400 actual,
401 'Child\n'
402 '\n'
403 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
404 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
405
406 def test_git_number_moooooooore_lineage(self):
407 actual = self._test_git_number(
408 'Parent\n'
409 '\n'
410 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
411 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
412 dest_ref='refs/heads/mooore',
413 child_msg='Child')
414 self.assertEqualByLine(
415 actual,
416 'Child\n'
417 '\n'
418 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
419 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
420 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
421
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100422 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700423 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100424 actual = self._test_git_number(
425 'CQ commit on fresh new branch + numbering.\n'
426 '\n'
427 'NOTRY=True\n'
428 'NOPRESUBMIT=True\n'
429 'BUG=\n'
430 '\n'
431 'Review-Url: https://codereview.chromium.org/2577703003\n'
432 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
433 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
434 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
435 dest_ref='refs/heads/gnumb-test/cl',
436 child_msg='git cl on fresh new branch + numbering.\n'
437 '\n'
438 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
439 self.assertEqualByLine(
440 actual,
441 'git cl on fresh new branch + numbering.\n'
442 '\n'
443 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
444 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
445 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
446 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
447 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100448
449 def test_git_number_cherry_pick(self):
450 actual = self._test_git_number(
451 'Parent\n'
452 '\n'
453 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
454 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
455 dest_ref='refs/heads/branch',
456 child_msg='Child, which is cherry-pick from master\n'
457 '\n'
458 'Cr-Commit-Position: refs/heads/master@{#100}\n'
459 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
460 self.assertEqualByLine(
461 actual,
462 'Child, which is cherry-pick from master\n'
463 '\n'
464 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
465 '\n'
466 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
467 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
468 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
469
Edward Lemurda4b6c62020-02-13 00:28:40 +0000470 @mock.patch('gerrit_util.GetAccountDetails')
471 def test_valid_accounts(self, mockGetAccountDetails):
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000472 mock_per_account = {
473 'u1': None, # 404, doesn't exist.
474 'u2': {
475 '_account_id': 123124,
476 'avatars': [],
477 'email': 'u2@example.com',
478 'name': 'User Number 2',
479 'status': 'OOO',
480 },
481 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
482 }
483 def GetAccountDetailsMock(_, account):
484 # Poor-man's mock library's side_effect.
485 v = mock_per_account.pop(account)
486 if isinstance(v, Exception):
487 raise v
488 return v
489
Edward Lemurda4b6c62020-02-13 00:28:40 +0000490 mockGetAccountDetails.side_effect = GetAccountDetailsMock
491 actual = git_cl.gerrit_util.ValidAccounts(
492 'host', ['u1', 'u2', 'u3'], max_threads=1)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000493 self.assertEqual(actual, {
494 'u2': {
495 '_account_id': 123124,
496 'avatars': [],
497 'email': 'u2@example.com',
498 'name': 'User Number 2',
499 'status': 'OOO',
500 },
501 })
502
503
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200504class TestParseIssueURL(unittest.TestCase):
505 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000506 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200507 self.assertIsNotNone(parsed)
508 if fail:
509 self.assertFalse(parsed.valid)
510 return
511 self.assertTrue(parsed.valid)
512 self.assertEqual(parsed.issue, issue)
513 self.assertEqual(parsed.patchset, patchset)
514 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200515
Edward Lemur678a6842019-10-03 22:25:05 +0000516 def test_ParseIssueNumberArgument(self):
517 def test(arg, *args, **kwargs):
518 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200519
Edward Lemur678a6842019-10-03 22:25:05 +0000520 test('123', 123)
521 test('', fail=True)
522 test('abc', fail=True)
523 test('123/1', fail=True)
524 test('123a', fail=True)
525 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200526
Edward Lemur678a6842019-10-03 22:25:05 +0000527 test('https://codereview.source.com/123',
528 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200529 test('http://chrome-review.source.com/c/123',
530 123, None, 'chrome-review.source.com')
531 test('https://chrome-review.source.com/c/123/',
532 123, None, 'chrome-review.source.com')
533 test('https://chrome-review.source.com/c/123/4',
534 123, 4, 'chrome-review.source.com')
535 test('https://chrome-review.source.com/#/c/123/4',
536 123, 4, 'chrome-review.source.com')
537 test('https://chrome-review.source.com/c/123/4',
538 123, 4, 'chrome-review.source.com')
539 test('https://chrome-review.source.com/123',
540 123, None, 'chrome-review.source.com')
541 test('https://chrome-review.source.com/123/4',
542 123, 4, 'chrome-review.source.com')
543
Edward Lemur678a6842019-10-03 22:25:05 +0000544 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200545 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
546 test('https://chrome-review.source.com/c/abc/', fail=True)
547 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
548
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200549
550
Edward Lemurda4b6c62020-02-13 00:28:40 +0000551class GitCookiesCheckerTest(unittest.TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100552 def setUp(self):
553 super(GitCookiesCheckerTest, self).setUp()
554 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100555 self.c._all_hosts = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000556 mock.patch('sys.stdout', StringIO()).start()
557 self.addCleanup(mock.patch.stopall)
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100558
559 def mock_hosts_creds(self, subhost_identity_pairs):
560 def ensure_googlesource(h):
561 if not h.endswith(self.c._GOOGLESOURCE):
562 assert not h.endswith('.')
563 return h + '.' + self.c._GOOGLESOURCE
564 return h
565 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
566 for h, i in subhost_identity_pairs]
567
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200568 def test_identity_parsing(self):
569 self.assertEqual(self.c._parse_identity('ldap.google.com'),
570 ('ldap', 'google.com'))
571 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
572 ('ldap', 'example.com'))
573 # Specical case because we know there are no subdomains in chromium.org.
574 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
575 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800576 # Pathological: ".period." can be either username OR domain, more likely
577 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200578 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
579 ('note', 'period.example.com'))
580
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100581 def test_analysis_nothing(self):
582 self.c._all_hosts = []
583 self.assertFalse(self.c.has_generic_host())
584 self.assertEqual(set(), self.c.get_conflicting_hosts())
585 self.assertEqual(set(), self.c.get_duplicated_hosts())
586 self.assertEqual(set(), self.c.get_partially_configured_hosts())
587 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
588
589 def test_analysis(self):
590 self.mock_hosts_creds([
591 ('.googlesource.com', 'git-example.chromium.org'),
592
593 ('chromium', 'git-example.google.com'),
594 ('chromium-review', 'git-example.google.com'),
595 ('chrome-internal', 'git-example.chromium.org'),
596 ('chrome-internal-review', 'git-example.chromium.org'),
597 ('conflict', 'git-example.google.com'),
598 ('conflict-review', 'git-example.chromium.org'),
599 ('dup', 'git-example.google.com'),
600 ('dup', 'git-example.google.com'),
601 ('dup-review', 'git-example.google.com'),
602 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200603 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100604 ])
605 self.assertTrue(self.c.has_generic_host())
606 self.assertEqual(set(['conflict.googlesource.com']),
607 self.c.get_conflicting_hosts())
608 self.assertEqual(set(['dup.googlesource.com']),
609 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200610 self.assertEqual(set(['partial.googlesource.com',
611 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100612 self.c.get_partially_configured_hosts())
613 self.assertEqual(set(['chromium.googlesource.com',
614 'chrome-internal.googlesource.com']),
615 self.c.get_hosts_with_wrong_identities())
616
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100617 def test_report_no_problems(self):
618 self.test_analysis_nothing()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100619 self.assertFalse(self.c.find_and_report_problems())
620 self.assertEqual(sys.stdout.getvalue(), '')
621
Edward Lemurda4b6c62020-02-13 00:28:40 +0000622 @mock.patch(
623 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
624 return_value='~/.gitcookies')
625 def test_report(self, *_mocks):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100626 self.test_analysis()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100627 self.assertTrue(self.c.find_and_report_problems())
628 with open(os.path.join(os.path.dirname(__file__),
629 'git_cl_creds_check_report.txt')) as f:
630 expected = f.read()
631 def by_line(text):
632 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700633 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200634 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100635
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800636
Edward Lemurda4b6c62020-02-13 00:28:40 +0000637class TestGitCl(unittest.TestCase):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000638 def setUp(self):
639 super(TestGitCl, self).setUp()
640 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700641 self._calls_done = []
Edward Lemurda4b6c62020-02-13 00:28:40 +0000642 mock.patch('sys.stdout', StringIO()).start()
643 mock.patch(
644 'git_cl.time_time',
645 lambda: self._mocked_call('time.time')).start()
646 mock.patch(
647 'git_cl.metrics.collector.add_repeated',
648 lambda *a: self._mocked_call('add_repeated', *a)).start()
649 mock.patch('subprocess2.call', self._mocked_call).start()
650 mock.patch('subprocess2.check_call', self._mocked_call).start()
651 mock.patch('subprocess2.check_output', self._mocked_call).start()
652 mock.patch(
653 'subprocess2.communicate',
654 lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
655 mock.patch(
656 'git_cl.gclient_utils.CheckCallAndFilter',
657 self._mocked_call).start()
658 mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
659 mock.patch(
660 'git_common.get_or_create_merge_base',
661 lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
662 mock.patch('git_cl.BranchExists', return_value=True).start()
663 mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
664 mock.patch(
665 'git_cl.SaveDescriptionBackup',
666 lambda _: self._mocked_call('SaveDescriptionBackup')).start()
667 mock.patch(
Edward Lemurda4b6c62020-02-13 00:28:40 +0000668 'git_cl.write_json',
669 lambda *a: self._mocked_call('write_json', *a)).start()
670 mock.patch(
Edward Lemur227d5102020-02-25 23:45:35 +0000671 'git_cl.Changelist.RunHook',
672 return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000673 mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
674 mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000675 mock.patch('gerrit_util.GetChangeDetail').start()
Edward Lemurda4b6c62020-02-13 00:28:40 +0000676 mock.patch(
677 'git_cl.gerrit_util.GetChangeComments',
678 lambda *a: self._mocked_call('GetChangeComments', *a)).start()
679 mock.patch(
680 'git_cl.gerrit_util.GetChangeRobotComments',
681 lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
682 mock.patch(
683 'git_cl.gerrit_util.AddReviewers',
684 lambda *a: self._mocked_call('AddReviewers', *a)).start()
685 mock.patch(
686 'git_cl.gerrit_util.SetReview',
687 lambda h, i, msg=None, labels=None, notify=None, ready=None: (
688 self._mocked_call(
689 'SetReview', h, i, msg, labels, notify, ready))).start()
690 mock.patch(
691 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
692 return_value=False).start()
693 mock.patch(
694 'git_cl.gerrit_util.GceAuthenticator.is_gce',
695 return_value=False).start()
696 mock.patch(
697 'git_cl.gerrit_util.ValidAccounts',
698 lambda *a: self._mocked_call('ValidAccounts', *a)).start()
Edward Lemurd55c5072020-02-20 01:09:07 +0000699 mock.patch('sys.exit', side_effect=SystemExitMock).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000700 mock.patch('git_cl.Settings.GetRoot', return_value='').start()
Edward Lemur85153282020-02-14 22:06:29 +0000701 self.mockGit = GitMocks()
702 mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
703 mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
704 mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
Edward Lemur84101642020-02-21 21:40:34 +0000705 mock.patch(
706 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000707 mock.patch(
Edward Lemur85153282020-02-14 22:06:29 +0000708 'scm.GIT.FetchUpstreamTuple',
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000709 return_value=('origin', 'refs/heads/master')).start()
Edward Lemur85153282020-02-14 22:06:29 +0000710 mock.patch(
711 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000712 # It's important to reset settings to not have inter-tests interference.
713 git_cl.settings = None
Edward Lemurda4b6c62020-02-13 00:28:40 +0000714 self.addCleanup(mock.patch.stopall)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000715
716 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000717 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000718 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100719 except AssertionError:
Edward Lemur85153282020-02-14 22:06:29 +0000720 calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
721 if len(self.calls) > 5:
722 calls += ' ...\n'
723 self.fail(
724 '\n'
725 'There are un-consumed calls after this test has finished:\n' +
726 calls)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000727 finally:
728 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000729
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000730 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000731 self.assertTrue(
732 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700733 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000734 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000735 expected_args, result = top
736
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000737 # Also logs otherwise it could get caught in a try/finally and be hard to
738 # diagnose.
739 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700740 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000741 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700742 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
743 for i, c in enumerate(self._calls_done[-N:]))
744 following_calls = '\n '.join(
745 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
746 for i, c in enumerate(self.calls[:N]))
747 extended_msg = (
748 'A few prior calls:\n %s\n\n'
749 'This (expected):\n @%d: %r\n'
750 'This (actual):\n @%d: %r\n\n'
751 'A few following expected calls:\n %s' %
752 (prior_calls, len(self._calls_done), expected_args,
753 len(self._calls_done), args, following_calls))
tandrii9d206752016-06-20 11:32:47 -0700754
tandrii99a72f22016-08-17 14:33:24 -0700755 self.fail('@%d\n'
756 ' Expected: %r\n'
Edward Lemur26964072020-02-19 19:18:51 +0000757 ' Actual: %r\n'
758 '\n'
759 '%s' % (
760 len(self._calls_done), expected_args, args, extended_msg))
tandrii9d206752016-06-20 11:32:47 -0700761
762 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700763 if isinstance(result, Exception):
764 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000765 # stdout from git commands is supposed to be a bytestream. Convert it here
766 # instead of converting all test output in this file to bytes.
767 if args[0][0] == 'git' and not isinstance(result, bytes):
768 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000769 return result
770
Edward Lemur1a83da12020-03-04 21:18:36 +0000771 @mock.patch('sys.stdin', StringIO('blah\nye\n'))
772 @mock.patch('sys.stdout', StringIO())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100773 def test_ask_for_explicit_yes_true(self):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100774 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
Edward Lemur1a83da12020-03-04 21:18:36 +0000775 self.assertEqual(
776 'prompt [Yes/No]: Please, type yes or no: ',
777 sys.stdout.getvalue())
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100778
tandrii48df5812016-10-17 03:55:37 -0700779 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000780 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700781 self.calls = [
782 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700783 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
784 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
785 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
786 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700787 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
788 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700789 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
790 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000791 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
792 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700793 ((['git', 'config', 'gerrit.host', 'true'],), ''),
794 ]
795 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
796
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000797 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100798 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200799 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000800 custom_cl_base=None, short_hostname='chromium',
801 change_id=None):
Edward Lemur26964072020-02-19 19:18:51 +0000802 calls = []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200803 if custom_cl_base:
804 ancestor_revision = custom_cl_base
805 else:
806 # Determine ancestor_revision to be merge base.
807 ancestor_revision = 'fake_ancestor_sha'
808 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000809 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
810 ancestor_revision),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200811 ]
812
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100813 if issue:
Edward Lesmes7677e5c2020-02-19 20:39:03 +0000814 gerrit_util.GetChangeDetail.return_value = {
815 'owner': {'email': (other_cl_owner or 'owner@example.com')},
816 'change_id': (change_id or '123456789'),
817 'current_revision': 'sha1_of_current_revision',
818 'revisions': {'sha1_of_current_revision': {
819 'commit': {'message': fetched_description},
820 }},
821 'status': fetched_status or 'NEW',
822 }
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100823 if fetched_status == 'ABANDONED':
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100824 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100825 if other_cl_owner:
826 calls += [
827 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
828 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100829
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100830 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200831 ((['git', 'rev-parse', 'HEAD'],), '12345'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100832 ]
833
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100834 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200835 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
836 ([custom_cl_base] if custom_cl_base else
837 [ancestor_revision, 'HEAD']),),
838 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100839 ]
840 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000841
Edward Lemur26964072020-02-19 19:18:51 +0000842 def _gerrit_upload_calls(self, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700843 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000844 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700845 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100846 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000847 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000848 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000849 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000850 final_description=None, gitcookies_exists=True,
Josipe827b0f2020-01-30 00:07:20 +0000851 force=False, edit_description=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000852 if post_amend_description is None:
853 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700854 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200855
856 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000857
Edward Lemur26964072020-02-19 19:18:51 +0000858 if squash_mode in ('override_squash', 'override_nosquash'):
859 self.mockGit.config['gerrit.override-squash-uploads'] = (
860 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700861
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000862 # If issue is given, then description is fetched from Gerrit instead.
863 if issue is None:
Aaron Gableb56ad332017-01-06 15:24:31 -0800864 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000865 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800866 else:
867 if not title:
868 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200869 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
870 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800871 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000872 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000873 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000874 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200875 (('DownloadGerritHook', False), ''),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200876 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000877 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000878 if force or not issue:
Anthony Polito8b955342019-09-24 19:01:36 +0000879 if not force:
880 calls += [
Anthony Polito8b955342019-09-24 19:01:36 +0000881 ((['RunEditor'],), description),
882 ]
Josipe827b0f2020-01-30 00:07:20 +0000883 # user wants to edit description
884 if edit_description:
885 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000886 ((['RunEditor'],), edit_description),
887 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000888 ref_to_push = 'abcdef0123456789'
889 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200890 ]
891
892 if custom_cl_base is None:
893 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000894 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000895 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200896 ]
897 parent = 'origin/master'
898 else:
899 calls += [
900 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
901 'refs/remotes/origin/master'],),
902 callError(1)), # Means not ancenstor.
903 (('ask_for_data',
904 'Do you take responsibility for cleaning up potential mess '
905 'resulting from proceeding with upload? Press Enter to upload, '
906 'or Ctrl+C to abort'), ''),
907 ]
908 parent = custom_cl_base
909
910 calls += [
911 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
912 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000913 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200914 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000915 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200916 ref_to_push),
917 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000918 else:
919 ref_to_push = 'HEAD'
920
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000921 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000922 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200923 ((['git', 'rev-list',
924 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
925 ref_to_push],),
926 '1hashPerLine\n'),
927 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000928
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000929 metrics_arguments = []
930
Aaron Gableafd52772017-06-27 16:40:10 -0700931 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700932 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000933 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700934 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400935 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700936 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000937 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700938 else:
939 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000940 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800941
Aaron Gable70f4e242017-06-26 10:45:59 -0700942 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700943 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000944 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000945
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000946 if short_hostname == 'chromium':
947 # All reviwers and ccs get into ref_suffix.
948 for r in sorted(reviewers):
949 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000950 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000951 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000952 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000953 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000954 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000955 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000956 reviewers, cc = [], []
957 else:
958 # TODO(crbug/877717): remove this case.
959 calls += [
960 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
961 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000962 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000963 {
964 e: {'email': e}
965 for e in (reviewers + ['joe@example.com'] + cc)
966 })
967 ]
968 for r in sorted(reviewers):
969 if r != 'bad-account-or-email':
970 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000971 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000972 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000973 if issue is None:
974 cc += ['joe@example.com']
975 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000976 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000977 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000978 if c in cc:
979 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000980
Edward Lemur687ca902018-12-05 02:30:30 +0000981 for k, v in sorted((labels or {}).items()):
982 ref_suffix += ',l=%s+%d' % (k, v)
983 metrics_arguments.append('l=%s+%d' % (k, v))
984
985 if tbr:
986 calls += [
987 (('GetCodeReviewTbrScore',
988 '%s-review.googlesource.com' % short_hostname,
989 'my/repo'),
990 2,),
991 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000992
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000993 calls += [
994 (('time.time',), 1000,),
995 ((['git', 'push',
996 'https://%s.googlesource.com/my/repo' % short_hostname,
997 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
998 (('remote:\n'
999 'remote: Processing changes: (\)\n'
1000 'remote: Processing changes: (|)\n'
1001 'remote: Processing changes: (/)\n'
1002 'remote: Processing changes: (-)\n'
1003 'remote: Processing changes: new: 1 (/)\n'
1004 'remote: Processing changes: new: 1, done\n'
1005 'remote:\n'
1006 'remote: New Changes:\n'
1007 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1008 ' XXX\n'
1009 'remote:\n'
1010 'To https://%s.googlesource.com/my/repo\n'
1011 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1012 ) % (short_hostname, short_hostname)),),
1013 (('time.time',), 2000,),
1014 (('add_repeated',
1015 'sub_commands',
1016 {
1017 'execution_time': 1000,
1018 'command': 'git push',
1019 'exit_code': 0,
1020 'arguments': sorted(metrics_arguments),
1021 }),
1022 None,),
1023 ]
1024
Edward Lemur1b52d872019-05-09 21:12:12 +00001025 final_description = final_description or post_amend_description.strip()
1026 original_title = original_title or title or '<untitled>'
1027 # Trace-related calls
1028 calls += [
1029 # Write a description with context for the current trace.
1030 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001031 'Thu Mar 16 20:00:41 2017\n'
1032 '%(short_hostname)s-review.googlesource.com\n'
1033 '%(change_id)s\n'
1034 '%(title)s\n'
1035 '%(description)s\n'
1036 '1000\n'
1037 '0\n'
1038 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001039 'short_hostname': short_hostname,
1040 'change_id': change_id,
1041 'description': final_description,
1042 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001043 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001044 }],),
1045 None,
1046 ),
1047 # Read traces and shorten git hashes.
1048 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1049 True,
1050 ),
1051 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1052 ('git-hash: 0123456789012345678901234567890123456789\n'
1053 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1054 ),
1055 ((['FileWrite', 'TEMP_DIR/trace-packet',
1056 'git-hash: 012345\n'
1057 'git-hash: abcdea\n'],),
1058 None,
1059 ),
1060 # Make zip file for the git traces.
1061 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1062 'TEMP_DIR'],),
1063 None,
1064 ),
1065 # Collect git config and gitcookies.
1066 ((['git', 'config', '-l'],),
1067 'git-config-output',
1068 ),
1069 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1070 None,
1071 ),
1072 ((['os.path.isfile', '~/.gitcookies'],),
1073 gitcookies_exists,
1074 ),
1075 ]
1076 if gitcookies_exists:
1077 calls += [
1078 ((['FileRead', '~/.gitcookies'],),
1079 'gitcookies 1/SECRET',
1080 ),
1081 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1082 None,
1083 ),
1084 ]
1085 calls += [
1086 # Make zip file for the git config and gitcookies.
1087 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1088 'TEMP_DIR'],),
1089 None,
1090 ),
1091 ]
1092
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001093 # TODO(crbug/877717): this should never be used.
1094 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001095 calls += [
1096 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001097 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001098 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001099 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001100 notify),
1101 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001102 ]
Edward Lemur26964072020-02-19 19:18:51 +00001103 calls += [
1104 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1105 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001106 return calls
1107
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001108 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001109 self,
1110 upload_args,
1111 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001112 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001113 squash=True,
1114 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001115 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001116 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001117 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001118 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001119 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001120 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001121 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001122 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001123 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001124 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001125 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001126 labels=None,
1127 change_id=None,
1128 original_title=None,
1129 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001130 gitcookies_exists=True,
1131 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001132 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001133 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001134 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001135 if squash_mode is None:
1136 if '--no-squash' in upload_args:
1137 squash_mode = 'nosquash'
1138 elif '--squash' in upload_args:
1139 squash_mode = 'squash'
1140 else:
1141 squash_mode = 'default'
1142
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001143 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001144 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001145 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001146 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001147 same_auth=('git-owner.example.com', '', 'pass'))).start()
1148 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1149 lambda _, offer_removal: None).start()
1150 mock.patch('git_cl.gclient_utils.RunEditor',
1151 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1152 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1153 'DownloadGerritHook', force)).start()
1154 mock.patch('git_cl.gclient_utils.FileRead',
1155 lambda path: self._mocked_call(['FileRead', path])).start()
1156 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001157 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001158 ['FileWrite', path, contents])).start()
1159 mock.patch('git_cl.datetime_now',
1160 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1161 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1162 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1163 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001164 '%(now)s\n'
1165 '%(gerrit_host)s\n'
1166 '%(change_id)s\n'
1167 '%(title)s\n'
1168 '%(description)s\n'
1169 '%(execution_time)s\n'
1170 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001171 '%(trace_name)s').start()
1172 mock.patch('git_cl.shutil.make_archive',
1173 lambda *args: self._mocked_call(['make_archive'] +
1174 list(args))).start()
1175 mock.patch('os.path.isfile',
1176 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001177 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001178 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00001179 'git_cl._create_description_from_log', return_value=description).start()
1180 mock.patch(
1181 'git_cl.Changelist._AddChangeIdToCommitMessage',
1182 return_value=post_amend_description or description).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001183 mock.patch(
1184 'git_cl.ask_for_data',
1185 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001186
Edward Lemur26964072020-02-19 19:18:51 +00001187 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001188 self.mockGit.config['branch.master.gerritissue'] = (
1189 str(issue) if issue else None)
1190 self.mockGit.config['remote.origin.url'] = (
1191 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001192 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001193
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001194 self.calls = self._gerrit_base_calls(
1195 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001196 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001197 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001198 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001199 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001200 short_hostname=short_hostname,
1201 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001202 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001203 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001204 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001205 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001206 self.calls += self._gerrit_upload_calls(
1207 description, reviewers, squash,
1208 squash_mode=squash_mode,
1209 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001210 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001211 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001212 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001213 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001214 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001215 labels=labels,
1216 change_id=change_id,
1217 original_title=original_title,
1218 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001219 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001220 force=force,
1221 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001222 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001223 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001224 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001225 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001226 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001227 self.assertEqual(
1228 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001229 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001230
Edward Lemur1b52d872019-05-09 21:12:12 +00001231 def test_gerrit_upload_traces_no_gitcookies(self):
1232 self._run_gerrit_upload_test(
1233 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001234 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001235 [],
1236 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001237 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001238 change_id='Ixxx',
1239 gitcookies_exists=False)
1240
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001241 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001242 self._run_gerrit_upload_test(
1243 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001244 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001245 [],
1246 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001247 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001248 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001249
1250 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001251 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001252 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001253 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001254 [],
tandriia60502f2016-06-20 02:01:53 -07001255 squash=False,
1256 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001257 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001258 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001259
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001260 def test_gerrit_no_reviewer(self):
1261 self._run_gerrit_upload_test(
1262 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001263 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001264 [],
1265 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001266 squash_mode='override_nosquash',
1267 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001268
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001269 def test_gerrit_no_reviewer_non_chromium_host(self):
1270 # TODO(crbug/877717): remove this test case.
1271 self._run_gerrit_upload_test(
1272 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001273 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001274 [],
1275 squash=False,
1276 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001277 short_hostname='other',
1278 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001279
Nick Carter8692b182017-11-06 16:30:38 -08001280 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001281 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001282 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001283 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001284 squash=False,
1285 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001286 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1287 change_id='I123456789',
1288 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001289
ukai@chromium.orge8077812012-02-03 03:41:46 +00001290 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001291 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001292 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001293 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001294 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001295 squash=False,
1296 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001297 notify=True,
1298 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001299 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001300 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001301
Anthony Polito8b955342019-09-24 19:01:36 +00001302 def test_gerrit_upload_force_sets_bug(self):
1303 self._run_gerrit_upload_test(
1304 ['-b', '10000', '-f'],
1305 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1306 [],
1307 force=True,
1308 expected_upstream_ref='origin/master',
1309 fetched_description='desc=\n\nChange-Id: Ixxx',
1310 original_title='Initial upload',
1311 change_id='Ixxx')
1312
1313 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1314 self._run_gerrit_upload_test(
1315 ['-b', '10000', '-f', '-m', 'Title'],
1316 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1317 [],
1318 force=True,
1319 issue='123456',
1320 expected_upstream_ref='origin/master',
1321 fetched_description='desc=\n\nChange-Id: Ixxxx',
1322 original_title='Title',
1323 title='Title',
1324 change_id='Izzzz')
1325
Dan Beamd8b04ca2019-10-10 21:23:26 +00001326 def test_gerrit_upload_force_sets_fixed(self):
1327 self._run_gerrit_upload_test(
1328 ['-x', '10000', '-f'],
1329 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1330 [],
1331 force=True,
1332 expected_upstream_ref='origin/master',
1333 fetched_description='desc=\n\nChange-Id: Ixxx',
1334 original_title='Initial upload',
1335 change_id='Ixxx')
1336
ukai@chromium.orge8077812012-02-03 03:41:46 +00001337 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001338 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1339 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001340 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001341 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001342 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001343 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001344 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001345 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001346 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001347 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001348 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001349 labels={'Code-Review': 2},
1350 change_id='123456789',
1351 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001352
1353 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001354 self._run_gerrit_upload_test(
1355 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001356 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001357 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001358 expected_upstream_ref='origin/master',
1359 change_id='123456789',
1360 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001361
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001362 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001363 self._run_gerrit_upload_test(
1364 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001365 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001366 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001367 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001368 expected_upstream_ref='origin/master',
1369 change_id='123456789',
1370 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001371
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001372 def test_gerrit_upload_squash_first_with_labels(self):
1373 self._run_gerrit_upload_test(
1374 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001375 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001376 [],
1377 squash=True,
1378 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001379 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1380 change_id='123456789',
1381 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001382
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001383 def test_gerrit_upload_squash_first_against_rev(self):
1384 custom_cl_base = 'custom_cl_base_rev_or_branch'
1385 self._run_gerrit_upload_test(
1386 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001387 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001388 [],
1389 squash=True,
1390 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001391 custom_cl_base=custom_cl_base,
1392 change_id='123456789',
1393 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001394 self.assertIn(
1395 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1396 sys.stdout.getvalue())
1397
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001398 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001399 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001400 self._run_gerrit_upload_test(
1401 ['--squash'],
1402 description,
1403 [],
1404 squash=True,
1405 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001406 issue=123456,
1407 change_id='123456789',
1408 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001409
Edward Lemurd55c5072020-02-20 01:09:07 +00001410 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001411 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001412 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001413 with self.assertRaises(SystemExitMock):
1414 self._run_gerrit_upload_test(
1415 ['--squash'],
1416 description,
1417 [],
1418 squash=True,
1419 expected_upstream_ref='origin/master',
1420 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001421 fetched_status='ABANDONED',
1422 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001423 self.assertEqual(
1424 'Change https://chromium-review.googlesource.com/123456 has been '
1425 'abandoned, new uploads are not allowed\n',
1426 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001427
Edward Lemurda4b6c62020-02-13 00:28:40 +00001428 @mock.patch(
1429 'gerrit_util.GetAccountDetails',
1430 return_value={'email': 'yet-another@example.com'})
1431 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001432 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001433 self._run_gerrit_upload_test(
1434 ['--squash'],
1435 description,
1436 [],
1437 squash=True,
1438 expected_upstream_ref='origin/master',
1439 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001440 other_cl_owner='other@example.com',
1441 change_id='123456789',
1442 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001443 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001444 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001445 'authenticate to Gerrit as yet-another@example.com.\n'
1446 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001447 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001448
Josipe827b0f2020-01-30 00:07:20 +00001449 def test_upload_change_description_editor(self):
1450 fetched_description = 'foo\n\nChange-Id: 123456789'
1451 description = 'bar\n\nChange-Id: 123456789'
1452 self._run_gerrit_upload_test(
1453 ['--squash', '--edit-description'],
1454 description,
1455 [],
1456 fetched_description=fetched_description,
1457 squash=True,
1458 expected_upstream_ref='origin/master',
1459 issue=123456,
1460 change_id='123456789',
1461 original_title='User input',
1462 edit_description=description)
1463
Edward Lemurda4b6c62020-02-13 00:28:40 +00001464 @mock.patch('git_cl.RunGit')
1465 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001466 @mock.patch('sys.stdin', StringIO('\n'))
1467 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001468 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001469 def mock_run_git(*args, **_kwargs):
1470 if args[0] == ['for-each-ref',
1471 '--format=%(refname:short) %(upstream:short)',
1472 'refs/heads']:
1473 # Create a local branch dependency tree that looks like this:
1474 # test1 -> test2 -> test3 -> test4 -> test5
1475 # -> test3.1
1476 # test6 -> test0
1477 branch_deps = [
1478 'test2 test1', # test1 -> test2
1479 'test3 test2', # test2 -> test3
1480 'test3.1 test2', # test2 -> test3.1
1481 'test4 test3', # test3 -> test4
1482 'test5 test4', # test4 -> test5
1483 'test6 test0', # test0 -> test6
1484 'test7', # test7
1485 ]
1486 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001487 git_cl.RunGit.side_effect = mock_run_git
1488 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001489
1490 class MockChangelist():
1491 def __init__(self):
1492 pass
1493 def GetBranch(self):
1494 return 'test1'
1495 def GetIssue(self):
1496 return '123'
1497 def GetPatchset(self):
1498 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001499 def IsGerrit(self):
1500 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001501
1502 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1503 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001504 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001505 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001506 'This command will checkout all dependent branches '
1507 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001508 'or Ctrl+C to abort',
1509 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001510 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001511
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001512 def test_gerrit_change_id(self):
1513 self.calls = [
1514 ((['git', 'write-tree'], ),
1515 'hashtree'),
1516 ((['git', 'rev-parse', 'HEAD~0'], ),
1517 'branch-parent'),
1518 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1519 'A B <a@b.org> 1456848326 +0100'),
1520 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1521 'C D <c@d.org> 1456858326 +0100'),
1522 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1523 'hashchange'),
1524 ]
1525 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1526 self.assertEqual(change_id, 'Ihashchange')
1527
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001528 def test_desecription_append_footer(self):
1529 for init_desc, footer_line, expected_desc in [
1530 # Use unique desc first lines for easy test failure identification.
1531 ('foo', 'R=one', 'foo\n\nR=one'),
1532 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1533 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1534 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1535 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1536 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1537 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1538 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1539 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1540 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1541 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1542 ]:
1543 desc = git_cl.ChangeDescription(init_desc)
1544 desc.append_footer(footer_line)
1545 self.assertEqual(desc.description, expected_desc)
1546
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001547 def test_update_reviewers(self):
1548 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001549 ('foo', [], [],
1550 'foo'),
1551 ('foo\nR=xx', [], [],
1552 'foo\nR=xx'),
1553 ('foo\nTBR=xx', [], [],
1554 'foo\nTBR=xx'),
1555 ('foo', ['a@c'], [],
1556 'foo\n\nR=a@c'),
1557 ('foo\nR=xx', ['a@c'], [],
1558 'foo\n\nR=a@c, xx'),
1559 ('foo\nTBR=xx', ['a@c'], [],
1560 'foo\n\nR=a@c\nTBR=xx'),
1561 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1562 'foo\n\nR=a@c, yy\nTBR=xx'),
1563 ('foo\nBUG=', ['a@c'], [],
1564 'foo\nBUG=\nR=a@c'),
1565 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1566 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1567 ('foo', ['a@c', 'b@c'], [],
1568 'foo\n\nR=a@c, b@c'),
1569 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1570 'foo\nBar\n\nR=c@c\nBUG='),
1571 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1572 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001573 # Same as the line before, but full of whitespaces.
1574 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001575 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001576 'foo\nBar\n\nR=c@c\n BUG =',
1577 ),
1578 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001579 ('foo BUG=allo R=joe ', ['c@c'], [],
1580 'foo BUG=allo R=joe\n\nR=c@c'),
1581 # Redundant TBRs get promoted to Rs
1582 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1583 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001584 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001585 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001586 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001587 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001588 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001589 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001590 actual.append(obj.description)
1591 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001592
Nodir Turakulov23b82142017-11-16 11:04:25 -08001593 def test_get_hash_tags(self):
1594 cases = [
1595 ('', []),
1596 ('a', []),
1597 ('[a]', ['a']),
1598 ('[aa]', ['aa']),
1599 ('[a ]', ['a']),
1600 ('[a- ]', ['a']),
1601 ('[a- b]', ['a-b']),
1602 ('[a--b]', ['a-b']),
1603 ('[a', []),
1604 ('[a]x', ['a']),
1605 ('[aa]x', ['aa']),
1606 ('[a b]', ['a-b']),
1607 ('[a b]', ['a-b']),
1608 ('[a__b]', ['a-b']),
1609 ('[a] x', ['a']),
1610 ('[a][b]', ['a', 'b']),
1611 ('[a] [b]', ['a', 'b']),
1612 ('[a][b]x', ['a', 'b']),
1613 ('[a][b] x', ['a', 'b']),
1614 ('[a]\n[b]', ['a']),
1615 ('[a\nb]', []),
1616 ('[a][', ['a']),
1617 ('Revert "[a] feature"', ['a']),
1618 ('Reland "[a] feature"', ['a']),
1619 ('Revert: [a] feature', ['a']),
1620 ('Reland: [a] feature', ['a']),
1621 ('Revert "Reland: [a] feature"', ['a']),
1622 ('Foo: feature', ['foo']),
1623 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001624 ('Change Foo::Bar', []),
1625 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001626 ('Revert "Foo bar: feature"', ['foo-bar']),
1627 ('Reland "Foo bar: feature"', ['foo-bar']),
1628 ]
1629 for desc, expected in cases:
1630 change_desc = git_cl.ChangeDescription(desc)
1631 actual = change_desc.get_hash_tags()
1632 self.assertEqual(
1633 actual,
1634 expected,
1635 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1636
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001637 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001638 self.assertEqual(None, git_cl.GetTargetRef(None,
1639 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001640 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001641
wittman@chromium.org455dc922015-01-26 20:15:50 +00001642 # Check default target refs for branches.
1643 self.assertEqual('refs/heads/master',
1644 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001645 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001646 self.assertEqual('refs/heads/master',
1647 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001648 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001649 self.assertEqual('refs/heads/master',
1650 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001651 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001652 self.assertEqual('refs/branch-heads/123',
1653 git_cl.GetTargetRef('origin',
1654 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001655 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001656 self.assertEqual('refs/diff/test',
1657 git_cl.GetTargetRef('origin',
1658 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001659 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001660 self.assertEqual('refs/heads/chrome/m42',
1661 git_cl.GetTargetRef('origin',
1662 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001663 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001664
1665 # Check target refs for user-specified target branch.
1666 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1667 'refs/remotes/branch-heads/123'):
1668 self.assertEqual('refs/branch-heads/123',
1669 git_cl.GetTargetRef('origin',
1670 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001671 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001672 for branch in ('origin/master', 'remotes/origin/master',
1673 'refs/remotes/origin/master'):
1674 self.assertEqual('refs/heads/master',
1675 git_cl.GetTargetRef('origin',
1676 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001677 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001678 for branch in ('master', 'heads/master', 'refs/heads/master'):
1679 self.assertEqual('refs/heads/master',
1680 git_cl.GetTargetRef('origin',
1681 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001682 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001683
Edward Lemurda4b6c62020-02-13 00:28:40 +00001684 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1685 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001686 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001687 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1688
Edward Lemur85153282020-02-14 22:06:29 +00001689 def assertIssueAndPatchset(
1690 self, branch='master', issue='123456', patchset='7',
1691 git_short_host='chromium'):
1692 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001693 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001694 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001695 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001696 self.assertEqual(
1697 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001698 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001699
Edward Lemur85153282020-02-14 22:06:29 +00001700 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001701 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001702 self.mockGit.config['remote.origin.url'] = (
1703 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001704 gerrit_util.GetChangeDetail.return_value = {
1705 'current_revision': '7777777777',
1706 'revisions': {
1707 '1111111111': {
1708 '_number': 1,
1709 'fetch': {'http': {
1710 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1711 'ref': 'refs/changes/56/123456/1',
1712 }},
1713 },
1714 '7777777777': {
1715 '_number': 7,
1716 'fetch': {'http': {
1717 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1718 'ref': 'refs/changes/56/123456/7',
1719 }},
1720 },
1721 },
1722 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001723
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001724 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001725 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001726 self.calls += [
1727 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1728 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001729 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001730 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001731 ]
1732 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001733 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001734
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001735 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001736 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001737 self.calls += [
1738 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1739 'refs/changes/56/123456/7'],), ''),
1740 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001741 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001742 ]
Edward Lemur85153282020-02-14 22:06:29 +00001743 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1744 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001745
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001746 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001747 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001748 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001749 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001750 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001751 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001752 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001753 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001754 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001755 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001756
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001757 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001758 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001759 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001760 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001761 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001762 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001763 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001764 ]
1765 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001766 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001767 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001768
Aaron Gable697a91b2018-01-19 15:20:15 -08001769 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001770 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001771 self.calls += [
1772 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1773 'refs/changes/56/123456/1'],), ''),
1774 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001775 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001776 ]
1777 self.assertEqual(git_cl.main(
1778 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1779 0)
Edward Lemur85153282020-02-14 22:06:29 +00001780 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001781
Edward Lemurd55c5072020-02-20 01:09:07 +00001782 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001783 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001784 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001785 self.calls += [
1786 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001787 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001788 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001789 ]
1790 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001791 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001792 self.assertEqual(
1793 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1794 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001795
Edward Lemurda4b6c62020-02-13 00:28:40 +00001796 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001797 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001798 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001799 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001800 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001801 self.mockGit.config['remote.origin.url'] = (
1802 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001803 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001804 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001805 self.assertEqual(
1806 'change 123456 at https://chromium-review.googlesource.com does not '
1807 'exist or you have no access to it\n',
1808 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001809
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001810 def _checkout_calls(self):
1811 return [
1812 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001813 'branch\\..*\\.gerritissue'], ),
1814 ('branch.ger-branch.gerritissue 123456\n'
1815 'branch.gbranch654.gerritissue 654321\n')),
1816 ]
1817
1818 def test_checkout_gerrit(self):
1819 """Tests git cl checkout <issue>."""
1820 self.calls = self._checkout_calls()
1821 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1822 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1823
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001824 def test_checkout_not_found(self):
1825 """Tests git cl checkout <issue>."""
1826 self.calls = self._checkout_calls()
1827 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1828
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001829 def test_checkout_no_branch_issues(self):
1830 """Tests git cl checkout <issue>."""
1831 self.calls = [
1832 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001833 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001834 ]
1835 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1836
Edward Lemur26964072020-02-19 19:18:51 +00001837 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001838 mock.patch(
1839 'git_cl.ask_for_data',
1840 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001841 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1842 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001843 self.mockGit.config['remote.origin.url'] = (
1844 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001845 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001846 cl.branch = 'master'
1847 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001848 return cl
1849
Edward Lemurd55c5072020-02-20 01:09:07 +00001850 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001851 def test_gerrit_ensure_authenticated_missing(self):
1852 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001853 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001854 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001855 with self.assertRaises(SystemExitMock):
1856 cl.EnsureAuthenticated(force=False)
1857 self.assertEqual(
1858 'Credentials for the following hosts are required:\n'
1859 ' chromium-review.googlesource.com\n'
1860 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1861 'You can (re)generate your credentials by visiting '
1862 'https://chromium-review.googlesource.com/new-password\n',
1863 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001864
1865 def test_gerrit_ensure_authenticated_conflict(self):
1866 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001867 'chromium.googlesource.com':
1868 ('git-one.example.com', None, 'secret1'),
1869 'chromium-review.googlesource.com':
1870 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001871 })
1872 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001873 (('ask_for_data', 'If you know what you are doing '
1874 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001875 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1876
1877 def test_gerrit_ensure_authenticated_ok(self):
1878 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001879 'chromium.googlesource.com':
1880 ('git-same.example.com', None, 'secret'),
1881 'chromium-review.googlesource.com':
1882 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001883 })
1884 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1885
tandrii@chromium.org28253532016-04-14 13:46:56 +00001886 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001887 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1888 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001889 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1890
Eric Boren2fb63102018-10-05 13:05:03 +00001891 def test_gerrit_ensure_authenticated_bearer_token(self):
1892 cl = self._test_gerrit_ensure_authenticated_common(auth={
1893 'chromium.googlesource.com':
1894 ('', None, 'secret'),
1895 'chromium-review.googlesource.com':
1896 ('', None, 'secret'),
1897 })
1898 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1899 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1900 'chromium.googlesource.com')
1901 self.assertTrue('Bearer' in header)
1902
Daniel Chengcf6269b2019-05-18 01:02:12 +00001903 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001904 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001905 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001906 (('logging.warning',
1907 'Ignoring branch %(branch)s with non-https remote '
1908 '%(remote)s', {
1909 'branch': 'master',
1910 'remote': 'custom-scheme://repo'}
1911 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001912 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001913 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1914 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1915 mock.patch('logging.warning',
1916 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001917 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001918 cl.branch = 'master'
1919 cl.branchref = 'refs/heads/master'
1920 cl.lookedup_issue = True
1921 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1922
Florian Mayerae510e82020-01-30 21:04:48 +00001923 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001924 self.mockGit.config['remote.origin.url'] = (
1925 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001926 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001927 (('logging.error',
1928 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1929 'but it doesn\'t exist.', {
1930 'remote': 'origin',
1931 'branch': 'master',
1932 'url': 'git@somehost.example:foo/bar.git'}
1933 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001934 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001935 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1936 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1937 mock.patch('logging.error',
1938 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001939 cl = git_cl.Changelist()
1940 cl.branch = 'master'
1941 cl.branchref = 'refs/heads/master'
1942 cl.lookedup_issue = True
1943 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1944
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001945 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001946 self.mockGit.config['branch.master.gerritissue'] = '123'
1947 self.mockGit.config['branch.master.gerritserver'] = (
1948 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001949 self.mockGit.config['remote.origin.url'] = (
1950 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001951 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001952 (('SetReview', 'chromium-review.googlesource.com',
1953 'infra%2Finfra~123', None,
1954 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001955 ]
tandriid9e5ce52016-07-13 02:32:59 -07001956
1957 def test_cmd_set_commit_gerrit_clear(self):
1958 self._cmd_set_commit_gerrit_common(0)
1959 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1960
1961 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001962 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001963 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1964
tandriid9e5ce52016-07-13 02:32:59 -07001965 def test_cmd_set_commit_gerrit(self):
1966 self._cmd_set_commit_gerrit_common(2)
1967 self.assertEqual(0, git_cl.main(['set-commit']))
1968
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001969 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001970 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001971 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001972
1973 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001974 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001975
Edward Lemurda4b6c62020-02-13 00:28:40 +00001976 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001977 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001978 try:
1979 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001980 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001981 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001982 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001983
1984 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001985 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001986 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07001987 return 'foobar'
1988
Edward Lemurda4b6c62020-02-13 00:28:40 +00001989 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07001990 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00001991 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001992 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001993 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07001994
iannuccie53c9352016-08-17 14:40:40 -07001995 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001996
iannuccie53c9352016-08-17 14:40:40 -07001997 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001998 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07001999 return 'foobar'
2000
Edward Lemurda4b6c62020-02-13 00:28:40 +00002001 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2002 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002003 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002004 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002005
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002006 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002007 self.mockGit.config['remote.origin.url'] = (
2008 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002009 gerrit_util.GetChangeDetail.return_value = {
2010 'current_revision': 'sha1',
2011 'revisions': {'sha1': {
2012 'commit': {'message': 'foobar'},
2013 }},
2014 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002015 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002016 'description',
2017 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2018 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002019 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002020
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002021 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002022 mock.patch('git_cl.Changelist', ChangelistMock).start()
2023 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002024
2025 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2026 self.assertEqual('hihi', ChangelistMock.desc)
2027
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002028 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002029 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002030
2031 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002032 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002033 '# Enter a description of the change.\n'
2034 '# This will be displayed on the codereview site.\n'
2035 '# The first line will also be used as the subject of the review.\n'
2036 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002037 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002038 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002039 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002040 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002041 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002042
Edward Lemur6c6827c2020-02-06 21:15:18 +00002043 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002044 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002045
Edward Lemurda4b6c62020-02-13 00:28:40 +00002046 mock.patch('git_cl.Changelist.FetchDescription',
2047 lambda *args: current_desc).start()
2048 mock.patch('git_cl.Changelist.UpdateDescription',
2049 UpdateDescription).start()
2050 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002051
Edward Lemur85153282020-02-14 22:06:29 +00002052 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002053 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002054
Dan Beamd8b04ca2019-10-10 21:23:26 +00002055 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2056 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2057
2058 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002059 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002060 '# Enter a description of the change.\n'
2061 '# This will be displayed on the codereview site.\n'
2062 '# The first line will also be used as the subject of the review.\n'
2063 '#--------------------This line is 72 characters long'
2064 '--------------------\n'
2065 'Some.\n\nFixed: 123\nChange-Id: xxx',
2066 desc)
2067 return desc
2068
Edward Lemurda4b6c62020-02-13 00:28:40 +00002069 mock.patch('git_cl.Changelist.FetchDescription',
2070 lambda *args: current_desc).start()
2071 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002072
Edward Lemur85153282020-02-14 22:06:29 +00002073 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002074 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002075
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002076 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002077 mock.patch('git_cl.Changelist', ChangelistMock).start()
2078 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002079
2080 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2081 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2082
kmarshall3bff56b2016-06-06 18:31:47 -07002083 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002084 self.calls = [
2085 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002086 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002087 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002088 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002089 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002090 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002091
Edward Lemurda4b6c62020-02-13 00:28:40 +00002092 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002093 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002094 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2095 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002096 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002097
2098 self.assertEqual(0, git_cl.main(['archive', '-f']))
2099
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002100 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002101 self.calls = [
2102 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2103 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2104 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2105 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002106 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2107 ((['git', 'branch', '-D', 'foo'],), '')
2108 ]
2109
Edward Lemurda4b6c62020-02-13 00:28:40 +00002110 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002111 lambda branches, fine_grained, max_processes:
2112 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2113 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002114 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002115
2116 self.assertEqual(0, git_cl.main(['archive', '-f']))
2117
kmarshall3bff56b2016-06-06 18:31:47 -07002118 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002119 self.calls = [
2120 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2121 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002122 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002123 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002124
Edward Lemurda4b6c62020-02-13 00:28:40 +00002125 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002126 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002127 [(MockChangelistWithBranchAndIssue('master', 1),
2128 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002129
2130 self.assertEqual(1, git_cl.main(['archive', '-f']))
2131
2132 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002133 self.calls = [
2134 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2135 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002136 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002137 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002138
Edward Lemurda4b6c62020-02-13 00:28:40 +00002139 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002140 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002141 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2142 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002143 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002144
kmarshall9249e012016-08-23 12:02:16 -07002145 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2146
2147 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002148 self.calls = [
2149 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2150 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002151 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002152 ((['git', 'branch', '-D', 'foo'],), '')
2153 ]
kmarshall9249e012016-08-23 12:02:16 -07002154
Edward Lemurda4b6c62020-02-13 00:28:40 +00002155 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002156 lambda branches, fine_grained, max_processes:
2157 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2158 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002159 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002160
2161 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002162
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002163 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002164 self.calls = [
2165 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2166 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2167 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002168 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2169 'refs/tags/git-cl-archived-456-foo'),
2170 ((['git', 'branch', '-D', 'foo'],), CERR1),
2171 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2172 'refs/tags/git-cl-archived-456-foo'),
2173 ]
2174
Edward Lemurda4b6c62020-02-13 00:28:40 +00002175 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002176 lambda branches, fine_grained, max_processes:
2177 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2178 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002179 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002180
2181 self.assertEqual(0, git_cl.main(['archive', '-f']))
2182
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002183 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002184 self.mockGit.config['branch.master.gerritissue'] = '123'
2185 self.mockGit.config['branch.master.gerritserver'] = (
2186 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002187 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002188 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002189 ]
2190 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002191 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2192 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002193
Aaron Gable400e9892017-07-12 15:31:21 -07002194 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002195 self.mockGit.config['branch.master.gerritissue'] = '123'
2196 self.mockGit.config['branch.master.gerritserver'] = (
2197 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002198 mock.patch('git_cl.Changelist.FetchDescription',
2199 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002200 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002201 ((['git', 'log', '-1', '--format=%B'],),
2202 'This is a description\n\nChange-Id: Ideadbeef'),
2203 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002204 ]
2205 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002206 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2207 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002208
phajdan.jre328cf92016-08-22 04:12:17 -07002209 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002210 self.mockGit.config['branch.master.gerritissue'] = '123'
2211 self.mockGit.config['branch.master.gerritserver'] = (
2212 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002213 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002214 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002215 {'issue': 123,
2216 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002217 ''),
2218 ]
2219 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2220
tandrii16e0b4e2016-06-07 10:34:28 -07002221 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002222 mock.patch(
2223 'git_cl.os.path.abspath',
2224 lambda path: self._mocked_call(['abspath', path])).start()
2225 mock.patch(
2226 'git_cl.os.path.exists',
2227 lambda path: self._mocked_call(['exists', path])).start()
2228 mock.patch(
2229 'git_cl.gclient_utils.FileRead',
2230 lambda path: self._mocked_call(['FileRead', path])).start()
2231 mock.patch(
2232 'git_cl.gclient_utils.rm_file_or_tree',
2233 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002234 mock.patch(
2235 'git_cl.ask_for_data',
2236 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002237 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002238
2239 def test_GerritCommitMsgHookCheck_custom_hook(self):
2240 cl = self._common_GerritCommitMsgHookCheck()
2241 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002242 ((['exists', '.git/hooks/commit-msg'],), True),
2243 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002244 '#!/bin/sh\necho "custom hook"')
2245 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002246 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002247
2248 def test_GerritCommitMsgHookCheck_not_exists(self):
2249 cl = self._common_GerritCommitMsgHookCheck()
2250 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002251 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002252 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002253 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002254
2255 def test_GerritCommitMsgHookCheck(self):
2256 cl = self._common_GerritCommitMsgHookCheck()
2257 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002258 ((['exists', '.git/hooks/commit-msg'],), True),
2259 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002260 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002261 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002262 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002263 ''),
2264 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002265 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002266
tandriic4344b52016-08-29 06:04:54 -07002267 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002268 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2269 self.mockGit.config['branch.master.gerritserver'] = (
2270 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002271 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002272 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002273 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002274 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002275 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002276 'labels': {},
2277 'current_revision': 'deadbeaf',
2278 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002279 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002280 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002281 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002282 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2283 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002284 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002285 self.assertEqual(0, cl.CMDLand(force=True,
2286 bypass_hooks=True,
2287 verbose=True,
2288 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002289 self.assertIn(
2290 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002291 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002292 self.assertIn(
2293 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002294 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002295
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002296 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002297 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002298
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002299 def test_gerrit_change_detail_cache_simple(self):
2300 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002301 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002302 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002303 cl1._cached_remote_url = (
2304 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002305 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002306 cl2._cached_remote_url = (
2307 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002308 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2309 self.assertEqual(cl1._GetChangeDetail(), 'a')
2310 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002311
2312 def test_gerrit_change_detail_cache_options(self):
2313 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002314 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002315 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002316 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002317 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2318 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2319 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2320 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2321 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2322 self.assertEqual(cl._GetChangeDetail(), 'cab')
2323
2324 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2325 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2326 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2327 self.assertEqual(cl._GetChangeDetail(), 'cab')
2328
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002329 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002330 gerrit_util.GetChangeDetail.return_value = {
2331 'current_revision': 'rev1',
2332 'revisions': {
2333 'rev1': {'commit': {'message': 'desc1'}},
2334 },
2335 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002336
2337 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002338 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002339 cl._cached_remote_url = (
2340 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002341 self.assertEqual(cl.FetchDescription(), 'desc1')
2342 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002343
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002344 def test_print_current_creds(self):
2345 class CookiesAuthenticatorMock(object):
2346 def __init__(self):
2347 self.gitcookies = {
2348 'host.googlesource.com': ('user', 'pass'),
2349 'host-review.googlesource.com': ('user', 'pass'),
2350 }
2351 self.netrc = self
2352 self.netrc.hosts = {
2353 'github.com': ('user2', None, 'pass2'),
2354 'host2.googlesource.com': ('user3', None, 'pass'),
2355 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002356 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2357 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002358 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2359 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2360 ' Host\t User\t Which file',
2361 '============================\t=====\t===========',
2362 'host-review.googlesource.com\t user\t.gitcookies',
2363 ' host.googlesource.com\t user\t.gitcookies',
2364 ' host2.googlesource.com\tuser3\t .netrc',
2365 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002366 sys.stdout.seek(0)
2367 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002368 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2369 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2370 ' Host\tUser\t Which file',
2371 '============================\t====\t===========',
2372 'host-review.googlesource.com\tuser\t.gitcookies',
2373 ' host.googlesource.com\tuser\t.gitcookies',
2374 ])
2375
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002376 def _common_creds_check_mocks(self):
2377 def exists_mock(path):
2378 dirname = os.path.dirname(path)
2379 if dirname == os.path.expanduser('~'):
2380 dirname = '~'
2381 base = os.path.basename(path)
2382 if base in ('.netrc', '.gitcookies'):
2383 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2384 # git cl also checks for existence other files not relevant to this test.
2385 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002386 mock.patch(
2387 'git_cl.ask_for_data',
2388 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002389 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002390
2391 def test_creds_check_gitcookies_not_configured(self):
2392 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002393 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2394 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002395 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002396 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002397 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2398 (('os.path.exists', '~/.netrc'), True),
2399 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2400 'or Ctrl+C to abort'), ''),
2401 ((['git', 'config', '--global', 'http.cookiefile',
2402 os.path.expanduser('~/.gitcookies')], ), ''),
2403 ]
2404 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002405 self.assertTrue(
2406 sys.stdout.getvalue().startswith(
2407 'You seem to be using outdated .netrc for git credentials:'))
2408 self.assertIn(
2409 '\nConfigured git to use .gitcookies from',
2410 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002411
2412 def test_creds_check_gitcookies_configured_custom_broken(self):
2413 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002414 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2415 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002416 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002417 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002418 ((['git', 'config', '--global', 'http.cookiefile'],),
2419 '/custom/.gitcookies'),
2420 (('os.path.exists', '/custom/.gitcookies'), False),
2421 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2422 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2423 ((['git', 'config', '--global', 'http.cookiefile',
2424 os.path.expanduser('~/.gitcookies')], ), ''),
2425 ]
2426 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002427 self.assertIn(
2428 'WARNING: You have configured custom path to .gitcookies: ',
2429 sys.stdout.getvalue())
2430 self.assertIn(
2431 'However, your configured .gitcookies file is missing.',
2432 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002433
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002434 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002435 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002436 self.mockGit.config['remote.origin.url'] = (
2437 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002438 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002439 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002440 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002441 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002442 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002443 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002444
Edward Lemurda4b6c62020-02-13 00:28:40 +00002445 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2446 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002447 self.mockGit.config['remote.origin.url'] = (
2448 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002449 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002450 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002451 'current_revision': 'ba5eba11',
2452 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002453 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002454 '_number': 1,
2455 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002456 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002457 '_number': 2,
2458 },
2459 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002460 'messages': [
2461 {
2462 u'_revision_number': 1,
2463 u'author': {
2464 u'_account_id': 1111084,
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00002465 u'email': u'could-be-anything@example.com',
2466 u'name': u'LUCI CQ'
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002467 },
2468 u'date': u'2017-03-15 20:08:45.000000000',
2469 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002470 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002471 u'tag': u'autogenerated:cq:dry-run'
2472 },
2473 {
2474 u'_revision_number': 2,
2475 u'author': {
2476 u'_account_id': 11151243,
2477 u'email': u'owner@example.com',
2478 u'name': u'owner'
2479 },
2480 u'date': u'2017-03-16 20:00:41.000000000',
2481 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2482 u'message': u'PTAL',
2483 },
2484 {
2485 u'_revision_number': 2,
2486 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002487 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002488 u'email': u'reviewer@example.com',
2489 u'name': u'reviewer'
2490 },
2491 u'date': u'2017-03-17 05:19:37.500000000',
2492 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2493 u'message': u'Patch Set 2: Code-Review+1',
2494 },
2495 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002496 }
2497 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002498 (('GetChangeComments', 'chromium-review.googlesource.com',
2499 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002500 '/COMMIT_MSG': [
2501 {
2502 'author': {'email': u'reviewer@example.com'},
2503 'updated': u'2017-03-17 05:19:37.500000000',
2504 'patch_set': 2,
2505 'side': 'REVISION',
2506 'message': 'Please include a bug link',
2507 },
2508 ],
2509 'codereview.settings': [
2510 {
2511 'author': {'email': u'owner@example.com'},
2512 'updated': u'2017-03-16 20:00:41.000000000',
2513 'patch_set': 2,
2514 'side': 'PARENT',
2515 'line': 42,
2516 'message': 'I removed this because it is bad',
2517 },
2518 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002519 }),
2520 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2521 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002522 ] * 2 + [
2523 (('write_json', 'output.json', [
2524 {
2525 u'date': u'2017-03-16 20:00:41.000000',
2526 u'message': (
2527 u'PTAL\n' +
2528 u'\n' +
2529 u'codereview.settings\n' +
2530 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2531 u'c/1/2/codereview.settings#b42\n' +
2532 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002533 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002534 u'approval': False,
2535 u'disapproval': False,
2536 u'sender': u'owner@example.com'
2537 }, {
2538 u'date': u'2017-03-17 05:19:37.500000',
2539 u'message': (
2540 u'Patch Set 2: Code-Review+1\n' +
2541 u'\n' +
2542 u'/COMMIT_MSG\n' +
2543 u' PS2, File comment: https://chromium-review.googlesource' +
2544 u'.com/c/1/2//COMMIT_MSG#\n' +
2545 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002546 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002547 u'approval': False,
2548 u'disapproval': False,
2549 u'sender': u'reviewer@example.com'
2550 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002551 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002552 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002553 expected_comments_summary = [
2554 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002555 message=(
2556 u'PTAL\n' +
2557 u'\n' +
2558 u'codereview.settings\n' +
2559 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2560 u'c/1/2/codereview.settings#b42\n' +
2561 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002562 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002563 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002564 disapproval=False, approval=False, sender=u'owner@example.com'),
2565 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002566 message=(
2567 u'Patch Set 2: Code-Review+1\n' +
2568 u'\n' +
2569 u'/COMMIT_MSG\n' +
2570 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2571 u'c/1/2//COMMIT_MSG#\n' +
2572 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002573 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002574 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002575 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2576 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002577 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002578 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002579 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002580 self.assertEqual(
2581 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2582
2583 def test_git_cl_comments_robot_comments(self):
2584 # git cl comments also fetches robot comments (which are considered a type
2585 # of autogenerated comment), and unlike other types of comments, only robot
2586 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002587 self.mockGit.config['remote.origin.url'] = (
2588 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002589 gerrit_util.GetChangeDetail.return_value = {
2590 'owner': {'email': 'owner@example.com'},
2591 'current_revision': 'ba5eba11',
2592 'revisions': {
2593 'deadbeaf': {
2594 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002595 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002596 'ba5eba11': {
2597 '_number': 2,
2598 },
2599 },
2600 'messages': [
2601 {
2602 u'_revision_number': 1,
2603 u'author': {
2604 u'_account_id': 1111084,
2605 u'email': u'commit-bot@chromium.org',
2606 u'name': u'Commit Bot'
2607 },
2608 u'date': u'2017-03-15 20:08:45.000000000',
2609 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2610 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2611 u'tag': u'autogenerated:cq:dry-run'
2612 },
2613 {
2614 u'_revision_number': 1,
2615 u'author': {
2616 u'_account_id': 123,
2617 u'email': u'tricium@serviceaccount.com',
2618 u'name': u'Tricium'
2619 },
2620 u'date': u'2017-03-16 20:00:41.000000000',
2621 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2622 u'message': u'(1 comment)',
2623 u'tag': u'autogenerated:tricium',
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': 2,
2639 u'author': {
2640 u'_account_id': 123,
2641 u'email': u'tricium@serviceaccount.com',
2642 u'name': u'reviewer'
2643 },
2644 u'date': u'2017-03-17 05:30:37.000000000',
2645 u'tag': u'autogenerated:tricium',
2646 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2647 u'message': u'(1 comment)',
2648 },
2649 ]
2650 }
2651 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002652 (('GetChangeComments', 'chromium-review.googlesource.com',
2653 'infra%2Finfra~1'), {}),
2654 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2655 'infra%2Finfra~1'), {
2656 'codereview.settings': [
2657 {
2658 u'author': {u'email': u'tricium@serviceaccount.com'},
2659 u'updated': u'2017-03-17 05:30:37.000000000',
2660 u'robot_run_id': u'5565031076855808',
2661 u'robot_id': u'Linter/Category',
2662 u'tag': u'autogenerated:tricium',
2663 u'patch_set': 2,
2664 u'side': u'REVISION',
2665 u'message': u'Linter warning message text',
2666 u'line': 32,
2667 },
2668 ],
2669 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002670 ]
2671 expected_comments_summary = [
2672 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2673 message=(
2674 u'(1 comment)\n\ncodereview.settings\n'
2675 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2676 u'c/1/2/codereview.settings#32\n'
2677 u' Linter warning message text\n'),
2678 sender=u'tricium@serviceaccount.com',
2679 autogenerated=True, approval=False, disapproval=False)
2680 ]
2681 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002682 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002683 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002684
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002685 def test_get_remote_url_with_mirror(self):
2686 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002687
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002688 def selective_os_path_isdir_mock(path):
2689 if path == '/cache/this-dir-exists':
2690 return self._mocked_call('os.path.isdir', path)
2691 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002692
Edward Lemurda4b6c62020-02-13 00:28:40 +00002693 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002694
2695 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002696 self.mockGit.config['remote.origin.url'] = (
2697 '/cache/this-dir-exists')
2698 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2699 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002700 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002701 (('os.path.isdir', '/cache/this-dir-exists'),
2702 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002703 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002704 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002705 self.assertEqual(cl.GetRemoteUrl(), url)
2706 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2707
Edward Lemur298f2cf2019-02-22 21:40:39 +00002708 def test_get_remote_url_non_existing_mirror(self):
2709 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002710
Edward Lemur298f2cf2019-02-22 21:40:39 +00002711 def selective_os_path_isdir_mock(path):
2712 if path == '/cache/this-dir-doesnt-exist':
2713 return self._mocked_call('os.path.isdir', path)
2714 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002715
Edward Lemurda4b6c62020-02-13 00:28:40 +00002716 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2717 mock.patch('logging.error',
2718 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002719
Edward Lemur26964072020-02-19 19:18:51 +00002720 self.mockGit.config['remote.origin.url'] = (
2721 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002722 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002723 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2724 False),
2725 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002726 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2727 'but it doesn\'t exist.', {
2728 'remote': 'origin',
2729 'branch': 'master',
2730 'url': '/cache/this-dir-doesnt-exist'}
2731 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002732 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002733 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002734 self.assertIsNone(cl.GetRemoteUrl())
2735
2736 def test_get_remote_url_misconfigured_mirror(self):
2737 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002738
Edward Lemur298f2cf2019-02-22 21:40:39 +00002739 def selective_os_path_isdir_mock(path):
2740 if path == '/cache/this-dir-exists':
2741 return self._mocked_call('os.path.isdir', path)
2742 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002743
Edward Lemurda4b6c62020-02-13 00:28:40 +00002744 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2745 mock.patch('logging.error',
2746 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002747
Edward Lemur26964072020-02-19 19:18:51 +00002748 self.mockGit.config['remote.origin.url'] = (
2749 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002750 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002751 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002752 (('logging.error',
2753 'Remote "%(remote)s" for branch "%(branch)s" points to '
2754 '"%(cache_path)s", but it is misconfigured.\n'
2755 '"%(cache_path)s" must be a git repo and must have a remote named '
2756 '"%(remote)s" pointing to the git host.', {
2757 'remote': 'origin',
2758 'cache_path': '/cache/this-dir-exists',
2759 'branch': 'master'}
2760 ), None),
2761 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002762 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002763 self.assertIsNone(cl.GetRemoteUrl())
2764
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002765 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002766 self.mockGit.config['remote.origin.url'] = (
2767 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002768 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002769 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2770
2771 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002772 mock.patch('logging.error',
2773 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002774
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002775 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002776 (('logging.error',
2777 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2778 'but it doesn\'t exist.', {
2779 'remote': 'origin',
2780 'branch': 'master',
2781 'url': ''}
2782 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002783 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002784 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002785 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002786
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002787
Edward Lemur9aa1a962020-02-25 00:58:38 +00002788class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002789 def setUp(self):
2790 super(ChangelistTest, self).setUp()
2791 mock.patch('gclient_utils.FileRead').start()
2792 mock.patch('gclient_utils.FileWrite').start()
2793 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2794 mock.patch(
2795 'git_cl.Changelist.GetCodereviewServer',
2796 return_value='https://chromium-review.googlesource.com').start()
2797 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2798 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2799 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2800 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2801 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2802 mock.patch('git_cl.time_time').start()
2803 mock.patch('metrics.collector').start()
2804 mock.patch('subprocess2.Popen').start()
2805 self.addCleanup(mock.patch.stopall)
2806 self.temp_count = 0
2807
Edward Lemur227d5102020-02-25 23:45:35 +00002808 def testRunHook(self):
2809 expected_results = {
2810 'more_cc': ['more@example.com', 'cc@example.com'],
2811 'should_continue': True,
2812 }
2813 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2814 git_cl.time_time.side_effect = [100, 200]
2815 mockProcess = mock.Mock()
2816 mockProcess.wait.return_value = 0
2817 subprocess2.Popen.return_value = mockProcess
2818
2819 cl = git_cl.Changelist()
2820 results = cl.RunHook(
2821 committing=True,
2822 may_prompt=True,
2823 verbose=2,
2824 parallel=True,
2825 upstream='upstream',
2826 description='description',
2827 all_files=True)
2828
2829 self.assertEqual(expected_results, results)
2830 subprocess2.Popen.assert_called_once_with([
2831 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002832 '--root', 'root',
2833 '--upstream', 'upstream',
2834 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002835 '--author', 'author',
2836 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002837 '--issue', '123456',
2838 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002839 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002840 '--may_prompt',
2841 '--parallel',
2842 '--all_files',
2843 '--json_output', '/tmp/fake-temp2',
2844 '--description_file', '/tmp/fake-temp1',
2845 ])
2846 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002847 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002848 metrics.collector.add_repeated('sub_commands', {
2849 'command': 'presubmit',
2850 'execution_time': 100,
2851 'exit_code': 0,
2852 })
2853
Edward Lemur99df04e2020-03-05 19:39:43 +00002854 def testRunHook_FewerOptions(self):
2855 expected_results = {
2856 'more_cc': ['more@example.com', 'cc@example.com'],
2857 'should_continue': True,
2858 }
2859 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2860 git_cl.time_time.side_effect = [100, 200]
2861 mockProcess = mock.Mock()
2862 mockProcess.wait.return_value = 0
2863 subprocess2.Popen.return_value = mockProcess
2864
2865 git_cl.Changelist.GetAuthor.return_value = None
2866 git_cl.Changelist.GetIssue.return_value = None
2867 git_cl.Changelist.GetPatchset.return_value = None
2868 git_cl.Changelist.GetCodereviewServer.return_value = None
2869
2870 cl = git_cl.Changelist()
2871 results = cl.RunHook(
2872 committing=False,
2873 may_prompt=False,
2874 verbose=0,
2875 parallel=False,
2876 upstream='upstream',
2877 description='description',
2878 all_files=False)
2879
2880 self.assertEqual(expected_results, results)
2881 subprocess2.Popen.assert_called_once_with([
2882 'vpython', 'PRESUBMIT_SUPPORT',
2883 '--root', 'root',
2884 '--upstream', 'upstream',
2885 '--upload',
2886 '--json_output', '/tmp/fake-temp2',
2887 '--description_file', '/tmp/fake-temp1',
2888 ])
2889 gclient_utils.FileWrite.assert_called_once_with(
2890 '/tmp/fake-temp1', 'description')
2891 metrics.collector.add_repeated('sub_commands', {
2892 'command': 'presubmit',
2893 'execution_time': 100,
2894 'exit_code': 0,
2895 })
2896
Edward Lemur227d5102020-02-25 23:45:35 +00002897 @mock.patch('sys.exit', side_effect=SystemExitMock)
2898 def testRunHook_Failure(self, _mock):
2899 git_cl.time_time.side_effect = [100, 200]
2900 mockProcess = mock.Mock()
2901 mockProcess.wait.return_value = 2
2902 subprocess2.Popen.return_value = mockProcess
2903
2904 cl = git_cl.Changelist()
2905 with self.assertRaises(SystemExitMock):
2906 cl.RunHook(
2907 committing=True,
2908 may_prompt=True,
2909 verbose=2,
2910 parallel=True,
2911 upstream='upstream',
2912 description='description',
2913 all_files=True)
2914
2915 sys.exit.assert_called_once_with(2)
2916
Edward Lemur75526302020-02-27 22:31:05 +00002917 def testRunPostUploadHook(self):
2918 cl = git_cl.Changelist()
2919 cl.RunPostUploadHook(2, 'upstream', 'description')
2920
2921 subprocess2.Popen.assert_called_once_with([
2922 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002923 '--root', 'root',
2924 '--upstream', 'upstream',
2925 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002926 '--author', 'author',
2927 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002928 '--issue', '123456',
2929 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002930 '--post_upload',
2931 '--description_file', '/tmp/fake-temp1',
2932 ])
2933 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002934 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002935
Edward Lemur9aa1a962020-02-25 00:58:38 +00002936
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002937class CMDTestCaseBase(unittest.TestCase):
2938 _STATUSES = [
2939 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2940 'INFRA_FAILURE', 'CANCELED',
2941 ]
2942 _CHANGE_DETAIL = {
2943 'project': 'depot_tools',
2944 'status': 'OPEN',
2945 'owner': {'email': 'owner@e.mail'},
2946 'current_revision': 'beeeeeef',
2947 'revisions': {
2948 'deadbeaf': {'_number': 6},
2949 'beeeeeef': {
2950 '_number': 7,
2951 'fetch': {'http': {
2952 'url': 'https://chromium.googlesource.com/depot_tools',
2953 'ref': 'refs/changes/56/123456/7'
2954 }},
2955 },
2956 },
2957 }
2958 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002959 'builds': [{
2960 'id': str(100 + idx),
2961 'builder': {
2962 'project': 'chromium',
2963 'bucket': 'try',
2964 'builder': 'bot_' + status.lower(),
2965 },
2966 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2967 'tags': [],
2968 'status': status,
2969 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002970 }
2971
Edward Lemur4c707a22019-09-24 21:13:43 +00002972 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002973 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002974 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002975 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2976 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002977 mock.patch(
2978 'git_cl.Changelist.GetCodereviewServer',
2979 return_value='https://chromium-review.googlesource.com').start()
2980 mock.patch(
2981 'git_cl.Changelist._GetGerritHost',
2982 return_value='chromium-review.googlesource.com').start()
2983 mock.patch(
2984 'git_cl.Changelist.GetMostRecentPatchset',
2985 return_value=7).start()
2986 mock.patch(
2987 'git_cl.Changelist.GetRemoteUrl',
2988 return_value='https://chromium.googlesource.com/depot_tools').start()
2989 mock.patch(
2990 'auth.Authenticator',
2991 return_value=AuthenticatorMock()).start()
2992 mock.patch(
2993 'gerrit_util.GetChangeDetail',
2994 return_value=self._CHANGE_DETAIL).start()
2995 mock.patch(
2996 'git_cl._call_buildbucket',
2997 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002998 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00002999 self.addCleanup(mock.patch.stopall)
3000
Edward Lemur4c707a22019-09-24 21:13:43 +00003001
Edward Lemur9468eba2020-02-27 19:07:22 +00003002class CMDPresubmitTestCase(CMDTestCaseBase):
3003 def setUp(self):
3004 super(CMDPresubmitTestCase, self).setUp()
3005 mock.patch(
3006 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3007 return_value='upstream').start()
3008 mock.patch(
3009 'git_cl.Changelist.FetchDescription',
3010 return_value='fetch description').start()
3011 mock.patch(
Edward Lemura12175c2020-03-09 16:58:26 +00003012 'git_cl._create_description_from_log',
Edward Lemur9468eba2020-02-27 19:07:22 +00003013 return_value='get description').start()
3014 mock.patch('git_cl.Changelist.RunHook').start()
3015
3016 def testDefaultCase(self):
3017 self.assertEqual(0, git_cl.main(['presubmit']))
3018 git_cl.Changelist.RunHook.assert_called_once_with(
3019 committing=True,
3020 may_prompt=False,
3021 verbose=0,
3022 parallel=None,
3023 upstream='upstream',
3024 description='fetch description',
3025 all_files=None)
3026
3027 def testNoIssue(self):
3028 git_cl.Changelist.GetIssue.return_value = None
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='get description',
3037 all_files=None)
3038
3039 def testCustomBranch(self):
3040 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3041 git_cl.Changelist.RunHook.assert_called_once_with(
3042 committing=True,
3043 may_prompt=False,
3044 verbose=0,
3045 parallel=None,
3046 upstream='custom_branch',
3047 description='fetch description',
3048 all_files=None)
3049
3050 def testOptions(self):
3051 self.assertEqual(
3052 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
3053 git_cl.Changelist.RunHook.assert_called_once_with(
3054 committing=False,
3055 may_prompt=False,
3056 verbose=2,
3057 parallel=True,
3058 upstream='upstream',
3059 description='fetch description',
3060 all_files=True)
3061
3062
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003063class CMDTryResultsTestCase(CMDTestCaseBase):
3064 _DEFAULT_REQUEST = {
3065 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003066 "gerritChanges": [{
3067 "project": "depot_tools",
3068 "host": "chromium-review.googlesource.com",
3069 "patchset": 7,
3070 "change": 123456,
3071 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003072 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003073 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3074 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003075 }
3076
3077 def testNoJobs(self):
3078 git_cl._call_buildbucket.return_value = {}
3079
3080 self.assertEqual(0, git_cl.main(['try-results']))
3081 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3082 git_cl._call_buildbucket.assert_called_once_with(
3083 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3084 self._DEFAULT_REQUEST)
3085
3086 def testPrintToStdout(self):
3087 self.assertEqual(0, git_cl.main(['try-results']))
3088 self.assertEqual([
3089 'Successes:',
3090 ' bot_success https://ci.chromium.org/b/103',
3091 'Infra Failures:',
3092 ' bot_infra_failure https://ci.chromium.org/b/105',
3093 'Failures:',
3094 ' bot_failure https://ci.chromium.org/b/104',
3095 'Canceled:',
3096 ' bot_canceled ',
3097 'Started:',
3098 ' bot_started https://ci.chromium.org/b/102',
3099 'Scheduled:',
3100 ' bot_scheduled id=101',
3101 'Other:',
3102 ' bot_status_unspecified id=100',
3103 'Total: 7 tryjobs',
3104 ], sys.stdout.getvalue().splitlines())
3105 git_cl._call_buildbucket.assert_called_once_with(
3106 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3107 self._DEFAULT_REQUEST)
3108
3109 def testPrintToStdoutWithMasters(self):
3110 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3111 self.assertEqual([
3112 'Successes:',
3113 ' try bot_success https://ci.chromium.org/b/103',
3114 'Infra Failures:',
3115 ' try bot_infra_failure https://ci.chromium.org/b/105',
3116 'Failures:',
3117 ' try bot_failure https://ci.chromium.org/b/104',
3118 'Canceled:',
3119 ' try bot_canceled ',
3120 'Started:',
3121 ' try bot_started https://ci.chromium.org/b/102',
3122 'Scheduled:',
3123 ' try bot_scheduled id=101',
3124 'Other:',
3125 ' try bot_status_unspecified id=100',
3126 'Total: 7 tryjobs',
3127 ], sys.stdout.getvalue().splitlines())
3128 git_cl._call_buildbucket.assert_called_once_with(
3129 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3130 self._DEFAULT_REQUEST)
3131
3132 @mock.patch('git_cl.write_json')
3133 def testWriteToJson(self, mockJsonDump):
3134 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3135 git_cl._call_buildbucket.assert_called_once_with(
3136 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3137 self._DEFAULT_REQUEST)
3138 mockJsonDump.assert_called_once_with(
3139 'file.json', self._DEFAULT_RESPONSE['builds'])
3140
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003141 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003142 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3143 self.assertEqual(
3144 [
3145 ('chromium', 'try', 'bot_failure'),
3146 ('chromium', 'try', 'bot_infra_failure'),
3147 ],
3148 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003149
3150 def test_filter_failed_for_retry_many_builds(self):
3151
3152 def _build(name, created_sec, status, experimental=False):
3153 assert 0 <= created_sec < 100, created_sec
3154 b = {
3155 'id': 112112,
3156 'builder': {
3157 'project': 'chromium',
3158 'bucket': 'try',
3159 'builder': name,
3160 },
3161 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3162 'status': status,
3163 'tags': [],
3164 }
3165 if experimental:
3166 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3167 return b
3168
3169 builds = [
3170 _build('flaky-last-green', 1, 'FAILURE'),
3171 _build('flaky-last-green', 2, 'SUCCESS'),
3172 _build('flaky', 1, 'SUCCESS'),
3173 _build('flaky', 2, 'FAILURE'),
3174 _build('running', 1, 'FAILED'),
3175 _build('running', 2, 'SCHEDULED'),
3176 _build('yep-still-running', 1, 'STARTED'),
3177 _build('yep-still-running', 2, 'FAILURE'),
3178 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3179 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3180
3181 # Simulate experimental in CQ builder, which developer decided
3182 # to retry manually which resulted in 2nd build non-experimental.
3183 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3184 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3185 ]
3186 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003187 self.assertEqual(
3188 [
3189 ('chromium', 'try', 'flaky'),
3190 ('chromium', 'try', 'sometimes-experimental'),
3191 ],
3192 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003193
3194
3195class CMDTryTestCase(CMDTestCaseBase):
3196
3197 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003198 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003199 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003200 self.assertEqual(0, git_cl.main(['try']))
3201 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3202 self.assertEqual(
3203 sys.stdout.getvalue(),
3204 'Scheduling CQ dry run on: '
3205 'https://chromium-review.googlesource.com/123456\n')
3206
Edward Lemur4c707a22019-09-24 21:13:43 +00003207 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003208 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003209 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003210
3211 self.assertEqual(0, git_cl.main([
3212 'try', '-B', 'luci.chromium.try', '-b', 'win',
3213 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3214 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003215 'Scheduling jobs on:\n'
3216 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003217 git_cl.sys.stdout.getvalue())
3218
3219 expected_request = {
3220 "requests": [{
3221 "scheduleBuild": {
3222 "requestId": "uuid4",
3223 "builder": {
3224 "project": "chromium",
3225 "builder": "win",
3226 "bucket": "try",
3227 },
3228 "gerritChanges": [{
3229 "project": "depot_tools",
3230 "host": "chromium-review.googlesource.com",
3231 "patchset": 7,
3232 "change": 123456,
3233 }],
3234 "properties": {
3235 "category": "git_cl_try",
3236 "json": [{"a": 1}, None],
3237 "key": "val",
3238 },
3239 "tags": [
3240 {"value": "win", "key": "builder"},
3241 {"value": "git_cl_try", "key": "user_agent"},
3242 ],
3243 },
3244 }],
3245 }
3246 mockCallBuildbucket.assert_called_with(
3247 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3248
Anthony Polito1a5fe232020-01-24 23:17:52 +00003249 @mock.patch('git_cl._call_buildbucket')
3250 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3251 mockCallBuildbucket.return_value = {}
3252
3253 self.assertEqual(0, git_cl.main([
3254 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3255 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3256 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3257 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003258 'Scheduling jobs on:\n'
3259 ' chromium/try: linux\n'
3260 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003261 git_cl.sys.stdout.getvalue())
3262
3263 expected_request = {
3264 "requests": [{
3265 "scheduleBuild": {
3266 "requestId": "uuid4",
3267 "builder": {
3268 "project": "chromium",
3269 "builder": "linux",
3270 "bucket": "try",
3271 },
3272 "gerritChanges": [{
3273 "project": "depot_tools",
3274 "host": "chromium-review.googlesource.com",
3275 "patchset": 7,
3276 "change": 123456,
3277 }],
3278 "properties": {
3279 "category": "git_cl_try",
3280 "json": [{"a": 1}, None],
3281 "key": "val",
3282 },
3283 "tags": [
3284 {"value": "linux", "key": "builder"},
3285 {"value": "git_cl_try", "key": "user_agent"},
3286 ],
3287 "gitilesCommit": {
3288 "host": "chromium-review.googlesource.com",
3289 "project": "depot_tools",
3290 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3291 }
3292 },
3293 },
3294 {
3295 "scheduleBuild": {
3296 "requestId": "uuid4",
3297 "builder": {
3298 "project": "chromium",
3299 "builder": "win",
3300 "bucket": "try",
3301 },
3302 "gerritChanges": [{
3303 "project": "depot_tools",
3304 "host": "chromium-review.googlesource.com",
3305 "patchset": 7,
3306 "change": 123456,
3307 }],
3308 "properties": {
3309 "category": "git_cl_try",
3310 "json": [{"a": 1}, None],
3311 "key": "val",
3312 },
3313 "tags": [
3314 {"value": "win", "key": "builder"},
3315 {"value": "git_cl_try", "key": "user_agent"},
3316 ],
3317 "gitilesCommit": {
3318 "host": "chromium-review.googlesource.com",
3319 "project": "depot_tools",
3320 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3321 }
3322 },
3323 }],
3324 }
3325 mockCallBuildbucket.assert_called_with(
3326 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3327
Edward Lemur45768512020-03-02 19:03:14 +00003328 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003329 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003330 with self.assertRaises(SystemExit):
3331 git_cl.main([
3332 'try', '-B', 'not-a-bucket', '-b', 'win',
3333 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003334 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003335 'Invalid bucket: not-a-bucket.',
3336 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003337
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003338 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003339 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003340 def testScheduleOnBuildbucketRetryFailed(
3341 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003342 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003343 7: [],
3344 6: [{
3345 'id': 112112,
3346 'builder': {
3347 'project': 'chromium',
3348 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003349 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003350 'createTime': '2019-10-09T08:00:01.854286Z',
3351 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003352 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003353 mockCallBuildbucket.return_value = {}
3354
3355 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3356 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003357 'Scheduling jobs on:\n'
3358 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003359 git_cl.sys.stdout.getvalue())
3360
3361 expected_request = {
3362 "requests": [{
3363 "scheduleBuild": {
3364 "requestId": "uuid4",
3365 "builder": {
3366 "project": "chromium",
3367 "bucket": "try",
3368 "builder": "linux",
3369 },
3370 "gerritChanges": [{
3371 "project": "depot_tools",
3372 "host": "chromium-review.googlesource.com",
3373 "patchset": 7,
3374 "change": 123456,
3375 }],
3376 "properties": {
3377 "category": "git_cl_try",
3378 },
3379 "tags": [
3380 {"value": "linux", "key": "builder"},
3381 {"value": "git_cl_try", "key": "user_agent"},
3382 {"value": "1", "key": "retry_failed"},
3383 ],
3384 },
3385 }],
3386 }
3387 mockCallBuildbucket.assert_called_with(
3388 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3389
Edward Lemur4c707a22019-09-24 21:13:43 +00003390 def test_parse_bucket(self):
3391 test_cases = [
3392 {
3393 'bucket': 'chromium/try',
3394 'result': ('chromium', 'try'),
3395 },
3396 {
3397 'bucket': 'luci.chromium.try',
3398 'result': ('chromium', 'try'),
3399 'has_warning': True,
3400 },
3401 {
3402 'bucket': 'skia.primary',
3403 'result': ('skia', 'skia.primary'),
3404 'has_warning': True,
3405 },
3406 {
3407 'bucket': 'not-a-bucket',
3408 'result': (None, None),
3409 },
3410 ]
3411
3412 for test_case in test_cases:
3413 git_cl.sys.stdout.truncate(0)
3414 self.assertEqual(
3415 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3416 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003417 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3418 test_case['result'])
3419 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003420
3421
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003422class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003423
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003424 def setUp(self):
3425 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003426 mock.patch('git_cl._fetch_tryjobs').start()
3427 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003428 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003429 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003430 self.addCleanup(mock.patch.stopall)
3431
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003432 def testWarmUpChangeDetailCache(self):
3433 self.assertEqual(0, git_cl.main(['upload']))
3434 gerrit_util.GetChangeDetail.assert_called_once_with(
3435 'chromium-review.googlesource.com', 'depot_tools~123456',
3436 frozenset([
3437 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3438 'CURRENT_COMMIT']))
3439
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003440 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003441 # This test mocks out the actual upload part, and just asserts that after
3442 # upload, if --retry-failed is added, then the tool will fetch try jobs
3443 # from the previous patchset and trigger the right builders on the latest
3444 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003445 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003446 # Latest patchset: No builds.
3447 [],
3448 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003449 [{
3450 'id': str(100 + idx),
3451 'builder': {
3452 'project': 'chromium',
3453 'bucket': 'try',
3454 'builder': 'bot_' + status.lower(),
3455 },
3456 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3457 'tags': [],
3458 'status': status,
3459 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003460 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003461
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003462 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003463 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003464 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3465 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003466 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003467 expected_buckets = [
3468 ('chromium', 'try', 'bot_failure'),
3469 ('chromium', 'try', 'bot_infra_failure'),
3470 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003471 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3472 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003473
Brian Sheedy59b06a82019-10-14 17:03:29 +00003474
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003475class MakeRequestsHelperTestCase(unittest.TestCase):
3476
3477 def exampleGerritChange(self):
3478 return {
3479 'host': 'chromium-review.googlesource.com',
3480 'project': 'depot_tools',
3481 'change': 1,
3482 'patchset': 2,
3483 }
3484
3485 def testMakeRequestsHelperNoOptions(self):
3486 # Basic test for the helper function _make_tryjob_schedule_requests;
3487 # it shouldn't throw AttributeError even when options doesn't have any
3488 # of the expected values; it will use default option values.
3489 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3490 jobs = [('chromium', 'try', 'my-builder')]
3491 options = optparse.Values()
3492 requests = git_cl._make_tryjob_schedule_requests(
3493 changelist, jobs, options, patchset=None)
3494
3495 # requestId is non-deterministic. Just assert that it's there and has
3496 # a particular length.
3497 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3498 self.assertEqual(requests, [{
3499 'scheduleBuild': {
3500 'builder': {
3501 'bucket': 'try',
3502 'builder': 'my-builder',
3503 'project': 'chromium'
3504 },
3505 'gerritChanges': [self.exampleGerritChange()],
3506 'properties': {
3507 'category': 'git_cl_try'
3508 },
3509 'tags': [{
3510 'key': 'builder',
3511 'value': 'my-builder'
3512 }, {
3513 'key': 'user_agent',
3514 'value': 'git_cl_try'
3515 }]
3516 }
3517 }])
3518
3519 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3520 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3521 jobs = [('chromium', 'try', 'presubmit')]
3522 options = optparse.Values()
3523 requests = git_cl._make_tryjob_schedule_requests(
3524 changelist, jobs, options, patchset=None)
3525 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3526 'category': 'git_cl_try',
3527 'dry_run': 'true'
3528 })
3529
3530 def testMakeRequestsHelperRevisionSet(self):
3531 # Gitiles commit is specified when revision is in options.
3532 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3533 jobs = [('chromium', 'try', 'my-builder')]
3534 options = optparse.Values({'revision': 'ba5eba11'})
3535 requests = git_cl._make_tryjob_schedule_requests(
3536 changelist, jobs, options, patchset=None)
3537 self.assertEqual(
3538 requests[0]['scheduleBuild']['gitilesCommit'], {
3539 'host': 'chromium-review.googlesource.com',
3540 'id': 'ba5eba11',
3541 'project': 'depot_tools'
3542 })
3543
3544 def testMakeRequestsHelperRetryFailedSet(self):
3545 # An extra tag is added when retry_failed is in options.
3546 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3547 jobs = [('chromium', 'try', 'my-builder')]
3548 options = optparse.Values({'retry_failed': 'true'})
3549 requests = git_cl._make_tryjob_schedule_requests(
3550 changelist, jobs, options, patchset=None)
3551 self.assertEqual(
3552 requests[0]['scheduleBuild']['tags'], [
3553 {
3554 'key': 'builder',
3555 'value': 'my-builder'
3556 },
3557 {
3558 'key': 'user_agent',
3559 'value': 'git_cl_try'
3560 },
3561 {
3562 'key': 'retry_failed',
3563 'value': '1'
3564 }
3565 ])
3566
3567 def testMakeRequestsHelperCategorySet(self):
3568 # The category property can be overriden with options.
3569 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3570 jobs = [('chromium', 'try', 'my-builder')]
3571 options = optparse.Values({'category': 'my-special-category'})
3572 requests = git_cl._make_tryjob_schedule_requests(
3573 changelist, jobs, options, patchset=None)
3574 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3575 {'category': 'my-special-category'})
3576
3577
Edward Lemurda4b6c62020-02-13 00:28:40 +00003578class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003579
3580 def setUp(self):
3581 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003582 mock.patch('git_cl.RunCommand').start()
3583 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3584 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3585 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003586 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003587 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003588
3589 def tearDown(self):
3590 shutil.rmtree(self._top_dir)
3591 super(CMDFormatTestCase, self).tearDown()
3592
Jamie Madill5e96ad12020-01-13 16:08:35 +00003593 def _make_temp_file(self, fname, contents):
3594 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3595 tf.write('\n'.join(contents))
3596
Brian Sheedy59b06a82019-10-14 17:03:29 +00003597 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003598 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003599
Brian Sheedyb4307d52019-12-02 19:18:17 +00003600 def _check_yapf_filtering(self, files, expected):
3601 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3602 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003603
Edward Lemur1a83da12020-03-04 21:18:36 +00003604 def _run_command_mock(self, return_value):
3605 def f(*args, **kwargs):
3606 if 'stdin' in kwargs:
3607 self.assertIsInstance(kwargs['stdin'], bytes)
3608 return return_value
3609 return f
3610
Jamie Madill5e96ad12020-01-13 16:08:35 +00003611 def testClangFormatDiffFull(self):
3612 self._make_temp_file('test.cc', ['// test'])
3613 git_cl.settings.GetFormatFullByDefault.return_value = False
3614 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3615 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3616
3617 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003618 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003619 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3620 self._top_dir, 'HEAD')
3621 self.assertEqual(2, return_value)
3622
3623 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003624 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003625 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3626 self._top_dir, 'HEAD')
3627 self.assertEqual(0, return_value)
3628
3629 def testClangFormatDiff(self):
3630 git_cl.settings.GetFormatFullByDefault.return_value = False
3631 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3632
3633 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003634 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3635 return_value = git_cl._RunClangFormatDiff(
3636 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003637 self.assertEqual(2, return_value)
3638
3639 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003640 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003641 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3642 'HEAD')
3643 self.assertEqual(0, return_value)
3644
Brian Sheedyb4307d52019-12-02 19:18:17 +00003645 def testYapfignoreExplicit(self):
3646 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3647 files = [
3648 'bar.py',
3649 'foo/bar.py',
3650 'foo/baz.py',
3651 'foo/bar/baz.py',
3652 'foo/bar/foobar.py',
3653 ]
3654 expected = [
3655 'bar.py',
3656 'foo/baz.py',
3657 'foo/bar/foobar.py',
3658 ]
3659 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003660
Brian Sheedyb4307d52019-12-02 19:18:17 +00003661 def testYapfignoreSingleWildcards(self):
3662 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3663 files = [
3664 'bar.py', # Matched by *bar.py.
3665 'bar.txt',
3666 'foobar.py', # Matched by *bar.py, foo*.
3667 'foobar.txt', # Matched by foo*.
3668 'bazbar.py', # Matched by *bar.py, baz*.py.
3669 'bazbar.txt',
3670 'foo/baz.txt', # Matched by foo*.
3671 'bar/bar.py', # Matched by *bar.py.
3672 'baz/foo.py', # Matched by baz*.py, foo*.
3673 'baz/foo.txt',
3674 ]
3675 expected = [
3676 'bar.txt',
3677 'bazbar.txt',
3678 'baz/foo.txt',
3679 ]
3680 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003681
Brian Sheedyb4307d52019-12-02 19:18:17 +00003682 def testYapfignoreMultiplewildcards(self):
3683 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3684 files = [
3685 'bar.py', # Matched by *bar*.
3686 'bar.txt', # Matched by *bar*.
3687 'abar.py', # Matched by *bar*.
3688 'foobaz.txt', # Matched by *foo*baz.txt.
3689 'foobaz.py',
3690 'afoobaz.txt', # Matched by *foo*baz.txt.
3691 ]
3692 expected = [
3693 'foobaz.py',
3694 ]
3695 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003696
3697 def testYapfignoreComments(self):
3698 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003699 files = [
3700 'test.py',
3701 'test2.py',
3702 ]
3703 expected = [
3704 'test2.py',
3705 ]
3706 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003707
3708 def testYapfignoreBlankLines(self):
3709 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003710 files = [
3711 'test.py',
3712 'test2.py',
3713 'test3.py',
3714 ]
3715 expected = [
3716 'test3.py',
3717 ]
3718 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003719
3720 def testYapfignoreWhitespace(self):
3721 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003722 files = [
3723 'test.py',
3724 'test2.py',
3725 ]
3726 expected = [
3727 'test2.py',
3728 ]
3729 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003730
Brian Sheedyb4307d52019-12-02 19:18:17 +00003731 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003732 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003733 self._check_yapf_filtering([], [])
3734
3735 def testYapfignoreMissingYapfignore(self):
3736 files = [
3737 'test.py',
3738 ]
3739 expected = [
3740 'test.py',
3741 ]
3742 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003743
3744
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003745if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003746 logging.basicConfig(
3747 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003748 unittest.main()