blob: d3b083eeec52001a0d3cf951dab879d6e61fb7c1 [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
490 def _run_and_validate(self, func, url, *args, **kwargs):
491 result = func(urlparse.urlparse(url))
492 if kwargs.pop('fail', False):
493 self.assertIsNone(result)
494 return None
495 self._validate(result, *args, fail=False, **kwargs)
496
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200497 def test_gerrit(self):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200498 def test(url, *args, **kwargs):
Edward Lemur125d60a2019-09-13 18:25:41 +0000499 self._run_and_validate(git_cl.Changelist.ParseIssueURL, url,
Edward Lemurf38bc172019-09-03 21:02:13 +0000500 *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200501
502 test('http://chrome-review.source.com/c/123',
503 123, None, 'chrome-review.source.com')
504 test('https://chrome-review.source.com/c/123/',
505 123, None, 'chrome-review.source.com')
506 test('https://chrome-review.source.com/c/123/4',
507 123, 4, 'chrome-review.source.com')
508 test('https://chrome-review.source.com/#/c/123/4',
509 123, 4, 'chrome-review.source.com')
510 test('https://chrome-review.source.com/c/123/4',
511 123, 4, 'chrome-review.source.com')
512 test('https://chrome-review.source.com/123',
513 123, None, 'chrome-review.source.com')
514 test('https://chrome-review.source.com/123/4',
515 123, 4, 'chrome-review.source.com')
516
517 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
518 test('https://chrome-review.source.com/c/abc/', fail=True)
519 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
520
521 def test_ParseIssueNumberArgument(self):
522 def test(arg, *args, **kwargs):
Edward Lemurf38bc172019-09-03 21:02:13 +0000523 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200524
525 test('123', 123)
526 test('', fail=True)
527 test('abc', fail=True)
528 test('123/1', fail=True)
529 test('123a', fail=True)
530 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +0000531
Andrii Shyshkalovc9712392017-04-11 13:35:21 +0200532 test('https://codereview.source.com/123',
Edward Lemurf38bc172019-09-03 21:02:13 +0000533 123, None, 'codereview.source.com')
Andrii Shyshkalovf5569d22018-10-15 03:35:23 +0000534
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200535 # Gerrrit.
536 test('https://chrome-review.source.com/c/123/4',
Edward Lemurf38bc172019-09-03 21:02:13 +0000537 123, 4, 'chrome-review.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200538 test('https://chrome-review.source.com/bad/123/4', fail=True)
539
540
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100541class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100542 def setUp(self):
543 super(GitCookiesCheckerTest, self).setUp()
544 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100545 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100546
547 def mock_hosts_creds(self, subhost_identity_pairs):
548 def ensure_googlesource(h):
549 if not h.endswith(self.c._GOOGLESOURCE):
550 assert not h.endswith('.')
551 return h + '.' + self.c._GOOGLESOURCE
552 return h
553 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
554 for h, i in subhost_identity_pairs]
555
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200556 def test_identity_parsing(self):
557 self.assertEqual(self.c._parse_identity('ldap.google.com'),
558 ('ldap', 'google.com'))
559 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
560 ('ldap', 'example.com'))
561 # Specical case because we know there are no subdomains in chromium.org.
562 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
563 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800564 # Pathological: ".period." can be either username OR domain, more likely
565 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200566 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
567 ('note', 'period.example.com'))
568
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100569 def test_analysis_nothing(self):
570 self.c._all_hosts = []
571 self.assertFalse(self.c.has_generic_host())
572 self.assertEqual(set(), self.c.get_conflicting_hosts())
573 self.assertEqual(set(), self.c.get_duplicated_hosts())
574 self.assertEqual(set(), self.c.get_partially_configured_hosts())
575 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
576
577 def test_analysis(self):
578 self.mock_hosts_creds([
579 ('.googlesource.com', 'git-example.chromium.org'),
580
581 ('chromium', 'git-example.google.com'),
582 ('chromium-review', 'git-example.google.com'),
583 ('chrome-internal', 'git-example.chromium.org'),
584 ('chrome-internal-review', 'git-example.chromium.org'),
585 ('conflict', 'git-example.google.com'),
586 ('conflict-review', 'git-example.chromium.org'),
587 ('dup', 'git-example.google.com'),
588 ('dup', 'git-example.google.com'),
589 ('dup-review', 'git-example.google.com'),
590 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200591 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100592 ])
593 self.assertTrue(self.c.has_generic_host())
594 self.assertEqual(set(['conflict.googlesource.com']),
595 self.c.get_conflicting_hosts())
596 self.assertEqual(set(['dup.googlesource.com']),
597 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200598 self.assertEqual(set(['partial.googlesource.com',
599 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100600 self.c.get_partially_configured_hosts())
601 self.assertEqual(set(['chromium.googlesource.com',
602 'chrome-internal.googlesource.com']),
603 self.c.get_hosts_with_wrong_identities())
604
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100605 def test_report_no_problems(self):
606 self.test_analysis_nothing()
607 self.mock(sys, 'stdout', StringIO.StringIO())
608 self.assertFalse(self.c.find_and_report_problems())
609 self.assertEqual(sys.stdout.getvalue(), '')
610
611 def test_report(self):
612 self.test_analysis()
613 self.mock(sys, 'stdout', StringIO.StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200614 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
615 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100616 self.assertTrue(self.c.find_and_report_problems())
617 with open(os.path.join(os.path.dirname(__file__),
618 'git_cl_creds_check_report.txt')) as f:
619 expected = f.read()
620 def by_line(text):
621 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700622 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200623 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100624
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800625
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000626class TestGitCl(TestCase):
627 def setUp(self):
628 super(TestGitCl, self).setUp()
629 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700630 self._calls_done = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000631 self.mock(git_cl, 'time_time',
632 lambda: self._mocked_call('time.time'))
633 self.mock(git_cl.metrics.collector, 'add_repeated',
634 lambda *a: self._mocked_call('add_repeated', *a))
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000635 self.mock(subprocess2, 'call', self._mocked_call)
636 self.mock(subprocess2, 'check_call', self._mocked_call)
637 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700638 self.mock(subprocess2, 'communicate',
639 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000640 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000641 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000642 self.mock(git_common, 'get_or_create_merge_base',
643 lambda *a: (
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000644 self._mocked_call(['get_or_create_merge_base'] + list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000645 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000646 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000647 self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
648 self._mocked_call('SaveDescriptionBackup'))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100649 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000650 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700651 self.mock(git_cl, 'write_json', lambda path, contents:
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000652 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000653 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000654 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000655 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100656 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
657 lambda *args, **kwargs: self._mocked_call(
658 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700659 self.mock(git_cl.gerrit_util, 'GetChangeComments',
660 lambda *args, **kwargs: self._mocked_call(
661 'GetChangeComments', *args, **kwargs))
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000662 self.mock(git_cl.gerrit_util, 'GetChangeRobotComments',
663 lambda *args, **kwargs: self._mocked_call(
664 'GetChangeRobotComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100665 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700666 lambda h, i, reviewers, ccs, notify: self._mocked_call(
667 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700668 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700669 lambda h, i, msg=None, labels=None, notify=None:
670 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700671 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
672 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000673 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
674 classmethod(lambda _: False))
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000675 self.mock(git_cl.gerrit_util, 'ValidAccounts',
676 lambda host, accounts:
677 self._mocked_call('ValidAccounts', host, accounts))
tandriic2405f52016-10-10 08:13:15 -0700678 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100679 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000680 # It's important to reset settings to not have inter-tests interference.
681 git_cl.settings = None
682
683 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000684 try:
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100685 self.assertEquals([], self.calls)
686 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000687 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100688 raise
689 # Sadly, has_failed() returns True if this OR any other tests before this
690 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200691 git_cl.logging.error(
692 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100693 'There are un-consumed self.calls after this test has finished.\n'
694 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700695 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200696 'If you are already running only this test, then **first** fix the '
697 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100698 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700699 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100700 'and follow instructions above.\n' +
701 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000702 finally:
703 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000704
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000705 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000706 self.assertTrue(
707 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700708 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000709 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000710 expected_args, result = top
711
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000712 # Also logs otherwise it could get caught in a try/finally and be hard to
713 # diagnose.
714 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700715 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000716 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700717 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
718 for i, c in enumerate(self._calls_done[-N:]))
719 following_calls = '\n '.join(
720 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
721 for i, c in enumerate(self.calls[:N]))
722 extended_msg = (
723 'A few prior calls:\n %s\n\n'
724 'This (expected):\n @%d: %r\n'
725 'This (actual):\n @%d: %r\n\n'
726 'A few following expected calls:\n %s' %
727 (prior_calls, len(self._calls_done), expected_args,
728 len(self._calls_done), args, following_calls))
729 git_cl.logging.error(extended_msg)
730
tandrii99a72f22016-08-17 14:33:24 -0700731 self.fail('@%d\n'
732 ' Expected: %r\n'
733 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700734 len(self._calls_done), expected_args, args))
735
736 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700737 if isinstance(result, Exception):
738 raise result
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000739 return result
740
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100741 def test_ask_for_explicit_yes_true(self):
742 self.calls = [
743 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
744 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
745 ]
746 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
747
tandrii48df5812016-10-17 03:55:37 -0700748 def test_LoadCodereviewSettingsFromFile_gerrit(self):
749 codereview_file = StringIO.StringIO('GERRIT_HOST: true')
750 self.calls = [
751 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700752 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
753 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
754 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
755 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700756 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
757 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700758 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
759 CERR1),
760 ((['git', 'config', 'gerrit.host', 'true'],), ''),
761 ]
762 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
763
maruel@chromium.orga3353652011-11-30 14:26:57 +0000764 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000765 def _is_gerrit_calls(cls, gerrit=False):
766 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
767 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
768
769 @classmethod
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000770 def _git_post_upload_calls(cls):
771 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000772 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
773 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
774 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000775 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000776 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000777 ]
778
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000779 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000780 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000781 fake_ancestor = 'fake_ancestor'
782 fake_cl = 'fake_cl_for_patch'
783 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000784 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000785 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000786 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000787 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000788 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000789 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000790 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000791 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700792 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000793 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000794 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000795 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000796 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000797 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000798 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000799 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000800 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000801 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000802 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000803 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000804
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000805 @classmethod
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000806 def _gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000807 cls, issue=None, skip_auth_check=False, short_hostname='chromium',
808 custom_cl_base=None):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000809 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000810 if skip_auth_check:
811 return [((cmd, ), 'true')]
812
tandrii5d48c322016-08-18 16:19:37 -0700813 calls = [((cmd, ), CERR1)]
Edward Lemurf38bc172019-09-03 21:02:13 +0000814
815 if custom_cl_base:
816 calls += [
817 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
818 ]
819
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000820 calls.extend([
821 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
822 ((['git', 'config', 'branch.master.remote'],), 'origin'),
823 ((['git', 'config', 'remote.origin.url'],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000824 'https://%s.googlesource.com/my/repo' % short_hostname),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000825 ])
Edward Lemurf38bc172019-09-03 21:02:13 +0000826
827 calls += [
828 ((['git', 'config', 'branch.master.gerritissue'],),
829 CERR1 if issue is None else str(issue)),
830 ]
831
Daniel Chengcf6269b2019-05-18 01:02:12 +0000832 if issue:
833 calls.extend([
834 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
835 ])
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000836 return calls
837
838 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100839 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200840 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000841 custom_cl_base=None, short_hostname='chromium',
842 change_id=None):
Aaron Gable13101a62018-02-09 13:20:41 -0800843 calls = cls._is_gerrit_calls(True)
Edward Lemurf38bc172019-09-03 21:02:13 +0000844 if not custom_cl_base:
845 calls += [
846 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
847 ]
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200848
849 if custom_cl_base:
850 ancestor_revision = custom_cl_base
851 else:
852 # Determine ancestor_revision to be merge base.
853 ancestor_revision = 'fake_ancestor_sha'
854 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000855 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000856 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000857 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200858 'refs/remotes/origin/master'],), ancestor_revision),
859 ]
860
861 # Calls to verify branch point is ancestor
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000862 calls += cls._gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000863 issue=issue, short_hostname=short_hostname,
864 custom_cl_base=custom_cl_base)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100865
866 if issue:
867 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000868 (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +0000869 'my%2Frepo~123456',
Andrii Shyshkalovc4a73562018-09-25 18:40:17 +0000870 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
871 ),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100872 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100873 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Anthony Polito8b955342019-09-24 19:01:36 +0000874 'change_id': (change_id or '123456789'),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100875 'current_revision': 'sha1_of_current_revision',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000876 'revisions': {'sha1_of_current_revision': {
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100877 'commit': {'message': fetched_description},
878 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100879 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100880 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100881 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100882 if fetched_status == 'ABANDONED':
883 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000884 (('DieWithError', 'Change https://%s-review.googlesource.com/'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100885 '123456 has been abandoned, new uploads are not '
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000886 'allowed' % short_hostname), SystemExitMock()),
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100887 ]
888 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100889 if other_cl_owner:
890 calls += [
891 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
892 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100893
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200894 calls += cls._git_sanity_checks(ancestor_revision, 'master',
895 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100896 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200897 ((['git', 'rev-parse', '--show-cdup'],), ''),
898 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000899
Aaron Gable7817f022017-12-12 09:43:17 -0800900 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
901 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200902 'M\t.gitignore\n'),
903 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100904 ]
905
906 if not issue:
907 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200908 ((['git', 'log', '--pretty=format:%s%n%n%b',
909 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000910 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100911 ]
912
913 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200914 ((['git', 'config', 'user.email'],), 'me@example.com'),
Edward Lemur2c48f242019-06-04 16:14:09 +0000915 (('time.time',), 1000,),
916 (('time.time',), 3000,),
917 (('add_repeated', 'sub_commands', {
918 'execution_time': 2000,
919 'command': 'presubmit',
920 'exit_code': 0
921 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200922 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
923 ([custom_cl_base] if custom_cl_base else
924 [ancestor_revision, 'HEAD']),),
925 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100926 ]
927 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000928
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000929 @classmethod
930 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700931 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000932 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700933 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100934 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000935 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000936 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000937 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000938 final_description=None, gitcookies_exists=True,
939 force=False):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000940 if post_amend_description is None:
941 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700942 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200943 # Determined in `_gerrit_base_calls`.
944 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
945
946 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000947
tandriia60502f2016-06-20 02:01:53 -0700948 if squash_mode == 'default':
949 calls.extend([
950 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
951 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
952 ])
953 elif squash_mode in ('override_squash', 'override_nosquash'):
954 calls.extend([
955 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
956 'true' if squash_mode == 'override_squash' else 'false'),
957 ])
958 else:
959 assert squash_mode in ('squash', 'nosquash')
960
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000961 # If issue is given, then description is fetched from Gerrit instead.
962 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000963 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200964 ((['git', 'log', '--pretty=format:%s\n\n%b',
965 ((custom_cl_base + '..') if custom_cl_base else
966 'fake_ancestor_sha..HEAD')],),
967 description),
968 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800969 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000970 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800971 else:
972 if not title:
973 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200974 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
975 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800976 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000977 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000978 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000979 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200980 (('DownloadGerritHook', False), ''),
981 # Amending of commit message to get the Change-Id.
982 ((['git', 'log', '--pretty=format:%s\n\n%b',
983 determined_ancestor_revision + '..HEAD'],),
984 description),
985 ((['git', 'commit', '--amend', '-m', description],), ''),
986 ((['git', 'log', '--pretty=format:%s\n\n%b',
987 determined_ancestor_revision + '..HEAD'],),
988 post_amend_description)
989 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000990 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000991 if force or not issue:
992 if issue:
993 calls += [
994 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
995 ]
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000996 # Prompting to edit description on first upload.
997 calls += [
Jonas Termansend0f79112019-03-22 15:28:26 +0000998 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000999 ]
Anthony Polito8b955342019-09-24 19:01:36 +00001000 if not force:
1001 calls += [
1002 ((['git', 'config', 'core.editor'],), ''),
1003 ((['RunEditor'],), description),
1004 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001005 ref_to_push = 'abcdef0123456789'
1006 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001007 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1008 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1009 ]
1010
1011 if custom_cl_base is None:
1012 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001013 ((['get_or_create_merge_base', 'master',
1014 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001015 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001016 ]
1017 parent = 'origin/master'
1018 else:
1019 calls += [
1020 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
1021 'refs/remotes/origin/master'],),
1022 callError(1)), # Means not ancenstor.
1023 (('ask_for_data',
1024 'Do you take responsibility for cleaning up potential mess '
1025 'resulting from proceeding with upload? Press Enter to upload, '
1026 'or Ctrl+C to abort'), ''),
1027 ]
1028 parent = custom_cl_base
1029
1030 calls += [
1031 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
1032 '0123456789abcdef'),
1033 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -07001034 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001035 ref_to_push),
1036 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001037 else:
1038 ref_to_push = 'HEAD'
1039
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001040 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00001041 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001042 ((['git', 'rev-list',
1043 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1044 ref_to_push],),
1045 '1hashPerLine\n'),
1046 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001047
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001048 metrics_arguments = []
1049
Aaron Gableafd52772017-06-27 16:40:10 -07001050 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001051 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001052 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -07001053 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001054 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001055 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001056 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -07001057 else:
1058 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001059 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -08001060
Aaron Gable70f4e242017-06-26 10:45:59 -07001061 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001062 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001063 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001064
Edward Lemur4508b422019-10-03 21:56:35 +00001065 if issue is None:
1066 calls += [
1067 ((['git', 'config', 'rietveld.cc'],), ''),
1068 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001069 if short_hostname == 'chromium':
1070 # All reviwers and ccs get into ref_suffix.
1071 for r in sorted(reviewers):
1072 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001073 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +00001074 if issue is None:
1075 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
1076 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001077 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001078 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001079 reviewers, cc = [], []
1080 else:
1081 # TODO(crbug/877717): remove this case.
1082 calls += [
1083 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
1084 sorted(reviewers) + ['joe@example.com',
1085 'chromium-reviews+test-more-cc@chromium.org'] + cc),
1086 {
1087 e: {'email': e}
1088 for e in (reviewers + ['joe@example.com'] + cc)
1089 })
1090 ]
1091 for r in sorted(reviewers):
1092 if r != 'bad-account-or-email':
1093 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001094 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001095 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +00001096 if issue is None:
1097 cc += ['joe@example.com']
1098 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001099 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001100 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001101 if c in cc:
1102 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001103
Edward Lemur687ca902018-12-05 02:30:30 +00001104 for k, v in sorted((labels or {}).items()):
1105 ref_suffix += ',l=%s+%d' % (k, v)
1106 metrics_arguments.append('l=%s+%d' % (k, v))
1107
1108 if tbr:
1109 calls += [
1110 (('GetCodeReviewTbrScore',
1111 '%s-review.googlesource.com' % short_hostname,
1112 'my/repo'),
1113 2,),
1114 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001115
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001116 calls += [
1117 (('time.time',), 1000,),
1118 ((['git', 'push',
1119 'https://%s.googlesource.com/my/repo' % short_hostname,
1120 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1121 (('remote:\n'
1122 'remote: Processing changes: (\)\n'
1123 'remote: Processing changes: (|)\n'
1124 'remote: Processing changes: (/)\n'
1125 'remote: Processing changes: (-)\n'
1126 'remote: Processing changes: new: 1 (/)\n'
1127 'remote: Processing changes: new: 1, done\n'
1128 'remote:\n'
1129 'remote: New Changes:\n'
1130 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1131 ' XXX\n'
1132 'remote:\n'
1133 'To https://%s.googlesource.com/my/repo\n'
1134 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1135 ) % (short_hostname, short_hostname)),),
1136 (('time.time',), 2000,),
1137 (('add_repeated',
1138 'sub_commands',
1139 {
1140 'execution_time': 1000,
1141 'command': 'git push',
1142 'exit_code': 0,
1143 'arguments': sorted(metrics_arguments),
1144 }),
1145 None,),
1146 ]
1147
Edward Lemur1b52d872019-05-09 21:12:12 +00001148 final_description = final_description or post_amend_description.strip()
1149 original_title = original_title or title or '<untitled>'
1150 # Trace-related calls
1151 calls += [
1152 # Write a description with context for the current trace.
1153 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001154 'Thu Mar 16 20:00:41 2017\n'
1155 '%(short_hostname)s-review.googlesource.com\n'
1156 '%(change_id)s\n'
1157 '%(title)s\n'
1158 '%(description)s\n'
1159 '1000\n'
1160 '0\n'
1161 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001162 'short_hostname': short_hostname,
1163 'change_id': change_id,
1164 'description': final_description,
1165 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001166 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001167 }],),
1168 None,
1169 ),
1170 # Read traces and shorten git hashes.
1171 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1172 True,
1173 ),
1174 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1175 ('git-hash: 0123456789012345678901234567890123456789\n'
1176 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1177 ),
1178 ((['FileWrite', 'TEMP_DIR/trace-packet',
1179 'git-hash: 012345\n'
1180 'git-hash: abcdea\n'],),
1181 None,
1182 ),
1183 # Make zip file for the git traces.
1184 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1185 'TEMP_DIR'],),
1186 None,
1187 ),
1188 # Collect git config and gitcookies.
1189 ((['git', 'config', '-l'],),
1190 'git-config-output',
1191 ),
1192 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1193 None,
1194 ),
1195 ((['os.path.isfile', '~/.gitcookies'],),
1196 gitcookies_exists,
1197 ),
1198 ]
1199 if gitcookies_exists:
1200 calls += [
1201 ((['FileRead', '~/.gitcookies'],),
1202 'gitcookies 1/SECRET',
1203 ),
1204 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1205 None,
1206 ),
1207 ]
1208 calls += [
1209 # Make zip file for the git config and gitcookies.
1210 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1211 'TEMP_DIR'],),
1212 None,
1213 ),
1214 ]
1215
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001216 if squash:
1217 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001218 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001219 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001220 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001221 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001222 ((['git', 'config', 'branch.master.gerritsquashhash',
1223 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001224 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001225 # TODO(crbug/877717): this should never be used.
1226 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001227 calls += [
1228 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001229 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001230 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001231 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1232 notify),
1233 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001234 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001235 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001236 return calls
1237
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001238 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001239 self,
1240 upload_args,
1241 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001242 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001243 squash=True,
1244 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001245 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001246 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001247 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001248 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001249 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001250 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001251 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001252 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001253 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001254 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001255 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001256 labels=None,
1257 change_id=None,
1258 original_title=None,
1259 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001260 gitcookies_exists=True,
1261 force=False,
1262 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001263 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001264 if squash_mode is None:
1265 if '--no-squash' in upload_args:
1266 squash_mode = 'nosquash'
1267 elif '--squash' in upload_args:
1268 squash_mode = 'squash'
1269 else:
1270 squash_mode = 'default'
1271
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001272 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001273 cc = cc or []
tandrii@chromium.org28253532016-04-14 13:46:56 +00001274 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001275 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001276 CookiesAuthenticatorMockFactory(
1277 same_auth=('git-owner.example.com', '', 'pass')))
Edward Lemur125d60a2019-09-13 18:25:41 +00001278 self.mock(git_cl.Changelist, '_GerritCommitMsgHookCheck',
tandrii16e0b4e2016-06-07 10:34:28 -07001279 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001280 self.mock(git_cl.gclient_utils, 'RunEditor',
1281 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001282 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1283 'DownloadGerritHook', force))
Edward Lemur1b52d872019-05-09 21:12:12 +00001284 self.mock(git_cl.gclient_utils, 'FileRead',
1285 lambda path: self._mocked_call(['FileRead', path]))
1286 self.mock(git_cl.gclient_utils, 'FileWrite',
1287 lambda path, contents: self._mocked_call(
1288 ['FileWrite', path, contents]))
1289 self.mock(git_cl, 'datetime_now',
1290 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0))
1291 self.mock(git_cl.tempfile, 'mkdtemp', lambda: 'TEMP_DIR')
1292 self.mock(git_cl, 'TRACES_DIR', 'TRACES_DIR')
Edward Lemur75391d42019-05-14 23:35:56 +00001293 self.mock(git_cl, 'TRACES_README_FORMAT',
1294 '%(now)s\n'
1295 '%(gerrit_host)s\n'
1296 '%(change_id)s\n'
1297 '%(title)s\n'
1298 '%(description)s\n'
1299 '%(execution_time)s\n'
1300 '%(exit_code)s\n'
1301 '%(trace_name)s')
Edward Lemur1b52d872019-05-09 21:12:12 +00001302 self.mock(git_cl.shutil, 'make_archive',
1303 lambda *args: self._mocked_call(['make_archive'] + list(args)))
1304 self.mock(os.path, 'isfile',
1305 lambda path: self._mocked_call(['os.path.isfile', path]))
tandriia60502f2016-06-20 02:01:53 -07001306
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001307 self.calls = self._gerrit_base_calls(
1308 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001309 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001310 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001311 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001312 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001313 short_hostname=short_hostname,
1314 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001315 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001316 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
1317 expected_content=description))
1318 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001319 self.calls += self._gerrit_upload_calls(
1320 description, reviewers, squash,
1321 squash_mode=squash_mode,
1322 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001323 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001324 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001325 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001326 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001327 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001328 labels=labels,
1329 change_id=change_id,
1330 original_title=original_title,
1331 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001332 gitcookies_exists=gitcookies_exists,
1333 force=force)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001334 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001335 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001336 git_cl.main(['upload'] + upload_args)
1337
Edward Lemur1b52d872019-05-09 21:12:12 +00001338 def test_gerrit_upload_traces_no_gitcookies(self):
1339 self._run_gerrit_upload_test(
1340 ['--no-squash'],
1341 'desc\n\nBUG=\n',
1342 [],
1343 squash=False,
1344 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1345 change_id='Ixxx',
1346 gitcookies_exists=False)
1347
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001348 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001349 self._run_gerrit_upload_test(
1350 ['--no-squash'],
1351 'desc\n\nBUG=\n',
1352 [],
1353 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001354 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1355 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001356
1357 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001358 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001359 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +00001360 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001361 [],
tandriia60502f2016-06-20 02:01:53 -07001362 squash=False,
1363 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001364 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1365 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001366
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001367 def test_gerrit_no_reviewer(self):
1368 self._run_gerrit_upload_test(
1369 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001370 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001371 [],
1372 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001373 squash_mode='override_nosquash',
1374 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001375
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001376 def test_gerrit_no_reviewer_non_chromium_host(self):
1377 # TODO(crbug/877717): remove this test case.
1378 self._run_gerrit_upload_test(
1379 [],
1380 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
1381 [],
1382 squash=False,
1383 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001384 short_hostname='other',
1385 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001386
Nick Carter8692b182017-11-06 16:30:38 -08001387 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001388 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1389 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001390 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001391 'desc\n\nBUG=\n\nChange-Id: I123456789',
1392 squash=False,
1393 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001394 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1395 change_id='I123456789',
1396 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001397
ukai@chromium.orge8077812012-02-03 03:41:46 +00001398 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001399 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001400 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001401 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001402 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001403 squash=False,
1404 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001405 notify=True,
1406 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001407 final_description=(
1408 'desc\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001409
Anthony Polito8b955342019-09-24 19:01:36 +00001410 def test_gerrit_upload_force_sets_bug(self):
1411 self._run_gerrit_upload_test(
1412 ['-b', '10000', '-f'],
1413 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1414 [],
1415 force=True,
1416 expected_upstream_ref='origin/master',
1417 fetched_description='desc=\n\nChange-Id: Ixxx',
1418 original_title='Initial upload',
1419 change_id='Ixxx')
1420
1421 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1422 self._run_gerrit_upload_test(
1423 ['-b', '10000', '-f', '-m', 'Title'],
1424 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1425 [],
1426 force=True,
1427 issue='123456',
1428 expected_upstream_ref='origin/master',
1429 fetched_description='desc=\n\nChange-Id: Ixxxx',
1430 original_title='Title',
1431 title='Title',
1432 change_id='Izzzz')
1433
ukai@chromium.orge8077812012-02-03 03:41:46 +00001434 def test_gerrit_reviewer_multiple(self):
Edward Lemur687ca902018-12-05 02:30:30 +00001435 self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
1436 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001437 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001438 [],
bradnelsond975b302016-10-23 12:20:23 -07001439 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1440 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001441 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001442 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001443 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001444 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001445 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001446 labels={'Code-Review': 2},
1447 change_id='123456789',
1448 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001449
1450 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001451 self._run_gerrit_upload_test(
1452 [],
1453 'desc\nBUG=\n\nChange-Id: 123456789',
1454 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001455 expected_upstream_ref='origin/master',
1456 change_id='123456789',
1457 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001458
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001459 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001460 self._run_gerrit_upload_test(
1461 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001462 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001463 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001464 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001465 expected_upstream_ref='origin/master',
1466 change_id='123456789',
1467 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001468
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001469 def test_gerrit_upload_squash_first_with_labels(self):
1470 self._run_gerrit_upload_test(
1471 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
1472 'desc\nBUG=\n\nChange-Id: 123456789',
1473 [],
1474 squash=True,
1475 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001476 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1477 change_id='123456789',
1478 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001479
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001480 def test_gerrit_upload_squash_first_against_rev(self):
1481 custom_cl_base = 'custom_cl_base_rev_or_branch'
1482 self._run_gerrit_upload_test(
1483 ['--squash', custom_cl_base],
1484 'desc\nBUG=\n\nChange-Id: 123456789',
1485 [],
1486 squash=True,
1487 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001488 custom_cl_base=custom_cl_base,
1489 change_id='123456789',
1490 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001491 self.assertIn(
1492 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1493 sys.stdout.getvalue())
1494
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001495 def test_gerrit_upload_squash_reupload(self):
1496 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001497 self._run_gerrit_upload_test(
1498 ['--squash'],
1499 description,
1500 [],
1501 squash=True,
1502 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001503 issue=123456,
1504 change_id='123456789',
1505 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001506
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001507 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1508 self.mock(git_cl, 'DieWithError',
1509 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1510 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1511 with self.assertRaises(SystemExitMock):
1512 self._run_gerrit_upload_test(
1513 ['--squash'],
1514 description,
1515 [],
1516 squash=True,
1517 expected_upstream_ref='origin/master',
1518 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001519 fetched_status='ABANDONED',
1520 change_id='123456789')
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001521
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001522 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1523 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1524 lambda *_, **__: {'email': 'yet-another@example.com'})
1525 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1526 self._run_gerrit_upload_test(
1527 ['--squash'],
1528 description,
1529 [],
1530 squash=True,
1531 expected_upstream_ref='origin/master',
1532 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001533 other_cl_owner='other@example.com',
1534 change_id='123456789',
1535 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001536 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001537 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001538 'authenticate to Gerrit as yet-another@example.com.\n'
1539 'Uploading may fail due to lack of permissions',
1540 git_cl.sys.stdout.getvalue())
1541
rmistry@google.com2dd99862015-06-22 12:22:18 +00001542 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001543 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001544 def mock_run_git(*args, **_kwargs):
1545 if args[0] == ['for-each-ref',
1546 '--format=%(refname:short) %(upstream:short)',
1547 'refs/heads']:
1548 # Create a local branch dependency tree that looks like this:
1549 # test1 -> test2 -> test3 -> test4 -> test5
1550 # -> test3.1
1551 # test6 -> test0
1552 branch_deps = [
1553 'test2 test1', # test1 -> test2
1554 'test3 test2', # test2 -> test3
1555 'test3.1 test2', # test2 -> test3.1
1556 'test4 test3', # test3 -> test4
1557 'test5 test4', # test4 -> test5
1558 'test6 test0', # test0 -> test6
1559 'test7', # test7
1560 ]
1561 return '\n'.join(branch_deps)
1562 self.mock(git_cl, 'RunGit', mock_run_git)
1563
1564 class RecordCalls:
1565 times_called = 0
1566 record_calls = RecordCalls()
1567 def mock_CMDupload(*args, **_kwargs):
1568 record_calls.times_called += 1
1569 return 0
1570 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1571
1572 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001573 (('ask_for_data', 'This command will checkout all dependent branches '
1574 'and run "git cl upload". Press Enter to continue, '
1575 'or Ctrl+C to abort'), ''),
1576 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001577
1578 class MockChangelist():
1579 def __init__(self):
1580 pass
1581 def GetBranch(self):
1582 return 'test1'
1583 def GetIssue(self):
1584 return '123'
1585 def GetPatchset(self):
1586 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001587 def IsGerrit(self):
1588 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001589
1590 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1591 # CMDupload should have been called 5 times because of 5 dependent branches.
1592 self.assertEquals(5, record_calls.times_called)
1593 self.assertEquals(0, ret)
1594
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001595 def test_gerrit_change_id(self):
1596 self.calls = [
1597 ((['git', 'write-tree'], ),
1598 'hashtree'),
1599 ((['git', 'rev-parse', 'HEAD~0'], ),
1600 'branch-parent'),
1601 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1602 'A B <a@b.org> 1456848326 +0100'),
1603 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1604 'C D <c@d.org> 1456858326 +0100'),
1605 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1606 'hashchange'),
1607 ]
1608 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1609 self.assertEqual(change_id, 'Ihashchange')
1610
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001611 def test_desecription_append_footer(self):
1612 for init_desc, footer_line, expected_desc in [
1613 # Use unique desc first lines for easy test failure identification.
1614 ('foo', 'R=one', 'foo\n\nR=one'),
1615 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1616 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1617 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1618 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1619 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1620 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1621 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1622 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1623 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1624 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1625 ]:
1626 desc = git_cl.ChangeDescription(init_desc)
1627 desc.append_footer(footer_line)
1628 self.assertEqual(desc.description, expected_desc)
1629
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001630 def test_update_reviewers(self):
1631 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001632 ('foo', [], [],
1633 'foo'),
1634 ('foo\nR=xx', [], [],
1635 'foo\nR=xx'),
1636 ('foo\nTBR=xx', [], [],
1637 'foo\nTBR=xx'),
1638 ('foo', ['a@c'], [],
1639 'foo\n\nR=a@c'),
1640 ('foo\nR=xx', ['a@c'], [],
1641 'foo\n\nR=a@c, xx'),
1642 ('foo\nTBR=xx', ['a@c'], [],
1643 'foo\n\nR=a@c\nTBR=xx'),
1644 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1645 'foo\n\nR=a@c, yy\nTBR=xx'),
1646 ('foo\nBUG=', ['a@c'], [],
1647 'foo\nBUG=\nR=a@c'),
1648 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1649 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1650 ('foo', ['a@c', 'b@c'], [],
1651 'foo\n\nR=a@c, b@c'),
1652 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1653 'foo\nBar\n\nR=c@c\nBUG='),
1654 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1655 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001656 # Same as the line before, but full of whitespaces.
1657 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001658 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001659 'foo\nBar\n\nR=c@c\n BUG =',
1660 ),
1661 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001662 ('foo BUG=allo R=joe ', ['c@c'], [],
1663 'foo BUG=allo R=joe\n\nR=c@c'),
1664 # Redundant TBRs get promoted to Rs
1665 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1666 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001667 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001668 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001669 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001670 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001671 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001672 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001673 actual.append(obj.description)
1674 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001675
Nodir Turakulov23b82142017-11-16 11:04:25 -08001676 def test_get_hash_tags(self):
1677 cases = [
1678 ('', []),
1679 ('a', []),
1680 ('[a]', ['a']),
1681 ('[aa]', ['aa']),
1682 ('[a ]', ['a']),
1683 ('[a- ]', ['a']),
1684 ('[a- b]', ['a-b']),
1685 ('[a--b]', ['a-b']),
1686 ('[a', []),
1687 ('[a]x', ['a']),
1688 ('[aa]x', ['aa']),
1689 ('[a b]', ['a-b']),
1690 ('[a b]', ['a-b']),
1691 ('[a__b]', ['a-b']),
1692 ('[a] x', ['a']),
1693 ('[a][b]', ['a', 'b']),
1694 ('[a] [b]', ['a', 'b']),
1695 ('[a][b]x', ['a', 'b']),
1696 ('[a][b] x', ['a', 'b']),
1697 ('[a]\n[b]', ['a']),
1698 ('[a\nb]', []),
1699 ('[a][', ['a']),
1700 ('Revert "[a] feature"', ['a']),
1701 ('Reland "[a] feature"', ['a']),
1702 ('Revert: [a] feature', ['a']),
1703 ('Reland: [a] feature', ['a']),
1704 ('Revert "Reland: [a] feature"', ['a']),
1705 ('Foo: feature', ['foo']),
1706 ('Foo Bar: feature', ['foo-bar']),
1707 ('Revert "Foo bar: feature"', ['foo-bar']),
1708 ('Reland "Foo bar: feature"', ['foo-bar']),
1709 ]
1710 for desc, expected in cases:
1711 change_desc = git_cl.ChangeDescription(desc)
1712 actual = change_desc.get_hash_tags()
1713 self.assertEqual(
1714 actual,
1715 expected,
1716 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1717
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001718 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001719 self.assertEqual(None, git_cl.GetTargetRef(None,
1720 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001721 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001722
wittman@chromium.org455dc922015-01-26 20:15:50 +00001723 # Check default target refs for branches.
1724 self.assertEqual('refs/heads/master',
1725 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001726 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001727 self.assertEqual('refs/heads/master',
1728 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001729 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001730 self.assertEqual('refs/heads/master',
1731 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001732 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001733 self.assertEqual('refs/branch-heads/123',
1734 git_cl.GetTargetRef('origin',
1735 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001736 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001737 self.assertEqual('refs/diff/test',
1738 git_cl.GetTargetRef('origin',
1739 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001740 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001741 self.assertEqual('refs/heads/chrome/m42',
1742 git_cl.GetTargetRef('origin',
1743 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001744 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001745
1746 # Check target refs for user-specified target branch.
1747 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1748 'refs/remotes/branch-heads/123'):
1749 self.assertEqual('refs/branch-heads/123',
1750 git_cl.GetTargetRef('origin',
1751 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001752 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001753 for branch in ('origin/master', 'remotes/origin/master',
1754 'refs/remotes/origin/master'):
1755 self.assertEqual('refs/heads/master',
1756 git_cl.GetTargetRef('origin',
1757 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001758 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001759 for branch in ('master', 'heads/master', 'refs/heads/master'):
1760 self.assertEqual('refs/heads/master',
1761 git_cl.GetTargetRef('origin',
1762 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001763 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001764
wychen@chromium.orga872e752015-04-28 23:42:18 +00001765 def test_patch_when_dirty(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001766 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001767 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1768 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1769
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001770 @staticmethod
1771 def _get_gerrit_codereview_server_calls(branch, value=None,
1772 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001773 detect_branch=True,
1774 detect_server=True):
Edward Lemur125d60a2019-09-13 18:25:41 +00001775 """Returns calls executed by Changelist.GetCodereviewServer.
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001776
1777 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1778 """
1779 calls = []
1780 if detect_branch:
1781 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001782 if detect_server:
1783 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1784 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001785 if value is None:
1786 calls += [
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001787 ((['git', 'config', 'branch.' + branch + '.merge'],),
1788 'refs/heads' + branch),
1789 ((['git', 'config', 'branch.' + branch + '.remote'],),
1790 'origin'),
1791 ((['git', 'config', 'remote.origin.url'],),
1792 'https://%s.googlesource.com/my/repo' % git_short_host),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001793 ]
1794 return calls
1795
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001796 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001797 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001798 detect_gerrit_server=False,
1799 actual_codereview=None,
1800 codereview_in_url=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001801 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
wychen@chromium.orga872e752015-04-28 23:42:18 +00001802 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1803
tandriidf09a462016-08-18 16:23:55 -07001804 if new_branch:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001805 self.calls = [((['git', 'new-branch', 'master'],), '')]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001806
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001807 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001808 self.calls += [
1809 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001810 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001811 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001812
1813 if not force_codereview and not codereview_in_url:
1814 # These calls detect codereview to use.
1815 self.calls += [
1816 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001817 ]
1818 if detect_gerrit_server:
1819 self.calls += self._get_gerrit_codereview_server_calls(
1820 'master', git_short_host=git_short_host,
1821 detect_branch=not new_branch and force_codereview)
1822 actual_codereview = 'gerrit'
1823
1824 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001825 self.calls += [
1826 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001827 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001828 {
1829 'current_revision': '7777777777',
1830 'revisions': {
1831 '1111111111': {
1832 '_number': 1,
1833 'fetch': {'http': {
1834 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1835 'ref': 'refs/changes/56/123456/1',
1836 }},
1837 },
1838 '7777777777': {
1839 '_number': 7,
1840 'fetch': {'http': {
1841 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1842 'ref': 'refs/changes/56/123456/7',
1843 }},
1844 },
1845 },
1846 }),
1847 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001848
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001849 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001850 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001851 self.calls += [
1852 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1853 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001854 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001855 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001856 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001857 ((['git', 'config', 'branch.master.gerritserver',
1858 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001859 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001860 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1861 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1862 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001863 ]
1864 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1865
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001866 def test_patch_gerrit_new_branch(self):
1867 self._patch_common(
1868 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1869 self.calls += [
1870 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1871 'refs/changes/56/123456/7'],), ''),
1872 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1873 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1874 ''),
1875 ((['git', 'config', 'branch.master.gerritserver',
1876 'https://chromium-review.googlesource.com'],), ''),
1877 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1878 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1879 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1880 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1881 ]
1882 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1883
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001884 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001885 self._patch_common(
1886 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001887 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001888 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001889 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001890 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001891 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001892 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001893 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001894 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001895 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001896 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1897 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1898 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001899 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001900 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001901
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001902 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001903 self.calls += self._get_gerrit_codereview_server_calls(
1904 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001905 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001906 actual_codereview='gerrit', git_short_host='else',
1907 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001908 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001909 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001910 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001911 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001912 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001913 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001914 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001915 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001916 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001917 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1918 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1919 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001920 ]
1921 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001922 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001923
Aaron Gable697a91b2018-01-19 15:20:15 -08001924 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001925 self.calls += self._get_gerrit_codereview_server_calls(
1926 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001927 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001928 actual_codereview='gerrit', git_short_host='else',
1929 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001930 self.calls += [
1931 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1932 'refs/changes/56/123456/1'],), ''),
1933 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1934 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1935 ''),
1936 ((['git', 'config', 'branch.master.gerritserver',
1937 'https://else-review.googlesource.com'],), ''),
1938 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1939 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1940 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1941 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1942 ]
1943 self.assertEqual(git_cl.main(
1944 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1945 0)
1946
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001947 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001948 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001949 self.calls += [
1950 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001951 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001952 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1953 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1954 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001955 ]
1956 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001957 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001958
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001959 def test_patch_gerrit_not_exists(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001960
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001961 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001962 raise git_cl.gerrit_util.GerritError(404, '')
1963 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1964
tandriic2405f52016-10-10 08:13:15 -07001965 self.calls = [
1966 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001967 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1968 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1969 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1970 ((['git', 'config', 'remote.origin.url'],),
1971 'https://chromium.googlesource.com/my/repo'),
1972 ((['DieWithError',
1973 'change 123456 at https://chromium-review.googlesource.com does not '
1974 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001975 ]
1976 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001977 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001978
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001979 def _checkout_calls(self):
1980 return [
1981 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001982 'branch\\..*\\.gerritissue'], ),
1983 ('branch.ger-branch.gerritissue 123456\n'
1984 'branch.gbranch654.gerritissue 654321\n')),
1985 ]
1986
1987 def test_checkout_gerrit(self):
1988 """Tests git cl checkout <issue>."""
1989 self.calls = self._checkout_calls()
1990 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1991 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1992
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001993 def test_checkout_not_found(self):
1994 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001995 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001996 self.calls = self._checkout_calls()
1997 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1998
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001999 def test_checkout_no_branch_issues(self):
2000 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00002001 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002002 self.calls = [
2003 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07002004 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002005 ]
2006 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2007
tandrii@chromium.org28253532016-04-14 13:46:56 +00002008 def _test_gerrit_ensure_authenticated_common(self, auth,
2009 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002010 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2011 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
2012 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11002013 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00002014 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
Edward Lemurf38bc172019-09-03 21:02:13 +00002015 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00002016 cl.branch = 'master'
2017 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002018 return cl
2019
2020 def test_gerrit_ensure_authenticated_missing(self):
2021 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002022 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002023 })
2024 self.calls.append(
2025 ((['DieWithError',
2026 'Credentials for the following hosts are required:\n'
2027 ' chromium-review.googlesource.com\n'
2028 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002029 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002030 'https://chromium-review.googlesource.com/new-password'],), ''),)
2031 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2032
2033 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00002034 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002035 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002036 'chromium.googlesource.com':
2037 ('git-one.example.com', None, 'secret1'),
2038 'chromium-review.googlesource.com':
2039 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002040 })
2041 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002042 (('ask_for_data', 'If you know what you are doing '
2043 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002044 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2045
2046 def test_gerrit_ensure_authenticated_ok(self):
2047 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002048 'chromium.googlesource.com':
2049 ('git-same.example.com', None, 'secret'),
2050 'chromium-review.googlesource.com':
2051 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002052 })
2053 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2054
tandrii@chromium.org28253532016-04-14 13:46:56 +00002055 def test_gerrit_ensure_authenticated_skipped(self):
2056 cl = self._test_gerrit_ensure_authenticated_common(
2057 auth={}, skip_auth_check=True)
2058 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2059
Eric Boren2fb63102018-10-05 13:05:03 +00002060 def test_gerrit_ensure_authenticated_bearer_token(self):
2061 cl = self._test_gerrit_ensure_authenticated_common(auth={
2062 'chromium.googlesource.com':
2063 ('', None, 'secret'),
2064 'chromium-review.googlesource.com':
2065 ('', None, 'secret'),
2066 })
2067 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2068 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2069 'chromium.googlesource.com')
2070 self.assertTrue('Bearer' in header)
2071
Daniel Chengcf6269b2019-05-18 01:02:12 +00002072 def test_gerrit_ensure_authenticated_non_https(self):
2073 self.calls = [
2074 ((['git', 'config', '--bool',
2075 'gerrit.skip-ensure-authenticated'],), CERR1),
2076 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
2077 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2078 ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
2079 ]
2080 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2081 CookiesAuthenticatorMockFactory(hosts_with_creds={}))
Edward Lemurf38bc172019-09-03 21:02:13 +00002082 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00002083 cl.branch = 'master'
2084 cl.branchref = 'refs/heads/master'
2085 cl.lookedup_issue = True
2086 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2087
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002088 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002089 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002090 lambda h, i, labels, notify=None:
2091 self._mocked_call(['SetReview', h, i, labels, notify]))
2092
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002093 self.calls = [
2094 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002095 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002096 ((['git', 'config', 'branch.feature.gerritserver'],),
2097 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002098 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2099 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2100 ((['git', 'config', 'remote.origin.url'],),
2101 'https://chromium.googlesource.com/infra/infra.git'),
2102 ((['SetReview', 'chromium-review.googlesource.com',
2103 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002104 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002105 ]
tandriid9e5ce52016-07-13 02:32:59 -07002106
2107 def test_cmd_set_commit_gerrit_clear(self):
2108 self._cmd_set_commit_gerrit_common(0)
2109 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2110
2111 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002112 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002113 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2114
tandriid9e5ce52016-07-13 02:32:59 -07002115 def test_cmd_set_commit_gerrit(self):
2116 self._cmd_set_commit_gerrit_common(2)
2117 self.assertEqual(0, git_cl.main(['set-commit']))
2118
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002119 def test_description_display(self):
2120 out = StringIO.StringIO()
2121 self.mock(git_cl.sys, 'stdout', out)
2122
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002123 self.mock(git_cl, 'Changelist', ChangelistMock)
2124 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002125
2126 self.assertEqual(0, git_cl.main(['description', '-d']))
2127 self.assertEqual('foo\n', out.getvalue())
2128
iannucci3c972b92016-08-17 13:24:10 -07002129 def test_StatusFieldOverrideIssueMissingArgs(self):
2130 out = StringIO.StringIO()
2131 self.mock(git_cl.sys, 'stderr', out)
2132
2133 try:
2134 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2135 except SystemExit as ex:
2136 self.assertEqual(ex.code, 2)
Edward Lemurf38bc172019-09-03 21:02:13 +00002137 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002138
2139 out = StringIO.StringIO()
2140 self.mock(git_cl.sys, 'stderr', out)
2141
2142 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002143 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07002144 except SystemExit as ex:
2145 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002146 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002147
2148 def test_StatusFieldOverrideIssue(self):
2149 out = StringIO.StringIO()
2150 self.mock(git_cl.sys, 'stdout', out)
2151
2152 def assertIssue(cl_self, *_args):
2153 self.assertEquals(cl_self.issue, 1)
2154 return 'foobar'
2155
2156 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07002157 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002158 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002159 0)
iannucci3c972b92016-08-17 13:24:10 -07002160 self.assertEqual(out.getvalue(), 'foobar\n')
2161
iannuccie53c9352016-08-17 14:40:40 -07002162 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002163
iannuccie53c9352016-08-17 14:40:40 -07002164 def assertIssue(cl_self, *_args):
2165 self.assertEquals(cl_self.issue, 1)
2166 return 'foobar'
2167
2168 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2169 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07002170 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002171 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002172
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002173 def test_description(self):
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002174 out = StringIO.StringIO()
2175 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002176 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002177 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2178 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2179 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2180 ((['git', 'config', 'remote.origin.url'],),
2181 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002182 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002183 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002184 {
2185 'current_revision': 'sha1',
2186 'revisions': {'sha1': {
2187 'commit': {'message': 'foobar'},
2188 }},
2189 }),
2190 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002191 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002192 'description',
2193 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2194 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002195 self.assertEqual('foobar\n', out.getvalue())
2196
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002197 def test_description_set_raw(self):
2198 out = StringIO.StringIO()
2199 self.mock(git_cl.sys, 'stdout', out)
2200
2201 self.mock(git_cl, 'Changelist', ChangelistMock)
2202 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
2203
2204 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2205 self.assertEqual('hihi', ChangelistMock.desc)
2206
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002207 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002208 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002209
2210 def RunEditor(desc, _, **kwargs):
2211 self.assertEquals(
2212 '# Enter a description of the change.\n'
2213 '# This will be displayed on the codereview site.\n'
2214 '# The first line will also be used as the subject of the review.\n'
2215 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002216 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002217 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002218 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002219 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002220 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002221
dsansomee2d6fd92016-09-08 00:10:47 -07002222 def UpdateDescriptionRemote(_, desc, force=False):
Aaron Gable3a16ed12017-03-23 10:51:55 -07002223 self.assertEquals(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002224
2225 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2226 self.mock(git_cl.Changelist, 'GetDescription',
2227 lambda *args: current_desc)
Edward Lemur125d60a2019-09-13 18:25:41 +00002228 self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002229 UpdateDescriptionRemote)
2230 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2231
2232 self.calls = [
2233 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002234 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002235 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2236 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002237 ((['git', 'config', 'core.editor'],), 'vi'),
2238 ]
2239 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2240
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002241 def test_description_set_stdin(self):
2242 out = StringIO.StringIO()
2243 self.mock(git_cl.sys, 'stdout', out)
2244
2245 self.mock(git_cl, 'Changelist', ChangelistMock)
2246 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
2247
2248 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2249 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2250
kmarshall3bff56b2016-06-06 18:31:47 -07002251 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07002252 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2253
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002254 self.calls = [
2255 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002256 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002257 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2258 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002259 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002260 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002261
kmarshall3bff56b2016-06-06 18:31:47 -07002262 self.mock(git_cl, 'get_cl_statuses',
2263 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002264 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2265 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2266 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002267
2268 self.assertEqual(0, git_cl.main(['archive', '-f']))
2269
2270 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07002271 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002272 self.calls = [
2273 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2274 'refs/heads/master'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002275 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2276 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002277
kmarshall9249e012016-08-23 12:02:16 -07002278 self.mock(git_cl, 'get_cl_statuses',
2279 lambda branches, fine_grained, max_processes:
2280 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2281
2282 self.assertEqual(1, git_cl.main(['archive', '-f']))
2283
2284 def test_archive_dry_run(self):
2285 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2286
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002287 self.calls = [
2288 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2289 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002290 ((['git', 'symbolic-ref', 'HEAD'],), 'master')
2291 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002292
2293 self.mock(git_cl, 'get_cl_statuses',
2294 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002295 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2296 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2297 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002298
kmarshall9249e012016-08-23 12:02:16 -07002299 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2300
2301 def test_archive_no_tags(self):
2302 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2303
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002304 self.calls = [
2305 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2306 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002307 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2308 ((['git', 'branch', '-D', 'foo'],), '')
2309 ]
kmarshall9249e012016-08-23 12:02:16 -07002310
2311 self.mock(git_cl, 'get_cl_statuses',
2312 lambda branches, fine_grained, max_processes:
2313 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2314 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2315 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2316
2317 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002318
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002319 def test_cmd_issue_erase_existing(self):
2320 out = StringIO.StringIO()
2321 self.mock(git_cl.sys, 'stdout', out)
2322 self.calls = [
2323 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002324 # Let this command raise exception (retcode=1) - it should be ignored.
2325 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002326 CERR1),
2327 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2328 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002329 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2330 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2331 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002332 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002333 ]
2334 self.assertEqual(0, git_cl.main(['issue', '0']))
2335
Aaron Gable400e9892017-07-12 15:31:21 -07002336 def test_cmd_issue_erase_existing_with_change_id(self):
2337 out = StringIO.StringIO()
2338 self.mock(git_cl.sys, 'stdout', out)
2339 self.mock(git_cl.Changelist, 'GetDescription',
2340 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2341 self.calls = [
2342 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Aaron Gable400e9892017-07-12 15:31:21 -07002343 # Let this command raise exception (retcode=1) - it should be ignored.
2344 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2345 CERR1),
2346 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2347 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2348 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2349 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2350 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002351 ((['git', 'log', '-1', '--format=%B'],),
2352 'This is a description\n\nChange-Id: Ideadbeef'),
2353 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002354 ]
2355 self.assertEqual(0, git_cl.main(['issue', '0']))
2356
phajdan.jre328cf92016-08-22 04:12:17 -07002357 def test_cmd_issue_json(self):
2358 out = StringIO.StringIO()
2359 self.mock(git_cl.sys, 'stdout', out)
2360 self.calls = [
2361 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002362 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2363 ((['git', 'config', 'branch.feature.gerritserver'],),
2364 'https://chromium-review.googlesource.com'),
phajdan.jre328cf92016-08-22 04:12:17 -07002365 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002366 {'issue': 123,
2367 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002368 ''),
2369 ]
2370 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2371
tandrii16e0b4e2016-06-07 10:34:28 -07002372 def _common_GerritCommitMsgHookCheck(self):
2373 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2374 self.mock(git_cl.os.path, 'abspath',
2375 lambda path: self._mocked_call(['abspath', path]))
2376 self.mock(git_cl.os.path, 'exists',
2377 lambda path: self._mocked_call(['exists', path]))
2378 self.mock(git_cl.gclient_utils, 'FileRead',
2379 lambda path: self._mocked_call(['FileRead', path]))
2380 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2381 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2382 self.calls = [
2383 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2384 ((['abspath', '../'],), '/abs/git_repo_root'),
2385 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002386 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002387
2388 def test_GerritCommitMsgHookCheck_custom_hook(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 '#!/bin/sh\necho "custom hook"')
2394 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002395 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002396
2397 def test_GerritCommitMsgHookCheck_not_exists(self):
2398 cl = self._common_GerritCommitMsgHookCheck()
2399 self.calls += [
2400 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2401 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002402 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002403
2404 def test_GerritCommitMsgHookCheck(self):
2405 cl = self._common_GerritCommitMsgHookCheck()
2406 self.calls += [
2407 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2408 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2409 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002410 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002411 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2412 ''),
2413 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002414 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002415
tandriic4344b52016-08-29 06:04:54 -07002416 def test_GerritCmdLand(self):
2417 self.calls += [
2418 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2419 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2420 'deadbeaf'),
2421 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2422 ((['git', 'config', 'branch.feature.gerritserver'],),
2423 'chromium-review.googlesource.com'),
2424 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002425 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002426 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002427 'labels': {},
2428 'current_revision': 'deadbeaf',
2429 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002430 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002431 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002432 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002433 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2434 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002435 cl.SubmitIssue = lambda wait_for_merge: None
tandrii8da412c2016-09-07 16:01:07 -07002436 out = StringIO.StringIO()
2437 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002438 self.assertEqual(0, cl.CMDLand(force=True,
2439 bypass_hooks=True,
2440 verbose=True,
2441 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002442 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002443 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002444
tandrii221ab252016-10-06 08:12:04 -07002445 BUILDBUCKET_BUILDS_MAP = {
Quinten Yearsleya563d722017-12-11 16:36:54 -08002446 '9000': {
2447 'id': '9000',
2448 'bucket': 'master.x.y',
2449 'created_by': 'user:someone@chromium.org',
2450 'created_ts': '147200002222000',
2451 'experimental': False,
2452 'parameters_json': json.dumps({
2453 'builder_name': 'my-bot',
2454 'properties': {'category': 'cq'},
2455 }),
2456 'status': 'STARTED',
2457 'tags': [
2458 'build_address:x.y/my-bot/2',
2459 'builder:my-bot',
2460 'experimental:false',
2461 'user_agent:cq',
2462 ],
2463 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2464 },
2465 '8000': {
2466 'id': '8000',
2467 'bucket': 'master.x.y',
2468 'created_by': 'user:someone@chromium.org',
2469 'created_ts': '147200001111000',
2470 'experimental': False,
2471 'failure_reason': 'BUILD_FAILURE',
2472 'parameters_json': json.dumps({
2473 'builder_name': 'my-bot',
2474 'properties': {'category': 'cq'},
2475 }),
2476 'result_details_json': json.dumps({
2477 'properties': {'buildnumber': 1},
2478 }),
2479 'result': 'FAILURE',
2480 'status': 'COMPLETED',
2481 'tags': [
2482 'build_address:x.y/my-bot/1',
2483 'builder:my-bot',
2484 'experimental:false',
2485 'user_agent:cq',
2486 ],
2487 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2488 },
2489 }
tandrii221ab252016-10-06 08:12:04 -07002490
2491 def test_write_try_results_json(self):
2492 expected_output = [
Quinten Yearsleya563d722017-12-11 16:36:54 -08002493 {
2494 'bucket': 'master.x.y',
2495 'buildbucket_id': '8000',
2496 'builder_name': 'my-bot',
2497 'created_ts': '147200001111000',
2498 'experimental': False,
2499 'failure_reason': 'BUILD_FAILURE',
2500 'result': 'FAILURE',
2501 'status': 'COMPLETED',
2502 'tags': [
2503 'build_address:x.y/my-bot/1',
2504 'builder:my-bot',
2505 'experimental:false',
2506 'user_agent:cq',
2507 ],
2508 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2509 },
2510 {
2511 'bucket': 'master.x.y',
2512 'buildbucket_id': '9000',
2513 'builder_name': 'my-bot',
2514 'created_ts': '147200002222000',
2515 'experimental': False,
2516 'failure_reason': None,
2517 'result': None,
2518 'status': 'STARTED',
2519 'tags': [
2520 'build_address:x.y/my-bot/2',
2521 'builder:my-bot',
2522 'experimental:false',
2523 'user_agent:cq',
2524 ],
2525 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2526 },
tandrii221ab252016-10-06 08:12:04 -07002527 ]
2528 self.calls = [(('write_json', 'output.json', expected_output), '')]
2529 git_cl.write_try_results_json('output.json', self.BUILDBUCKET_BUILDS_MAP)
2530
tandrii45b2a582016-10-11 03:14:16 -07002531 def _setup_fetch_try_jobs(self, most_recent_patchset=20001):
tandrii221ab252016-10-06 08:12:04 -07002532 out = StringIO.StringIO()
2533 self.mock(sys, 'stdout', out)
tandrii45b2a582016-10-11 03:14:16 -07002534 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
2535 lambda *args: most_recent_patchset)
tandrii221ab252016-10-06 08:12:04 -07002536 self.mock(git_cl.auth, 'get_authenticator_for_host', lambda host, _cfg:
2537 self._mocked_call(['get_authenticator_for_host', host]))
2538 self.mock(git_cl, '_buildbucket_retry', lambda *_, **__:
2539 self._mocked_call(['_buildbucket_retry']))
tandrii45b2a582016-10-11 03:14:16 -07002540
tandrii45b2a582016-10-11 03:14:16 -07002541 def _setup_fetch_try_jobs_gerrit(self, *request_results):
2542 self._setup_fetch_try_jobs(most_recent_patchset=13)
2543 self.calls += [
2544 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii45b2a582016-10-11 03:14:16 -07002545 ((['git', 'config', 'branch.feature.gerritissue'],), '1'),
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002546 # TODO(tandrii): Uncomment the below if we decide to support checking
2547 # patchsets for Gerrit.
tandrii45b2a582016-10-11 03:14:16 -07002548 # Simulate that Gerrit has more patchsets than local.
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002549 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'),
tandrii45b2a582016-10-11 03:14:16 -07002550 ((['git', 'config', 'branch.feature.gerritserver'],),
2551 'https://x-review.googlesource.com'),
2552 ((['get_authenticator_for_host', 'x-review.googlesource.com'],),
2553 AuthenticatorMock()),
2554 ] + [((['_buildbucket_retry'],), r) for r in request_results]
2555
2556 def test_fetch_try_jobs_none_gerrit(self):
2557 self._setup_fetch_try_jobs_gerrit({})
2558 self.assertEqual(0, git_cl.main(['try-results']))
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002559 # TODO(tandrii): Uncomment the below if we decide to support checking
2560 # patchsets for Gerrit.
2561 # self.assertRegexpMatches(
2562 # sys.stdout.getvalue(),
2563 # r'Warning: Codereview server has newer patchsets \(13\)')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002564 self.assertRegexpMatches(sys.stdout.getvalue(), 'No tryjobs')
tandrii45b2a582016-10-11 03:14:16 -07002565
2566 def test_fetch_try_jobs_some_gerrit(self):
2567 self._setup_fetch_try_jobs_gerrit({
2568 'builds': self.BUILDBUCKET_BUILDS_MAP.values(),
2569 })
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002570 # TODO(tandrii): Uncomment the below if we decide to support checking
2571 # patchsets for Gerrit.
2572 # self.calls.remove(
2573 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'))
tandrii45b2a582016-10-11 03:14:16 -07002574 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '5']))
2575
2576 # ... and doesn't result in warning.
2577 self.assertNotRegexpMatches(sys.stdout.getvalue(), 'Warning')
2578 self.assertRegexpMatches(sys.stdout.getvalue(), '^Failures:')
tandrii221ab252016-10-06 08:12:04 -07002579 self.assertRegexpMatches(sys.stdout.getvalue(), 'Started:')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002580 self.assertRegexpMatches(sys.stdout.getvalue(), '2 tryjobs')
tandrii221ab252016-10-06 08:12:04 -07002581
Quinten Yearsley983111f2019-09-26 17:18:48 +00002582 def test_filter_failed_none(self):
2583 self.assertEqual(git_cl._filter_failed({}), {})
2584
2585 def test_filter_failed_some(self):
2586 builds = {
2587 '9000': {
2588 'id': '9000',
2589 'bucket': 'luci.chromium.try',
2590 'project': 'chromium',
2591 'created_by': 'user:someone@chromium.org',
2592 'created_ts': '147200002222000',
2593 'experimental': False,
2594 'parameters_json': json.dumps({
2595 'builder_name': 'my-bot',
2596 'properties': {'category': 'cq'},
2597 }),
2598 'status': 'COMPLETED',
2599 'result': 'FAILURE',
2600 }
2601 }
2602 self.assertEqual(
2603 git_cl._filter_failed(builds),
2604 {'chromium/try': {'my-bot': []}})
2605
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002606 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemur125d60a2019-09-13 18:25:41 +00002607 self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002608
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002609 def test_gerrit_change_detail_cache_simple(self):
2610 self._mock_gerrit_changes_for_detail_cache()
2611 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002612 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2613 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2614 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002615 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002616 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002617 cl1._cached_remote_url = (
2618 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002619 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002620 cl2._cached_remote_url = (
2621 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002622 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2623 self.assertEqual(cl1._GetChangeDetail(), 'a')
2624 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2625 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2626 self.assertEqual(cl1._GetChangeDetail(), 'a')
2627 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002628
2629 def test_gerrit_change_detail_cache_options(self):
2630 self._mock_gerrit_changes_for_detail_cache()
2631 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002632 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2633 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2634 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2635 # no longer in cache.
2636 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002637 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002638 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002639 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002640 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2641 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2642 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2643 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2644 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2645 self.assertEqual(cl._GetChangeDetail(), 'cab')
2646
2647 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2648 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2649 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2650 self.assertEqual(cl._GetChangeDetail(), 'cab')
2651
2652 # Finally, no_cache should invalidate all caches for given change.
2653 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2654 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2655
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002656 def test_gerrit_description_caching(self):
2657 def gen_detail(rev, desc):
2658 return {
2659 'current_revision': rev,
2660 'revisions': {rev: {'commit': {'message': desc}}}
2661 }
2662 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002663 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002664 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2665 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002666 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002667 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2668 gen_detail('rev2', 'desc2')),
2669 ]
2670
2671 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002672 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002673 cl._cached_remote_url = (
2674 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002675 self.assertEqual(cl.GetDescription(), 'desc1')
2676 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2677 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002678
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002679 def test_print_current_creds(self):
2680 class CookiesAuthenticatorMock(object):
2681 def __init__(self):
2682 self.gitcookies = {
2683 'host.googlesource.com': ('user', 'pass'),
2684 'host-review.googlesource.com': ('user', 'pass'),
2685 }
2686 self.netrc = self
2687 self.netrc.hosts = {
2688 'github.com': ('user2', None, 'pass2'),
2689 'host2.googlesource.com': ('user3', None, 'pass'),
2690 }
2691 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2692 CookiesAuthenticatorMock)
2693 self.mock(sys, 'stdout', StringIO.StringIO())
2694 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2695 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2696 ' Host\t User\t Which file',
2697 '============================\t=====\t===========',
2698 'host-review.googlesource.com\t user\t.gitcookies',
2699 ' host.googlesource.com\t user\t.gitcookies',
2700 ' host2.googlesource.com\tuser3\t .netrc',
2701 ])
2702 sys.stdout.buf = ''
2703 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2704 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2705 ' Host\tUser\t Which file',
2706 '============================\t====\t===========',
2707 'host-review.googlesource.com\tuser\t.gitcookies',
2708 ' host.googlesource.com\tuser\t.gitcookies',
2709 ])
2710
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002711 def _common_creds_check_mocks(self):
2712 def exists_mock(path):
2713 dirname = os.path.dirname(path)
2714 if dirname == os.path.expanduser('~'):
2715 dirname = '~'
2716 base = os.path.basename(path)
2717 if base in ('.netrc', '.gitcookies'):
2718 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2719 # git cl also checks for existence other files not relevant to this test.
2720 return None
2721 self.mock(os.path, 'exists', exists_mock)
2722 self.mock(sys, 'stdout', StringIO.StringIO())
2723
2724 def test_creds_check_gitcookies_not_configured(self):
2725 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002726 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002727 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002728 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002729 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002730 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2731 (('os.path.exists', '~/.netrc'), True),
2732 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2733 'or Ctrl+C to abort'), ''),
2734 ((['git', 'config', '--global', 'http.cookiefile',
2735 os.path.expanduser('~/.gitcookies')], ), ''),
2736 ]
2737 self.assertEqual(0, git_cl.main(['creds-check']))
2738 self.assertRegexpMatches(
2739 sys.stdout.getvalue(),
2740 '^You seem to be using outdated .netrc for git credentials:')
2741 self.assertRegexpMatches(
2742 sys.stdout.getvalue(),
2743 '\nConfigured git to use .gitcookies from')
2744
2745 def test_creds_check_gitcookies_configured_custom_broken(self):
2746 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002747 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002748 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002749 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002750 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002751 ((['git', 'config', '--global', 'http.cookiefile'],),
2752 '/custom/.gitcookies'),
2753 (('os.path.exists', '/custom/.gitcookies'), False),
2754 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2755 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2756 ((['git', 'config', '--global', 'http.cookiefile',
2757 os.path.expanduser('~/.gitcookies')], ), ''),
2758 ]
2759 self.assertEqual(0, git_cl.main(['creds-check']))
2760 self.assertRegexpMatches(
2761 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002762 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002763 self.assertRegexpMatches(
2764 sys.stdout.getvalue(),
2765 'However, your configured .gitcookies file is missing.')
2766
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002767 def test_git_cl_comment_add_gerrit(self):
2768 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002769 lambda host, change, msg, ready:
2770 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002771 self.calls = [
2772 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2773 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2774 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2775 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2776 'origin/master'),
2777 ((['git', 'config', 'remote.origin.url'],),
2778 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002779 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2780 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002781 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002782 ]
2783 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2784 '-a', 'msg']))
2785
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002786 def test_git_cl_comments_fetch_gerrit(self):
2787 self.mock(sys, 'stdout', StringIO.StringIO())
2788 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002789 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2790 ((['git', 'config', 'branch.foo.merge'],), ''),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002791 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2792 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2793 'origin/master'),
2794 ((['git', 'config', 'remote.origin.url'],),
2795 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002796 (('GetChangeDetail', 'chromium-review.googlesource.com',
2797 'infra%2Finfra~1',
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002798 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2799 'CURRENT_COMMIT']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002800 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002801 'current_revision': 'ba5eba11',
2802 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002803 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002804 '_number': 1,
2805 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002806 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002807 '_number': 2,
2808 },
2809 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002810 'messages': [
2811 {
2812 u'_revision_number': 1,
2813 u'author': {
2814 u'_account_id': 1111084,
2815 u'email': u'commit-bot@chromium.org',
2816 u'name': u'Commit Bot'
2817 },
2818 u'date': u'2017-03-15 20:08:45.000000000',
2819 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002820 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002821 u'tag': u'autogenerated:cq:dry-run'
2822 },
2823 {
2824 u'_revision_number': 2,
2825 u'author': {
2826 u'_account_id': 11151243,
2827 u'email': u'owner@example.com',
2828 u'name': u'owner'
2829 },
2830 u'date': u'2017-03-16 20:00:41.000000000',
2831 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2832 u'message': u'PTAL',
2833 },
2834 {
2835 u'_revision_number': 2,
2836 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002837 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002838 u'email': u'reviewer@example.com',
2839 u'name': u'reviewer'
2840 },
2841 u'date': u'2017-03-17 05:19:37.500000000',
2842 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2843 u'message': u'Patch Set 2: Code-Review+1',
2844 },
2845 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002846 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002847 (('GetChangeComments', 'chromium-review.googlesource.com',
2848 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002849 '/COMMIT_MSG': [
2850 {
2851 'author': {'email': u'reviewer@example.com'},
2852 'updated': u'2017-03-17 05:19:37.500000000',
2853 'patch_set': 2,
2854 'side': 'REVISION',
2855 'message': 'Please include a bug link',
2856 },
2857 ],
2858 'codereview.settings': [
2859 {
2860 'author': {'email': u'owner@example.com'},
2861 'updated': u'2017-03-16 20:00:41.000000000',
2862 'patch_set': 2,
2863 'side': 'PARENT',
2864 'line': 42,
2865 'message': 'I removed this because it is bad',
2866 },
2867 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002868 }),
2869 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2870 'infra%2Finfra~1'), {}),
2871 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002872 ] * 2 + [
2873 (('write_json', 'output.json', [
2874 {
2875 u'date': u'2017-03-16 20:00:41.000000',
2876 u'message': (
2877 u'PTAL\n' +
2878 u'\n' +
2879 u'codereview.settings\n' +
2880 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2881 u'c/1/2/codereview.settings#b42\n' +
2882 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002883 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002884 u'approval': False,
2885 u'disapproval': False,
2886 u'sender': u'owner@example.com'
2887 }, {
2888 u'date': u'2017-03-17 05:19:37.500000',
2889 u'message': (
2890 u'Patch Set 2: Code-Review+1\n' +
2891 u'\n' +
2892 u'/COMMIT_MSG\n' +
2893 u' PS2, File comment: https://chromium-review.googlesource' +
2894 u'.com/c/1/2//COMMIT_MSG#\n' +
2895 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002896 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002897 u'approval': False,
2898 u'disapproval': False,
2899 u'sender': u'reviewer@example.com'
2900 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002901 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002902 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002903 expected_comments_summary = [
2904 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002905 message=(
2906 u'PTAL\n' +
2907 u'\n' +
2908 u'codereview.settings\n' +
2909 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2910 u'c/1/2/codereview.settings#b42\n' +
2911 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002912 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002913 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002914 disapproval=False, approval=False, sender=u'owner@example.com'),
2915 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002916 message=(
2917 u'Patch Set 2: Code-Review+1\n' +
2918 u'\n' +
2919 u'/COMMIT_MSG\n' +
2920 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2921 u'c/1/2//COMMIT_MSG#\n' +
2922 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002923 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002924 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002925 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2926 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002927 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002928 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002929 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002930 self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
2931 self.assertEqual(
2932 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2933
2934 def test_git_cl_comments_robot_comments(self):
2935 # git cl comments also fetches robot comments (which are considered a type
2936 # of autogenerated comment), and unlike other types of comments, only robot
2937 # comments from the latest patchset are shown.
2938 self.mock(sys, 'stdout', StringIO.StringIO())
2939 self.calls = [
2940 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2941 ((['git', 'config', 'branch.foo.merge'],), ''),
2942 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2943 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2944 'origin/master'),
2945 ((['git', 'config', 'remote.origin.url'],),
2946 'https://chromium.googlesource.com/infra/infra'),
2947 (('GetChangeDetail', 'chromium-review.googlesource.com',
2948 'infra%2Finfra~1',
2949 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2950 'CURRENT_COMMIT']), {
2951 'owner': {'email': 'owner@example.com'},
2952 'current_revision': 'ba5eba11',
2953 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002954 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002955 '_number': 1,
2956 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002957 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002958 '_number': 2,
2959 },
2960 },
2961 'messages': [
2962 {
2963 u'_revision_number': 1,
2964 u'author': {
2965 u'_account_id': 1111084,
2966 u'email': u'commit-bot@chromium.org',
2967 u'name': u'Commit Bot'
2968 },
2969 u'date': u'2017-03-15 20:08:45.000000000',
2970 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2971 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2972 u'tag': u'autogenerated:cq:dry-run'
2973 },
2974 {
2975 u'_revision_number': 1,
2976 u'author': {
2977 u'_account_id': 123,
2978 u'email': u'tricium@serviceaccount.com',
2979 u'name': u'Tricium'
2980 },
2981 u'date': u'2017-03-16 20:00:41.000000000',
2982 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2983 u'message': u'(1 comment)',
2984 u'tag': u'autogenerated:tricium',
2985 },
2986 {
2987 u'_revision_number': 1,
2988 u'author': {
2989 u'_account_id': 123,
2990 u'email': u'tricium@serviceaccount.com',
2991 u'name': u'Tricium'
2992 },
2993 u'date': u'2017-03-16 20:00:41.000000000',
2994 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2995 u'message': u'(1 comment)',
2996 u'tag': u'autogenerated:tricium',
2997 },
2998 {
2999 u'_revision_number': 2,
3000 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003001 u'_account_id': 123,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00003002 u'email': u'tricium@serviceaccount.com',
3003 u'name': u'reviewer'
3004 },
3005 u'date': u'2017-03-17 05:30:37.000000000',
3006 u'tag': u'autogenerated:tricium',
3007 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
3008 u'message': u'(1 comment)',
3009 },
3010 ]
3011 }),
3012 (('GetChangeComments', 'chromium-review.googlesource.com',
3013 'infra%2Finfra~1'), {}),
3014 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
3015 'infra%2Finfra~1'), {
3016 'codereview.settings': [
3017 {
3018 u'author': {u'email': u'tricium@serviceaccount.com'},
3019 u'updated': u'2017-03-17 05:30:37.000000000',
3020 u'robot_run_id': u'5565031076855808',
3021 u'robot_id': u'Linter/Category',
3022 u'tag': u'autogenerated:tricium',
3023 u'patch_set': 2,
3024 u'side': u'REVISION',
3025 u'message': u'Linter warning message text',
3026 u'line': 32,
3027 },
3028 ],
3029 }),
3030 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
3031 ]
3032 expected_comments_summary = [
3033 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
3034 message=(
3035 u'(1 comment)\n\ncodereview.settings\n'
3036 u' PS2, Line 32: https://chromium-review.googlesource.com/'
3037 u'c/1/2/codereview.settings#32\n'
3038 u' Linter warning message text\n'),
3039 sender=u'tricium@serviceaccount.com',
3040 autogenerated=True, approval=False, disapproval=False)
3041 ]
3042 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00003043 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00003044 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003045
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003046 def test_get_remote_url_with_mirror(self):
3047 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003048
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003049 def selective_os_path_isdir_mock(path):
3050 if path == '/cache/this-dir-exists':
3051 return self._mocked_call('os.path.isdir', path)
3052 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003053
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003054 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3055
3056 url = 'https://chromium.googlesource.com/my/repo'
3057 self.calls = [
3058 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3059 ((['git', 'config', 'branch.master.merge'],), 'master'),
3060 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3061 ((['git', 'config', 'remote.origin.url'],),
3062 '/cache/this-dir-exists'),
3063 (('os.path.isdir', '/cache/this-dir-exists'),
3064 True),
3065 # Runs in /cache/this-dir-exists.
3066 ((['git', 'config', 'remote.origin.url'],),
3067 url),
3068 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003069 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003070 self.assertEqual(cl.GetRemoteUrl(), url)
3071 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
3072
Edward Lemur298f2cf2019-02-22 21:40:39 +00003073 def test_get_remote_url_non_existing_mirror(self):
3074 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003075
Edward Lemur298f2cf2019-02-22 21:40:39 +00003076 def selective_os_path_isdir_mock(path):
3077 if path == '/cache/this-dir-doesnt-exist':
3078 return self._mocked_call('os.path.isdir', path)
3079 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003080
Edward Lemur298f2cf2019-02-22 21:40:39 +00003081 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3082 self.mock(logging, 'error',
3083 lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
3084
3085 self.calls = [
3086 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3087 ((['git', 'config', 'branch.master.merge'],), 'master'),
3088 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3089 ((['git', 'config', 'remote.origin.url'],),
3090 '/cache/this-dir-doesnt-exist'),
3091 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
3092 False),
3093 (('logging.error',
Daniel Bratell4a60db42019-09-16 17:02:52 +00003094 'Remote "origin" for branch "master" points to'
3095 ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00003096 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003097 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00003098 self.assertIsNone(cl.GetRemoteUrl())
3099
3100 def test_get_remote_url_misconfigured_mirror(self):
3101 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003102
Edward Lemur298f2cf2019-02-22 21:40:39 +00003103 def selective_os_path_isdir_mock(path):
3104 if path == '/cache/this-dir-exists':
3105 return self._mocked_call('os.path.isdir', path)
3106 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003107
Edward Lemur298f2cf2019-02-22 21:40:39 +00003108 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3109 self.mock(logging, 'error',
3110 lambda *a: self._mocked_call('logging.error', *a))
3111
3112 self.calls = [
3113 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3114 ((['git', 'config', 'branch.master.merge'],), 'master'),
3115 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3116 ((['git', 'config', 'remote.origin.url'],),
3117 '/cache/this-dir-exists'),
3118 (('os.path.isdir', '/cache/this-dir-exists'), True),
3119 # Runs in /cache/this-dir-exists.
3120 ((['git', 'config', 'remote.origin.url'],), ''),
3121 (('logging.error',
3122 'Remote "%(remote)s" for branch "%(branch)s" points to '
3123 '"%(cache_path)s", but it is misconfigured.\n'
3124 '"%(cache_path)s" must be a git repo and must have a remote named '
3125 '"%(remote)s" pointing to the git host.', {
3126 'remote': 'origin',
3127 'cache_path': '/cache/this-dir-exists',
3128 'branch': 'master'}
3129 ), None),
3130 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003131 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00003132 self.assertIsNone(cl.GetRemoteUrl())
3133
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003134 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003135 self.calls = [
3136 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3137 ((['git', 'config', 'branch.master.merge'],), 'master'),
3138 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3139 ((['git', 'config', 'remote.origin.url'],),
3140 'https://chromium.googlesource.com/a/my/repo.git/'),
3141 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003142 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003143 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3144
3145 def test_gerrit_change_identifier_without_project(self):
3146 self.calls = [
3147 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3148 ((['git', 'config', 'branch.master.merge'],), 'master'),
3149 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3150 ((['git', 'config', 'remote.origin.url'],), CERR1),
3151 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003152 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003153 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003154
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003155
Edward Lemur4c707a22019-09-24 21:13:43 +00003156class CMDTryTestCase(unittest.TestCase):
3157 def setUp(self):
3158 super(CMDTryTestCase, self).setUp()
3159 mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
3160 mock.patch('git_cl.uuid.uuid4', _constantFn('uuid4')).start()
3161 mock.patch('git_cl.Changelist.GetIssue', _constantFn(123456)).start()
3162 mock.patch('git_cl.Changelist.GetCodereviewServer',
3163 _constantFn('https://chromium-review.googlesource.com')).start()
3164 mock.patch('git_cl.Changelist.SetPatchset').start()
3165 mock.patch('git_cl.Changelist.GetPatchset', _constantFn(7)).start()
3166 mock.patch('git_cl.auth.get_authenticator_for_host', AuthenticatorMock())
3167 self.addCleanup(mock.patch.stopall)
3168
3169 @mock.patch('git_cl.Changelist._GetChangeDetail')
3170 @mock.patch('git_cl.Changelist.SetCQState')
3171 @mock.patch('git_cl._get_bucket_map', _constantFn({}))
3172 def testSetCQDryRunByDefault(self, mockSetCQState, mockGetChangeDetail):
3173 mockSetCQState.return_value = 0
3174 mockGetChangeDetail.return_value = {
3175 'project': 'depot_tools',
3176 'status': 'OPEN',
3177 'owner': {'email': 'owner@e.mail'},
3178 'current_revision': 'beeeeeef',
3179 'revisions': {
3180 'deadbeaf': {
3181 '_number': 6,
3182 },
3183 'beeeeeef': {
3184 '_number': 7,
3185 'fetch': {'http': {
3186 'url': 'https://chromium.googlesource.com/depot_tools',
3187 'ref': 'refs/changes/56/123456/7'
3188 }},
3189 },
3190 },
3191 }
3192
3193 self.assertEqual(0, git_cl.main(['try']))
3194 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3195 self.assertEqual(
3196 sys.stdout.getvalue(),
3197 'Scheduling CQ dry run on: '
3198 'https://chromium-review.googlesource.com/123456\n')
3199
3200 @mock.patch('git_cl.Changelist._GetChangeDetail')
3201 @mock.patch('git_cl._call_buildbucket')
3202 def testScheduleOnBuildbucket(self, mockCallBuildbucket, mockGetChangeDetail):
3203 mockCallBuildbucket.return_value = {}
3204 mockGetChangeDetail.return_value = {
3205 'project': 'depot_tools',
3206 'status': 'OPEN',
3207 'owner': {'email': 'owner@e.mail'},
3208 'current_revision': 'beeeeeef',
3209 'revisions': {
3210 'deadbeaf': {
3211 '_number': 6,
3212 },
3213 'beeeeeef': {
3214 '_number': 7,
3215 'fetch': {'http': {
3216 'url': 'https://chromium.googlesource.com/depot_tools',
3217 'ref': 'refs/changes/56/123456/7'
3218 }},
3219 },
3220 },
3221 }
3222
3223 self.assertEqual(0, git_cl.main([
3224 'try', '-B', 'luci.chromium.try', '-b', 'win',
3225 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3226 self.assertIn(
3227 'Scheduling jobs on:\nBucket: luci.chromium.try',
3228 git_cl.sys.stdout.getvalue())
3229
3230 expected_request = {
3231 "requests": [{
3232 "scheduleBuild": {
3233 "requestId": "uuid4",
3234 "builder": {
3235 "project": "chromium",
3236 "builder": "win",
3237 "bucket": "try",
3238 },
3239 "gerritChanges": [{
3240 "project": "depot_tools",
3241 "host": "chromium-review.googlesource.com",
3242 "patchset": 7,
3243 "change": 123456,
3244 }],
3245 "properties": {
3246 "category": "git_cl_try",
3247 "json": [{"a": 1}, None],
3248 "key": "val",
Edward Lemurf0faf482019-09-25 20:40:17 +00003249 'patch_issue': 123456,
3250 'patch_set': 7,
3251 'patch_project': 'depot_tools',
3252 'patch_storage': 'gerrit',
3253 'patch_ref': 'refs/changes/56/123456/7',
3254 'patch_repository_url':
3255 'https://chromium.googlesource.com/depot_tools',
3256 'patch_gerrit_url':
3257 'https://chromium-review.googlesource.com',
Edward Lemur4c707a22019-09-24 21:13:43 +00003258 },
3259 "tags": [
3260 {"value": "win", "key": "builder"},
3261 {"value": "git_cl_try", "key": "user_agent"},
3262 ],
3263 },
3264 }],
3265 }
3266 mockCallBuildbucket.assert_called_with(
3267 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3268
Edward Lemur4c707a22019-09-24 21:13:43 +00003269 @mock.patch('git_cl.Changelist._GetChangeDetail')
3270 def testScheduleOnBuildbucket_WrongBucket(self, mockGetChangeDetail):
3271 mockGetChangeDetail.return_value = {
3272 'project': 'depot_tools',
3273 'status': 'OPEN',
3274 'owner': {'email': 'owner@e.mail'},
3275 'current_revision': 'beeeeeef',
3276 'revisions': {
3277 'deadbeaf': {
3278 '_number': 6,
3279 },
3280 'beeeeeef': {
3281 '_number': 7,
3282 'fetch': {'http': {
3283 'url': 'https://chromium.googlesource.com/depot_tools',
3284 'ref': 'refs/changes/56/123456/7'
3285 }},
3286 },
3287 },
3288 }
3289
3290 self.assertEqual(0, git_cl.main([
3291 'try', '-B', 'not-a-bucket', '-b', 'win',
3292 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3293 self.assertIn(
3294 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3295 git_cl.sys.stdout.getvalue())
3296
3297 def test_parse_bucket(self):
3298 test_cases = [
3299 {
3300 'bucket': 'chromium/try',
3301 'result': ('chromium', 'try'),
3302 },
3303 {
3304 'bucket': 'luci.chromium.try',
3305 'result': ('chromium', 'try'),
3306 'has_warning': True,
3307 },
3308 {
3309 'bucket': 'skia.primary',
3310 'result': ('skia', 'skia.primary'),
3311 'has_warning': True,
3312 },
3313 {
3314 'bucket': 'not-a-bucket',
3315 'result': (None, None),
3316 },
3317 ]
3318
3319 for test_case in test_cases:
3320 git_cl.sys.stdout.truncate(0)
3321 self.assertEqual(
3322 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3323 if test_case.get('has_warning'):
3324 self.assertIn(
3325 'WARNING Please specify buckets', git_cl.sys.stdout.getvalue())
3326
3327
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003328class CMDUploadTestCase(unittest.TestCase):
3329
3330 def setUp(self):
3331 super(CMDUploadTestCase, self).setUp()
3332 mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
3333 mock.patch('git_cl.uuid.uuid4', _constantFn('uuid4')).start()
3334 mock.patch('git_cl.Changelist.GetIssue', _constantFn(123456)).start()
3335 mock.patch('git_cl.Changelist.GetCodereviewServer',
3336 _constantFn('https://chromium-review.googlesource.com')).start()
3337 mock.patch('git_cl.Changelist.GetMostRecentPatchset',
3338 _constantFn(7)).start()
3339 mock.patch('git_cl.auth.get_authenticator_for_host', AuthenticatorMock())
3340 self.addCleanup(mock.patch.stopall)
3341
3342 @mock.patch('git_cl.fetch_try_jobs')
3343 @mock.patch('git_cl._trigger_try_jobs')
3344 @mock.patch('git_cl.Changelist._GetChangeDetail')
3345 @mock.patch('git_cl.Changelist.CMDUpload', _constantFn(0))
3346 def testUploadRetryFailed(self, mockGetChangeDetail, mockTriggerTryJobs,
3347 mockFetchTryJobs):
3348 # This test mocks out the actual upload part, and just asserts that after
3349 # upload, if --retry-failed is added, then the tool will fetch try jobs
3350 # from the previous patchset and trigger the right builders on the latest
3351 # patchset.
3352 mockGetChangeDetail.return_value = {
3353 'project': 'depot_tools',
3354 'status': 'OPEN',
3355 'owner': {'email': 'owner@e.mail'},
3356 'current_revision': 'beeeeeef',
3357 'revisions': {
3358 'deadbeaf': {
3359 '_number': 6,
3360 },
3361 'beeeeeef': {
3362 '_number': 7,
3363 'fetch': {'http': {
3364 'url': 'https://chromium.googlesource.com/depot_tools',
3365 'ref': 'refs/changes/56/123456/7'
3366 }},
3367 },
3368 },
3369 }
3370 mockFetchTryJobs.return_value = {
3371 '9000': {
3372 'id': '9000',
3373 'project': 'infra',
3374 'bucket': 'luci.infra.try',
3375 'created_by': 'user:someone@chromium.org',
3376 'created_ts': '147200002222000',
3377 'experimental': False,
3378 'parameters_json': json.dumps({
3379 'builder_name': 'red-bot',
3380 'properties': {'category': 'cq'},
3381 }),
3382 'status': 'COMPLETED',
3383 'result': 'FAILURE',
3384 'tags': ['user_agent:cq'],
3385 },
3386 8000: {
3387 'id': '8000',
3388 'project': 'infra',
3389 'bucket': 'luci.infra.try',
3390 'created_by': 'user:someone@chromium.org',
3391 'created_ts': '147200002222020',
3392 'experimental': False,
3393 'parameters_json': json.dumps({
3394 'builder_name': 'green-bot',
3395 'properties': {'category': 'cq'},
3396 }),
3397 'status': 'COMPLETED',
3398 'result': 'SUCCESS',
3399 'tags': ['user_agent:cq'],
3400 },
3401 }
3402 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
3403 mockFetchTryJobs.assert_called_with(
3404 mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', 7)
3405 buckets = {'infra/try': {'red-bot': []}}
3406 mockTriggerTryJobs.assert_called_once_with(
3407 mock.ANY, mock.ANY, buckets, mock.ANY, 8)
3408
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003409if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003410 logging.basicConfig(
3411 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003412 unittest.main()