blob: ed805b0a7f52a19171f0f39d893593962fa6aa22 [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 # Determined in `_gerrit_base_calls`.
856 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
857
858 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000859
Edward Lemur26964072020-02-19 19:18:51 +0000860 if squash_mode in ('override_squash', 'override_nosquash'):
861 self.mockGit.config['gerrit.override-squash-uploads'] = (
862 'true' if squash_mode == 'override_squash' else 'false')
tandriia60502f2016-06-20 02:01:53 -0700863
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000864 # If issue is given, then description is fetched from Gerrit instead.
865 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000866 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200867 ((['git', 'log', '--pretty=format:%s\n\n%b',
868 ((custom_cl_base + '..') if custom_cl_base else
869 'fake_ancestor_sha..HEAD')],),
870 description),
871 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800872 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000873 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800874 else:
875 if not title:
876 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200877 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
878 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800879 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000880 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000881 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000882 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200883 (('DownloadGerritHook', False), ''),
884 # Amending of commit message to get the Change-Id.
885 ((['git', 'log', '--pretty=format:%s\n\n%b',
886 determined_ancestor_revision + '..HEAD'],),
887 description),
888 ((['git', 'commit', '--amend', '-m', description],), ''),
889 ((['git', 'log', '--pretty=format:%s\n\n%b',
890 determined_ancestor_revision + '..HEAD'],),
891 post_amend_description)
892 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000893 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000894 if force or not issue:
Anthony Polito8b955342019-09-24 19:01:36 +0000895 if not force:
896 calls += [
Anthony Polito8b955342019-09-24 19:01:36 +0000897 ((['RunEditor'],), description),
898 ]
Josipe827b0f2020-01-30 00:07:20 +0000899 # user wants to edit description
900 if edit_description:
901 calls += [
Josipe827b0f2020-01-30 00:07:20 +0000902 ((['RunEditor'],), edit_description),
903 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000904 ref_to_push = 'abcdef0123456789'
905 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200906 ]
907
908 if custom_cl_base is None:
909 calls += [
Edward Lemurda4b6c62020-02-13 00:28:40 +0000910 (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000911 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200912 ]
913 parent = 'origin/master'
914 else:
915 calls += [
916 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
917 'refs/remotes/origin/master'],),
918 callError(1)), # Means not ancenstor.
919 (('ask_for_data',
920 'Do you take responsibility for cleaning up potential mess '
921 'resulting from proceeding with upload? Press Enter to upload, '
922 'or Ctrl+C to abort'), ''),
923 ]
924 parent = custom_cl_base
925
926 calls += [
927 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
928 '0123456789abcdef'),
Edward Lemur1773f372020-02-22 00:27:14 +0000929 ((['FileWrite', '/tmp/fake-temp1', description],), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200930 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Edward Lemur1773f372020-02-22 00:27:14 +0000931 '-F', '/tmp/fake-temp1'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200932 ref_to_push),
933 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000934 else:
935 ref_to_push = 'HEAD'
936
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000937 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000938 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200939 ((['git', 'rev-list',
940 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
941 ref_to_push],),
942 '1hashPerLine\n'),
943 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000944
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000945 metrics_arguments = []
946
Aaron Gableafd52772017-06-27 16:40:10 -0700947 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -0700948 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000949 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -0700950 else:
Jamie Madill276da0b2018-04-27 14:41:20 -0400951 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -0700952 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000953 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -0700954 else:
955 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000956 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -0800957
Aaron Gable70f4e242017-06-26 10:45:59 -0700958 if title:
Aaron Gableafd52772017-06-27 16:40:10 -0700959 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000960 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000961
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000962 if short_hostname == 'chromium':
963 # All reviwers and ccs get into ref_suffix.
964 for r in sorted(reviewers):
965 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000966 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +0000967 if issue is None:
Edward Lemur227d5102020-02-25 23:45:35 +0000968 cc += ['test-more-cc@chromium.org', 'joe@example.com']
Edward Lemur4508b422019-10-03 21:56:35 +0000969 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000970 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000971 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000972 reviewers, cc = [], []
973 else:
974 # TODO(crbug/877717): remove this case.
975 calls += [
976 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
977 sorted(reviewers) + ['joe@example.com',
Edward Lemur227d5102020-02-25 23:45:35 +0000978 'test-more-cc@chromium.org'] + cc),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000979 {
980 e: {'email': e}
981 for e in (reviewers + ['joe@example.com'] + cc)
982 })
983 ]
984 for r in sorted(reviewers):
985 if r != 'bad-account-or-email':
986 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000987 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000988 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +0000989 if issue is None:
990 cc += ['joe@example.com']
991 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000992 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000993 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000994 if c in cc:
995 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +0000996
Edward Lemur687ca902018-12-05 02:30:30 +0000997 for k, v in sorted((labels or {}).items()):
998 ref_suffix += ',l=%s+%d' % (k, v)
999 metrics_arguments.append('l=%s+%d' % (k, v))
1000
1001 if tbr:
1002 calls += [
1003 (('GetCodeReviewTbrScore',
1004 '%s-review.googlesource.com' % short_hostname,
1005 'my/repo'),
1006 2,),
1007 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001008
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001009 calls += [
1010 (('time.time',), 1000,),
1011 ((['git', 'push',
1012 'https://%s.googlesource.com/my/repo' % short_hostname,
1013 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1014 (('remote:\n'
1015 'remote: Processing changes: (\)\n'
1016 'remote: Processing changes: (|)\n'
1017 'remote: Processing changes: (/)\n'
1018 'remote: Processing changes: (-)\n'
1019 'remote: Processing changes: new: 1 (/)\n'
1020 'remote: Processing changes: new: 1, done\n'
1021 'remote:\n'
1022 'remote: New Changes:\n'
1023 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1024 ' XXX\n'
1025 'remote:\n'
1026 'To https://%s.googlesource.com/my/repo\n'
1027 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1028 ) % (short_hostname, short_hostname)),),
1029 (('time.time',), 2000,),
1030 (('add_repeated',
1031 'sub_commands',
1032 {
1033 'execution_time': 1000,
1034 'command': 'git push',
1035 'exit_code': 0,
1036 'arguments': sorted(metrics_arguments),
1037 }),
1038 None,),
1039 ]
1040
Edward Lemur1b52d872019-05-09 21:12:12 +00001041 final_description = final_description or post_amend_description.strip()
1042 original_title = original_title or title or '<untitled>'
1043 # Trace-related calls
1044 calls += [
1045 # Write a description with context for the current trace.
1046 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001047 'Thu Mar 16 20:00:41 2017\n'
1048 '%(short_hostname)s-review.googlesource.com\n'
1049 '%(change_id)s\n'
1050 '%(title)s\n'
1051 '%(description)s\n'
1052 '1000\n'
1053 '0\n'
1054 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001055 'short_hostname': short_hostname,
1056 'change_id': change_id,
1057 'description': final_description,
1058 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001059 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001060 }],),
1061 None,
1062 ),
1063 # Read traces and shorten git hashes.
1064 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1065 True,
1066 ),
1067 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1068 ('git-hash: 0123456789012345678901234567890123456789\n'
1069 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1070 ),
1071 ((['FileWrite', 'TEMP_DIR/trace-packet',
1072 'git-hash: 012345\n'
1073 'git-hash: abcdea\n'],),
1074 None,
1075 ),
1076 # Make zip file for the git traces.
1077 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1078 'TEMP_DIR'],),
1079 None,
1080 ),
1081 # Collect git config and gitcookies.
1082 ((['git', 'config', '-l'],),
1083 'git-config-output',
1084 ),
1085 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1086 None,
1087 ),
1088 ((['os.path.isfile', '~/.gitcookies'],),
1089 gitcookies_exists,
1090 ),
1091 ]
1092 if gitcookies_exists:
1093 calls += [
1094 ((['FileRead', '~/.gitcookies'],),
1095 'gitcookies 1/SECRET',
1096 ),
1097 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1098 None,
1099 ),
1100 ]
1101 calls += [
1102 # Make zip file for the git config and gitcookies.
1103 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1104 'TEMP_DIR'],),
1105 None,
1106 ),
1107 ]
1108
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001109 # TODO(crbug/877717): this should never be used.
1110 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001111 calls += [
1112 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001113 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001114 sorted(reviewers),
Edward Lemur227d5102020-02-25 23:45:35 +00001115 cc + ['test-more-cc@chromium.org'],
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001116 notify),
1117 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001118 ]
Edward Lemur26964072020-02-19 19:18:51 +00001119 calls += [
1120 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
1121 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +00001122 return calls
1123
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001124 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001125 self,
1126 upload_args,
1127 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001128 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001129 squash=True,
1130 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001131 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001132 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001133 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001134 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001135 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001136 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001137 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001138 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001139 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001140 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001141 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001142 labels=None,
1143 change_id=None,
1144 original_title=None,
1145 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001146 gitcookies_exists=True,
1147 force=False,
Josipe827b0f2020-01-30 00:07:20 +00001148 edit_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001149 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001150 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001151 if squash_mode is None:
1152 if '--no-squash' in upload_args:
1153 squash_mode = 'nosquash'
1154 elif '--squash' in upload_args:
1155 squash_mode = 'squash'
1156 else:
1157 squash_mode = 'default'
1158
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001159 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001160 cc = cc or []
Edward Lemurda4b6c62020-02-13 00:28:40 +00001161 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001162 CookiesAuthenticatorMockFactory(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001163 same_auth=('git-owner.example.com', '', 'pass'))).start()
1164 mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
1165 lambda _, offer_removal: None).start()
1166 mock.patch('git_cl.gclient_utils.RunEditor',
1167 lambda *_, **__: self._mocked_call(['RunEditor'])).start()
1168 mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
1169 'DownloadGerritHook', force)).start()
1170 mock.patch('git_cl.gclient_utils.FileRead',
1171 lambda path: self._mocked_call(['FileRead', path])).start()
1172 mock.patch('git_cl.gclient_utils.FileWrite',
Edward Lemur1b52d872019-05-09 21:12:12 +00001173 lambda path, contents: self._mocked_call(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001174 ['FileWrite', path, contents])).start()
1175 mock.patch('git_cl.datetime_now',
1176 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
1177 mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
1178 mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
1179 mock.patch('git_cl.TRACES_README_FORMAT',
Edward Lemur75391d42019-05-14 23:35:56 +00001180 '%(now)s\n'
1181 '%(gerrit_host)s\n'
1182 '%(change_id)s\n'
1183 '%(title)s\n'
1184 '%(description)s\n'
1185 '%(execution_time)s\n'
1186 '%(exit_code)s\n'
Edward Lemurda4b6c62020-02-13 00:28:40 +00001187 '%(trace_name)s').start()
1188 mock.patch('git_cl.shutil.make_archive',
1189 lambda *args: self._mocked_call(['make_archive'] +
1190 list(args))).start()
1191 mock.patch('os.path.isfile',
1192 lambda path: self._mocked_call(['os.path.isfile', path])).start()
Edward Lemurd55c5072020-02-20 01:09:07 +00001193 mock.patch('git_cl.Changelist.GitSanityChecks', return_value=True).start()
Edward Lemur9aa1a962020-02-25 00:58:38 +00001194 mock.patch(
1195 'git_cl.Changelist.GetLocalDescription', return_value='foo').start()
Edward Lemur1a83da12020-03-04 21:18:36 +00001196 mock.patch(
1197 'git_cl.ask_for_data',
1198 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
tandriia60502f2016-06-20 02:01:53 -07001199
Edward Lemur26964072020-02-19 19:18:51 +00001200 self.mockGit.config['gerrit.host'] = 'true'
Edward Lemur85153282020-02-14 22:06:29 +00001201 self.mockGit.config['branch.master.gerritissue'] = (
1202 str(issue) if issue else None)
1203 self.mockGit.config['remote.origin.url'] = (
1204 'https://%s.googlesource.com/my/repo' % short_hostname)
Edward Lemur9aa1a962020-02-25 00:58:38 +00001205 self.mockGit.config['user.email'] = 'me@example.com'
Edward Lemur85153282020-02-14 22:06:29 +00001206
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001207 self.calls = self._gerrit_base_calls(
1208 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001209 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001210 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001211 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001212 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001213 short_hostname=short_hostname,
1214 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001215 if fetched_status != 'ABANDONED':
Edward Lemurda4b6c62020-02-13 00:28:40 +00001216 mock.patch(
Edward Lemur1773f372020-02-22 00:27:14 +00001217 'gclient_utils.temporary_file', TemporaryFileMock()).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001218 mock.patch('os.remove', return_value=True).start()
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001219 self.calls += self._gerrit_upload_calls(
1220 description, reviewers, squash,
1221 squash_mode=squash_mode,
1222 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001223 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001224 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001225 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001226 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001227 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001228 labels=labels,
1229 change_id=change_id,
1230 original_title=original_title,
1231 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001232 gitcookies_exists=gitcookies_exists,
Josipe827b0f2020-01-30 00:07:20 +00001233 force=force,
1234 edit_description=edit_description)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001235 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001236 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001237 git_cl.main(['upload'] + upload_args)
Edward Lemur85153282020-02-14 22:06:29 +00001238 if squash:
Edward Lemur26964072020-02-19 19:18:51 +00001239 self.assertIssueAndPatchset(patchset=None)
Edward Lemur85153282020-02-14 22:06:29 +00001240 self.assertEqual(
1241 'abcdef0123456789',
Edward Lemur26964072020-02-19 19:18:51 +00001242 scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001243
Edward Lemur1b52d872019-05-09 21:12:12 +00001244 def test_gerrit_upload_traces_no_gitcookies(self):
1245 self._run_gerrit_upload_test(
1246 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001247 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001248 [],
1249 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001250 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001251 change_id='Ixxx',
1252 gitcookies_exists=False)
1253
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001254 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001255 self._run_gerrit_upload_test(
1256 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001257 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001258 [],
1259 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001260 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001261 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001262
1263 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001264 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001265 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001266 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001267 [],
tandriia60502f2016-06-20 02:01:53 -07001268 squash=False,
1269 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001270 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001271 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001272
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001273 def test_gerrit_no_reviewer(self):
1274 self._run_gerrit_upload_test(
1275 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001276 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001277 [],
1278 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001279 squash_mode='override_nosquash',
1280 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001281
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001282 def test_gerrit_no_reviewer_non_chromium_host(self):
1283 # TODO(crbug/877717): remove this test case.
1284 self._run_gerrit_upload_test(
1285 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001286 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001287 [],
1288 squash=False,
1289 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001290 short_hostname='other',
1291 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001292
Nick Carter8692b182017-11-06 16:30:38 -08001293 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001294 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001295 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001296 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001297 squash=False,
1298 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001299 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1300 change_id='I123456789',
1301 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001302
ukai@chromium.orge8077812012-02-03 03:41:46 +00001303 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001304 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001305 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001306 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001307 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001308 squash=False,
1309 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001310 notify=True,
1311 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001312 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001313 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001314
Anthony Polito8b955342019-09-24 19:01:36 +00001315 def test_gerrit_upload_force_sets_bug(self):
1316 self._run_gerrit_upload_test(
1317 ['-b', '10000', '-f'],
1318 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1319 [],
1320 force=True,
1321 expected_upstream_ref='origin/master',
1322 fetched_description='desc=\n\nChange-Id: Ixxx',
1323 original_title='Initial upload',
1324 change_id='Ixxx')
1325
1326 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1327 self._run_gerrit_upload_test(
1328 ['-b', '10000', '-f', '-m', 'Title'],
1329 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1330 [],
1331 force=True,
1332 issue='123456',
1333 expected_upstream_ref='origin/master',
1334 fetched_description='desc=\n\nChange-Id: Ixxxx',
1335 original_title='Title',
1336 title='Title',
1337 change_id='Izzzz')
1338
Dan Beamd8b04ca2019-10-10 21:23:26 +00001339 def test_gerrit_upload_force_sets_fixed(self):
1340 self._run_gerrit_upload_test(
1341 ['-x', '10000', '-f'],
1342 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1343 [],
1344 force=True,
1345 expected_upstream_ref='origin/master',
1346 fetched_description='desc=\n\nChange-Id: Ixxx',
1347 original_title='Initial upload',
1348 change_id='Ixxx')
1349
ukai@chromium.orge8077812012-02-03 03:41:46 +00001350 def test_gerrit_reviewer_multiple(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001351 mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
1352 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001353 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001354 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001355 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001356 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001357 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001358 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001359 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001360 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001361 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001362 labels={'Code-Review': 2},
1363 change_id='123456789',
1364 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001365
1366 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001367 self._run_gerrit_upload_test(
1368 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001369 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001370 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001371 expected_upstream_ref='origin/master',
1372 change_id='123456789',
1373 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001374
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001375 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001376 self._run_gerrit_upload_test(
1377 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001378 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001379 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001380 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001381 expected_upstream_ref='origin/master',
1382 change_id='123456789',
1383 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001384
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001385 def test_gerrit_upload_squash_first_with_labels(self):
1386 self._run_gerrit_upload_test(
1387 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001388 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001389 [],
1390 squash=True,
1391 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001392 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1393 change_id='123456789',
1394 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001395
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001396 def test_gerrit_upload_squash_first_against_rev(self):
1397 custom_cl_base = 'custom_cl_base_rev_or_branch'
1398 self._run_gerrit_upload_test(
1399 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001400 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001401 [],
1402 squash=True,
1403 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001404 custom_cl_base=custom_cl_base,
1405 change_id='123456789',
1406 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001407 self.assertIn(
1408 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1409 sys.stdout.getvalue())
1410
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001411 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001412 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001413 self._run_gerrit_upload_test(
1414 ['--squash'],
1415 description,
1416 [],
1417 squash=True,
1418 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001419 issue=123456,
1420 change_id='123456789',
1421 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001422
Edward Lemurd55c5072020-02-20 01:09:07 +00001423 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001424 def test_gerrit_upload_squash_reupload_to_abandoned(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001425 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001426 with self.assertRaises(SystemExitMock):
1427 self._run_gerrit_upload_test(
1428 ['--squash'],
1429 description,
1430 [],
1431 squash=True,
1432 expected_upstream_ref='origin/master',
1433 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001434 fetched_status='ABANDONED',
1435 change_id='123456789')
Edward Lemurd55c5072020-02-20 01:09:07 +00001436 self.assertEqual(
1437 'Change https://chromium-review.googlesource.com/123456 has been '
1438 'abandoned, new uploads are not allowed\n',
1439 sys.stderr.getvalue())
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001440
Edward Lemurda4b6c62020-02-13 00:28:40 +00001441 @mock.patch(
1442 'gerrit_util.GetAccountDetails',
1443 return_value={'email': 'yet-another@example.com'})
1444 def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
Edward Lemur0db01f02019-11-12 22:01:51 +00001445 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001446 self._run_gerrit_upload_test(
1447 ['--squash'],
1448 description,
1449 [],
1450 squash=True,
1451 expected_upstream_ref='origin/master',
1452 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001453 other_cl_owner='other@example.com',
1454 change_id='123456789',
1455 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001456 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001457 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001458 'authenticate to Gerrit as yet-another@example.com.\n'
1459 'Uploading may fail due to lack of permissions',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001460 sys.stdout.getvalue())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001461
Josipe827b0f2020-01-30 00:07:20 +00001462 def test_upload_change_description_editor(self):
1463 fetched_description = 'foo\n\nChange-Id: 123456789'
1464 description = 'bar\n\nChange-Id: 123456789'
1465 self._run_gerrit_upload_test(
1466 ['--squash', '--edit-description'],
1467 description,
1468 [],
1469 fetched_description=fetched_description,
1470 squash=True,
1471 expected_upstream_ref='origin/master',
1472 issue=123456,
1473 change_id='123456789',
1474 original_title='User input',
1475 edit_description=description)
1476
Edward Lemurda4b6c62020-02-13 00:28:40 +00001477 @mock.patch('git_cl.RunGit')
1478 @mock.patch('git_cl.CMDupload')
Edward Lemur1a83da12020-03-04 21:18:36 +00001479 @mock.patch('sys.stdin', StringIO('\n'))
1480 @mock.patch('sys.stdout', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001481 def test_upload_branch_deps(self, *_mocks):
rmistry@google.com2dd99862015-06-22 12:22:18 +00001482 def mock_run_git(*args, **_kwargs):
1483 if args[0] == ['for-each-ref',
1484 '--format=%(refname:short) %(upstream:short)',
1485 'refs/heads']:
1486 # Create a local branch dependency tree that looks like this:
1487 # test1 -> test2 -> test3 -> test4 -> test5
1488 # -> test3.1
1489 # test6 -> test0
1490 branch_deps = [
1491 'test2 test1', # test1 -> test2
1492 'test3 test2', # test2 -> test3
1493 'test3.1 test2', # test2 -> test3.1
1494 'test4 test3', # test3 -> test4
1495 'test5 test4', # test4 -> test5
1496 'test6 test0', # test0 -> test6
1497 'test7', # test7
1498 ]
1499 return '\n'.join(branch_deps)
Edward Lemurda4b6c62020-02-13 00:28:40 +00001500 git_cl.RunGit.side_effect = mock_run_git
1501 git_cl.CMDupload.return_value = 0
rmistry@google.com2dd99862015-06-22 12:22:18 +00001502
1503 class MockChangelist():
1504 def __init__(self):
1505 pass
1506 def GetBranch(self):
1507 return 'test1'
1508 def GetIssue(self):
1509 return '123'
1510 def GetPatchset(self):
1511 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001512 def IsGerrit(self):
1513 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001514
1515 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1516 # CMDupload should have been called 5 times because of 5 dependent branches.
Edward Lemurda4b6c62020-02-13 00:28:40 +00001517 self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
Edward Lemur1a83da12020-03-04 21:18:36 +00001518 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001519 'This command will checkout all dependent branches '
1520 'and run "git cl upload". Press Enter to continue, '
Edward Lemur1a83da12020-03-04 21:18:36 +00001521 'or Ctrl+C to abort',
1522 sys.stdout.getvalue())
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001523 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001524
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001525 def test_gerrit_change_id(self):
1526 self.calls = [
1527 ((['git', 'write-tree'], ),
1528 'hashtree'),
1529 ((['git', 'rev-parse', 'HEAD~0'], ),
1530 'branch-parent'),
1531 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1532 'A B <a@b.org> 1456848326 +0100'),
1533 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1534 'C D <c@d.org> 1456858326 +0100'),
1535 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1536 'hashchange'),
1537 ]
1538 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1539 self.assertEqual(change_id, 'Ihashchange')
1540
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001541 def test_desecription_append_footer(self):
1542 for init_desc, footer_line, expected_desc in [
1543 # Use unique desc first lines for easy test failure identification.
1544 ('foo', 'R=one', 'foo\n\nR=one'),
1545 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1546 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1547 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1548 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1549 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1550 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1551 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1552 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1553 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1554 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1555 ]:
1556 desc = git_cl.ChangeDescription(init_desc)
1557 desc.append_footer(footer_line)
1558 self.assertEqual(desc.description, expected_desc)
1559
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001560 def test_update_reviewers(self):
1561 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001562 ('foo', [], [],
1563 'foo'),
1564 ('foo\nR=xx', [], [],
1565 'foo\nR=xx'),
1566 ('foo\nTBR=xx', [], [],
1567 'foo\nTBR=xx'),
1568 ('foo', ['a@c'], [],
1569 'foo\n\nR=a@c'),
1570 ('foo\nR=xx', ['a@c'], [],
1571 'foo\n\nR=a@c, xx'),
1572 ('foo\nTBR=xx', ['a@c'], [],
1573 'foo\n\nR=a@c\nTBR=xx'),
1574 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1575 'foo\n\nR=a@c, yy\nTBR=xx'),
1576 ('foo\nBUG=', ['a@c'], [],
1577 'foo\nBUG=\nR=a@c'),
1578 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1579 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1580 ('foo', ['a@c', 'b@c'], [],
1581 'foo\n\nR=a@c, b@c'),
1582 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1583 'foo\nBar\n\nR=c@c\nBUG='),
1584 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1585 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001586 # Same as the line before, but full of whitespaces.
1587 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001588 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001589 'foo\nBar\n\nR=c@c\n BUG =',
1590 ),
1591 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001592 ('foo BUG=allo R=joe ', ['c@c'], [],
1593 'foo BUG=allo R=joe\n\nR=c@c'),
1594 # Redundant TBRs get promoted to Rs
1595 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1596 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001597 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001598 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001599 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001600 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001601 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001602 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001603 actual.append(obj.description)
1604 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001605
Nodir Turakulov23b82142017-11-16 11:04:25 -08001606 def test_get_hash_tags(self):
1607 cases = [
1608 ('', []),
1609 ('a', []),
1610 ('[a]', ['a']),
1611 ('[aa]', ['aa']),
1612 ('[a ]', ['a']),
1613 ('[a- ]', ['a']),
1614 ('[a- b]', ['a-b']),
1615 ('[a--b]', ['a-b']),
1616 ('[a', []),
1617 ('[a]x', ['a']),
1618 ('[aa]x', ['aa']),
1619 ('[a b]', ['a-b']),
1620 ('[a b]', ['a-b']),
1621 ('[a__b]', ['a-b']),
1622 ('[a] x', ['a']),
1623 ('[a][b]', ['a', 'b']),
1624 ('[a] [b]', ['a', 'b']),
1625 ('[a][b]x', ['a', 'b']),
1626 ('[a][b] x', ['a', 'b']),
1627 ('[a]\n[b]', ['a']),
1628 ('[a\nb]', []),
1629 ('[a][', ['a']),
1630 ('Revert "[a] feature"', ['a']),
1631 ('Reland "[a] feature"', ['a']),
1632 ('Revert: [a] feature', ['a']),
1633 ('Reland: [a] feature', ['a']),
1634 ('Revert "Reland: [a] feature"', ['a']),
1635 ('Foo: feature', ['foo']),
1636 ('Foo Bar: feature', ['foo-bar']),
Anthony Polito02b5af32019-12-02 19:49:47 +00001637 ('Change Foo::Bar', []),
1638 ('Foo: Change Foo::Bar', ['foo']),
Nodir Turakulov23b82142017-11-16 11:04:25 -08001639 ('Revert "Foo bar: feature"', ['foo-bar']),
1640 ('Reland "Foo bar: feature"', ['foo-bar']),
1641 ]
1642 for desc, expected in cases:
1643 change_desc = git_cl.ChangeDescription(desc)
1644 actual = change_desc.get_hash_tags()
1645 self.assertEqual(
1646 actual,
1647 expected,
1648 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1649
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001650 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001651 self.assertEqual(None, git_cl.GetTargetRef(None,
1652 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001653 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001654
wittman@chromium.org455dc922015-01-26 20:15:50 +00001655 # Check default target refs for branches.
1656 self.assertEqual('refs/heads/master',
1657 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001658 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001659 self.assertEqual('refs/heads/master',
1660 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001661 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001662 self.assertEqual('refs/heads/master',
1663 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001664 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001665 self.assertEqual('refs/branch-heads/123',
1666 git_cl.GetTargetRef('origin',
1667 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001668 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001669 self.assertEqual('refs/diff/test',
1670 git_cl.GetTargetRef('origin',
1671 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001672 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001673 self.assertEqual('refs/heads/chrome/m42',
1674 git_cl.GetTargetRef('origin',
1675 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001676 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001677
1678 # Check target refs for user-specified target branch.
1679 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1680 'refs/remotes/branch-heads/123'):
1681 self.assertEqual('refs/branch-heads/123',
1682 git_cl.GetTargetRef('origin',
1683 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001684 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001685 for branch in ('origin/master', 'remotes/origin/master',
1686 'refs/remotes/origin/master'):
1687 self.assertEqual('refs/heads/master',
1688 git_cl.GetTargetRef('origin',
1689 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001690 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001691 for branch in ('master', 'heads/master', 'refs/heads/master'):
1692 self.assertEqual('refs/heads/master',
1693 git_cl.GetTargetRef('origin',
1694 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001695 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001696
Edward Lemurda4b6c62020-02-13 00:28:40 +00001697 @mock.patch('git_common.is_dirty_git_tree', return_value=True)
1698 def test_patch_when_dirty(self, *_mocks):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001699 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001700 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1701
Edward Lemur85153282020-02-14 22:06:29 +00001702 def assertIssueAndPatchset(
1703 self, branch='master', issue='123456', patchset='7',
1704 git_short_host='chromium'):
1705 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001706 issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
Edward Lemur85153282020-02-14 22:06:29 +00001707 self.assertEqual(
Edward Lemur26964072020-02-19 19:18:51 +00001708 patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
Edward Lemur85153282020-02-14 22:06:29 +00001709 self.assertEqual(
1710 'https://%s-review.googlesource.com' % git_short_host,
Edward Lemur26964072020-02-19 19:18:51 +00001711 scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001712
Edward Lemur85153282020-02-14 22:06:29 +00001713 def _patch_common(self, git_short_host='chromium'):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001714 mock.patch('git_cl.IsGitVersionAtLeast', return_value=True).start()
Edward Lemur26964072020-02-19 19:18:51 +00001715 self.mockGit.config['remote.origin.url'] = (
1716 'https://%s.googlesource.com/my/repo' % git_short_host)
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001717 gerrit_util.GetChangeDetail.return_value = {
1718 'current_revision': '7777777777',
1719 'revisions': {
1720 '1111111111': {
1721 '_number': 1,
1722 'fetch': {'http': {
1723 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1724 'ref': 'refs/changes/56/123456/1',
1725 }},
1726 },
1727 '7777777777': {
1728 '_number': 7,
1729 'fetch': {'http': {
1730 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1731 'ref': 'refs/changes/56/123456/7',
1732 }},
1733 },
1734 },
1735 }
wychen@chromium.orga872e752015-04-28 23:42:18 +00001736
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001737 def test_patch_gerrit_default(self):
Edward Lemur85153282020-02-14 22:06:29 +00001738 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001739 self.calls += [
1740 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1741 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001742 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001743 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001744 ]
1745 self.assertEqual(git_cl.main(['patch', '123456']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001746 self.assertIssueAndPatchset()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001747
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001748 def test_patch_gerrit_new_branch(self):
Edward Lemur85153282020-02-14 22:06:29 +00001749 self._patch_common()
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001750 self.calls += [
1751 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1752 'refs/changes/56/123456/7'],), ''),
1753 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001754 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001755 ]
Edward Lemur85153282020-02-14 22:06:29 +00001756 self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
1757 self.assertIssueAndPatchset(branch='feature')
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001758
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001759 def test_patch_gerrit_force(self):
Edward Lemur85153282020-02-14 22:06:29 +00001760 self._patch_common('host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001761 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001762 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001763 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001764 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001765 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001766 ]
Edward Lemur52969c92020-02-06 18:15:28 +00001767 self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001768 self.assertIssueAndPatchset(git_short_host='host')
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001769
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001770 def test_patch_gerrit_guess_by_url(self):
Edward Lemur85153282020-02-14 22:06:29 +00001771 self._patch_common('else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001772 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001773 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001774 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001775 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001776 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001777 ]
1778 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001779 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
Edward Lemur85153282020-02-14 22:06:29 +00001780 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001781
Aaron Gable697a91b2018-01-19 15:20:15 -08001782 def test_patch_gerrit_guess_by_url_with_repo(self):
Edward Lemur85153282020-02-14 22:06:29 +00001783 self._patch_common('else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001784 self.calls += [
1785 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1786 'refs/changes/56/123456/1'],), ''),
1787 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
Aaron Gable697a91b2018-01-19 15:20:15 -08001788 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
Aaron Gable697a91b2018-01-19 15:20:15 -08001789 ]
1790 self.assertEqual(git_cl.main(
1791 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1792 0)
Edward Lemur85153282020-02-14 22:06:29 +00001793 self.assertIssueAndPatchset(patchset='1', git_short_host='else')
Aaron Gable697a91b2018-01-19 15:20:15 -08001794
Edward Lemurd55c5072020-02-20 01:09:07 +00001795 @mock.patch('sys.stderr', StringIO())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001796 def test_patch_gerrit_conflict(self):
Edward Lemur85153282020-02-14 22:06:29 +00001797 self._patch_common()
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001798 self.calls += [
1799 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001800 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001801 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001802 ]
1803 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001804 git_cl.main(['patch', '123456'])
Edward Lemurd55c5072020-02-20 01:09:07 +00001805 self.assertEqual(
1806 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
1807 sys.stderr.getvalue())
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001808
Edward Lemurda4b6c62020-02-13 00:28:40 +00001809 @mock.patch(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001810 'gerrit_util.GetChangeDetail',
Edward Lemurda4b6c62020-02-13 00:28:40 +00001811 side_effect=gerrit_util.GerritError(404, ''))
Edward Lemurd55c5072020-02-20 01:09:07 +00001812 @mock.patch('sys.stderr', StringIO())
Edward Lemurda4b6c62020-02-13 00:28:40 +00001813 def test_patch_gerrit_not_exists(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00001814 self.mockGit.config['remote.origin.url'] = (
1815 'https://chromium.googlesource.com/my/repo')
tandriic2405f52016-10-10 08:13:15 -07001816 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001817 self.assertEqual(1, git_cl.main(['patch', '123456']))
Edward Lemurd55c5072020-02-20 01:09:07 +00001818 self.assertEqual(
1819 'change 123456 at https://chromium-review.googlesource.com does not '
1820 'exist or you have no access to it\n',
1821 sys.stderr.getvalue())
tandriic2405f52016-10-10 08:13:15 -07001822
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001823 def _checkout_calls(self):
1824 return [
1825 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001826 'branch\\..*\\.gerritissue'], ),
1827 ('branch.ger-branch.gerritissue 123456\n'
1828 'branch.gbranch654.gerritissue 654321\n')),
1829 ]
1830
1831 def test_checkout_gerrit(self):
1832 """Tests git cl checkout <issue>."""
1833 self.calls = self._checkout_calls()
1834 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1835 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1836
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001837 def test_checkout_not_found(self):
1838 """Tests git cl checkout <issue>."""
1839 self.calls = self._checkout_calls()
1840 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1841
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001842 def test_checkout_no_branch_issues(self):
1843 """Tests git cl checkout <issue>."""
1844 self.calls = [
1845 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001846 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001847 ]
1848 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1849
Edward Lemur26964072020-02-19 19:18:51 +00001850 def _test_gerrit_ensure_authenticated_common(self, auth):
Edward Lemur1a83da12020-03-04 21:18:36 +00001851 mock.patch(
1852 'git_cl.ask_for_data',
1853 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00001854 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1855 CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
Edward Lemur26964072020-02-19 19:18:51 +00001856 self.mockGit.config['remote.origin.url'] = (
1857 'https://chromium.googlesource.com/my/repo')
Edward Lemurf38bc172019-09-03 21:02:13 +00001858 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001859 cl.branch = 'master'
1860 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001861 return cl
1862
Edward Lemurd55c5072020-02-20 01:09:07 +00001863 @mock.patch('sys.stderr', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001864 def test_gerrit_ensure_authenticated_missing(self):
1865 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001866 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001867 })
Edward Lemurd55c5072020-02-20 01:09:07 +00001868 with self.assertRaises(SystemExitMock):
1869 cl.EnsureAuthenticated(force=False)
1870 self.assertEqual(
1871 'Credentials for the following hosts are required:\n'
1872 ' chromium-review.googlesource.com\n'
1873 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1874 'You can (re)generate your credentials by visiting '
1875 'https://chromium-review.googlesource.com/new-password\n',
1876 sys.stderr.getvalue())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001877
1878 def test_gerrit_ensure_authenticated_conflict(self):
1879 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001880 'chromium.googlesource.com':
1881 ('git-one.example.com', None, 'secret1'),
1882 'chromium-review.googlesource.com':
1883 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001884 })
1885 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001886 (('ask_for_data', 'If you know what you are doing '
1887 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001888 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1889
1890 def test_gerrit_ensure_authenticated_ok(self):
1891 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001892 'chromium.googlesource.com':
1893 ('git-same.example.com', None, 'secret'),
1894 'chromium-review.googlesource.com':
1895 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001896 })
1897 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1898
tandrii@chromium.org28253532016-04-14 13:46:56 +00001899 def test_gerrit_ensure_authenticated_skipped(self):
Edward Lemur26964072020-02-19 19:18:51 +00001900 self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
1901 cl = self._test_gerrit_ensure_authenticated_common(auth={})
tandrii@chromium.org28253532016-04-14 13:46:56 +00001902 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1903
Eric Boren2fb63102018-10-05 13:05:03 +00001904 def test_gerrit_ensure_authenticated_bearer_token(self):
1905 cl = self._test_gerrit_ensure_authenticated_common(auth={
1906 'chromium.googlesource.com':
1907 ('', None, 'secret'),
1908 'chromium-review.googlesource.com':
1909 ('', None, 'secret'),
1910 })
1911 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1912 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1913 'chromium.googlesource.com')
1914 self.assertTrue('Bearer' in header)
1915
Daniel Chengcf6269b2019-05-18 01:02:12 +00001916 def test_gerrit_ensure_authenticated_non_https(self):
Edward Lemur26964072020-02-19 19:18:51 +00001917 self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
Daniel Chengcf6269b2019-05-18 01:02:12 +00001918 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001919 (('logging.warning',
1920 'Ignoring branch %(branch)s with non-https remote '
1921 '%(remote)s', {
1922 'branch': 'master',
1923 'remote': 'custom-scheme://repo'}
1924 ), None),
Daniel Chengcf6269b2019-05-18 01:02:12 +00001925 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001926 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1927 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1928 mock.patch('logging.warning',
1929 lambda *a: self._mocked_call('logging.warning', *a)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00001930 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00001931 cl.branch = 'master'
1932 cl.branchref = 'refs/heads/master'
1933 cl.lookedup_issue = True
1934 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1935
Florian Mayerae510e82020-01-30 21:04:48 +00001936 def test_gerrit_ensure_authenticated_non_url(self):
Edward Lemur26964072020-02-19 19:18:51 +00001937 self.mockGit.config['remote.origin.url'] = (
1938 'git@somehost.example:foo/bar.git')
Florian Mayerae510e82020-01-30 21:04:48 +00001939 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00001940 (('logging.error',
1941 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1942 'but it doesn\'t exist.', {
1943 'remote': 'origin',
1944 'branch': 'master',
1945 'url': 'git@somehost.example:foo/bar.git'}
1946 ), None),
Florian Mayerae510e82020-01-30 21:04:48 +00001947 ]
Edward Lemurda4b6c62020-02-13 00:28:40 +00001948 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
1949 CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
1950 mock.patch('logging.error',
1951 lambda *a: self._mocked_call('logging.error', *a)).start()
Florian Mayerae510e82020-01-30 21:04:48 +00001952 cl = git_cl.Changelist()
1953 cl.branch = 'master'
1954 cl.branchref = 'refs/heads/master'
1955 cl.lookedup_issue = True
1956 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1957
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001958 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
Edward Lemur85153282020-02-14 22:06:29 +00001959 self.mockGit.config['branch.master.gerritissue'] = '123'
1960 self.mockGit.config['branch.master.gerritserver'] = (
1961 'https://chromium-review.googlesource.com')
Edward Lemur26964072020-02-19 19:18:51 +00001962 self.mockGit.config['remote.origin.url'] = (
1963 'https://chromium.googlesource.com/infra/infra')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001964 self.calls = [
Edward Lemurda4b6c62020-02-13 00:28:40 +00001965 (('SetReview', 'chromium-review.googlesource.com',
1966 'infra%2Finfra~123', None,
1967 {'Commit-Queue': vote}, notify, None), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001968 ]
tandriid9e5ce52016-07-13 02:32:59 -07001969
1970 def test_cmd_set_commit_gerrit_clear(self):
1971 self._cmd_set_commit_gerrit_common(0)
1972 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1973
1974 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001975 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001976 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1977
tandriid9e5ce52016-07-13 02:32:59 -07001978 def test_cmd_set_commit_gerrit(self):
1979 self._cmd_set_commit_gerrit_common(2)
1980 self.assertEqual(0, git_cl.main(['set-commit']))
1981
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001982 def test_description_display(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00001983 mock.patch('git_cl.Changelist', ChangelistMock).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001984 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001985
1986 self.assertEqual(0, git_cl.main(['description', '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00001987 self.assertEqual('foo\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001988
Edward Lemurda4b6c62020-02-13 00:28:40 +00001989 @mock.patch('sys.stderr', StringIO())
iannucci3c972b92016-08-17 13:24:10 -07001990 def test_StatusFieldOverrideIssueMissingArgs(self):
iannucci3c972b92016-08-17 13:24:10 -07001991 try:
1992 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
Edward Lemurd55c5072020-02-20 01:09:07 +00001993 except SystemExitMock:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001994 self.assertIn(
Edward Lemurda4b6c62020-02-13 00:28:40 +00001995 '--field must be given when --issue is set.', sys.stderr.getvalue())
iannucci3c972b92016-08-17 13:24:10 -07001996
1997 def test_StatusFieldOverrideIssue(self):
iannucci3c972b92016-08-17 13:24:10 -07001998 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001999 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002000 return 'foobar'
2001
Edward Lemurda4b6c62020-02-13 00:28:40 +00002002 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
iannuccie53c9352016-08-17 14:40:40 -07002003 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002004 git_cl.main(['status', '--issue', '1', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002005 0)
Edward Lemurda4b6c62020-02-13 00:28:40 +00002006 self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
iannucci3c972b92016-08-17 13:24:10 -07002007
iannuccie53c9352016-08-17 14:40:40 -07002008 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002009
iannuccie53c9352016-08-17 14:40:40 -07002010 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002011 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002012 return 'foobar'
2013
Edward Lemurda4b6c62020-02-13 00:28:40 +00002014 mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
2015 mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
iannuccie53c9352016-08-17 14:40:40 -07002016 self.assertEqual(
Edward Lemur52969c92020-02-06 18:15:28 +00002017 git_cl.main(['set-close', '--issue', '1']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002018
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002019 def test_description(self):
Edward Lemur26964072020-02-19 19:18:51 +00002020 self.mockGit.config['remote.origin.url'] = (
2021 'https://chromium.googlesource.com/my/repo')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002022 gerrit_util.GetChangeDetail.return_value = {
2023 'current_revision': 'sha1',
2024 'revisions': {'sha1': {
2025 'commit': {'message': 'foobar'},
2026 }},
2027 }
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002028 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002029 'description',
2030 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2031 '-d']))
Edward Lemurda4b6c62020-02-13 00:28:40 +00002032 self.assertEqual('foobar\n', sys.stdout.getvalue())
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002033
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002034 def test_description_set_raw(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002035 mock.patch('git_cl.Changelist', ChangelistMock).start()
2036 mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002037
2038 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2039 self.assertEqual('hihi', ChangelistMock.desc)
2040
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002041 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002042 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002043
2044 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002045 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002046 '# Enter a description of the change.\n'
2047 '# This will be displayed on the codereview site.\n'
2048 '# The first line will also be used as the subject of the review.\n'
2049 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002050 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002051 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002052 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002053 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002054 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002055
Edward Lemur6c6827c2020-02-06 21:15:18 +00002056 def UpdateDescription(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002057 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002058
Edward Lemurda4b6c62020-02-13 00:28:40 +00002059 mock.patch('git_cl.Changelist.FetchDescription',
2060 lambda *args: current_desc).start()
2061 mock.patch('git_cl.Changelist.UpdateDescription',
2062 UpdateDescription).start()
2063 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002064
Edward Lemur85153282020-02-14 22:06:29 +00002065 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002066 self.assertEqual(0, git_cl.main(['description']))
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002067
Dan Beamd8b04ca2019-10-10 21:23:26 +00002068 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2069 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2070
2071 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002072 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002073 '# Enter a description of the change.\n'
2074 '# This will be displayed on the codereview site.\n'
2075 '# The first line will also be used as the subject of the review.\n'
2076 '#--------------------This line is 72 characters long'
2077 '--------------------\n'
2078 'Some.\n\nFixed: 123\nChange-Id: xxx',
2079 desc)
2080 return desc
2081
Edward Lemurda4b6c62020-02-13 00:28:40 +00002082 mock.patch('git_cl.Changelist.FetchDescription',
2083 lambda *args: current_desc).start()
2084 mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002085
Edward Lemur85153282020-02-14 22:06:29 +00002086 self.mockGit.config['branch.master.gerritissue'] = '123'
Edward Lemur52969c92020-02-06 18:15:28 +00002087 self.assertEqual(0, git_cl.main(['description']))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002088
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002089 def test_description_set_stdin(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002090 mock.patch('git_cl.Changelist', ChangelistMock).start()
2091 mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002092
2093 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2094 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2095
kmarshall3bff56b2016-06-06 18:31:47 -07002096 def test_archive(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002097 self.calls = [
2098 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002099 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002100 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002101 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002102 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002103 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002104
Edward Lemurda4b6c62020-02-13 00:28:40 +00002105 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002106 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002107 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2108 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002109 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002110
2111 self.assertEqual(0, git_cl.main(['archive', '-f']))
2112
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002113 def test_archive_tag_collision(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002114 self.calls = [
2115 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2116 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2117 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
2118 'refs/tags/git-cl-archived-456-foo'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002119 ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
2120 ((['git', 'branch', '-D', 'foo'],), '')
2121 ]
2122
Edward Lemurda4b6c62020-02-13 00:28:40 +00002123 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002124 lambda branches, fine_grained, max_processes:
2125 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2126 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002127 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002128
2129 self.assertEqual(0, git_cl.main(['archive', '-f']))
2130
kmarshall3bff56b2016-06-06 18:31:47 -07002131 def test_archive_current_branch_fails(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002132 self.calls = [
2133 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2134 'refs/heads/master'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002135 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002136 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002137
Edward Lemurda4b6c62020-02-13 00:28:40 +00002138 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002139 lambda branches, fine_grained, max_processes:
Edward Lemurda4b6c62020-02-13 00:28:40 +00002140 [(MockChangelistWithBranchAndIssue('master', 1),
2141 'closed')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002142
2143 self.assertEqual(1, git_cl.main(['archive', '-f']))
2144
2145 def test_archive_dry_run(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002146 self.calls = [
2147 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2148 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002149 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002150 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002151
Edward Lemurda4b6c62020-02-13 00:28:40 +00002152 mock.patch('git_cl.get_cl_statuses',
kmarshall3bff56b2016-06-06 18:31:47 -07002153 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002154 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2155 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002156 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall3bff56b2016-06-06 18:31:47 -07002157
kmarshall9249e012016-08-23 12:02:16 -07002158 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2159
2160 def test_archive_no_tags(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002161 self.calls = [
2162 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2163 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002164 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002165 ((['git', 'branch', '-D', 'foo'],), '')
2166 ]
kmarshall9249e012016-08-23 12:02:16 -07002167
Edward Lemurda4b6c62020-02-13 00:28:40 +00002168 mock.patch('git_cl.get_cl_statuses',
kmarshall9249e012016-08-23 12:02:16 -07002169 lambda branches, fine_grained, max_processes:
2170 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2171 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002172 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
kmarshall9249e012016-08-23 12:02:16 -07002173
2174 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002175
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002176 def test_archive_tag_cleanup_on_branch_deletion_error(self):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002177 self.calls = [
2178 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2179 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2180 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002181 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
2182 'refs/tags/git-cl-archived-456-foo'),
2183 ((['git', 'branch', '-D', 'foo'],), CERR1),
2184 ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
2185 'refs/tags/git-cl-archived-456-foo'),
2186 ]
2187
Edward Lemurda4b6c62020-02-13 00:28:40 +00002188 mock.patch('git_cl.get_cl_statuses',
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002189 lambda branches, fine_grained, max_processes:
2190 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2191 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
Edward Lemurda4b6c62020-02-13 00:28:40 +00002192 (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00002193
2194 self.assertEqual(0, git_cl.main(['archive', '-f']))
2195
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002196 def test_cmd_issue_erase_existing(self):
Edward Lemur85153282020-02-14 22:06:29 +00002197 self.mockGit.config['branch.master.gerritissue'] = '123'
2198 self.mockGit.config['branch.master.gerritserver'] = (
2199 'https://chromium-review.googlesource.com')
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002200 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002201 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002202 ]
2203 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002204 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2205 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002206
Aaron Gable400e9892017-07-12 15:31:21 -07002207 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur85153282020-02-14 22:06:29 +00002208 self.mockGit.config['branch.master.gerritissue'] = '123'
2209 self.mockGit.config['branch.master.gerritserver'] = (
2210 'https://chromium-review.googlesource.com')
Edward Lemurda4b6c62020-02-13 00:28:40 +00002211 mock.patch('git_cl.Changelist.FetchDescription',
2212 lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
Aaron Gable400e9892017-07-12 15:31:21 -07002213 self.calls = [
Aaron Gableca01e2c2017-07-19 11:16:02 -07002214 ((['git', 'log', '-1', '--format=%B'],),
2215 'This is a description\n\nChange-Id: Ideadbeef'),
2216 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002217 ]
2218 self.assertEqual(0, git_cl.main(['issue', '0']))
Edward Lemur85153282020-02-14 22:06:29 +00002219 self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
2220 self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
Aaron Gable400e9892017-07-12 15:31:21 -07002221
phajdan.jre328cf92016-08-22 04:12:17 -07002222 def test_cmd_issue_json(self):
Edward Lemur85153282020-02-14 22:06:29 +00002223 self.mockGit.config['branch.master.gerritissue'] = '123'
2224 self.mockGit.config['branch.master.gerritserver'] = (
2225 'https://chromium-review.googlesource.com')
phajdan.jre328cf92016-08-22 04:12:17 -07002226 self.calls = [
phajdan.jre328cf92016-08-22 04:12:17 -07002227 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002228 {'issue': 123,
2229 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002230 ''),
2231 ]
2232 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2233
tandrii16e0b4e2016-06-07 10:34:28 -07002234 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002235 mock.patch(
2236 'git_cl.os.path.abspath',
2237 lambda path: self._mocked_call(['abspath', path])).start()
2238 mock.patch(
2239 'git_cl.os.path.exists',
2240 lambda path: self._mocked_call(['exists', path])).start()
2241 mock.patch(
2242 'git_cl.gclient_utils.FileRead',
2243 lambda path: self._mocked_call(['FileRead', path])).start()
2244 mock.patch(
2245 'git_cl.gclient_utils.rm_file_or_tree',
2246 lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
Edward Lemur1a83da12020-03-04 21:18:36 +00002247 mock.patch(
2248 'git_cl.ask_for_data',
2249 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurf38bc172019-09-03 21:02:13 +00002250 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002251
2252 def test_GerritCommitMsgHookCheck_custom_hook(self):
2253 cl = self._common_GerritCommitMsgHookCheck()
2254 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002255 ((['exists', '.git/hooks/commit-msg'],), True),
2256 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002257 '#!/bin/sh\necho "custom hook"')
2258 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002259 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002260
2261 def test_GerritCommitMsgHookCheck_not_exists(self):
2262 cl = self._common_GerritCommitMsgHookCheck()
2263 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002264 ((['exists', '.git/hooks/commit-msg'],), False),
tandrii16e0b4e2016-06-07 10:34:28 -07002265 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002266 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002267
2268 def test_GerritCommitMsgHookCheck(self):
2269 cl = self._common_GerritCommitMsgHookCheck()
2270 self.calls += [
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002271 ((['exists', '.git/hooks/commit-msg'],), True),
2272 ((['FileRead', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002273 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002274 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
Edward Lemur15a9b8c2020-02-13 00:52:30 +00002275 ((['rm_file_or_tree', '.git/hooks/commit-msg'],),
tandrii16e0b4e2016-06-07 10:34:28 -07002276 ''),
2277 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002278 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002279
tandriic4344b52016-08-29 06:04:54 -07002280 def test_GerritCmdLand(self):
Edward Lemur85153282020-02-14 22:06:29 +00002281 self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
2282 self.mockGit.config['branch.master.gerritserver'] = (
2283 'chromium-review.googlesource.com')
tandriic4344b52016-08-29 06:04:54 -07002284 self.calls += [
tandriic4344b52016-08-29 06:04:54 -07002285 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
tandriic4344b52016-08-29 06:04:54 -07002286 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002287 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002288 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002289 'labels': {},
2290 'current_revision': 'deadbeaf',
2291 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002292 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002293 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002294 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002295 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2296 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002297 cl.SubmitIssue = lambda wait_for_merge: None
Olivier Robin75ee7252018-04-13 10:02:56 +02002298 self.assertEqual(0, cl.CMDLand(force=True,
2299 bypass_hooks=True,
2300 verbose=True,
2301 parallel=False))
Edward Lemur73c76702020-02-06 23:57:18 +00002302 self.assertIn(
2303 'Issue chromium-review.googlesource.com/123 has been submitted',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002304 sys.stdout.getvalue())
Edward Lemur73c76702020-02-06 23:57:18 +00002305 self.assertIn(
2306 'Landed as: https://git.googlesource.com/test/+/deadbeef',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002307 sys.stdout.getvalue())
tandriic4344b52016-08-29 06:04:54 -07002308
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002309 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002310 mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002311
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002312 def test_gerrit_change_detail_cache_simple(self):
2313 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002314 gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
Edward Lemurf38bc172019-09-03 21:02:13 +00002315 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002316 cl1._cached_remote_url = (
2317 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002318 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002319 cl2._cached_remote_url = (
2320 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002321 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2322 self.assertEqual(cl1._GetChangeDetail(), 'a')
2323 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002324
2325 def test_gerrit_change_detail_cache_options(self):
2326 self._mock_gerrit_changes_for_detail_cache()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002327 gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
Edward Lemurf38bc172019-09-03 21:02:13 +00002328 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002329 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002330 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2331 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2332 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2333 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2334 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2335 self.assertEqual(cl._GetChangeDetail(), 'cab')
2336
2337 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2338 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2339 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2340 self.assertEqual(cl._GetChangeDetail(), 'cab')
2341
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002342 def test_gerrit_description_caching(self):
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002343 gerrit_util.GetChangeDetail.return_value = {
2344 'current_revision': 'rev1',
2345 'revisions': {
2346 'rev1': {'commit': {'message': 'desc1'}},
2347 },
2348 }
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002349
2350 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002351 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002352 cl._cached_remote_url = (
2353 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemur6c6827c2020-02-06 21:15:18 +00002354 self.assertEqual(cl.FetchDescription(), 'desc1')
2355 self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002356
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002357 def test_print_current_creds(self):
2358 class CookiesAuthenticatorMock(object):
2359 def __init__(self):
2360 self.gitcookies = {
2361 'host.googlesource.com': ('user', 'pass'),
2362 'host-review.googlesource.com': ('user', 'pass'),
2363 }
2364 self.netrc = self
2365 self.netrc.hosts = {
2366 'github.com': ('user2', None, 'pass2'),
2367 'host2.googlesource.com': ('user3', None, 'pass'),
2368 }
Edward Lemurda4b6c62020-02-13 00:28:40 +00002369 mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
2370 CookiesAuthenticatorMock).start()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002371 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2372 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2373 ' Host\t User\t Which file',
2374 '============================\t=====\t===========',
2375 'host-review.googlesource.com\t user\t.gitcookies',
2376 ' host.googlesource.com\t user\t.gitcookies',
2377 ' host2.googlesource.com\tuser3\t .netrc',
2378 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002379 sys.stdout.seek(0)
2380 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002381 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2382 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2383 ' Host\tUser\t Which file',
2384 '============================\t====\t===========',
2385 'host-review.googlesource.com\tuser\t.gitcookies',
2386 ' host.googlesource.com\tuser\t.gitcookies',
2387 ])
2388
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002389 def _common_creds_check_mocks(self):
2390 def exists_mock(path):
2391 dirname = os.path.dirname(path)
2392 if dirname == os.path.expanduser('~'):
2393 dirname = '~'
2394 base = os.path.basename(path)
2395 if base in ('.netrc', '.gitcookies'):
2396 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2397 # git cl also checks for existence other files not relevant to this test.
2398 return None
Edward Lemur1a83da12020-03-04 21:18:36 +00002399 mock.patch(
2400 'git_cl.ask_for_data',
2401 lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002402 mock.patch('os.path.exists', exists_mock).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002403
2404 def test_creds_check_gitcookies_not_configured(self):
2405 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002406 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2407 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002408 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002409 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002410 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2411 (('os.path.exists', '~/.netrc'), True),
2412 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2413 'or Ctrl+C to abort'), ''),
2414 ((['git', 'config', '--global', 'http.cookiefile',
2415 os.path.expanduser('~/.gitcookies')], ), ''),
2416 ]
2417 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002418 self.assertTrue(
2419 sys.stdout.getvalue().startswith(
2420 'You seem to be using outdated .netrc for git credentials:'))
2421 self.assertIn(
2422 '\nConfigured git to use .gitcookies from',
2423 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002424
2425 def test_creds_check_gitcookies_configured_custom_broken(self):
2426 self._common_creds_check_mocks()
Edward Lemurda4b6c62020-02-13 00:28:40 +00002427 mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
2428 lambda _, include_netrc=False: []).start()
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002429 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002430 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002431 ((['git', 'config', '--global', 'http.cookiefile'],),
2432 '/custom/.gitcookies'),
2433 (('os.path.exists', '/custom/.gitcookies'), False),
2434 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2435 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2436 ((['git', 'config', '--global', 'http.cookiefile',
2437 os.path.expanduser('~/.gitcookies')], ), ''),
2438 ]
2439 self.assertEqual(0, git_cl.main(['creds-check']))
Edward Lemur73c76702020-02-06 23:57:18 +00002440 self.assertIn(
2441 'WARNING: You have configured custom path to .gitcookies: ',
2442 sys.stdout.getvalue())
2443 self.assertIn(
2444 'However, your configured .gitcookies file is missing.',
2445 sys.stdout.getvalue())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002446
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002447 def test_git_cl_comment_add_gerrit(self):
Edward Lemur85153282020-02-14 22:06:29 +00002448 self.mockGit.branchref = None
Edward Lemur26964072020-02-19 19:18:51 +00002449 self.mockGit.config['remote.origin.url'] = (
2450 'https://chromium.googlesource.com/infra/infra')
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002451 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002452 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
Edward Lemurda4b6c62020-02-13 00:28:40 +00002453 'msg', None, None, None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002454 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002455 ]
Edward Lemur52969c92020-02-06 18:15:28 +00002456 self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002457
Edward Lemurda4b6c62020-02-13 00:28:40 +00002458 @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
2459 def test_git_cl_comments_fetch_gerrit(self, *_mocks):
Edward Lemur26964072020-02-19 19:18:51 +00002460 self.mockGit.config['remote.origin.url'] = (
2461 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002462 gerrit_util.GetChangeDetail.return_value = {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002463 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002464 'current_revision': 'ba5eba11',
2465 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002466 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002467 '_number': 1,
2468 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002469 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002470 '_number': 2,
2471 },
2472 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002473 'messages': [
2474 {
2475 u'_revision_number': 1,
2476 u'author': {
2477 u'_account_id': 1111084,
2478 u'email': u'commit-bot@chromium.org',
2479 u'name': u'Commit Bot'
2480 },
2481 u'date': u'2017-03-15 20:08:45.000000000',
2482 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002483 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002484 u'tag': u'autogenerated:cq:dry-run'
2485 },
2486 {
2487 u'_revision_number': 2,
2488 u'author': {
2489 u'_account_id': 11151243,
2490 u'email': u'owner@example.com',
2491 u'name': u'owner'
2492 },
2493 u'date': u'2017-03-16 20:00:41.000000000',
2494 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2495 u'message': u'PTAL',
2496 },
2497 {
2498 u'_revision_number': 2,
2499 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002500 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002501 u'email': u'reviewer@example.com',
2502 u'name': u'reviewer'
2503 },
2504 u'date': u'2017-03-17 05:19:37.500000000',
2505 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2506 u'message': u'Patch Set 2: Code-Review+1',
2507 },
2508 ]
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002509 }
2510 self.calls = [
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002511 (('GetChangeComments', 'chromium-review.googlesource.com',
2512 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002513 '/COMMIT_MSG': [
2514 {
2515 'author': {'email': u'reviewer@example.com'},
2516 'updated': u'2017-03-17 05:19:37.500000000',
2517 'patch_set': 2,
2518 'side': 'REVISION',
2519 'message': 'Please include a bug link',
2520 },
2521 ],
2522 'codereview.settings': [
2523 {
2524 'author': {'email': u'owner@example.com'},
2525 'updated': u'2017-03-16 20:00:41.000000000',
2526 'patch_set': 2,
2527 'side': 'PARENT',
2528 'line': 42,
2529 'message': 'I removed this because it is bad',
2530 },
2531 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002532 }),
2533 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2534 'infra%2Finfra~1'), {}),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002535 ] * 2 + [
2536 (('write_json', 'output.json', [
2537 {
2538 u'date': u'2017-03-16 20:00:41.000000',
2539 u'message': (
2540 u'PTAL\n' +
2541 u'\n' +
2542 u'codereview.settings\n' +
2543 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2544 u'c/1/2/codereview.settings#b42\n' +
2545 u' I removed this because it is bad\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'owner@example.com'
2550 }, {
2551 u'date': u'2017-03-17 05:19:37.500000',
2552 u'message': (
2553 u'Patch Set 2: Code-Review+1\n' +
2554 u'\n' +
2555 u'/COMMIT_MSG\n' +
2556 u' PS2, File comment: https://chromium-review.googlesource' +
2557 u'.com/c/1/2//COMMIT_MSG#\n' +
2558 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002559 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002560 u'approval': False,
2561 u'disapproval': False,
2562 u'sender': u'reviewer@example.com'
2563 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002564 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002565 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002566 expected_comments_summary = [
2567 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002568 message=(
2569 u'PTAL\n' +
2570 u'\n' +
2571 u'codereview.settings\n' +
2572 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2573 u'c/1/2/codereview.settings#b42\n' +
2574 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002575 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002576 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002577 disapproval=False, approval=False, sender=u'owner@example.com'),
2578 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002579 message=(
2580 u'Patch Set 2: Code-Review+1\n' +
2581 u'\n' +
2582 u'/COMMIT_MSG\n' +
2583 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2584 u'c/1/2//COMMIT_MSG#\n' +
2585 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002586 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002587 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002588 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2589 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002590 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002591 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002592 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002593 self.assertEqual(
2594 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2595
2596 def test_git_cl_comments_robot_comments(self):
2597 # git cl comments also fetches robot comments (which are considered a type
2598 # of autogenerated comment), and unlike other types of comments, only robot
2599 # comments from the latest patchset are shown.
Edward Lemur26964072020-02-19 19:18:51 +00002600 self.mockGit.config['remote.origin.url'] = (
2601 'https://chromium.googlesource.com/infra/infra')
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002602 gerrit_util.GetChangeDetail.return_value = {
2603 'owner': {'email': 'owner@example.com'},
2604 'current_revision': 'ba5eba11',
2605 'revisions': {
2606 'deadbeaf': {
2607 '_number': 1,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002608 },
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002609 'ba5eba11': {
2610 '_number': 2,
2611 },
2612 },
2613 'messages': [
2614 {
2615 u'_revision_number': 1,
2616 u'author': {
2617 u'_account_id': 1111084,
2618 u'email': u'commit-bot@chromium.org',
2619 u'name': u'Commit Bot'
2620 },
2621 u'date': u'2017-03-15 20:08:45.000000000',
2622 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2623 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2624 u'tag': u'autogenerated:cq:dry-run'
2625 },
2626 {
2627 u'_revision_number': 1,
2628 u'author': {
2629 u'_account_id': 123,
2630 u'email': u'tricium@serviceaccount.com',
2631 u'name': u'Tricium'
2632 },
2633 u'date': u'2017-03-16 20:00:41.000000000',
2634 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2635 u'message': u'(1 comment)',
2636 u'tag': u'autogenerated:tricium',
2637 },
2638 {
2639 u'_revision_number': 1,
2640 u'author': {
2641 u'_account_id': 123,
2642 u'email': u'tricium@serviceaccount.com',
2643 u'name': u'Tricium'
2644 },
2645 u'date': u'2017-03-16 20:00:41.000000000',
2646 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2647 u'message': u'(1 comment)',
2648 u'tag': u'autogenerated:tricium',
2649 },
2650 {
2651 u'_revision_number': 2,
2652 u'author': {
2653 u'_account_id': 123,
2654 u'email': u'tricium@serviceaccount.com',
2655 u'name': u'reviewer'
2656 },
2657 u'date': u'2017-03-17 05:30:37.000000000',
2658 u'tag': u'autogenerated:tricium',
2659 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2660 u'message': u'(1 comment)',
2661 },
2662 ]
2663 }
2664 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002665 (('GetChangeComments', 'chromium-review.googlesource.com',
2666 'infra%2Finfra~1'), {}),
2667 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2668 'infra%2Finfra~1'), {
2669 'codereview.settings': [
2670 {
2671 u'author': {u'email': u'tricium@serviceaccount.com'},
2672 u'updated': u'2017-03-17 05:30:37.000000000',
2673 u'robot_run_id': u'5565031076855808',
2674 u'robot_id': u'Linter/Category',
2675 u'tag': u'autogenerated:tricium',
2676 u'patch_set': 2,
2677 u'side': u'REVISION',
2678 u'message': u'Linter warning message text',
2679 u'line': 32,
2680 },
2681 ],
2682 }),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002683 ]
2684 expected_comments_summary = [
2685 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2686 message=(
2687 u'(1 comment)\n\ncodereview.settings\n'
2688 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2689 u'c/1/2/codereview.settings#32\n'
2690 u' Linter warning message text\n'),
2691 sender=u'tricium@serviceaccount.com',
2692 autogenerated=True, approval=False, disapproval=False)
2693 ]
2694 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002695 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002696 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002697
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002698 def test_get_remote_url_with_mirror(self):
2699 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002700
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002701 def selective_os_path_isdir_mock(path):
2702 if path == '/cache/this-dir-exists':
2703 return self._mocked_call('os.path.isdir', path)
2704 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002705
Edward Lemurda4b6c62020-02-13 00:28:40 +00002706 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002707
2708 url = 'https://chromium.googlesource.com/my/repo'
Edward Lemur26964072020-02-19 19:18:51 +00002709 self.mockGit.config['remote.origin.url'] = (
2710 '/cache/this-dir-exists')
2711 self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
2712 url)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002713 self.calls = [
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002714 (('os.path.isdir', '/cache/this-dir-exists'),
2715 True),
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002716 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002717 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002718 self.assertEqual(cl.GetRemoteUrl(), url)
2719 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2720
Edward Lemur298f2cf2019-02-22 21:40:39 +00002721 def test_get_remote_url_non_existing_mirror(self):
2722 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002723
Edward Lemur298f2cf2019-02-22 21:40:39 +00002724 def selective_os_path_isdir_mock(path):
2725 if path == '/cache/this-dir-doesnt-exist':
2726 return self._mocked_call('os.path.isdir', path)
2727 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002728
Edward Lemurda4b6c62020-02-13 00:28:40 +00002729 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2730 mock.patch('logging.error',
2731 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002732
Edward Lemur26964072020-02-19 19:18:51 +00002733 self.mockGit.config['remote.origin.url'] = (
2734 '/cache/this-dir-doesnt-exist')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002735 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002736 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2737 False),
2738 (('logging.error',
Josip906bfde2020-01-31 22:38:49 +00002739 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2740 'but it doesn\'t exist.', {
2741 'remote': 'origin',
2742 'branch': 'master',
2743 'url': '/cache/this-dir-doesnt-exist'}
2744 ), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002745 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002746 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002747 self.assertIsNone(cl.GetRemoteUrl())
2748
2749 def test_get_remote_url_misconfigured_mirror(self):
2750 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002751
Edward Lemur298f2cf2019-02-22 21:40:39 +00002752 def selective_os_path_isdir_mock(path):
2753 if path == '/cache/this-dir-exists':
2754 return self._mocked_call('os.path.isdir', path)
2755 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002756
Edward Lemurda4b6c62020-02-13 00:28:40 +00002757 mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
2758 mock.patch('logging.error',
2759 lambda *a: self._mocked_call('logging.error', *a)).start()
Edward Lemur298f2cf2019-02-22 21:40:39 +00002760
Edward Lemur26964072020-02-19 19:18:51 +00002761 self.mockGit.config['remote.origin.url'] = (
2762 '/cache/this-dir-exists')
Edward Lemur298f2cf2019-02-22 21:40:39 +00002763 self.calls = [
Edward Lemur298f2cf2019-02-22 21:40:39 +00002764 (('os.path.isdir', '/cache/this-dir-exists'), True),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002765 (('logging.error',
2766 'Remote "%(remote)s" for branch "%(branch)s" points to '
2767 '"%(cache_path)s", but it is misconfigured.\n'
2768 '"%(cache_path)s" must be a git repo and must have a remote named '
2769 '"%(remote)s" pointing to the git host.', {
2770 'remote': 'origin',
2771 'cache_path': '/cache/this-dir-exists',
2772 'branch': 'master'}
2773 ), None),
2774 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002775 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002776 self.assertIsNone(cl.GetRemoteUrl())
2777
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002778 def test_gerrit_change_identifier_with_project(self):
Edward Lemur26964072020-02-19 19:18:51 +00002779 self.mockGit.config['remote.origin.url'] = (
2780 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002781 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002782 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2783
2784 def test_gerrit_change_identifier_without_project(self):
Edward Lemurda4b6c62020-02-13 00:28:40 +00002785 mock.patch('logging.error',
2786 lambda *a: self._mocked_call('logging.error', *a)).start()
Josip906bfde2020-01-31 22:38:49 +00002787
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002788 self.calls = [
Josip906bfde2020-01-31 22:38:49 +00002789 (('logging.error',
2790 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
2791 'but it doesn\'t exist.', {
2792 'remote': 'origin',
2793 'branch': 'master',
2794 'url': ''}
2795 ), None),
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002796 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002797 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002798 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002799
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002800
Edward Lemur9aa1a962020-02-25 00:58:38 +00002801class ChangelistTest(unittest.TestCase):
Edward Lemur227d5102020-02-25 23:45:35 +00002802 def setUp(self):
2803 super(ChangelistTest, self).setUp()
2804 mock.patch('gclient_utils.FileRead').start()
2805 mock.patch('gclient_utils.FileWrite').start()
2806 mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
2807 mock.patch(
2808 'git_cl.Changelist.GetCodereviewServer',
2809 return_value='https://chromium-review.googlesource.com').start()
2810 mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
2811 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
2812 mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
2813 mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
2814 mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
2815 mock.patch('git_cl.time_time').start()
2816 mock.patch('metrics.collector').start()
2817 mock.patch('subprocess2.Popen').start()
2818 self.addCleanup(mock.patch.stopall)
2819 self.temp_count = 0
2820
Edward Lemur9aa1a962020-02-25 00:58:38 +00002821 @mock.patch('git_cl.RunGitWithCode')
2822 def testGetLocalDescription(self, _mock):
2823 git_cl.RunGitWithCode.return_value = (0, 'description')
2824 cl = git_cl.Changelist()
2825 self.assertEqual('description', cl.GetLocalDescription('branch'))
2826 self.assertEqual('description', cl.GetLocalDescription('branch'))
2827 git_cl.RunGitWithCode.assert_called_once_with(
2828 ['log', '--pretty=format:%s%n%n%b', 'branch...'])
2829
Edward Lemur227d5102020-02-25 23:45:35 +00002830 def testRunHook(self):
2831 expected_results = {
2832 'more_cc': ['more@example.com', 'cc@example.com'],
2833 'should_continue': True,
2834 }
2835 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2836 git_cl.time_time.side_effect = [100, 200]
2837 mockProcess = mock.Mock()
2838 mockProcess.wait.return_value = 0
2839 subprocess2.Popen.return_value = mockProcess
2840
2841 cl = git_cl.Changelist()
2842 results = cl.RunHook(
2843 committing=True,
2844 may_prompt=True,
2845 verbose=2,
2846 parallel=True,
2847 upstream='upstream',
2848 description='description',
2849 all_files=True)
2850
2851 self.assertEqual(expected_results, results)
2852 subprocess2.Popen.assert_called_once_with([
2853 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur227d5102020-02-25 23:45:35 +00002854 '--root', 'root',
2855 '--upstream', 'upstream',
2856 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002857 '--author', 'author',
2858 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur227d5102020-02-25 23:45:35 +00002859 '--issue', '123456',
2860 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002861 '--commit',
Edward Lemur227d5102020-02-25 23:45:35 +00002862 '--may_prompt',
2863 '--parallel',
2864 '--all_files',
2865 '--json_output', '/tmp/fake-temp2',
2866 '--description_file', '/tmp/fake-temp1',
2867 ])
2868 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002869 '/tmp/fake-temp1', 'description')
Edward Lemur227d5102020-02-25 23:45:35 +00002870 metrics.collector.add_repeated('sub_commands', {
2871 'command': 'presubmit',
2872 'execution_time': 100,
2873 'exit_code': 0,
2874 })
2875
Edward Lemur99df04e2020-03-05 19:39:43 +00002876 def testRunHook_FewerOptions(self):
2877 expected_results = {
2878 'more_cc': ['more@example.com', 'cc@example.com'],
2879 'should_continue': True,
2880 }
2881 gclient_utils.FileRead.return_value = json.dumps(expected_results)
2882 git_cl.time_time.side_effect = [100, 200]
2883 mockProcess = mock.Mock()
2884 mockProcess.wait.return_value = 0
2885 subprocess2.Popen.return_value = mockProcess
2886
2887 git_cl.Changelist.GetAuthor.return_value = None
2888 git_cl.Changelist.GetIssue.return_value = None
2889 git_cl.Changelist.GetPatchset.return_value = None
2890 git_cl.Changelist.GetCodereviewServer.return_value = None
2891
2892 cl = git_cl.Changelist()
2893 results = cl.RunHook(
2894 committing=False,
2895 may_prompt=False,
2896 verbose=0,
2897 parallel=False,
2898 upstream='upstream',
2899 description='description',
2900 all_files=False)
2901
2902 self.assertEqual(expected_results, results)
2903 subprocess2.Popen.assert_called_once_with([
2904 'vpython', 'PRESUBMIT_SUPPORT',
2905 '--root', 'root',
2906 '--upstream', 'upstream',
2907 '--upload',
2908 '--json_output', '/tmp/fake-temp2',
2909 '--description_file', '/tmp/fake-temp1',
2910 ])
2911 gclient_utils.FileWrite.assert_called_once_with(
2912 '/tmp/fake-temp1', 'description')
2913 metrics.collector.add_repeated('sub_commands', {
2914 'command': 'presubmit',
2915 'execution_time': 100,
2916 'exit_code': 0,
2917 })
2918
Edward Lemur227d5102020-02-25 23:45:35 +00002919 @mock.patch('sys.exit', side_effect=SystemExitMock)
2920 def testRunHook_Failure(self, _mock):
2921 git_cl.time_time.side_effect = [100, 200]
2922 mockProcess = mock.Mock()
2923 mockProcess.wait.return_value = 2
2924 subprocess2.Popen.return_value = mockProcess
2925
2926 cl = git_cl.Changelist()
2927 with self.assertRaises(SystemExitMock):
2928 cl.RunHook(
2929 committing=True,
2930 may_prompt=True,
2931 verbose=2,
2932 parallel=True,
2933 upstream='upstream',
2934 description='description',
2935 all_files=True)
2936
2937 sys.exit.assert_called_once_with(2)
2938
Edward Lemur75526302020-02-27 22:31:05 +00002939 def testRunPostUploadHook(self):
2940 cl = git_cl.Changelist()
2941 cl.RunPostUploadHook(2, 'upstream', 'description')
2942
2943 subprocess2.Popen.assert_called_once_with([
2944 'vpython', 'PRESUBMIT_SUPPORT',
Edward Lemur75526302020-02-27 22:31:05 +00002945 '--root', 'root',
2946 '--upstream', 'upstream',
2947 '--verbose', '--verbose',
Edward Lemur99df04e2020-03-05 19:39:43 +00002948 '--author', 'author',
2949 '--gerrit_url', 'https://chromium-review.googlesource.com',
Edward Lemur75526302020-02-27 22:31:05 +00002950 '--issue', '123456',
2951 '--patchset', '7',
Edward Lemur75526302020-02-27 22:31:05 +00002952 '--post_upload',
2953 '--description_file', '/tmp/fake-temp1',
2954 ])
2955 gclient_utils.FileWrite.assert_called_once_with(
Edward Lemur1a83da12020-03-04 21:18:36 +00002956 '/tmp/fake-temp1', 'description')
Edward Lemur75526302020-02-27 22:31:05 +00002957
Edward Lemur9aa1a962020-02-25 00:58:38 +00002958
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002959class CMDTestCaseBase(unittest.TestCase):
2960 _STATUSES = [
2961 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
2962 'INFRA_FAILURE', 'CANCELED',
2963 ]
2964 _CHANGE_DETAIL = {
2965 'project': 'depot_tools',
2966 'status': 'OPEN',
2967 'owner': {'email': 'owner@e.mail'},
2968 'current_revision': 'beeeeeef',
2969 'revisions': {
2970 'deadbeaf': {'_number': 6},
2971 'beeeeeef': {
2972 '_number': 7,
2973 'fetch': {'http': {
2974 'url': 'https://chromium.googlesource.com/depot_tools',
2975 'ref': 'refs/changes/56/123456/7'
2976 }},
2977 },
2978 },
2979 }
2980 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00002981 'builds': [{
2982 'id': str(100 + idx),
2983 'builder': {
2984 'project': 'chromium',
2985 'bucket': 'try',
2986 'builder': 'bot_' + status.lower(),
2987 },
2988 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
2989 'tags': [],
2990 'status': status,
2991 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002992 }
2993
Edward Lemur4c707a22019-09-24 21:13:43 +00002994 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002995 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00002996 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00002997 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
2998 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00002999 mock.patch(
3000 'git_cl.Changelist.GetCodereviewServer',
3001 return_value='https://chromium-review.googlesource.com').start()
3002 mock.patch(
3003 'git_cl.Changelist._GetGerritHost',
3004 return_value='chromium-review.googlesource.com').start()
3005 mock.patch(
3006 'git_cl.Changelist.GetMostRecentPatchset',
3007 return_value=7).start()
3008 mock.patch(
3009 'git_cl.Changelist.GetRemoteUrl',
3010 return_value='https://chromium.googlesource.com/depot_tools').start()
3011 mock.patch(
3012 'auth.Authenticator',
3013 return_value=AuthenticatorMock()).start()
3014 mock.patch(
3015 'gerrit_util.GetChangeDetail',
3016 return_value=self._CHANGE_DETAIL).start()
3017 mock.patch(
3018 'git_cl._call_buildbucket',
3019 return_value = self._DEFAULT_RESPONSE).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003020 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003021 self.addCleanup(mock.patch.stopall)
3022
Edward Lemur4c707a22019-09-24 21:13:43 +00003023
Edward Lemur9468eba2020-02-27 19:07:22 +00003024class CMDPresubmitTestCase(CMDTestCaseBase):
3025 def setUp(self):
3026 super(CMDPresubmitTestCase, self).setUp()
3027 mock.patch(
3028 'git_cl.Changelist.GetCommonAncestorWithUpstream',
3029 return_value='upstream').start()
3030 mock.patch(
3031 'git_cl.Changelist.FetchDescription',
3032 return_value='fetch description').start()
3033 mock.patch(
3034 'git_cl.Changelist.GetLocalDescription',
3035 return_value='get description').start()
3036 mock.patch('git_cl.Changelist.RunHook').start()
3037
3038 def testDefaultCase(self):
3039 self.assertEqual(0, git_cl.main(['presubmit']))
3040 git_cl.Changelist.RunHook.assert_called_once_with(
3041 committing=True,
3042 may_prompt=False,
3043 verbose=0,
3044 parallel=None,
3045 upstream='upstream',
3046 description='fetch description',
3047 all_files=None)
3048
3049 def testNoIssue(self):
3050 git_cl.Changelist.GetIssue.return_value = None
3051 self.assertEqual(0, git_cl.main(['presubmit']))
3052 git_cl.Changelist.RunHook.assert_called_once_with(
3053 committing=True,
3054 may_prompt=False,
3055 verbose=0,
3056 parallel=None,
3057 upstream='upstream',
3058 description='get description',
3059 all_files=None)
3060
3061 def testCustomBranch(self):
3062 self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
3063 git_cl.Changelist.RunHook.assert_called_once_with(
3064 committing=True,
3065 may_prompt=False,
3066 verbose=0,
3067 parallel=None,
3068 upstream='custom_branch',
3069 description='fetch description',
3070 all_files=None)
3071
3072 def testOptions(self):
3073 self.assertEqual(
3074 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u']))
3075 git_cl.Changelist.RunHook.assert_called_once_with(
3076 committing=False,
3077 may_prompt=False,
3078 verbose=2,
3079 parallel=True,
3080 upstream='upstream',
3081 description='fetch description',
3082 all_files=True)
3083
3084
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003085class CMDTryResultsTestCase(CMDTestCaseBase):
3086 _DEFAULT_REQUEST = {
3087 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003088 "gerritChanges": [{
3089 "project": "depot_tools",
3090 "host": "chromium-review.googlesource.com",
3091 "patchset": 7,
3092 "change": 123456,
3093 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003094 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003095 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3096 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003097 }
3098
3099 def testNoJobs(self):
3100 git_cl._call_buildbucket.return_value = {}
3101
3102 self.assertEqual(0, git_cl.main(['try-results']))
3103 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3104 git_cl._call_buildbucket.assert_called_once_with(
3105 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3106 self._DEFAULT_REQUEST)
3107
3108 def testPrintToStdout(self):
3109 self.assertEqual(0, git_cl.main(['try-results']))
3110 self.assertEqual([
3111 'Successes:',
3112 ' bot_success https://ci.chromium.org/b/103',
3113 'Infra Failures:',
3114 ' bot_infra_failure https://ci.chromium.org/b/105',
3115 'Failures:',
3116 ' bot_failure https://ci.chromium.org/b/104',
3117 'Canceled:',
3118 ' bot_canceled ',
3119 'Started:',
3120 ' bot_started https://ci.chromium.org/b/102',
3121 'Scheduled:',
3122 ' bot_scheduled id=101',
3123 'Other:',
3124 ' bot_status_unspecified id=100',
3125 'Total: 7 tryjobs',
3126 ], sys.stdout.getvalue().splitlines())
3127 git_cl._call_buildbucket.assert_called_once_with(
3128 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3129 self._DEFAULT_REQUEST)
3130
3131 def testPrintToStdoutWithMasters(self):
3132 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3133 self.assertEqual([
3134 'Successes:',
3135 ' try bot_success https://ci.chromium.org/b/103',
3136 'Infra Failures:',
3137 ' try bot_infra_failure https://ci.chromium.org/b/105',
3138 'Failures:',
3139 ' try bot_failure https://ci.chromium.org/b/104',
3140 'Canceled:',
3141 ' try bot_canceled ',
3142 'Started:',
3143 ' try bot_started https://ci.chromium.org/b/102',
3144 'Scheduled:',
3145 ' try bot_scheduled id=101',
3146 'Other:',
3147 ' try bot_status_unspecified id=100',
3148 'Total: 7 tryjobs',
3149 ], sys.stdout.getvalue().splitlines())
3150 git_cl._call_buildbucket.assert_called_once_with(
3151 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3152 self._DEFAULT_REQUEST)
3153
3154 @mock.patch('git_cl.write_json')
3155 def testWriteToJson(self, mockJsonDump):
3156 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3157 git_cl._call_buildbucket.assert_called_once_with(
3158 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3159 self._DEFAULT_REQUEST)
3160 mockJsonDump.assert_called_once_with(
3161 'file.json', self._DEFAULT_RESPONSE['builds'])
3162
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003163 def test_filter_failed_for_one_simple(self):
Edward Lemur45768512020-03-02 19:03:14 +00003164 self.assertEqual([], git_cl._filter_failed_for_retry([]))
3165 self.assertEqual(
3166 [
3167 ('chromium', 'try', 'bot_failure'),
3168 ('chromium', 'try', 'bot_infra_failure'),
3169 ],
3170 git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003171
3172 def test_filter_failed_for_retry_many_builds(self):
3173
3174 def _build(name, created_sec, status, experimental=False):
3175 assert 0 <= created_sec < 100, created_sec
3176 b = {
3177 'id': 112112,
3178 'builder': {
3179 'project': 'chromium',
3180 'bucket': 'try',
3181 'builder': name,
3182 },
3183 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3184 'status': status,
3185 'tags': [],
3186 }
3187 if experimental:
3188 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3189 return b
3190
3191 builds = [
3192 _build('flaky-last-green', 1, 'FAILURE'),
3193 _build('flaky-last-green', 2, 'SUCCESS'),
3194 _build('flaky', 1, 'SUCCESS'),
3195 _build('flaky', 2, 'FAILURE'),
3196 _build('running', 1, 'FAILED'),
3197 _build('running', 2, 'SCHEDULED'),
3198 _build('yep-still-running', 1, 'STARTED'),
3199 _build('yep-still-running', 2, 'FAILURE'),
3200 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3201 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3202
3203 # Simulate experimental in CQ builder, which developer decided
3204 # to retry manually which resulted in 2nd build non-experimental.
3205 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3206 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3207 ]
3208 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
Edward Lemur45768512020-03-02 19:03:14 +00003209 self.assertEqual(
3210 [
3211 ('chromium', 'try', 'flaky'),
3212 ('chromium', 'try', 'sometimes-experimental'),
3213 ],
3214 git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003215
3216
3217class CMDTryTestCase(CMDTestCaseBase):
3218
3219 @mock.patch('git_cl.Changelist.SetCQState')
Edward Lemur45768512020-03-02 19:03:14 +00003220 def testSetCQDryRunByDefault(self, mockSetCQState):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003221 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003222 self.assertEqual(0, git_cl.main(['try']))
3223 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3224 self.assertEqual(
3225 sys.stdout.getvalue(),
3226 'Scheduling CQ dry run on: '
3227 'https://chromium-review.googlesource.com/123456\n')
3228
Edward Lemur4c707a22019-09-24 21:13:43 +00003229 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003230 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003231 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003232
3233 self.assertEqual(0, git_cl.main([
3234 'try', '-B', 'luci.chromium.try', '-b', 'win',
3235 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3236 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003237 'Scheduling jobs on:\n'
3238 ' chromium/try: win',
Edward Lemur4c707a22019-09-24 21:13:43 +00003239 git_cl.sys.stdout.getvalue())
3240
3241 expected_request = {
3242 "requests": [{
3243 "scheduleBuild": {
3244 "requestId": "uuid4",
3245 "builder": {
3246 "project": "chromium",
3247 "builder": "win",
3248 "bucket": "try",
3249 },
3250 "gerritChanges": [{
3251 "project": "depot_tools",
3252 "host": "chromium-review.googlesource.com",
3253 "patchset": 7,
3254 "change": 123456,
3255 }],
3256 "properties": {
3257 "category": "git_cl_try",
3258 "json": [{"a": 1}, None],
3259 "key": "val",
3260 },
3261 "tags": [
3262 {"value": "win", "key": "builder"},
3263 {"value": "git_cl_try", "key": "user_agent"},
3264 ],
3265 },
3266 }],
3267 }
3268 mockCallBuildbucket.assert_called_with(
3269 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3270
Anthony Polito1a5fe232020-01-24 23:17:52 +00003271 @mock.patch('git_cl._call_buildbucket')
3272 def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
3273 mockCallBuildbucket.return_value = {}
3274
3275 self.assertEqual(0, git_cl.main([
3276 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
3277 '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
3278 '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
3279 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003280 'Scheduling jobs on:\n'
3281 ' chromium/try: linux\n'
3282 ' chromium/try: win',
Anthony Polito1a5fe232020-01-24 23:17:52 +00003283 git_cl.sys.stdout.getvalue())
3284
3285 expected_request = {
3286 "requests": [{
3287 "scheduleBuild": {
3288 "requestId": "uuid4",
3289 "builder": {
3290 "project": "chromium",
3291 "builder": "linux",
3292 "bucket": "try",
3293 },
3294 "gerritChanges": [{
3295 "project": "depot_tools",
3296 "host": "chromium-review.googlesource.com",
3297 "patchset": 7,
3298 "change": 123456,
3299 }],
3300 "properties": {
3301 "category": "git_cl_try",
3302 "json": [{"a": 1}, None],
3303 "key": "val",
3304 },
3305 "tags": [
3306 {"value": "linux", "key": "builder"},
3307 {"value": "git_cl_try", "key": "user_agent"},
3308 ],
3309 "gitilesCommit": {
3310 "host": "chromium-review.googlesource.com",
3311 "project": "depot_tools",
3312 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3313 }
3314 },
3315 },
3316 {
3317 "scheduleBuild": {
3318 "requestId": "uuid4",
3319 "builder": {
3320 "project": "chromium",
3321 "builder": "win",
3322 "bucket": "try",
3323 },
3324 "gerritChanges": [{
3325 "project": "depot_tools",
3326 "host": "chromium-review.googlesource.com",
3327 "patchset": 7,
3328 "change": 123456,
3329 }],
3330 "properties": {
3331 "category": "git_cl_try",
3332 "json": [{"a": 1}, None],
3333 "key": "val",
3334 },
3335 "tags": [
3336 {"value": "win", "key": "builder"},
3337 {"value": "git_cl_try", "key": "user_agent"},
3338 ],
3339 "gitilesCommit": {
3340 "host": "chromium-review.googlesource.com",
3341 "project": "depot_tools",
3342 "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
3343 }
3344 },
3345 }],
3346 }
3347 mockCallBuildbucket.assert_called_with(
3348 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3349
Edward Lemur45768512020-03-02 19:03:14 +00003350 @mock.patch('sys.stderr', StringIO())
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003351 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur45768512020-03-02 19:03:14 +00003352 with self.assertRaises(SystemExit):
3353 git_cl.main([
3354 'try', '-B', 'not-a-bucket', '-b', 'win',
3355 '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
Edward Lemur4c707a22019-09-24 21:13:43 +00003356 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003357 'Invalid bucket: not-a-bucket.',
3358 sys.stderr.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003359
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003360 @mock.patch('git_cl._call_buildbucket')
Quinten Yearsley777660f2020-03-04 23:37:06 +00003361 @mock.patch('git_cl._fetch_tryjobs')
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003362 def testScheduleOnBuildbucketRetryFailed(
3363 self, mockFetchTryJobs, mockCallBuildbucket):
Quinten Yearsley777660f2020-03-04 23:37:06 +00003364 git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003365 7: [],
3366 6: [{
3367 'id': 112112,
3368 'builder': {
3369 'project': 'chromium',
3370 'bucket': 'try',
Quinten Yearsley777660f2020-03-04 23:37:06 +00003371 'builder': 'linux', },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003372 'createTime': '2019-10-09T08:00:01.854286Z',
3373 'tags': [],
Quinten Yearsley777660f2020-03-04 23:37:06 +00003374 'status': 'FAILURE', }], }[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003375 mockCallBuildbucket.return_value = {}
3376
3377 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3378 self.assertIn(
Edward Lemur45768512020-03-02 19:03:14 +00003379 'Scheduling jobs on:\n'
3380 ' chromium/try: linux',
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003381 git_cl.sys.stdout.getvalue())
3382
3383 expected_request = {
3384 "requests": [{
3385 "scheduleBuild": {
3386 "requestId": "uuid4",
3387 "builder": {
3388 "project": "chromium",
3389 "bucket": "try",
3390 "builder": "linux",
3391 },
3392 "gerritChanges": [{
3393 "project": "depot_tools",
3394 "host": "chromium-review.googlesource.com",
3395 "patchset": 7,
3396 "change": 123456,
3397 }],
3398 "properties": {
3399 "category": "git_cl_try",
3400 },
3401 "tags": [
3402 {"value": "linux", "key": "builder"},
3403 {"value": "git_cl_try", "key": "user_agent"},
3404 {"value": "1", "key": "retry_failed"},
3405 ],
3406 },
3407 }],
3408 }
3409 mockCallBuildbucket.assert_called_with(
3410 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3411
Edward Lemur4c707a22019-09-24 21:13:43 +00003412 def test_parse_bucket(self):
3413 test_cases = [
3414 {
3415 'bucket': 'chromium/try',
3416 'result': ('chromium', 'try'),
3417 },
3418 {
3419 'bucket': 'luci.chromium.try',
3420 'result': ('chromium', 'try'),
3421 'has_warning': True,
3422 },
3423 {
3424 'bucket': 'skia.primary',
3425 'result': ('skia', 'skia.primary'),
3426 'has_warning': True,
3427 },
3428 {
3429 'bucket': 'not-a-bucket',
3430 'result': (None, None),
3431 },
3432 ]
3433
3434 for test_case in test_cases:
3435 git_cl.sys.stdout.truncate(0)
3436 self.assertEqual(
3437 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3438 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003439 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3440 test_case['result'])
3441 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003442
3443
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003444class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003445
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003446 def setUp(self):
3447 super(CMDUploadTestCase, self).setUp()
Quinten Yearsley777660f2020-03-04 23:37:06 +00003448 mock.patch('git_cl._fetch_tryjobs').start()
3449 mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003450 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003451 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003452 self.addCleanup(mock.patch.stopall)
3453
Edward Lesmes7677e5c2020-02-19 20:39:03 +00003454 def testWarmUpChangeDetailCache(self):
3455 self.assertEqual(0, git_cl.main(['upload']))
3456 gerrit_util.GetChangeDetail.assert_called_once_with(
3457 'chromium-review.googlesource.com', 'depot_tools~123456',
3458 frozenset([
3459 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
3460 'CURRENT_COMMIT']))
3461
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003462 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003463 # This test mocks out the actual upload part, and just asserts that after
3464 # upload, if --retry-failed is added, then the tool will fetch try jobs
3465 # from the previous patchset and trigger the right builders on the latest
3466 # patchset.
Quinten Yearsley777660f2020-03-04 23:37:06 +00003467 git_cl._fetch_tryjobs.side_effect = [
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003468 # Latest patchset: No builds.
3469 [],
3470 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003471 [{
3472 'id': str(100 + idx),
3473 'builder': {
3474 'project': 'chromium',
3475 'bucket': 'try',
3476 'builder': 'bot_' + status.lower(),
3477 },
3478 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3479 'tags': [],
3480 'status': status,
3481 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003482 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003483
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003484 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003485 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003486 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3487 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Quinten Yearsley777660f2020-03-04 23:37:06 +00003488 ], git_cl._fetch_tryjobs.mock_calls)
Edward Lemur45768512020-03-02 19:03:14 +00003489 expected_buckets = [
3490 ('chromium', 'try', 'bot_failure'),
3491 ('chromium', 'try', 'bot_infra_failure'),
3492 ]
Quinten Yearsley777660f2020-03-04 23:37:06 +00003493 git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
3494 mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003495
Brian Sheedy59b06a82019-10-14 17:03:29 +00003496
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +00003497class MakeRequestsHelperTestCase(unittest.TestCase):
3498
3499 def exampleGerritChange(self):
3500 return {
3501 'host': 'chromium-review.googlesource.com',
3502 'project': 'depot_tools',
3503 'change': 1,
3504 'patchset': 2,
3505 }
3506
3507 def testMakeRequestsHelperNoOptions(self):
3508 # Basic test for the helper function _make_tryjob_schedule_requests;
3509 # it shouldn't throw AttributeError even when options doesn't have any
3510 # of the expected values; it will use default option values.
3511 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3512 jobs = [('chromium', 'try', 'my-builder')]
3513 options = optparse.Values()
3514 requests = git_cl._make_tryjob_schedule_requests(
3515 changelist, jobs, options, patchset=None)
3516
3517 # requestId is non-deterministic. Just assert that it's there and has
3518 # a particular length.
3519 self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
3520 self.assertEqual(requests, [{
3521 'scheduleBuild': {
3522 'builder': {
3523 'bucket': 'try',
3524 'builder': 'my-builder',
3525 'project': 'chromium'
3526 },
3527 'gerritChanges': [self.exampleGerritChange()],
3528 'properties': {
3529 'category': 'git_cl_try'
3530 },
3531 'tags': [{
3532 'key': 'builder',
3533 'value': 'my-builder'
3534 }, {
3535 'key': 'user_agent',
3536 'value': 'git_cl_try'
3537 }]
3538 }
3539 }])
3540
3541 def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
3542 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3543 jobs = [('chromium', 'try', 'presubmit')]
3544 options = optparse.Values()
3545 requests = git_cl._make_tryjob_schedule_requests(
3546 changelist, jobs, options, patchset=None)
3547 self.assertEqual(requests[0]['scheduleBuild']['properties'], {
3548 'category': 'git_cl_try',
3549 'dry_run': 'true'
3550 })
3551
3552 def testMakeRequestsHelperRevisionSet(self):
3553 # Gitiles commit is specified when revision is in options.
3554 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3555 jobs = [('chromium', 'try', 'my-builder')]
3556 options = optparse.Values({'revision': 'ba5eba11'})
3557 requests = git_cl._make_tryjob_schedule_requests(
3558 changelist, jobs, options, patchset=None)
3559 self.assertEqual(
3560 requests[0]['scheduleBuild']['gitilesCommit'], {
3561 'host': 'chromium-review.googlesource.com',
3562 'id': 'ba5eba11',
3563 'project': 'depot_tools'
3564 })
3565
3566 def testMakeRequestsHelperRetryFailedSet(self):
3567 # An extra tag is added when retry_failed is in options.
3568 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3569 jobs = [('chromium', 'try', 'my-builder')]
3570 options = optparse.Values({'retry_failed': 'true'})
3571 requests = git_cl._make_tryjob_schedule_requests(
3572 changelist, jobs, options, patchset=None)
3573 self.assertEqual(
3574 requests[0]['scheduleBuild']['tags'], [
3575 {
3576 'key': 'builder',
3577 'value': 'my-builder'
3578 },
3579 {
3580 'key': 'user_agent',
3581 'value': 'git_cl_try'
3582 },
3583 {
3584 'key': 'retry_failed',
3585 'value': '1'
3586 }
3587 ])
3588
3589 def testMakeRequestsHelperCategorySet(self):
3590 # The category property can be overriden with options.
3591 changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
3592 jobs = [('chromium', 'try', 'my-builder')]
3593 options = optparse.Values({'category': 'my-special-category'})
3594 requests = git_cl._make_tryjob_schedule_requests(
3595 changelist, jobs, options, patchset=None)
3596 self.assertEqual(requests[0]['scheduleBuild']['properties'],
3597 {'category': 'my-special-category'})
3598
3599
Edward Lemurda4b6c62020-02-13 00:28:40 +00003600class CMDFormatTestCase(unittest.TestCase):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003601
3602 def setUp(self):
3603 super(CMDFormatTestCase, self).setUp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003604 mock.patch('git_cl.RunCommand').start()
3605 mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
3606 mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
3607 mock.patch('git_cl.settings').start()
Brian Sheedy59b06a82019-10-14 17:03:29 +00003608 self._top_dir = tempfile.mkdtemp()
Jamie Madill5e96ad12020-01-13 16:08:35 +00003609 self.addCleanup(mock.patch.stopall)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003610
3611 def tearDown(self):
3612 shutil.rmtree(self._top_dir)
3613 super(CMDFormatTestCase, self).tearDown()
3614
Jamie Madill5e96ad12020-01-13 16:08:35 +00003615 def _make_temp_file(self, fname, contents):
3616 with open(os.path.join(self._top_dir, fname), 'w') as tf:
3617 tf.write('\n'.join(contents))
3618
Brian Sheedy59b06a82019-10-14 17:03:29 +00003619 def _make_yapfignore(self, contents):
Jamie Madill5e96ad12020-01-13 16:08:35 +00003620 self._make_temp_file('.yapfignore', contents)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003621
Brian Sheedyb4307d52019-12-02 19:18:17 +00003622 def _check_yapf_filtering(self, files, expected):
3623 self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
3624 files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
Brian Sheedy59b06a82019-10-14 17:03:29 +00003625
Edward Lemur1a83da12020-03-04 21:18:36 +00003626 def _run_command_mock(self, return_value):
3627 def f(*args, **kwargs):
3628 if 'stdin' in kwargs:
3629 self.assertIsInstance(kwargs['stdin'], bytes)
3630 return return_value
3631 return f
3632
Jamie Madill5e96ad12020-01-13 16:08:35 +00003633 def testClangFormatDiffFull(self):
3634 self._make_temp_file('test.cc', ['// test'])
3635 git_cl.settings.GetFormatFullByDefault.return_value = False
3636 diff_file = [os.path.join(self._top_dir, 'test.cc')]
3637 mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
3638
3639 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003640 git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003641 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3642 self._top_dir, 'HEAD')
3643 self.assertEqual(2, return_value)
3644
3645 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003646 git_cl.RunCommand.side_effect = self._run_command_mock('// test')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003647 return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
3648 self._top_dir, 'HEAD')
3649 self.assertEqual(0, return_value)
3650
3651 def testClangFormatDiff(self):
3652 git_cl.settings.GetFormatFullByDefault.return_value = False
3653 mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
3654
3655 # Diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003656 git_cl.RunCommand.side_effect = self._run_command_mock('error')
3657 return_value = git_cl._RunClangFormatDiff(
3658 mock_opts, ['.'], self._top_dir, 'HEAD')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003659 self.assertEqual(2, return_value)
3660
3661 # No diff
Edward Lemur1a83da12020-03-04 21:18:36 +00003662 git_cl.RunCommand.side_effect = self._run_command_mock('')
Jamie Madill5e96ad12020-01-13 16:08:35 +00003663 return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
3664 'HEAD')
3665 self.assertEqual(0, return_value)
3666
Brian Sheedyb4307d52019-12-02 19:18:17 +00003667 def testYapfignoreExplicit(self):
3668 self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
3669 files = [
3670 'bar.py',
3671 'foo/bar.py',
3672 'foo/baz.py',
3673 'foo/bar/baz.py',
3674 'foo/bar/foobar.py',
3675 ]
3676 expected = [
3677 'bar.py',
3678 'foo/baz.py',
3679 'foo/bar/foobar.py',
3680 ]
3681 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003682
Brian Sheedyb4307d52019-12-02 19:18:17 +00003683 def testYapfignoreSingleWildcards(self):
3684 self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
3685 files = [
3686 'bar.py', # Matched by *bar.py.
3687 'bar.txt',
3688 'foobar.py', # Matched by *bar.py, foo*.
3689 'foobar.txt', # Matched by foo*.
3690 'bazbar.py', # Matched by *bar.py, baz*.py.
3691 'bazbar.txt',
3692 'foo/baz.txt', # Matched by foo*.
3693 'bar/bar.py', # Matched by *bar.py.
3694 'baz/foo.py', # Matched by baz*.py, foo*.
3695 'baz/foo.txt',
3696 ]
3697 expected = [
3698 'bar.txt',
3699 'bazbar.txt',
3700 'baz/foo.txt',
3701 ]
3702 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003703
Brian Sheedyb4307d52019-12-02 19:18:17 +00003704 def testYapfignoreMultiplewildcards(self):
3705 self._make_yapfignore(['*bar*', '*foo*baz.txt'])
3706 files = [
3707 'bar.py', # Matched by *bar*.
3708 'bar.txt', # Matched by *bar*.
3709 'abar.py', # Matched by *bar*.
3710 'foobaz.txt', # Matched by *foo*baz.txt.
3711 'foobaz.py',
3712 'afoobaz.txt', # Matched by *foo*baz.txt.
3713 ]
3714 expected = [
3715 'foobaz.py',
3716 ]
3717 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003718
3719 def testYapfignoreComments(self):
3720 self._make_yapfignore(['test.py', '#test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003721 files = [
3722 'test.py',
3723 'test2.py',
3724 ]
3725 expected = [
3726 'test2.py',
3727 ]
3728 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003729
3730 def testYapfignoreBlankLines(self):
3731 self._make_yapfignore(['test.py', '', '', 'test2.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003732 files = [
3733 'test.py',
3734 'test2.py',
3735 'test3.py',
3736 ]
3737 expected = [
3738 'test3.py',
3739 ]
3740 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003741
3742 def testYapfignoreWhitespace(self):
3743 self._make_yapfignore([' test.py '])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003744 files = [
3745 'test.py',
3746 'test2.py',
3747 ]
3748 expected = [
3749 'test2.py',
3750 ]
3751 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003752
Brian Sheedyb4307d52019-12-02 19:18:17 +00003753 def testYapfignoreNoFiles(self):
Brian Sheedy59b06a82019-10-14 17:03:29 +00003754 self._make_yapfignore(['test.py'])
Brian Sheedyb4307d52019-12-02 19:18:17 +00003755 self._check_yapf_filtering([], [])
3756
3757 def testYapfignoreMissingYapfignore(self):
3758 files = [
3759 'test.py',
3760 ]
3761 expected = [
3762 'test.py',
3763 ]
3764 self._check_yapf_filtering(files, expected)
Brian Sheedy59b06a82019-10-14 17:03:29 +00003765
3766
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003767if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003768 logging.basicConfig(
3769 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003770 unittest.main()