blob: c734e220b0dee11fd2913022759c720dd2a7b88b [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)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000639 self.mock(git_cl.auth, 'get_authenticator_for_host', 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
ukai@chromium.orge8077812012-02-03 03:41:46 +00001418 def test_gerrit_reviewer_multiple(self):
Edward Lemur687ca902018-12-05 02:30:30 +00001419 self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
1420 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001421 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001422 [],
bradnelsond975b302016-10-23 12:20:23 -07001423 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1424 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001425 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001426 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001427 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001428 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001429 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001430 labels={'Code-Review': 2},
1431 change_id='123456789',
1432 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001433
1434 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001435 self._run_gerrit_upload_test(
1436 [],
1437 'desc\nBUG=\n\nChange-Id: 123456789',
1438 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001439 expected_upstream_ref='origin/master',
1440 change_id='123456789',
1441 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001442
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001443 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001444 self._run_gerrit_upload_test(
1445 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001446 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001447 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001448 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001449 expected_upstream_ref='origin/master',
1450 change_id='123456789',
1451 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001452
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001453 def test_gerrit_upload_squash_first_with_labels(self):
1454 self._run_gerrit_upload_test(
1455 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
1456 'desc\nBUG=\n\nChange-Id: 123456789',
1457 [],
1458 squash=True,
1459 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001460 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1461 change_id='123456789',
1462 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001463
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001464 def test_gerrit_upload_squash_first_against_rev(self):
1465 custom_cl_base = 'custom_cl_base_rev_or_branch'
1466 self._run_gerrit_upload_test(
1467 ['--squash', custom_cl_base],
1468 'desc\nBUG=\n\nChange-Id: 123456789',
1469 [],
1470 squash=True,
1471 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001472 custom_cl_base=custom_cl_base,
1473 change_id='123456789',
1474 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001475 self.assertIn(
1476 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1477 sys.stdout.getvalue())
1478
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001479 def test_gerrit_upload_squash_reupload(self):
1480 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001481 self._run_gerrit_upload_test(
1482 ['--squash'],
1483 description,
1484 [],
1485 squash=True,
1486 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001487 issue=123456,
1488 change_id='123456789',
1489 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001490
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001491 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1492 self.mock(git_cl, 'DieWithError',
1493 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1494 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1495 with self.assertRaises(SystemExitMock):
1496 self._run_gerrit_upload_test(
1497 ['--squash'],
1498 description,
1499 [],
1500 squash=True,
1501 expected_upstream_ref='origin/master',
1502 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001503 fetched_status='ABANDONED',
1504 change_id='123456789')
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001505
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001506 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1507 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1508 lambda *_, **__: {'email': 'yet-another@example.com'})
1509 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1510 self._run_gerrit_upload_test(
1511 ['--squash'],
1512 description,
1513 [],
1514 squash=True,
1515 expected_upstream_ref='origin/master',
1516 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001517 other_cl_owner='other@example.com',
1518 change_id='123456789',
1519 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001520 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001521 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001522 'authenticate to Gerrit as yet-another@example.com.\n'
1523 'Uploading may fail due to lack of permissions',
1524 git_cl.sys.stdout.getvalue())
1525
rmistry@google.com2dd99862015-06-22 12:22:18 +00001526 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001527 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001528 def mock_run_git(*args, **_kwargs):
1529 if args[0] == ['for-each-ref',
1530 '--format=%(refname:short) %(upstream:short)',
1531 'refs/heads']:
1532 # Create a local branch dependency tree that looks like this:
1533 # test1 -> test2 -> test3 -> test4 -> test5
1534 # -> test3.1
1535 # test6 -> test0
1536 branch_deps = [
1537 'test2 test1', # test1 -> test2
1538 'test3 test2', # test2 -> test3
1539 'test3.1 test2', # test2 -> test3.1
1540 'test4 test3', # test3 -> test4
1541 'test5 test4', # test4 -> test5
1542 'test6 test0', # test0 -> test6
1543 'test7', # test7
1544 ]
1545 return '\n'.join(branch_deps)
1546 self.mock(git_cl, 'RunGit', mock_run_git)
1547
1548 class RecordCalls:
1549 times_called = 0
1550 record_calls = RecordCalls()
1551 def mock_CMDupload(*args, **_kwargs):
1552 record_calls.times_called += 1
1553 return 0
1554 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1555
1556 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001557 (('ask_for_data', 'This command will checkout all dependent branches '
1558 'and run "git cl upload". Press Enter to continue, '
1559 'or Ctrl+C to abort'), ''),
1560 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001561
1562 class MockChangelist():
1563 def __init__(self):
1564 pass
1565 def GetBranch(self):
1566 return 'test1'
1567 def GetIssue(self):
1568 return '123'
1569 def GetPatchset(self):
1570 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001571 def IsGerrit(self):
1572 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001573
1574 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1575 # CMDupload should have been called 5 times because of 5 dependent branches.
1576 self.assertEquals(5, record_calls.times_called)
1577 self.assertEquals(0, ret)
1578
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001579 def test_gerrit_change_id(self):
1580 self.calls = [
1581 ((['git', 'write-tree'], ),
1582 'hashtree'),
1583 ((['git', 'rev-parse', 'HEAD~0'], ),
1584 'branch-parent'),
1585 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1586 'A B <a@b.org> 1456848326 +0100'),
1587 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1588 'C D <c@d.org> 1456858326 +0100'),
1589 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1590 'hashchange'),
1591 ]
1592 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1593 self.assertEqual(change_id, 'Ihashchange')
1594
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001595 def test_desecription_append_footer(self):
1596 for init_desc, footer_line, expected_desc in [
1597 # Use unique desc first lines for easy test failure identification.
1598 ('foo', 'R=one', 'foo\n\nR=one'),
1599 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1600 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1601 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1602 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1603 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1604 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1605 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1606 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1607 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1608 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1609 ]:
1610 desc = git_cl.ChangeDescription(init_desc)
1611 desc.append_footer(footer_line)
1612 self.assertEqual(desc.description, expected_desc)
1613
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001614 def test_update_reviewers(self):
1615 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001616 ('foo', [], [],
1617 'foo'),
1618 ('foo\nR=xx', [], [],
1619 'foo\nR=xx'),
1620 ('foo\nTBR=xx', [], [],
1621 'foo\nTBR=xx'),
1622 ('foo', ['a@c'], [],
1623 'foo\n\nR=a@c'),
1624 ('foo\nR=xx', ['a@c'], [],
1625 'foo\n\nR=a@c, xx'),
1626 ('foo\nTBR=xx', ['a@c'], [],
1627 'foo\n\nR=a@c\nTBR=xx'),
1628 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1629 'foo\n\nR=a@c, yy\nTBR=xx'),
1630 ('foo\nBUG=', ['a@c'], [],
1631 'foo\nBUG=\nR=a@c'),
1632 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1633 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1634 ('foo', ['a@c', 'b@c'], [],
1635 'foo\n\nR=a@c, b@c'),
1636 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1637 'foo\nBar\n\nR=c@c\nBUG='),
1638 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1639 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001640 # Same as the line before, but full of whitespaces.
1641 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001642 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001643 'foo\nBar\n\nR=c@c\n BUG =',
1644 ),
1645 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001646 ('foo BUG=allo R=joe ', ['c@c'], [],
1647 'foo BUG=allo R=joe\n\nR=c@c'),
1648 # Redundant TBRs get promoted to Rs
1649 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1650 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001651 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001652 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001653 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001654 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001655 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001656 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001657 actual.append(obj.description)
1658 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001659
Nodir Turakulov23b82142017-11-16 11:04:25 -08001660 def test_get_hash_tags(self):
1661 cases = [
1662 ('', []),
1663 ('a', []),
1664 ('[a]', ['a']),
1665 ('[aa]', ['aa']),
1666 ('[a ]', ['a']),
1667 ('[a- ]', ['a']),
1668 ('[a- b]', ['a-b']),
1669 ('[a--b]', ['a-b']),
1670 ('[a', []),
1671 ('[a]x', ['a']),
1672 ('[aa]x', ['aa']),
1673 ('[a b]', ['a-b']),
1674 ('[a b]', ['a-b']),
1675 ('[a__b]', ['a-b']),
1676 ('[a] x', ['a']),
1677 ('[a][b]', ['a', 'b']),
1678 ('[a] [b]', ['a', 'b']),
1679 ('[a][b]x', ['a', 'b']),
1680 ('[a][b] x', ['a', 'b']),
1681 ('[a]\n[b]', ['a']),
1682 ('[a\nb]', []),
1683 ('[a][', ['a']),
1684 ('Revert "[a] feature"', ['a']),
1685 ('Reland "[a] feature"', ['a']),
1686 ('Revert: [a] feature', ['a']),
1687 ('Reland: [a] feature', ['a']),
1688 ('Revert "Reland: [a] feature"', ['a']),
1689 ('Foo: feature', ['foo']),
1690 ('Foo Bar: feature', ['foo-bar']),
1691 ('Revert "Foo bar: feature"', ['foo-bar']),
1692 ('Reland "Foo bar: feature"', ['foo-bar']),
1693 ]
1694 for desc, expected in cases:
1695 change_desc = git_cl.ChangeDescription(desc)
1696 actual = change_desc.get_hash_tags()
1697 self.assertEqual(
1698 actual,
1699 expected,
1700 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1701
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001702 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001703 self.assertEqual(None, git_cl.GetTargetRef(None,
1704 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001705 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001706
wittman@chromium.org455dc922015-01-26 20:15:50 +00001707 # Check default target refs for branches.
1708 self.assertEqual('refs/heads/master',
1709 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001710 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001711 self.assertEqual('refs/heads/master',
1712 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001713 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001714 self.assertEqual('refs/heads/master',
1715 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001716 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001717 self.assertEqual('refs/branch-heads/123',
1718 git_cl.GetTargetRef('origin',
1719 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001720 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001721 self.assertEqual('refs/diff/test',
1722 git_cl.GetTargetRef('origin',
1723 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001724 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001725 self.assertEqual('refs/heads/chrome/m42',
1726 git_cl.GetTargetRef('origin',
1727 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001728 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001729
1730 # Check target refs for user-specified target branch.
1731 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1732 'refs/remotes/branch-heads/123'):
1733 self.assertEqual('refs/branch-heads/123',
1734 git_cl.GetTargetRef('origin',
1735 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001736 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001737 for branch in ('origin/master', 'remotes/origin/master',
1738 'refs/remotes/origin/master'):
1739 self.assertEqual('refs/heads/master',
1740 git_cl.GetTargetRef('origin',
1741 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001742 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001743 for branch in ('master', 'heads/master', 'refs/heads/master'):
1744 self.assertEqual('refs/heads/master',
1745 git_cl.GetTargetRef('origin',
1746 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001747 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001748
wychen@chromium.orga872e752015-04-28 23:42:18 +00001749 def test_patch_when_dirty(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001750 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001751 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1752 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1753
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001754 @staticmethod
1755 def _get_gerrit_codereview_server_calls(branch, value=None,
1756 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001757 detect_branch=True,
1758 detect_server=True):
Edward Lemur125d60a2019-09-13 18:25:41 +00001759 """Returns calls executed by Changelist.GetCodereviewServer.
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001760
1761 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1762 """
1763 calls = []
1764 if detect_branch:
1765 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001766 if detect_server:
1767 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1768 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001769 if value is None:
1770 calls += [
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001771 ((['git', 'config', 'branch.' + branch + '.merge'],),
1772 'refs/heads' + branch),
1773 ((['git', 'config', 'branch.' + branch + '.remote'],),
1774 'origin'),
1775 ((['git', 'config', 'remote.origin.url'],),
1776 'https://%s.googlesource.com/my/repo' % git_short_host),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001777 ]
1778 return calls
1779
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001780 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001781 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001782 detect_gerrit_server=False,
1783 actual_codereview=None,
1784 codereview_in_url=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001785 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
wychen@chromium.orga872e752015-04-28 23:42:18 +00001786 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1787
tandriidf09a462016-08-18 16:23:55 -07001788 if new_branch:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001789 self.calls = [((['git', 'new-branch', 'master'],), '')]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001790
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001791 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001792 self.calls += [
1793 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001794 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001795 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001796
1797 if not force_codereview and not codereview_in_url:
1798 # These calls detect codereview to use.
1799 self.calls += [
1800 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001801 ]
1802 if detect_gerrit_server:
1803 self.calls += self._get_gerrit_codereview_server_calls(
1804 'master', git_short_host=git_short_host,
1805 detect_branch=not new_branch and force_codereview)
1806 actual_codereview = 'gerrit'
1807
1808 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001809 self.calls += [
1810 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001811 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001812 {
1813 'current_revision': '7777777777',
1814 'revisions': {
1815 '1111111111': {
1816 '_number': 1,
1817 'fetch': {'http': {
1818 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1819 'ref': 'refs/changes/56/123456/1',
1820 }},
1821 },
1822 '7777777777': {
1823 '_number': 7,
1824 'fetch': {'http': {
1825 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1826 'ref': 'refs/changes/56/123456/7',
1827 }},
1828 },
1829 },
1830 }),
1831 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001832
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001833 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001834 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001835 self.calls += [
1836 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1837 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001838 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001839 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001840 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001841 ((['git', 'config', 'branch.master.gerritserver',
1842 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001843 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001844 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1845 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1846 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001847 ]
1848 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1849
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001850 def test_patch_gerrit_new_branch(self):
1851 self._patch_common(
1852 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1853 self.calls += [
1854 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1855 'refs/changes/56/123456/7'],), ''),
1856 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1857 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1858 ''),
1859 ((['git', 'config', 'branch.master.gerritserver',
1860 'https://chromium-review.googlesource.com'],), ''),
1861 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1862 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1863 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1864 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1865 ]
1866 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1867
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001868 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001869 self._patch_common(
1870 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001871 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001872 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001873 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001874 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001875 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001876 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001877 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001878 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001879 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001880 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1881 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1882 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001883 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001884 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001885
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001886 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001887 self.calls += self._get_gerrit_codereview_server_calls(
1888 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001889 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001890 actual_codereview='gerrit', git_short_host='else',
1891 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001892 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001893 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001894 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001895 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001896 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001897 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001898 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001899 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001900 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001901 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1902 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1903 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001904 ]
1905 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001906 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001907
Aaron Gable697a91b2018-01-19 15:20:15 -08001908 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001909 self.calls += self._get_gerrit_codereview_server_calls(
1910 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001911 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001912 actual_codereview='gerrit', git_short_host='else',
1913 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001914 self.calls += [
1915 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1916 'refs/changes/56/123456/1'],), ''),
1917 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1918 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1919 ''),
1920 ((['git', 'config', 'branch.master.gerritserver',
1921 'https://else-review.googlesource.com'],), ''),
1922 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1923 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1924 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1925 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1926 ]
1927 self.assertEqual(git_cl.main(
1928 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1929 0)
1930
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001931 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001932 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001933 self.calls += [
1934 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001935 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001936 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1937 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1938 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001939 ]
1940 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001941 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001942
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001943 def test_patch_gerrit_not_exists(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001944
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001945 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001946 raise git_cl.gerrit_util.GerritError(404, '')
1947 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1948
tandriic2405f52016-10-10 08:13:15 -07001949 self.calls = [
1950 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001951 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1952 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1953 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1954 ((['git', 'config', 'remote.origin.url'],),
1955 'https://chromium.googlesource.com/my/repo'),
1956 ((['DieWithError',
1957 'change 123456 at https://chromium-review.googlesource.com does not '
1958 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001959 ]
1960 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001961 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001962
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001963 def _checkout_calls(self):
1964 return [
1965 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001966 'branch\\..*\\.gerritissue'], ),
1967 ('branch.ger-branch.gerritissue 123456\n'
1968 'branch.gbranch654.gerritissue 654321\n')),
1969 ]
1970
1971 def test_checkout_gerrit(self):
1972 """Tests git cl checkout <issue>."""
1973 self.calls = self._checkout_calls()
1974 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1975 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1976
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001977 def test_checkout_not_found(self):
1978 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001979 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001980 self.calls = self._checkout_calls()
1981 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1982
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001983 def test_checkout_no_branch_issues(self):
1984 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001985 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001986 self.calls = [
1987 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001988 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001989 ]
1990 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1991
tandrii@chromium.org28253532016-04-14 13:46:56 +00001992 def _test_gerrit_ensure_authenticated_common(self, auth,
1993 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001994 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1995 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1996 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11001997 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001998 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
Edward Lemurf38bc172019-09-03 21:02:13 +00001999 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00002000 cl.branch = 'master'
2001 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002002 return cl
2003
2004 def test_gerrit_ensure_authenticated_missing(self):
2005 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002006 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002007 })
2008 self.calls.append(
2009 ((['DieWithError',
2010 'Credentials for the following hosts are required:\n'
2011 ' chromium-review.googlesource.com\n'
2012 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002013 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002014 'https://chromium-review.googlesource.com/new-password'],), ''),)
2015 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2016
2017 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00002018 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002019 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002020 'chromium.googlesource.com':
2021 ('git-one.example.com', None, 'secret1'),
2022 'chromium-review.googlesource.com':
2023 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002024 })
2025 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002026 (('ask_for_data', 'If you know what you are doing '
2027 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002028 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2029
2030 def test_gerrit_ensure_authenticated_ok(self):
2031 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002032 'chromium.googlesource.com':
2033 ('git-same.example.com', None, 'secret'),
2034 'chromium-review.googlesource.com':
2035 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002036 })
2037 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2038
tandrii@chromium.org28253532016-04-14 13:46:56 +00002039 def test_gerrit_ensure_authenticated_skipped(self):
2040 cl = self._test_gerrit_ensure_authenticated_common(
2041 auth={}, skip_auth_check=True)
2042 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2043
Eric Boren2fb63102018-10-05 13:05:03 +00002044 def test_gerrit_ensure_authenticated_bearer_token(self):
2045 cl = self._test_gerrit_ensure_authenticated_common(auth={
2046 'chromium.googlesource.com':
2047 ('', None, 'secret'),
2048 'chromium-review.googlesource.com':
2049 ('', None, 'secret'),
2050 })
2051 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2052 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2053 'chromium.googlesource.com')
2054 self.assertTrue('Bearer' in header)
2055
Daniel Chengcf6269b2019-05-18 01:02:12 +00002056 def test_gerrit_ensure_authenticated_non_https(self):
2057 self.calls = [
2058 ((['git', 'config', '--bool',
2059 'gerrit.skip-ensure-authenticated'],), CERR1),
2060 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
2061 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2062 ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
2063 ]
2064 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2065 CookiesAuthenticatorMockFactory(hosts_with_creds={}))
Edward Lemurf38bc172019-09-03 21:02:13 +00002066 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00002067 cl.branch = 'master'
2068 cl.branchref = 'refs/heads/master'
2069 cl.lookedup_issue = True
2070 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2071
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002072 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002073 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002074 lambda h, i, labels, notify=None:
2075 self._mocked_call(['SetReview', h, i, labels, notify]))
2076
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002077 self.calls = [
2078 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002079 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002080 ((['git', 'config', 'branch.feature.gerritserver'],),
2081 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002082 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2083 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2084 ((['git', 'config', 'remote.origin.url'],),
2085 'https://chromium.googlesource.com/infra/infra.git'),
2086 ((['SetReview', 'chromium-review.googlesource.com',
2087 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002088 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002089 ]
tandriid9e5ce52016-07-13 02:32:59 -07002090
2091 def test_cmd_set_commit_gerrit_clear(self):
2092 self._cmd_set_commit_gerrit_common(0)
2093 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2094
2095 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002096 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002097 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2098
tandriid9e5ce52016-07-13 02:32:59 -07002099 def test_cmd_set_commit_gerrit(self):
2100 self._cmd_set_commit_gerrit_common(2)
2101 self.assertEqual(0, git_cl.main(['set-commit']))
2102
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002103 def test_description_display(self):
2104 out = StringIO.StringIO()
2105 self.mock(git_cl.sys, 'stdout', out)
2106
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002107 self.mock(git_cl, 'Changelist', ChangelistMock)
2108 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002109
2110 self.assertEqual(0, git_cl.main(['description', '-d']))
2111 self.assertEqual('foo\n', out.getvalue())
2112
iannucci3c972b92016-08-17 13:24:10 -07002113 def test_StatusFieldOverrideIssueMissingArgs(self):
2114 out = StringIO.StringIO()
2115 self.mock(git_cl.sys, 'stderr', out)
2116
2117 try:
2118 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2119 except SystemExit as ex:
2120 self.assertEqual(ex.code, 2)
Edward Lemurf38bc172019-09-03 21:02:13 +00002121 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002122
2123 out = StringIO.StringIO()
2124 self.mock(git_cl.sys, 'stderr', out)
2125
2126 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002127 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07002128 except SystemExit as ex:
2129 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002130 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002131
2132 def test_StatusFieldOverrideIssue(self):
2133 out = StringIO.StringIO()
2134 self.mock(git_cl.sys, 'stdout', out)
2135
2136 def assertIssue(cl_self, *_args):
2137 self.assertEquals(cl_self.issue, 1)
2138 return 'foobar'
2139
2140 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07002141 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002142 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002143 0)
iannucci3c972b92016-08-17 13:24:10 -07002144 self.assertEqual(out.getvalue(), 'foobar\n')
2145
iannuccie53c9352016-08-17 14:40:40 -07002146 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002147
iannuccie53c9352016-08-17 14:40:40 -07002148 def assertIssue(cl_self, *_args):
2149 self.assertEquals(cl_self.issue, 1)
2150 return 'foobar'
2151
2152 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2153 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07002154 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002155 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002156
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002157 def test_description(self):
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002158 out = StringIO.StringIO()
2159 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002160 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002161 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2162 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2163 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2164 ((['git', 'config', 'remote.origin.url'],),
2165 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002166 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002167 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002168 {
2169 'current_revision': 'sha1',
2170 'revisions': {'sha1': {
2171 'commit': {'message': 'foobar'},
2172 }},
2173 }),
2174 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002175 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002176 'description',
2177 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2178 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002179 self.assertEqual('foobar\n', out.getvalue())
2180
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002181 def test_description_set_raw(self):
2182 out = StringIO.StringIO()
2183 self.mock(git_cl.sys, 'stdout', out)
2184
2185 self.mock(git_cl, 'Changelist', ChangelistMock)
2186 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
2187
2188 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2189 self.assertEqual('hihi', ChangelistMock.desc)
2190
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002191 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002192 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002193
2194 def RunEditor(desc, _, **kwargs):
2195 self.assertEquals(
2196 '# Enter a description of the change.\n'
2197 '# This will be displayed on the codereview site.\n'
2198 '# The first line will also be used as the subject of the review.\n'
2199 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002200 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002201 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002202 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002203 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002204 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002205
dsansomee2d6fd92016-09-08 00:10:47 -07002206 def UpdateDescriptionRemote(_, desc, force=False):
Aaron Gable3a16ed12017-03-23 10:51:55 -07002207 self.assertEquals(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002208
2209 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2210 self.mock(git_cl.Changelist, 'GetDescription',
2211 lambda *args: current_desc)
Edward Lemur125d60a2019-09-13 18:25:41 +00002212 self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002213 UpdateDescriptionRemote)
2214 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2215
2216 self.calls = [
2217 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002218 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002219 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2220 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002221 ((['git', 'config', 'core.editor'],), 'vi'),
2222 ]
2223 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2224
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002225 def test_description_set_stdin(self):
2226 out = StringIO.StringIO()
2227 self.mock(git_cl.sys, 'stdout', out)
2228
2229 self.mock(git_cl, 'Changelist', ChangelistMock)
2230 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
2231
2232 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2233 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2234
kmarshall3bff56b2016-06-06 18:31:47 -07002235 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07002236 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2237
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002238 self.calls = [
2239 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002240 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002241 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2242 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002243 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002244 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002245
kmarshall3bff56b2016-06-06 18:31:47 -07002246 self.mock(git_cl, 'get_cl_statuses',
2247 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002248 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2249 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2250 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002251
2252 self.assertEqual(0, git_cl.main(['archive', '-f']))
2253
2254 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07002255 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002256 self.calls = [
2257 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2258 'refs/heads/master'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002259 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2260 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002261
kmarshall9249e012016-08-23 12:02:16 -07002262 self.mock(git_cl, 'get_cl_statuses',
2263 lambda branches, fine_grained, max_processes:
2264 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2265
2266 self.assertEqual(1, git_cl.main(['archive', '-f']))
2267
2268 def test_archive_dry_run(self):
2269 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2270
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002271 self.calls = [
2272 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2273 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002274 ((['git', 'symbolic-ref', 'HEAD'],), 'master')
2275 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002276
2277 self.mock(git_cl, 'get_cl_statuses',
2278 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002279 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2280 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2281 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002282
kmarshall9249e012016-08-23 12:02:16 -07002283 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2284
2285 def test_archive_no_tags(self):
2286 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2287
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002288 self.calls = [
2289 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2290 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002291 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2292 ((['git', 'branch', '-D', 'foo'],), '')
2293 ]
kmarshall9249e012016-08-23 12:02:16 -07002294
2295 self.mock(git_cl, 'get_cl_statuses',
2296 lambda branches, fine_grained, max_processes:
2297 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2298 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2299 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2300
2301 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002302
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002303 def test_cmd_issue_erase_existing(self):
2304 out = StringIO.StringIO()
2305 self.mock(git_cl.sys, 'stdout', out)
2306 self.calls = [
2307 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002308 # Let this command raise exception (retcode=1) - it should be ignored.
2309 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002310 CERR1),
2311 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2312 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002313 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2314 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2315 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002316 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002317 ]
2318 self.assertEqual(0, git_cl.main(['issue', '0']))
2319
Aaron Gable400e9892017-07-12 15:31:21 -07002320 def test_cmd_issue_erase_existing_with_change_id(self):
2321 out = StringIO.StringIO()
2322 self.mock(git_cl.sys, 'stdout', out)
2323 self.mock(git_cl.Changelist, 'GetDescription',
2324 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2325 self.calls = [
2326 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Aaron Gable400e9892017-07-12 15:31:21 -07002327 # Let this command raise exception (retcode=1) - it should be ignored.
2328 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2329 CERR1),
2330 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2331 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2332 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2333 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2334 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002335 ((['git', 'log', '-1', '--format=%B'],),
2336 'This is a description\n\nChange-Id: Ideadbeef'),
2337 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002338 ]
2339 self.assertEqual(0, git_cl.main(['issue', '0']))
2340
phajdan.jre328cf92016-08-22 04:12:17 -07002341 def test_cmd_issue_json(self):
2342 out = StringIO.StringIO()
2343 self.mock(git_cl.sys, 'stdout', out)
2344 self.calls = [
2345 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002346 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2347 ((['git', 'config', 'branch.feature.gerritserver'],),
2348 'https://chromium-review.googlesource.com'),
phajdan.jre328cf92016-08-22 04:12:17 -07002349 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002350 {'issue': 123,
2351 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002352 ''),
2353 ]
2354 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2355
tandrii16e0b4e2016-06-07 10:34:28 -07002356 def _common_GerritCommitMsgHookCheck(self):
2357 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2358 self.mock(git_cl.os.path, 'abspath',
2359 lambda path: self._mocked_call(['abspath', path]))
2360 self.mock(git_cl.os.path, 'exists',
2361 lambda path: self._mocked_call(['exists', path]))
2362 self.mock(git_cl.gclient_utils, 'FileRead',
2363 lambda path: self._mocked_call(['FileRead', path]))
2364 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2365 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2366 self.calls = [
2367 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2368 ((['abspath', '../'],), '/abs/git_repo_root'),
2369 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002370 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002371
2372 def test_GerritCommitMsgHookCheck_custom_hook(self):
2373 cl = self._common_GerritCommitMsgHookCheck()
2374 self.calls += [
2375 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2376 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2377 '#!/bin/sh\necho "custom hook"')
2378 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002379 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002380
2381 def test_GerritCommitMsgHookCheck_not_exists(self):
2382 cl = self._common_GerritCommitMsgHookCheck()
2383 self.calls += [
2384 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2385 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002386 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002387
2388 def test_GerritCommitMsgHookCheck(self):
2389 cl = self._common_GerritCommitMsgHookCheck()
2390 self.calls += [
2391 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2392 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2393 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002394 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002395 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2396 ''),
2397 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002398 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002399
tandriic4344b52016-08-29 06:04:54 -07002400 def test_GerritCmdLand(self):
2401 self.calls += [
2402 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2403 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2404 'deadbeaf'),
2405 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2406 ((['git', 'config', 'branch.feature.gerritserver'],),
2407 'chromium-review.googlesource.com'),
2408 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002409 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002410 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002411 'labels': {},
2412 'current_revision': 'deadbeaf',
2413 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002414 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002415 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002416 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002417 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2418 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002419 cl.SubmitIssue = lambda wait_for_merge: None
tandrii8da412c2016-09-07 16:01:07 -07002420 out = StringIO.StringIO()
2421 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002422 self.assertEqual(0, cl.CMDLand(force=True,
2423 bypass_hooks=True,
2424 verbose=True,
2425 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002426 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002427 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002428
tandrii221ab252016-10-06 08:12:04 -07002429 BUILDBUCKET_BUILDS_MAP = {
Quinten Yearsleya563d722017-12-11 16:36:54 -08002430 '9000': {
2431 'id': '9000',
2432 'bucket': 'master.x.y',
2433 'created_by': 'user:someone@chromium.org',
2434 'created_ts': '147200002222000',
2435 'experimental': False,
2436 'parameters_json': json.dumps({
2437 'builder_name': 'my-bot',
2438 'properties': {'category': 'cq'},
2439 }),
2440 'status': 'STARTED',
2441 'tags': [
2442 'build_address:x.y/my-bot/2',
2443 'builder:my-bot',
2444 'experimental:false',
2445 'user_agent:cq',
2446 ],
2447 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2448 },
2449 '8000': {
2450 'id': '8000',
2451 'bucket': 'master.x.y',
2452 'created_by': 'user:someone@chromium.org',
2453 'created_ts': '147200001111000',
2454 'experimental': False,
2455 'failure_reason': 'BUILD_FAILURE',
2456 'parameters_json': json.dumps({
2457 'builder_name': 'my-bot',
2458 'properties': {'category': 'cq'},
2459 }),
2460 'result_details_json': json.dumps({
2461 'properties': {'buildnumber': 1},
2462 }),
2463 'result': 'FAILURE',
2464 'status': 'COMPLETED',
2465 'tags': [
2466 'build_address:x.y/my-bot/1',
2467 'builder:my-bot',
2468 'experimental:false',
2469 'user_agent:cq',
2470 ],
2471 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2472 },
2473 }
tandrii221ab252016-10-06 08:12:04 -07002474
2475 def test_write_try_results_json(self):
2476 expected_output = [
Quinten Yearsleya563d722017-12-11 16:36:54 -08002477 {
2478 'bucket': 'master.x.y',
2479 'buildbucket_id': '8000',
2480 'builder_name': 'my-bot',
2481 'created_ts': '147200001111000',
2482 'experimental': False,
2483 'failure_reason': 'BUILD_FAILURE',
2484 'result': 'FAILURE',
2485 'status': 'COMPLETED',
2486 'tags': [
2487 'build_address:x.y/my-bot/1',
2488 'builder:my-bot',
2489 'experimental:false',
2490 'user_agent:cq',
2491 ],
2492 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2493 },
2494 {
2495 'bucket': 'master.x.y',
2496 'buildbucket_id': '9000',
2497 'builder_name': 'my-bot',
2498 'created_ts': '147200002222000',
2499 'experimental': False,
2500 'failure_reason': None,
2501 'result': None,
2502 'status': 'STARTED',
2503 'tags': [
2504 'build_address:x.y/my-bot/2',
2505 'builder:my-bot',
2506 'experimental:false',
2507 'user_agent:cq',
2508 ],
2509 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2510 },
tandrii221ab252016-10-06 08:12:04 -07002511 ]
2512 self.calls = [(('write_json', 'output.json', expected_output), '')]
2513 git_cl.write_try_results_json('output.json', self.BUILDBUCKET_BUILDS_MAP)
2514
tandrii45b2a582016-10-11 03:14:16 -07002515 def _setup_fetch_try_jobs(self, most_recent_patchset=20001):
tandrii221ab252016-10-06 08:12:04 -07002516 out = StringIO.StringIO()
2517 self.mock(sys, 'stdout', out)
tandrii45b2a582016-10-11 03:14:16 -07002518 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
2519 lambda *args: most_recent_patchset)
tandrii221ab252016-10-06 08:12:04 -07002520 self.mock(git_cl.auth, 'get_authenticator_for_host', lambda host, _cfg:
2521 self._mocked_call(['get_authenticator_for_host', host]))
2522 self.mock(git_cl, '_buildbucket_retry', lambda *_, **__:
2523 self._mocked_call(['_buildbucket_retry']))
tandrii45b2a582016-10-11 03:14:16 -07002524
tandrii45b2a582016-10-11 03:14:16 -07002525 def _setup_fetch_try_jobs_gerrit(self, *request_results):
2526 self._setup_fetch_try_jobs(most_recent_patchset=13)
2527 self.calls += [
2528 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii45b2a582016-10-11 03:14:16 -07002529 ((['git', 'config', 'branch.feature.gerritissue'],), '1'),
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002530 # TODO(tandrii): Uncomment the below if we decide to support checking
2531 # patchsets for Gerrit.
tandrii45b2a582016-10-11 03:14:16 -07002532 # Simulate that Gerrit has more patchsets than local.
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002533 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'),
tandrii45b2a582016-10-11 03:14:16 -07002534 ((['git', 'config', 'branch.feature.gerritserver'],),
2535 'https://x-review.googlesource.com'),
2536 ((['get_authenticator_for_host', 'x-review.googlesource.com'],),
2537 AuthenticatorMock()),
2538 ] + [((['_buildbucket_retry'],), r) for r in request_results]
2539
2540 def test_fetch_try_jobs_none_gerrit(self):
2541 self._setup_fetch_try_jobs_gerrit({})
2542 self.assertEqual(0, git_cl.main(['try-results']))
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002543 # TODO(tandrii): Uncomment the below if we decide to support checking
2544 # patchsets for Gerrit.
2545 # self.assertRegexpMatches(
2546 # sys.stdout.getvalue(),
2547 # r'Warning: Codereview server has newer patchsets \(13\)')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002548 self.assertRegexpMatches(sys.stdout.getvalue(), 'No tryjobs')
tandrii45b2a582016-10-11 03:14:16 -07002549
2550 def test_fetch_try_jobs_some_gerrit(self):
2551 self._setup_fetch_try_jobs_gerrit({
2552 'builds': self.BUILDBUCKET_BUILDS_MAP.values(),
2553 })
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002554 # TODO(tandrii): Uncomment the below if we decide to support checking
2555 # patchsets for Gerrit.
2556 # self.calls.remove(
2557 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'))
tandrii45b2a582016-10-11 03:14:16 -07002558 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '5']))
2559
2560 # ... and doesn't result in warning.
2561 self.assertNotRegexpMatches(sys.stdout.getvalue(), 'Warning')
2562 self.assertRegexpMatches(sys.stdout.getvalue(), '^Failures:')
tandrii221ab252016-10-06 08:12:04 -07002563 self.assertRegexpMatches(sys.stdout.getvalue(), 'Started:')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002564 self.assertRegexpMatches(sys.stdout.getvalue(), '2 tryjobs')
tandrii221ab252016-10-06 08:12:04 -07002565
Quinten Yearsley983111f2019-09-26 17:18:48 +00002566 def test_filter_failed_none(self):
2567 self.assertEqual(git_cl._filter_failed({}), {})
2568
2569 def test_filter_failed_some(self):
2570 builds = {
2571 '9000': {
2572 'id': '9000',
2573 'bucket': 'luci.chromium.try',
2574 'project': 'chromium',
2575 'created_by': 'user:someone@chromium.org',
2576 'created_ts': '147200002222000',
2577 'experimental': False,
2578 'parameters_json': json.dumps({
2579 'builder_name': 'my-bot',
2580 'properties': {'category': 'cq'},
2581 }),
2582 'status': 'COMPLETED',
2583 'result': 'FAILURE',
2584 }
2585 }
2586 self.assertEqual(
2587 git_cl._filter_failed(builds),
2588 {'chromium/try': {'my-bot': []}})
2589
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002590 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemur125d60a2019-09-13 18:25:41 +00002591 self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002592
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002593 def test_gerrit_change_detail_cache_simple(self):
2594 self._mock_gerrit_changes_for_detail_cache()
2595 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002596 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2597 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2598 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002599 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002600 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002601 cl1._cached_remote_url = (
2602 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002603 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002604 cl2._cached_remote_url = (
2605 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002606 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2607 self.assertEqual(cl1._GetChangeDetail(), 'a')
2608 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2609 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2610 self.assertEqual(cl1._GetChangeDetail(), 'a')
2611 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002612
2613 def test_gerrit_change_detail_cache_options(self):
2614 self._mock_gerrit_changes_for_detail_cache()
2615 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002616 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2617 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2618 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2619 # no longer in cache.
2620 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002621 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002622 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002623 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002624 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2625 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2626 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2627 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2628 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2629 self.assertEqual(cl._GetChangeDetail(), 'cab')
2630
2631 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2632 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2633 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2634 self.assertEqual(cl._GetChangeDetail(), 'cab')
2635
2636 # Finally, no_cache should invalidate all caches for given change.
2637 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2638 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2639
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002640 def test_gerrit_description_caching(self):
2641 def gen_detail(rev, desc):
2642 return {
2643 'current_revision': rev,
2644 'revisions': {rev: {'commit': {'message': desc}}}
2645 }
2646 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002647 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002648 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2649 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002650 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002651 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2652 gen_detail('rev2', 'desc2')),
2653 ]
2654
2655 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002656 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002657 cl._cached_remote_url = (
2658 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002659 self.assertEqual(cl.GetDescription(), 'desc1')
2660 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2661 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002662
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002663 def test_print_current_creds(self):
2664 class CookiesAuthenticatorMock(object):
2665 def __init__(self):
2666 self.gitcookies = {
2667 'host.googlesource.com': ('user', 'pass'),
2668 'host-review.googlesource.com': ('user', 'pass'),
2669 }
2670 self.netrc = self
2671 self.netrc.hosts = {
2672 'github.com': ('user2', None, 'pass2'),
2673 'host2.googlesource.com': ('user3', None, 'pass'),
2674 }
2675 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2676 CookiesAuthenticatorMock)
2677 self.mock(sys, 'stdout', StringIO.StringIO())
2678 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2679 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2680 ' Host\t User\t Which file',
2681 '============================\t=====\t===========',
2682 'host-review.googlesource.com\t user\t.gitcookies',
2683 ' host.googlesource.com\t user\t.gitcookies',
2684 ' host2.googlesource.com\tuser3\t .netrc',
2685 ])
2686 sys.stdout.buf = ''
2687 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2688 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2689 ' Host\tUser\t Which file',
2690 '============================\t====\t===========',
2691 'host-review.googlesource.com\tuser\t.gitcookies',
2692 ' host.googlesource.com\tuser\t.gitcookies',
2693 ])
2694
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002695 def _common_creds_check_mocks(self):
2696 def exists_mock(path):
2697 dirname = os.path.dirname(path)
2698 if dirname == os.path.expanduser('~'):
2699 dirname = '~'
2700 base = os.path.basename(path)
2701 if base in ('.netrc', '.gitcookies'):
2702 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2703 # git cl also checks for existence other files not relevant to this test.
2704 return None
2705 self.mock(os.path, 'exists', exists_mock)
2706 self.mock(sys, 'stdout', StringIO.StringIO())
2707
2708 def test_creds_check_gitcookies_not_configured(self):
2709 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002710 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002711 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002712 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002713 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002714 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2715 (('os.path.exists', '~/.netrc'), True),
2716 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2717 'or Ctrl+C to abort'), ''),
2718 ((['git', 'config', '--global', 'http.cookiefile',
2719 os.path.expanduser('~/.gitcookies')], ), ''),
2720 ]
2721 self.assertEqual(0, git_cl.main(['creds-check']))
2722 self.assertRegexpMatches(
2723 sys.stdout.getvalue(),
2724 '^You seem to be using outdated .netrc for git credentials:')
2725 self.assertRegexpMatches(
2726 sys.stdout.getvalue(),
2727 '\nConfigured git to use .gitcookies from')
2728
2729 def test_creds_check_gitcookies_configured_custom_broken(self):
2730 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002731 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002732 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002733 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002734 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002735 ((['git', 'config', '--global', 'http.cookiefile'],),
2736 '/custom/.gitcookies'),
2737 (('os.path.exists', '/custom/.gitcookies'), False),
2738 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2739 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2740 ((['git', 'config', '--global', 'http.cookiefile',
2741 os.path.expanduser('~/.gitcookies')], ), ''),
2742 ]
2743 self.assertEqual(0, git_cl.main(['creds-check']))
2744 self.assertRegexpMatches(
2745 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002746 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002747 self.assertRegexpMatches(
2748 sys.stdout.getvalue(),
2749 'However, your configured .gitcookies file is missing.')
2750
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002751 def test_git_cl_comment_add_gerrit(self):
2752 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002753 lambda host, change, msg, ready:
2754 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002755 self.calls = [
2756 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2757 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2758 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2759 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2760 'origin/master'),
2761 ((['git', 'config', 'remote.origin.url'],),
2762 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002763 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2764 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002765 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002766 ]
2767 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2768 '-a', 'msg']))
2769
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002770 def test_git_cl_comments_fetch_gerrit(self):
2771 self.mock(sys, 'stdout', StringIO.StringIO())
2772 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002773 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2774 ((['git', 'config', 'branch.foo.merge'],), ''),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002775 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2776 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2777 'origin/master'),
2778 ((['git', 'config', 'remote.origin.url'],),
2779 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002780 (('GetChangeDetail', 'chromium-review.googlesource.com',
2781 'infra%2Finfra~1',
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002782 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2783 'CURRENT_COMMIT']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002784 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002785 'current_revision': 'ba5eba11',
2786 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002787 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002788 '_number': 1,
2789 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002790 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002791 '_number': 2,
2792 },
2793 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002794 'messages': [
2795 {
2796 u'_revision_number': 1,
2797 u'author': {
2798 u'_account_id': 1111084,
2799 u'email': u'commit-bot@chromium.org',
2800 u'name': u'Commit Bot'
2801 },
2802 u'date': u'2017-03-15 20:08:45.000000000',
2803 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002804 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002805 u'tag': u'autogenerated:cq:dry-run'
2806 },
2807 {
2808 u'_revision_number': 2,
2809 u'author': {
2810 u'_account_id': 11151243,
2811 u'email': u'owner@example.com',
2812 u'name': u'owner'
2813 },
2814 u'date': u'2017-03-16 20:00:41.000000000',
2815 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2816 u'message': u'PTAL',
2817 },
2818 {
2819 u'_revision_number': 2,
2820 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002821 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002822 u'email': u'reviewer@example.com',
2823 u'name': u'reviewer'
2824 },
2825 u'date': u'2017-03-17 05:19:37.500000000',
2826 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2827 u'message': u'Patch Set 2: Code-Review+1',
2828 },
2829 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002830 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002831 (('GetChangeComments', 'chromium-review.googlesource.com',
2832 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002833 '/COMMIT_MSG': [
2834 {
2835 'author': {'email': u'reviewer@example.com'},
2836 'updated': u'2017-03-17 05:19:37.500000000',
2837 'patch_set': 2,
2838 'side': 'REVISION',
2839 'message': 'Please include a bug link',
2840 },
2841 ],
2842 'codereview.settings': [
2843 {
2844 'author': {'email': u'owner@example.com'},
2845 'updated': u'2017-03-16 20:00:41.000000000',
2846 'patch_set': 2,
2847 'side': 'PARENT',
2848 'line': 42,
2849 'message': 'I removed this because it is bad',
2850 },
2851 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002852 }),
2853 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2854 'infra%2Finfra~1'), {}),
2855 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002856 ] * 2 + [
2857 (('write_json', 'output.json', [
2858 {
2859 u'date': u'2017-03-16 20:00:41.000000',
2860 u'message': (
2861 u'PTAL\n' +
2862 u'\n' +
2863 u'codereview.settings\n' +
2864 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2865 u'c/1/2/codereview.settings#b42\n' +
2866 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002867 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002868 u'approval': False,
2869 u'disapproval': False,
2870 u'sender': u'owner@example.com'
2871 }, {
2872 u'date': u'2017-03-17 05:19:37.500000',
2873 u'message': (
2874 u'Patch Set 2: Code-Review+1\n' +
2875 u'\n' +
2876 u'/COMMIT_MSG\n' +
2877 u' PS2, File comment: https://chromium-review.googlesource' +
2878 u'.com/c/1/2//COMMIT_MSG#\n' +
2879 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002880 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002881 u'approval': False,
2882 u'disapproval': False,
2883 u'sender': u'reviewer@example.com'
2884 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002885 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002886 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002887 expected_comments_summary = [
2888 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002889 message=(
2890 u'PTAL\n' +
2891 u'\n' +
2892 u'codereview.settings\n' +
2893 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2894 u'c/1/2/codereview.settings#b42\n' +
2895 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002896 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002897 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002898 disapproval=False, approval=False, sender=u'owner@example.com'),
2899 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002900 message=(
2901 u'Patch Set 2: Code-Review+1\n' +
2902 u'\n' +
2903 u'/COMMIT_MSG\n' +
2904 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2905 u'c/1/2//COMMIT_MSG#\n' +
2906 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002907 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002908 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002909 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2910 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002911 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002912 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002913 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002914 self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
2915 self.assertEqual(
2916 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2917
2918 def test_git_cl_comments_robot_comments(self):
2919 # git cl comments also fetches robot comments (which are considered a type
2920 # of autogenerated comment), and unlike other types of comments, only robot
2921 # comments from the latest patchset are shown.
2922 self.mock(sys, 'stdout', StringIO.StringIO())
2923 self.calls = [
2924 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2925 ((['git', 'config', 'branch.foo.merge'],), ''),
2926 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2927 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2928 'origin/master'),
2929 ((['git', 'config', 'remote.origin.url'],),
2930 'https://chromium.googlesource.com/infra/infra'),
2931 (('GetChangeDetail', 'chromium-review.googlesource.com',
2932 'infra%2Finfra~1',
2933 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2934 'CURRENT_COMMIT']), {
2935 'owner': {'email': 'owner@example.com'},
2936 'current_revision': 'ba5eba11',
2937 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002938 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002939 '_number': 1,
2940 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002941 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002942 '_number': 2,
2943 },
2944 },
2945 'messages': [
2946 {
2947 u'_revision_number': 1,
2948 u'author': {
2949 u'_account_id': 1111084,
2950 u'email': u'commit-bot@chromium.org',
2951 u'name': u'Commit Bot'
2952 },
2953 u'date': u'2017-03-15 20:08:45.000000000',
2954 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2955 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2956 u'tag': u'autogenerated:cq:dry-run'
2957 },
2958 {
2959 u'_revision_number': 1,
2960 u'author': {
2961 u'_account_id': 123,
2962 u'email': u'tricium@serviceaccount.com',
2963 u'name': u'Tricium'
2964 },
2965 u'date': u'2017-03-16 20:00:41.000000000',
2966 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2967 u'message': u'(1 comment)',
2968 u'tag': u'autogenerated:tricium',
2969 },
2970 {
2971 u'_revision_number': 1,
2972 u'author': {
2973 u'_account_id': 123,
2974 u'email': u'tricium@serviceaccount.com',
2975 u'name': u'Tricium'
2976 },
2977 u'date': u'2017-03-16 20:00:41.000000000',
2978 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2979 u'message': u'(1 comment)',
2980 u'tag': u'autogenerated:tricium',
2981 },
2982 {
2983 u'_revision_number': 2,
2984 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002985 u'_account_id': 123,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002986 u'email': u'tricium@serviceaccount.com',
2987 u'name': u'reviewer'
2988 },
2989 u'date': u'2017-03-17 05:30:37.000000000',
2990 u'tag': u'autogenerated:tricium',
2991 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2992 u'message': u'(1 comment)',
2993 },
2994 ]
2995 }),
2996 (('GetChangeComments', 'chromium-review.googlesource.com',
2997 'infra%2Finfra~1'), {}),
2998 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2999 'infra%2Finfra~1'), {
3000 'codereview.settings': [
3001 {
3002 u'author': {u'email': u'tricium@serviceaccount.com'},
3003 u'updated': u'2017-03-17 05:30:37.000000000',
3004 u'robot_run_id': u'5565031076855808',
3005 u'robot_id': u'Linter/Category',
3006 u'tag': u'autogenerated:tricium',
3007 u'patch_set': 2,
3008 u'side': u'REVISION',
3009 u'message': u'Linter warning message text',
3010 u'line': 32,
3011 },
3012 ],
3013 }),
3014 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
3015 ]
3016 expected_comments_summary = [
3017 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
3018 message=(
3019 u'(1 comment)\n\ncodereview.settings\n'
3020 u' PS2, Line 32: https://chromium-review.googlesource.com/'
3021 u'c/1/2/codereview.settings#32\n'
3022 u' Linter warning message text\n'),
3023 sender=u'tricium@serviceaccount.com',
3024 autogenerated=True, approval=False, disapproval=False)
3025 ]
3026 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00003027 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00003028 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003029
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003030 def test_get_remote_url_with_mirror(self):
3031 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003032
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003033 def selective_os_path_isdir_mock(path):
3034 if path == '/cache/this-dir-exists':
3035 return self._mocked_call('os.path.isdir', path)
3036 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003037
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003038 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3039
3040 url = 'https://chromium.googlesource.com/my/repo'
3041 self.calls = [
3042 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3043 ((['git', 'config', 'branch.master.merge'],), 'master'),
3044 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3045 ((['git', 'config', 'remote.origin.url'],),
3046 '/cache/this-dir-exists'),
3047 (('os.path.isdir', '/cache/this-dir-exists'),
3048 True),
3049 # Runs in /cache/this-dir-exists.
3050 ((['git', 'config', 'remote.origin.url'],),
3051 url),
3052 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003053 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003054 self.assertEqual(cl.GetRemoteUrl(), url)
3055 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
3056
Edward Lemur298f2cf2019-02-22 21:40:39 +00003057 def test_get_remote_url_non_existing_mirror(self):
3058 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003059
Edward Lemur298f2cf2019-02-22 21:40:39 +00003060 def selective_os_path_isdir_mock(path):
3061 if path == '/cache/this-dir-doesnt-exist':
3062 return self._mocked_call('os.path.isdir', path)
3063 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003064
Edward Lemur298f2cf2019-02-22 21:40:39 +00003065 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3066 self.mock(logging, 'error',
3067 lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
3068
3069 self.calls = [
3070 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3071 ((['git', 'config', 'branch.master.merge'],), 'master'),
3072 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3073 ((['git', 'config', 'remote.origin.url'],),
3074 '/cache/this-dir-doesnt-exist'),
3075 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
3076 False),
3077 (('logging.error',
Daniel Bratell4a60db42019-09-16 17:02:52 +00003078 'Remote "origin" for branch "master" points to'
3079 ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00003080 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003081 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00003082 self.assertIsNone(cl.GetRemoteUrl())
3083
3084 def test_get_remote_url_misconfigured_mirror(self):
3085 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003086
Edward Lemur298f2cf2019-02-22 21:40:39 +00003087 def selective_os_path_isdir_mock(path):
3088 if path == '/cache/this-dir-exists':
3089 return self._mocked_call('os.path.isdir', path)
3090 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003091
Edward Lemur298f2cf2019-02-22 21:40:39 +00003092 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3093 self.mock(logging, 'error',
3094 lambda *a: self._mocked_call('logging.error', *a))
3095
3096 self.calls = [
3097 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3098 ((['git', 'config', 'branch.master.merge'],), 'master'),
3099 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3100 ((['git', 'config', 'remote.origin.url'],),
3101 '/cache/this-dir-exists'),
3102 (('os.path.isdir', '/cache/this-dir-exists'), True),
3103 # Runs in /cache/this-dir-exists.
3104 ((['git', 'config', 'remote.origin.url'],), ''),
3105 (('logging.error',
3106 'Remote "%(remote)s" for branch "%(branch)s" points to '
3107 '"%(cache_path)s", but it is misconfigured.\n'
3108 '"%(cache_path)s" must be a git repo and must have a remote named '
3109 '"%(remote)s" pointing to the git host.', {
3110 'remote': 'origin',
3111 'cache_path': '/cache/this-dir-exists',
3112 'branch': 'master'}
3113 ), None),
3114 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003115 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00003116 self.assertIsNone(cl.GetRemoteUrl())
3117
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003118 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003119 self.calls = [
3120 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3121 ((['git', 'config', 'branch.master.merge'],), 'master'),
3122 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3123 ((['git', 'config', 'remote.origin.url'],),
3124 'https://chromium.googlesource.com/a/my/repo.git/'),
3125 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003126 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003127 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3128
3129 def test_gerrit_change_identifier_without_project(self):
3130 self.calls = [
3131 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3132 ((['git', 'config', 'branch.master.merge'],), 'master'),
3133 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3134 ((['git', 'config', 'remote.origin.url'],), CERR1),
3135 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003136 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003137 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003138
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003139
Edward Lemur4c707a22019-09-24 21:13:43 +00003140class CMDTryTestCase(unittest.TestCase):
3141 def setUp(self):
3142 super(CMDTryTestCase, self).setUp()
3143 mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
3144 mock.patch('git_cl.uuid.uuid4', _constantFn('uuid4')).start()
3145 mock.patch('git_cl.Changelist.GetIssue', _constantFn(123456)).start()
3146 mock.patch('git_cl.Changelist.GetCodereviewServer',
3147 _constantFn('https://chromium-review.googlesource.com')).start()
3148 mock.patch('git_cl.Changelist.SetPatchset').start()
3149 mock.patch('git_cl.Changelist.GetPatchset', _constantFn(7)).start()
3150 mock.patch('git_cl.auth.get_authenticator_for_host', AuthenticatorMock())
3151 self.addCleanup(mock.patch.stopall)
3152
3153 @mock.patch('git_cl.Changelist._GetChangeDetail')
3154 @mock.patch('git_cl.Changelist.SetCQState')
3155 @mock.patch('git_cl._get_bucket_map', _constantFn({}))
3156 def testSetCQDryRunByDefault(self, mockSetCQState, mockGetChangeDetail):
3157 mockSetCQState.return_value = 0
3158 mockGetChangeDetail.return_value = {
3159 'project': 'depot_tools',
3160 'status': 'OPEN',
3161 'owner': {'email': 'owner@e.mail'},
3162 'current_revision': 'beeeeeef',
3163 'revisions': {
3164 'deadbeaf': {
3165 '_number': 6,
3166 },
3167 'beeeeeef': {
3168 '_number': 7,
3169 'fetch': {'http': {
3170 'url': 'https://chromium.googlesource.com/depot_tools',
3171 'ref': 'refs/changes/56/123456/7'
3172 }},
3173 },
3174 },
3175 }
3176
3177 self.assertEqual(0, git_cl.main(['try']))
3178 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3179 self.assertEqual(
3180 sys.stdout.getvalue(),
3181 'Scheduling CQ dry run on: '
3182 'https://chromium-review.googlesource.com/123456\n')
3183
3184 @mock.patch('git_cl.Changelist._GetChangeDetail')
3185 @mock.patch('git_cl._call_buildbucket')
3186 def testScheduleOnBuildbucket(self, mockCallBuildbucket, mockGetChangeDetail):
3187 mockCallBuildbucket.return_value = {}
3188 mockGetChangeDetail.return_value = {
3189 'project': 'depot_tools',
3190 'status': 'OPEN',
3191 'owner': {'email': 'owner@e.mail'},
3192 'current_revision': 'beeeeeef',
3193 'revisions': {
3194 'deadbeaf': {
3195 '_number': 6,
3196 },
3197 'beeeeeef': {
3198 '_number': 7,
3199 'fetch': {'http': {
3200 'url': 'https://chromium.googlesource.com/depot_tools',
3201 'ref': 'refs/changes/56/123456/7'
3202 }},
3203 },
3204 },
3205 }
3206
3207 self.assertEqual(0, git_cl.main([
3208 'try', '-B', 'luci.chromium.try', '-b', 'win',
3209 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3210 self.assertIn(
3211 'Scheduling jobs on:\nBucket: luci.chromium.try',
3212 git_cl.sys.stdout.getvalue())
3213
3214 expected_request = {
3215 "requests": [{
3216 "scheduleBuild": {
3217 "requestId": "uuid4",
3218 "builder": {
3219 "project": "chromium",
3220 "builder": "win",
3221 "bucket": "try",
3222 },
3223 "gerritChanges": [{
3224 "project": "depot_tools",
3225 "host": "chromium-review.googlesource.com",
3226 "patchset": 7,
3227 "change": 123456,
3228 }],
3229 "properties": {
3230 "category": "git_cl_try",
3231 "json": [{"a": 1}, None],
3232 "key": "val",
3233 },
3234 "tags": [
3235 {"value": "win", "key": "builder"},
3236 {"value": "git_cl_try", "key": "user_agent"},
3237 ],
3238 },
3239 }],
3240 }
3241 mockCallBuildbucket.assert_called_with(
3242 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3243
Edward Lemur4c707a22019-09-24 21:13:43 +00003244 @mock.patch('git_cl.Changelist._GetChangeDetail')
3245 def testScheduleOnBuildbucket_WrongBucket(self, mockGetChangeDetail):
3246 mockGetChangeDetail.return_value = {
3247 'project': 'depot_tools',
3248 'status': 'OPEN',
3249 'owner': {'email': 'owner@e.mail'},
3250 'current_revision': 'beeeeeef',
3251 'revisions': {
3252 'deadbeaf': {
3253 '_number': 6,
3254 },
3255 'beeeeeef': {
3256 '_number': 7,
3257 'fetch': {'http': {
3258 'url': 'https://chromium.googlesource.com/depot_tools',
3259 'ref': 'refs/changes/56/123456/7'
3260 }},
3261 },
3262 },
3263 }
3264
3265 self.assertEqual(0, git_cl.main([
3266 'try', '-B', 'not-a-bucket', '-b', 'win',
3267 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3268 self.assertIn(
3269 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3270 git_cl.sys.stdout.getvalue())
3271
3272 def test_parse_bucket(self):
3273 test_cases = [
3274 {
3275 'bucket': 'chromium/try',
3276 'result': ('chromium', 'try'),
3277 },
3278 {
3279 'bucket': 'luci.chromium.try',
3280 'result': ('chromium', 'try'),
3281 'has_warning': True,
3282 },
3283 {
3284 'bucket': 'skia.primary',
3285 'result': ('skia', 'skia.primary'),
3286 'has_warning': True,
3287 },
3288 {
3289 'bucket': 'not-a-bucket',
3290 'result': (None, None),
3291 },
3292 ]
3293
3294 for test_case in test_cases:
3295 git_cl.sys.stdout.truncate(0)
3296 self.assertEqual(
3297 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3298 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003299 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3300 test_case['result'])
3301 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003302
3303
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003304class CMDUploadTestCase(unittest.TestCase):
3305
3306 def setUp(self):
3307 super(CMDUploadTestCase, self).setUp()
3308 mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
3309 mock.patch('git_cl.uuid.uuid4', _constantFn('uuid4')).start()
3310 mock.patch('git_cl.Changelist.GetIssue', _constantFn(123456)).start()
3311 mock.patch('git_cl.Changelist.GetCodereviewServer',
3312 _constantFn('https://chromium-review.googlesource.com')).start()
3313 mock.patch('git_cl.Changelist.GetMostRecentPatchset',
3314 _constantFn(7)).start()
Andrii Shyshkalove7ae5142019-10-08 00:52:31 +00003315 mock.patch('git_cl.auth.get_authenticator_for_host',
3316 AuthenticatorMock()).start()
3317 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003318 self.addCleanup(mock.patch.stopall)
3319
3320 @mock.patch('git_cl.fetch_try_jobs')
3321 @mock.patch('git_cl._trigger_try_jobs')
3322 @mock.patch('git_cl.Changelist._GetChangeDetail')
3323 @mock.patch('git_cl.Changelist.CMDUpload', _constantFn(0))
3324 def testUploadRetryFailed(self, mockGetChangeDetail, mockTriggerTryJobs,
3325 mockFetchTryJobs):
3326 # This test mocks out the actual upload part, and just asserts that after
3327 # upload, if --retry-failed is added, then the tool will fetch try jobs
3328 # from the previous patchset and trigger the right builders on the latest
3329 # patchset.
3330 mockGetChangeDetail.return_value = {
3331 'project': 'depot_tools',
3332 'status': 'OPEN',
3333 'owner': {'email': 'owner@e.mail'},
3334 'current_revision': 'beeeeeef',
3335 'revisions': {
3336 'deadbeaf': {
3337 '_number': 6,
3338 },
3339 'beeeeeef': {
3340 '_number': 7,
3341 'fetch': {'http': {
3342 'url': 'https://chromium.googlesource.com/depot_tools',
3343 'ref': 'refs/changes/56/123456/7'
3344 }},
3345 },
3346 },
3347 }
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003348 mockFetchTryJobs.side_effect = [
3349 # Prior patchset - no builds.
3350 {},
3351 # Prior to prior patchset -- some builds.
3352 {
3353 '9000': {
3354 'id': '9000',
3355 'project': 'infra',
3356 'bucket': 'luci.infra.try',
3357 'created_by': 'user:someone@chromium.org',
3358 'created_ts': '147200002222000',
3359 'experimental': False,
3360 'parameters_json': json.dumps({
3361 'builder_name': 'red-bot',
3362 'properties': {'category': 'cq'},
3363 }),
3364 'status': 'COMPLETED',
3365 'result': 'FAILURE',
3366 'tags': ['user_agent:cq'],
3367 },
3368 8000: {
3369 'id': '8000',
3370 'project': 'infra',
3371 'bucket': 'luci.infra.try',
3372 'created_by': 'user:someone@chromium.org',
3373 'created_ts': '147200002222020',
3374 'experimental': False,
3375 'parameters_json': json.dumps({
3376 'builder_name': 'green-bot',
3377 'properties': {'category': 'cq'},
3378 }),
3379 'status': 'COMPLETED',
3380 'result': 'SUCCESS',
3381 'tags': ['user_agent:cq'],
3382 },
3383 },
3384 ]
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003385 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003386 mockFetchTryJobs.assert_has_calls([
3387 mock.call(mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3388 mock.call(mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
3389 ])
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003390 buckets = {'infra/try': {'red-bot': []}}
3391 mockTriggerTryJobs.assert_called_once_with(
3392 mock.ANY, mock.ANY, buckets, mock.ANY, 8)
3393
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003394if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003395 logging.basicConfig(
3396 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003397 unittest.main()