blob: 63b9b0c5dae43fc783ae8b51197765950e0df5bf [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 Shyshkalovcd6a9362016-12-07 12:04:12 +01008import contextlib
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01009import datetime
tandriide281ae2016-10-12 06:02:30 -070010import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010011import logging
maruel@chromium.orgddd59412011-11-30 14:20:38 +000012import os
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
22
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000023import metrics
24# We have to disable monitoring before importing git_cl.
25metrics.DISABLE_METRICS_COLLECTION = True
26
Eric Boren2fb63102018-10-05 13:05:03 +000027import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000028import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000029import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000030import git_footers
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000032
tandrii5d48c322016-08-18 16:19:37 -070033def callError(code=1, cmd='', cwd='', stdout='', stderr=''):
34 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
35
36
37CERR1 = callError(1)
38
39
Aaron Gable9a03ae02017-11-03 11:31:07 -070040def MakeNamedTemporaryFileMock(expected_content):
41 class NamedTemporaryFileMock(object):
42 def __init__(self, *args, **kwargs):
43 self.name = '/tmp/named'
44 self.expected_content = expected_content
45
46 def __enter__(self):
47 return self
48
49 def __exit__(self, _type, _value, _tb):
50 pass
51
52 def write(self, content):
53 if self.expected_content:
54 assert content == self.expected_content
55
56 def close(self):
57 pass
58
59 return NamedTemporaryFileMock
60
61
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000062class ChangelistMock(object):
63 # A class variable so we can access it when we don't have access to the
64 # instance that's being set.
65 desc = ""
66 def __init__(self, **kwargs):
67 pass
68 def GetIssue(self):
69 return 1
Kenneth Russell61e2ed42017-02-15 11:47:13 -080070 def GetDescription(self, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000071 return ChangelistMock.desc
dsansomee2d6fd92016-09-08 00:10:47 -070072 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000073 ChangelistMock.desc = desc
74
tandrii5d48c322016-08-18 16:19:37 -070075
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000076class PresubmitMock(object):
77 def __init__(self, *args, **kwargs):
78 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080079 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
80
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000081 @staticmethod
82 def should_continue():
83 return True
84
85
skobes6468b902016-10-24 08:45:10 -070086class GitCheckoutMock(object):
87 def __init__(self, *args, **kwargs):
88 pass
89
90 @staticmethod
91 def reset():
92 GitCheckoutMock.conflict = False
93
94 def apply_patch(self, p):
95 if GitCheckoutMock.conflict:
96 raise Exception('failed')
97
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000098
99class WatchlistsMock(object):
100 def __init__(self, _):
101 pass
102 @staticmethod
103 def GetWatchersForPaths(_):
104 return ['joe@example.com']
105
106
ukai@chromium.org78c4b982012-02-14 02:20:26 +0000107class CodereviewSettingsFileMock(object):
108 def __init__(self):
109 pass
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800110 # pylint: disable=no-self-use
ukai@chromium.org78c4b982012-02-14 02:20:26 +0000111 def read(self):
112 return ("CODE_REVIEW_SERVER: gerrit.chromium.org\n" +
andybons@chromium.org11f46eb2016-02-02 19:26:51 +0000113 "GERRIT_HOST: True\n")
ukai@chromium.org78c4b982012-02-14 02:20:26 +0000114
115
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000116class AuthenticatorMock(object):
117 def __init__(self, *_args):
118 pass
119 def has_cached_credentials(self):
120 return True
tandrii221ab252016-10-06 08:12:04 -0700121 def authorize(self, http):
122 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000123
124
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100125def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000126 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
127
128 Usage:
129 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100130 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000131
132 OR
133 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100134 CookiesAuthenticatorMockFactory(
135 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000136 """
137 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800138 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000139 # Intentionally not calling super() because it reads actual cookie files.
140 pass
141 @classmethod
142 def get_gitcookies_path(cls):
143 return '~/.gitcookies'
144 @classmethod
145 def get_netrc_path(cls):
146 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100147 def _get_auth_for_host(self, host):
148 if same_auth:
149 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000150 return (hosts_with_creds or {}).get(host)
151 return CookiesAuthenticatorMock
152
Aaron Gable9a03ae02017-11-03 11:31:07 -0700153
kmarshall9249e012016-08-23 12:02:16 -0700154class MockChangelistWithBranchAndIssue():
155 def __init__(self, branch, issue):
156 self.branch = branch
157 self.issue = issue
158 def GetBranch(self):
159 return self.branch
160 def GetIssue(self):
161 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000162
tandriic2405f52016-10-10 08:13:15 -0700163
164class SystemExitMock(Exception):
165 pass
166
167
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000168class TestGitClBasic(unittest.TestCase):
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100169 def test_get_description(self):
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +0000170 cl = git_cl.Changelist(issue=1, codereview='gerrit',
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100171 codereview_host='host')
172 cl.description = 'x'
173 cl.has_description = True
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800174 cl._codereview_impl.FetchDescription = lambda *a, **kw: 'y'
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100175 self.assertEquals(cl.GetDescription(), 'x')
176 self.assertEquals(cl.GetDescription(force=True), 'y')
177 self.assertEquals(cl.GetDescription(), 'y')
178
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700179 def test_description_footers(self):
180 cl = git_cl.Changelist(issue=1, codereview='gerrit',
181 codereview_host='host')
182 cl.description = '\n'.join([
183 'This is some message',
184 '',
185 'It has some lines',
186 'and, also',
187 '',
188 'Some: Really',
189 'Awesome: Footers',
190 ])
191 cl.has_description = True
192 cl._codereview_impl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
193 msg, footers = cl.GetDescriptionFooters()
194 self.assertEquals(
195 msg, ['This is some message', '', 'It has some lines', 'and, also'])
196 self.assertEquals(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
197
198 msg.append('wut')
199 footers.append(('gnarly-dude', 'beans'))
200 cl.UpdateDescriptionFooters(msg, footers)
201 self.assertEquals(cl.GetDescription().splitlines(), [
202 'This is some message',
203 '',
204 'It has some lines',
205 'and, also',
206 'wut'
207 '',
208 'Some: Really',
209 'Awesome: Footers',
210 'Gnarly-Dude: beans',
211 ])
212
tandriif9aefb72016-07-01 09:06:51 -0700213 def test_get_bug_line_values(self):
214 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
215 self.assertEqual(f('', ''), [])
216 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
217 self.assertEqual(f('v8', '456'), ['v8:456'])
218 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
219 # Not nice, but not worth carying.
220 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
221 ['v8:456', 'chromium:123', 'v8:123'])
222
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100223 def _test_git_number(self, parent_msg, dest_ref, child_msg,
224 parent_hash='parenthash'):
225 desc = git_cl.ChangeDescription(child_msg)
226 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
227 return desc.description
228
229 def assertEqualByLine(self, actual, expected):
230 self.assertEqual(actual.splitlines(), expected.splitlines())
231
232 def test_git_number_bad_parent(self):
233 with self.assertRaises(ValueError):
234 self._test_git_number('Parent', 'refs/heads/master', 'Child')
235
236 def test_git_number_bad_parent_footer(self):
237 with self.assertRaises(AssertionError):
238 self._test_git_number(
239 'Parent\n'
240 '\n'
241 'Cr-Commit-Position: wrong',
242 'refs/heads/master', 'Child')
243
244 def test_git_number_bad_lineage_ignored(self):
245 actual = self._test_git_number(
246 'Parent\n'
247 '\n'
248 'Cr-Commit-Position: refs/heads/master@{#1}\n'
249 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
250 'refs/heads/master', 'Child')
251 self.assertEqualByLine(
252 actual,
253 'Child\n'
254 '\n'
255 'Cr-Commit-Position: refs/heads/master@{#2}\n'
256 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
257
258 def test_git_number_same_branch(self):
259 actual = self._test_git_number(
260 'Parent\n'
261 '\n'
262 'Cr-Commit-Position: refs/heads/master@{#12}',
263 dest_ref='refs/heads/master',
264 child_msg='Child')
265 self.assertEqualByLine(
266 actual,
267 'Child\n'
268 '\n'
269 'Cr-Commit-Position: refs/heads/master@{#13}')
270
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200271 def test_git_number_same_branch_mixed_footers(self):
272 actual = self._test_git_number(
273 'Parent\n'
274 '\n'
275 'Cr-Commit-Position: refs/heads/master@{#12}',
276 dest_ref='refs/heads/master',
277 child_msg='Child\n'
278 '\n'
279 'Broken-by: design\n'
280 'BUG=123')
281 self.assertEqualByLine(
282 actual,
283 'Child\n'
284 '\n'
285 'Broken-by: design\n'
286 'BUG=123\n'
287 'Cr-Commit-Position: refs/heads/master@{#13}')
288
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100289 def test_git_number_same_branch_with_originals(self):
290 actual = self._test_git_number(
291 'Parent\n'
292 '\n'
293 'Cr-Commit-Position: refs/heads/master@{#12}',
294 dest_ref='refs/heads/master',
295 child_msg='Child\n'
296 '\n'
297 'Some users are smart and insert their own footers\n'
298 '\n'
299 'Cr-Whatever: value\n'
300 'Cr-Commit-Position: refs/copy/paste@{#22}')
301 self.assertEqualByLine(
302 actual,
303 'Child\n'
304 '\n'
305 'Some users are smart and insert their own footers\n'
306 '\n'
307 'Cr-Original-Whatever: value\n'
308 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
309 'Cr-Commit-Position: refs/heads/master@{#13}')
310
311 def test_git_number_new_branch(self):
312 actual = self._test_git_number(
313 'Parent\n'
314 '\n'
315 'Cr-Commit-Position: refs/heads/master@{#12}',
316 dest_ref='refs/heads/branch',
317 child_msg='Child')
318 self.assertEqualByLine(
319 actual,
320 'Child\n'
321 '\n'
322 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
323 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
324
325 def test_git_number_lineage(self):
326 actual = self._test_git_number(
327 'Parent\n'
328 '\n'
329 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
330 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
331 dest_ref='refs/heads/branch',
332 child_msg='Child')
333 self.assertEqualByLine(
334 actual,
335 'Child\n'
336 '\n'
337 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
338 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
339
340 def test_git_number_moooooooore_lineage(self):
341 actual = self._test_git_number(
342 'Parent\n'
343 '\n'
344 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
345 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
346 dest_ref='refs/heads/mooore',
347 child_msg='Child')
348 self.assertEqualByLine(
349 actual,
350 'Child\n'
351 '\n'
352 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
353 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
354 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
355
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100356 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700357 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100358 actual = self._test_git_number(
359 'CQ commit on fresh new branch + numbering.\n'
360 '\n'
361 'NOTRY=True\n'
362 'NOPRESUBMIT=True\n'
363 'BUG=\n'
364 '\n'
365 'Review-Url: https://codereview.chromium.org/2577703003\n'
366 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
367 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
368 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
369 dest_ref='refs/heads/gnumb-test/cl',
370 child_msg='git cl on fresh new branch + numbering.\n'
371 '\n'
372 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
373 self.assertEqualByLine(
374 actual,
375 'git cl on fresh new branch + numbering.\n'
376 '\n'
377 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
378 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
379 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
380 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
381 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100382
383 def test_git_number_cherry_pick(self):
384 actual = self._test_git_number(
385 'Parent\n'
386 '\n'
387 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
388 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
389 dest_ref='refs/heads/branch',
390 child_msg='Child, which is cherry-pick from master\n'
391 '\n'
392 'Cr-Commit-Position: refs/heads/master@{#100}\n'
393 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
394 self.assertEqualByLine(
395 actual,
396 'Child, which is cherry-pick from master\n'
397 '\n'
398 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
399 '\n'
400 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
401 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
402 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
403
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000404 def test_gerrit_mirror_hack(self):
405 cr = 'chromium-review.googlesource.com'
406 url0 = 'https://%s/a/changes/x?a=b' % cr
407 origMirrors = git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES
408 try:
409 git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = ['us1', 'us2']
410 url1 = git_cl.gerrit_util._UseGerritMirror(url0, cr)
411 url2 = git_cl.gerrit_util._UseGerritMirror(url1, cr)
412 url3 = git_cl.gerrit_util._UseGerritMirror(url2, cr)
413
414 self.assertNotEqual(url1, url2)
415 self.assertEqual(sorted((url1, url2)), [
416 'https://us1-mirror-chromium-review.googlesource.com/a/changes/x?a=b',
417 'https://us2-mirror-chromium-review.googlesource.com/a/changes/x?a=b'])
418 self.assertEqual(url1, url3)
419 finally:
420 git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = origMirrors
421
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000422 def test_valid_accounts(self):
423 mock_per_account = {
424 'u1': None, # 404, doesn't exist.
425 'u2': {
426 '_account_id': 123124,
427 'avatars': [],
428 'email': 'u2@example.com',
429 'name': 'User Number 2',
430 'status': 'OOO',
431 },
432 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
433 }
434 def GetAccountDetailsMock(_, account):
435 # Poor-man's mock library's side_effect.
436 v = mock_per_account.pop(account)
437 if isinstance(v, Exception):
438 raise v
439 return v
440
441 original = git_cl.gerrit_util.GetAccountDetails
442 try:
443 git_cl.gerrit_util.GetAccountDetails = GetAccountDetailsMock
444 actual = git_cl.gerrit_util.ValidAccounts(
445 'host', ['u1', 'u2', 'u3'], max_threads=1)
446 finally:
447 git_cl.gerrit_util.GetAccountDetails = original
448 self.assertEqual(actual, {
449 'u2': {
450 '_account_id': 123124,
451 'avatars': [],
452 'email': 'u2@example.com',
453 'name': 'User Number 2',
454 'status': 'OOO',
455 },
456 })
457
458
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000459
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200460class TestParseIssueURL(unittest.TestCase):
461 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
462 codereview=None, fail=False):
463 self.assertIsNotNone(parsed)
464 if fail:
465 self.assertFalse(parsed.valid)
466 return
467 self.assertTrue(parsed.valid)
468 self.assertEqual(parsed.issue, issue)
469 self.assertEqual(parsed.patchset, patchset)
470 self.assertEqual(parsed.hostname, hostname)
471 self.assertEqual(parsed.codereview, codereview)
472
473 def _run_and_validate(self, func, url, *args, **kwargs):
474 result = func(urlparse.urlparse(url))
475 if kwargs.pop('fail', False):
476 self.assertIsNone(result)
477 return None
478 self._validate(result, *args, fail=False, **kwargs)
479
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200480 def test_gerrit(self):
481 def test(url, issue=None, patchset=None, hostname=None, fail=None):
482 self._test_ParseIssueUrl(
483 git_cl._GerritChangelistImpl.ParseIssueURL,
484 url, issue, patchset, hostname, fail)
485 def test(url, *args, **kwargs):
486 self._run_and_validate(git_cl._GerritChangelistImpl.ParseIssueURL, url,
487 *args, codereview='gerrit', **kwargs)
488
489 test('http://chrome-review.source.com/c/123',
490 123, None, 'chrome-review.source.com')
491 test('https://chrome-review.source.com/c/123/',
492 123, None, 'chrome-review.source.com')
493 test('https://chrome-review.source.com/c/123/4',
494 123, 4, 'chrome-review.source.com')
495 test('https://chrome-review.source.com/#/c/123/4',
496 123, 4, 'chrome-review.source.com')
497 test('https://chrome-review.source.com/c/123/4',
498 123, 4, 'chrome-review.source.com')
499 test('https://chrome-review.source.com/123',
500 123, None, 'chrome-review.source.com')
501 test('https://chrome-review.source.com/123/4',
502 123, 4, 'chrome-review.source.com')
503
504 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
505 test('https://chrome-review.source.com/c/abc/', fail=True)
506 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
507
508 def test_ParseIssueNumberArgument(self):
509 def test(arg, *args, **kwargs):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +0200510 codereview_hint = kwargs.pop('hint', None)
511 self._validate(git_cl.ParseIssueNumberArgument(arg, codereview_hint),
512 *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200513
514 test('123', 123)
515 test('', fail=True)
516 test('abc', fail=True)
517 test('123/1', fail=True)
518 test('123a', fail=True)
519 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +0000520
521 # Looks like Rietveld and Gerrit, but we should select Gerrit now
522 # w/ or w/o hint.
Andrii Shyshkalovc9712392017-04-11 13:35:21 +0200523 test('https://codereview.source.com/123',
524 123, None, 'codereview.source.com', 'gerrit',
525 hint='gerrit')
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +0000526 test('https://codereview.source.com/123',
527 123, None, 'codereview.source.com', 'gerrit')
528
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200529 # Gerrrit.
530 test('https://chrome-review.source.com/c/123/4',
531 123, 4, 'chrome-review.source.com', 'gerrit')
532 test('https://chrome-review.source.com/bad/123/4', fail=True)
533
534
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100535class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100536 def setUp(self):
537 super(GitCookiesCheckerTest, self).setUp()
538 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100539 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100540
541 def mock_hosts_creds(self, subhost_identity_pairs):
542 def ensure_googlesource(h):
543 if not h.endswith(self.c._GOOGLESOURCE):
544 assert not h.endswith('.')
545 return h + '.' + self.c._GOOGLESOURCE
546 return h
547 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
548 for h, i in subhost_identity_pairs]
549
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200550 def test_identity_parsing(self):
551 self.assertEqual(self.c._parse_identity('ldap.google.com'),
552 ('ldap', 'google.com'))
553 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
554 ('ldap', 'example.com'))
555 # Specical case because we know there are no subdomains in chromium.org.
556 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
557 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800558 # Pathological: ".period." can be either username OR domain, more likely
559 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200560 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
561 ('note', 'period.example.com'))
562
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100563 def test_analysis_nothing(self):
564 self.c._all_hosts = []
565 self.assertFalse(self.c.has_generic_host())
566 self.assertEqual(set(), self.c.get_conflicting_hosts())
567 self.assertEqual(set(), self.c.get_duplicated_hosts())
568 self.assertEqual(set(), self.c.get_partially_configured_hosts())
569 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
570
571 def test_analysis(self):
572 self.mock_hosts_creds([
573 ('.googlesource.com', 'git-example.chromium.org'),
574
575 ('chromium', 'git-example.google.com'),
576 ('chromium-review', 'git-example.google.com'),
577 ('chrome-internal', 'git-example.chromium.org'),
578 ('chrome-internal-review', 'git-example.chromium.org'),
579 ('conflict', 'git-example.google.com'),
580 ('conflict-review', 'git-example.chromium.org'),
581 ('dup', 'git-example.google.com'),
582 ('dup', 'git-example.google.com'),
583 ('dup-review', 'git-example.google.com'),
584 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200585 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100586 ])
587 self.assertTrue(self.c.has_generic_host())
588 self.assertEqual(set(['conflict.googlesource.com']),
589 self.c.get_conflicting_hosts())
590 self.assertEqual(set(['dup.googlesource.com']),
591 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200592 self.assertEqual(set(['partial.googlesource.com',
593 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100594 self.c.get_partially_configured_hosts())
595 self.assertEqual(set(['chromium.googlesource.com',
596 'chrome-internal.googlesource.com']),
597 self.c.get_hosts_with_wrong_identities())
598
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100599 def test_report_no_problems(self):
600 self.test_analysis_nothing()
601 self.mock(sys, 'stdout', StringIO.StringIO())
602 self.assertFalse(self.c.find_and_report_problems())
603 self.assertEqual(sys.stdout.getvalue(), '')
604
605 def test_report(self):
606 self.test_analysis()
607 self.mock(sys, 'stdout', StringIO.StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200608 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
609 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100610 self.assertTrue(self.c.find_and_report_problems())
611 with open(os.path.join(os.path.dirname(__file__),
612 'git_cl_creds_check_report.txt')) as f:
613 expected = f.read()
614 def by_line(text):
615 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700616 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200617 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100618
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800619
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000620class TestGitCl(TestCase):
621 def setUp(self):
622 super(TestGitCl, self).setUp()
623 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700624 self._calls_done = []
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000625 self.mock(subprocess2, 'call', self._mocked_call)
626 self.mock(subprocess2, 'check_call', self._mocked_call)
627 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700628 self.mock(subprocess2, 'communicate',
629 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000630 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000631 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000632 self.mock(git_common, 'get_or_create_merge_base',
633 lambda *a: (
634 self._mocked_call(['get_or_create_merge_base']+list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000635 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000636 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000637 self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
638 self._mocked_call('SaveDescriptionBackup'))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100639 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000640 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700641 self.mock(git_cl, 'write_json', lambda path, contents:
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000642 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000643 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
skobes6468b902016-10-24 08:45:10 -0700644 self.mock(git_cl.checkout, 'GitCheckout', GitCheckoutMock)
645 GitCheckoutMock.reset()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000646 self.mock(git_cl.upload, 'RealMain', self.fail)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000647 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000648 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100649 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
650 lambda *args, **kwargs: self._mocked_call(
651 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700652 self.mock(git_cl.gerrit_util, 'GetChangeComments',
653 lambda *args, **kwargs: self._mocked_call(
654 'GetChangeComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100655 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700656 lambda h, i, reviewers, ccs, notify: self._mocked_call(
657 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700658 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700659 lambda h, i, msg=None, labels=None, notify=None:
660 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700661 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
662 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000663 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
664 classmethod(lambda _: False))
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000665 self.mock(git_cl.gerrit_util, 'ValidAccounts',
666 lambda host, accounts:
667 self._mocked_call('ValidAccounts', host, accounts))
tandriic2405f52016-10-10 08:13:15 -0700668 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100669 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000670 # It's important to reset settings to not have inter-tests interference.
671 git_cl.settings = None
672
673 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000674 try:
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100675 self.assertEquals([], self.calls)
676 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000677 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100678 raise
679 # Sadly, has_failed() returns True if this OR any other tests before this
680 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200681 git_cl.logging.error(
682 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100683 'There are un-consumed self.calls after this test has finished.\n'
684 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700685 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200686 'If you are already running only this test, then **first** fix the '
687 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100688 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700689 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100690 'and follow instructions above.\n' +
691 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000692 finally:
693 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000694
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000695 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000696 self.assertTrue(
697 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700698 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000699 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000700 expected_args, result = top
701
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000702 # Also logs otherwise it could get caught in a try/finally and be hard to
703 # diagnose.
704 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700705 N = 5
706 prior_calls = '\n '.join(
707 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
708 for i, c in enumerate(self._calls_done[-N:]))
709 following_calls = '\n '.join(
710 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
711 for i, c in enumerate(self.calls[:N]))
712 extended_msg = (
713 'A few prior calls:\n %s\n\n'
714 'This (expected):\n @%d: %r\n'
715 'This (actual):\n @%d: %r\n\n'
716 'A few following expected calls:\n %s' %
717 (prior_calls, len(self._calls_done), expected_args,
718 len(self._calls_done), args, following_calls))
719 git_cl.logging.error(extended_msg)
720
tandrii99a72f22016-08-17 14:33:24 -0700721 self.fail('@%d\n'
722 ' Expected: %r\n'
723 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700724 len(self._calls_done), expected_args, args))
725
726 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700727 if isinstance(result, Exception):
728 raise result
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000729 return result
730
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100731 def test_ask_for_explicit_yes_true(self):
732 self.calls = [
733 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
734 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
735 ]
736 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
737
tandrii48df5812016-10-17 03:55:37 -0700738 def test_LoadCodereviewSettingsFromFile_gerrit(self):
739 codereview_file = StringIO.StringIO('GERRIT_HOST: true')
740 self.calls = [
741 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
742 ((['git', 'config', '--unset-all', 'rietveld.private'],), CERR1),
743 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
744 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
745 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
746 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700747 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
748 CERR1),
749 ((['git', 'config', '--unset-all', 'rietveld.project'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700750 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
751 CERR1),
752 ((['git', 'config', 'gerrit.host', 'true'],), ''),
753 ]
754 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
755
maruel@chromium.orga3353652011-11-30 14:26:57 +0000756 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000757 def _is_gerrit_calls(cls, gerrit=False):
758 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
759 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
760
761 @classmethod
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000762 def _git_post_upload_calls(cls):
763 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000764 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
765 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
766 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000767 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000768 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000769 ]
770
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000771 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000772 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000773 fake_ancestor = 'fake_ancestor'
774 fake_cl = 'fake_cl_for_patch'
775 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000776 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000777 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000778 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000779 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000780 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000781 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000782 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000783 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700784 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000785 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000786 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000787 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000788 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000789 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000790 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000791 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000792 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000793 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000794 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000795 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000796
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000797 @classmethod
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000798 def _gerrit_ensure_auth_calls(
799 cls, issue=None, skip_auth_check=False, short_hostname='chromium'):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000800 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000801 if skip_auth_check:
802 return [((cmd, ), 'true')]
803
tandrii5d48c322016-08-18 16:19:37 -0700804 calls = [((cmd, ), CERR1)]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000805 if issue:
806 calls.extend([
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100807 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000808 ])
809 calls.extend([
810 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
811 ((['git', 'config', 'branch.master.remote'],), 'origin'),
812 ((['git', 'config', 'remote.origin.url'],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000813 'https://%s.googlesource.com/my/repo' % short_hostname),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000814 ])
815 return calls
816
817 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100818 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200819 fetched_status=None, other_cl_owner=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000820 custom_cl_base=None, short_hostname='chromium'):
Aaron Gable13101a62018-02-09 13:20:41 -0800821 calls = cls._is_gerrit_calls(True)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100822 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200823 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
824 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
825 ((['git', 'config', 'branch.master.gerritissue'],),
826 CERR1 if issue is None else str(issue)),
827 ]
828
829 if custom_cl_base:
830 ancestor_revision = custom_cl_base
831 else:
832 # Determine ancestor_revision to be merge base.
833 ancestor_revision = 'fake_ancestor_sha'
834 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000835 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000836 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000837 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200838 'refs/remotes/origin/master'],), ancestor_revision),
839 ]
840
841 # Calls to verify branch point is ancestor
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000842 calls += cls._gerrit_ensure_auth_calls(
843 issue=issue, short_hostname=short_hostname)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100844
845 if issue:
846 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000847 (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +0000848 'my%2Frepo~123456',
Andrii Shyshkalovc4a73562018-09-25 18:40:17 +0000849 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
850 ),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100851 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100852 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100853 'change_id': '123456789',
854 'current_revision': 'sha1_of_current_revision',
855 'revisions': { 'sha1_of_current_revision': {
856 'commit': {'message': fetched_description},
857 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100858 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100859 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100860 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100861 if fetched_status == 'ABANDONED':
862 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000863 (('DieWithError', 'Change https://%s-review.googlesource.com/'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100864 '123456 has been abandoned, new uploads are not '
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000865 'allowed' % short_hostname), SystemExitMock()),
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100866 ]
867 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100868 if other_cl_owner:
869 calls += [
870 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
871 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100872
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200873 calls += cls._git_sanity_checks(ancestor_revision, 'master',
874 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100875 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200876 ((['git', 'rev-parse', '--show-cdup'],), ''),
877 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000878
Aaron Gable7817f022017-12-12 09:43:17 -0800879 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
880 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200881 'M\t.gitignore\n'),
882 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100883 ]
884
885 if not issue:
886 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200887 ((['git', 'log', '--pretty=format:%s%n%n%b',
888 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000889 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100890 ]
891
892 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200893 ((['git', 'config', 'user.email'],), 'me@example.com'),
894 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
895 ([custom_cl_base] if custom_cl_base else
896 [ancestor_revision, 'HEAD']),),
897 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100898 ]
899 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000900
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000901 @classmethod
902 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700903 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000904 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700905 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100906 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000907 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000908 short_hostname='chromium',
909 labels=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000910 if post_amend_description is None:
911 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700912 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200913 # Determined in `_gerrit_base_calls`.
914 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
915
916 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000917
tandriia60502f2016-06-20 02:01:53 -0700918 if squash_mode == 'default':
919 calls.extend([
920 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
921 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
922 ])
923 elif squash_mode in ('override_squash', 'override_nosquash'):
924 calls.extend([
925 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
926 'true' if squash_mode == 'override_squash' else 'false'),
927 ])
928 else:
929 assert squash_mode in ('squash', 'nosquash')
930
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000931 # If issue is given, then description is fetched from Gerrit instead.
932 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000933 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200934 ((['git', 'log', '--pretty=format:%s\n\n%b',
935 ((custom_cl_base + '..') if custom_cl_base else
936 'fake_ancestor_sha..HEAD')],),
937 description),
938 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800939 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000940 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800941 else:
942 if not title:
943 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200944 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
945 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800946 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000947 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000948 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000949 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200950 (('DownloadGerritHook', False), ''),
951 # Amending of commit message to get the Change-Id.
952 ((['git', 'log', '--pretty=format:%s\n\n%b',
953 determined_ancestor_revision + '..HEAD'],),
954 description),
955 ((['git', 'commit', '--amend', '-m', description],), ''),
956 ((['git', 'log', '--pretty=format:%s\n\n%b',
957 determined_ancestor_revision + '..HEAD'],),
958 post_amend_description)
959 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000960 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000961 if not issue:
962 # Prompting to edit description on first upload.
963 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200964 ((['git', 'config', 'core.editor'],), ''),
965 ((['RunEditor'],), description),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000966 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000967 ref_to_push = 'abcdef0123456789'
968 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200969 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
970 ((['git', 'config', 'branch.master.remote'],), 'origin'),
971 ]
972
973 if custom_cl_base is None:
974 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000975 ((['get_or_create_merge_base', 'master',
976 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000977 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200978 ]
979 parent = 'origin/master'
980 else:
981 calls += [
982 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
983 'refs/remotes/origin/master'],),
984 callError(1)), # Means not ancenstor.
985 (('ask_for_data',
986 'Do you take responsibility for cleaning up potential mess '
987 'resulting from proceeding with upload? Press Enter to upload, '
988 'or Ctrl+C to abort'), ''),
989 ]
990 parent = custom_cl_base
991
992 calls += [
993 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
994 '0123456789abcdef'),
995 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -0700996 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200997 ref_to_push),
998 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000999 else:
1000 ref_to_push = 'HEAD'
1001
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001002 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00001003 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001004 ((['git', 'rev-list',
1005 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1006 ref_to_push],),
1007 '1hashPerLine\n'),
1008 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001009
Aaron Gableafd52772017-06-27 16:40:10 -07001010 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001011 ref_suffix = '%ready,notify=ALL'
1012 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001013 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001014 ref_suffix = '%wip'
1015 else:
1016 ref_suffix = '%notify=NONE'
Aaron Gable9b713dd2016-12-14 16:04:21 -08001017
Aaron Gable70f4e242017-06-26 10:45:59 -07001018 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001019 ref_suffix += ',m=' + title
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001020
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001021 calls += [
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001022 ((['git', 'config', 'rietveld.cc'],), ''),
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001023 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001024 if short_hostname == 'chromium':
1025 # All reviwers and ccs get into ref_suffix.
1026 for r in sorted(reviewers):
1027 ref_suffix += ',r=%s' % r
1028 for c in sorted(['chromium-reviews+test-more-cc@chromium.org',
1029 'joe@example.com'] + cc):
1030 ref_suffix += ',cc=%s' % c
1031 reviewers, cc = [], []
1032 else:
1033 # TODO(crbug/877717): remove this case.
1034 calls += [
1035 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
1036 sorted(reviewers) + ['joe@example.com',
1037 'chromium-reviews+test-more-cc@chromium.org'] + cc),
1038 {
1039 e: {'email': e}
1040 for e in (reviewers + ['joe@example.com'] + cc)
1041 })
1042 ]
1043 for r in sorted(reviewers):
1044 if r != 'bad-account-or-email':
1045 ref_suffix += ',r=%s' % r
1046 reviewers.remove(r)
1047 for c in sorted(['joe@example.com'] + cc):
1048 ref_suffix += ',cc=%s' % c
1049 if c in cc:
1050 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001051
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001052 if not tbr:
1053 for k, v in sorted((labels or {}).items()):
1054 ref_suffix += ',l=%s+%d' % (k, v)
1055
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001056 calls.append((
1057 (['git', 'push',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001058 'https://%s.googlesource.com/my/repo' % short_hostname,
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001059 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001060 (('remote:\n'
1061 'remote: Processing changes: (\)\n'
1062 'remote: Processing changes: (|)\n'
1063 'remote: Processing changes: (/)\n'
1064 'remote: Processing changes: (-)\n'
1065 'remote: Processing changes: new: 1 (/)\n'
1066 'remote: Processing changes: new: 1, done\n'
1067 'remote:\n'
1068 'remote: New Changes:\n'
1069 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1070 ' XXX\n'
1071 'remote:\n'
1072 'To https://%s.googlesource.com/my/repo\n'
1073 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1074 ) % (short_hostname, short_hostname))
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001075 ))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001076 if squash:
1077 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001078 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001079 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001080 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001081 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001082 ((['git', 'config', 'branch.master.gerritsquashhash',
1083 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001084 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001085 # TODO(crbug/877717): this should never be used.
1086 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001087 calls += [
1088 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001089 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001090 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001091 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1092 notify),
1093 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001094 ]
Aaron Gablefd238082017-06-07 13:42:34 -07001095 if tbr:
1096 calls += [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001097 (('GetChangeDetail', 'chromium-review.googlesource.com',
1098 'my%2Frepo~123456', ['LABELS']), {
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001099 'labels': {
1100 'Code-Review': {
1101 'default_value': 0,
1102 'all': [],
1103 'values': {
1104 '+2': 'lgtm, approved',
1105 '+1': 'lgtm, but someone else must approve',
1106 ' 0': 'No score',
1107 '-1': 'Don\'t submit as-is',
1108 }
1109 }
1110 }
1111 }),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001112 (('SetReview',
1113 'chromium-review.googlesource.com',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001114 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001115 'Self-approving for TBR',
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001116 {'Code-Review': 2}, None), ''),
Aaron Gablefd238082017-06-07 13:42:34 -07001117 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001118 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001119 return calls
1120
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001121 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001122 self,
1123 upload_args,
1124 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001125 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001126 squash=True,
1127 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001128 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001129 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001130 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001131 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001132 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001133 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001134 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001135 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001136 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001137 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001138 short_hostname='chromium',
1139 labels=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001140 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001141 if squash_mode is None:
1142 if '--no-squash' in upload_args:
1143 squash_mode = 'nosquash'
1144 elif '--squash' in upload_args:
1145 squash_mode = 'squash'
1146 else:
1147 squash_mode = 'default'
1148
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001149 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001150 cc = cc or []
tandrii@chromium.org28253532016-04-14 13:46:56 +00001151 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001152 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001153 CookiesAuthenticatorMockFactory(
1154 same_auth=('git-owner.example.com', '', 'pass')))
tandrii16e0b4e2016-06-07 10:34:28 -07001155 self.mock(git_cl._GerritChangelistImpl, '_GerritCommitMsgHookCheck',
1156 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001157 self.mock(git_cl.gclient_utils, 'RunEditor',
1158 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001159 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1160 'DownloadGerritHook', force))
tandriia60502f2016-06-20 02:01:53 -07001161
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001162 self.calls = self._gerrit_base_calls(
1163 issue=issue,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001164 fetched_description=description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001165 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001166 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001167 custom_cl_base=custom_cl_base,
1168 short_hostname=short_hostname)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001169 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001170 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
1171 expected_content=description))
1172 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001173 self.calls += self._gerrit_upload_calls(
1174 description, reviewers, squash,
1175 squash_mode=squash_mode,
1176 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001177 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001178 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001179 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001180 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001181 short_hostname=short_hostname,
1182 labels=labels)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001183 # Uncomment when debugging.
1184 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001185 git_cl.main(['upload'] + upload_args)
1186
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001187 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001188 self._run_gerrit_upload_test(
1189 ['--no-squash'],
1190 'desc\n\nBUG=\n',
1191 [],
1192 squash=False,
1193 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
1194
1195 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001196 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001197 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +00001198 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001199 [],
tandriia60502f2016-06-20 02:01:53 -07001200 squash=False,
1201 squash_mode='override_nosquash',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001202 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001203
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001204 def test_gerrit_no_reviewer(self):
1205 self._run_gerrit_upload_test(
1206 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001207 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001208 [],
1209 squash=False,
1210 squash_mode='override_nosquash')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001211
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001212 def test_gerrit_no_reviewer_non_chromium_host(self):
1213 # TODO(crbug/877717): remove this test case.
1214 self._run_gerrit_upload_test(
1215 [],
1216 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
1217 [],
1218 squash=False,
1219 squash_mode='override_nosquash',
1220 short_hostname='other')
1221
Nick Carter8692b182017-11-06 16:30:38 -08001222 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001223 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1224 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001225 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001226 'desc\n\nBUG=\n\nChange-Id: I123456789',
1227 squash=False,
1228 squash_mode='override_nosquash',
Nick Carter8692b182017-11-06 16:30:38 -08001229 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001230
ukai@chromium.orge8077812012-02-03 03:41:46 +00001231 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001232 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001233 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001234 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001235 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001236 squash=False,
1237 squash_mode='override_nosquash',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001238 notify=True)
ukai@chromium.orge8077812012-02-03 03:41:46 +00001239
1240 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001241 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001242 [],
bradnelsond975b302016-10-23 12:20:23 -07001243 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1244 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001245 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001246 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001247 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001248 cc=['more@example.com', 'people@example.com'],
1249 tbr='reviewer@example.com')
tandriia60502f2016-06-20 02:01:53 -07001250
1251 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001252 self._run_gerrit_upload_test(
1253 [],
1254 'desc\nBUG=\n\nChange-Id: 123456789',
1255 [],
1256 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001257
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001258 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001259 self._run_gerrit_upload_test(
1260 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001261 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001262 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001263 squash=True,
1264 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001265
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001266 def test_gerrit_upload_squash_first_with_labels(self):
1267 self._run_gerrit_upload_test(
1268 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
1269 'desc\nBUG=\n\nChange-Id: 123456789',
1270 [],
1271 squash=True,
1272 expected_upstream_ref='origin/master',
1273 labels={'Commit-Queue': 1, 'Auto-Submit': 1})
1274
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001275 def test_gerrit_upload_squash_first_against_rev(self):
1276 custom_cl_base = 'custom_cl_base_rev_or_branch'
1277 self._run_gerrit_upload_test(
1278 ['--squash', custom_cl_base],
1279 'desc\nBUG=\n\nChange-Id: 123456789',
1280 [],
1281 squash=True,
1282 expected_upstream_ref='origin/master',
1283 custom_cl_base=custom_cl_base)
1284 self.assertIn(
1285 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1286 sys.stdout.getvalue())
1287
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001288 def test_gerrit_upload_squash_reupload(self):
1289 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001290 self._run_gerrit_upload_test(
1291 ['--squash'],
1292 description,
1293 [],
1294 squash=True,
1295 expected_upstream_ref='origin/master',
1296 issue=123456)
1297
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001298 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1299 self.mock(git_cl, 'DieWithError',
1300 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1301 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1302 with self.assertRaises(SystemExitMock):
1303 self._run_gerrit_upload_test(
1304 ['--squash'],
1305 description,
1306 [],
1307 squash=True,
1308 expected_upstream_ref='origin/master',
1309 issue=123456,
1310 fetched_status='ABANDONED')
1311
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001312 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1313 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1314 lambda *_, **__: {'email': 'yet-another@example.com'})
1315 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1316 self._run_gerrit_upload_test(
1317 ['--squash'],
1318 description,
1319 [],
1320 squash=True,
1321 expected_upstream_ref='origin/master',
1322 issue=123456,
1323 other_cl_owner='other@example.com')
1324 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001325 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001326 'authenticate to Gerrit as yet-another@example.com.\n'
1327 'Uploading may fail due to lack of permissions',
1328 git_cl.sys.stdout.getvalue())
1329
rmistry@google.com2dd99862015-06-22 12:22:18 +00001330 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001331 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001332 def mock_run_git(*args, **_kwargs):
1333 if args[0] == ['for-each-ref',
1334 '--format=%(refname:short) %(upstream:short)',
1335 'refs/heads']:
1336 # Create a local branch dependency tree that looks like this:
1337 # test1 -> test2 -> test3 -> test4 -> test5
1338 # -> test3.1
1339 # test6 -> test0
1340 branch_deps = [
1341 'test2 test1', # test1 -> test2
1342 'test3 test2', # test2 -> test3
1343 'test3.1 test2', # test2 -> test3.1
1344 'test4 test3', # test3 -> test4
1345 'test5 test4', # test4 -> test5
1346 'test6 test0', # test0 -> test6
1347 'test7', # test7
1348 ]
1349 return '\n'.join(branch_deps)
1350 self.mock(git_cl, 'RunGit', mock_run_git)
1351
1352 class RecordCalls:
1353 times_called = 0
1354 record_calls = RecordCalls()
1355 def mock_CMDupload(*args, **_kwargs):
1356 record_calls.times_called += 1
1357 return 0
1358 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1359
1360 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001361 (('ask_for_data', 'This command will checkout all dependent branches '
1362 'and run "git cl upload". Press Enter to continue, '
1363 'or Ctrl+C to abort'), ''),
1364 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001365
1366 class MockChangelist():
1367 def __init__(self):
1368 pass
1369 def GetBranch(self):
1370 return 'test1'
1371 def GetIssue(self):
1372 return '123'
1373 def GetPatchset(self):
1374 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001375 def IsGerrit(self):
1376 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001377
1378 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1379 # CMDupload should have been called 5 times because of 5 dependent branches.
1380 self.assertEquals(5, record_calls.times_called)
1381 self.assertEquals(0, ret)
1382
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001383 def test_gerrit_change_id(self):
1384 self.calls = [
1385 ((['git', 'write-tree'], ),
1386 'hashtree'),
1387 ((['git', 'rev-parse', 'HEAD~0'], ),
1388 'branch-parent'),
1389 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1390 'A B <a@b.org> 1456848326 +0100'),
1391 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1392 'C D <c@d.org> 1456858326 +0100'),
1393 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1394 'hashchange'),
1395 ]
1396 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1397 self.assertEqual(change_id, 'Ihashchange')
1398
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001399 def test_desecription_append_footer(self):
1400 for init_desc, footer_line, expected_desc in [
1401 # Use unique desc first lines for easy test failure identification.
1402 ('foo', 'R=one', 'foo\n\nR=one'),
1403 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1404 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1405 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1406 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1407 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1408 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1409 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1410 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1411 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1412 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1413 ]:
1414 desc = git_cl.ChangeDescription(init_desc)
1415 desc.append_footer(footer_line)
1416 self.assertEqual(desc.description, expected_desc)
1417
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001418 def test_update_reviewers(self):
1419 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001420 ('foo', [], [],
1421 'foo'),
1422 ('foo\nR=xx', [], [],
1423 'foo\nR=xx'),
1424 ('foo\nTBR=xx', [], [],
1425 'foo\nTBR=xx'),
1426 ('foo', ['a@c'], [],
1427 'foo\n\nR=a@c'),
1428 ('foo\nR=xx', ['a@c'], [],
1429 'foo\n\nR=a@c, xx'),
1430 ('foo\nTBR=xx', ['a@c'], [],
1431 'foo\n\nR=a@c\nTBR=xx'),
1432 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1433 'foo\n\nR=a@c, yy\nTBR=xx'),
1434 ('foo\nBUG=', ['a@c'], [],
1435 'foo\nBUG=\nR=a@c'),
1436 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1437 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1438 ('foo', ['a@c', 'b@c'], [],
1439 'foo\n\nR=a@c, b@c'),
1440 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1441 'foo\nBar\n\nR=c@c\nBUG='),
1442 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1443 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001444 # Same as the line before, but full of whitespaces.
1445 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001446 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001447 'foo\nBar\n\nR=c@c\n BUG =',
1448 ),
1449 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001450 ('foo BUG=allo R=joe ', ['c@c'], [],
1451 'foo BUG=allo R=joe\n\nR=c@c'),
1452 # Redundant TBRs get promoted to Rs
1453 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1454 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001455 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001456 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001457 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001458 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001459 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001460 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001461 actual.append(obj.description)
1462 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001463
Nodir Turakulov23b82142017-11-16 11:04:25 -08001464 def test_get_hash_tags(self):
1465 cases = [
1466 ('', []),
1467 ('a', []),
1468 ('[a]', ['a']),
1469 ('[aa]', ['aa']),
1470 ('[a ]', ['a']),
1471 ('[a- ]', ['a']),
1472 ('[a- b]', ['a-b']),
1473 ('[a--b]', ['a-b']),
1474 ('[a', []),
1475 ('[a]x', ['a']),
1476 ('[aa]x', ['aa']),
1477 ('[a b]', ['a-b']),
1478 ('[a b]', ['a-b']),
1479 ('[a__b]', ['a-b']),
1480 ('[a] x', ['a']),
1481 ('[a][b]', ['a', 'b']),
1482 ('[a] [b]', ['a', 'b']),
1483 ('[a][b]x', ['a', 'b']),
1484 ('[a][b] x', ['a', 'b']),
1485 ('[a]\n[b]', ['a']),
1486 ('[a\nb]', []),
1487 ('[a][', ['a']),
1488 ('Revert "[a] feature"', ['a']),
1489 ('Reland "[a] feature"', ['a']),
1490 ('Revert: [a] feature', ['a']),
1491 ('Reland: [a] feature', ['a']),
1492 ('Revert "Reland: [a] feature"', ['a']),
1493 ('Foo: feature', ['foo']),
1494 ('Foo Bar: feature', ['foo-bar']),
1495 ('Revert "Foo bar: feature"', ['foo-bar']),
1496 ('Reland "Foo bar: feature"', ['foo-bar']),
1497 ]
1498 for desc, expected in cases:
1499 change_desc = git_cl.ChangeDescription(desc)
1500 actual = change_desc.get_hash_tags()
1501 self.assertEqual(
1502 actual,
1503 expected,
1504 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1505
wittman@chromium.org455dc922015-01-26 20:15:50 +00001506 def test_get_target_ref(self):
1507 # Check remote or remote branch not present.
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001508 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001509 self.assertEqual(None, git_cl.GetTargetRef(None,
1510 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001511 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001512
wittman@chromium.org455dc922015-01-26 20:15:50 +00001513 # Check default target refs for branches.
1514 self.assertEqual('refs/heads/master',
1515 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001516 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001517 self.assertEqual('refs/heads/master',
1518 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001519 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001520 self.assertEqual('refs/heads/master',
1521 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001522 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001523 self.assertEqual('refs/branch-heads/123',
1524 git_cl.GetTargetRef('origin',
1525 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001526 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001527 self.assertEqual('refs/diff/test',
1528 git_cl.GetTargetRef('origin',
1529 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001530 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001531 self.assertEqual('refs/heads/chrome/m42',
1532 git_cl.GetTargetRef('origin',
1533 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001534 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001535
1536 # Check target refs for user-specified target branch.
1537 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1538 'refs/remotes/branch-heads/123'):
1539 self.assertEqual('refs/branch-heads/123',
1540 git_cl.GetTargetRef('origin',
1541 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001542 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001543 for branch in ('origin/master', 'remotes/origin/master',
1544 'refs/remotes/origin/master'):
1545 self.assertEqual('refs/heads/master',
1546 git_cl.GetTargetRef('origin',
1547 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001548 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001549 for branch in ('master', 'heads/master', 'refs/heads/master'):
1550 self.assertEqual('refs/heads/master',
1551 git_cl.GetTargetRef('origin',
1552 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001553 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001554
wychen@chromium.orga872e752015-04-28 23:42:18 +00001555 def test_patch_when_dirty(self):
1556 # Patch when local tree is dirty
1557 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1558 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1559
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001560 @staticmethod
1561 def _get_gerrit_codereview_server_calls(branch, value=None,
1562 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001563 detect_branch=True,
1564 detect_server=True):
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001565 """Returns calls executed by _GerritChangelistImpl.GetCodereviewServer.
1566
1567 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1568 """
1569 calls = []
1570 if detect_branch:
1571 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001572 if detect_server:
1573 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1574 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001575 if value is None:
1576 calls += [
1577 ((['git', 'config', 'branch.' + branch + '.merge'],),
1578 'refs/heads' + branch),
1579 ((['git', 'config', 'branch.' + branch + '.remote'],),
1580 'origin'),
1581 ((['git', 'config', 'remote.origin.url'],),
1582 'https://%s.googlesource.com/my/repo' % git_short_host),
1583 ]
1584 return calls
1585
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001586 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001587 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001588 detect_gerrit_server=False,
1589 actual_codereview=None,
1590 codereview_in_url=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001591 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001592 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1593 lambda x: '60001')
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001594 self.mock(git_cl._RietveldChangelistImpl, 'FetchDescription',
Kenneth Russell61e2ed42017-02-15 11:47:13 -08001595 lambda *a, **kw: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001596 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1597
tandriidf09a462016-08-18 16:23:55 -07001598 if new_branch:
1599 self.calls = [((['git', 'new-branch', 'master'],), ''),]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001600
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001601 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001602 self.calls += [
1603 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001604 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001605 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001606
1607 if not force_codereview and not codereview_in_url:
1608 # These calls detect codereview to use.
1609 self.calls += [
1610 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1611 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
1612 ((['git', 'config', 'branch.master.gerritissue'],), CERR1),
1613 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
1614 ((['git', 'config', 'gerrit.host'],), 'true'),
1615 ]
1616 if detect_gerrit_server:
1617 self.calls += self._get_gerrit_codereview_server_calls(
1618 'master', git_short_host=git_short_host,
1619 detect_branch=not new_branch and force_codereview)
1620 actual_codereview = 'gerrit'
1621
1622 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001623 self.calls += [
1624 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001625 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001626 {
1627 'current_revision': '7777777777',
1628 'revisions': {
1629 '1111111111': {
1630 '_number': 1,
1631 'fetch': {'http': {
1632 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1633 'ref': 'refs/changes/56/123456/1',
1634 }},
1635 },
1636 '7777777777': {
1637 '_number': 7,
1638 'fetch': {'http': {
1639 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1640 'ref': 'refs/changes/56/123456/7',
1641 }},
1642 },
1643 },
1644 }),
1645 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001646
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001647 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001648 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001649 self.calls += [
1650 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1651 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001652 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001653 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001654 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001655 ((['git', 'config', 'branch.master.gerritserver',
1656 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001657 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001658 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1659 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1660 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001661 ]
1662 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1663
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001664 def test_patch_gerrit_new_branch(self):
1665 self._patch_common(
1666 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1667 self.calls += [
1668 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1669 'refs/changes/56/123456/7'],), ''),
1670 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1671 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1672 ''),
1673 ((['git', 'config', 'branch.master.gerritserver',
1674 'https://chromium-review.googlesource.com'],), ''),
1675 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1676 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1677 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1678 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1679 ]
1680 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1681
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001682 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001683 self._patch_common(
1684 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001685 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001686 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001687 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001688 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001689 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001690 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001691 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001692 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001693 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001694 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1695 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1696 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001697 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001698 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001699
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001700 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001701 self.calls += self._get_gerrit_codereview_server_calls(
1702 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001703 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001704 actual_codereview='gerrit', git_short_host='else',
1705 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001706 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001707 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001708 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001709 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001710 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001711 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001712 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001713 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001714 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001715 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1716 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1717 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001718 ]
1719 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001720 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001721
Aaron Gable697a91b2018-01-19 15:20:15 -08001722 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001723 self.calls += self._get_gerrit_codereview_server_calls(
1724 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001725 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001726 actual_codereview='gerrit', git_short_host='else',
1727 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001728 self.calls += [
1729 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1730 'refs/changes/56/123456/1'],), ''),
1731 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1732 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1733 ''),
1734 ((['git', 'config', 'branch.master.gerritserver',
1735 'https://else-review.googlesource.com'],), ''),
1736 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1737 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1738 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1739 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1740 ]
1741 self.assertEqual(git_cl.main(
1742 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1743 0)
1744
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001745 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001746 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001747 self.calls += [
1748 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001749 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001750 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1751 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1752 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001753 ]
1754 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001755 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001756
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001757 def test_patch_gerrit_not_exists(self):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001758 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001759 raise git_cl.gerrit_util.GerritError(404, '')
1760 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1761
tandriic2405f52016-10-10 08:13:15 -07001762 self.calls = [
1763 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandriic2405f52016-10-10 08:13:15 -07001764 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
1765 ((['git', 'config', 'branch.master.gerritissue'],), CERR1),
1766 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
1767 ((['git', 'config', 'gerrit.host'],), 'true'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001768 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1769 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1770 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1771 ((['git', 'config', 'remote.origin.url'],),
1772 'https://chromium.googlesource.com/my/repo'),
1773 ((['DieWithError',
1774 'change 123456 at https://chromium-review.googlesource.com does not '
1775 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001776 ]
1777 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001778 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001779
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001780 def _checkout_calls(self):
1781 return [
1782 ((['git', 'config', '--local', '--get-regexp',
1783 'branch\\..*\\.rietveldissue'], ),
1784 ('branch.retrying.rietveldissue 1111111111\n'
1785 'branch.some-fix.rietveldissue 2222222222\n')),
1786 ((['git', 'config', '--local', '--get-regexp',
1787 'branch\\..*\\.gerritissue'], ),
1788 ('branch.ger-branch.gerritissue 123456\n'
1789 'branch.gbranch654.gerritissue 654321\n')),
1790 ]
1791
1792 def test_checkout_gerrit(self):
1793 """Tests git cl checkout <issue>."""
1794 self.calls = self._checkout_calls()
1795 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1796 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1797
1798 def test_checkout_rietveld(self):
1799 """Tests git cl checkout <issue>."""
1800 self.calls = self._checkout_calls()
1801 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1802 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1803
1804 def test_checkout_not_found(self):
1805 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001806 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001807 self.calls = self._checkout_calls()
1808 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1809
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001810 def test_checkout_no_branch_issues(self):
1811 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001812 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001813 self.calls = [
1814 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001815 'branch\\..*\\.rietveldissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001816 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001817 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001818 ]
1819 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1820
tandrii@chromium.org28253532016-04-14 13:46:56 +00001821 def _test_gerrit_ensure_authenticated_common(self, auth,
1822 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001823 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1824 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1825 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11001826 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001827 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001828 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00001829 cl.branch = 'master'
1830 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001831 cl.lookedup_issue = True
1832 return cl
1833
1834 def test_gerrit_ensure_authenticated_missing(self):
1835 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001836 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001837 })
1838 self.calls.append(
1839 ((['DieWithError',
1840 'Credentials for the following hosts are required:\n'
1841 ' chromium-review.googlesource.com\n'
1842 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01001843 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001844 'https://chromium-review.googlesource.com/new-password'],), ''),)
1845 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1846
1847 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001848 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001849 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001850 'chromium.googlesource.com':
1851 ('git-one.example.com', None, 'secret1'),
1852 'chromium-review.googlesource.com':
1853 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001854 })
1855 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001856 (('ask_for_data', 'If you know what you are doing '
1857 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001858 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1859
1860 def test_gerrit_ensure_authenticated_ok(self):
1861 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001862 'chromium.googlesource.com':
1863 ('git-same.example.com', None, 'secret'),
1864 'chromium-review.googlesource.com':
1865 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001866 })
1867 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1868
tandrii@chromium.org28253532016-04-14 13:46:56 +00001869 def test_gerrit_ensure_authenticated_skipped(self):
1870 cl = self._test_gerrit_ensure_authenticated_common(
1871 auth={}, skip_auth_check=True)
1872 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1873
Eric Boren2fb63102018-10-05 13:05:03 +00001874 def test_gerrit_ensure_authenticated_bearer_token(self):
1875 cl = self._test_gerrit_ensure_authenticated_common(auth={
1876 'chromium.googlesource.com':
1877 ('', None, 'secret'),
1878 'chromium-review.googlesource.com':
1879 ('', None, 'secret'),
1880 })
1881 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1882 header = gerrit_util.CookiesAuthenticator().get_auth_header(
1883 'chromium.googlesource.com')
1884 self.assertTrue('Bearer' in header)
1885
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001886 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001887 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001888 lambda h, i, labels, notify=None:
1889 self._mocked_call(['SetReview', h, i, labels, notify]))
1890
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001891 self.calls = [
1892 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07001893 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
1894 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001895 ((['git', 'config', 'branch.feature.gerritserver'],),
1896 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00001897 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
1898 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
1899 ((['git', 'config', 'remote.origin.url'],),
1900 'https://chromium.googlesource.com/infra/infra.git'),
1901 ((['SetReview', 'chromium-review.googlesource.com',
1902 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01001903 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001904 ]
tandriid9e5ce52016-07-13 02:32:59 -07001905
1906 def test_cmd_set_commit_gerrit_clear(self):
1907 self._cmd_set_commit_gerrit_common(0)
1908 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1909
1910 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07001911 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001912 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1913
tandriid9e5ce52016-07-13 02:32:59 -07001914 def test_cmd_set_commit_gerrit(self):
1915 self._cmd_set_commit_gerrit_common(2)
1916 self.assertEqual(0, git_cl.main(['set-commit']))
1917
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001918 def test_description_display(self):
1919 out = StringIO.StringIO()
1920 self.mock(git_cl.sys, 'stdout', out)
1921
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001922 self.mock(git_cl, 'Changelist', ChangelistMock)
1923 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001924
1925 self.assertEqual(0, git_cl.main(['description', '-d']))
1926 self.assertEqual('foo\n', out.getvalue())
1927
iannucci3c972b92016-08-17 13:24:10 -07001928 def test_StatusFieldOverrideIssueMissingArgs(self):
1929 out = StringIO.StringIO()
1930 self.mock(git_cl.sys, 'stderr', out)
1931
1932 try:
1933 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
1934 except SystemExit as ex:
1935 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07001936 self.assertRegexpMatches(out.getvalue(), r'--issue must be specified')
iannucci3c972b92016-08-17 13:24:10 -07001937
1938 out = StringIO.StringIO()
1939 self.mock(git_cl.sys, 'stderr', out)
1940
1941 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00001942 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07001943 except SystemExit as ex:
1944 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07001945 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07001946
1947 def test_StatusFieldOverrideIssue(self):
1948 out = StringIO.StringIO()
1949 self.mock(git_cl.sys, 'stdout', out)
1950
1951 def assertIssue(cl_self, *_args):
1952 self.assertEquals(cl_self.issue, 1)
1953 return 'foobar'
1954
1955 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07001956 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00001957 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07001958 0)
iannucci3c972b92016-08-17 13:24:10 -07001959 self.assertEqual(out.getvalue(), 'foobar\n')
1960
iannuccie53c9352016-08-17 14:40:40 -07001961 def test_SetCloseOverrideIssue(self):
1962 def assertIssue(cl_self, *_args):
1963 self.assertEquals(cl_self.issue, 1)
1964 return 'foobar'
1965
1966 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
1967 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07001968 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00001969 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07001970
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001971 def test_description(self):
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001972 out = StringIO.StringIO()
1973 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001974 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001975 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1976 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
1977 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
1978 ((['git', 'config', 'remote.origin.url'],),
1979 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001980 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001981 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001982 {
1983 'current_revision': 'sha1',
1984 'revisions': {'sha1': {
1985 'commit': {'message': 'foobar'},
1986 }},
1987 }),
1988 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001989 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00001990 'description',
1991 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
1992 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001993 self.assertEqual('foobar\n', out.getvalue())
1994
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001995 def test_description_set_raw(self):
1996 out = StringIO.StringIO()
1997 self.mock(git_cl.sys, 'stdout', out)
1998
1999 self.mock(git_cl, 'Changelist', ChangelistMock)
2000 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
2001
2002 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2003 self.assertEqual('hihi', ChangelistMock.desc)
2004
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002005 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002006 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002007
2008 def RunEditor(desc, _, **kwargs):
2009 self.assertEquals(
2010 '# Enter a description of the change.\n'
2011 '# This will be displayed on the codereview site.\n'
2012 '# The first line will also be used as the subject of the review.\n'
2013 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002014 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002015 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002016 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002017 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002018 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002019
dsansomee2d6fd92016-09-08 00:10:47 -07002020 def UpdateDescriptionRemote(_, desc, force=False):
Aaron Gable3a16ed12017-03-23 10:51:55 -07002021 self.assertEquals(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002022
2023 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2024 self.mock(git_cl.Changelist, 'GetDescription',
2025 lambda *args: current_desc)
2026 self.mock(git_cl._GerritChangelistImpl, 'UpdateDescriptionRemote',
2027 UpdateDescriptionRemote)
2028 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2029
2030 self.calls = [
2031 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002032 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002033 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2034 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002035 ((['git', 'config', 'core.editor'],), 'vi'),
2036 ]
2037 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2038
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002039 def test_description_set_stdin(self):
2040 out = StringIO.StringIO()
2041 self.mock(git_cl.sys, 'stdout', out)
2042
2043 self.mock(git_cl, 'Changelist', ChangelistMock)
2044 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
2045
2046 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2047 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2048
kmarshall3bff56b2016-06-06 18:31:47 -07002049 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07002050 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2051
kmarshall3bff56b2016-06-06 18:31:47 -07002052 self.calls = \
2053 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2054 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
tandrii33a46ff2016-08-23 05:53:40 -07002055 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
tandrii5d48c322016-08-18 16:19:37 -07002056 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2057 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
tandrii33a46ff2016-08-23 05:53:40 -07002058 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
2059 ((['git', 'config', 'branch.bar.rietveldissue'],), CERR1),
2060 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
kmarshall3bff56b2016-06-06 18:31:47 -07002061 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2062 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
2063 ((['git', 'branch', '-D', 'foo'],), '')]
2064
kmarshall3bff56b2016-06-06 18:31:47 -07002065 self.mock(git_cl, 'get_cl_statuses',
2066 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002067 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2068 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2069 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002070
2071 self.assertEqual(0, git_cl.main(['archive', '-f']))
2072
2073 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07002074 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
kmarshall3bff56b2016-06-06 18:31:47 -07002075 self.calls = \
2076 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2077 'refs/heads/master'),
tandrii33a46ff2016-08-23 05:53:40 -07002078 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
tandrii5d48c322016-08-18 16:19:37 -07002079 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2080 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
kmarshall3bff56b2016-06-06 18:31:47 -07002081 ((['git', 'symbolic-ref', 'HEAD'],), 'master')]
2082
kmarshall9249e012016-08-23 12:02:16 -07002083 self.mock(git_cl, 'get_cl_statuses',
2084 lambda branches, fine_grained, max_processes:
2085 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2086
2087 self.assertEqual(1, git_cl.main(['archive', '-f']))
2088
2089 def test_archive_dry_run(self):
2090 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2091
2092 self.calls = \
2093 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2094 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2095 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
2096 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2097 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
2098 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
2099 ((['git', 'config', 'branch.bar.rietveldissue'],), CERR1),
2100 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
2101 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),]
kmarshall3bff56b2016-06-06 18:31:47 -07002102
2103 self.mock(git_cl, 'get_cl_statuses',
2104 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002105 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2106 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2107 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002108
kmarshall9249e012016-08-23 12:02:16 -07002109 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2110
2111 def test_archive_no_tags(self):
2112 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2113
2114 self.calls = \
2115 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2116 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2117 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
2118 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2119 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
2120 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
2121 ((['git', 'config', 'branch.bar.rietveldissue'],), CERR1),
2122 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
2123 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2124 ((['git', 'branch', '-D', 'foo'],), '')]
2125
2126 self.mock(git_cl, 'get_cl_statuses',
2127 lambda branches, fine_grained, max_processes:
2128 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2129 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2130 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2131
2132 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002133
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002134 def test_cmd_issue_erase_existing(self):
2135 out = StringIO.StringIO()
2136 self.mock(git_cl.sys, 'stdout', out)
2137 self.calls = [
2138 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002139 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2140 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002141 # Let this command raise exception (retcode=1) - it should be ignored.
2142 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002143 CERR1),
2144 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2145 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002146 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2147 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2148 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002149 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002150 ]
2151 self.assertEqual(0, git_cl.main(['issue', '0']))
2152
Aaron Gable400e9892017-07-12 15:31:21 -07002153 def test_cmd_issue_erase_existing_with_change_id(self):
2154 out = StringIO.StringIO()
2155 self.mock(git_cl.sys, 'stdout', out)
2156 self.mock(git_cl.Changelist, 'GetDescription',
2157 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2158 self.calls = [
2159 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2160 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2161 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
Aaron Gable400e9892017-07-12 15:31:21 -07002162 # Let this command raise exception (retcode=1) - it should be ignored.
2163 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2164 CERR1),
2165 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2166 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2167 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2168 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2169 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002170 ((['git', 'log', '-1', '--format=%B'],),
2171 'This is a description\n\nChange-Id: Ideadbeef'),
2172 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002173 ]
2174 self.assertEqual(0, git_cl.main(['issue', '0']))
2175
phajdan.jre328cf92016-08-22 04:12:17 -07002176 def test_cmd_issue_json(self):
2177 out = StringIO.StringIO()
2178 self.mock(git_cl.sys, 'stdout', out)
2179 self.calls = [
2180 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002181 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
phajdan.jre328cf92016-08-22 04:12:17 -07002182 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2183 ((['git', 'config', 'rietveld.server'],),
2184 'https://codereview.chromium.org'),
2185 ((['git', 'config', 'branch.feature.rietveldserver'],), ''),
2186 (('write_json', 'output.json',
2187 {'issue': 123, 'issue_url': 'https://codereview.chromium.org/123'}),
2188 ''),
2189 ]
2190 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2191
tandrii8c5a3532016-11-04 07:52:02 -07002192 def test_git_cl_try_default_cq_dry_run_gerrit(self):
2193 self.mock(git_cl.Changelist, 'GetChange',
2194 lambda _, *a: (
2195 self._mocked_call(['GetChange']+list(a))))
2196 self.mock(git_cl.presubmit_support, 'DoGetTryMasters',
2197 lambda *_, **__: (
2198 self._mocked_call(['DoGetTryMasters'])))
2199 self.mock(git_cl._GerritChangelistImpl, 'SetCQState',
2200 lambda _, s: self._mocked_call(['SetCQState', s]))
2201
tandrii8c5a3532016-11-04 07:52:02 -07002202 self.calls = [
2203 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2204 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2205 ((['git', 'config', 'branch.feature.gerritissue'],), '123456'),
2206 ((['git', 'config', 'branch.feature.gerritserver'],),
2207 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002208 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2209 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2210 ((['git', 'config', 'remote.origin.url'],),
2211 'https://chromium.googlesource.com/depot_tools'),
2212 (('GetChangeDetail', 'chromium-review.googlesource.com',
2213 'depot_tools~123456',
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01002214 ['DETAILED_ACCOUNTS', 'ALL_REVISIONS', 'CURRENT_COMMIT']), {
2215 'project': 'depot_tools',
2216 'status': 'OPEN',
2217 'owner': {'email': 'owner@e.mail'},
2218 'revisions': {
2219 'deadbeaf': {
2220 '_number': 6,
2221 },
2222 'beeeeeef': {
2223 '_number': 7,
2224 'fetch': {'http': {
2225 'url': 'https://chromium.googlesource.com/depot_tools',
2226 'ref': 'refs/changes/56/123456/7'
2227 }},
2228 },
2229 },
2230 }),
tandrii8c5a3532016-11-04 07:52:02 -07002231 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2232 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2233 ((['get_or_create_merge_base', 'feature', 'feature'],),
2234 'fake_ancestor_sha'),
2235 ((['GetChange', 'fake_ancestor_sha', None], ),
2236 git_cl.presubmit_support.GitChange(
2237 '', '', '', '', '', '', '', '')),
2238 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2239 ((['DoGetTryMasters'], ), None),
2240 ((['SetCQState', git_cl._CQState.DRY_RUN], ), None),
2241 ]
2242 out = StringIO.StringIO()
2243 self.mock(git_cl.sys, 'stdout', out)
2244 self.assertEqual(0, git_cl.main(['try']))
2245 self.assertEqual(
2246 out.getvalue(),
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07002247 'Scheduling CQ dry run on: '
tandrii8c5a3532016-11-04 07:52:02 -07002248 'https://chromium-review.googlesource.com/123456\n')
2249
tandrii8c5a3532016-11-04 07:52:02 -07002250 def test_git_cl_try_buildbucket_with_properties_gerrit(self):
2251 self.mock(git_cl.Changelist, 'GetMostRecentPatchset', lambda _: 7)
2252 self.mock(git_cl.uuid, 'uuid4', lambda: 'uuid4')
2253
tandrii8c5a3532016-11-04 07:52:02 -07002254 self.calls = [
2255 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2256 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2257 ((['git', 'config', 'branch.feature.gerritissue'],), '123456'),
2258 ((['git', 'config', 'branch.feature.gerritserver'],),
2259 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002260 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2261 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2262 ((['git', 'config', 'remote.origin.url'],),
2263 'https://chromium.googlesource.com/depot_tools'),
2264 (('GetChangeDetail', 'chromium-review.googlesource.com',
2265 'depot_tools~123456',
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01002266 ['DETAILED_ACCOUNTS', 'ALL_REVISIONS', 'CURRENT_COMMIT']), {
tandrii8c5a3532016-11-04 07:52:02 -07002267 'project': 'depot_tools',
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01002268 'status': 'OPEN',
2269 'owner': {'email': 'owner@e.mail'},
tandrii8c5a3532016-11-04 07:52:02 -07002270 'revisions': {
2271 'deadbeaf': {
2272 '_number': 6,
2273 },
2274 'beeeeeef': {
2275 '_number': 7,
2276 'fetch': {'http': {
2277 'url': 'https://chromium.googlesource.com/depot_tools',
2278 'ref': 'refs/changes/56/123456/7'
2279 }},
2280 },
2281 },
2282 }),
2283 ]
2284
2285 def _buildbucket_retry(*_, **kw):
2286 # self.maxDiff = 10000
2287 body = json.loads(kw['body'])
2288 self.assertEqual(len(body['builds']), 1)
2289 build = body['builds'][0]
2290 params = json.loads(build.pop('parameters_json'))
2291 self.assertEqual(params, {
2292 u'builder_name': u'win',
2293 u'changes': [{u'author': {u'email': u'owner@e.mail'},
2294 u'revision': None}],
2295 u'properties': {
2296 u'category': u'git_cl_try',
2297 u'key': u'val',
2298 u'json': [{u'a': 1}, None],
tandrii8c5a3532016-11-04 07:52:02 -07002299
2300 u'patch_gerrit_url':
2301 u'https://chromium-review.googlesource.com',
2302 u'patch_issue': 123456,
2303 u'patch_project': u'depot_tools',
2304 u'patch_ref': u'refs/changes/56/123456/7',
2305 u'patch_repository_url':
2306 u'https://chromium.googlesource.com/depot_tools',
2307 u'patch_set': 7,
2308 u'patch_storage': u'gerrit',
2309 }
2310 })
2311 self.assertEqual(build, {
Andrii Shyshkalov03da1502018-10-15 03:42:34 +00002312 u'bucket': u'luci.chromium.try',
tandrii8c5a3532016-11-04 07:52:02 -07002313 u'client_operation_id': u'uuid4',
2314 u'tags': [
2315 u'builder:win',
2316 u'buildset:patch/gerrit/chromium-review.googlesource.com/123456/7',
2317 u'user_agent:git_cl_try',
Andrii Shyshkalov03da1502018-10-15 03:42:34 +00002318 ],
tandrii8c5a3532016-11-04 07:52:02 -07002319 })
2320
2321 self.mock(git_cl, '_buildbucket_retry', _buildbucket_retry)
2322
2323 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2324 self.assertEqual(0, git_cl.main([
Andrii Shyshkalov03da1502018-10-15 03:42:34 +00002325 'try', '-B', 'luci.chromium.try', '-b', 'win',
tandrii8c5a3532016-11-04 07:52:02 -07002326 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
2327 self.assertRegexpMatches(
2328 git_cl.sys.stdout.getvalue(),
Andrii Shyshkalov03da1502018-10-15 03:42:34 +00002329 'Tried jobs on:\nBucket: luci.chromium.try')
tandriide281ae2016-10-12 06:02:30 -07002330
qyearsley123a4682016-10-26 09:12:17 -07002331 def test_git_cl_try_bots_on_multiple_masters(self):
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +00002332 self.mock(git_cl.Changelist, 'GetMostRecentPatchset', lambda _: 7)
2333 self.mock(git_cl.Changelist, 'GetChange',
2334 lambda _, *a: (
2335 self._mocked_call(['GetChange']+list(a))))
2336 self.mock(git_cl.presubmit_support, 'DoGetTryMasters',
2337 lambda *_, **__: (
2338 self._mocked_call(['DoGetTryMasters'])))
2339 self.mock(git_cl._GerritChangelistImpl, 'SetCQState',
2340 lambda _, s: self._mocked_call(['SetCQState', s]))
2341
qyearsley123a4682016-10-26 09:12:17 -07002342 self.calls = [
2343 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +00002344 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2345 ((['git', 'config', 'branch.feature.gerritissue'],), '123456'),
2346 ((['git', 'config', 'branch.feature.gerritserver'],),
2347 'https://chromium-review.googlesource.com'),
2348 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2349 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2350 ((['git', 'config', 'remote.origin.url'],),
2351 'https://chromium.googlesource.com/depot_tools'),
2352 (('GetChangeDetail', 'chromium-review.googlesource.com',
2353 'depot_tools~123456',
2354 ['DETAILED_ACCOUNTS', 'ALL_REVISIONS', 'CURRENT_COMMIT']), {
2355 'project': 'depot_tools',
2356 'status': 'OPEN',
2357 'owner': {'email': 'owner@e.mail'},
2358 'revisions': {
2359 'deadbeaf': {
2360 '_number': 6,
2361 },
2362 'beeeeeef': {
2363 '_number': 7,
2364 'fetch': {'http': {
2365 'url': 'https://chromium.googlesource.com/depot_tools',
2366 'ref': 'refs/changes/56/123456/7'
2367 }},
2368 },
2369 },
2370 }),
qyearsley123a4682016-10-26 09:12:17 -07002371 ]
2372
2373 def _buildbucket_retry(*_, **kw):
2374 body = json.loads(kw['body'])
2375 self.assertEqual(len(body['builds']), 2)
2376
Nodir Turakulovb422e682018-02-20 22:51:30 -08002377 self.assertEqual(body['builds'][0]['bucket'], 'bucket1')
2378 params = json.loads(body['builds'][0]['parameters_json'])
2379 self.assertEqual(params['builder_name'], 'builder1')
qyearsley123a4682016-10-26 09:12:17 -07002380
Nodir Turakulovb422e682018-02-20 22:51:30 -08002381 self.assertEqual(body['builds'][1]['bucket'], 'bucket2')
2382 params = json.loads(body['builds'][1]['parameters_json'])
2383 self.assertEqual(params['builder_name'], 'builder2')
qyearsley123a4682016-10-26 09:12:17 -07002384
2385 self.mock(git_cl, '_buildbucket_retry', _buildbucket_retry)
2386
2387 self.mock(git_cl.urllib2, 'urlopen', lambda _: StringIO.StringIO(
Nodir Turakulovb422e682018-02-20 22:51:30 -08002388 json.dumps({
2389 'builder1': {'bucket': 'bucket1'},
2390 'builder2': {'bucket': 'bucket2'},
2391 })))
qyearsley123a4682016-10-26 09:12:17 -07002392
2393 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2394 self.assertEqual(
2395 0, git_cl.main(['try', '-b', 'builder1', '-b', 'builder2']))
2396 self.assertEqual(
2397 git_cl.sys.stdout.getvalue(),
2398 'Tried jobs on:\n'
Nodir Turakulovb422e682018-02-20 22:51:30 -08002399 'Bucket: bucket1\n'
qyearsley123a4682016-10-26 09:12:17 -07002400 ' builder1: []\n'
Nodir Turakulovb422e682018-02-20 22:51:30 -08002401 'Bucket: bucket2\n'
qyearsley123a4682016-10-26 09:12:17 -07002402 ' builder2: []\n'
2403 'To see results here, run: git cl try-results\n'
2404 'To see results in browser, run: git cl web\n')
2405
tandrii16e0b4e2016-06-07 10:34:28 -07002406 def _common_GerritCommitMsgHookCheck(self):
2407 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2408 self.mock(git_cl.os.path, 'abspath',
2409 lambda path: self._mocked_call(['abspath', path]))
2410 self.mock(git_cl.os.path, 'exists',
2411 lambda path: self._mocked_call(['exists', path]))
2412 self.mock(git_cl.gclient_utils, 'FileRead',
2413 lambda path: self._mocked_call(['FileRead', path]))
2414 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2415 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2416 self.calls = [
2417 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2418 ((['abspath', '../'],), '/abs/git_repo_root'),
2419 ]
2420 return git_cl.Changelist(codereview='gerrit', issue=123)
2421
2422 def test_GerritCommitMsgHookCheck_custom_hook(self):
2423 cl = self._common_GerritCommitMsgHookCheck()
2424 self.calls += [
2425 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2426 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2427 '#!/bin/sh\necho "custom hook"')
2428 ]
2429 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
2430
2431 def test_GerritCommitMsgHookCheck_not_exists(self):
2432 cl = self._common_GerritCommitMsgHookCheck()
2433 self.calls += [
2434 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2435 ]
2436 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
2437
2438 def test_GerritCommitMsgHookCheck(self):
2439 cl = self._common_GerritCommitMsgHookCheck()
2440 self.calls += [
2441 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2442 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2443 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002444 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002445 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2446 ''),
2447 ]
2448 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
2449
tandriic4344b52016-08-29 06:04:54 -07002450 def test_GerritCmdLand(self):
2451 self.calls += [
2452 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2453 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2454 'deadbeaf'),
2455 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2456 ((['git', 'config', 'branch.feature.gerritserver'],),
2457 'chromium-review.googlesource.com'),
2458 ]
2459 cl = git_cl.Changelist(issue=123, codereview='gerrit')
2460 cl._codereview_impl._GetChangeDetail = lambda _: {
2461 'labels': {},
2462 'current_revision': 'deadbeaf',
2463 }
agable32978d92016-11-01 12:55:02 -07002464 cl._codereview_impl._GetChangeCommit = lambda: {
2465 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002466 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002467 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2468 }
tandriic4344b52016-08-29 06:04:54 -07002469 cl._codereview_impl.SubmitIssue = lambda wait_for_merge: None
tandrii8da412c2016-09-07 16:01:07 -07002470 out = StringIO.StringIO()
2471 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002472 self.assertEqual(0, cl.CMDLand(force=True,
2473 bypass_hooks=True,
2474 verbose=True,
2475 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002476 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002477 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002478
tandrii221ab252016-10-06 08:12:04 -07002479 BUILDBUCKET_BUILDS_MAP = {
Quinten Yearsleya563d722017-12-11 16:36:54 -08002480 '9000': {
2481 'id': '9000',
2482 'bucket': 'master.x.y',
2483 'created_by': 'user:someone@chromium.org',
2484 'created_ts': '147200002222000',
2485 'experimental': False,
2486 'parameters_json': json.dumps({
2487 'builder_name': 'my-bot',
2488 'properties': {'category': 'cq'},
2489 }),
2490 'status': 'STARTED',
2491 'tags': [
2492 'build_address:x.y/my-bot/2',
2493 'builder:my-bot',
2494 'experimental:false',
2495 'user_agent:cq',
2496 ],
2497 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2498 },
2499 '8000': {
2500 'id': '8000',
2501 'bucket': 'master.x.y',
2502 'created_by': 'user:someone@chromium.org',
2503 'created_ts': '147200001111000',
2504 'experimental': False,
2505 'failure_reason': 'BUILD_FAILURE',
2506 'parameters_json': json.dumps({
2507 'builder_name': 'my-bot',
2508 'properties': {'category': 'cq'},
2509 }),
2510 'result_details_json': json.dumps({
2511 'properties': {'buildnumber': 1},
2512 }),
2513 'result': 'FAILURE',
2514 'status': 'COMPLETED',
2515 'tags': [
2516 'build_address:x.y/my-bot/1',
2517 'builder:my-bot',
2518 'experimental:false',
2519 'user_agent:cq',
2520 ],
2521 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2522 },
2523 }
tandrii221ab252016-10-06 08:12:04 -07002524
2525 def test_write_try_results_json(self):
2526 expected_output = [
Quinten Yearsleya563d722017-12-11 16:36:54 -08002527 {
2528 'bucket': 'master.x.y',
2529 'buildbucket_id': '8000',
2530 'builder_name': 'my-bot',
2531 'created_ts': '147200001111000',
2532 'experimental': False,
2533 'failure_reason': 'BUILD_FAILURE',
2534 'result': 'FAILURE',
2535 'status': 'COMPLETED',
2536 'tags': [
2537 'build_address:x.y/my-bot/1',
2538 'builder:my-bot',
2539 'experimental:false',
2540 'user_agent:cq',
2541 ],
2542 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2543 },
2544 {
2545 'bucket': 'master.x.y',
2546 'buildbucket_id': '9000',
2547 'builder_name': 'my-bot',
2548 'created_ts': '147200002222000',
2549 'experimental': False,
2550 'failure_reason': None,
2551 'result': None,
2552 'status': 'STARTED',
2553 'tags': [
2554 'build_address:x.y/my-bot/2',
2555 'builder:my-bot',
2556 'experimental:false',
2557 'user_agent:cq',
2558 ],
2559 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2560 },
tandrii221ab252016-10-06 08:12:04 -07002561 ]
2562 self.calls = [(('write_json', 'output.json', expected_output), '')]
2563 git_cl.write_try_results_json('output.json', self.BUILDBUCKET_BUILDS_MAP)
2564
tandrii45b2a582016-10-11 03:14:16 -07002565 def _setup_fetch_try_jobs(self, most_recent_patchset=20001):
tandrii221ab252016-10-06 08:12:04 -07002566 out = StringIO.StringIO()
2567 self.mock(sys, 'stdout', out)
tandrii45b2a582016-10-11 03:14:16 -07002568 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
2569 lambda *args: most_recent_patchset)
tandrii221ab252016-10-06 08:12:04 -07002570 self.mock(git_cl.auth, 'get_authenticator_for_host', lambda host, _cfg:
2571 self._mocked_call(['get_authenticator_for_host', host]))
2572 self.mock(git_cl, '_buildbucket_retry', lambda *_, **__:
2573 self._mocked_call(['_buildbucket_retry']))
tandrii45b2a582016-10-11 03:14:16 -07002574
tandrii45b2a582016-10-11 03:14:16 -07002575 def _setup_fetch_try_jobs_gerrit(self, *request_results):
2576 self._setup_fetch_try_jobs(most_recent_patchset=13)
2577 self.calls += [
2578 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2579 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2580 ((['git', 'config', 'branch.feature.gerritissue'],), '1'),
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002581 # TODO(tandrii): Uncomment the below if we decide to support checking
2582 # patchsets for Gerrit.
tandrii45b2a582016-10-11 03:14:16 -07002583 # Simulate that Gerrit has more patchsets than local.
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002584 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'),
tandrii45b2a582016-10-11 03:14:16 -07002585 ((['git', 'config', 'branch.feature.gerritserver'],),
2586 'https://x-review.googlesource.com'),
2587 ((['get_authenticator_for_host', 'x-review.googlesource.com'],),
2588 AuthenticatorMock()),
2589 ] + [((['_buildbucket_retry'],), r) for r in request_results]
2590
2591 def test_fetch_try_jobs_none_gerrit(self):
2592 self._setup_fetch_try_jobs_gerrit({})
2593 self.assertEqual(0, git_cl.main(['try-results']))
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002594 # TODO(tandrii): Uncomment the below if we decide to support checking
2595 # patchsets for Gerrit.
2596 # self.assertRegexpMatches(
2597 # sys.stdout.getvalue(),
2598 # r'Warning: Codereview server has newer patchsets \(13\)')
tandrii45b2a582016-10-11 03:14:16 -07002599 self.assertRegexpMatches(sys.stdout.getvalue(), 'No try jobs')
2600
2601 def test_fetch_try_jobs_some_gerrit(self):
2602 self._setup_fetch_try_jobs_gerrit({
2603 'builds': self.BUILDBUCKET_BUILDS_MAP.values(),
2604 })
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002605 # TODO(tandrii): Uncomment the below if we decide to support checking
2606 # patchsets for Gerrit.
2607 # self.calls.remove(
2608 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'))
tandrii45b2a582016-10-11 03:14:16 -07002609 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '5']))
2610
2611 # ... and doesn't result in warning.
2612 self.assertNotRegexpMatches(sys.stdout.getvalue(), 'Warning')
2613 self.assertRegexpMatches(sys.stdout.getvalue(), '^Failures:')
tandrii221ab252016-10-06 08:12:04 -07002614 self.assertRegexpMatches(sys.stdout.getvalue(), 'Started:')
2615 self.assertRegexpMatches(sys.stdout.getvalue(), '2 try jobs')
2616
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002617 def _mock_gerrit_changes_for_detail_cache(self):
2618 self.mock(git_cl._GerritChangelistImpl, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002619
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002620 def test_gerrit_change_detail_cache_simple(self):
2621 self._mock_gerrit_changes_for_detail_cache()
2622 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002623 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2624 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2625 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002626 ]
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002627 cl1 = git_cl.Changelist(issue=1, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002628 cl1._cached_remote_url = (
2629 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002630 cl2 = git_cl.Changelist(issue=2, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002631 cl2._cached_remote_url = (
2632 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002633 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2634 self.assertEqual(cl1._GetChangeDetail(), 'a')
2635 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2636 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2637 self.assertEqual(cl1._GetChangeDetail(), 'a')
2638 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002639
2640 def test_gerrit_change_detail_cache_options(self):
2641 self._mock_gerrit_changes_for_detail_cache()
2642 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002643 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2644 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2645 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2646 # no longer in cache.
2647 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002648 ]
2649 cl = git_cl.Changelist(issue=1, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002650 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002651 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2652 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2653 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2654 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2655 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2656 self.assertEqual(cl._GetChangeDetail(), 'cab')
2657
2658 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2659 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2660 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2661 self.assertEqual(cl._GetChangeDetail(), 'cab')
2662
2663 # Finally, no_cache should invalidate all caches for given change.
2664 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2665 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2666
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002667 def test_gerrit_description_caching(self):
2668 def gen_detail(rev, desc):
2669 return {
2670 'current_revision': rev,
2671 'revisions': {rev: {'commit': {'message': desc}}}
2672 }
2673 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002674 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002675 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2676 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002677 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002678 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2679 gen_detail('rev2', 'desc2')),
2680 ]
2681
2682 self._mock_gerrit_changes_for_detail_cache()
2683 cl = git_cl.Changelist(issue=1, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002684 cl._cached_remote_url = (
2685 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002686 self.assertEqual(cl.GetDescription(), 'desc1')
2687 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2688 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002689
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002690 def test_print_current_creds(self):
2691 class CookiesAuthenticatorMock(object):
2692 def __init__(self):
2693 self.gitcookies = {
2694 'host.googlesource.com': ('user', 'pass'),
2695 'host-review.googlesource.com': ('user', 'pass'),
2696 }
2697 self.netrc = self
2698 self.netrc.hosts = {
2699 'github.com': ('user2', None, 'pass2'),
2700 'host2.googlesource.com': ('user3', None, 'pass'),
2701 }
2702 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2703 CookiesAuthenticatorMock)
2704 self.mock(sys, 'stdout', StringIO.StringIO())
2705 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2706 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2707 ' Host\t User\t Which file',
2708 '============================\t=====\t===========',
2709 'host-review.googlesource.com\t user\t.gitcookies',
2710 ' host.googlesource.com\t user\t.gitcookies',
2711 ' host2.googlesource.com\tuser3\t .netrc',
2712 ])
2713 sys.stdout.buf = ''
2714 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2715 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2716 ' Host\tUser\t Which file',
2717 '============================\t====\t===========',
2718 'host-review.googlesource.com\tuser\t.gitcookies',
2719 ' host.googlesource.com\tuser\t.gitcookies',
2720 ])
2721
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002722 def _common_creds_check_mocks(self):
2723 def exists_mock(path):
2724 dirname = os.path.dirname(path)
2725 if dirname == os.path.expanduser('~'):
2726 dirname = '~'
2727 base = os.path.basename(path)
2728 if base in ('.netrc', '.gitcookies'):
2729 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2730 # git cl also checks for existence other files not relevant to this test.
2731 return None
2732 self.mock(os.path, 'exists', exists_mock)
2733 self.mock(sys, 'stdout', StringIO.StringIO())
2734
2735 def test_creds_check_gitcookies_not_configured(self):
2736 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002737 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002738 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002739 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002740 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002741 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2742 (('os.path.exists', '~/.netrc'), True),
2743 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2744 'or Ctrl+C to abort'), ''),
2745 ((['git', 'config', '--global', 'http.cookiefile',
2746 os.path.expanduser('~/.gitcookies')], ), ''),
2747 ]
2748 self.assertEqual(0, git_cl.main(['creds-check']))
2749 self.assertRegexpMatches(
2750 sys.stdout.getvalue(),
2751 '^You seem to be using outdated .netrc for git credentials:')
2752 self.assertRegexpMatches(
2753 sys.stdout.getvalue(),
2754 '\nConfigured git to use .gitcookies from')
2755
2756 def test_creds_check_gitcookies_configured_custom_broken(self):
2757 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002758 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002759 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002760 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002761 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002762 ((['git', 'config', '--global', 'http.cookiefile'],),
2763 '/custom/.gitcookies'),
2764 (('os.path.exists', '/custom/.gitcookies'), False),
2765 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2766 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2767 ((['git', 'config', '--global', 'http.cookiefile',
2768 os.path.expanduser('~/.gitcookies')], ), ''),
2769 ]
2770 self.assertEqual(0, git_cl.main(['creds-check']))
2771 self.assertRegexpMatches(
2772 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002773 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002774 self.assertRegexpMatches(
2775 sys.stdout.getvalue(),
2776 'However, your configured .gitcookies file is missing.')
2777
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002778 def test_git_cl_comment_add_gerrit(self):
2779 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002780 lambda host, change, msg, ready:
2781 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002782 self.calls = [
2783 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2784 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2785 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2786 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2787 'origin/master'),
2788 ((['git', 'config', 'remote.origin.url'],),
2789 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002790 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2791 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002792 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002793 ]
2794 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2795 '-a', 'msg']))
2796
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002797 def test_git_cl_comments_fetch_gerrit(self):
2798 self.mock(sys, 'stdout', StringIO.StringIO())
2799 self.calls = [
2800 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2801 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2802 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2803 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2804 'origin/master'),
2805 ((['git', 'config', 'remote.origin.url'],),
2806 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002807 (('GetChangeDetail', 'chromium-review.googlesource.com',
2808 'infra%2Finfra~1',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002809 ['MESSAGES', 'DETAILED_ACCOUNTS']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002810 'owner': {'email': 'owner@example.com'},
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002811 'messages': [
2812 {
2813 u'_revision_number': 1,
2814 u'author': {
2815 u'_account_id': 1111084,
2816 u'email': u'commit-bot@chromium.org',
2817 u'name': u'Commit Bot'
2818 },
2819 u'date': u'2017-03-15 20:08:45.000000000',
2820 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002821 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002822 u'tag': u'autogenerated:cq:dry-run'
2823 },
2824 {
2825 u'_revision_number': 2,
2826 u'author': {
2827 u'_account_id': 11151243,
2828 u'email': u'owner@example.com',
2829 u'name': u'owner'
2830 },
2831 u'date': u'2017-03-16 20:00:41.000000000',
2832 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2833 u'message': u'PTAL',
2834 },
2835 {
2836 u'_revision_number': 2,
2837 u'author': {
2838 u'_account_id': 148512 ,
2839 u'email': u'reviewer@example.com',
2840 u'name': u'reviewer'
2841 },
2842 u'date': u'2017-03-17 05:19:37.500000000',
2843 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2844 u'message': u'Patch Set 2: Code-Review+1',
2845 },
2846 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002847 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002848 (('GetChangeComments', 'chromium-review.googlesource.com',
2849 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002850 '/COMMIT_MSG': [
2851 {
2852 'author': {'email': u'reviewer@example.com'},
2853 'updated': u'2017-03-17 05:19:37.500000000',
2854 'patch_set': 2,
2855 'side': 'REVISION',
2856 'message': 'Please include a bug link',
2857 },
2858 ],
2859 'codereview.settings': [
2860 {
2861 'author': {'email': u'owner@example.com'},
2862 'updated': u'2017-03-16 20:00:41.000000000',
2863 'patch_set': 2,
2864 'side': 'PARENT',
2865 'line': 42,
2866 'message': 'I removed this because it is bad',
2867 },
2868 ]
Leszek Swirski45b20c42018-09-17 17:05:26 +00002869 })
2870 ] * 2 + [
2871 (('write_json', 'output.json', [
2872 {
2873 u'date': u'2017-03-16 20:00:41.000000',
2874 u'message': (
2875 u'PTAL\n' +
2876 u'\n' +
2877 u'codereview.settings\n' +
2878 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2879 u'c/1/2/codereview.settings#b42\n' +
2880 u' I removed this because it is bad\n'),
2881 u'approval': False,
2882 u'disapproval': False,
2883 u'sender': u'owner@example.com'
2884 }, {
2885 u'date': u'2017-03-17 05:19:37.500000',
2886 u'message': (
2887 u'Patch Set 2: Code-Review+1\n' +
2888 u'\n' +
2889 u'/COMMIT_MSG\n' +
2890 u' PS2, File comment: https://chromium-review.googlesource' +
2891 u'.com/c/1/2//COMMIT_MSG#\n' +
2892 u' Please include a bug link\n'),
2893 u'approval': False,
2894 u'disapproval': False,
2895 u'sender': u'reviewer@example.com'
2896 }
2897 ]),'')
2898 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002899 expected_comments_summary = [
2900 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002901 message=(
2902 u'PTAL\n' +
2903 u'\n' +
2904 u'codereview.settings\n' +
2905 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2906 u'c/1/2/codereview.settings#b42\n' +
2907 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002908 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
2909 disapproval=False, approval=False, sender=u'owner@example.com'),
2910 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002911 message=(
2912 u'Patch Set 2: Code-Review+1\n' +
2913 u'\n' +
2914 u'/COMMIT_MSG\n' +
2915 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2916 u'c/1/2//COMMIT_MSG#\n' +
2917 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002918 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
2919 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2920 ]
2921 cl = git_cl.Changelist(codereview='gerrit', issue=1)
2922 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov642641d2018-10-16 05:54:41 +00002923 self.assertEqual(0, git_cl.main(['comment', '-i', '1',
Leszek Swirski45b20c42018-09-17 17:05:26 +00002924 '-j', 'output.json']))
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002925
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002926 def test_get_remote_url_with_mirror(self):
2927 original_os_path_isdir = os.path.isdir
2928 def selective_os_path_isdir_mock(path):
2929 if path == '/cache/this-dir-exists':
2930 return self._mocked_call('os.path.isdir', path)
2931 return original_os_path_isdir(path)
2932 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2933
2934 url = 'https://chromium.googlesource.com/my/repo'
2935 self.calls = [
2936 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2937 ((['git', 'config', 'branch.master.merge'],), 'master'),
2938 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2939 ((['git', 'config', 'remote.origin.url'],),
2940 '/cache/this-dir-exists'),
2941 (('os.path.isdir', '/cache/this-dir-exists'),
2942 True),
2943 # Runs in /cache/this-dir-exists.
2944 ((['git', 'config', 'remote.origin.url'],),
2945 url),
2946 ]
2947 cl = git_cl.Changelist(codereview='gerrit', issue=1)
2948 self.assertEqual(cl.GetRemoteUrl(), url)
2949 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2950
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002951 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002952 self.calls = [
2953 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2954 ((['git', 'config', 'branch.master.merge'],), 'master'),
2955 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2956 ((['git', 'config', 'remote.origin.url'],),
2957 'https://chromium.googlesource.com/a/my/repo.git/'),
2958 ]
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002959 cl = git_cl.Changelist(codereview='gerrit', issue=123456)
2960 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2961
2962 def test_gerrit_change_identifier_without_project(self):
2963 self.calls = [
2964 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2965 ((['git', 'config', 'branch.master.merge'],), 'master'),
2966 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2967 ((['git', 'config', 'remote.origin.url'],), CERR1),
2968 ]
2969 cl = git_cl.Changelist(codereview='gerrit', issue=123456)
2970 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002971
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002972
maruel@chromium.orgddd59412011-11-30 14:20:38 +00002973if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01002974 logging.basicConfig(
2975 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00002976 unittest.main()