blob: e1b2266dd82da117159964789c93c48fd3a0b6d1 [file] [log] [blame]
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001#!/usr/bin/env python
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Unit tests for git_cl.py."""
7
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01008import datetime
tandriide281ae2016-10-12 06:02:30 -07009import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010010import logging
maruel@chromium.orgddd59412011-11-30 14:20:38 +000011import os
Brian Sheedy59b06a82019-10-14 17:03:29 +000012import shutil
maruel@chromium.orga3353652011-11-30 14:26:57 +000013import StringIO
maruel@chromium.orgddd59412011-11-30 14:20:38 +000014import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070015import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000016import unittest
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +000017import urlparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000018
19sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
20
21from testing_support.auto_stub import TestCase
Edward Lemur4c707a22019-09-24 21:13:43 +000022from third_party import mock
maruel@chromium.orgddd59412011-11-30 14:20:38 +000023
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000024import metrics
25# We have to disable monitoring before importing git_cl.
26metrics.DISABLE_METRICS_COLLECTION = True
27
Eric Boren2fb63102018-10-05 13:05:03 +000028import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000029import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000030import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000031import git_footers
maruel@chromium.orgddd59412011-11-30 14:20:38 +000032import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000033
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000034
tandrii5d48c322016-08-18 16:19:37 -070035def callError(code=1, cmd='', cwd='', stdout='', stderr=''):
36 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
37
38
Edward Lemur4c707a22019-09-24 21:13:43 +000039def _constantFn(return_value):
40 def f(*args, **kwargs):
41 return return_value
42 return f
43
44
tandrii5d48c322016-08-18 16:19:37 -070045CERR1 = callError(1)
46
47
Aaron Gable9a03ae02017-11-03 11:31:07 -070048def MakeNamedTemporaryFileMock(expected_content):
49 class NamedTemporaryFileMock(object):
50 def __init__(self, *args, **kwargs):
51 self.name = '/tmp/named'
52 self.expected_content = expected_content
53
54 def __enter__(self):
55 return self
56
57 def __exit__(self, _type, _value, _tb):
58 pass
59
60 def write(self, content):
61 if self.expected_content:
62 assert content == self.expected_content
63
64 def close(self):
65 pass
66
67 return NamedTemporaryFileMock
68
69
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000070class ChangelistMock(object):
71 # A class variable so we can access it when we don't have access to the
72 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000073 desc = ''
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000074 def __init__(self, **kwargs):
75 pass
76 def GetIssue(self):
77 return 1
Kenneth Russell61e2ed42017-02-15 11:47:13 -080078 def GetDescription(self, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000079 return ChangelistMock.desc
dsansomee2d6fd92016-09-08 00:10:47 -070080 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000081 ChangelistMock.desc = desc
82
tandrii5d48c322016-08-18 16:19:37 -070083
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000084class PresubmitMock(object):
85 def __init__(self, *args, **kwargs):
86 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080087 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
88
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000089 @staticmethod
90 def should_continue():
91 return True
92
93
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000094class WatchlistsMock(object):
95 def __init__(self, _):
96 pass
97 @staticmethod
98 def GetWatchersForPaths(_):
99 return ['joe@example.com']
100
101
Edward Lemur4c707a22019-09-24 21:13:43 +0000102class CodereviewSettingsFileMock(object):
103 def __init__(self):
104 pass
105 # pylint: disable=no-self-use
106 def read(self):
107 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
108 'GERRIT_HOST: True\n')
109
110
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000111class AuthenticatorMock(object):
112 def __init__(self, *_args):
113 pass
114 def has_cached_credentials(self):
115 return True
tandrii221ab252016-10-06 08:12:04 -0700116 def authorize(self, http):
117 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000118
119
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100120def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000121 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
122
123 Usage:
124 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100125 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000126
127 OR
128 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100129 CookiesAuthenticatorMockFactory(
130 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000131 """
132 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800133 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000134 # Intentionally not calling super() because it reads actual cookie files.
135 pass
136 @classmethod
137 def get_gitcookies_path(cls):
138 return '~/.gitcookies'
139 @classmethod
140 def get_netrc_path(cls):
141 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100142 def _get_auth_for_host(self, host):
143 if same_auth:
144 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000145 return (hosts_with_creds or {}).get(host)
146 return CookiesAuthenticatorMock
147
Aaron Gable9a03ae02017-11-03 11:31:07 -0700148
kmarshall9249e012016-08-23 12:02:16 -0700149class MockChangelistWithBranchAndIssue():
150 def __init__(self, branch, issue):
151 self.branch = branch
152 self.issue = issue
153 def GetBranch(self):
154 return self.branch
155 def GetIssue(self):
156 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000157
tandriic2405f52016-10-10 08:13:15 -0700158
159class SystemExitMock(Exception):
160 pass
161
162
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000163class TestGitClBasic(unittest.TestCase):
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100164 def test_get_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000165 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100166 cl.description = 'x'
167 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000168 cl.FetchDescription = lambda *a, **kw: 'y'
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000169 self.assertEqual(cl.GetDescription(), 'x')
170 self.assertEqual(cl.GetDescription(force=True), 'y')
171 self.assertEqual(cl.GetDescription(), 'y')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100172
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700173 def test_description_footers(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000174 cl = git_cl.Changelist(issue=1, codereview_host='host')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700175 cl.description = '\n'.join([
176 'This is some message',
177 '',
178 'It has some lines',
179 'and, also',
180 '',
181 'Some: Really',
182 'Awesome: Footers',
183 ])
184 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000185 cl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700186 msg, footers = cl.GetDescriptionFooters()
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000187 self.assertEqual(
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700188 msg, ['This is some message', '', 'It has some lines', 'and, also'])
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000189 self.assertEqual(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700190
191 msg.append('wut')
192 footers.append(('gnarly-dude', 'beans'))
193 cl.UpdateDescriptionFooters(msg, footers)
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000194 self.assertEqual(cl.GetDescription().splitlines(), [
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700195 'This is some message',
196 '',
197 'It has some lines',
198 'and, also',
199 'wut'
200 '',
201 'Some: Really',
202 'Awesome: Footers',
203 'Gnarly-Dude: beans',
204 ])
205
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000206 def test_set_preserve_tryjobs(self):
207 d = git_cl.ChangeDescription('Simple.')
208 d.set_preserve_tryjobs()
209 self.assertEqual(d.description.splitlines(), [
210 'Simple.',
211 '',
212 'Cq-Do-Not-Cancel-Tryjobs: true',
213 ])
214 before = d.description
215 d.set_preserve_tryjobs()
216 self.assertEqual(before, d.description)
217
218 d = git_cl.ChangeDescription('\n'.join([
219 'One is enough',
220 '',
221 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
222 'Change-Id: Ideadbeef',
223 ]))
224 d.set_preserve_tryjobs()
225 self.assertEqual(d.description.splitlines(), [
226 'One is enough',
227 '',
228 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
229 'Change-Id: Ideadbeef',
230 'Cq-Do-Not-Cancel-Tryjobs: true',
231 ])
232
tandriif9aefb72016-07-01 09:06:51 -0700233 def test_get_bug_line_values(self):
234 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
235 self.assertEqual(f('', ''), [])
236 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
237 self.assertEqual(f('v8', '456'), ['v8:456'])
238 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
239 # Not nice, but not worth carying.
240 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
241 ['v8:456', 'chromium:123', 'v8:123'])
242
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100243 def _test_git_number(self, parent_msg, dest_ref, child_msg,
244 parent_hash='parenthash'):
245 desc = git_cl.ChangeDescription(child_msg)
246 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
247 return desc.description
248
249 def assertEqualByLine(self, actual, expected):
250 self.assertEqual(actual.splitlines(), expected.splitlines())
251
252 def test_git_number_bad_parent(self):
253 with self.assertRaises(ValueError):
254 self._test_git_number('Parent', 'refs/heads/master', 'Child')
255
256 def test_git_number_bad_parent_footer(self):
257 with self.assertRaises(AssertionError):
258 self._test_git_number(
259 'Parent\n'
260 '\n'
261 'Cr-Commit-Position: wrong',
262 'refs/heads/master', 'Child')
263
264 def test_git_number_bad_lineage_ignored(self):
265 actual = self._test_git_number(
266 'Parent\n'
267 '\n'
268 'Cr-Commit-Position: refs/heads/master@{#1}\n'
269 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
270 'refs/heads/master', 'Child')
271 self.assertEqualByLine(
272 actual,
273 'Child\n'
274 '\n'
275 'Cr-Commit-Position: refs/heads/master@{#2}\n'
276 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
277
278 def test_git_number_same_branch(self):
279 actual = self._test_git_number(
280 'Parent\n'
281 '\n'
282 'Cr-Commit-Position: refs/heads/master@{#12}',
283 dest_ref='refs/heads/master',
284 child_msg='Child')
285 self.assertEqualByLine(
286 actual,
287 'Child\n'
288 '\n'
289 'Cr-Commit-Position: refs/heads/master@{#13}')
290
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200291 def test_git_number_same_branch_mixed_footers(self):
292 actual = self._test_git_number(
293 'Parent\n'
294 '\n'
295 'Cr-Commit-Position: refs/heads/master@{#12}',
296 dest_ref='refs/heads/master',
297 child_msg='Child\n'
298 '\n'
299 'Broken-by: design\n'
300 'BUG=123')
301 self.assertEqualByLine(
302 actual,
303 'Child\n'
304 '\n'
305 'Broken-by: design\n'
306 'BUG=123\n'
307 'Cr-Commit-Position: refs/heads/master@{#13}')
308
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100309 def test_git_number_same_branch_with_originals(self):
310 actual = self._test_git_number(
311 'Parent\n'
312 '\n'
313 'Cr-Commit-Position: refs/heads/master@{#12}',
314 dest_ref='refs/heads/master',
315 child_msg='Child\n'
316 '\n'
317 'Some users are smart and insert their own footers\n'
318 '\n'
319 'Cr-Whatever: value\n'
320 'Cr-Commit-Position: refs/copy/paste@{#22}')
321 self.assertEqualByLine(
322 actual,
323 'Child\n'
324 '\n'
325 'Some users are smart and insert their own footers\n'
326 '\n'
327 'Cr-Original-Whatever: value\n'
328 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
329 'Cr-Commit-Position: refs/heads/master@{#13}')
330
331 def test_git_number_new_branch(self):
332 actual = self._test_git_number(
333 'Parent\n'
334 '\n'
335 'Cr-Commit-Position: refs/heads/master@{#12}',
336 dest_ref='refs/heads/branch',
337 child_msg='Child')
338 self.assertEqualByLine(
339 actual,
340 'Child\n'
341 '\n'
342 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
343 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
344
345 def test_git_number_lineage(self):
346 actual = self._test_git_number(
347 'Parent\n'
348 '\n'
349 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
350 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
351 dest_ref='refs/heads/branch',
352 child_msg='Child')
353 self.assertEqualByLine(
354 actual,
355 'Child\n'
356 '\n'
357 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
358 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
359
360 def test_git_number_moooooooore_lineage(self):
361 actual = self._test_git_number(
362 'Parent\n'
363 '\n'
364 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
365 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
366 dest_ref='refs/heads/mooore',
367 child_msg='Child')
368 self.assertEqualByLine(
369 actual,
370 'Child\n'
371 '\n'
372 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
373 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
374 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
375
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100376 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700377 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100378 actual = self._test_git_number(
379 'CQ commit on fresh new branch + numbering.\n'
380 '\n'
381 'NOTRY=True\n'
382 'NOPRESUBMIT=True\n'
383 'BUG=\n'
384 '\n'
385 'Review-Url: https://codereview.chromium.org/2577703003\n'
386 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
387 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
388 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
389 dest_ref='refs/heads/gnumb-test/cl',
390 child_msg='git cl on fresh new branch + numbering.\n'
391 '\n'
392 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
393 self.assertEqualByLine(
394 actual,
395 'git cl on fresh new branch + numbering.\n'
396 '\n'
397 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
398 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
399 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
400 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
401 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100402
403 def test_git_number_cherry_pick(self):
404 actual = self._test_git_number(
405 'Parent\n'
406 '\n'
407 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
408 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
409 dest_ref='refs/heads/branch',
410 child_msg='Child, which is cherry-pick from master\n'
411 '\n'
412 'Cr-Commit-Position: refs/heads/master@{#100}\n'
413 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
414 self.assertEqualByLine(
415 actual,
416 'Child, which is cherry-pick from master\n'
417 '\n'
418 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
419 '\n'
420 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
421 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
422 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
423
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000424 def test_valid_accounts(self):
425 mock_per_account = {
426 'u1': None, # 404, doesn't exist.
427 'u2': {
428 '_account_id': 123124,
429 'avatars': [],
430 'email': 'u2@example.com',
431 'name': 'User Number 2',
432 'status': 'OOO',
433 },
434 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
435 }
436 def GetAccountDetailsMock(_, account):
437 # Poor-man's mock library's side_effect.
438 v = mock_per_account.pop(account)
439 if isinstance(v, Exception):
440 raise v
441 return v
442
443 original = git_cl.gerrit_util.GetAccountDetails
444 try:
445 git_cl.gerrit_util.GetAccountDetails = GetAccountDetailsMock
446 actual = git_cl.gerrit_util.ValidAccounts(
447 'host', ['u1', 'u2', 'u3'], max_threads=1)
448 finally:
449 git_cl.gerrit_util.GetAccountDetails = original
450 self.assertEqual(actual, {
451 'u2': {
452 '_account_id': 123124,
453 'avatars': [],
454 'email': 'u2@example.com',
455 'name': 'User Number 2',
456 'status': 'OOO',
457 },
458 })
459
460
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200461class TestParseIssueURL(unittest.TestCase):
462 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000463 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200464 self.assertIsNotNone(parsed)
465 if fail:
466 self.assertFalse(parsed.valid)
467 return
468 self.assertTrue(parsed.valid)
469 self.assertEqual(parsed.issue, issue)
470 self.assertEqual(parsed.patchset, patchset)
471 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200472
Edward Lemur678a6842019-10-03 22:25:05 +0000473 def test_ParseIssueNumberArgument(self):
474 def test(arg, *args, **kwargs):
475 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200476
Edward Lemur678a6842019-10-03 22:25:05 +0000477 test('123', 123)
478 test('', fail=True)
479 test('abc', fail=True)
480 test('123/1', fail=True)
481 test('123a', fail=True)
482 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200483
Edward Lemur678a6842019-10-03 22:25:05 +0000484 test('https://codereview.source.com/123',
485 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200486 test('http://chrome-review.source.com/c/123',
487 123, None, 'chrome-review.source.com')
488 test('https://chrome-review.source.com/c/123/',
489 123, None, 'chrome-review.source.com')
490 test('https://chrome-review.source.com/c/123/4',
491 123, 4, 'chrome-review.source.com')
492 test('https://chrome-review.source.com/#/c/123/4',
493 123, 4, 'chrome-review.source.com')
494 test('https://chrome-review.source.com/c/123/4',
495 123, 4, 'chrome-review.source.com')
496 test('https://chrome-review.source.com/123',
497 123, None, 'chrome-review.source.com')
498 test('https://chrome-review.source.com/123/4',
499 123, 4, 'chrome-review.source.com')
500
Edward Lemur678a6842019-10-03 22:25:05 +0000501 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200502 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
503 test('https://chrome-review.source.com/c/abc/', fail=True)
504 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
505
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200506
507
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100508class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100509 def setUp(self):
510 super(GitCookiesCheckerTest, self).setUp()
511 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100512 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100513
514 def mock_hosts_creds(self, subhost_identity_pairs):
515 def ensure_googlesource(h):
516 if not h.endswith(self.c._GOOGLESOURCE):
517 assert not h.endswith('.')
518 return h + '.' + self.c._GOOGLESOURCE
519 return h
520 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
521 for h, i in subhost_identity_pairs]
522
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200523 def test_identity_parsing(self):
524 self.assertEqual(self.c._parse_identity('ldap.google.com'),
525 ('ldap', 'google.com'))
526 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
527 ('ldap', 'example.com'))
528 # Specical case because we know there are no subdomains in chromium.org.
529 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
530 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800531 # Pathological: ".period." can be either username OR domain, more likely
532 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200533 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
534 ('note', 'period.example.com'))
535
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100536 def test_analysis_nothing(self):
537 self.c._all_hosts = []
538 self.assertFalse(self.c.has_generic_host())
539 self.assertEqual(set(), self.c.get_conflicting_hosts())
540 self.assertEqual(set(), self.c.get_duplicated_hosts())
541 self.assertEqual(set(), self.c.get_partially_configured_hosts())
542 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
543
544 def test_analysis(self):
545 self.mock_hosts_creds([
546 ('.googlesource.com', 'git-example.chromium.org'),
547
548 ('chromium', 'git-example.google.com'),
549 ('chromium-review', 'git-example.google.com'),
550 ('chrome-internal', 'git-example.chromium.org'),
551 ('chrome-internal-review', 'git-example.chromium.org'),
552 ('conflict', 'git-example.google.com'),
553 ('conflict-review', 'git-example.chromium.org'),
554 ('dup', 'git-example.google.com'),
555 ('dup', 'git-example.google.com'),
556 ('dup-review', 'git-example.google.com'),
557 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200558 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100559 ])
560 self.assertTrue(self.c.has_generic_host())
561 self.assertEqual(set(['conflict.googlesource.com']),
562 self.c.get_conflicting_hosts())
563 self.assertEqual(set(['dup.googlesource.com']),
564 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200565 self.assertEqual(set(['partial.googlesource.com',
566 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100567 self.c.get_partially_configured_hosts())
568 self.assertEqual(set(['chromium.googlesource.com',
569 'chrome-internal.googlesource.com']),
570 self.c.get_hosts_with_wrong_identities())
571
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100572 def test_report_no_problems(self):
573 self.test_analysis_nothing()
574 self.mock(sys, 'stdout', StringIO.StringIO())
575 self.assertFalse(self.c.find_and_report_problems())
576 self.assertEqual(sys.stdout.getvalue(), '')
577
578 def test_report(self):
579 self.test_analysis()
580 self.mock(sys, 'stdout', StringIO.StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200581 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
582 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100583 self.assertTrue(self.c.find_and_report_problems())
584 with open(os.path.join(os.path.dirname(__file__),
585 'git_cl_creds_check_report.txt')) as f:
586 expected = f.read()
587 def by_line(text):
588 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700589 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200590 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100591
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800592
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000593class TestGitCl(TestCase):
594 def setUp(self):
595 super(TestGitCl, self).setUp()
596 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700597 self._calls_done = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000598 self.mock(git_cl, 'time_time',
599 lambda: self._mocked_call('time.time'))
600 self.mock(git_cl.metrics.collector, 'add_repeated',
601 lambda *a: self._mocked_call('add_repeated', *a))
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000602 self.mock(subprocess2, 'call', self._mocked_call)
603 self.mock(subprocess2, 'check_call', self._mocked_call)
604 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700605 self.mock(subprocess2, 'communicate',
606 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000607 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000608 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000609 self.mock(git_common, 'get_or_create_merge_base',
610 lambda *a: (
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000611 self._mocked_call(['get_or_create_merge_base'] + list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000612 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000613 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000614 self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
615 self._mocked_call('SaveDescriptionBackup'))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100616 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000617 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700618 self.mock(git_cl, 'write_json', lambda path, contents:
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000619 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000620 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000621 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
Edward Lemur5b929a42019-10-21 17:57:39 +0000622 self.mock(git_cl.auth, 'Authenticator', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100623 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
624 lambda *args, **kwargs: self._mocked_call(
625 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700626 self.mock(git_cl.gerrit_util, 'GetChangeComments',
627 lambda *args, **kwargs: self._mocked_call(
628 'GetChangeComments', *args, **kwargs))
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000629 self.mock(git_cl.gerrit_util, 'GetChangeRobotComments',
630 lambda *args, **kwargs: self._mocked_call(
631 'GetChangeRobotComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100632 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700633 lambda h, i, reviewers, ccs, notify: self._mocked_call(
634 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700635 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700636 lambda h, i, msg=None, labels=None, notify=None:
637 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700638 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
639 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000640 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
641 classmethod(lambda _: False))
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000642 self.mock(git_cl.gerrit_util, 'ValidAccounts',
643 lambda host, accounts:
644 self._mocked_call('ValidAccounts', host, accounts))
tandriic2405f52016-10-10 08:13:15 -0700645 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100646 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000647 # It's important to reset settings to not have inter-tests interference.
648 git_cl.settings = None
649
650 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000651 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000652 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100653 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000654 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100655 raise
656 # Sadly, has_failed() returns True if this OR any other tests before this
657 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200658 git_cl.logging.error(
659 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100660 'There are un-consumed self.calls after this test has finished.\n'
661 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700662 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200663 'If you are already running only this test, then **first** fix the '
664 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100665 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700666 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100667 'and follow instructions above.\n' +
668 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000669 finally:
670 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000671
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000672 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000673 self.assertTrue(
674 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700675 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000676 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000677 expected_args, result = top
678
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000679 # Also logs otherwise it could get caught in a try/finally and be hard to
680 # diagnose.
681 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700682 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000683 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700684 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
685 for i, c in enumerate(self._calls_done[-N:]))
686 following_calls = '\n '.join(
687 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
688 for i, c in enumerate(self.calls[:N]))
689 extended_msg = (
690 'A few prior calls:\n %s\n\n'
691 'This (expected):\n @%d: %r\n'
692 'This (actual):\n @%d: %r\n\n'
693 'A few following expected calls:\n %s' %
694 (prior_calls, len(self._calls_done), expected_args,
695 len(self._calls_done), args, following_calls))
696 git_cl.logging.error(extended_msg)
697
tandrii99a72f22016-08-17 14:33:24 -0700698 self.fail('@%d\n'
699 ' Expected: %r\n'
700 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700701 len(self._calls_done), expected_args, args))
702
703 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700704 if isinstance(result, Exception):
705 raise result
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000706 return result
707
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100708 def test_ask_for_explicit_yes_true(self):
709 self.calls = [
710 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
711 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
712 ]
713 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
714
tandrii48df5812016-10-17 03:55:37 -0700715 def test_LoadCodereviewSettingsFromFile_gerrit(self):
716 codereview_file = StringIO.StringIO('GERRIT_HOST: true')
717 self.calls = [
718 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700719 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
720 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
721 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
722 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700723 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
724 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700725 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
726 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000727 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
728 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700729 ((['git', 'config', 'gerrit.host', 'true'],), ''),
730 ]
731 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
732
maruel@chromium.orga3353652011-11-30 14:26:57 +0000733 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000734 def _is_gerrit_calls(cls, gerrit=False):
735 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
736 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
737
738 @classmethod
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000739 def _git_post_upload_calls(cls):
740 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000741 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
742 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
743 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000744 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000745 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000746 ]
747
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000748 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000749 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000750 fake_ancestor = 'fake_ancestor'
751 fake_cl = 'fake_cl_for_patch'
752 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000753 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000754 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000755 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000756 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000757 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000758 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000759 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000760 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700761 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000762 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000763 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000764 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000765 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000766 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000767 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000768 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000769 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000770 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000771 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000772 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000773
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000774 @classmethod
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000775 def _gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000776 cls, issue=None, skip_auth_check=False, short_hostname='chromium',
777 custom_cl_base=None):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000778 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000779 if skip_auth_check:
780 return [((cmd, ), 'true')]
781
tandrii5d48c322016-08-18 16:19:37 -0700782 calls = [((cmd, ), CERR1)]
Edward Lemurf38bc172019-09-03 21:02:13 +0000783
784 if custom_cl_base:
785 calls += [
786 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
787 ]
788
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000789 calls.extend([
790 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
791 ((['git', 'config', 'branch.master.remote'],), 'origin'),
792 ((['git', 'config', 'remote.origin.url'],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000793 'https://%s.googlesource.com/my/repo' % short_hostname),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000794 ])
Edward Lemurf38bc172019-09-03 21:02:13 +0000795
796 calls += [
797 ((['git', 'config', 'branch.master.gerritissue'],),
798 CERR1 if issue is None else str(issue)),
799 ]
800
Daniel Chengcf6269b2019-05-18 01:02:12 +0000801 if issue:
802 calls.extend([
803 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
804 ])
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000805 return calls
806
807 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100808 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200809 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000810 custom_cl_base=None, short_hostname='chromium',
811 change_id=None):
Aaron Gable13101a62018-02-09 13:20:41 -0800812 calls = cls._is_gerrit_calls(True)
Edward Lemurf38bc172019-09-03 21:02:13 +0000813 if not custom_cl_base:
814 calls += [
815 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
816 ]
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200817
818 if custom_cl_base:
819 ancestor_revision = custom_cl_base
820 else:
821 # Determine ancestor_revision to be merge base.
822 ancestor_revision = 'fake_ancestor_sha'
823 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000824 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000825 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000826 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200827 'refs/remotes/origin/master'],), ancestor_revision),
828 ]
829
830 # Calls to verify branch point is ancestor
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000831 calls += cls._gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000832 issue=issue, short_hostname=short_hostname,
833 custom_cl_base=custom_cl_base)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100834
835 if issue:
836 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000837 (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +0000838 'my%2Frepo~123456',
Andrii Shyshkalovc4a73562018-09-25 18:40:17 +0000839 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
840 ),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100841 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100842 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Anthony Polito8b955342019-09-24 19:01:36 +0000843 'change_id': (change_id or '123456789'),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100844 'current_revision': 'sha1_of_current_revision',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000845 'revisions': {'sha1_of_current_revision': {
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100846 'commit': {'message': fetched_description},
847 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100848 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100849 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100850 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100851 if fetched_status == 'ABANDONED':
852 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000853 (('DieWithError', 'Change https://%s-review.googlesource.com/'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100854 '123456 has been abandoned, new uploads are not '
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000855 'allowed' % short_hostname), SystemExitMock()),
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100856 ]
857 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100858 if other_cl_owner:
859 calls += [
860 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
861 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100862
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200863 calls += cls._git_sanity_checks(ancestor_revision, 'master',
864 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100865 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200866 ((['git', 'rev-parse', '--show-cdup'],), ''),
867 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000868
Aaron Gable7817f022017-12-12 09:43:17 -0800869 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
870 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200871 'M\t.gitignore\n'),
872 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100873 ]
874
875 if not issue:
876 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200877 ((['git', 'log', '--pretty=format:%s%n%n%b',
878 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000879 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100880 ]
881
882 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200883 ((['git', 'config', 'user.email'],), 'me@example.com'),
Edward Lemur2c48f242019-06-04 16:14:09 +0000884 (('time.time',), 1000,),
885 (('time.time',), 3000,),
886 (('add_repeated', 'sub_commands', {
887 'execution_time': 2000,
888 'command': 'presubmit',
889 'exit_code': 0
890 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200891 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
892 ([custom_cl_base] if custom_cl_base else
893 [ancestor_revision, 'HEAD']),),
894 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100895 ]
896 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000897
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000898 @classmethod
899 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700900 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000901 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700902 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100903 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000904 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000905 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000906 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000907 final_description=None, gitcookies_exists=True,
908 force=False):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000909 if post_amend_description is None:
910 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700911 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200912 # Determined in `_gerrit_base_calls`.
913 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
914
915 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000916
tandriia60502f2016-06-20 02:01:53 -0700917 if squash_mode == 'default':
918 calls.extend([
919 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
920 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
921 ])
922 elif squash_mode in ('override_squash', 'override_nosquash'):
923 calls.extend([
924 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
925 'true' if squash_mode == 'override_squash' else 'false'),
926 ])
927 else:
928 assert squash_mode in ('squash', 'nosquash')
929
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000930 # If issue is given, then description is fetched from Gerrit instead.
931 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000932 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200933 ((['git', 'log', '--pretty=format:%s\n\n%b',
934 ((custom_cl_base + '..') if custom_cl_base else
935 'fake_ancestor_sha..HEAD')],),
936 description),
937 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800938 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000939 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800940 else:
941 if not title:
942 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200943 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
944 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800945 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000946 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000947 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000948 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200949 (('DownloadGerritHook', False), ''),
950 # Amending of commit message to get the Change-Id.
951 ((['git', 'log', '--pretty=format:%s\n\n%b',
952 determined_ancestor_revision + '..HEAD'],),
953 description),
954 ((['git', 'commit', '--amend', '-m', description],), ''),
955 ((['git', 'log', '--pretty=format:%s\n\n%b',
956 determined_ancestor_revision + '..HEAD'],),
957 post_amend_description)
958 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000959 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000960 if force or not issue:
961 if issue:
962 calls += [
963 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
964 ]
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000965 # Prompting to edit description on first upload.
966 calls += [
Jonas Termansend0f79112019-03-22 15:28:26 +0000967 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000968 ]
Anthony Polito8b955342019-09-24 19:01:36 +0000969 if not force:
970 calls += [
971 ((['git', 'config', 'core.editor'],), ''),
972 ((['RunEditor'],), description),
973 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000974 ref_to_push = 'abcdef0123456789'
975 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200976 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
977 ((['git', 'config', 'branch.master.remote'],), 'origin'),
978 ]
979
980 if custom_cl_base is None:
981 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000982 ((['get_or_create_merge_base', 'master',
983 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000984 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200985 ]
986 parent = 'origin/master'
987 else:
988 calls += [
989 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
990 'refs/remotes/origin/master'],),
991 callError(1)), # Means not ancenstor.
992 (('ask_for_data',
993 'Do you take responsibility for cleaning up potential mess '
994 'resulting from proceeding with upload? Press Enter to upload, '
995 'or Ctrl+C to abort'), ''),
996 ]
997 parent = custom_cl_base
998
999 calls += [
1000 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
1001 '0123456789abcdef'),
1002 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -07001003 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001004 ref_to_push),
1005 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001006 else:
1007 ref_to_push = 'HEAD'
1008
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001009 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00001010 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001011 ((['git', 'rev-list',
1012 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1013 ref_to_push],),
1014 '1hashPerLine\n'),
1015 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001016
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001017 metrics_arguments = []
1018
Aaron Gableafd52772017-06-27 16:40:10 -07001019 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001020 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001021 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -07001022 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001023 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001024 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001025 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -07001026 else:
1027 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001028 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -08001029
Aaron Gable70f4e242017-06-26 10:45:59 -07001030 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001031 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001032 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001033
Edward Lemur4508b422019-10-03 21:56:35 +00001034 if issue is None:
1035 calls += [
1036 ((['git', 'config', 'rietveld.cc'],), ''),
1037 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001038 if short_hostname == 'chromium':
1039 # All reviwers and ccs get into ref_suffix.
1040 for r in sorted(reviewers):
1041 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001042 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +00001043 if issue is None:
1044 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
1045 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001046 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001047 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001048 reviewers, cc = [], []
1049 else:
1050 # TODO(crbug/877717): remove this case.
1051 calls += [
1052 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
1053 sorted(reviewers) + ['joe@example.com',
1054 'chromium-reviews+test-more-cc@chromium.org'] + cc),
1055 {
1056 e: {'email': e}
1057 for e in (reviewers + ['joe@example.com'] + cc)
1058 })
1059 ]
1060 for r in sorted(reviewers):
1061 if r != 'bad-account-or-email':
1062 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001063 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001064 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +00001065 if issue is None:
1066 cc += ['joe@example.com']
1067 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001068 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001069 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001070 if c in cc:
1071 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001072
Edward Lemur687ca902018-12-05 02:30:30 +00001073 for k, v in sorted((labels or {}).items()):
1074 ref_suffix += ',l=%s+%d' % (k, v)
1075 metrics_arguments.append('l=%s+%d' % (k, v))
1076
1077 if tbr:
1078 calls += [
1079 (('GetCodeReviewTbrScore',
1080 '%s-review.googlesource.com' % short_hostname,
1081 'my/repo'),
1082 2,),
1083 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001084
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001085 calls += [
1086 (('time.time',), 1000,),
1087 ((['git', 'push',
1088 'https://%s.googlesource.com/my/repo' % short_hostname,
1089 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1090 (('remote:\n'
1091 'remote: Processing changes: (\)\n'
1092 'remote: Processing changes: (|)\n'
1093 'remote: Processing changes: (/)\n'
1094 'remote: Processing changes: (-)\n'
1095 'remote: Processing changes: new: 1 (/)\n'
1096 'remote: Processing changes: new: 1, done\n'
1097 'remote:\n'
1098 'remote: New Changes:\n'
1099 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1100 ' XXX\n'
1101 'remote:\n'
1102 'To https://%s.googlesource.com/my/repo\n'
1103 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1104 ) % (short_hostname, short_hostname)),),
1105 (('time.time',), 2000,),
1106 (('add_repeated',
1107 'sub_commands',
1108 {
1109 'execution_time': 1000,
1110 'command': 'git push',
1111 'exit_code': 0,
1112 'arguments': sorted(metrics_arguments),
1113 }),
1114 None,),
1115 ]
1116
Edward Lemur1b52d872019-05-09 21:12:12 +00001117 final_description = final_description or post_amend_description.strip()
1118 original_title = original_title or title or '<untitled>'
1119 # Trace-related calls
1120 calls += [
1121 # Write a description with context for the current trace.
1122 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001123 'Thu Mar 16 20:00:41 2017\n'
1124 '%(short_hostname)s-review.googlesource.com\n'
1125 '%(change_id)s\n'
1126 '%(title)s\n'
1127 '%(description)s\n'
1128 '1000\n'
1129 '0\n'
1130 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001131 'short_hostname': short_hostname,
1132 'change_id': change_id,
1133 'description': final_description,
1134 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001135 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001136 }],),
1137 None,
1138 ),
1139 # Read traces and shorten git hashes.
1140 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1141 True,
1142 ),
1143 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1144 ('git-hash: 0123456789012345678901234567890123456789\n'
1145 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1146 ),
1147 ((['FileWrite', 'TEMP_DIR/trace-packet',
1148 'git-hash: 012345\n'
1149 'git-hash: abcdea\n'],),
1150 None,
1151 ),
1152 # Make zip file for the git traces.
1153 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1154 'TEMP_DIR'],),
1155 None,
1156 ),
1157 # Collect git config and gitcookies.
1158 ((['git', 'config', '-l'],),
1159 'git-config-output',
1160 ),
1161 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1162 None,
1163 ),
1164 ((['os.path.isfile', '~/.gitcookies'],),
1165 gitcookies_exists,
1166 ),
1167 ]
1168 if gitcookies_exists:
1169 calls += [
1170 ((['FileRead', '~/.gitcookies'],),
1171 'gitcookies 1/SECRET',
1172 ),
1173 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1174 None,
1175 ),
1176 ]
1177 calls += [
1178 # Make zip file for the git config and gitcookies.
1179 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1180 'TEMP_DIR'],),
1181 None,
1182 ),
1183 ]
1184
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001185 if squash:
1186 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001187 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001188 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001189 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001190 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001191 ((['git', 'config', 'branch.master.gerritsquashhash',
1192 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001193 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001194 # TODO(crbug/877717): this should never be used.
1195 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001196 calls += [
1197 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001198 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001199 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001200 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1201 notify),
1202 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001203 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001204 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001205 return calls
1206
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001207 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001208 self,
1209 upload_args,
1210 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001211 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001212 squash=True,
1213 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001214 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001215 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001216 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001217 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001218 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001219 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001220 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001221 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001222 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001223 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001224 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001225 labels=None,
1226 change_id=None,
1227 original_title=None,
1228 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001229 gitcookies_exists=True,
1230 force=False,
1231 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001232 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001233 if squash_mode is None:
1234 if '--no-squash' in upload_args:
1235 squash_mode = 'nosquash'
1236 elif '--squash' in upload_args:
1237 squash_mode = 'squash'
1238 else:
1239 squash_mode = 'default'
1240
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001241 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001242 cc = cc or []
tandrii@chromium.org28253532016-04-14 13:46:56 +00001243 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001244 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001245 CookiesAuthenticatorMockFactory(
1246 same_auth=('git-owner.example.com', '', 'pass')))
Edward Lemur125d60a2019-09-13 18:25:41 +00001247 self.mock(git_cl.Changelist, '_GerritCommitMsgHookCheck',
tandrii16e0b4e2016-06-07 10:34:28 -07001248 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001249 self.mock(git_cl.gclient_utils, 'RunEditor',
1250 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001251 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1252 'DownloadGerritHook', force))
Edward Lemur1b52d872019-05-09 21:12:12 +00001253 self.mock(git_cl.gclient_utils, 'FileRead',
1254 lambda path: self._mocked_call(['FileRead', path]))
1255 self.mock(git_cl.gclient_utils, 'FileWrite',
1256 lambda path, contents: self._mocked_call(
1257 ['FileWrite', path, contents]))
1258 self.mock(git_cl, 'datetime_now',
1259 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0))
1260 self.mock(git_cl.tempfile, 'mkdtemp', lambda: 'TEMP_DIR')
1261 self.mock(git_cl, 'TRACES_DIR', 'TRACES_DIR')
Edward Lemur75391d42019-05-14 23:35:56 +00001262 self.mock(git_cl, 'TRACES_README_FORMAT',
1263 '%(now)s\n'
1264 '%(gerrit_host)s\n'
1265 '%(change_id)s\n'
1266 '%(title)s\n'
1267 '%(description)s\n'
1268 '%(execution_time)s\n'
1269 '%(exit_code)s\n'
1270 '%(trace_name)s')
Edward Lemur1b52d872019-05-09 21:12:12 +00001271 self.mock(git_cl.shutil, 'make_archive',
1272 lambda *args: self._mocked_call(['make_archive'] + list(args)))
1273 self.mock(os.path, 'isfile',
1274 lambda path: self._mocked_call(['os.path.isfile', path]))
tandriia60502f2016-06-20 02:01:53 -07001275
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001276 self.calls = self._gerrit_base_calls(
1277 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001278 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001279 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001280 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001281 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001282 short_hostname=short_hostname,
1283 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001284 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001285 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
1286 expected_content=description))
1287 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001288 self.calls += self._gerrit_upload_calls(
1289 description, reviewers, squash,
1290 squash_mode=squash_mode,
1291 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001292 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001293 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001294 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001295 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001296 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001297 labels=labels,
1298 change_id=change_id,
1299 original_title=original_title,
1300 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001301 gitcookies_exists=gitcookies_exists,
1302 force=force)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001303 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001304 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001305 git_cl.main(['upload'] + upload_args)
1306
Edward Lemur1b52d872019-05-09 21:12:12 +00001307 def test_gerrit_upload_traces_no_gitcookies(self):
1308 self._run_gerrit_upload_test(
1309 ['--no-squash'],
1310 'desc\n\nBUG=\n',
1311 [],
1312 squash=False,
1313 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1314 change_id='Ixxx',
1315 gitcookies_exists=False)
1316
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001317 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001318 self._run_gerrit_upload_test(
1319 ['--no-squash'],
1320 'desc\n\nBUG=\n',
1321 [],
1322 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001323 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1324 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001325
1326 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001327 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001328 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +00001329 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001330 [],
tandriia60502f2016-06-20 02:01:53 -07001331 squash=False,
1332 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001333 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1334 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001335
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001336 def test_gerrit_no_reviewer(self):
1337 self._run_gerrit_upload_test(
1338 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001339 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001340 [],
1341 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001342 squash_mode='override_nosquash',
1343 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001344
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001345 def test_gerrit_no_reviewer_non_chromium_host(self):
1346 # TODO(crbug/877717): remove this test case.
1347 self._run_gerrit_upload_test(
1348 [],
1349 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
1350 [],
1351 squash=False,
1352 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001353 short_hostname='other',
1354 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001355
Nick Carter8692b182017-11-06 16:30:38 -08001356 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001357 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1358 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001359 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001360 'desc\n\nBUG=\n\nChange-Id: I123456789',
1361 squash=False,
1362 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001363 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1364 change_id='I123456789',
1365 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001366
ukai@chromium.orge8077812012-02-03 03:41:46 +00001367 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001368 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001369 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001370 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001371 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001372 squash=False,
1373 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001374 notify=True,
1375 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001376 final_description=(
1377 'desc\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001378
Anthony Polito8b955342019-09-24 19:01:36 +00001379 def test_gerrit_upload_force_sets_bug(self):
1380 self._run_gerrit_upload_test(
1381 ['-b', '10000', '-f'],
1382 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1383 [],
1384 force=True,
1385 expected_upstream_ref='origin/master',
1386 fetched_description='desc=\n\nChange-Id: Ixxx',
1387 original_title='Initial upload',
1388 change_id='Ixxx')
1389
1390 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1391 self._run_gerrit_upload_test(
1392 ['-b', '10000', '-f', '-m', 'Title'],
1393 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1394 [],
1395 force=True,
1396 issue='123456',
1397 expected_upstream_ref='origin/master',
1398 fetched_description='desc=\n\nChange-Id: Ixxxx',
1399 original_title='Title',
1400 title='Title',
1401 change_id='Izzzz')
1402
Dan Beamd8b04ca2019-10-10 21:23:26 +00001403 def test_gerrit_upload_force_sets_fixed(self):
1404 self._run_gerrit_upload_test(
1405 ['-x', '10000', '-f'],
1406 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1407 [],
1408 force=True,
1409 expected_upstream_ref='origin/master',
1410 fetched_description='desc=\n\nChange-Id: Ixxx',
1411 original_title='Initial upload',
1412 change_id='Ixxx')
1413
ukai@chromium.orge8077812012-02-03 03:41:46 +00001414 def test_gerrit_reviewer_multiple(self):
Edward Lemur687ca902018-12-05 02:30:30 +00001415 self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
1416 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001417 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001418 [],
bradnelsond975b302016-10-23 12:20:23 -07001419 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1420 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001421 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001422 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001423 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001424 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001425 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001426 labels={'Code-Review': 2},
1427 change_id='123456789',
1428 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001429
1430 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001431 self._run_gerrit_upload_test(
1432 [],
1433 'desc\nBUG=\n\nChange-Id: 123456789',
1434 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001435 expected_upstream_ref='origin/master',
1436 change_id='123456789',
1437 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001438
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001439 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001440 self._run_gerrit_upload_test(
1441 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001442 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001443 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001444 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001445 expected_upstream_ref='origin/master',
1446 change_id='123456789',
1447 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001448
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001449 def test_gerrit_upload_squash_first_with_labels(self):
1450 self._run_gerrit_upload_test(
1451 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
1452 'desc\nBUG=\n\nChange-Id: 123456789',
1453 [],
1454 squash=True,
1455 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001456 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1457 change_id='123456789',
1458 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001459
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001460 def test_gerrit_upload_squash_first_against_rev(self):
1461 custom_cl_base = 'custom_cl_base_rev_or_branch'
1462 self._run_gerrit_upload_test(
1463 ['--squash', custom_cl_base],
1464 'desc\nBUG=\n\nChange-Id: 123456789',
1465 [],
1466 squash=True,
1467 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001468 custom_cl_base=custom_cl_base,
1469 change_id='123456789',
1470 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001471 self.assertIn(
1472 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1473 sys.stdout.getvalue())
1474
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001475 def test_gerrit_upload_squash_reupload(self):
1476 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001477 self._run_gerrit_upload_test(
1478 ['--squash'],
1479 description,
1480 [],
1481 squash=True,
1482 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001483 issue=123456,
1484 change_id='123456789',
1485 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001486
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001487 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1488 self.mock(git_cl, 'DieWithError',
1489 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1490 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1491 with self.assertRaises(SystemExitMock):
1492 self._run_gerrit_upload_test(
1493 ['--squash'],
1494 description,
1495 [],
1496 squash=True,
1497 expected_upstream_ref='origin/master',
1498 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001499 fetched_status='ABANDONED',
1500 change_id='123456789')
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001501
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001502 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1503 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1504 lambda *_, **__: {'email': 'yet-another@example.com'})
1505 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1506 self._run_gerrit_upload_test(
1507 ['--squash'],
1508 description,
1509 [],
1510 squash=True,
1511 expected_upstream_ref='origin/master',
1512 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001513 other_cl_owner='other@example.com',
1514 change_id='123456789',
1515 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001516 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001517 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001518 'authenticate to Gerrit as yet-another@example.com.\n'
1519 'Uploading may fail due to lack of permissions',
1520 git_cl.sys.stdout.getvalue())
1521
rmistry@google.com2dd99862015-06-22 12:22:18 +00001522 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001523 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001524 def mock_run_git(*args, **_kwargs):
1525 if args[0] == ['for-each-ref',
1526 '--format=%(refname:short) %(upstream:short)',
1527 'refs/heads']:
1528 # Create a local branch dependency tree that looks like this:
1529 # test1 -> test2 -> test3 -> test4 -> test5
1530 # -> test3.1
1531 # test6 -> test0
1532 branch_deps = [
1533 'test2 test1', # test1 -> test2
1534 'test3 test2', # test2 -> test3
1535 'test3.1 test2', # test2 -> test3.1
1536 'test4 test3', # test3 -> test4
1537 'test5 test4', # test4 -> test5
1538 'test6 test0', # test0 -> test6
1539 'test7', # test7
1540 ]
1541 return '\n'.join(branch_deps)
1542 self.mock(git_cl, 'RunGit', mock_run_git)
1543
1544 class RecordCalls:
1545 times_called = 0
1546 record_calls = RecordCalls()
1547 def mock_CMDupload(*args, **_kwargs):
1548 record_calls.times_called += 1
1549 return 0
1550 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1551
1552 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001553 (('ask_for_data', 'This command will checkout all dependent branches '
1554 'and run "git cl upload". Press Enter to continue, '
1555 'or Ctrl+C to abort'), ''),
1556 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001557
1558 class MockChangelist():
1559 def __init__(self):
1560 pass
1561 def GetBranch(self):
1562 return 'test1'
1563 def GetIssue(self):
1564 return '123'
1565 def GetPatchset(self):
1566 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001567 def IsGerrit(self):
1568 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001569
1570 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1571 # CMDupload should have been called 5 times because of 5 dependent branches.
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001572 self.assertEqual(5, record_calls.times_called)
1573 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001574
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001575 def test_gerrit_change_id(self):
1576 self.calls = [
1577 ((['git', 'write-tree'], ),
1578 'hashtree'),
1579 ((['git', 'rev-parse', 'HEAD~0'], ),
1580 'branch-parent'),
1581 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1582 'A B <a@b.org> 1456848326 +0100'),
1583 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1584 'C D <c@d.org> 1456858326 +0100'),
1585 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1586 'hashchange'),
1587 ]
1588 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1589 self.assertEqual(change_id, 'Ihashchange')
1590
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001591 def test_desecription_append_footer(self):
1592 for init_desc, footer_line, expected_desc in [
1593 # Use unique desc first lines for easy test failure identification.
1594 ('foo', 'R=one', 'foo\n\nR=one'),
1595 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1596 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1597 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1598 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1599 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1600 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1601 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1602 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1603 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1604 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1605 ]:
1606 desc = git_cl.ChangeDescription(init_desc)
1607 desc.append_footer(footer_line)
1608 self.assertEqual(desc.description, expected_desc)
1609
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001610 def test_update_reviewers(self):
1611 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001612 ('foo', [], [],
1613 'foo'),
1614 ('foo\nR=xx', [], [],
1615 'foo\nR=xx'),
1616 ('foo\nTBR=xx', [], [],
1617 'foo\nTBR=xx'),
1618 ('foo', ['a@c'], [],
1619 'foo\n\nR=a@c'),
1620 ('foo\nR=xx', ['a@c'], [],
1621 'foo\n\nR=a@c, xx'),
1622 ('foo\nTBR=xx', ['a@c'], [],
1623 'foo\n\nR=a@c\nTBR=xx'),
1624 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1625 'foo\n\nR=a@c, yy\nTBR=xx'),
1626 ('foo\nBUG=', ['a@c'], [],
1627 'foo\nBUG=\nR=a@c'),
1628 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1629 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1630 ('foo', ['a@c', 'b@c'], [],
1631 'foo\n\nR=a@c, b@c'),
1632 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1633 'foo\nBar\n\nR=c@c\nBUG='),
1634 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1635 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001636 # Same as the line before, but full of whitespaces.
1637 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001638 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001639 'foo\nBar\n\nR=c@c\n BUG =',
1640 ),
1641 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001642 ('foo BUG=allo R=joe ', ['c@c'], [],
1643 'foo BUG=allo R=joe\n\nR=c@c'),
1644 # Redundant TBRs get promoted to Rs
1645 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1646 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001647 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001648 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001649 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001650 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001651 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001652 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001653 actual.append(obj.description)
1654 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001655
Nodir Turakulov23b82142017-11-16 11:04:25 -08001656 def test_get_hash_tags(self):
1657 cases = [
1658 ('', []),
1659 ('a', []),
1660 ('[a]', ['a']),
1661 ('[aa]', ['aa']),
1662 ('[a ]', ['a']),
1663 ('[a- ]', ['a']),
1664 ('[a- b]', ['a-b']),
1665 ('[a--b]', ['a-b']),
1666 ('[a', []),
1667 ('[a]x', ['a']),
1668 ('[aa]x', ['aa']),
1669 ('[a b]', ['a-b']),
1670 ('[a b]', ['a-b']),
1671 ('[a__b]', ['a-b']),
1672 ('[a] x', ['a']),
1673 ('[a][b]', ['a', 'b']),
1674 ('[a] [b]', ['a', 'b']),
1675 ('[a][b]x', ['a', 'b']),
1676 ('[a][b] x', ['a', 'b']),
1677 ('[a]\n[b]', ['a']),
1678 ('[a\nb]', []),
1679 ('[a][', ['a']),
1680 ('Revert "[a] feature"', ['a']),
1681 ('Reland "[a] feature"', ['a']),
1682 ('Revert: [a] feature', ['a']),
1683 ('Reland: [a] feature', ['a']),
1684 ('Revert "Reland: [a] feature"', ['a']),
1685 ('Foo: feature', ['foo']),
1686 ('Foo Bar: feature', ['foo-bar']),
1687 ('Revert "Foo bar: feature"', ['foo-bar']),
1688 ('Reland "Foo bar: feature"', ['foo-bar']),
1689 ]
1690 for desc, expected in cases:
1691 change_desc = git_cl.ChangeDescription(desc)
1692 actual = change_desc.get_hash_tags()
1693 self.assertEqual(
1694 actual,
1695 expected,
1696 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1697
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001698 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001699 self.assertEqual(None, git_cl.GetTargetRef(None,
1700 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001701 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001702
wittman@chromium.org455dc922015-01-26 20:15:50 +00001703 # Check default target refs for branches.
1704 self.assertEqual('refs/heads/master',
1705 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001706 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001707 self.assertEqual('refs/heads/master',
1708 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001709 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001710 self.assertEqual('refs/heads/master',
1711 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001712 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001713 self.assertEqual('refs/branch-heads/123',
1714 git_cl.GetTargetRef('origin',
1715 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001716 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001717 self.assertEqual('refs/diff/test',
1718 git_cl.GetTargetRef('origin',
1719 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001720 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001721 self.assertEqual('refs/heads/chrome/m42',
1722 git_cl.GetTargetRef('origin',
1723 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001724 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001725
1726 # Check target refs for user-specified target branch.
1727 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1728 'refs/remotes/branch-heads/123'):
1729 self.assertEqual('refs/branch-heads/123',
1730 git_cl.GetTargetRef('origin',
1731 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001732 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001733 for branch in ('origin/master', 'remotes/origin/master',
1734 'refs/remotes/origin/master'):
1735 self.assertEqual('refs/heads/master',
1736 git_cl.GetTargetRef('origin',
1737 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001738 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001739 for branch in ('master', 'heads/master', 'refs/heads/master'):
1740 self.assertEqual('refs/heads/master',
1741 git_cl.GetTargetRef('origin',
1742 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001743 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001744
wychen@chromium.orga872e752015-04-28 23:42:18 +00001745 def test_patch_when_dirty(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001746 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001747 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1748 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1749
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001750 @staticmethod
1751 def _get_gerrit_codereview_server_calls(branch, value=None,
1752 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001753 detect_branch=True,
1754 detect_server=True):
Edward Lemur125d60a2019-09-13 18:25:41 +00001755 """Returns calls executed by Changelist.GetCodereviewServer.
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001756
1757 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1758 """
1759 calls = []
1760 if detect_branch:
1761 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001762 if detect_server:
1763 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1764 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001765 if value is None:
1766 calls += [
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001767 ((['git', 'config', 'branch.' + branch + '.merge'],),
1768 'refs/heads' + branch),
1769 ((['git', 'config', 'branch.' + branch + '.remote'],),
1770 'origin'),
1771 ((['git', 'config', 'remote.origin.url'],),
1772 'https://%s.googlesource.com/my/repo' % git_short_host),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001773 ]
1774 return calls
1775
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001776 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001777 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001778 detect_gerrit_server=False,
1779 actual_codereview=None,
1780 codereview_in_url=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001781 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
wychen@chromium.orga872e752015-04-28 23:42:18 +00001782 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1783
tandriidf09a462016-08-18 16:23:55 -07001784 if new_branch:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001785 self.calls = [((['git', 'new-branch', 'master'],), '')]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001786
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001787 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001788 self.calls += [
1789 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001790 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001791 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001792
1793 if not force_codereview and not codereview_in_url:
1794 # These calls detect codereview to use.
1795 self.calls += [
1796 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001797 ]
1798 if detect_gerrit_server:
1799 self.calls += self._get_gerrit_codereview_server_calls(
1800 'master', git_short_host=git_short_host,
1801 detect_branch=not new_branch and force_codereview)
1802 actual_codereview = 'gerrit'
1803
1804 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001805 self.calls += [
1806 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001807 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001808 {
1809 'current_revision': '7777777777',
1810 'revisions': {
1811 '1111111111': {
1812 '_number': 1,
1813 'fetch': {'http': {
1814 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1815 'ref': 'refs/changes/56/123456/1',
1816 }},
1817 },
1818 '7777777777': {
1819 '_number': 7,
1820 'fetch': {'http': {
1821 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1822 'ref': 'refs/changes/56/123456/7',
1823 }},
1824 },
1825 },
1826 }),
1827 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001828
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001829 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001830 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001831 self.calls += [
1832 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1833 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001834 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001835 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001836 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001837 ((['git', 'config', 'branch.master.gerritserver',
1838 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001839 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001840 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1841 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1842 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001843 ]
1844 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1845
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001846 def test_patch_gerrit_new_branch(self):
1847 self._patch_common(
1848 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1849 self.calls += [
1850 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1851 'refs/changes/56/123456/7'],), ''),
1852 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1853 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1854 ''),
1855 ((['git', 'config', 'branch.master.gerritserver',
1856 'https://chromium-review.googlesource.com'],), ''),
1857 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1858 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1859 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1860 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1861 ]
1862 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1863
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001864 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001865 self._patch_common(
1866 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001867 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001868 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001869 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001870 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001871 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001872 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001873 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001874 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001875 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001876 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1877 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1878 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001879 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001880 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001881
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001882 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001883 self.calls += self._get_gerrit_codereview_server_calls(
1884 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001885 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001886 actual_codereview='gerrit', git_short_host='else',
1887 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001888 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001889 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001890 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001891 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001892 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001893 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001894 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001895 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001896 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001897 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1898 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1899 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001900 ]
1901 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001902 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001903
Aaron Gable697a91b2018-01-19 15:20:15 -08001904 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001905 self.calls += self._get_gerrit_codereview_server_calls(
1906 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001907 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001908 actual_codereview='gerrit', git_short_host='else',
1909 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001910 self.calls += [
1911 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1912 'refs/changes/56/123456/1'],), ''),
1913 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1914 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1915 ''),
1916 ((['git', 'config', 'branch.master.gerritserver',
1917 'https://else-review.googlesource.com'],), ''),
1918 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1919 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1920 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1921 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1922 ]
1923 self.assertEqual(git_cl.main(
1924 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1925 0)
1926
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001927 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001928 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001929 self.calls += [
1930 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001931 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001932 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1933 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1934 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001935 ]
1936 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001937 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001938
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001939 def test_patch_gerrit_not_exists(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001940
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001941 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001942 raise git_cl.gerrit_util.GerritError(404, '')
1943 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1944
tandriic2405f52016-10-10 08:13:15 -07001945 self.calls = [
1946 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001947 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1948 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1949 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1950 ((['git', 'config', 'remote.origin.url'],),
1951 'https://chromium.googlesource.com/my/repo'),
1952 ((['DieWithError',
1953 'change 123456 at https://chromium-review.googlesource.com does not '
1954 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001955 ]
1956 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001957 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001958
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001959 def _checkout_calls(self):
1960 return [
1961 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001962 'branch\\..*\\.gerritissue'], ),
1963 ('branch.ger-branch.gerritissue 123456\n'
1964 'branch.gbranch654.gerritissue 654321\n')),
1965 ]
1966
1967 def test_checkout_gerrit(self):
1968 """Tests git cl checkout <issue>."""
1969 self.calls = self._checkout_calls()
1970 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1971 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1972
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001973 def test_checkout_not_found(self):
1974 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001975 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001976 self.calls = self._checkout_calls()
1977 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1978
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001979 def test_checkout_no_branch_issues(self):
1980 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001981 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001982 self.calls = [
1983 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001984 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001985 ]
1986 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1987
tandrii@chromium.org28253532016-04-14 13:46:56 +00001988 def _test_gerrit_ensure_authenticated_common(self, auth,
1989 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001990 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1991 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1992 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11001993 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001994 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
Edward Lemurf38bc172019-09-03 21:02:13 +00001995 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001996 cl.branch = 'master'
1997 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001998 return cl
1999
2000 def test_gerrit_ensure_authenticated_missing(self):
2001 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002002 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002003 })
2004 self.calls.append(
2005 ((['DieWithError',
2006 'Credentials for the following hosts are required:\n'
2007 ' chromium-review.googlesource.com\n'
2008 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002009 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002010 'https://chromium-review.googlesource.com/new-password'],), ''),)
2011 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2012
2013 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00002014 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002015 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002016 'chromium.googlesource.com':
2017 ('git-one.example.com', None, 'secret1'),
2018 'chromium-review.googlesource.com':
2019 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002020 })
2021 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002022 (('ask_for_data', 'If you know what you are doing '
2023 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002024 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2025
2026 def test_gerrit_ensure_authenticated_ok(self):
2027 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002028 'chromium.googlesource.com':
2029 ('git-same.example.com', None, 'secret'),
2030 'chromium-review.googlesource.com':
2031 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002032 })
2033 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2034
tandrii@chromium.org28253532016-04-14 13:46:56 +00002035 def test_gerrit_ensure_authenticated_skipped(self):
2036 cl = self._test_gerrit_ensure_authenticated_common(
2037 auth={}, skip_auth_check=True)
2038 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2039
Eric Boren2fb63102018-10-05 13:05:03 +00002040 def test_gerrit_ensure_authenticated_bearer_token(self):
2041 cl = self._test_gerrit_ensure_authenticated_common(auth={
2042 'chromium.googlesource.com':
2043 ('', None, 'secret'),
2044 'chromium-review.googlesource.com':
2045 ('', None, 'secret'),
2046 })
2047 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2048 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2049 'chromium.googlesource.com')
2050 self.assertTrue('Bearer' in header)
2051
Daniel Chengcf6269b2019-05-18 01:02:12 +00002052 def test_gerrit_ensure_authenticated_non_https(self):
2053 self.calls = [
2054 ((['git', 'config', '--bool',
2055 'gerrit.skip-ensure-authenticated'],), CERR1),
2056 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
2057 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2058 ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
2059 ]
2060 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2061 CookiesAuthenticatorMockFactory(hosts_with_creds={}))
Edward Lemurf38bc172019-09-03 21:02:13 +00002062 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00002063 cl.branch = 'master'
2064 cl.branchref = 'refs/heads/master'
2065 cl.lookedup_issue = True
2066 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2067
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002068 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002069 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002070 lambda h, i, labels, notify=None:
2071 self._mocked_call(['SetReview', h, i, labels, notify]))
2072
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002073 self.calls = [
2074 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002075 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002076 ((['git', 'config', 'branch.feature.gerritserver'],),
2077 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002078 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2079 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2080 ((['git', 'config', 'remote.origin.url'],),
2081 'https://chromium.googlesource.com/infra/infra.git'),
2082 ((['SetReview', 'chromium-review.googlesource.com',
2083 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002084 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002085 ]
tandriid9e5ce52016-07-13 02:32:59 -07002086
2087 def test_cmd_set_commit_gerrit_clear(self):
2088 self._cmd_set_commit_gerrit_common(0)
2089 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2090
2091 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002092 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002093 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2094
tandriid9e5ce52016-07-13 02:32:59 -07002095 def test_cmd_set_commit_gerrit(self):
2096 self._cmd_set_commit_gerrit_common(2)
2097 self.assertEqual(0, git_cl.main(['set-commit']))
2098
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002099 def test_description_display(self):
2100 out = StringIO.StringIO()
2101 self.mock(git_cl.sys, 'stdout', out)
2102
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002103 self.mock(git_cl, 'Changelist', ChangelistMock)
2104 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002105
2106 self.assertEqual(0, git_cl.main(['description', '-d']))
2107 self.assertEqual('foo\n', out.getvalue())
2108
iannucci3c972b92016-08-17 13:24:10 -07002109 def test_StatusFieldOverrideIssueMissingArgs(self):
2110 out = StringIO.StringIO()
2111 self.mock(git_cl.sys, 'stderr', out)
2112
2113 try:
2114 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2115 except SystemExit as ex:
2116 self.assertEqual(ex.code, 2)
Edward Lemurf38bc172019-09-03 21:02:13 +00002117 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002118
2119 out = StringIO.StringIO()
2120 self.mock(git_cl.sys, 'stderr', out)
2121
2122 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002123 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07002124 except SystemExit as ex:
2125 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002126 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002127
2128 def test_StatusFieldOverrideIssue(self):
2129 out = StringIO.StringIO()
2130 self.mock(git_cl.sys, 'stdout', out)
2131
2132 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002133 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002134 return 'foobar'
2135
2136 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07002137 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002138 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002139 0)
iannucci3c972b92016-08-17 13:24:10 -07002140 self.assertEqual(out.getvalue(), 'foobar\n')
2141
iannuccie53c9352016-08-17 14:40:40 -07002142 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002143
iannuccie53c9352016-08-17 14:40:40 -07002144 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002145 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002146 return 'foobar'
2147
2148 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2149 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07002150 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002151 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002152
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002153 def test_description(self):
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002154 out = StringIO.StringIO()
2155 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002156 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002157 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2158 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2159 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2160 ((['git', 'config', 'remote.origin.url'],),
2161 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002162 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002163 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002164 {
2165 'current_revision': 'sha1',
2166 'revisions': {'sha1': {
2167 'commit': {'message': 'foobar'},
2168 }},
2169 }),
2170 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002171 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002172 'description',
2173 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2174 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002175 self.assertEqual('foobar\n', out.getvalue())
2176
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002177 def test_description_set_raw(self):
2178 out = StringIO.StringIO()
2179 self.mock(git_cl.sys, 'stdout', out)
2180
2181 self.mock(git_cl, 'Changelist', ChangelistMock)
2182 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
2183
2184 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2185 self.assertEqual('hihi', ChangelistMock.desc)
2186
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002187 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002188 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002189
2190 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002191 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002192 '# Enter a description of the change.\n'
2193 '# This will be displayed on the codereview site.\n'
2194 '# The first line will also be used as the subject of the review.\n'
2195 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002196 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002197 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002198 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002199 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002200 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002201
dsansomee2d6fd92016-09-08 00:10:47 -07002202 def UpdateDescriptionRemote(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002203 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002204
2205 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2206 self.mock(git_cl.Changelist, 'GetDescription',
2207 lambda *args: current_desc)
Edward Lemur125d60a2019-09-13 18:25:41 +00002208 self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002209 UpdateDescriptionRemote)
2210 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2211
2212 self.calls = [
2213 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002214 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002215 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2216 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002217 ((['git', 'config', 'core.editor'],), 'vi'),
2218 ]
2219 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2220
Dan Beamd8b04ca2019-10-10 21:23:26 +00002221 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2222 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2223
2224 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002225 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002226 '# Enter a description of the change.\n'
2227 '# This will be displayed on the codereview site.\n'
2228 '# The first line will also be used as the subject of the review.\n'
2229 '#--------------------This line is 72 characters long'
2230 '--------------------\n'
2231 'Some.\n\nFixed: 123\nChange-Id: xxx',
2232 desc)
2233 return desc
2234
2235 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2236 self.mock(git_cl.Changelist, 'GetDescription',
2237 lambda *args: current_desc)
2238 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2239
2240 self.calls = [
2241 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2242 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2243 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2244 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
2245 ((['git', 'config', 'core.editor'],), 'vi'),
2246 ]
2247 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2248
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002249 def test_description_set_stdin(self):
2250 out = StringIO.StringIO()
2251 self.mock(git_cl.sys, 'stdout', out)
2252
2253 self.mock(git_cl, 'Changelist', ChangelistMock)
2254 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
2255
2256 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2257 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2258
kmarshall3bff56b2016-06-06 18:31:47 -07002259 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07002260 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2261
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002262 self.calls = [
2263 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002264 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002265 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2266 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002267 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002268 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002269
kmarshall3bff56b2016-06-06 18:31:47 -07002270 self.mock(git_cl, 'get_cl_statuses',
2271 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002272 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2273 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2274 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002275
2276 self.assertEqual(0, git_cl.main(['archive', '-f']))
2277
2278 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07002279 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002280 self.calls = [
2281 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2282 'refs/heads/master'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002283 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2284 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002285
kmarshall9249e012016-08-23 12:02:16 -07002286 self.mock(git_cl, 'get_cl_statuses',
2287 lambda branches, fine_grained, max_processes:
2288 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2289
2290 self.assertEqual(1, git_cl.main(['archive', '-f']))
2291
2292 def test_archive_dry_run(self):
2293 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2294
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002295 self.calls = [
2296 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2297 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002298 ((['git', 'symbolic-ref', 'HEAD'],), 'master')
2299 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002300
2301 self.mock(git_cl, 'get_cl_statuses',
2302 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002303 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2304 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2305 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002306
kmarshall9249e012016-08-23 12:02:16 -07002307 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2308
2309 def test_archive_no_tags(self):
2310 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2311
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002312 self.calls = [
2313 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2314 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002315 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2316 ((['git', 'branch', '-D', 'foo'],), '')
2317 ]
kmarshall9249e012016-08-23 12:02:16 -07002318
2319 self.mock(git_cl, 'get_cl_statuses',
2320 lambda branches, fine_grained, max_processes:
2321 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2322 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2323 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2324
2325 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002326
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002327 def test_cmd_issue_erase_existing(self):
2328 out = StringIO.StringIO()
2329 self.mock(git_cl.sys, 'stdout', out)
2330 self.calls = [
2331 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002332 # Let this command raise exception (retcode=1) - it should be ignored.
2333 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002334 CERR1),
2335 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2336 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002337 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2338 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2339 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002340 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002341 ]
2342 self.assertEqual(0, git_cl.main(['issue', '0']))
2343
Aaron Gable400e9892017-07-12 15:31:21 -07002344 def test_cmd_issue_erase_existing_with_change_id(self):
2345 out = StringIO.StringIO()
2346 self.mock(git_cl.sys, 'stdout', out)
2347 self.mock(git_cl.Changelist, 'GetDescription',
2348 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2349 self.calls = [
2350 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Aaron Gable400e9892017-07-12 15:31:21 -07002351 # Let this command raise exception (retcode=1) - it should be ignored.
2352 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2353 CERR1),
2354 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2355 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2356 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2357 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2358 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002359 ((['git', 'log', '-1', '--format=%B'],),
2360 'This is a description\n\nChange-Id: Ideadbeef'),
2361 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002362 ]
2363 self.assertEqual(0, git_cl.main(['issue', '0']))
2364
phajdan.jre328cf92016-08-22 04:12:17 -07002365 def test_cmd_issue_json(self):
2366 out = StringIO.StringIO()
2367 self.mock(git_cl.sys, 'stdout', out)
2368 self.calls = [
2369 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002370 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2371 ((['git', 'config', 'branch.feature.gerritserver'],),
2372 'https://chromium-review.googlesource.com'),
phajdan.jre328cf92016-08-22 04:12:17 -07002373 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002374 {'issue': 123,
2375 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002376 ''),
2377 ]
2378 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2379
tandrii16e0b4e2016-06-07 10:34:28 -07002380 def _common_GerritCommitMsgHookCheck(self):
2381 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2382 self.mock(git_cl.os.path, 'abspath',
2383 lambda path: self._mocked_call(['abspath', path]))
2384 self.mock(git_cl.os.path, 'exists',
2385 lambda path: self._mocked_call(['exists', path]))
2386 self.mock(git_cl.gclient_utils, 'FileRead',
2387 lambda path: self._mocked_call(['FileRead', path]))
2388 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2389 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2390 self.calls = [
2391 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2392 ((['abspath', '../'],), '/abs/git_repo_root'),
2393 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002394 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002395
2396 def test_GerritCommitMsgHookCheck_custom_hook(self):
2397 cl = self._common_GerritCommitMsgHookCheck()
2398 self.calls += [
2399 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2400 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2401 '#!/bin/sh\necho "custom hook"')
2402 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002403 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002404
2405 def test_GerritCommitMsgHookCheck_not_exists(self):
2406 cl = self._common_GerritCommitMsgHookCheck()
2407 self.calls += [
2408 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2409 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002410 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002411
2412 def test_GerritCommitMsgHookCheck(self):
2413 cl = self._common_GerritCommitMsgHookCheck()
2414 self.calls += [
2415 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2416 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2417 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002418 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002419 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2420 ''),
2421 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002422 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002423
tandriic4344b52016-08-29 06:04:54 -07002424 def test_GerritCmdLand(self):
2425 self.calls += [
2426 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2427 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2428 'deadbeaf'),
2429 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2430 ((['git', 'config', 'branch.feature.gerritserver'],),
2431 'chromium-review.googlesource.com'),
2432 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002433 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002434 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002435 'labels': {},
2436 'current_revision': 'deadbeaf',
2437 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002438 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002439 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002440 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002441 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2442 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002443 cl.SubmitIssue = lambda wait_for_merge: None
tandrii8da412c2016-09-07 16:01:07 -07002444 out = StringIO.StringIO()
2445 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002446 self.assertEqual(0, cl.CMDLand(force=True,
2447 bypass_hooks=True,
2448 verbose=True,
2449 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002450 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002451 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002452
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002453 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemur125d60a2019-09-13 18:25:41 +00002454 self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002455
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002456 def test_gerrit_change_detail_cache_simple(self):
2457 self._mock_gerrit_changes_for_detail_cache()
2458 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002459 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2460 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2461 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002462 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002463 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002464 cl1._cached_remote_url = (
2465 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002466 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002467 cl2._cached_remote_url = (
2468 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002469 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2470 self.assertEqual(cl1._GetChangeDetail(), 'a')
2471 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2472 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2473 self.assertEqual(cl1._GetChangeDetail(), 'a')
2474 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002475
2476 def test_gerrit_change_detail_cache_options(self):
2477 self._mock_gerrit_changes_for_detail_cache()
2478 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002479 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2480 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2481 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2482 # no longer in cache.
2483 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002484 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002485 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002486 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002487 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2488 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2489 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2490 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2491 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2492 self.assertEqual(cl._GetChangeDetail(), 'cab')
2493
2494 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2495 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2496 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2497 self.assertEqual(cl._GetChangeDetail(), 'cab')
2498
2499 # Finally, no_cache should invalidate all caches for given change.
2500 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2501 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2502
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002503 def test_gerrit_description_caching(self):
2504 def gen_detail(rev, desc):
2505 return {
2506 'current_revision': rev,
2507 'revisions': {rev: {'commit': {'message': desc}}}
2508 }
2509 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002510 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002511 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2512 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002513 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002514 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2515 gen_detail('rev2', 'desc2')),
2516 ]
2517
2518 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002519 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002520 cl._cached_remote_url = (
2521 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002522 self.assertEqual(cl.GetDescription(), 'desc1')
2523 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2524 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002525
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002526 def test_print_current_creds(self):
2527 class CookiesAuthenticatorMock(object):
2528 def __init__(self):
2529 self.gitcookies = {
2530 'host.googlesource.com': ('user', 'pass'),
2531 'host-review.googlesource.com': ('user', 'pass'),
2532 }
2533 self.netrc = self
2534 self.netrc.hosts = {
2535 'github.com': ('user2', None, 'pass2'),
2536 'host2.googlesource.com': ('user3', None, 'pass'),
2537 }
2538 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2539 CookiesAuthenticatorMock)
2540 self.mock(sys, 'stdout', StringIO.StringIO())
2541 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2542 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2543 ' Host\t User\t Which file',
2544 '============================\t=====\t===========',
2545 'host-review.googlesource.com\t user\t.gitcookies',
2546 ' host.googlesource.com\t user\t.gitcookies',
2547 ' host2.googlesource.com\tuser3\t .netrc',
2548 ])
2549 sys.stdout.buf = ''
2550 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2551 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2552 ' Host\tUser\t Which file',
2553 '============================\t====\t===========',
2554 'host-review.googlesource.com\tuser\t.gitcookies',
2555 ' host.googlesource.com\tuser\t.gitcookies',
2556 ])
2557
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002558 def _common_creds_check_mocks(self):
2559 def exists_mock(path):
2560 dirname = os.path.dirname(path)
2561 if dirname == os.path.expanduser('~'):
2562 dirname = '~'
2563 base = os.path.basename(path)
2564 if base in ('.netrc', '.gitcookies'):
2565 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2566 # git cl also checks for existence other files not relevant to this test.
2567 return None
2568 self.mock(os.path, 'exists', exists_mock)
2569 self.mock(sys, 'stdout', StringIO.StringIO())
2570
2571 def test_creds_check_gitcookies_not_configured(self):
2572 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002573 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002574 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002575 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002576 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002577 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2578 (('os.path.exists', '~/.netrc'), True),
2579 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2580 'or Ctrl+C to abort'), ''),
2581 ((['git', 'config', '--global', 'http.cookiefile',
2582 os.path.expanduser('~/.gitcookies')], ), ''),
2583 ]
2584 self.assertEqual(0, git_cl.main(['creds-check']))
2585 self.assertRegexpMatches(
2586 sys.stdout.getvalue(),
2587 '^You seem to be using outdated .netrc for git credentials:')
2588 self.assertRegexpMatches(
2589 sys.stdout.getvalue(),
2590 '\nConfigured git to use .gitcookies from')
2591
2592 def test_creds_check_gitcookies_configured_custom_broken(self):
2593 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002594 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002595 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002596 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002597 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002598 ((['git', 'config', '--global', 'http.cookiefile'],),
2599 '/custom/.gitcookies'),
2600 (('os.path.exists', '/custom/.gitcookies'), False),
2601 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2602 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2603 ((['git', 'config', '--global', 'http.cookiefile',
2604 os.path.expanduser('~/.gitcookies')], ), ''),
2605 ]
2606 self.assertEqual(0, git_cl.main(['creds-check']))
2607 self.assertRegexpMatches(
2608 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002609 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002610 self.assertRegexpMatches(
2611 sys.stdout.getvalue(),
2612 'However, your configured .gitcookies file is missing.')
2613
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002614 def test_git_cl_comment_add_gerrit(self):
2615 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002616 lambda host, change, msg, ready:
2617 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002618 self.calls = [
2619 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2620 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2621 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2622 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2623 'origin/master'),
2624 ((['git', 'config', 'remote.origin.url'],),
2625 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002626 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2627 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002628 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002629 ]
2630 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2631 '-a', 'msg']))
2632
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002633 def test_git_cl_comments_fetch_gerrit(self):
2634 self.mock(sys, 'stdout', StringIO.StringIO())
2635 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002636 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2637 ((['git', 'config', 'branch.foo.merge'],), ''),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002638 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2639 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2640 'origin/master'),
2641 ((['git', 'config', 'remote.origin.url'],),
2642 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002643 (('GetChangeDetail', 'chromium-review.googlesource.com',
2644 'infra%2Finfra~1',
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002645 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2646 'CURRENT_COMMIT']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002647 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002648 'current_revision': 'ba5eba11',
2649 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002650 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002651 '_number': 1,
2652 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002653 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002654 '_number': 2,
2655 },
2656 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002657 'messages': [
2658 {
2659 u'_revision_number': 1,
2660 u'author': {
2661 u'_account_id': 1111084,
2662 u'email': u'commit-bot@chromium.org',
2663 u'name': u'Commit Bot'
2664 },
2665 u'date': u'2017-03-15 20:08:45.000000000',
2666 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002667 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002668 u'tag': u'autogenerated:cq:dry-run'
2669 },
2670 {
2671 u'_revision_number': 2,
2672 u'author': {
2673 u'_account_id': 11151243,
2674 u'email': u'owner@example.com',
2675 u'name': u'owner'
2676 },
2677 u'date': u'2017-03-16 20:00:41.000000000',
2678 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2679 u'message': u'PTAL',
2680 },
2681 {
2682 u'_revision_number': 2,
2683 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002684 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002685 u'email': u'reviewer@example.com',
2686 u'name': u'reviewer'
2687 },
2688 u'date': u'2017-03-17 05:19:37.500000000',
2689 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2690 u'message': u'Patch Set 2: Code-Review+1',
2691 },
2692 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002693 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002694 (('GetChangeComments', 'chromium-review.googlesource.com',
2695 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002696 '/COMMIT_MSG': [
2697 {
2698 'author': {'email': u'reviewer@example.com'},
2699 'updated': u'2017-03-17 05:19:37.500000000',
2700 'patch_set': 2,
2701 'side': 'REVISION',
2702 'message': 'Please include a bug link',
2703 },
2704 ],
2705 'codereview.settings': [
2706 {
2707 'author': {'email': u'owner@example.com'},
2708 'updated': u'2017-03-16 20:00:41.000000000',
2709 'patch_set': 2,
2710 'side': 'PARENT',
2711 'line': 42,
2712 'message': 'I removed this because it is bad',
2713 },
2714 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002715 }),
2716 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2717 'infra%2Finfra~1'), {}),
2718 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002719 ] * 2 + [
2720 (('write_json', 'output.json', [
2721 {
2722 u'date': u'2017-03-16 20:00:41.000000',
2723 u'message': (
2724 u'PTAL\n' +
2725 u'\n' +
2726 u'codereview.settings\n' +
2727 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2728 u'c/1/2/codereview.settings#b42\n' +
2729 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002730 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002731 u'approval': False,
2732 u'disapproval': False,
2733 u'sender': u'owner@example.com'
2734 }, {
2735 u'date': u'2017-03-17 05:19:37.500000',
2736 u'message': (
2737 u'Patch Set 2: Code-Review+1\n' +
2738 u'\n' +
2739 u'/COMMIT_MSG\n' +
2740 u' PS2, File comment: https://chromium-review.googlesource' +
2741 u'.com/c/1/2//COMMIT_MSG#\n' +
2742 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002743 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002744 u'approval': False,
2745 u'disapproval': False,
2746 u'sender': u'reviewer@example.com'
2747 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002748 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002749 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002750 expected_comments_summary = [
2751 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002752 message=(
2753 u'PTAL\n' +
2754 u'\n' +
2755 u'codereview.settings\n' +
2756 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2757 u'c/1/2/codereview.settings#b42\n' +
2758 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002759 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002760 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002761 disapproval=False, approval=False, sender=u'owner@example.com'),
2762 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002763 message=(
2764 u'Patch Set 2: Code-Review+1\n' +
2765 u'\n' +
2766 u'/COMMIT_MSG\n' +
2767 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2768 u'c/1/2//COMMIT_MSG#\n' +
2769 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002770 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002771 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002772 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2773 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002774 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002775 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002776 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002777 self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
2778 self.assertEqual(
2779 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2780
2781 def test_git_cl_comments_robot_comments(self):
2782 # git cl comments also fetches robot comments (which are considered a type
2783 # of autogenerated comment), and unlike other types of comments, only robot
2784 # comments from the latest patchset are shown.
2785 self.mock(sys, 'stdout', StringIO.StringIO())
2786 self.calls = [
2787 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2788 ((['git', 'config', 'branch.foo.merge'],), ''),
2789 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2790 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2791 'origin/master'),
2792 ((['git', 'config', 'remote.origin.url'],),
2793 'https://chromium.googlesource.com/infra/infra'),
2794 (('GetChangeDetail', 'chromium-review.googlesource.com',
2795 'infra%2Finfra~1',
2796 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2797 'CURRENT_COMMIT']), {
2798 'owner': {'email': 'owner@example.com'},
2799 'current_revision': 'ba5eba11',
2800 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002801 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002802 '_number': 1,
2803 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002804 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002805 '_number': 2,
2806 },
2807 },
2808 'messages': [
2809 {
2810 u'_revision_number': 1,
2811 u'author': {
2812 u'_account_id': 1111084,
2813 u'email': u'commit-bot@chromium.org',
2814 u'name': u'Commit Bot'
2815 },
2816 u'date': u'2017-03-15 20:08:45.000000000',
2817 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2818 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2819 u'tag': u'autogenerated:cq:dry-run'
2820 },
2821 {
2822 u'_revision_number': 1,
2823 u'author': {
2824 u'_account_id': 123,
2825 u'email': u'tricium@serviceaccount.com',
2826 u'name': u'Tricium'
2827 },
2828 u'date': u'2017-03-16 20:00:41.000000000',
2829 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2830 u'message': u'(1 comment)',
2831 u'tag': u'autogenerated:tricium',
2832 },
2833 {
2834 u'_revision_number': 1,
2835 u'author': {
2836 u'_account_id': 123,
2837 u'email': u'tricium@serviceaccount.com',
2838 u'name': u'Tricium'
2839 },
2840 u'date': u'2017-03-16 20:00:41.000000000',
2841 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2842 u'message': u'(1 comment)',
2843 u'tag': u'autogenerated:tricium',
2844 },
2845 {
2846 u'_revision_number': 2,
2847 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002848 u'_account_id': 123,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002849 u'email': u'tricium@serviceaccount.com',
2850 u'name': u'reviewer'
2851 },
2852 u'date': u'2017-03-17 05:30:37.000000000',
2853 u'tag': u'autogenerated:tricium',
2854 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2855 u'message': u'(1 comment)',
2856 },
2857 ]
2858 }),
2859 (('GetChangeComments', 'chromium-review.googlesource.com',
2860 'infra%2Finfra~1'), {}),
2861 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2862 'infra%2Finfra~1'), {
2863 'codereview.settings': [
2864 {
2865 u'author': {u'email': u'tricium@serviceaccount.com'},
2866 u'updated': u'2017-03-17 05:30:37.000000000',
2867 u'robot_run_id': u'5565031076855808',
2868 u'robot_id': u'Linter/Category',
2869 u'tag': u'autogenerated:tricium',
2870 u'patch_set': 2,
2871 u'side': u'REVISION',
2872 u'message': u'Linter warning message text',
2873 u'line': 32,
2874 },
2875 ],
2876 }),
2877 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
2878 ]
2879 expected_comments_summary = [
2880 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2881 message=(
2882 u'(1 comment)\n\ncodereview.settings\n'
2883 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2884 u'c/1/2/codereview.settings#32\n'
2885 u' Linter warning message text\n'),
2886 sender=u'tricium@serviceaccount.com',
2887 autogenerated=True, approval=False, disapproval=False)
2888 ]
2889 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002890 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002891 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002892
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002893 def test_get_remote_url_with_mirror(self):
2894 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002895
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002896 def selective_os_path_isdir_mock(path):
2897 if path == '/cache/this-dir-exists':
2898 return self._mocked_call('os.path.isdir', path)
2899 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002900
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002901 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2902
2903 url = 'https://chromium.googlesource.com/my/repo'
2904 self.calls = [
2905 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2906 ((['git', 'config', 'branch.master.merge'],), 'master'),
2907 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2908 ((['git', 'config', 'remote.origin.url'],),
2909 '/cache/this-dir-exists'),
2910 (('os.path.isdir', '/cache/this-dir-exists'),
2911 True),
2912 # Runs in /cache/this-dir-exists.
2913 ((['git', 'config', 'remote.origin.url'],),
2914 url),
2915 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002916 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002917 self.assertEqual(cl.GetRemoteUrl(), url)
2918 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2919
Edward Lemur298f2cf2019-02-22 21:40:39 +00002920 def test_get_remote_url_non_existing_mirror(self):
2921 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002922
Edward Lemur298f2cf2019-02-22 21:40:39 +00002923 def selective_os_path_isdir_mock(path):
2924 if path == '/cache/this-dir-doesnt-exist':
2925 return self._mocked_call('os.path.isdir', path)
2926 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002927
Edward Lemur298f2cf2019-02-22 21:40:39 +00002928 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2929 self.mock(logging, 'error',
2930 lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
2931
2932 self.calls = [
2933 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2934 ((['git', 'config', 'branch.master.merge'],), 'master'),
2935 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2936 ((['git', 'config', 'remote.origin.url'],),
2937 '/cache/this-dir-doesnt-exist'),
2938 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2939 False),
2940 (('logging.error',
Daniel Bratell4a60db42019-09-16 17:02:52 +00002941 'Remote "origin" for branch "master" points to'
2942 ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002943 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002944 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002945 self.assertIsNone(cl.GetRemoteUrl())
2946
2947 def test_get_remote_url_misconfigured_mirror(self):
2948 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002949
Edward Lemur298f2cf2019-02-22 21:40:39 +00002950 def selective_os_path_isdir_mock(path):
2951 if path == '/cache/this-dir-exists':
2952 return self._mocked_call('os.path.isdir', path)
2953 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002954
Edward Lemur298f2cf2019-02-22 21:40:39 +00002955 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2956 self.mock(logging, 'error',
2957 lambda *a: self._mocked_call('logging.error', *a))
2958
2959 self.calls = [
2960 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2961 ((['git', 'config', 'branch.master.merge'],), 'master'),
2962 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2963 ((['git', 'config', 'remote.origin.url'],),
2964 '/cache/this-dir-exists'),
2965 (('os.path.isdir', '/cache/this-dir-exists'), True),
2966 # Runs in /cache/this-dir-exists.
2967 ((['git', 'config', 'remote.origin.url'],), ''),
2968 (('logging.error',
2969 'Remote "%(remote)s" for branch "%(branch)s" points to '
2970 '"%(cache_path)s", but it is misconfigured.\n'
2971 '"%(cache_path)s" must be a git repo and must have a remote named '
2972 '"%(remote)s" pointing to the git host.', {
2973 'remote': 'origin',
2974 'cache_path': '/cache/this-dir-exists',
2975 'branch': 'master'}
2976 ), None),
2977 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002978 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002979 self.assertIsNone(cl.GetRemoteUrl())
2980
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002981 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002982 self.calls = [
2983 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2984 ((['git', 'config', 'branch.master.merge'],), 'master'),
2985 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2986 ((['git', 'config', 'remote.origin.url'],),
2987 'https://chromium.googlesource.com/a/my/repo.git/'),
2988 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002989 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002990 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2991
2992 def test_gerrit_change_identifier_without_project(self):
2993 self.calls = [
2994 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2995 ((['git', 'config', 'branch.master.merge'],), 'master'),
2996 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2997 ((['git', 'config', 'remote.origin.url'],), CERR1),
2998 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002999 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003000 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003001
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003002
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003003class CMDTestCaseBase(unittest.TestCase):
3004 _STATUSES = [
3005 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3006 'INFRA_FAILURE', 'CANCELED',
3007 ]
3008 _CHANGE_DETAIL = {
3009 'project': 'depot_tools',
3010 'status': 'OPEN',
3011 'owner': {'email': 'owner@e.mail'},
3012 'current_revision': 'beeeeeef',
3013 'revisions': {
3014 'deadbeaf': {'_number': 6},
3015 'beeeeeef': {
3016 '_number': 7,
3017 'fetch': {'http': {
3018 'url': 'https://chromium.googlesource.com/depot_tools',
3019 'ref': 'refs/changes/56/123456/7'
3020 }},
3021 },
3022 },
3023 }
3024 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003025 'builds': [{
3026 'id': str(100 + idx),
3027 'builder': {
3028 'project': 'chromium',
3029 'bucket': 'try',
3030 'builder': 'bot_' + status.lower(),
3031 },
3032 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3033 'tags': [],
3034 'status': status,
3035 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003036 }
3037
Edward Lemur4c707a22019-09-24 21:13:43 +00003038 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003039 super(CMDTestCaseBase, self).setUp()
Edward Lemur4c707a22019-09-24 21:13:43 +00003040 mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003041 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3042 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003043 mock.patch('git_cl.Changelist.GetCodereviewServer',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003044 return_value='https://chromium-review.googlesource.com').start()
3045 mock.patch('git_cl.Changelist.GetMostRecentPatchset',
3046 return_value=7).start()
Edward Lemur5b929a42019-10-21 17:57:39 +00003047 mock.patch('git_cl.auth.Authenticator',
Edward Lemurb4a587d2019-10-09 23:56:38 +00003048 return_value=AuthenticatorMock()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003049 mock.patch('git_cl.Changelist._GetChangeDetail',
3050 return_value=self._CHANGE_DETAIL).start()
3051 mock.patch('git_cl._call_buildbucket',
3052 return_value = self._DEFAULT_RESPONSE).start()
3053 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003054 self.addCleanup(mock.patch.stopall)
3055
Edward Lemur4c707a22019-09-24 21:13:43 +00003056
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003057class CMDTryResultsTestCase(CMDTestCaseBase):
3058 _DEFAULT_REQUEST = {
3059 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003060 "gerritChanges": [{
3061 "project": "depot_tools",
3062 "host": "chromium-review.googlesource.com",
3063 "patchset": 7,
3064 "change": 123456,
3065 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003066 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003067 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3068 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003069 }
3070
3071 def testNoJobs(self):
3072 git_cl._call_buildbucket.return_value = {}
3073
3074 self.assertEqual(0, git_cl.main(['try-results']))
3075 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3076 git_cl._call_buildbucket.assert_called_once_with(
3077 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3078 self._DEFAULT_REQUEST)
3079
3080 def testPrintToStdout(self):
3081 self.assertEqual(0, git_cl.main(['try-results']))
3082 self.assertEqual([
3083 'Successes:',
3084 ' bot_success https://ci.chromium.org/b/103',
3085 'Infra Failures:',
3086 ' bot_infra_failure https://ci.chromium.org/b/105',
3087 'Failures:',
3088 ' bot_failure https://ci.chromium.org/b/104',
3089 'Canceled:',
3090 ' bot_canceled ',
3091 'Started:',
3092 ' bot_started https://ci.chromium.org/b/102',
3093 'Scheduled:',
3094 ' bot_scheduled id=101',
3095 'Other:',
3096 ' bot_status_unspecified id=100',
3097 'Total: 7 tryjobs',
3098 ], sys.stdout.getvalue().splitlines())
3099 git_cl._call_buildbucket.assert_called_once_with(
3100 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3101 self._DEFAULT_REQUEST)
3102
3103 def testPrintToStdoutWithMasters(self):
3104 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3105 self.assertEqual([
3106 'Successes:',
3107 ' try bot_success https://ci.chromium.org/b/103',
3108 'Infra Failures:',
3109 ' try bot_infra_failure https://ci.chromium.org/b/105',
3110 'Failures:',
3111 ' try bot_failure https://ci.chromium.org/b/104',
3112 'Canceled:',
3113 ' try bot_canceled ',
3114 'Started:',
3115 ' try bot_started https://ci.chromium.org/b/102',
3116 'Scheduled:',
3117 ' try bot_scheduled id=101',
3118 'Other:',
3119 ' try bot_status_unspecified id=100',
3120 'Total: 7 tryjobs',
3121 ], sys.stdout.getvalue().splitlines())
3122 git_cl._call_buildbucket.assert_called_once_with(
3123 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3124 self._DEFAULT_REQUEST)
3125
3126 @mock.patch('git_cl.write_json')
3127 def testWriteToJson(self, mockJsonDump):
3128 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3129 git_cl._call_buildbucket.assert_called_once_with(
3130 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3131 self._DEFAULT_REQUEST)
3132 mockJsonDump.assert_called_once_with(
3133 'file.json', self._DEFAULT_RESPONSE['builds'])
3134
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003135 def test_filter_failed_for_one_simple(self):
3136 self.assertEqual({}, git_cl._filter_failed_for_retry([]))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003137 self.assertEqual({
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003138 'chromium/try': {
3139 'bot_failure': [],
3140 'bot_infra_failure': []
3141 },
3142 }, git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
3143
3144 def test_filter_failed_for_retry_many_builds(self):
3145
3146 def _build(name, created_sec, status, experimental=False):
3147 assert 0 <= created_sec < 100, created_sec
3148 b = {
3149 'id': 112112,
3150 'builder': {
3151 'project': 'chromium',
3152 'bucket': 'try',
3153 'builder': name,
3154 },
3155 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3156 'status': status,
3157 'tags': [],
3158 }
3159 if experimental:
3160 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3161 return b
3162
3163 builds = [
3164 _build('flaky-last-green', 1, 'FAILURE'),
3165 _build('flaky-last-green', 2, 'SUCCESS'),
3166 _build('flaky', 1, 'SUCCESS'),
3167 _build('flaky', 2, 'FAILURE'),
3168 _build('running', 1, 'FAILED'),
3169 _build('running', 2, 'SCHEDULED'),
3170 _build('yep-still-running', 1, 'STARTED'),
3171 _build('yep-still-running', 2, 'FAILURE'),
3172 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3173 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3174
3175 # Simulate experimental in CQ builder, which developer decided
3176 # to retry manually which resulted in 2nd build non-experimental.
3177 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3178 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3179 ]
3180 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
3181 self.assertEqual({
3182 'chromium/try': {
3183 'flaky': [],
3184 'sometimes-experimental': []
3185 },
3186 }, git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003187
3188
3189class CMDTryTestCase(CMDTestCaseBase):
3190
3191 @mock.patch('git_cl.Changelist.SetCQState')
3192 @mock.patch('git_cl._get_bucket_map', return_value={})
3193 def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
3194 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003195 self.assertEqual(0, git_cl.main(['try']))
3196 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3197 self.assertEqual(
3198 sys.stdout.getvalue(),
3199 'Scheduling CQ dry run on: '
3200 'https://chromium-review.googlesource.com/123456\n')
3201
Edward Lemur4c707a22019-09-24 21:13:43 +00003202 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003203 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003204 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003205
3206 self.assertEqual(0, git_cl.main([
3207 'try', '-B', 'luci.chromium.try', '-b', 'win',
3208 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3209 self.assertIn(
3210 'Scheduling jobs on:\nBucket: luci.chromium.try',
3211 git_cl.sys.stdout.getvalue())
3212
3213 expected_request = {
3214 "requests": [{
3215 "scheduleBuild": {
3216 "requestId": "uuid4",
3217 "builder": {
3218 "project": "chromium",
3219 "builder": "win",
3220 "bucket": "try",
3221 },
3222 "gerritChanges": [{
3223 "project": "depot_tools",
3224 "host": "chromium-review.googlesource.com",
3225 "patchset": 7,
3226 "change": 123456,
3227 }],
3228 "properties": {
3229 "category": "git_cl_try",
3230 "json": [{"a": 1}, None],
3231 "key": "val",
3232 },
3233 "tags": [
3234 {"value": "win", "key": "builder"},
3235 {"value": "git_cl_try", "key": "user_agent"},
3236 ],
3237 },
3238 }],
3239 }
3240 mockCallBuildbucket.assert_called_with(
3241 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3242
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003243 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur4c707a22019-09-24 21:13:43 +00003244 self.assertEqual(0, git_cl.main([
3245 'try', '-B', 'not-a-bucket', '-b', 'win',
3246 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3247 self.assertIn(
3248 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3249 git_cl.sys.stdout.getvalue())
3250
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003251 @mock.patch('git_cl._call_buildbucket')
3252 @mock.patch('git_cl.fetch_try_jobs')
3253 def testScheduleOnBuildbucketRetryFailed(
3254 self, mockFetchTryJobs, mockCallBuildbucket):
3255
3256 git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
3257 7: [],
3258 6: [{
3259 'id': 112112,
3260 'builder': {
3261 'project': 'chromium',
3262 'bucket': 'try',
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003263 'builder': 'linux',},
3264 'createTime': '2019-10-09T08:00:01.854286Z',
3265 'tags': [],
3266 'status': 'FAILURE',}],}[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003267 mockCallBuildbucket.return_value = {}
3268
3269 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3270 self.assertIn(
3271 'Scheduling jobs on:\nBucket: chromium/try',
3272 git_cl.sys.stdout.getvalue())
3273
3274 expected_request = {
3275 "requests": [{
3276 "scheduleBuild": {
3277 "requestId": "uuid4",
3278 "builder": {
3279 "project": "chromium",
3280 "bucket": "try",
3281 "builder": "linux",
3282 },
3283 "gerritChanges": [{
3284 "project": "depot_tools",
3285 "host": "chromium-review.googlesource.com",
3286 "patchset": 7,
3287 "change": 123456,
3288 }],
3289 "properties": {
3290 "category": "git_cl_try",
3291 },
3292 "tags": [
3293 {"value": "linux", "key": "builder"},
3294 {"value": "git_cl_try", "key": "user_agent"},
3295 {"value": "1", "key": "retry_failed"},
3296 ],
3297 },
3298 }],
3299 }
3300 mockCallBuildbucket.assert_called_with(
3301 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3302
Edward Lemur4c707a22019-09-24 21:13:43 +00003303 def test_parse_bucket(self):
3304 test_cases = [
3305 {
3306 'bucket': 'chromium/try',
3307 'result': ('chromium', 'try'),
3308 },
3309 {
3310 'bucket': 'luci.chromium.try',
3311 'result': ('chromium', 'try'),
3312 'has_warning': True,
3313 },
3314 {
3315 'bucket': 'skia.primary',
3316 'result': ('skia', 'skia.primary'),
3317 'has_warning': True,
3318 },
3319 {
3320 'bucket': 'not-a-bucket',
3321 'result': (None, None),
3322 },
3323 ]
3324
3325 for test_case in test_cases:
3326 git_cl.sys.stdout.truncate(0)
3327 self.assertEqual(
3328 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3329 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003330 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3331 test_case['result'])
3332 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003333
3334
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003335class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003336 def setUp(self):
3337 super(CMDUploadTestCase, self).setUp()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003338 mock.patch('git_cl.fetch_try_jobs').start()
3339 mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
3340 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003341 self.addCleanup(mock.patch.stopall)
3342
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003343 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003344 # This test mocks out the actual upload part, and just asserts that after
3345 # upload, if --retry-failed is added, then the tool will fetch try jobs
3346 # from the previous patchset and trigger the right builders on the latest
3347 # patchset.
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003348 git_cl.fetch_try_jobs.side_effect = [
3349 # Latest patchset: No builds.
3350 [],
3351 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003352 [{
3353 'id': str(100 + idx),
3354 'builder': {
3355 'project': 'chromium',
3356 'bucket': 'try',
3357 'builder': 'bot_' + status.lower(),
3358 },
3359 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3360 'tags': [],
3361 'status': status,
3362 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003363 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003364
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003365 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003366 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003367 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3368 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003369 ], git_cl.fetch_try_jobs.mock_calls)
3370 expected_buckets = {
3371 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
3372 }
3373 git_cl._trigger_try_jobs.assert_called_once_with(
Edward Lemur5b929a42019-10-21 17:57:39 +00003374 mock.ANY, expected_buckets, mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003375
Brian Sheedy59b06a82019-10-14 17:03:29 +00003376
3377class CMDFormatTestCase(TestCase):
3378
3379 def setUp(self):
3380 super(CMDFormatTestCase, self).setUp()
3381 self._top_dir = tempfile.mkdtemp()
3382
3383 def tearDown(self):
3384 shutil.rmtree(self._top_dir)
3385 super(CMDFormatTestCase, self).tearDown()
3386
3387 def _make_yapfignore(self, contents):
3388 with open(os.path.join(self._top_dir, '.yapfignore'), 'w') as yapfignore:
3389 yapfignore.write('\n'.join(contents))
3390
3391 def _make_files(self, file_dict):
3392 for directory, files in file_dict.iteritems():
3393 subdir = os.path.join(self._top_dir, directory)
3394 if not os.path.exists(subdir):
3395 os.makedirs(subdir)
3396 for f in files:
3397 with open(os.path.join(subdir, f), 'w'):
3398 pass
3399
3400 def testYapfignoreBasic(self):
3401 self._make_yapfignore(['test.py', '*/bar.py'])
3402 self._make_files({
3403 '.': ['test.py', 'bar.py'],
3404 'foo': ['bar.py'],
3405 })
3406 self.assertEqual(
3407 set(['test.py', 'foo/bar.py']),
3408 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3409
3410 def testYapfignoreMissingYapfignore(self):
3411 self.assertEqual(set(), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3412
3413 def testYapfignoreMissingFile(self):
3414 self._make_yapfignore(['test.py', 'test2.py', 'test3.py'])
3415 self._make_files({
3416 '.': ['test.py', 'test3.py'],
3417 })
3418 self.assertEqual(
3419 set(['test.py', 'test3.py']),
3420 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3421
3422 def testYapfignoreComments(self):
3423 self._make_yapfignore(['test.py', '#test2.py'])
3424 self._make_files({
3425 '.': ['test.py', 'test2.py'],
3426 })
3427 self.assertEqual(
3428 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3429
3430 def testYapfignoreBlankLines(self):
3431 self._make_yapfignore(['test.py', '', '', 'test2.py'])
3432 self._make_files({'.': ['test.py', 'test2.py']})
3433 self.assertEqual(
3434 set(['test.py', 'test2.py']),
3435 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3436
3437 def testYapfignoreWhitespace(self):
3438 self._make_yapfignore([' test.py '])
3439 self._make_files({'.': ['test.py']})
3440 self.assertEqual(
3441 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3442
3443 def testYapfignoreMultiWildcard(self):
3444 self._make_yapfignore(['*es*.py'])
3445 self._make_files({
3446 '.': ['test.py', 'test2.py'],
3447 })
3448 self.assertEqual(
3449 set(['test.py', 'test2.py']),
3450 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3451
3452 def testYapfignoreRestoresDirectory(self):
3453 self._make_yapfignore(['test.py'])
3454 self._make_files({
3455 '.': ['test.py'],
3456 })
3457 old_cwd = os.getcwd()
3458 self.assertEqual(
3459 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3460 self.assertEqual(old_cwd, os.getcwd())
3461
3462
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003463if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003464 logging.basicConfig(
3465 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003466 unittest.main()