blob: f7de42b836eb420a0eec8b4ad86e2fad81d2d6e7 [file] [log] [blame]
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001#!/usr/bin/env python
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Unit tests for git_cl.py."""
7
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01008import datetime
tandriide281ae2016-10-12 06:02:30 -07009import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010010import logging
maruel@chromium.orgddd59412011-11-30 14:20:38 +000011import os
maruel@chromium.orga3353652011-11-30 14:26:57 +000012import StringIO
maruel@chromium.orgddd59412011-11-30 14:20:38 +000013import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070014import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000015import unittest
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +000016import urlparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000017
18sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19
20from testing_support.auto_stub import TestCase
Edward Lemur4c707a22019-09-24 21:13:43 +000021from third_party import mock
maruel@chromium.orgddd59412011-11-30 14:20:38 +000022
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
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000033
tandrii5d48c322016-08-18 16:19:37 -070034def callError(code=1, cmd='', cwd='', stdout='', stderr=''):
35 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
36
37
Edward Lemur4c707a22019-09-24 21:13:43 +000038def _constantFn(return_value):
39 def f(*args, **kwargs):
40 return return_value
41 return f
42
43
tandrii5d48c322016-08-18 16:19:37 -070044CERR1 = callError(1)
45
46
Aaron Gable9a03ae02017-11-03 11:31:07 -070047def MakeNamedTemporaryFileMock(expected_content):
48 class NamedTemporaryFileMock(object):
49 def __init__(self, *args, **kwargs):
50 self.name = '/tmp/named'
51 self.expected_content = expected_content
52
53 def __enter__(self):
54 return self
55
56 def __exit__(self, _type, _value, _tb):
57 pass
58
59 def write(self, content):
60 if self.expected_content:
61 assert content == self.expected_content
62
63 def close(self):
64 pass
65
66 return NamedTemporaryFileMock
67
68
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000069class ChangelistMock(object):
70 # A class variable so we can access it when we don't have access to the
71 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000072 desc = ''
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000073 def __init__(self, **kwargs):
74 pass
75 def GetIssue(self):
76 return 1
Kenneth Russell61e2ed42017-02-15 11:47:13 -080077 def GetDescription(self, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000078 return ChangelistMock.desc
dsansomee2d6fd92016-09-08 00:10:47 -070079 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000080 ChangelistMock.desc = desc
81
tandrii5d48c322016-08-18 16:19:37 -070082
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000083class PresubmitMock(object):
84 def __init__(self, *args, **kwargs):
85 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080086 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
87
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000088 @staticmethod
89 def should_continue():
90 return True
91
92
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000093class WatchlistsMock(object):
94 def __init__(self, _):
95 pass
96 @staticmethod
97 def GetWatchersForPaths(_):
98 return ['joe@example.com']
99
100
Edward Lemur4c707a22019-09-24 21:13:43 +0000101class CodereviewSettingsFileMock(object):
102 def __init__(self):
103 pass
104 # pylint: disable=no-self-use
105 def read(self):
106 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
107 'GERRIT_HOST: True\n')
108
109
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000110class AuthenticatorMock(object):
111 def __init__(self, *_args):
112 pass
113 def has_cached_credentials(self):
114 return True
tandrii221ab252016-10-06 08:12:04 -0700115 def authorize(self, http):
116 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000117
118
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100119def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000120 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
121
122 Usage:
123 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100124 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000125
126 OR
127 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100128 CookiesAuthenticatorMockFactory(
129 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000130 """
131 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800132 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000133 # Intentionally not calling super() because it reads actual cookie files.
134 pass
135 @classmethod
136 def get_gitcookies_path(cls):
137 return '~/.gitcookies'
138 @classmethod
139 def get_netrc_path(cls):
140 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100141 def _get_auth_for_host(self, host):
142 if same_auth:
143 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000144 return (hosts_with_creds or {}).get(host)
145 return CookiesAuthenticatorMock
146
Aaron Gable9a03ae02017-11-03 11:31:07 -0700147
kmarshall9249e012016-08-23 12:02:16 -0700148class MockChangelistWithBranchAndIssue():
149 def __init__(self, branch, issue):
150 self.branch = branch
151 self.issue = issue
152 def GetBranch(self):
153 return self.branch
154 def GetIssue(self):
155 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000156
tandriic2405f52016-10-10 08:13:15 -0700157
158class SystemExitMock(Exception):
159 pass
160
161
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000162class TestGitClBasic(unittest.TestCase):
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100163 def test_get_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000164 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100165 cl.description = 'x'
166 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000167 cl.FetchDescription = lambda *a, **kw: 'y'
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100168 self.assertEquals(cl.GetDescription(), 'x')
169 self.assertEquals(cl.GetDescription(force=True), 'y')
170 self.assertEquals(cl.GetDescription(), 'y')
171
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700172 def test_description_footers(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000173 cl = git_cl.Changelist(issue=1, codereview_host='host')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700174 cl.description = '\n'.join([
175 'This is some message',
176 '',
177 'It has some lines',
178 'and, also',
179 '',
180 'Some: Really',
181 'Awesome: Footers',
182 ])
183 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000184 cl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700185 msg, footers = cl.GetDescriptionFooters()
186 self.assertEquals(
187 msg, ['This is some message', '', 'It has some lines', 'and, also'])
188 self.assertEquals(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
189
190 msg.append('wut')
191 footers.append(('gnarly-dude', 'beans'))
192 cl.UpdateDescriptionFooters(msg, footers)
193 self.assertEquals(cl.GetDescription().splitlines(), [
194 'This is some message',
195 '',
196 'It has some lines',
197 'and, also',
198 'wut'
199 '',
200 'Some: Really',
201 'Awesome: Footers',
202 'Gnarly-Dude: beans',
203 ])
204
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000205 def test_set_preserve_tryjobs(self):
206 d = git_cl.ChangeDescription('Simple.')
207 d.set_preserve_tryjobs()
208 self.assertEqual(d.description.splitlines(), [
209 'Simple.',
210 '',
211 'Cq-Do-Not-Cancel-Tryjobs: true',
212 ])
213 before = d.description
214 d.set_preserve_tryjobs()
215 self.assertEqual(before, d.description)
216
217 d = git_cl.ChangeDescription('\n'.join([
218 'One is enough',
219 '',
220 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
221 'Change-Id: Ideadbeef',
222 ]))
223 d.set_preserve_tryjobs()
224 self.assertEqual(d.description.splitlines(), [
225 'One is enough',
226 '',
227 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
228 'Change-Id: Ideadbeef',
229 'Cq-Do-Not-Cancel-Tryjobs: true',
230 ])
231
tandriif9aefb72016-07-01 09:06:51 -0700232 def test_get_bug_line_values(self):
233 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
234 self.assertEqual(f('', ''), [])
235 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
236 self.assertEqual(f('v8', '456'), ['v8:456'])
237 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
238 # Not nice, but not worth carying.
239 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
240 ['v8:456', 'chromium:123', 'v8:123'])
241
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100242 def _test_git_number(self, parent_msg, dest_ref, child_msg,
243 parent_hash='parenthash'):
244 desc = git_cl.ChangeDescription(child_msg)
245 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
246 return desc.description
247
248 def assertEqualByLine(self, actual, expected):
249 self.assertEqual(actual.splitlines(), expected.splitlines())
250
251 def test_git_number_bad_parent(self):
252 with self.assertRaises(ValueError):
253 self._test_git_number('Parent', 'refs/heads/master', 'Child')
254
255 def test_git_number_bad_parent_footer(self):
256 with self.assertRaises(AssertionError):
257 self._test_git_number(
258 'Parent\n'
259 '\n'
260 'Cr-Commit-Position: wrong',
261 'refs/heads/master', 'Child')
262
263 def test_git_number_bad_lineage_ignored(self):
264 actual = self._test_git_number(
265 'Parent\n'
266 '\n'
267 'Cr-Commit-Position: refs/heads/master@{#1}\n'
268 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
269 'refs/heads/master', 'Child')
270 self.assertEqualByLine(
271 actual,
272 'Child\n'
273 '\n'
274 'Cr-Commit-Position: refs/heads/master@{#2}\n'
275 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
276
277 def test_git_number_same_branch(self):
278 actual = self._test_git_number(
279 'Parent\n'
280 '\n'
281 'Cr-Commit-Position: refs/heads/master@{#12}',
282 dest_ref='refs/heads/master',
283 child_msg='Child')
284 self.assertEqualByLine(
285 actual,
286 'Child\n'
287 '\n'
288 'Cr-Commit-Position: refs/heads/master@{#13}')
289
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200290 def test_git_number_same_branch_mixed_footers(self):
291 actual = self._test_git_number(
292 'Parent\n'
293 '\n'
294 'Cr-Commit-Position: refs/heads/master@{#12}',
295 dest_ref='refs/heads/master',
296 child_msg='Child\n'
297 '\n'
298 'Broken-by: design\n'
299 'BUG=123')
300 self.assertEqualByLine(
301 actual,
302 'Child\n'
303 '\n'
304 'Broken-by: design\n'
305 'BUG=123\n'
306 'Cr-Commit-Position: refs/heads/master@{#13}')
307
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100308 def test_git_number_same_branch_with_originals(self):
309 actual = self._test_git_number(
310 'Parent\n'
311 '\n'
312 'Cr-Commit-Position: refs/heads/master@{#12}',
313 dest_ref='refs/heads/master',
314 child_msg='Child\n'
315 '\n'
316 'Some users are smart and insert their own footers\n'
317 '\n'
318 'Cr-Whatever: value\n'
319 'Cr-Commit-Position: refs/copy/paste@{#22}')
320 self.assertEqualByLine(
321 actual,
322 'Child\n'
323 '\n'
324 'Some users are smart and insert their own footers\n'
325 '\n'
326 'Cr-Original-Whatever: value\n'
327 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
328 'Cr-Commit-Position: refs/heads/master@{#13}')
329
330 def test_git_number_new_branch(self):
331 actual = self._test_git_number(
332 'Parent\n'
333 '\n'
334 'Cr-Commit-Position: refs/heads/master@{#12}',
335 dest_ref='refs/heads/branch',
336 child_msg='Child')
337 self.assertEqualByLine(
338 actual,
339 'Child\n'
340 '\n'
341 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
342 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
343
344 def test_git_number_lineage(self):
345 actual = self._test_git_number(
346 'Parent\n'
347 '\n'
348 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
349 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
350 dest_ref='refs/heads/branch',
351 child_msg='Child')
352 self.assertEqualByLine(
353 actual,
354 'Child\n'
355 '\n'
356 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
357 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
358
359 def test_git_number_moooooooore_lineage(self):
360 actual = self._test_git_number(
361 'Parent\n'
362 '\n'
363 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
364 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
365 dest_ref='refs/heads/mooore',
366 child_msg='Child')
367 self.assertEqualByLine(
368 actual,
369 'Child\n'
370 '\n'
371 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
372 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
373 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
374
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100375 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700376 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100377 actual = self._test_git_number(
378 'CQ commit on fresh new branch + numbering.\n'
379 '\n'
380 'NOTRY=True\n'
381 'NOPRESUBMIT=True\n'
382 'BUG=\n'
383 '\n'
384 'Review-Url: https://codereview.chromium.org/2577703003\n'
385 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
386 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
387 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
388 dest_ref='refs/heads/gnumb-test/cl',
389 child_msg='git cl on fresh new branch + numbering.\n'
390 '\n'
391 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
392 self.assertEqualByLine(
393 actual,
394 'git cl on fresh new branch + numbering.\n'
395 '\n'
396 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
397 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
398 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
399 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
400 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100401
402 def test_git_number_cherry_pick(self):
403 actual = self._test_git_number(
404 'Parent\n'
405 '\n'
406 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
407 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
408 dest_ref='refs/heads/branch',
409 child_msg='Child, which is cherry-pick from master\n'
410 '\n'
411 'Cr-Commit-Position: refs/heads/master@{#100}\n'
412 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
413 self.assertEqualByLine(
414 actual,
415 'Child, which is cherry-pick from master\n'
416 '\n'
417 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
418 '\n'
419 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
420 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
421 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
422
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000423 def test_gerrit_mirror_hack(self):
424 cr = 'chromium-review.googlesource.com'
425 url0 = 'https://%s/a/changes/x?a=b' % cr
426 origMirrors = git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES
427 try:
428 git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = ['us1', 'us2']
429 url1 = git_cl.gerrit_util._UseGerritMirror(url0, cr)
430 url2 = git_cl.gerrit_util._UseGerritMirror(url1, cr)
431 url3 = git_cl.gerrit_util._UseGerritMirror(url2, cr)
432
433 self.assertNotEqual(url1, url2)
434 self.assertEqual(sorted((url1, url2)), [
435 'https://us1-mirror-chromium-review.googlesource.com/a/changes/x?a=b',
436 'https://us2-mirror-chromium-review.googlesource.com/a/changes/x?a=b'])
437 self.assertEqual(url1, url3)
438 finally:
439 git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = origMirrors
440
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000441 def test_valid_accounts(self):
442 mock_per_account = {
443 'u1': None, # 404, doesn't exist.
444 'u2': {
445 '_account_id': 123124,
446 'avatars': [],
447 'email': 'u2@example.com',
448 'name': 'User Number 2',
449 'status': 'OOO',
450 },
451 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
452 }
453 def GetAccountDetailsMock(_, account):
454 # Poor-man's mock library's side_effect.
455 v = mock_per_account.pop(account)
456 if isinstance(v, Exception):
457 raise v
458 return v
459
460 original = git_cl.gerrit_util.GetAccountDetails
461 try:
462 git_cl.gerrit_util.GetAccountDetails = GetAccountDetailsMock
463 actual = git_cl.gerrit_util.ValidAccounts(
464 'host', ['u1', 'u2', 'u3'], max_threads=1)
465 finally:
466 git_cl.gerrit_util.GetAccountDetails = original
467 self.assertEqual(actual, {
468 'u2': {
469 '_account_id': 123124,
470 'avatars': [],
471 'email': 'u2@example.com',
472 'name': 'User Number 2',
473 'status': 'OOO',
474 },
475 })
476
477
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200478class TestParseIssueURL(unittest.TestCase):
479 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000480 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200481 self.assertIsNotNone(parsed)
482 if fail:
483 self.assertFalse(parsed.valid)
484 return
485 self.assertTrue(parsed.valid)
486 self.assertEqual(parsed.issue, issue)
487 self.assertEqual(parsed.patchset, patchset)
488 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200489
Edward Lemur678a6842019-10-03 22:25:05 +0000490 def test_ParseIssueNumberArgument(self):
491 def test(arg, *args, **kwargs):
492 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200493
Edward Lemur678a6842019-10-03 22:25:05 +0000494 test('123', 123)
495 test('', fail=True)
496 test('abc', fail=True)
497 test('123/1', fail=True)
498 test('123a', fail=True)
499 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200500
Edward Lemur678a6842019-10-03 22:25:05 +0000501 test('https://codereview.source.com/123',
502 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200503 test('http://chrome-review.source.com/c/123',
504 123, None, 'chrome-review.source.com')
505 test('https://chrome-review.source.com/c/123/',
506 123, None, 'chrome-review.source.com')
507 test('https://chrome-review.source.com/c/123/4',
508 123, 4, 'chrome-review.source.com')
509 test('https://chrome-review.source.com/#/c/123/4',
510 123, 4, 'chrome-review.source.com')
511 test('https://chrome-review.source.com/c/123/4',
512 123, 4, 'chrome-review.source.com')
513 test('https://chrome-review.source.com/123',
514 123, None, 'chrome-review.source.com')
515 test('https://chrome-review.source.com/123/4',
516 123, 4, 'chrome-review.source.com')
517
Edward Lemur678a6842019-10-03 22:25:05 +0000518 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200519 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
520 test('https://chrome-review.source.com/c/abc/', fail=True)
521 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
522
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200523
524
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100525class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100526 def setUp(self):
527 super(GitCookiesCheckerTest, self).setUp()
528 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100529 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100530
531 def mock_hosts_creds(self, subhost_identity_pairs):
532 def ensure_googlesource(h):
533 if not h.endswith(self.c._GOOGLESOURCE):
534 assert not h.endswith('.')
535 return h + '.' + self.c._GOOGLESOURCE
536 return h
537 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
538 for h, i in subhost_identity_pairs]
539
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200540 def test_identity_parsing(self):
541 self.assertEqual(self.c._parse_identity('ldap.google.com'),
542 ('ldap', 'google.com'))
543 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
544 ('ldap', 'example.com'))
545 # Specical case because we know there are no subdomains in chromium.org.
546 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
547 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800548 # Pathological: ".period." can be either username OR domain, more likely
549 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200550 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
551 ('note', 'period.example.com'))
552
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100553 def test_analysis_nothing(self):
554 self.c._all_hosts = []
555 self.assertFalse(self.c.has_generic_host())
556 self.assertEqual(set(), self.c.get_conflicting_hosts())
557 self.assertEqual(set(), self.c.get_duplicated_hosts())
558 self.assertEqual(set(), self.c.get_partially_configured_hosts())
559 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
560
561 def test_analysis(self):
562 self.mock_hosts_creds([
563 ('.googlesource.com', 'git-example.chromium.org'),
564
565 ('chromium', 'git-example.google.com'),
566 ('chromium-review', 'git-example.google.com'),
567 ('chrome-internal', 'git-example.chromium.org'),
568 ('chrome-internal-review', 'git-example.chromium.org'),
569 ('conflict', 'git-example.google.com'),
570 ('conflict-review', 'git-example.chromium.org'),
571 ('dup', 'git-example.google.com'),
572 ('dup', 'git-example.google.com'),
573 ('dup-review', 'git-example.google.com'),
574 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200575 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100576 ])
577 self.assertTrue(self.c.has_generic_host())
578 self.assertEqual(set(['conflict.googlesource.com']),
579 self.c.get_conflicting_hosts())
580 self.assertEqual(set(['dup.googlesource.com']),
581 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200582 self.assertEqual(set(['partial.googlesource.com',
583 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100584 self.c.get_partially_configured_hosts())
585 self.assertEqual(set(['chromium.googlesource.com',
586 'chrome-internal.googlesource.com']),
587 self.c.get_hosts_with_wrong_identities())
588
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100589 def test_report_no_problems(self):
590 self.test_analysis_nothing()
591 self.mock(sys, 'stdout', StringIO.StringIO())
592 self.assertFalse(self.c.find_and_report_problems())
593 self.assertEqual(sys.stdout.getvalue(), '')
594
595 def test_report(self):
596 self.test_analysis()
597 self.mock(sys, 'stdout', StringIO.StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200598 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
599 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100600 self.assertTrue(self.c.find_and_report_problems())
601 with open(os.path.join(os.path.dirname(__file__),
602 'git_cl_creds_check_report.txt')) as f:
603 expected = f.read()
604 def by_line(text):
605 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700606 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200607 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100608
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800609
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000610class TestGitCl(TestCase):
611 def setUp(self):
612 super(TestGitCl, self).setUp()
613 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700614 self._calls_done = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000615 self.mock(git_cl, 'time_time',
616 lambda: self._mocked_call('time.time'))
617 self.mock(git_cl.metrics.collector, 'add_repeated',
618 lambda *a: self._mocked_call('add_repeated', *a))
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000619 self.mock(subprocess2, 'call', self._mocked_call)
620 self.mock(subprocess2, 'check_call', self._mocked_call)
621 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700622 self.mock(subprocess2, 'communicate',
623 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000624 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000625 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000626 self.mock(git_common, 'get_or_create_merge_base',
627 lambda *a: (
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000628 self._mocked_call(['get_or_create_merge_base'] + list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000629 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000630 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000631 self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
632 self._mocked_call('SaveDescriptionBackup'))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100633 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000634 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700635 self.mock(git_cl, 'write_json', lambda path, contents:
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000636 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000637 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000638 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
Edward Lemurb4a587d2019-10-09 23:56:38 +0000639 self.mock(git_cl.auth, 'get_authenticator', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100640 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
641 lambda *args, **kwargs: self._mocked_call(
642 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700643 self.mock(git_cl.gerrit_util, 'GetChangeComments',
644 lambda *args, **kwargs: self._mocked_call(
645 'GetChangeComments', *args, **kwargs))
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000646 self.mock(git_cl.gerrit_util, 'GetChangeRobotComments',
647 lambda *args, **kwargs: self._mocked_call(
648 'GetChangeRobotComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100649 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700650 lambda h, i, reviewers, ccs, notify: self._mocked_call(
651 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700652 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700653 lambda h, i, msg=None, labels=None, notify=None:
654 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700655 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
656 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000657 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
658 classmethod(lambda _: False))
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000659 self.mock(git_cl.gerrit_util, 'ValidAccounts',
660 lambda host, accounts:
661 self._mocked_call('ValidAccounts', host, accounts))
tandriic2405f52016-10-10 08:13:15 -0700662 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100663 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000664 # It's important to reset settings to not have inter-tests interference.
665 git_cl.settings = None
666
667 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000668 try:
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100669 self.assertEquals([], self.calls)
670 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000671 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100672 raise
673 # Sadly, has_failed() returns True if this OR any other tests before this
674 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200675 git_cl.logging.error(
676 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100677 'There are un-consumed self.calls after this test has finished.\n'
678 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700679 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200680 'If you are already running only this test, then **first** fix the '
681 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100682 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700683 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100684 'and follow instructions above.\n' +
685 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000686 finally:
687 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000688
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000689 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000690 self.assertTrue(
691 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700692 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000693 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000694 expected_args, result = top
695
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000696 # Also logs otherwise it could get caught in a try/finally and be hard to
697 # diagnose.
698 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700699 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000700 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700701 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
702 for i, c in enumerate(self._calls_done[-N:]))
703 following_calls = '\n '.join(
704 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
705 for i, c in enumerate(self.calls[:N]))
706 extended_msg = (
707 'A few prior calls:\n %s\n\n'
708 'This (expected):\n @%d: %r\n'
709 'This (actual):\n @%d: %r\n\n'
710 'A few following expected calls:\n %s' %
711 (prior_calls, len(self._calls_done), expected_args,
712 len(self._calls_done), args, following_calls))
713 git_cl.logging.error(extended_msg)
714
tandrii99a72f22016-08-17 14:33:24 -0700715 self.fail('@%d\n'
716 ' Expected: %r\n'
717 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700718 len(self._calls_done), expected_args, args))
719
720 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700721 if isinstance(result, Exception):
722 raise result
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000723 return result
724
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100725 def test_ask_for_explicit_yes_true(self):
726 self.calls = [
727 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
728 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
729 ]
730 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
731
tandrii48df5812016-10-17 03:55:37 -0700732 def test_LoadCodereviewSettingsFromFile_gerrit(self):
733 codereview_file = StringIO.StringIO('GERRIT_HOST: true')
734 self.calls = [
735 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700736 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
737 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
738 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
739 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700740 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
741 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700742 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
743 CERR1),
744 ((['git', 'config', 'gerrit.host', 'true'],), ''),
745 ]
746 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
747
maruel@chromium.orga3353652011-11-30 14:26:57 +0000748 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000749 def _is_gerrit_calls(cls, gerrit=False):
750 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
751 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
752
753 @classmethod
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000754 def _git_post_upload_calls(cls):
755 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000756 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
757 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
758 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000759 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000760 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000761 ]
762
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000763 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000764 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000765 fake_ancestor = 'fake_ancestor'
766 fake_cl = 'fake_cl_for_patch'
767 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000768 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000769 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000770 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000771 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000772 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000773 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000774 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000775 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700776 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000777 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000778 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000779 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000780 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000781 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000782 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000783 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000784 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000785 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000786 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000787 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000788
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000789 @classmethod
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000790 def _gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000791 cls, issue=None, skip_auth_check=False, short_hostname='chromium',
792 custom_cl_base=None):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000793 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000794 if skip_auth_check:
795 return [((cmd, ), 'true')]
796
tandrii5d48c322016-08-18 16:19:37 -0700797 calls = [((cmd, ), CERR1)]
Edward Lemurf38bc172019-09-03 21:02:13 +0000798
799 if custom_cl_base:
800 calls += [
801 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
802 ]
803
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000804 calls.extend([
805 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
806 ((['git', 'config', 'branch.master.remote'],), 'origin'),
807 ((['git', 'config', 'remote.origin.url'],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000808 'https://%s.googlesource.com/my/repo' % short_hostname),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000809 ])
Edward Lemurf38bc172019-09-03 21:02:13 +0000810
811 calls += [
812 ((['git', 'config', 'branch.master.gerritissue'],),
813 CERR1 if issue is None else str(issue)),
814 ]
815
Daniel Chengcf6269b2019-05-18 01:02:12 +0000816 if issue:
817 calls.extend([
818 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
819 ])
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000820 return calls
821
822 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100823 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200824 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000825 custom_cl_base=None, short_hostname='chromium',
826 change_id=None):
Aaron Gable13101a62018-02-09 13:20:41 -0800827 calls = cls._is_gerrit_calls(True)
Edward Lemurf38bc172019-09-03 21:02:13 +0000828 if not custom_cl_base:
829 calls += [
830 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
831 ]
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200832
833 if custom_cl_base:
834 ancestor_revision = custom_cl_base
835 else:
836 # Determine ancestor_revision to be merge base.
837 ancestor_revision = 'fake_ancestor_sha'
838 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000839 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000840 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000841 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200842 'refs/remotes/origin/master'],), ancestor_revision),
843 ]
844
845 # Calls to verify branch point is ancestor
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000846 calls += cls._gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000847 issue=issue, short_hostname=short_hostname,
848 custom_cl_base=custom_cl_base)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100849
850 if issue:
851 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000852 (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +0000853 'my%2Frepo~123456',
Andrii Shyshkalovc4a73562018-09-25 18:40:17 +0000854 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
855 ),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100856 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100857 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Anthony Polito8b955342019-09-24 19:01:36 +0000858 'change_id': (change_id or '123456789'),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100859 'current_revision': 'sha1_of_current_revision',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000860 'revisions': {'sha1_of_current_revision': {
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100861 'commit': {'message': fetched_description},
862 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100863 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100864 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100865 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100866 if fetched_status == 'ABANDONED':
867 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000868 (('DieWithError', 'Change https://%s-review.googlesource.com/'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100869 '123456 has been abandoned, new uploads are not '
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000870 'allowed' % short_hostname), SystemExitMock()),
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100871 ]
872 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100873 if other_cl_owner:
874 calls += [
875 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
876 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100877
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200878 calls += cls._git_sanity_checks(ancestor_revision, 'master',
879 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100880 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200881 ((['git', 'rev-parse', '--show-cdup'],), ''),
882 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000883
Aaron Gable7817f022017-12-12 09:43:17 -0800884 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
885 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200886 'M\t.gitignore\n'),
887 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100888 ]
889
890 if not issue:
891 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200892 ((['git', 'log', '--pretty=format:%s%n%n%b',
893 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000894 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100895 ]
896
897 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200898 ((['git', 'config', 'user.email'],), 'me@example.com'),
Edward Lemur2c48f242019-06-04 16:14:09 +0000899 (('time.time',), 1000,),
900 (('time.time',), 3000,),
901 (('add_repeated', 'sub_commands', {
902 'execution_time': 2000,
903 'command': 'presubmit',
904 'exit_code': 0
905 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200906 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
907 ([custom_cl_base] if custom_cl_base else
908 [ancestor_revision, 'HEAD']),),
909 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100910 ]
911 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000912
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000913 @classmethod
914 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700915 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000916 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700917 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100918 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000919 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000920 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000921 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000922 final_description=None, gitcookies_exists=True,
923 force=False):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000924 if post_amend_description is None:
925 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700926 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200927 # Determined in `_gerrit_base_calls`.
928 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
929
930 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000931
tandriia60502f2016-06-20 02:01:53 -0700932 if squash_mode == 'default':
933 calls.extend([
934 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
935 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
936 ])
937 elif squash_mode in ('override_squash', 'override_nosquash'):
938 calls.extend([
939 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
940 'true' if squash_mode == 'override_squash' else 'false'),
941 ])
942 else:
943 assert squash_mode in ('squash', 'nosquash')
944
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000945 # If issue is given, then description is fetched from Gerrit instead.
946 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000947 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200948 ((['git', 'log', '--pretty=format:%s\n\n%b',
949 ((custom_cl_base + '..') if custom_cl_base else
950 'fake_ancestor_sha..HEAD')],),
951 description),
952 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800953 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000954 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800955 else:
956 if not title:
957 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200958 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
959 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800960 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000961 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000962 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000963 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200964 (('DownloadGerritHook', False), ''),
965 # Amending of commit message to get the Change-Id.
966 ((['git', 'log', '--pretty=format:%s\n\n%b',
967 determined_ancestor_revision + '..HEAD'],),
968 description),
969 ((['git', 'commit', '--amend', '-m', description],), ''),
970 ((['git', 'log', '--pretty=format:%s\n\n%b',
971 determined_ancestor_revision + '..HEAD'],),
972 post_amend_description)
973 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000974 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000975 if force or not issue:
976 if issue:
977 calls += [
978 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
979 ]
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000980 # Prompting to edit description on first upload.
981 calls += [
Jonas Termansend0f79112019-03-22 15:28:26 +0000982 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000983 ]
Anthony Polito8b955342019-09-24 19:01:36 +0000984 if not force:
985 calls += [
986 ((['git', 'config', 'core.editor'],), ''),
987 ((['RunEditor'],), description),
988 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000989 ref_to_push = 'abcdef0123456789'
990 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200991 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
992 ((['git', 'config', 'branch.master.remote'],), 'origin'),
993 ]
994
995 if custom_cl_base is None:
996 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000997 ((['get_or_create_merge_base', 'master',
998 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000999 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001000 ]
1001 parent = 'origin/master'
1002 else:
1003 calls += [
1004 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
1005 'refs/remotes/origin/master'],),
1006 callError(1)), # Means not ancenstor.
1007 (('ask_for_data',
1008 'Do you take responsibility for cleaning up potential mess '
1009 'resulting from proceeding with upload? Press Enter to upload, '
1010 'or Ctrl+C to abort'), ''),
1011 ]
1012 parent = custom_cl_base
1013
1014 calls += [
1015 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
1016 '0123456789abcdef'),
1017 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -07001018 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001019 ref_to_push),
1020 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001021 else:
1022 ref_to_push = 'HEAD'
1023
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001024 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00001025 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001026 ((['git', 'rev-list',
1027 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1028 ref_to_push],),
1029 '1hashPerLine\n'),
1030 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001031
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001032 metrics_arguments = []
1033
Aaron Gableafd52772017-06-27 16:40:10 -07001034 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001035 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001036 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -07001037 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001038 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001039 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001040 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -07001041 else:
1042 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001043 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -08001044
Aaron Gable70f4e242017-06-26 10:45:59 -07001045 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001046 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001047 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001048
Edward Lemur4508b422019-10-03 21:56:35 +00001049 if issue is None:
1050 calls += [
1051 ((['git', 'config', 'rietveld.cc'],), ''),
1052 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001053 if short_hostname == 'chromium':
1054 # All reviwers and ccs get into ref_suffix.
1055 for r in sorted(reviewers):
1056 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001057 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +00001058 if issue is None:
1059 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
1060 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001061 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001062 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001063 reviewers, cc = [], []
1064 else:
1065 # TODO(crbug/877717): remove this case.
1066 calls += [
1067 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
1068 sorted(reviewers) + ['joe@example.com',
1069 'chromium-reviews+test-more-cc@chromium.org'] + cc),
1070 {
1071 e: {'email': e}
1072 for e in (reviewers + ['joe@example.com'] + cc)
1073 })
1074 ]
1075 for r in sorted(reviewers):
1076 if r != 'bad-account-or-email':
1077 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001078 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001079 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +00001080 if issue is None:
1081 cc += ['joe@example.com']
1082 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001083 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001084 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001085 if c in cc:
1086 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001087
Edward Lemur687ca902018-12-05 02:30:30 +00001088 for k, v in sorted((labels or {}).items()):
1089 ref_suffix += ',l=%s+%d' % (k, v)
1090 metrics_arguments.append('l=%s+%d' % (k, v))
1091
1092 if tbr:
1093 calls += [
1094 (('GetCodeReviewTbrScore',
1095 '%s-review.googlesource.com' % short_hostname,
1096 'my/repo'),
1097 2,),
1098 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001099
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001100 calls += [
1101 (('time.time',), 1000,),
1102 ((['git', 'push',
1103 'https://%s.googlesource.com/my/repo' % short_hostname,
1104 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1105 (('remote:\n'
1106 'remote: Processing changes: (\)\n'
1107 'remote: Processing changes: (|)\n'
1108 'remote: Processing changes: (/)\n'
1109 'remote: Processing changes: (-)\n'
1110 'remote: Processing changes: new: 1 (/)\n'
1111 'remote: Processing changes: new: 1, done\n'
1112 'remote:\n'
1113 'remote: New Changes:\n'
1114 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1115 ' XXX\n'
1116 'remote:\n'
1117 'To https://%s.googlesource.com/my/repo\n'
1118 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1119 ) % (short_hostname, short_hostname)),),
1120 (('time.time',), 2000,),
1121 (('add_repeated',
1122 'sub_commands',
1123 {
1124 'execution_time': 1000,
1125 'command': 'git push',
1126 'exit_code': 0,
1127 'arguments': sorted(metrics_arguments),
1128 }),
1129 None,),
1130 ]
1131
Edward Lemur1b52d872019-05-09 21:12:12 +00001132 final_description = final_description or post_amend_description.strip()
1133 original_title = original_title or title or '<untitled>'
1134 # Trace-related calls
1135 calls += [
1136 # Write a description with context for the current trace.
1137 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001138 'Thu Mar 16 20:00:41 2017\n'
1139 '%(short_hostname)s-review.googlesource.com\n'
1140 '%(change_id)s\n'
1141 '%(title)s\n'
1142 '%(description)s\n'
1143 '1000\n'
1144 '0\n'
1145 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001146 'short_hostname': short_hostname,
1147 'change_id': change_id,
1148 'description': final_description,
1149 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001150 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001151 }],),
1152 None,
1153 ),
1154 # Read traces and shorten git hashes.
1155 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1156 True,
1157 ),
1158 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1159 ('git-hash: 0123456789012345678901234567890123456789\n'
1160 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1161 ),
1162 ((['FileWrite', 'TEMP_DIR/trace-packet',
1163 'git-hash: 012345\n'
1164 'git-hash: abcdea\n'],),
1165 None,
1166 ),
1167 # Make zip file for the git traces.
1168 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1169 'TEMP_DIR'],),
1170 None,
1171 ),
1172 # Collect git config and gitcookies.
1173 ((['git', 'config', '-l'],),
1174 'git-config-output',
1175 ),
1176 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1177 None,
1178 ),
1179 ((['os.path.isfile', '~/.gitcookies'],),
1180 gitcookies_exists,
1181 ),
1182 ]
1183 if gitcookies_exists:
1184 calls += [
1185 ((['FileRead', '~/.gitcookies'],),
1186 'gitcookies 1/SECRET',
1187 ),
1188 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1189 None,
1190 ),
1191 ]
1192 calls += [
1193 # Make zip file for the git config and gitcookies.
1194 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1195 'TEMP_DIR'],),
1196 None,
1197 ),
1198 ]
1199
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001200 if squash:
1201 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001202 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001203 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001204 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001205 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001206 ((['git', 'config', 'branch.master.gerritsquashhash',
1207 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001208 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001209 # TODO(crbug/877717): this should never be used.
1210 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001211 calls += [
1212 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001213 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001214 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001215 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1216 notify),
1217 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001218 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001219 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001220 return calls
1221
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001222 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001223 self,
1224 upload_args,
1225 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001226 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001227 squash=True,
1228 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001229 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001230 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001231 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001232 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001233 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001234 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001235 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001236 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001237 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001238 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001239 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001240 labels=None,
1241 change_id=None,
1242 original_title=None,
1243 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001244 gitcookies_exists=True,
1245 force=False,
1246 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001247 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001248 if squash_mode is None:
1249 if '--no-squash' in upload_args:
1250 squash_mode = 'nosquash'
1251 elif '--squash' in upload_args:
1252 squash_mode = 'squash'
1253 else:
1254 squash_mode = 'default'
1255
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001256 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001257 cc = cc or []
tandrii@chromium.org28253532016-04-14 13:46:56 +00001258 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001259 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001260 CookiesAuthenticatorMockFactory(
1261 same_auth=('git-owner.example.com', '', 'pass')))
Edward Lemur125d60a2019-09-13 18:25:41 +00001262 self.mock(git_cl.Changelist, '_GerritCommitMsgHookCheck',
tandrii16e0b4e2016-06-07 10:34:28 -07001263 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001264 self.mock(git_cl.gclient_utils, 'RunEditor',
1265 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001266 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1267 'DownloadGerritHook', force))
Edward Lemur1b52d872019-05-09 21:12:12 +00001268 self.mock(git_cl.gclient_utils, 'FileRead',
1269 lambda path: self._mocked_call(['FileRead', path]))
1270 self.mock(git_cl.gclient_utils, 'FileWrite',
1271 lambda path, contents: self._mocked_call(
1272 ['FileWrite', path, contents]))
1273 self.mock(git_cl, 'datetime_now',
1274 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0))
1275 self.mock(git_cl.tempfile, 'mkdtemp', lambda: 'TEMP_DIR')
1276 self.mock(git_cl, 'TRACES_DIR', 'TRACES_DIR')
Edward Lemur75391d42019-05-14 23:35:56 +00001277 self.mock(git_cl, 'TRACES_README_FORMAT',
1278 '%(now)s\n'
1279 '%(gerrit_host)s\n'
1280 '%(change_id)s\n'
1281 '%(title)s\n'
1282 '%(description)s\n'
1283 '%(execution_time)s\n'
1284 '%(exit_code)s\n'
1285 '%(trace_name)s')
Edward Lemur1b52d872019-05-09 21:12:12 +00001286 self.mock(git_cl.shutil, 'make_archive',
1287 lambda *args: self._mocked_call(['make_archive'] + list(args)))
1288 self.mock(os.path, 'isfile',
1289 lambda path: self._mocked_call(['os.path.isfile', path]))
tandriia60502f2016-06-20 02:01:53 -07001290
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001291 self.calls = self._gerrit_base_calls(
1292 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001293 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001294 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001295 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001296 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001297 short_hostname=short_hostname,
1298 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001299 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001300 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
1301 expected_content=description))
1302 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001303 self.calls += self._gerrit_upload_calls(
1304 description, reviewers, squash,
1305 squash_mode=squash_mode,
1306 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001307 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001308 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001309 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001310 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001311 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001312 labels=labels,
1313 change_id=change_id,
1314 original_title=original_title,
1315 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001316 gitcookies_exists=gitcookies_exists,
1317 force=force)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001318 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001319 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001320 git_cl.main(['upload'] + upload_args)
1321
Edward Lemur1b52d872019-05-09 21:12:12 +00001322 def test_gerrit_upload_traces_no_gitcookies(self):
1323 self._run_gerrit_upload_test(
1324 ['--no-squash'],
1325 'desc\n\nBUG=\n',
1326 [],
1327 squash=False,
1328 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1329 change_id='Ixxx',
1330 gitcookies_exists=False)
1331
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001332 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001333 self._run_gerrit_upload_test(
1334 ['--no-squash'],
1335 'desc\n\nBUG=\n',
1336 [],
1337 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001338 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1339 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001340
1341 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001342 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001343 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +00001344 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001345 [],
tandriia60502f2016-06-20 02:01:53 -07001346 squash=False,
1347 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001348 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1349 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001350
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001351 def test_gerrit_no_reviewer(self):
1352 self._run_gerrit_upload_test(
1353 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001354 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001355 [],
1356 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001357 squash_mode='override_nosquash',
1358 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001359
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001360 def test_gerrit_no_reviewer_non_chromium_host(self):
1361 # TODO(crbug/877717): remove this test case.
1362 self._run_gerrit_upload_test(
1363 [],
1364 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
1365 [],
1366 squash=False,
1367 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001368 short_hostname='other',
1369 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001370
Nick Carter8692b182017-11-06 16:30:38 -08001371 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001372 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1373 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001374 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001375 'desc\n\nBUG=\n\nChange-Id: I123456789',
1376 squash=False,
1377 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001378 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1379 change_id='I123456789',
1380 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001381
ukai@chromium.orge8077812012-02-03 03:41:46 +00001382 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001383 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001384 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001385 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001386 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001387 squash=False,
1388 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001389 notify=True,
1390 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001391 final_description=(
1392 'desc\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001393
Anthony Polito8b955342019-09-24 19:01:36 +00001394 def test_gerrit_upload_force_sets_bug(self):
1395 self._run_gerrit_upload_test(
1396 ['-b', '10000', '-f'],
1397 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1398 [],
1399 force=True,
1400 expected_upstream_ref='origin/master',
1401 fetched_description='desc=\n\nChange-Id: Ixxx',
1402 original_title='Initial upload',
1403 change_id='Ixxx')
1404
1405 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1406 self._run_gerrit_upload_test(
1407 ['-b', '10000', '-f', '-m', 'Title'],
1408 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1409 [],
1410 force=True,
1411 issue='123456',
1412 expected_upstream_ref='origin/master',
1413 fetched_description='desc=\n\nChange-Id: Ixxxx',
1414 original_title='Title',
1415 title='Title',
1416 change_id='Izzzz')
1417
Dan Beamd8b04ca2019-10-10 21:23:26 +00001418 def test_gerrit_upload_force_sets_fixed(self):
1419 self._run_gerrit_upload_test(
1420 ['-x', '10000', '-f'],
1421 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1422 [],
1423 force=True,
1424 expected_upstream_ref='origin/master',
1425 fetched_description='desc=\n\nChange-Id: Ixxx',
1426 original_title='Initial upload',
1427 change_id='Ixxx')
1428
ukai@chromium.orge8077812012-02-03 03:41:46 +00001429 def test_gerrit_reviewer_multiple(self):
Edward Lemur687ca902018-12-05 02:30:30 +00001430 self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
1431 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001432 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001433 [],
bradnelsond975b302016-10-23 12:20:23 -07001434 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1435 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001436 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001437 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001438 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001439 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001440 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001441 labels={'Code-Review': 2},
1442 change_id='123456789',
1443 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001444
1445 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001446 self._run_gerrit_upload_test(
1447 [],
1448 'desc\nBUG=\n\nChange-Id: 123456789',
1449 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001450 expected_upstream_ref='origin/master',
1451 change_id='123456789',
1452 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001453
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001454 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001455 self._run_gerrit_upload_test(
1456 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001457 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001458 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001459 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001460 expected_upstream_ref='origin/master',
1461 change_id='123456789',
1462 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001463
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001464 def test_gerrit_upload_squash_first_with_labels(self):
1465 self._run_gerrit_upload_test(
1466 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
1467 'desc\nBUG=\n\nChange-Id: 123456789',
1468 [],
1469 squash=True,
1470 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001471 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1472 change_id='123456789',
1473 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001474
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001475 def test_gerrit_upload_squash_first_against_rev(self):
1476 custom_cl_base = 'custom_cl_base_rev_or_branch'
1477 self._run_gerrit_upload_test(
1478 ['--squash', custom_cl_base],
1479 'desc\nBUG=\n\nChange-Id: 123456789',
1480 [],
1481 squash=True,
1482 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001483 custom_cl_base=custom_cl_base,
1484 change_id='123456789',
1485 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001486 self.assertIn(
1487 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1488 sys.stdout.getvalue())
1489
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001490 def test_gerrit_upload_squash_reupload(self):
1491 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001492 self._run_gerrit_upload_test(
1493 ['--squash'],
1494 description,
1495 [],
1496 squash=True,
1497 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001498 issue=123456,
1499 change_id='123456789',
1500 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001501
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001502 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1503 self.mock(git_cl, 'DieWithError',
1504 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1505 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1506 with self.assertRaises(SystemExitMock):
1507 self._run_gerrit_upload_test(
1508 ['--squash'],
1509 description,
1510 [],
1511 squash=True,
1512 expected_upstream_ref='origin/master',
1513 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001514 fetched_status='ABANDONED',
1515 change_id='123456789')
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001516
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001517 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1518 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1519 lambda *_, **__: {'email': 'yet-another@example.com'})
1520 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1521 self._run_gerrit_upload_test(
1522 ['--squash'],
1523 description,
1524 [],
1525 squash=True,
1526 expected_upstream_ref='origin/master',
1527 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001528 other_cl_owner='other@example.com',
1529 change_id='123456789',
1530 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001531 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001532 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001533 'authenticate to Gerrit as yet-another@example.com.\n'
1534 'Uploading may fail due to lack of permissions',
1535 git_cl.sys.stdout.getvalue())
1536
rmistry@google.com2dd99862015-06-22 12:22:18 +00001537 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001538 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001539 def mock_run_git(*args, **_kwargs):
1540 if args[0] == ['for-each-ref',
1541 '--format=%(refname:short) %(upstream:short)',
1542 'refs/heads']:
1543 # Create a local branch dependency tree that looks like this:
1544 # test1 -> test2 -> test3 -> test4 -> test5
1545 # -> test3.1
1546 # test6 -> test0
1547 branch_deps = [
1548 'test2 test1', # test1 -> test2
1549 'test3 test2', # test2 -> test3
1550 'test3.1 test2', # test2 -> test3.1
1551 'test4 test3', # test3 -> test4
1552 'test5 test4', # test4 -> test5
1553 'test6 test0', # test0 -> test6
1554 'test7', # test7
1555 ]
1556 return '\n'.join(branch_deps)
1557 self.mock(git_cl, 'RunGit', mock_run_git)
1558
1559 class RecordCalls:
1560 times_called = 0
1561 record_calls = RecordCalls()
1562 def mock_CMDupload(*args, **_kwargs):
1563 record_calls.times_called += 1
1564 return 0
1565 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1566
1567 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001568 (('ask_for_data', 'This command will checkout all dependent branches '
1569 'and run "git cl upload". Press Enter to continue, '
1570 'or Ctrl+C to abort'), ''),
1571 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001572
1573 class MockChangelist():
1574 def __init__(self):
1575 pass
1576 def GetBranch(self):
1577 return 'test1'
1578 def GetIssue(self):
1579 return '123'
1580 def GetPatchset(self):
1581 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001582 def IsGerrit(self):
1583 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001584
1585 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1586 # CMDupload should have been called 5 times because of 5 dependent branches.
1587 self.assertEquals(5, record_calls.times_called)
1588 self.assertEquals(0, ret)
1589
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001590 def test_gerrit_change_id(self):
1591 self.calls = [
1592 ((['git', 'write-tree'], ),
1593 'hashtree'),
1594 ((['git', 'rev-parse', 'HEAD~0'], ),
1595 'branch-parent'),
1596 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1597 'A B <a@b.org> 1456848326 +0100'),
1598 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1599 'C D <c@d.org> 1456858326 +0100'),
1600 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1601 'hashchange'),
1602 ]
1603 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1604 self.assertEqual(change_id, 'Ihashchange')
1605
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001606 def test_desecription_append_footer(self):
1607 for init_desc, footer_line, expected_desc in [
1608 # Use unique desc first lines for easy test failure identification.
1609 ('foo', 'R=one', 'foo\n\nR=one'),
1610 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1611 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1612 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1613 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1614 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1615 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1616 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1617 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1618 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1619 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1620 ]:
1621 desc = git_cl.ChangeDescription(init_desc)
1622 desc.append_footer(footer_line)
1623 self.assertEqual(desc.description, expected_desc)
1624
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001625 def test_update_reviewers(self):
1626 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001627 ('foo', [], [],
1628 'foo'),
1629 ('foo\nR=xx', [], [],
1630 'foo\nR=xx'),
1631 ('foo\nTBR=xx', [], [],
1632 'foo\nTBR=xx'),
1633 ('foo', ['a@c'], [],
1634 'foo\n\nR=a@c'),
1635 ('foo\nR=xx', ['a@c'], [],
1636 'foo\n\nR=a@c, xx'),
1637 ('foo\nTBR=xx', ['a@c'], [],
1638 'foo\n\nR=a@c\nTBR=xx'),
1639 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1640 'foo\n\nR=a@c, yy\nTBR=xx'),
1641 ('foo\nBUG=', ['a@c'], [],
1642 'foo\nBUG=\nR=a@c'),
1643 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1644 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1645 ('foo', ['a@c', 'b@c'], [],
1646 'foo\n\nR=a@c, b@c'),
1647 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1648 'foo\nBar\n\nR=c@c\nBUG='),
1649 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1650 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001651 # Same as the line before, but full of whitespaces.
1652 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001653 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001654 'foo\nBar\n\nR=c@c\n BUG =',
1655 ),
1656 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001657 ('foo BUG=allo R=joe ', ['c@c'], [],
1658 'foo BUG=allo R=joe\n\nR=c@c'),
1659 # Redundant TBRs get promoted to Rs
1660 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1661 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001662 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001663 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001664 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001665 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001666 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001667 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001668 actual.append(obj.description)
1669 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001670
Nodir Turakulov23b82142017-11-16 11:04:25 -08001671 def test_get_hash_tags(self):
1672 cases = [
1673 ('', []),
1674 ('a', []),
1675 ('[a]', ['a']),
1676 ('[aa]', ['aa']),
1677 ('[a ]', ['a']),
1678 ('[a- ]', ['a']),
1679 ('[a- b]', ['a-b']),
1680 ('[a--b]', ['a-b']),
1681 ('[a', []),
1682 ('[a]x', ['a']),
1683 ('[aa]x', ['aa']),
1684 ('[a b]', ['a-b']),
1685 ('[a b]', ['a-b']),
1686 ('[a__b]', ['a-b']),
1687 ('[a] x', ['a']),
1688 ('[a][b]', ['a', 'b']),
1689 ('[a] [b]', ['a', 'b']),
1690 ('[a][b]x', ['a', 'b']),
1691 ('[a][b] x', ['a', 'b']),
1692 ('[a]\n[b]', ['a']),
1693 ('[a\nb]', []),
1694 ('[a][', ['a']),
1695 ('Revert "[a] feature"', ['a']),
1696 ('Reland "[a] feature"', ['a']),
1697 ('Revert: [a] feature', ['a']),
1698 ('Reland: [a] feature', ['a']),
1699 ('Revert "Reland: [a] feature"', ['a']),
1700 ('Foo: feature', ['foo']),
1701 ('Foo Bar: feature', ['foo-bar']),
1702 ('Revert "Foo bar: feature"', ['foo-bar']),
1703 ('Reland "Foo bar: feature"', ['foo-bar']),
1704 ]
1705 for desc, expected in cases:
1706 change_desc = git_cl.ChangeDescription(desc)
1707 actual = change_desc.get_hash_tags()
1708 self.assertEqual(
1709 actual,
1710 expected,
1711 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1712
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001713 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001714 self.assertEqual(None, git_cl.GetTargetRef(None,
1715 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001716 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001717
wittman@chromium.org455dc922015-01-26 20:15:50 +00001718 # Check default target refs for branches.
1719 self.assertEqual('refs/heads/master',
1720 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001721 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001722 self.assertEqual('refs/heads/master',
1723 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001724 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001725 self.assertEqual('refs/heads/master',
1726 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001727 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001728 self.assertEqual('refs/branch-heads/123',
1729 git_cl.GetTargetRef('origin',
1730 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001731 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001732 self.assertEqual('refs/diff/test',
1733 git_cl.GetTargetRef('origin',
1734 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001735 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001736 self.assertEqual('refs/heads/chrome/m42',
1737 git_cl.GetTargetRef('origin',
1738 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001739 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001740
1741 # Check target refs for user-specified target branch.
1742 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1743 'refs/remotes/branch-heads/123'):
1744 self.assertEqual('refs/branch-heads/123',
1745 git_cl.GetTargetRef('origin',
1746 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001747 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001748 for branch in ('origin/master', 'remotes/origin/master',
1749 'refs/remotes/origin/master'):
1750 self.assertEqual('refs/heads/master',
1751 git_cl.GetTargetRef('origin',
1752 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001753 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001754 for branch in ('master', 'heads/master', 'refs/heads/master'):
1755 self.assertEqual('refs/heads/master',
1756 git_cl.GetTargetRef('origin',
1757 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001758 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001759
wychen@chromium.orga872e752015-04-28 23:42:18 +00001760 def test_patch_when_dirty(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001761 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001762 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1763 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1764
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001765 @staticmethod
1766 def _get_gerrit_codereview_server_calls(branch, value=None,
1767 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001768 detect_branch=True,
1769 detect_server=True):
Edward Lemur125d60a2019-09-13 18:25:41 +00001770 """Returns calls executed by Changelist.GetCodereviewServer.
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001771
1772 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1773 """
1774 calls = []
1775 if detect_branch:
1776 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001777 if detect_server:
1778 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1779 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001780 if value is None:
1781 calls += [
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001782 ((['git', 'config', 'branch.' + branch + '.merge'],),
1783 'refs/heads' + branch),
1784 ((['git', 'config', 'branch.' + branch + '.remote'],),
1785 'origin'),
1786 ((['git', 'config', 'remote.origin.url'],),
1787 'https://%s.googlesource.com/my/repo' % git_short_host),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001788 ]
1789 return calls
1790
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001791 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001792 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001793 detect_gerrit_server=False,
1794 actual_codereview=None,
1795 codereview_in_url=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001796 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
wychen@chromium.orga872e752015-04-28 23:42:18 +00001797 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1798
tandriidf09a462016-08-18 16:23:55 -07001799 if new_branch:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001800 self.calls = [((['git', 'new-branch', 'master'],), '')]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001801
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001802 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001803 self.calls += [
1804 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001805 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001806 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001807
1808 if not force_codereview and not codereview_in_url:
1809 # These calls detect codereview to use.
1810 self.calls += [
1811 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001812 ]
1813 if detect_gerrit_server:
1814 self.calls += self._get_gerrit_codereview_server_calls(
1815 'master', git_short_host=git_short_host,
1816 detect_branch=not new_branch and force_codereview)
1817 actual_codereview = 'gerrit'
1818
1819 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001820 self.calls += [
1821 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001822 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001823 {
1824 'current_revision': '7777777777',
1825 'revisions': {
1826 '1111111111': {
1827 '_number': 1,
1828 'fetch': {'http': {
1829 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1830 'ref': 'refs/changes/56/123456/1',
1831 }},
1832 },
1833 '7777777777': {
1834 '_number': 7,
1835 'fetch': {'http': {
1836 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1837 'ref': 'refs/changes/56/123456/7',
1838 }},
1839 },
1840 },
1841 }),
1842 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001843
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001844 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001845 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001846 self.calls += [
1847 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1848 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001849 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001850 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001851 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001852 ((['git', 'config', 'branch.master.gerritserver',
1853 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001854 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001855 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1856 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1857 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001858 ]
1859 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1860
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001861 def test_patch_gerrit_new_branch(self):
1862 self._patch_common(
1863 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1864 self.calls += [
1865 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1866 'refs/changes/56/123456/7'],), ''),
1867 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1868 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1869 ''),
1870 ((['git', 'config', 'branch.master.gerritserver',
1871 'https://chromium-review.googlesource.com'],), ''),
1872 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1873 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1874 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1875 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1876 ]
1877 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1878
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001879 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001880 self._patch_common(
1881 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001882 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001883 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001884 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001885 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001886 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001887 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001888 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001889 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001890 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001891 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1892 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1893 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001894 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001895 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001896
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001897 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001898 self.calls += self._get_gerrit_codereview_server_calls(
1899 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001900 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001901 actual_codereview='gerrit', git_short_host='else',
1902 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001903 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001904 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001905 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001906 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001907 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001908 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001909 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001910 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001911 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001912 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1913 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1914 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001915 ]
1916 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001917 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001918
Aaron Gable697a91b2018-01-19 15:20:15 -08001919 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001920 self.calls += self._get_gerrit_codereview_server_calls(
1921 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001922 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001923 actual_codereview='gerrit', git_short_host='else',
1924 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001925 self.calls += [
1926 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1927 'refs/changes/56/123456/1'],), ''),
1928 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1929 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1930 ''),
1931 ((['git', 'config', 'branch.master.gerritserver',
1932 'https://else-review.googlesource.com'],), ''),
1933 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1934 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1935 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1936 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1937 ]
1938 self.assertEqual(git_cl.main(
1939 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1940 0)
1941
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001942 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001943 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001944 self.calls += [
1945 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001946 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001947 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1948 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1949 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001950 ]
1951 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001952 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001953
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001954 def test_patch_gerrit_not_exists(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001955
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001956 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001957 raise git_cl.gerrit_util.GerritError(404, '')
1958 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1959
tandriic2405f52016-10-10 08:13:15 -07001960 self.calls = [
1961 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001962 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1963 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1964 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1965 ((['git', 'config', 'remote.origin.url'],),
1966 'https://chromium.googlesource.com/my/repo'),
1967 ((['DieWithError',
1968 'change 123456 at https://chromium-review.googlesource.com does not '
1969 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001970 ]
1971 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001972 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001973
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001974 def _checkout_calls(self):
1975 return [
1976 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001977 'branch\\..*\\.gerritissue'], ),
1978 ('branch.ger-branch.gerritissue 123456\n'
1979 'branch.gbranch654.gerritissue 654321\n')),
1980 ]
1981
1982 def test_checkout_gerrit(self):
1983 """Tests git cl checkout <issue>."""
1984 self.calls = self._checkout_calls()
1985 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1986 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1987
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001988 def test_checkout_not_found(self):
1989 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001990 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001991 self.calls = self._checkout_calls()
1992 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1993
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001994 def test_checkout_no_branch_issues(self):
1995 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001996 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001997 self.calls = [
1998 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001999 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002000 ]
2001 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2002
tandrii@chromium.org28253532016-04-14 13:46:56 +00002003 def _test_gerrit_ensure_authenticated_common(self, auth,
2004 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002005 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2006 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
2007 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11002008 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00002009 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
Edward Lemurf38bc172019-09-03 21:02:13 +00002010 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00002011 cl.branch = 'master'
2012 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002013 return cl
2014
2015 def test_gerrit_ensure_authenticated_missing(self):
2016 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002017 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002018 })
2019 self.calls.append(
2020 ((['DieWithError',
2021 'Credentials for the following hosts are required:\n'
2022 ' chromium-review.googlesource.com\n'
2023 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002024 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002025 'https://chromium-review.googlesource.com/new-password'],), ''),)
2026 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2027
2028 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00002029 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002030 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002031 'chromium.googlesource.com':
2032 ('git-one.example.com', None, 'secret1'),
2033 'chromium-review.googlesource.com':
2034 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002035 })
2036 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002037 (('ask_for_data', 'If you know what you are doing '
2038 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002039 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2040
2041 def test_gerrit_ensure_authenticated_ok(self):
2042 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002043 'chromium.googlesource.com':
2044 ('git-same.example.com', None, 'secret'),
2045 'chromium-review.googlesource.com':
2046 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002047 })
2048 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2049
tandrii@chromium.org28253532016-04-14 13:46:56 +00002050 def test_gerrit_ensure_authenticated_skipped(self):
2051 cl = self._test_gerrit_ensure_authenticated_common(
2052 auth={}, skip_auth_check=True)
2053 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2054
Eric Boren2fb63102018-10-05 13:05:03 +00002055 def test_gerrit_ensure_authenticated_bearer_token(self):
2056 cl = self._test_gerrit_ensure_authenticated_common(auth={
2057 'chromium.googlesource.com':
2058 ('', None, 'secret'),
2059 'chromium-review.googlesource.com':
2060 ('', None, 'secret'),
2061 })
2062 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2063 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2064 'chromium.googlesource.com')
2065 self.assertTrue('Bearer' in header)
2066
Daniel Chengcf6269b2019-05-18 01:02:12 +00002067 def test_gerrit_ensure_authenticated_non_https(self):
2068 self.calls = [
2069 ((['git', 'config', '--bool',
2070 'gerrit.skip-ensure-authenticated'],), CERR1),
2071 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
2072 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2073 ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
2074 ]
2075 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2076 CookiesAuthenticatorMockFactory(hosts_with_creds={}))
Edward Lemurf38bc172019-09-03 21:02:13 +00002077 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00002078 cl.branch = 'master'
2079 cl.branchref = 'refs/heads/master'
2080 cl.lookedup_issue = True
2081 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2082
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002083 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002084 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002085 lambda h, i, labels, notify=None:
2086 self._mocked_call(['SetReview', h, i, labels, notify]))
2087
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002088 self.calls = [
2089 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002090 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002091 ((['git', 'config', 'branch.feature.gerritserver'],),
2092 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002093 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2094 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2095 ((['git', 'config', 'remote.origin.url'],),
2096 'https://chromium.googlesource.com/infra/infra.git'),
2097 ((['SetReview', 'chromium-review.googlesource.com',
2098 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002099 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002100 ]
tandriid9e5ce52016-07-13 02:32:59 -07002101
2102 def test_cmd_set_commit_gerrit_clear(self):
2103 self._cmd_set_commit_gerrit_common(0)
2104 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2105
2106 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002107 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002108 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2109
tandriid9e5ce52016-07-13 02:32:59 -07002110 def test_cmd_set_commit_gerrit(self):
2111 self._cmd_set_commit_gerrit_common(2)
2112 self.assertEqual(0, git_cl.main(['set-commit']))
2113
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002114 def test_description_display(self):
2115 out = StringIO.StringIO()
2116 self.mock(git_cl.sys, 'stdout', out)
2117
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002118 self.mock(git_cl, 'Changelist', ChangelistMock)
2119 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002120
2121 self.assertEqual(0, git_cl.main(['description', '-d']))
2122 self.assertEqual('foo\n', out.getvalue())
2123
iannucci3c972b92016-08-17 13:24:10 -07002124 def test_StatusFieldOverrideIssueMissingArgs(self):
2125 out = StringIO.StringIO()
2126 self.mock(git_cl.sys, 'stderr', out)
2127
2128 try:
2129 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2130 except SystemExit as ex:
2131 self.assertEqual(ex.code, 2)
Edward Lemurf38bc172019-09-03 21:02:13 +00002132 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002133
2134 out = StringIO.StringIO()
2135 self.mock(git_cl.sys, 'stderr', out)
2136
2137 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002138 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07002139 except SystemExit as ex:
2140 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002141 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002142
2143 def test_StatusFieldOverrideIssue(self):
2144 out = StringIO.StringIO()
2145 self.mock(git_cl.sys, 'stdout', out)
2146
2147 def assertIssue(cl_self, *_args):
2148 self.assertEquals(cl_self.issue, 1)
2149 return 'foobar'
2150
2151 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07002152 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002153 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002154 0)
iannucci3c972b92016-08-17 13:24:10 -07002155 self.assertEqual(out.getvalue(), 'foobar\n')
2156
iannuccie53c9352016-08-17 14:40:40 -07002157 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002158
iannuccie53c9352016-08-17 14:40:40 -07002159 def assertIssue(cl_self, *_args):
2160 self.assertEquals(cl_self.issue, 1)
2161 return 'foobar'
2162
2163 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2164 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07002165 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002166 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002167
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002168 def test_description(self):
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002169 out = StringIO.StringIO()
2170 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002171 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002172 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2173 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2174 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2175 ((['git', 'config', 'remote.origin.url'],),
2176 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002177 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002178 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002179 {
2180 'current_revision': 'sha1',
2181 'revisions': {'sha1': {
2182 'commit': {'message': 'foobar'},
2183 }},
2184 }),
2185 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002186 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002187 'description',
2188 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2189 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002190 self.assertEqual('foobar\n', out.getvalue())
2191
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002192 def test_description_set_raw(self):
2193 out = StringIO.StringIO()
2194 self.mock(git_cl.sys, 'stdout', out)
2195
2196 self.mock(git_cl, 'Changelist', ChangelistMock)
2197 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
2198
2199 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2200 self.assertEqual('hihi', ChangelistMock.desc)
2201
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002202 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002203 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002204
2205 def RunEditor(desc, _, **kwargs):
2206 self.assertEquals(
2207 '# Enter a description of the change.\n'
2208 '# This will be displayed on the codereview site.\n'
2209 '# The first line will also be used as the subject of the review.\n'
2210 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002211 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002212 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002213 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002214 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002215 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002216
dsansomee2d6fd92016-09-08 00:10:47 -07002217 def UpdateDescriptionRemote(_, desc, force=False):
Aaron Gable3a16ed12017-03-23 10:51:55 -07002218 self.assertEquals(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002219
2220 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2221 self.mock(git_cl.Changelist, 'GetDescription',
2222 lambda *args: current_desc)
Edward Lemur125d60a2019-09-13 18:25:41 +00002223 self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002224 UpdateDescriptionRemote)
2225 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2226
2227 self.calls = [
2228 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002229 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002230 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2231 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002232 ((['git', 'config', 'core.editor'],), 'vi'),
2233 ]
2234 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2235
Dan Beamd8b04ca2019-10-10 21:23:26 +00002236 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2237 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2238
2239 def RunEditor(desc, _, **kwargs):
2240 self.assertEquals(
2241 '# Enter a description of the change.\n'
2242 '# This will be displayed on the codereview site.\n'
2243 '# The first line will also be used as the subject of the review.\n'
2244 '#--------------------This line is 72 characters long'
2245 '--------------------\n'
2246 'Some.\n\nFixed: 123\nChange-Id: xxx',
2247 desc)
2248 return desc
2249
2250 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2251 self.mock(git_cl.Changelist, 'GetDescription',
2252 lambda *args: current_desc)
2253 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2254
2255 self.calls = [
2256 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2257 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2258 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2259 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
2260 ((['git', 'config', 'core.editor'],), 'vi'),
2261 ]
2262 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2263
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002264 def test_description_set_stdin(self):
2265 out = StringIO.StringIO()
2266 self.mock(git_cl.sys, 'stdout', out)
2267
2268 self.mock(git_cl, 'Changelist', ChangelistMock)
2269 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
2270
2271 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2272 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2273
kmarshall3bff56b2016-06-06 18:31:47 -07002274 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07002275 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2276
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002277 self.calls = [
2278 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002279 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002280 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2281 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002282 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002283 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002284
kmarshall3bff56b2016-06-06 18:31:47 -07002285 self.mock(git_cl, 'get_cl_statuses',
2286 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002287 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2288 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2289 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002290
2291 self.assertEqual(0, git_cl.main(['archive', '-f']))
2292
2293 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07002294 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002295 self.calls = [
2296 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2297 'refs/heads/master'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002298 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2299 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002300
kmarshall9249e012016-08-23 12:02:16 -07002301 self.mock(git_cl, 'get_cl_statuses',
2302 lambda branches, fine_grained, max_processes:
2303 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2304
2305 self.assertEqual(1, git_cl.main(['archive', '-f']))
2306
2307 def test_archive_dry_run(self):
2308 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2309
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002310 self.calls = [
2311 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2312 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002313 ((['git', 'symbolic-ref', 'HEAD'],), 'master')
2314 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002315
2316 self.mock(git_cl, 'get_cl_statuses',
2317 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002318 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2319 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2320 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002321
kmarshall9249e012016-08-23 12:02:16 -07002322 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2323
2324 def test_archive_no_tags(self):
2325 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2326
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002327 self.calls = [
2328 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2329 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002330 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2331 ((['git', 'branch', '-D', 'foo'],), '')
2332 ]
kmarshall9249e012016-08-23 12:02:16 -07002333
2334 self.mock(git_cl, 'get_cl_statuses',
2335 lambda branches, fine_grained, max_processes:
2336 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2337 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2338 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2339
2340 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002341
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002342 def test_cmd_issue_erase_existing(self):
2343 out = StringIO.StringIO()
2344 self.mock(git_cl.sys, 'stdout', out)
2345 self.calls = [
2346 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002347 # Let this command raise exception (retcode=1) - it should be ignored.
2348 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002349 CERR1),
2350 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2351 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002352 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2353 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2354 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002355 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002356 ]
2357 self.assertEqual(0, git_cl.main(['issue', '0']))
2358
Aaron Gable400e9892017-07-12 15:31:21 -07002359 def test_cmd_issue_erase_existing_with_change_id(self):
2360 out = StringIO.StringIO()
2361 self.mock(git_cl.sys, 'stdout', out)
2362 self.mock(git_cl.Changelist, 'GetDescription',
2363 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2364 self.calls = [
2365 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Aaron Gable400e9892017-07-12 15:31:21 -07002366 # Let this command raise exception (retcode=1) - it should be ignored.
2367 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2368 CERR1),
2369 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2370 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2371 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2372 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2373 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002374 ((['git', 'log', '-1', '--format=%B'],),
2375 'This is a description\n\nChange-Id: Ideadbeef'),
2376 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002377 ]
2378 self.assertEqual(0, git_cl.main(['issue', '0']))
2379
phajdan.jre328cf92016-08-22 04:12:17 -07002380 def test_cmd_issue_json(self):
2381 out = StringIO.StringIO()
2382 self.mock(git_cl.sys, 'stdout', out)
2383 self.calls = [
2384 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002385 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2386 ((['git', 'config', 'branch.feature.gerritserver'],),
2387 'https://chromium-review.googlesource.com'),
phajdan.jre328cf92016-08-22 04:12:17 -07002388 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002389 {'issue': 123,
2390 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002391 ''),
2392 ]
2393 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2394
tandrii16e0b4e2016-06-07 10:34:28 -07002395 def _common_GerritCommitMsgHookCheck(self):
2396 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2397 self.mock(git_cl.os.path, 'abspath',
2398 lambda path: self._mocked_call(['abspath', path]))
2399 self.mock(git_cl.os.path, 'exists',
2400 lambda path: self._mocked_call(['exists', path]))
2401 self.mock(git_cl.gclient_utils, 'FileRead',
2402 lambda path: self._mocked_call(['FileRead', path]))
2403 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2404 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2405 self.calls = [
2406 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2407 ((['abspath', '../'],), '/abs/git_repo_root'),
2408 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002409 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002410
2411 def test_GerritCommitMsgHookCheck_custom_hook(self):
2412 cl = self._common_GerritCommitMsgHookCheck()
2413 self.calls += [
2414 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2415 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2416 '#!/bin/sh\necho "custom hook"')
2417 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002418 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002419
2420 def test_GerritCommitMsgHookCheck_not_exists(self):
2421 cl = self._common_GerritCommitMsgHookCheck()
2422 self.calls += [
2423 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2424 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002425 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002426
2427 def test_GerritCommitMsgHookCheck(self):
2428 cl = self._common_GerritCommitMsgHookCheck()
2429 self.calls += [
2430 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2431 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2432 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002433 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002434 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2435 ''),
2436 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002437 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002438
tandriic4344b52016-08-29 06:04:54 -07002439 def test_GerritCmdLand(self):
2440 self.calls += [
2441 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2442 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2443 'deadbeaf'),
2444 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2445 ((['git', 'config', 'branch.feature.gerritserver'],),
2446 'chromium-review.googlesource.com'),
2447 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002448 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002449 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002450 'labels': {},
2451 'current_revision': 'deadbeaf',
2452 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002453 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002454 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002455 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002456 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2457 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002458 cl.SubmitIssue = lambda wait_for_merge: None
tandrii8da412c2016-09-07 16:01:07 -07002459 out = StringIO.StringIO()
2460 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002461 self.assertEqual(0, cl.CMDLand(force=True,
2462 bypass_hooks=True,
2463 verbose=True,
2464 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002465 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002466 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002467
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002468 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemur125d60a2019-09-13 18:25:41 +00002469 self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002470
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002471 def test_gerrit_change_detail_cache_simple(self):
2472 self._mock_gerrit_changes_for_detail_cache()
2473 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002474 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2475 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2476 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002477 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002478 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002479 cl1._cached_remote_url = (
2480 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002481 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002482 cl2._cached_remote_url = (
2483 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002484 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2485 self.assertEqual(cl1._GetChangeDetail(), 'a')
2486 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2487 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2488 self.assertEqual(cl1._GetChangeDetail(), 'a')
2489 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002490
2491 def test_gerrit_change_detail_cache_options(self):
2492 self._mock_gerrit_changes_for_detail_cache()
2493 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002494 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2495 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2496 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2497 # no longer in cache.
2498 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002499 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002500 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002501 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002502 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2503 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2504 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2505 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2506 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2507 self.assertEqual(cl._GetChangeDetail(), 'cab')
2508
2509 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2510 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2511 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2512 self.assertEqual(cl._GetChangeDetail(), 'cab')
2513
2514 # Finally, no_cache should invalidate all caches for given change.
2515 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2516 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2517
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002518 def test_gerrit_description_caching(self):
2519 def gen_detail(rev, desc):
2520 return {
2521 'current_revision': rev,
2522 'revisions': {rev: {'commit': {'message': desc}}}
2523 }
2524 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002525 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002526 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2527 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002528 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002529 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2530 gen_detail('rev2', 'desc2')),
2531 ]
2532
2533 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002534 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002535 cl._cached_remote_url = (
2536 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002537 self.assertEqual(cl.GetDescription(), 'desc1')
2538 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2539 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002540
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002541 def test_print_current_creds(self):
2542 class CookiesAuthenticatorMock(object):
2543 def __init__(self):
2544 self.gitcookies = {
2545 'host.googlesource.com': ('user', 'pass'),
2546 'host-review.googlesource.com': ('user', 'pass'),
2547 }
2548 self.netrc = self
2549 self.netrc.hosts = {
2550 'github.com': ('user2', None, 'pass2'),
2551 'host2.googlesource.com': ('user3', None, 'pass'),
2552 }
2553 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2554 CookiesAuthenticatorMock)
2555 self.mock(sys, 'stdout', StringIO.StringIO())
2556 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2557 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2558 ' Host\t User\t Which file',
2559 '============================\t=====\t===========',
2560 'host-review.googlesource.com\t user\t.gitcookies',
2561 ' host.googlesource.com\t user\t.gitcookies',
2562 ' host2.googlesource.com\tuser3\t .netrc',
2563 ])
2564 sys.stdout.buf = ''
2565 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2566 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2567 ' Host\tUser\t Which file',
2568 '============================\t====\t===========',
2569 'host-review.googlesource.com\tuser\t.gitcookies',
2570 ' host.googlesource.com\tuser\t.gitcookies',
2571 ])
2572
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002573 def _common_creds_check_mocks(self):
2574 def exists_mock(path):
2575 dirname = os.path.dirname(path)
2576 if dirname == os.path.expanduser('~'):
2577 dirname = '~'
2578 base = os.path.basename(path)
2579 if base in ('.netrc', '.gitcookies'):
2580 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2581 # git cl also checks for existence other files not relevant to this test.
2582 return None
2583 self.mock(os.path, 'exists', exists_mock)
2584 self.mock(sys, 'stdout', StringIO.StringIO())
2585
2586 def test_creds_check_gitcookies_not_configured(self):
2587 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002588 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002589 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002590 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002591 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002592 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2593 (('os.path.exists', '~/.netrc'), True),
2594 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2595 'or Ctrl+C to abort'), ''),
2596 ((['git', 'config', '--global', 'http.cookiefile',
2597 os.path.expanduser('~/.gitcookies')], ), ''),
2598 ]
2599 self.assertEqual(0, git_cl.main(['creds-check']))
2600 self.assertRegexpMatches(
2601 sys.stdout.getvalue(),
2602 '^You seem to be using outdated .netrc for git credentials:')
2603 self.assertRegexpMatches(
2604 sys.stdout.getvalue(),
2605 '\nConfigured git to use .gitcookies from')
2606
2607 def test_creds_check_gitcookies_configured_custom_broken(self):
2608 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002609 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002610 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002611 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002612 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002613 ((['git', 'config', '--global', 'http.cookiefile'],),
2614 '/custom/.gitcookies'),
2615 (('os.path.exists', '/custom/.gitcookies'), False),
2616 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2617 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2618 ((['git', 'config', '--global', 'http.cookiefile',
2619 os.path.expanduser('~/.gitcookies')], ), ''),
2620 ]
2621 self.assertEqual(0, git_cl.main(['creds-check']))
2622 self.assertRegexpMatches(
2623 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002624 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002625 self.assertRegexpMatches(
2626 sys.stdout.getvalue(),
2627 'However, your configured .gitcookies file is missing.')
2628
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002629 def test_git_cl_comment_add_gerrit(self):
2630 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002631 lambda host, change, msg, ready:
2632 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002633 self.calls = [
2634 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2635 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2636 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2637 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2638 'origin/master'),
2639 ((['git', 'config', 'remote.origin.url'],),
2640 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002641 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2642 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002643 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002644 ]
2645 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2646 '-a', 'msg']))
2647
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002648 def test_git_cl_comments_fetch_gerrit(self):
2649 self.mock(sys, 'stdout', StringIO.StringIO())
2650 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002651 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2652 ((['git', 'config', 'branch.foo.merge'],), ''),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002653 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2654 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2655 'origin/master'),
2656 ((['git', 'config', 'remote.origin.url'],),
2657 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002658 (('GetChangeDetail', 'chromium-review.googlesource.com',
2659 'infra%2Finfra~1',
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002660 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2661 'CURRENT_COMMIT']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002662 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002663 'current_revision': 'ba5eba11',
2664 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002665 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002666 '_number': 1,
2667 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002668 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002669 '_number': 2,
2670 },
2671 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002672 'messages': [
2673 {
2674 u'_revision_number': 1,
2675 u'author': {
2676 u'_account_id': 1111084,
2677 u'email': u'commit-bot@chromium.org',
2678 u'name': u'Commit Bot'
2679 },
2680 u'date': u'2017-03-15 20:08:45.000000000',
2681 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002682 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002683 u'tag': u'autogenerated:cq:dry-run'
2684 },
2685 {
2686 u'_revision_number': 2,
2687 u'author': {
2688 u'_account_id': 11151243,
2689 u'email': u'owner@example.com',
2690 u'name': u'owner'
2691 },
2692 u'date': u'2017-03-16 20:00:41.000000000',
2693 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2694 u'message': u'PTAL',
2695 },
2696 {
2697 u'_revision_number': 2,
2698 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002699 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002700 u'email': u'reviewer@example.com',
2701 u'name': u'reviewer'
2702 },
2703 u'date': u'2017-03-17 05:19:37.500000000',
2704 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2705 u'message': u'Patch Set 2: Code-Review+1',
2706 },
2707 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002708 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002709 (('GetChangeComments', 'chromium-review.googlesource.com',
2710 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002711 '/COMMIT_MSG': [
2712 {
2713 'author': {'email': u'reviewer@example.com'},
2714 'updated': u'2017-03-17 05:19:37.500000000',
2715 'patch_set': 2,
2716 'side': 'REVISION',
2717 'message': 'Please include a bug link',
2718 },
2719 ],
2720 'codereview.settings': [
2721 {
2722 'author': {'email': u'owner@example.com'},
2723 'updated': u'2017-03-16 20:00:41.000000000',
2724 'patch_set': 2,
2725 'side': 'PARENT',
2726 'line': 42,
2727 'message': 'I removed this because it is bad',
2728 },
2729 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002730 }),
2731 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2732 'infra%2Finfra~1'), {}),
2733 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002734 ] * 2 + [
2735 (('write_json', 'output.json', [
2736 {
2737 u'date': u'2017-03-16 20:00:41.000000',
2738 u'message': (
2739 u'PTAL\n' +
2740 u'\n' +
2741 u'codereview.settings\n' +
2742 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2743 u'c/1/2/codereview.settings#b42\n' +
2744 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002745 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002746 u'approval': False,
2747 u'disapproval': False,
2748 u'sender': u'owner@example.com'
2749 }, {
2750 u'date': u'2017-03-17 05:19:37.500000',
2751 u'message': (
2752 u'Patch Set 2: Code-Review+1\n' +
2753 u'\n' +
2754 u'/COMMIT_MSG\n' +
2755 u' PS2, File comment: https://chromium-review.googlesource' +
2756 u'.com/c/1/2//COMMIT_MSG#\n' +
2757 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002758 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002759 u'approval': False,
2760 u'disapproval': False,
2761 u'sender': u'reviewer@example.com'
2762 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002763 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002764 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002765 expected_comments_summary = [
2766 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002767 message=(
2768 u'PTAL\n' +
2769 u'\n' +
2770 u'codereview.settings\n' +
2771 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2772 u'c/1/2/codereview.settings#b42\n' +
2773 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002774 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002775 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002776 disapproval=False, approval=False, sender=u'owner@example.com'),
2777 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002778 message=(
2779 u'Patch Set 2: Code-Review+1\n' +
2780 u'\n' +
2781 u'/COMMIT_MSG\n' +
2782 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2783 u'c/1/2//COMMIT_MSG#\n' +
2784 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002785 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002786 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002787 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2788 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002789 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002790 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002791 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002792 self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
2793 self.assertEqual(
2794 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2795
2796 def test_git_cl_comments_robot_comments(self):
2797 # git cl comments also fetches robot comments (which are considered a type
2798 # of autogenerated comment), and unlike other types of comments, only robot
2799 # comments from the latest patchset are shown.
2800 self.mock(sys, 'stdout', StringIO.StringIO())
2801 self.calls = [
2802 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2803 ((['git', 'config', 'branch.foo.merge'],), ''),
2804 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2805 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2806 'origin/master'),
2807 ((['git', 'config', 'remote.origin.url'],),
2808 'https://chromium.googlesource.com/infra/infra'),
2809 (('GetChangeDetail', 'chromium-review.googlesource.com',
2810 'infra%2Finfra~1',
2811 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2812 'CURRENT_COMMIT']), {
2813 'owner': {'email': 'owner@example.com'},
2814 'current_revision': 'ba5eba11',
2815 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002816 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002817 '_number': 1,
2818 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002819 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002820 '_number': 2,
2821 },
2822 },
2823 'messages': [
2824 {
2825 u'_revision_number': 1,
2826 u'author': {
2827 u'_account_id': 1111084,
2828 u'email': u'commit-bot@chromium.org',
2829 u'name': u'Commit Bot'
2830 },
2831 u'date': u'2017-03-15 20:08:45.000000000',
2832 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2833 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2834 u'tag': u'autogenerated:cq:dry-run'
2835 },
2836 {
2837 u'_revision_number': 1,
2838 u'author': {
2839 u'_account_id': 123,
2840 u'email': u'tricium@serviceaccount.com',
2841 u'name': u'Tricium'
2842 },
2843 u'date': u'2017-03-16 20:00:41.000000000',
2844 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2845 u'message': u'(1 comment)',
2846 u'tag': u'autogenerated:tricium',
2847 },
2848 {
2849 u'_revision_number': 1,
2850 u'author': {
2851 u'_account_id': 123,
2852 u'email': u'tricium@serviceaccount.com',
2853 u'name': u'Tricium'
2854 },
2855 u'date': u'2017-03-16 20:00:41.000000000',
2856 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2857 u'message': u'(1 comment)',
2858 u'tag': u'autogenerated:tricium',
2859 },
2860 {
2861 u'_revision_number': 2,
2862 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002863 u'_account_id': 123,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002864 u'email': u'tricium@serviceaccount.com',
2865 u'name': u'reviewer'
2866 },
2867 u'date': u'2017-03-17 05:30:37.000000000',
2868 u'tag': u'autogenerated:tricium',
2869 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2870 u'message': u'(1 comment)',
2871 },
2872 ]
2873 }),
2874 (('GetChangeComments', 'chromium-review.googlesource.com',
2875 'infra%2Finfra~1'), {}),
2876 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2877 'infra%2Finfra~1'), {
2878 'codereview.settings': [
2879 {
2880 u'author': {u'email': u'tricium@serviceaccount.com'},
2881 u'updated': u'2017-03-17 05:30:37.000000000',
2882 u'robot_run_id': u'5565031076855808',
2883 u'robot_id': u'Linter/Category',
2884 u'tag': u'autogenerated:tricium',
2885 u'patch_set': 2,
2886 u'side': u'REVISION',
2887 u'message': u'Linter warning message text',
2888 u'line': 32,
2889 },
2890 ],
2891 }),
2892 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
2893 ]
2894 expected_comments_summary = [
2895 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2896 message=(
2897 u'(1 comment)\n\ncodereview.settings\n'
2898 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2899 u'c/1/2/codereview.settings#32\n'
2900 u' Linter warning message text\n'),
2901 sender=u'tricium@serviceaccount.com',
2902 autogenerated=True, approval=False, disapproval=False)
2903 ]
2904 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002905 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002906 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002907
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002908 def test_get_remote_url_with_mirror(self):
2909 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002910
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002911 def selective_os_path_isdir_mock(path):
2912 if path == '/cache/this-dir-exists':
2913 return self._mocked_call('os.path.isdir', path)
2914 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002915
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002916 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2917
2918 url = 'https://chromium.googlesource.com/my/repo'
2919 self.calls = [
2920 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2921 ((['git', 'config', 'branch.master.merge'],), 'master'),
2922 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2923 ((['git', 'config', 'remote.origin.url'],),
2924 '/cache/this-dir-exists'),
2925 (('os.path.isdir', '/cache/this-dir-exists'),
2926 True),
2927 # Runs in /cache/this-dir-exists.
2928 ((['git', 'config', 'remote.origin.url'],),
2929 url),
2930 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002931 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002932 self.assertEqual(cl.GetRemoteUrl(), url)
2933 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2934
Edward Lemur298f2cf2019-02-22 21:40:39 +00002935 def test_get_remote_url_non_existing_mirror(self):
2936 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002937
Edward Lemur298f2cf2019-02-22 21:40:39 +00002938 def selective_os_path_isdir_mock(path):
2939 if path == '/cache/this-dir-doesnt-exist':
2940 return self._mocked_call('os.path.isdir', path)
2941 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002942
Edward Lemur298f2cf2019-02-22 21:40:39 +00002943 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2944 self.mock(logging, 'error',
2945 lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
2946
2947 self.calls = [
2948 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2949 ((['git', 'config', 'branch.master.merge'],), 'master'),
2950 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2951 ((['git', 'config', 'remote.origin.url'],),
2952 '/cache/this-dir-doesnt-exist'),
2953 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2954 False),
2955 (('logging.error',
Daniel Bratell4a60db42019-09-16 17:02:52 +00002956 'Remote "origin" for branch "master" points to'
2957 ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002958 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002959 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002960 self.assertIsNone(cl.GetRemoteUrl())
2961
2962 def test_get_remote_url_misconfigured_mirror(self):
2963 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002964
Edward Lemur298f2cf2019-02-22 21:40:39 +00002965 def selective_os_path_isdir_mock(path):
2966 if path == '/cache/this-dir-exists':
2967 return self._mocked_call('os.path.isdir', path)
2968 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002969
Edward Lemur298f2cf2019-02-22 21:40:39 +00002970 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2971 self.mock(logging, 'error',
2972 lambda *a: self._mocked_call('logging.error', *a))
2973
2974 self.calls = [
2975 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2976 ((['git', 'config', 'branch.master.merge'],), 'master'),
2977 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2978 ((['git', 'config', 'remote.origin.url'],),
2979 '/cache/this-dir-exists'),
2980 (('os.path.isdir', '/cache/this-dir-exists'), True),
2981 # Runs in /cache/this-dir-exists.
2982 ((['git', 'config', 'remote.origin.url'],), ''),
2983 (('logging.error',
2984 'Remote "%(remote)s" for branch "%(branch)s" points to '
2985 '"%(cache_path)s", but it is misconfigured.\n'
2986 '"%(cache_path)s" must be a git repo and must have a remote named '
2987 '"%(remote)s" pointing to the git host.', {
2988 'remote': 'origin',
2989 'cache_path': '/cache/this-dir-exists',
2990 'branch': 'master'}
2991 ), None),
2992 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002993 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002994 self.assertIsNone(cl.GetRemoteUrl())
2995
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002996 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002997 self.calls = [
2998 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2999 ((['git', 'config', 'branch.master.merge'],), 'master'),
3000 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3001 ((['git', 'config', 'remote.origin.url'],),
3002 'https://chromium.googlesource.com/a/my/repo.git/'),
3003 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003004 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003005 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3006
3007 def test_gerrit_change_identifier_without_project(self):
3008 self.calls = [
3009 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3010 ((['git', 'config', 'branch.master.merge'],), 'master'),
3011 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3012 ((['git', 'config', 'remote.origin.url'],), CERR1),
3013 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003014 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003015 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003016
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003017
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003018class CMDTestCaseBase(unittest.TestCase):
3019 _STATUSES = [
3020 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3021 'INFRA_FAILURE', 'CANCELED',
3022 ]
3023 _CHANGE_DETAIL = {
3024 'project': 'depot_tools',
3025 'status': 'OPEN',
3026 'owner': {'email': 'owner@e.mail'},
3027 'current_revision': 'beeeeeef',
3028 'revisions': {
3029 'deadbeaf': {'_number': 6},
3030 'beeeeeef': {
3031 '_number': 7,
3032 'fetch': {'http': {
3033 'url': 'https://chromium.googlesource.com/depot_tools',
3034 'ref': 'refs/changes/56/123456/7'
3035 }},
3036 },
3037 },
3038 }
3039 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003040 'builds': [{
3041 'id': str(100 + idx),
3042 'builder': {
3043 'project': 'chromium',
3044 'bucket': 'try',
3045 'builder': 'bot_' + status.lower(),
3046 },
3047 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3048 'tags': [],
3049 'status': status,
3050 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003051 }
3052
Edward Lemur4c707a22019-09-24 21:13:43 +00003053 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003054 super(CMDTestCaseBase, self).setUp()
Edward Lemur4c707a22019-09-24 21:13:43 +00003055 mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003056 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3057 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003058 mock.patch('git_cl.Changelist.GetCodereviewServer',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003059 return_value='https://chromium-review.googlesource.com').start()
3060 mock.patch('git_cl.Changelist.GetMostRecentPatchset',
3061 return_value=7).start()
Edward Lemurb4a587d2019-10-09 23:56:38 +00003062 mock.patch('git_cl.auth.get_authenticator',
3063 return_value=AuthenticatorMock()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003064 mock.patch('git_cl.Changelist._GetChangeDetail',
3065 return_value=self._CHANGE_DETAIL).start()
3066 mock.patch('git_cl._call_buildbucket',
3067 return_value = self._DEFAULT_RESPONSE).start()
3068 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003069 self.addCleanup(mock.patch.stopall)
3070
Edward Lemur4c707a22019-09-24 21:13:43 +00003071
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003072class CMDTryResultsTestCase(CMDTestCaseBase):
3073 _DEFAULT_REQUEST = {
3074 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003075 "gerritChanges": [{
3076 "project": "depot_tools",
3077 "host": "chromium-review.googlesource.com",
3078 "patchset": 7,
3079 "change": 123456,
3080 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003081 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003082 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3083 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003084 }
3085
3086 def testNoJobs(self):
3087 git_cl._call_buildbucket.return_value = {}
3088
3089 self.assertEqual(0, git_cl.main(['try-results']))
3090 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3091 git_cl._call_buildbucket.assert_called_once_with(
3092 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3093 self._DEFAULT_REQUEST)
3094
3095 def testPrintToStdout(self):
3096 self.assertEqual(0, git_cl.main(['try-results']))
3097 self.assertEqual([
3098 'Successes:',
3099 ' bot_success https://ci.chromium.org/b/103',
3100 'Infra Failures:',
3101 ' bot_infra_failure https://ci.chromium.org/b/105',
3102 'Failures:',
3103 ' bot_failure https://ci.chromium.org/b/104',
3104 'Canceled:',
3105 ' bot_canceled ',
3106 'Started:',
3107 ' bot_started https://ci.chromium.org/b/102',
3108 'Scheduled:',
3109 ' bot_scheduled id=101',
3110 'Other:',
3111 ' bot_status_unspecified id=100',
3112 'Total: 7 tryjobs',
3113 ], sys.stdout.getvalue().splitlines())
3114 git_cl._call_buildbucket.assert_called_once_with(
3115 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3116 self._DEFAULT_REQUEST)
3117
3118 def testPrintToStdoutWithMasters(self):
3119 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3120 self.assertEqual([
3121 'Successes:',
3122 ' try bot_success https://ci.chromium.org/b/103',
3123 'Infra Failures:',
3124 ' try bot_infra_failure https://ci.chromium.org/b/105',
3125 'Failures:',
3126 ' try bot_failure https://ci.chromium.org/b/104',
3127 'Canceled:',
3128 ' try bot_canceled ',
3129 'Started:',
3130 ' try bot_started https://ci.chromium.org/b/102',
3131 'Scheduled:',
3132 ' try bot_scheduled id=101',
3133 'Other:',
3134 ' try bot_status_unspecified id=100',
3135 'Total: 7 tryjobs',
3136 ], sys.stdout.getvalue().splitlines())
3137 git_cl._call_buildbucket.assert_called_once_with(
3138 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3139 self._DEFAULT_REQUEST)
3140
3141 @mock.patch('git_cl.write_json')
3142 def testWriteToJson(self, mockJsonDump):
3143 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3144 git_cl._call_buildbucket.assert_called_once_with(
3145 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3146 self._DEFAULT_REQUEST)
3147 mockJsonDump.assert_called_once_with(
3148 'file.json', self._DEFAULT_RESPONSE['builds'])
3149
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003150 def test_filter_failed_for_one_simple(self):
3151 self.assertEqual({}, git_cl._filter_failed_for_retry([]))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003152 self.assertEqual({
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003153 'chromium/try': {
3154 'bot_failure': [],
3155 'bot_infra_failure': []
3156 },
3157 }, git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
3158
3159 def test_filter_failed_for_retry_many_builds(self):
3160
3161 def _build(name, created_sec, status, experimental=False):
3162 assert 0 <= created_sec < 100, created_sec
3163 b = {
3164 'id': 112112,
3165 'builder': {
3166 'project': 'chromium',
3167 'bucket': 'try',
3168 'builder': name,
3169 },
3170 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3171 'status': status,
3172 'tags': [],
3173 }
3174 if experimental:
3175 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3176 return b
3177
3178 builds = [
3179 _build('flaky-last-green', 1, 'FAILURE'),
3180 _build('flaky-last-green', 2, 'SUCCESS'),
3181 _build('flaky', 1, 'SUCCESS'),
3182 _build('flaky', 2, 'FAILURE'),
3183 _build('running', 1, 'FAILED'),
3184 _build('running', 2, 'SCHEDULED'),
3185 _build('yep-still-running', 1, 'STARTED'),
3186 _build('yep-still-running', 2, 'FAILURE'),
3187 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3188 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3189
3190 # Simulate experimental in CQ builder, which developer decided
3191 # to retry manually which resulted in 2nd build non-experimental.
3192 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3193 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3194 ]
3195 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
3196 self.assertEqual({
3197 'chromium/try': {
3198 'flaky': [],
3199 'sometimes-experimental': []
3200 },
3201 }, git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003202
3203
3204class CMDTryTestCase(CMDTestCaseBase):
3205
3206 @mock.patch('git_cl.Changelist.SetCQState')
3207 @mock.patch('git_cl._get_bucket_map', return_value={})
3208 def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
3209 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003210 self.assertEqual(0, git_cl.main(['try']))
3211 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3212 self.assertEqual(
3213 sys.stdout.getvalue(),
3214 'Scheduling CQ dry run on: '
3215 'https://chromium-review.googlesource.com/123456\n')
3216
Edward Lemur4c707a22019-09-24 21:13:43 +00003217 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003218 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003219 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003220
3221 self.assertEqual(0, git_cl.main([
3222 'try', '-B', 'luci.chromium.try', '-b', 'win',
3223 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3224 self.assertIn(
3225 'Scheduling jobs on:\nBucket: luci.chromium.try',
3226 git_cl.sys.stdout.getvalue())
3227
3228 expected_request = {
3229 "requests": [{
3230 "scheduleBuild": {
3231 "requestId": "uuid4",
3232 "builder": {
3233 "project": "chromium",
3234 "builder": "win",
3235 "bucket": "try",
3236 },
3237 "gerritChanges": [{
3238 "project": "depot_tools",
3239 "host": "chromium-review.googlesource.com",
3240 "patchset": 7,
3241 "change": 123456,
3242 }],
3243 "properties": {
3244 "category": "git_cl_try",
3245 "json": [{"a": 1}, None],
3246 "key": "val",
3247 },
3248 "tags": [
3249 {"value": "win", "key": "builder"},
3250 {"value": "git_cl_try", "key": "user_agent"},
3251 ],
3252 },
3253 }],
3254 }
3255 mockCallBuildbucket.assert_called_with(
3256 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3257
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003258 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur4c707a22019-09-24 21:13:43 +00003259 self.assertEqual(0, git_cl.main([
3260 'try', '-B', 'not-a-bucket', '-b', 'win',
3261 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3262 self.assertIn(
3263 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3264 git_cl.sys.stdout.getvalue())
3265
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003266 @mock.patch('git_cl._call_buildbucket')
3267 @mock.patch('git_cl.fetch_try_jobs')
3268 def testScheduleOnBuildbucketRetryFailed(
3269 self, mockFetchTryJobs, mockCallBuildbucket):
3270
3271 git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
3272 7: [],
3273 6: [{
3274 'id': 112112,
3275 'builder': {
3276 'project': 'chromium',
3277 'bucket': 'try',
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003278 'builder': 'linux',},
3279 'createTime': '2019-10-09T08:00:01.854286Z',
3280 'tags': [],
3281 'status': 'FAILURE',}],}[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003282 mockCallBuildbucket.return_value = {}
3283
3284 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3285 self.assertIn(
3286 'Scheduling jobs on:\nBucket: chromium/try',
3287 git_cl.sys.stdout.getvalue())
3288
3289 expected_request = {
3290 "requests": [{
3291 "scheduleBuild": {
3292 "requestId": "uuid4",
3293 "builder": {
3294 "project": "chromium",
3295 "bucket": "try",
3296 "builder": "linux",
3297 },
3298 "gerritChanges": [{
3299 "project": "depot_tools",
3300 "host": "chromium-review.googlesource.com",
3301 "patchset": 7,
3302 "change": 123456,
3303 }],
3304 "properties": {
3305 "category": "git_cl_try",
3306 },
3307 "tags": [
3308 {"value": "linux", "key": "builder"},
3309 {"value": "git_cl_try", "key": "user_agent"},
3310 {"value": "1", "key": "retry_failed"},
3311 ],
3312 },
3313 }],
3314 }
3315 mockCallBuildbucket.assert_called_with(
3316 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3317
Edward Lemur4c707a22019-09-24 21:13:43 +00003318 def test_parse_bucket(self):
3319 test_cases = [
3320 {
3321 'bucket': 'chromium/try',
3322 'result': ('chromium', 'try'),
3323 },
3324 {
3325 'bucket': 'luci.chromium.try',
3326 'result': ('chromium', 'try'),
3327 'has_warning': True,
3328 },
3329 {
3330 'bucket': 'skia.primary',
3331 'result': ('skia', 'skia.primary'),
3332 'has_warning': True,
3333 },
3334 {
3335 'bucket': 'not-a-bucket',
3336 'result': (None, None),
3337 },
3338 ]
3339
3340 for test_case in test_cases:
3341 git_cl.sys.stdout.truncate(0)
3342 self.assertEqual(
3343 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3344 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003345 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3346 test_case['result'])
3347 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003348
3349
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003350class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003351 def setUp(self):
3352 super(CMDUploadTestCase, self).setUp()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003353 mock.patch('git_cl.fetch_try_jobs').start()
3354 mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
3355 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003356 self.addCleanup(mock.patch.stopall)
3357
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003358 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003359 # This test mocks out the actual upload part, and just asserts that after
3360 # upload, if --retry-failed is added, then the tool will fetch try jobs
3361 # from the previous patchset and trigger the right builders on the latest
3362 # patchset.
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003363 git_cl.fetch_try_jobs.side_effect = [
3364 # Latest patchset: No builds.
3365 [],
3366 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003367 [{
3368 'id': str(100 + idx),
3369 'builder': {
3370 'project': 'chromium',
3371 'bucket': 'try',
3372 'builder': 'bot_' + status.lower(),
3373 },
3374 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3375 'tags': [],
3376 'status': status,
3377 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003378 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003379
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003380 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003381 self.assertEqual([
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003382 mock.call(mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3383 mock.call(mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003384 ], git_cl.fetch_try_jobs.mock_calls)
3385 expected_buckets = {
3386 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
3387 }
3388 git_cl._trigger_try_jobs.assert_called_once_with(
3389 mock.ANY, mock.ANY, expected_buckets, mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003390
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003391if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003392 logging.basicConfig(
3393 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003394 unittest.main()