blob: 452836819d9dde838a23cf8e1c00bed6f30b2569 [file] [log] [blame]
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001#!/usr/bin/env python
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Unit tests for git_cl.py."""
7
Andrii Shyshkalovcd6a9362016-12-07 12:04:12 +01008import contextlib
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01009import datetime
tandriide281ae2016-10-12 06:02:30 -070010import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010011import logging
maruel@chromium.orgddd59412011-11-30 14:20:38 +000012import os
maruel@chromium.orga3353652011-11-30 14:26:57 +000013import StringIO
maruel@chromium.orgddd59412011-11-30 14:20:38 +000014import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070015import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000016import unittest
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +000017import urlparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000018
19sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
20
21from testing_support.auto_stub import TestCase
22
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000023import metrics
24# We have to disable monitoring before importing git_cl.
25metrics.DISABLE_METRICS_COLLECTION = True
26
maruel@chromium.orgddd59412011-11-30 14:20:38 +000027import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000028import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000029import git_footers
maruel@chromium.orgddd59412011-11-30 14:20:38 +000030import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031
tandrii5d48c322016-08-18 16:19:37 -070032def callError(code=1, cmd='', cwd='', stdout='', stderr=''):
33 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
34
35
36CERR1 = callError(1)
37
38
Aaron Gable9a03ae02017-11-03 11:31:07 -070039def MakeNamedTemporaryFileMock(expected_content):
40 class NamedTemporaryFileMock(object):
41 def __init__(self, *args, **kwargs):
42 self.name = '/tmp/named'
43 self.expected_content = expected_content
44
45 def __enter__(self):
46 return self
47
48 def __exit__(self, _type, _value, _tb):
49 pass
50
51 def write(self, content):
52 if self.expected_content:
53 assert content == self.expected_content
54
55 def close(self):
56 pass
57
58 return NamedTemporaryFileMock
59
60
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000061class ChangelistMock(object):
62 # A class variable so we can access it when we don't have access to the
63 # instance that's being set.
64 desc = ""
65 def __init__(self, **kwargs):
66 pass
67 def GetIssue(self):
68 return 1
Kenneth Russell61e2ed42017-02-15 11:47:13 -080069 def GetDescription(self, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000070 return ChangelistMock.desc
dsansomee2d6fd92016-09-08 00:10:47 -070071 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000072 ChangelistMock.desc = desc
73
tandrii5d48c322016-08-18 16:19:37 -070074
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000075class PresubmitMock(object):
76 def __init__(self, *args, **kwargs):
77 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080078 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
79
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000080 @staticmethod
81 def should_continue():
82 return True
83
84
85class RietveldMock(object):
86 def __init__(self, *args, **kwargs):
87 pass
maruel@chromium.org78936cb2013-04-11 00:17:52 +000088
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000089 @staticmethod
Kenneth Russell61e2ed42017-02-15 11:47:13 -080090 def get_description(issue, force=False):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000091 return 'Issue: %d' % issue
92
maruel@chromium.org78936cb2013-04-11 00:17:52 +000093 @staticmethod
94 def get_issue_properties(_issue, _messages):
95 return {
96 'reviewers': ['joe@chromium.org', 'john@chromium.org'],
97 'messages': [
98 {
99 'approval': True,
Aaron Gablea1bab272017-04-11 16:38:18 -0700100 'disapproval': False,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000101 'sender': 'john@chromium.org',
102 },
103 ],
Andrii Shyshkalov06a25022016-11-24 16:47:00 +0100104 'patchsets': [1, 20001],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000105 }
106
iannuccie53c9352016-08-17 14:40:40 -0700107 @staticmethod
108 def close_issue(_issue):
109 return 'Closed'
110
skobes6468b902016-10-24 08:45:10 -0700111 @staticmethod
112 def get_patch(issue, patchset):
113 return 'patch set from issue %s patchset %s' % (issue, patchset)
114
Andrii Shyshkalov06a25022016-11-24 16:47:00 +0100115 @staticmethod
116 def update_description(_issue, _description):
117 return 'Updated'
118
119 @staticmethod
120 def add_comment(_issue, _comment):
121 return 'Commented'
122
123
skobes6468b902016-10-24 08:45:10 -0700124class GitCheckoutMock(object):
125 def __init__(self, *args, **kwargs):
126 pass
127
128 @staticmethod
129 def reset():
130 GitCheckoutMock.conflict = False
131
132 def apply_patch(self, p):
133 if GitCheckoutMock.conflict:
134 raise Exception('failed')
135
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000136
137class WatchlistsMock(object):
138 def __init__(self, _):
139 pass
140 @staticmethod
141 def GetWatchersForPaths(_):
142 return ['joe@example.com']
143
144
ukai@chromium.org78c4b982012-02-14 02:20:26 +0000145class CodereviewSettingsFileMock(object):
146 def __init__(self):
147 pass
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800148 # pylint: disable=no-self-use
ukai@chromium.org78c4b982012-02-14 02:20:26 +0000149 def read(self):
150 return ("CODE_REVIEW_SERVER: gerrit.chromium.org\n" +
andybons@chromium.org11f46eb2016-02-02 19:26:51 +0000151 "GERRIT_HOST: True\n")
ukai@chromium.org78c4b982012-02-14 02:20:26 +0000152
153
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000154class AuthenticatorMock(object):
155 def __init__(self, *_args):
156 pass
157 def has_cached_credentials(self):
158 return True
tandrii221ab252016-10-06 08:12:04 -0700159 def authorize(self, http):
160 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000161
162
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100163def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000164 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
165
166 Usage:
167 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100168 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000169
170 OR
171 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100172 CookiesAuthenticatorMockFactory(
173 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000174 """
175 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800176 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000177 # Intentionally not calling super() because it reads actual cookie files.
178 pass
179 @classmethod
180 def get_gitcookies_path(cls):
181 return '~/.gitcookies'
182 @classmethod
183 def get_netrc_path(cls):
184 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100185 def _get_auth_for_host(self, host):
186 if same_auth:
187 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000188 return (hosts_with_creds or {}).get(host)
189 return CookiesAuthenticatorMock
190
Aaron Gable9a03ae02017-11-03 11:31:07 -0700191
kmarshall9249e012016-08-23 12:02:16 -0700192class MockChangelistWithBranchAndIssue():
193 def __init__(self, branch, issue):
194 self.branch = branch
195 self.issue = issue
196 def GetBranch(self):
197 return self.branch
198 def GetIssue(self):
199 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000200
tandriic2405f52016-10-10 08:13:15 -0700201
202class SystemExitMock(Exception):
203 pass
204
205
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000206class TestGitClBasic(unittest.TestCase):
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100207 def test_get_description(self):
208 cl = git_cl.Changelist(issue=1, codereview='rietveld',
209 codereview_host='host')
210 cl.description = 'x'
211 cl.has_description = True
Kenneth Russell61e2ed42017-02-15 11:47:13 -0800212 cl._codereview_impl.FetchDescription = lambda *a, **kw: 'y'
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100213 self.assertEquals(cl.GetDescription(), 'x')
214 self.assertEquals(cl.GetDescription(force=True), 'y')
215 self.assertEquals(cl.GetDescription(), 'y')
216
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700217 def test_description_footers(self):
218 cl = git_cl.Changelist(issue=1, codereview='gerrit',
219 codereview_host='host')
220 cl.description = '\n'.join([
221 'This is some message',
222 '',
223 'It has some lines',
224 'and, also',
225 '',
226 'Some: Really',
227 'Awesome: Footers',
228 ])
229 cl.has_description = True
230 cl._codereview_impl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
231 msg, footers = cl.GetDescriptionFooters()
232 self.assertEquals(
233 msg, ['This is some message', '', 'It has some lines', 'and, also'])
234 self.assertEquals(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
235
236 msg.append('wut')
237 footers.append(('gnarly-dude', 'beans'))
238 cl.UpdateDescriptionFooters(msg, footers)
239 self.assertEquals(cl.GetDescription().splitlines(), [
240 'This is some message',
241 '',
242 'It has some lines',
243 'and, also',
244 'wut'
245 '',
246 'Some: Really',
247 'Awesome: Footers',
248 'Gnarly-Dude: beans',
249 ])
250
tandriif9aefb72016-07-01 09:06:51 -0700251 def test_get_bug_line_values(self):
252 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
253 self.assertEqual(f('', ''), [])
254 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
255 self.assertEqual(f('v8', '456'), ['v8:456'])
256 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
257 # Not nice, but not worth carying.
258 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
259 ['v8:456', 'chromium:123', 'v8:123'])
260
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100261 def _test_git_number(self, parent_msg, dest_ref, child_msg,
262 parent_hash='parenthash'):
263 desc = git_cl.ChangeDescription(child_msg)
264 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
265 return desc.description
266
267 def assertEqualByLine(self, actual, expected):
268 self.assertEqual(actual.splitlines(), expected.splitlines())
269
270 def test_git_number_bad_parent(self):
271 with self.assertRaises(ValueError):
272 self._test_git_number('Parent', 'refs/heads/master', 'Child')
273
274 def test_git_number_bad_parent_footer(self):
275 with self.assertRaises(AssertionError):
276 self._test_git_number(
277 'Parent\n'
278 '\n'
279 'Cr-Commit-Position: wrong',
280 'refs/heads/master', 'Child')
281
282 def test_git_number_bad_lineage_ignored(self):
283 actual = self._test_git_number(
284 'Parent\n'
285 '\n'
286 'Cr-Commit-Position: refs/heads/master@{#1}\n'
287 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
288 'refs/heads/master', 'Child')
289 self.assertEqualByLine(
290 actual,
291 'Child\n'
292 '\n'
293 'Cr-Commit-Position: refs/heads/master@{#2}\n'
294 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
295
296 def test_git_number_same_branch(self):
297 actual = self._test_git_number(
298 'Parent\n'
299 '\n'
300 'Cr-Commit-Position: refs/heads/master@{#12}',
301 dest_ref='refs/heads/master',
302 child_msg='Child')
303 self.assertEqualByLine(
304 actual,
305 'Child\n'
306 '\n'
307 'Cr-Commit-Position: refs/heads/master@{#13}')
308
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200309 def test_git_number_same_branch_mixed_footers(self):
310 actual = self._test_git_number(
311 'Parent\n'
312 '\n'
313 'Cr-Commit-Position: refs/heads/master@{#12}',
314 dest_ref='refs/heads/master',
315 child_msg='Child\n'
316 '\n'
317 'Broken-by: design\n'
318 'BUG=123')
319 self.assertEqualByLine(
320 actual,
321 'Child\n'
322 '\n'
323 'Broken-by: design\n'
324 'BUG=123\n'
325 'Cr-Commit-Position: refs/heads/master@{#13}')
326
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100327 def test_git_number_same_branch_with_originals(self):
328 actual = self._test_git_number(
329 'Parent\n'
330 '\n'
331 'Cr-Commit-Position: refs/heads/master@{#12}',
332 dest_ref='refs/heads/master',
333 child_msg='Child\n'
334 '\n'
335 'Some users are smart and insert their own footers\n'
336 '\n'
337 'Cr-Whatever: value\n'
338 'Cr-Commit-Position: refs/copy/paste@{#22}')
339 self.assertEqualByLine(
340 actual,
341 'Child\n'
342 '\n'
343 'Some users are smart and insert their own footers\n'
344 '\n'
345 'Cr-Original-Whatever: value\n'
346 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
347 'Cr-Commit-Position: refs/heads/master@{#13}')
348
349 def test_git_number_new_branch(self):
350 actual = self._test_git_number(
351 'Parent\n'
352 '\n'
353 'Cr-Commit-Position: refs/heads/master@{#12}',
354 dest_ref='refs/heads/branch',
355 child_msg='Child')
356 self.assertEqualByLine(
357 actual,
358 'Child\n'
359 '\n'
360 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
361 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
362
363 def test_git_number_lineage(self):
364 actual = self._test_git_number(
365 'Parent\n'
366 '\n'
367 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
368 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
369 dest_ref='refs/heads/branch',
370 child_msg='Child')
371 self.assertEqualByLine(
372 actual,
373 'Child\n'
374 '\n'
375 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
376 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
377
378 def test_git_number_moooooooore_lineage(self):
379 actual = self._test_git_number(
380 'Parent\n'
381 '\n'
382 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
383 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
384 dest_ref='refs/heads/mooore',
385 child_msg='Child')
386 self.assertEqualByLine(
387 actual,
388 'Child\n'
389 '\n'
390 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
391 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
392 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
393
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100394 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700395 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100396 actual = self._test_git_number(
397 'CQ commit on fresh new branch + numbering.\n'
398 '\n'
399 'NOTRY=True\n'
400 'NOPRESUBMIT=True\n'
401 'BUG=\n'
402 '\n'
403 'Review-Url: https://codereview.chromium.org/2577703003\n'
404 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
405 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
406 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
407 dest_ref='refs/heads/gnumb-test/cl',
408 child_msg='git cl on fresh new branch + numbering.\n'
409 '\n'
410 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
411 self.assertEqualByLine(
412 actual,
413 'git cl on fresh new branch + numbering.\n'
414 '\n'
415 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
416 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
417 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
418 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
419 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100420
421 def test_git_number_cherry_pick(self):
422 actual = self._test_git_number(
423 'Parent\n'
424 '\n'
425 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
426 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
427 dest_ref='refs/heads/branch',
428 child_msg='Child, which is cherry-pick from master\n'
429 '\n'
430 'Cr-Commit-Position: refs/heads/master@{#100}\n'
431 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
432 self.assertEqualByLine(
433 actual,
434 'Child, which is cherry-pick from master\n'
435 '\n'
436 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
437 '\n'
438 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
439 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
440 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
441
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000442 def test_gerrit_mirror_hack(self):
443 cr = 'chromium-review.googlesource.com'
444 url0 = 'https://%s/a/changes/x?a=b' % cr
445 origMirrors = git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES
446 try:
447 git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = ['us1', 'us2']
448 url1 = git_cl.gerrit_util._UseGerritMirror(url0, cr)
449 url2 = git_cl.gerrit_util._UseGerritMirror(url1, cr)
450 url3 = git_cl.gerrit_util._UseGerritMirror(url2, cr)
451
452 self.assertNotEqual(url1, url2)
453 self.assertEqual(sorted((url1, url2)), [
454 'https://us1-mirror-chromium-review.googlesource.com/a/changes/x?a=b',
455 'https://us2-mirror-chromium-review.googlesource.com/a/changes/x?a=b'])
456 self.assertEqual(url1, url3)
457 finally:
458 git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = origMirrors
459
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000460
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200461class TestParseIssueURL(unittest.TestCase):
462 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
463 codereview=None, fail=False):
464 self.assertIsNotNone(parsed)
465 if fail:
466 self.assertFalse(parsed.valid)
467 return
468 self.assertTrue(parsed.valid)
469 self.assertEqual(parsed.issue, issue)
470 self.assertEqual(parsed.patchset, patchset)
471 self.assertEqual(parsed.hostname, hostname)
472 self.assertEqual(parsed.codereview, codereview)
473
474 def _run_and_validate(self, func, url, *args, **kwargs):
475 result = func(urlparse.urlparse(url))
476 if kwargs.pop('fail', False):
477 self.assertIsNone(result)
478 return None
479 self._validate(result, *args, fail=False, **kwargs)
480
481 def test_rietveld(self):
482 def test(url, *args, **kwargs):
483 self._run_and_validate(git_cl._RietveldChangelistImpl.ParseIssueURL, url,
484 *args, codereview='rietveld', **kwargs)
485
486 test('http://codereview.chromium.org/123',
487 123, None, 'codereview.chromium.org')
488 test('https://codereview.chromium.org/123',
489 123, None, 'codereview.chromium.org')
490 test('https://codereview.chromium.org/123/',
491 123, None, 'codereview.chromium.org')
492 test('https://codereview.chromium.org/123/whatever',
493 123, None, 'codereview.chromium.org')
494 test('https://codereview.chromium.org/123/#ps20001',
495 123, 20001, 'codereview.chromium.org')
496 test('http://codereview.chromium.org/download/issue123_4.diff',
497 123, 4, 'codereview.chromium.org')
498 # This looks like bad Gerrit, but is actually valid Rietveld, too.
499 test('https://chrome-review.source.com/123/4/',
500 123, None, 'chrome-review.source.com')
501
502 test('https://codereview.chromium.org/deadbeaf', fail=True)
503 test('https://codereview.chromium.org/api/123', fail=True)
504 test('bad://codereview.chromium.org/123', fail=True)
505 test('http://codereview.chromium.org/download/issue123_4.diffff', fail=True)
506
507 def test_gerrit(self):
508 def test(url, issue=None, patchset=None, hostname=None, fail=None):
509 self._test_ParseIssueUrl(
510 git_cl._GerritChangelistImpl.ParseIssueURL,
511 url, issue, patchset, hostname, fail)
512 def test(url, *args, **kwargs):
513 self._run_and_validate(git_cl._GerritChangelistImpl.ParseIssueURL, url,
514 *args, codereview='gerrit', **kwargs)
515
516 test('http://chrome-review.source.com/c/123',
517 123, None, 'chrome-review.source.com')
518 test('https://chrome-review.source.com/c/123/',
519 123, None, 'chrome-review.source.com')
520 test('https://chrome-review.source.com/c/123/4',
521 123, 4, 'chrome-review.source.com')
522 test('https://chrome-review.source.com/#/c/123/4',
523 123, 4, 'chrome-review.source.com')
524 test('https://chrome-review.source.com/c/123/4',
525 123, 4, 'chrome-review.source.com')
526 test('https://chrome-review.source.com/123',
527 123, None, 'chrome-review.source.com')
528 test('https://chrome-review.source.com/123/4',
529 123, 4, 'chrome-review.source.com')
530
531 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
532 test('https://chrome-review.source.com/c/abc/', fail=True)
533 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
534
535 def test_ParseIssueNumberArgument(self):
536 def test(arg, *args, **kwargs):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +0200537 codereview_hint = kwargs.pop('hint', None)
538 self._validate(git_cl.ParseIssueNumberArgument(arg, codereview_hint),
539 *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200540
541 test('123', 123)
542 test('', fail=True)
543 test('abc', fail=True)
544 test('123/1', fail=True)
545 test('123a', fail=True)
546 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
547 # Rietveld.
548 test('https://codereview.source.com/www123', fail=True)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +0200549 # Matches both, but we take Rietveld now by default.
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200550 test('https://codereview.source.com/123',
551 123, None, 'codereview.source.com', 'rietveld')
Andrii Shyshkalovc9712392017-04-11 13:35:21 +0200552 # Matches both, but we take Gerrit if specifically requested.
553 test('https://codereview.source.com/123',
554 123, None, 'codereview.source.com', 'gerrit',
555 hint='gerrit')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200556 # Gerrrit.
557 test('https://chrome-review.source.com/c/123/4',
558 123, 4, 'chrome-review.source.com', 'gerrit')
559 test('https://chrome-review.source.com/bad/123/4', fail=True)
560
561
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100562class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100563 def setUp(self):
564 super(GitCookiesCheckerTest, self).setUp()
565 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100566 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100567
568 def mock_hosts_creds(self, subhost_identity_pairs):
569 def ensure_googlesource(h):
570 if not h.endswith(self.c._GOOGLESOURCE):
571 assert not h.endswith('.')
572 return h + '.' + self.c._GOOGLESOURCE
573 return h
574 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
575 for h, i in subhost_identity_pairs]
576
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200577 def test_identity_parsing(self):
578 self.assertEqual(self.c._parse_identity('ldap.google.com'),
579 ('ldap', 'google.com'))
580 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
581 ('ldap', 'example.com'))
582 # Specical case because we know there are no subdomains in chromium.org.
583 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
584 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800585 # Pathological: ".period." can be either username OR domain, more likely
586 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200587 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
588 ('note', 'period.example.com'))
589
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100590 def test_analysis_nothing(self):
591 self.c._all_hosts = []
592 self.assertFalse(self.c.has_generic_host())
593 self.assertEqual(set(), self.c.get_conflicting_hosts())
594 self.assertEqual(set(), self.c.get_duplicated_hosts())
595 self.assertEqual(set(), self.c.get_partially_configured_hosts())
596 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
597
598 def test_analysis(self):
599 self.mock_hosts_creds([
600 ('.googlesource.com', 'git-example.chromium.org'),
601
602 ('chromium', 'git-example.google.com'),
603 ('chromium-review', 'git-example.google.com'),
604 ('chrome-internal', 'git-example.chromium.org'),
605 ('chrome-internal-review', 'git-example.chromium.org'),
606 ('conflict', 'git-example.google.com'),
607 ('conflict-review', 'git-example.chromium.org'),
608 ('dup', 'git-example.google.com'),
609 ('dup', 'git-example.google.com'),
610 ('dup-review', 'git-example.google.com'),
611 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200612 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100613 ])
614 self.assertTrue(self.c.has_generic_host())
615 self.assertEqual(set(['conflict.googlesource.com']),
616 self.c.get_conflicting_hosts())
617 self.assertEqual(set(['dup.googlesource.com']),
618 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200619 self.assertEqual(set(['partial.googlesource.com',
620 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100621 self.c.get_partially_configured_hosts())
622 self.assertEqual(set(['chromium.googlesource.com',
623 'chrome-internal.googlesource.com']),
624 self.c.get_hosts_with_wrong_identities())
625
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100626 def test_report_no_problems(self):
627 self.test_analysis_nothing()
628 self.mock(sys, 'stdout', StringIO.StringIO())
629 self.assertFalse(self.c.find_and_report_problems())
630 self.assertEqual(sys.stdout.getvalue(), '')
631
632 def test_report(self):
633 self.test_analysis()
634 self.mock(sys, 'stdout', StringIO.StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200635 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
636 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100637 self.assertTrue(self.c.find_and_report_problems())
638 with open(os.path.join(os.path.dirname(__file__),
639 'git_cl_creds_check_report.txt')) as f:
640 expected = f.read()
641 def by_line(text):
642 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700643 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200644 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100645
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800646
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000647class TestGitCl(TestCase):
648 def setUp(self):
649 super(TestGitCl, self).setUp()
650 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700651 self._calls_done = []
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000652 self.mock(subprocess2, 'call', self._mocked_call)
653 self.mock(subprocess2, 'check_call', self._mocked_call)
654 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700655 self.mock(subprocess2, 'communicate',
656 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000657 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000658 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000659 self.mock(git_common, 'get_or_create_merge_base',
660 lambda *a: (
661 self._mocked_call(['get_or_create_merge_base']+list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000662 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000663 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100664 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
665 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700666 self.mock(git_cl, 'write_json', lambda path, contents:
667 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000668 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000669 self.mock(git_cl.rietveld, 'Rietveld', RietveldMock)
maruel@chromium.org4bac4b52012-11-27 20:33:52 +0000670 self.mock(git_cl.rietveld, 'CachingRietveld', RietveldMock)
skobes6468b902016-10-24 08:45:10 -0700671 self.mock(git_cl.checkout, 'GitCheckout', GitCheckoutMock)
672 GitCheckoutMock.reset()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000673 self.mock(git_cl.upload, 'RealMain', self.fail)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000674 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000675 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100676 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
677 lambda *args, **kwargs: self._mocked_call(
678 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700679 self.mock(git_cl.gerrit_util, 'GetChangeComments',
680 lambda *args, **kwargs: self._mocked_call(
681 'GetChangeComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100682 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700683 lambda h, i, reviewers, ccs, notify: self._mocked_call(
684 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700685 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700686 lambda h, i, msg=None, labels=None, notify=None:
687 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700688 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
689 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000690 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
691 classmethod(lambda _: False))
tandriic2405f52016-10-10 08:13:15 -0700692 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100693 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000694 # It's important to reset settings to not have inter-tests interference.
695 git_cl.settings = None
696
697 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000698 try:
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100699 self.assertEquals([], self.calls)
700 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000701 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100702 raise
703 # Sadly, has_failed() returns True if this OR any other tests before this
704 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200705 git_cl.logging.error(
706 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100707 'There are un-consumed self.calls after this test has finished.\n'
708 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700709 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200710 'If you are already running only this test, then **first** fix the '
711 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100712 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700713 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100714 'and follow instructions above.\n' +
715 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000716 finally:
717 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000718
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000719 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000720 self.assertTrue(
721 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700722 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000723 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000724 expected_args, result = top
725
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000726 # Also logs otherwise it could get caught in a try/finally and be hard to
727 # diagnose.
728 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700729 N = 5
730 prior_calls = '\n '.join(
731 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
732 for i, c in enumerate(self._calls_done[-N:]))
733 following_calls = '\n '.join(
734 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
735 for i, c in enumerate(self.calls[:N]))
736 extended_msg = (
737 'A few prior calls:\n %s\n\n'
738 'This (expected):\n @%d: %r\n'
739 'This (actual):\n @%d: %r\n\n'
740 'A few following expected calls:\n %s' %
741 (prior_calls, len(self._calls_done), expected_args,
742 len(self._calls_done), args, following_calls))
743 git_cl.logging.error(extended_msg)
744
tandrii99a72f22016-08-17 14:33:24 -0700745 self.fail('@%d\n'
746 ' Expected: %r\n'
747 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700748 len(self._calls_done), expected_args, args))
749
750 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700751 if isinstance(result, Exception):
752 raise result
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000753 return result
754
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100755 def test_ask_for_explicit_yes_true(self):
756 self.calls = [
757 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
758 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
759 ]
760 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
761
tandrii48df5812016-10-17 03:55:37 -0700762 def test_LoadCodereviewSettingsFromFile_gerrit(self):
763 codereview_file = StringIO.StringIO('GERRIT_HOST: true')
764 self.calls = [
765 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
766 ((['git', 'config', '--unset-all', 'rietveld.private'],), CERR1),
767 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
768 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
769 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
770 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700771 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
772 CERR1),
773 ((['git', 'config', '--unset-all', 'rietveld.project'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700774 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
775 CERR1),
776 ((['git', 'config', 'gerrit.host', 'true'],), ''),
777 ]
778 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
779
maruel@chromium.orga3353652011-11-30 14:26:57 +0000780 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000781 def _is_gerrit_calls(cls, gerrit=False):
782 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
783 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
784
785 @classmethod
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000786 def _upload_calls(cls, private, no_autocc):
Aaron Gable13101a62018-02-09 13:20:41 -0800787 return (cls._rietveld_git_base_calls() +
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000788 cls._git_upload_calls(private, no_autocc))
maruel@chromium.orga3353652011-11-30 14:26:57 +0000789
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000790 @classmethod
Aaron Gable13101a62018-02-09 13:20:41 -0800791 def _rietveld_upload_no_rev_calls(cls):
792 return (cls._rietveld_git_base_calls() + [
Andrii Shyshkalov73827d12017-04-12 15:05:11 +0200793 ((['git', 'config', 'core.editor'],), ''),
794 ])
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000795
796 @classmethod
Aaron Gable13101a62018-02-09 13:20:41 -0800797 def _rietveld_git_base_calls(cls):
798 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
799 '-l100000', '-C50', 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000800
Aaron Gable13101a62018-02-09 13:20:41 -0800801 return cls._is_gerrit_calls() + [
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000802 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii33a46ff2016-08-23 05:53:40 -0700803 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
804 ((['git', 'config', 'branch.master.gerritissue'],), CERR1),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000805 ((['git', 'config', 'rietveld.server'],),
806 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000807 ((['git', 'config', 'branch.master.merge'],), 'master'),
808 ((['git', 'config', 'branch.master.remote'],), 'origin'),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000809 ((['get_or_create_merge_base', 'master', 'master'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000810 'fake_ancestor_sha'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000811 ] + cls._git_sanity_checks('fake_ancestor_sha', 'master') + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000812 ((['git', 'rev-parse', '--show-cdup'],), ''),
813 ((['git', 'rev-parse', 'HEAD'],), '12345'),
Aaron Gable7817f022017-12-12 09:43:17 -0800814 ((['git', '-c', 'core.quotePath=false', 'diff',
815 '--name-status', '--no-renames', '-r', 'fake_ancestor_sha...', '.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000816 'M\t.gitignore\n'),
tandrii33a46ff2016-08-23 05:53:40 -0700817 ((['git', 'config', 'branch.master.rietveldpatchset'],), CERR1),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000818 ((['git', 'log', '--pretty=format:%s%n%n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000819 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000820 'foo'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000821 ((['git', 'config', 'user.email'],), 'me@example.com'),
iannucci@chromium.org79540052012-10-19 23:15:26 +0000822 stat_call,
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000823 ((['git', 'log', '--pretty=format:%s\n\n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000824 'fake_ancestor_sha..HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000825 'desc\n'),
Aaron Gable3a16ed12017-03-23 10:51:55 -0700826 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
maruel@chromium.orga3353652011-11-30 14:26:57 +0000827 ]
828
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000829 @classmethod
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000830 def _git_upload_calls(cls, private, no_autocc):
831 if private or no_autocc:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000832 cc_call = []
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000833 else:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000834 cc_call = [((['git', 'config', 'rietveld.cc'],), '')]
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000835
836 if private:
837 private_call = []
838 else:
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000839 private_call = [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000840 ((['git', 'config', 'rietveld.private'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000841
maruel@chromium.orga3353652011-11-30 14:26:57 +0000842 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000843 ((['git', 'config', 'core.editor'],), ''),
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000844 ] + cc_call + private_call + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000845 ((['git', 'config', 'branch.master.base-url'],), ''),
Aaron Gable1bc7bfe2016-12-19 10:08:14 -0800846 ((['git', 'config', 'remote.origin.url'],), ''),
sheyang@chromium.org152cf832014-06-11 21:37:49 +0000847 ((['git', 'config', 'rietveld.project'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -0700848 ((['git', 'config', 'branch.master.rietveldissue', '1'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000849 ((['git', 'config', 'branch.master.rietveldserver',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000850 'https://codereview.example.com'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000851 ((['git',
tandrii33a46ff2016-08-23 05:53:40 -0700852 'config', 'branch.master.rietveldpatchset', '2'],), ''),
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000853 ] + cls._git_post_upload_calls()
854
855 @classmethod
856 def _git_post_upload_calls(cls):
857 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000858 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
859 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
860 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000861 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000862 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000863 ]
864
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000865 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000866 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000867 fake_ancestor = 'fake_ancestor'
868 fake_cl = 'fake_cl_for_patch'
869 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000870 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000871 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000872 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000873 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000874 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000875 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000876 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000877 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700878 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000879 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000880 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000881 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000882 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000883 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000884 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000885 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000886 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000887 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000888 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000889 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000890
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000891 @staticmethod
Aaron Gable13101a62018-02-09 13:20:41 -0800892 def _cmd_line(description, args, private, cc):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000893 """Returns the upload command line passed to upload.RealMain()."""
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000894 return [
Daniel Cheng7227d212017-11-17 08:12:37 -0800895 'upload', '--assume_yes', '--server', 'https://codereview.example.com',
maruel@chromium.org71e12a92012-02-14 02:34:15 +0000896 '--message', description
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000897 ] + args + [
Daniel Cheng7227d212017-11-17 08:12:37 -0800898 '--cc',
899 ','.join(
900 ['joe@example.com', 'chromium-reviews+test-more-cc@chromium.org'] +
901 cc),
Aaron Gable13101a62018-02-09 13:20:41 -0800902 ] + (['--private'] if private else []) + ['fake_ancestor_sha', 'HEAD']
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000903
904 def _run_reviewer_test(
905 self,
906 upload_args,
907 expected_description,
908 returned_description,
909 final_description,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000910 reviewers,
bradnelsond975b302016-10-23 12:20:23 -0700911 cc=None):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000912 """Generic reviewer test framework."""
tandrii@chromium.org28253532016-04-14 13:46:56 +0000913 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
iannucci@chromium.org79540052012-10-19 23:15:26 +0000914
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000915 private = '--private' in upload_args
bradnelsond975b302016-10-23 12:20:23 -0700916 cc = cc or []
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000917 no_autocc = '--no-autocc' in upload_args
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000918
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000919 self.calls = self._upload_calls(private, no_autocc)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000920
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000921 def RunEditor(desc, _, **kwargs):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000922 self.assertEquals(
923 '# Enter a description of the change.\n'
janx@chromium.org104b2db2013-04-18 12:58:40 +0000924 '# This will be displayed on the codereview site.\n'
alancutter@chromium.org63a4d7f2013-05-31 02:22:45 +0000925 '# The first line will also be used as the subject of the review.\n'
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +0000926 '#--------------------This line is 72 characters long'
927 '--------------------\n' +
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000928 expected_description,
929 desc)
930 return returned_description
931 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000932
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000933 def check_upload(args):
Aaron Gable13101a62018-02-09 13:20:41 -0800934 cmd_line = self._cmd_line(final_description, reviewers, private, cc)
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000935 self.assertEquals(cmd_line, args)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000936 return 1, 2
937 self.mock(git_cl.upload, 'RealMain', check_upload)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000938
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000939 git_cl.main(['upload'] + upload_args)
940
941 def test_no_reviewer(self):
942 self._run_reviewer_test(
943 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000944 'desc\n\nBUG=',
945 '# Blah blah comment.\ndesc\n\nBUG=',
946 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000947 [])
948
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000949 def test_private(self):
950 self._run_reviewer_test(
951 ['--private'],
952 'desc\n\nBUG=',
953 '# Blah blah comment.\ndesc\n\nBUG=\n',
954 'desc\n\nBUG=',
955 [])
956
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +0000957 def test_no_autocc(self):
958 self._run_reviewer_test(
959 ['--no-autocc'],
960 'desc\n\nBUG=',
961 '# Blah blah comment.\ndesc\n\nBUG=\n',
962 'desc\n\nBUG=',
963 [])
964
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000965 def test_reviewers_cmd_line(self):
966 # Reviewer is passed as-is
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000967 description = 'desc\n\nR=foo@example.com\nBUG='
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000968 self._run_reviewer_test(
969 ['-r' 'foo@example.com'],
970 description,
971 '\n%s\n' % description,
972 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000973 ['--reviewers=foo@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000974
975 def test_reviewer_tbr_overriden(self):
976 # Reviewer is overriden with TBR
977 # Also verifies the regexp work without a trailing LF
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000978 description = 'Foo Bar\n\nTBR=reviewer@example.com'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000979 self._run_reviewer_test(
980 ['-r' 'foo@example.com'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000981 'desc\n\nR=foo@example.com\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000982 description.strip('\n'),
983 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000984 ['--reviewers=reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000985
986 def test_reviewer_multiple(self):
987 # Handles multiple R= or TBR= lines.
988 description = (
bradnelsond975b302016-10-23 12:20:23 -0700989 'Foo Bar\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
990 'CC=more@example.com,people@example.com')
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000991 self._run_reviewer_test(
992 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000993 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000994 description,
995 description,
bradnelsond975b302016-10-23 12:20:23 -0700996 ['--reviewers=another@example.com,reviewer@example.com'],
997 cc=['more@example.com', 'people@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000998
maruel@chromium.orga3353652011-11-30 14:26:57 +0000999 def test_reviewer_send_mail(self):
1000 # --send-mail can be used without -r if R= is used
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001001 description = 'Foo Bar\nR=reviewer@example.com'
maruel@chromium.orga3353652011-11-30 14:26:57 +00001002 self._run_reviewer_test(
1003 ['--send-mail'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001004 'desc\n\nBUG=',
maruel@chromium.orga3353652011-11-30 14:26:57 +00001005 description.strip('\n'),
1006 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001007 ['--reviewers=reviewer@example.com', '--send_mail'])
maruel@chromium.orga3353652011-11-30 14:26:57 +00001008
1009 def test_reviewer_send_mail_no_rev(self):
1010 # Fails without a reviewer.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +00001011 stdout = StringIO.StringIO()
Aaron Gable13101a62018-02-09 13:20:41 -08001012 self.calls = self._rietveld_upload_no_rev_calls() + [
tandriic2405f52016-10-10 08:13:15 -07001013 ((['DieWithError', 'Must specify reviewers to send email.'],),
1014 SystemExitMock())
1015 ]
1016
1017 def RunEditor(desc, _, **kwargs):
1018 return desc
1019 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
1020 self.mock(sys, 'stdout', stdout)
1021 with self.assertRaises(SystemExitMock):
maruel@chromium.orga3353652011-11-30 14:26:57 +00001022 git_cl.main(['upload', '--send-mail'])
Aaron Gablec4c40d12017-05-22 11:49:53 -07001023 self.assertEqual(
1024 '=====================================\n'
1025 'NOTICE: Rietveld is being deprecated. '
1026 'You can upload changes to Gerrit with\n'
1027 ' git cl upload --gerrit\n'
1028 'or set Gerrit to be your default code review tool with\n'
1029 ' git config gerrit.host true\n'
1030 '=====================================\n',
1031 stdout.getvalue())
maruel@chromium.orga3353652011-11-30 14:26:57 +00001032
tandriif9aefb72016-07-01 09:06:51 -07001033 def test_bug_on_cmd(self):
1034 self._run_reviewer_test(
1035 ['--bug=500658,proj:123'],
1036 'desc\n\nBUG=500658\nBUG=proj:123',
1037 '# Blah blah comment.\ndesc\n\nBUG=500658\nBUG=proj:1234',
1038 'desc\n\nBUG=500658\nBUG=proj:1234',
1039 [])
1040
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001041 @classmethod
tandrii@chromium.org28253532016-04-14 13:46:56 +00001042 def _gerrit_ensure_auth_calls(cls, issue=None, skip_auth_check=False):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +00001043 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +00001044 if skip_auth_check:
1045 return [((cmd, ), 'true')]
1046
tandrii5d48c322016-08-18 16:19:37 -07001047 calls = [((cmd, ), CERR1)]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001048 if issue:
1049 calls.extend([
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001050 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001051 ])
1052 calls.extend([
1053 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1054 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1055 ((['git', 'config', 'remote.origin.url'],),
1056 'https://chromium.googlesource.com/my/repo'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001057 ])
1058 return calls
1059
1060 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001061 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001062 fetched_status=None, other_cl_owner=None,
1063 custom_cl_base=None):
Aaron Gable13101a62018-02-09 13:20:41 -08001064 calls = cls._is_gerrit_calls(True)
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001065 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001066 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1067 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
1068 ((['git', 'config', 'branch.master.gerritissue'],),
1069 CERR1 if issue is None else str(issue)),
1070 ]
1071
1072 if custom_cl_base:
1073 ancestor_revision = custom_cl_base
1074 else:
1075 # Determine ancestor_revision to be merge base.
1076 ancestor_revision = 'fake_ancestor_sha'
1077 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001078 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +00001079 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001080 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001081 'refs/remotes/origin/master'],), ancestor_revision),
1082 ]
1083
1084 # Calls to verify branch point is ancestor
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001085 calls += cls._gerrit_ensure_auth_calls(issue=issue)
1086
1087 if issue:
1088 calls += [
Andrii Shyshkalov3e631422017-02-16 17:46:44 +01001089 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001090 'my%2Frepo~123456',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001091 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +01001092 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001093 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Andrii Shyshkalov3e631422017-02-16 17:46:44 +01001094 'change_id': '123456789',
1095 'current_revision': 'sha1_of_current_revision',
1096 'revisions': { 'sha1_of_current_revision': {
1097 'commit': {'message': fetched_description},
1098 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001099 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +01001100 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001101 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001102 if fetched_status == 'ABANDONED':
1103 calls += [
1104 (('DieWithError', 'Change https://chromium-review.googlesource.com/'
1105 '123456 has been abandoned, new uploads are not '
1106 'allowed'), SystemExitMock()),
1107 ]
1108 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001109 if other_cl_owner:
1110 calls += [
1111 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
1112 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001113
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001114 calls += cls._git_sanity_checks(ancestor_revision, 'master',
1115 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001116 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001117 ((['git', 'rev-parse', '--show-cdup'],), ''),
1118 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001119
Aaron Gable7817f022017-12-12 09:43:17 -08001120 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
1121 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001122 'M\t.gitignore\n'),
1123 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001124 ]
1125
1126 if not issue:
1127 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001128 ((['git', 'log', '--pretty=format:%s%n%n%b',
1129 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001130 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001131 ]
1132
1133 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001134 ((['git', 'config', 'user.email'],), 'me@example.com'),
1135 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
1136 ([custom_cl_base] if custom_cl_base else
1137 [ancestor_revision, 'HEAD']),),
1138 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +01001139 ]
1140 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +00001141
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001142 @classmethod
1143 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -07001144 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001145 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001146 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001147 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001148 custom_cl_base=None, tbr=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +00001149 if post_amend_description is None:
1150 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -07001151 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001152 # Determined in `_gerrit_base_calls`.
1153 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
1154
1155 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001156
tandriia60502f2016-06-20 02:01:53 -07001157 if squash_mode == 'default':
1158 calls.extend([
1159 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
1160 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
1161 ])
1162 elif squash_mode in ('override_squash', 'override_nosquash'):
1163 calls.extend([
1164 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
1165 'true' if squash_mode == 'override_squash' else 'false'),
1166 ])
1167 else:
1168 assert squash_mode in ('squash', 'nosquash')
1169
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001170 # If issue is given, then description is fetched from Gerrit instead.
1171 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001172 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001173 ((['git', 'log', '--pretty=format:%s\n\n%b',
1174 ((custom_cl_base + '..') if custom_cl_base else
1175 'fake_ancestor_sha..HEAD')],),
1176 description),
1177 ]
Aaron Gableb56ad332017-01-06 15:24:31 -08001178 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001179 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -08001180 else:
1181 if not title:
1182 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001183 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
1184 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -08001185 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001186 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +00001187 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001188 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001189 (('DownloadGerritHook', False), ''),
1190 # Amending of commit message to get the Change-Id.
1191 ((['git', 'log', '--pretty=format:%s\n\n%b',
1192 determined_ancestor_revision + '..HEAD'],),
1193 description),
1194 ((['git', 'commit', '--amend', '-m', description],), ''),
1195 ((['git', 'log', '--pretty=format:%s\n\n%b',
1196 determined_ancestor_revision + '..HEAD'],),
1197 post_amend_description)
1198 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001199 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001200 if not issue:
1201 # Prompting to edit description on first upload.
1202 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001203 ((['git', 'config', 'core.editor'],), ''),
1204 ((['RunEditor'],), description),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001205 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001206 ref_to_push = 'abcdef0123456789'
1207 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001208 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1209 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1210 ]
1211
1212 if custom_cl_base is None:
1213 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001214 ((['get_or_create_merge_base', 'master',
1215 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001216 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001217 ]
1218 parent = 'origin/master'
1219 else:
1220 calls += [
1221 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
1222 'refs/remotes/origin/master'],),
1223 callError(1)), # Means not ancenstor.
1224 (('ask_for_data',
1225 'Do you take responsibility for cleaning up potential mess '
1226 'resulting from proceeding with upload? Press Enter to upload, '
1227 'or Ctrl+C to abort'), ''),
1228 ]
1229 parent = custom_cl_base
1230
1231 calls += [
1232 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
1233 '0123456789abcdef'),
1234 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -07001235 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001236 ref_to_push),
1237 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001238 else:
1239 ref_to_push = 'HEAD'
1240
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001241 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001242 ((['git', 'rev-list',
1243 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1244 ref_to_push],),
1245 '1hashPerLine\n'),
1246 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001247
Aaron Gableafd52772017-06-27 16:40:10 -07001248 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001249 ref_suffix = '%ready,notify=ALL'
1250 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001251 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001252 ref_suffix = '%wip'
1253 else:
1254 ref_suffix = '%notify=NONE'
Aaron Gable9b713dd2016-12-14 16:04:21 -08001255
Aaron Gable70f4e242017-06-26 10:45:59 -07001256 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001257 ref_suffix += ',m=' + title
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001258
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001259 calls.append((
1260 (['git', 'push',
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001261 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001262 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1263 ('remote:\n'
1264 'remote: Processing changes: (\)\n'
1265 'remote: Processing changes: (|)\n'
1266 'remote: Processing changes: (/)\n'
1267 'remote: Processing changes: (-)\n'
1268 'remote: Processing changes: new: 1 (/)\n'
1269 'remote: Processing changes: new: 1, done\n'
1270 'remote:\n'
1271 'remote: New Changes:\n'
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001272 'remote: https://chromium-review.googlesource.com/#/c/my/repo/+/123456'
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001273 ' XXX\n'
1274 'remote:\n'
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001275 'To https://chromium.googlesource.com/my/repo\n'
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001276 ' * [new branch] hhhh -> refs/for/refs/heads/master\n')
1277 ))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001278 if squash:
1279 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001280 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001281 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001282 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001283 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001284 ((['git', 'config', 'branch.master.gerritsquashhash',
1285 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001286 ]
tandrii88189772016-09-29 04:29:57 -07001287 calls += [
1288 ((['git', 'config', 'rietveld.cc'],), ''),
tandrii88189772016-09-29 04:29:57 -07001289 ]
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001290 if squash:
1291 calls += [
1292 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001293 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001294 sorted(reviewers),
1295 ['joe@example.com', 'chromium-reviews+test-more-cc@chromium.org'] +
1296 cc, notify), ''),
1297 ]
Aaron Gablefd238082017-06-07 13:42:34 -07001298 if tbr:
1299 calls += [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001300 (('GetChangeDetail', 'chromium-review.googlesource.com',
1301 'my%2Frepo~123456', ['LABELS']), {
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001302 'labels': {
1303 'Code-Review': {
1304 'default_value': 0,
1305 'all': [],
1306 'values': {
1307 '+2': 'lgtm, approved',
1308 '+1': 'lgtm, but someone else must approve',
1309 ' 0': 'No score',
1310 '-1': 'Don\'t submit as-is',
1311 }
1312 }
1313 }
1314 }),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001315 (('SetReview',
1316 'chromium-review.googlesource.com',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001317 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001318 'Self-approving for TBR',
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001319 {'Code-Review': 2}, None), ''),
Aaron Gablefd238082017-06-07 13:42:34 -07001320 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001321 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001322 return calls
1323
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001324 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001325 self,
1326 upload_args,
1327 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001328 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001329 squash=True,
1330 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001331 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001332 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001333 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001334 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001335 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001336 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001337 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001338 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001339 custom_cl_base=None,
1340 tbr=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001341 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001342 if squash_mode is None:
1343 if '--no-squash' in upload_args:
1344 squash_mode = 'nosquash'
1345 elif '--squash' in upload_args:
1346 squash_mode = 'squash'
1347 else:
1348 squash_mode = 'default'
1349
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001350 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001351 cc = cc or []
tandrii@chromium.org28253532016-04-14 13:46:56 +00001352 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001353 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001354 CookiesAuthenticatorMockFactory(
1355 same_auth=('git-owner.example.com', '', 'pass')))
tandrii16e0b4e2016-06-07 10:34:28 -07001356 self.mock(git_cl._GerritChangelistImpl, '_GerritCommitMsgHookCheck',
1357 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001358 self.mock(git_cl.gclient_utils, 'RunEditor',
1359 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001360 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1361 'DownloadGerritHook', force))
tandriia60502f2016-06-20 02:01:53 -07001362
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001363 self.calls = self._gerrit_base_calls(
1364 issue=issue,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001365 fetched_description=description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001366 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001367 other_cl_owner=other_cl_owner,
1368 custom_cl_base=custom_cl_base)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001369 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001370 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
1371 expected_content=description))
1372 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001373 self.calls += self._gerrit_upload_calls(
1374 description, reviewers, squash,
1375 squash_mode=squash_mode,
1376 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001377 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001378 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001379 issue=issue, cc=cc,
Aaron Gablefd238082017-06-07 13:42:34 -07001380 custom_cl_base=custom_cl_base, tbr=tbr)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001381 # Uncomment when debugging.
1382 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001383 git_cl.main(['upload'] + upload_args)
1384
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001385 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001386 self._run_gerrit_upload_test(
1387 ['--no-squash'],
1388 'desc\n\nBUG=\n',
1389 [],
1390 squash=False,
1391 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
1392
1393 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001394 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001395 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +00001396 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001397 [],
tandriia60502f2016-06-20 02:01:53 -07001398 squash=False,
1399 squash_mode='override_nosquash',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001400 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001401
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001402 def test_gerrit_no_reviewer(self):
1403 self._run_gerrit_upload_test(
1404 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001405 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001406 [],
1407 squash=False,
1408 squash_mode='override_nosquash')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001409
Nick Carter8692b182017-11-06 16:30:38 -08001410 def test_gerrit_patchset_title_special_chars(self):
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001411 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1412 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001413 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001414 'desc\n\nBUG=\n\nChange-Id: I123456789',
1415 squash=False,
1416 squash_mode='override_nosquash',
Nick Carter8692b182017-11-06 16:30:38 -08001417 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001418
ukai@chromium.orge8077812012-02-03 03:41:46 +00001419 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001420 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001421 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001422 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001423 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001424 squash=False,
1425 squash_mode='override_nosquash',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001426 notify=True)
ukai@chromium.orge8077812012-02-03 03:41:46 +00001427
1428 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001429 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001430 [],
bradnelsond975b302016-10-23 12:20:23 -07001431 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1432 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001433 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001434 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001435 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001436 cc=['more@example.com', 'people@example.com'],
1437 tbr='reviewer@example.com')
tandriia60502f2016-06-20 02:01:53 -07001438
1439 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001440 self._run_gerrit_upload_test(
1441 [],
1442 'desc\nBUG=\n\nChange-Id: 123456789',
1443 [],
1444 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001445
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001446 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001447 self._run_gerrit_upload_test(
1448 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001449 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001450 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001451 squash=True,
1452 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001453
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001454 def test_gerrit_upload_squash_first_against_rev(self):
1455 custom_cl_base = 'custom_cl_base_rev_or_branch'
1456 self._run_gerrit_upload_test(
1457 ['--squash', custom_cl_base],
1458 'desc\nBUG=\n\nChange-Id: 123456789',
1459 [],
1460 squash=True,
1461 expected_upstream_ref='origin/master',
1462 custom_cl_base=custom_cl_base)
1463 self.assertIn(
1464 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1465 sys.stdout.getvalue())
1466
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001467 def test_gerrit_upload_squash_reupload(self):
1468 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001469 self._run_gerrit_upload_test(
1470 ['--squash'],
1471 description,
1472 [],
1473 squash=True,
1474 expected_upstream_ref='origin/master',
1475 issue=123456)
1476
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001477 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1478 self.mock(git_cl, 'DieWithError',
1479 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1480 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1481 with self.assertRaises(SystemExitMock):
1482 self._run_gerrit_upload_test(
1483 ['--squash'],
1484 description,
1485 [],
1486 squash=True,
1487 expected_upstream_ref='origin/master',
1488 issue=123456,
1489 fetched_status='ABANDONED')
1490
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001491 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1492 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1493 lambda *_, **__: {'email': 'yet-another@example.com'})
1494 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1495 self._run_gerrit_upload_test(
1496 ['--squash'],
1497 description,
1498 [],
1499 squash=True,
1500 expected_upstream_ref='origin/master',
1501 issue=123456,
1502 other_cl_owner='other@example.com')
1503 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001504 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001505 'authenticate to Gerrit as yet-another@example.com.\n'
1506 'Uploading may fail due to lack of permissions',
1507 git_cl.sys.stdout.getvalue())
1508
rmistry@google.com2dd99862015-06-22 12:22:18 +00001509 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001510 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001511 def mock_run_git(*args, **_kwargs):
1512 if args[0] == ['for-each-ref',
1513 '--format=%(refname:short) %(upstream:short)',
1514 'refs/heads']:
1515 # Create a local branch dependency tree that looks like this:
1516 # test1 -> test2 -> test3 -> test4 -> test5
1517 # -> test3.1
1518 # test6 -> test0
1519 branch_deps = [
1520 'test2 test1', # test1 -> test2
1521 'test3 test2', # test2 -> test3
1522 'test3.1 test2', # test2 -> test3.1
1523 'test4 test3', # test3 -> test4
1524 'test5 test4', # test4 -> test5
1525 'test6 test0', # test0 -> test6
1526 'test7', # test7
1527 ]
1528 return '\n'.join(branch_deps)
1529 self.mock(git_cl, 'RunGit', mock_run_git)
1530
1531 class RecordCalls:
1532 times_called = 0
1533 record_calls = RecordCalls()
1534 def mock_CMDupload(*args, **_kwargs):
1535 record_calls.times_called += 1
1536 return 0
1537 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1538
1539 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001540 (('ask_for_data', 'This command will checkout all dependent branches '
1541 'and run "git cl upload". Press Enter to continue, '
1542 'or Ctrl+C to abort'), ''),
1543 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001544
1545 class MockChangelist():
1546 def __init__(self):
1547 pass
1548 def GetBranch(self):
1549 return 'test1'
1550 def GetIssue(self):
1551 return '123'
1552 def GetPatchset(self):
1553 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001554 def IsGerrit(self):
1555 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001556
1557 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1558 # CMDupload should have been called 5 times because of 5 dependent branches.
1559 self.assertEquals(5, record_calls.times_called)
1560 self.assertEquals(0, ret)
1561
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001562 def test_gerrit_change_id(self):
1563 self.calls = [
1564 ((['git', 'write-tree'], ),
1565 'hashtree'),
1566 ((['git', 'rev-parse', 'HEAD~0'], ),
1567 'branch-parent'),
1568 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1569 'A B <a@b.org> 1456848326 +0100'),
1570 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1571 'C D <c@d.org> 1456858326 +0100'),
1572 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1573 'hashchange'),
1574 ]
1575 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1576 self.assertEqual(change_id, 'Ihashchange')
1577
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001578 def test_desecription_append_footer(self):
1579 for init_desc, footer_line, expected_desc in [
1580 # Use unique desc first lines for easy test failure identification.
1581 ('foo', 'R=one', 'foo\n\nR=one'),
1582 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1583 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1584 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1585 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1586 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1587 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1588 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1589 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1590 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1591 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1592 ]:
1593 desc = git_cl.ChangeDescription(init_desc)
1594 desc.append_footer(footer_line)
1595 self.assertEqual(desc.description, expected_desc)
1596
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001597 def test_update_reviewers(self):
1598 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001599 ('foo', [], [],
1600 'foo'),
1601 ('foo\nR=xx', [], [],
1602 'foo\nR=xx'),
1603 ('foo\nTBR=xx', [], [],
1604 'foo\nTBR=xx'),
1605 ('foo', ['a@c'], [],
1606 'foo\n\nR=a@c'),
1607 ('foo\nR=xx', ['a@c'], [],
1608 'foo\n\nR=a@c, xx'),
1609 ('foo\nTBR=xx', ['a@c'], [],
1610 'foo\n\nR=a@c\nTBR=xx'),
1611 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1612 'foo\n\nR=a@c, yy\nTBR=xx'),
1613 ('foo\nBUG=', ['a@c'], [],
1614 'foo\nBUG=\nR=a@c'),
1615 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1616 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1617 ('foo', ['a@c', 'b@c'], [],
1618 'foo\n\nR=a@c, b@c'),
1619 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1620 'foo\nBar\n\nR=c@c\nBUG='),
1621 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1622 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001623 # Same as the line before, but full of whitespaces.
1624 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001625 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001626 'foo\nBar\n\nR=c@c\n BUG =',
1627 ),
1628 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001629 ('foo BUG=allo R=joe ', ['c@c'], [],
1630 'foo BUG=allo R=joe\n\nR=c@c'),
1631 # Redundant TBRs get promoted to Rs
1632 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1633 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001634 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001635 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001636 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001637 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001638 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001639 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001640 actual.append(obj.description)
1641 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001642
Nodir Turakulov23b82142017-11-16 11:04:25 -08001643 def test_get_hash_tags(self):
1644 cases = [
1645 ('', []),
1646 ('a', []),
1647 ('[a]', ['a']),
1648 ('[aa]', ['aa']),
1649 ('[a ]', ['a']),
1650 ('[a- ]', ['a']),
1651 ('[a- b]', ['a-b']),
1652 ('[a--b]', ['a-b']),
1653 ('[a', []),
1654 ('[a]x', ['a']),
1655 ('[aa]x', ['aa']),
1656 ('[a b]', ['a-b']),
1657 ('[a b]', ['a-b']),
1658 ('[a__b]', ['a-b']),
1659 ('[a] x', ['a']),
1660 ('[a][b]', ['a', 'b']),
1661 ('[a] [b]', ['a', 'b']),
1662 ('[a][b]x', ['a', 'b']),
1663 ('[a][b] x', ['a', 'b']),
1664 ('[a]\n[b]', ['a']),
1665 ('[a\nb]', []),
1666 ('[a][', ['a']),
1667 ('Revert "[a] feature"', ['a']),
1668 ('Reland "[a] feature"', ['a']),
1669 ('Revert: [a] feature', ['a']),
1670 ('Reland: [a] feature', ['a']),
1671 ('Revert "Reland: [a] feature"', ['a']),
1672 ('Foo: feature', ['foo']),
1673 ('Foo Bar: feature', ['foo-bar']),
1674 ('Revert "Foo bar: feature"', ['foo-bar']),
1675 ('Reland "Foo bar: feature"', ['foo-bar']),
1676 ]
1677 for desc, expected in cases:
1678 change_desc = git_cl.ChangeDescription(desc)
1679 actual = change_desc.get_hash_tags()
1680 self.assertEqual(
1681 actual,
1682 expected,
1683 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1684
wittman@chromium.org455dc922015-01-26 20:15:50 +00001685 def test_get_target_ref(self):
1686 # Check remote or remote branch not present.
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001687 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001688 self.assertEqual(None, git_cl.GetTargetRef(None,
1689 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001690 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001691
wittman@chromium.org455dc922015-01-26 20:15:50 +00001692 # Check default target refs for branches.
1693 self.assertEqual('refs/heads/master',
1694 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001695 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001696 self.assertEqual('refs/heads/master',
1697 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001698 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001699 self.assertEqual('refs/heads/master',
1700 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001701 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001702 self.assertEqual('refs/branch-heads/123',
1703 git_cl.GetTargetRef('origin',
1704 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001705 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001706 self.assertEqual('refs/diff/test',
1707 git_cl.GetTargetRef('origin',
1708 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001709 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001710 self.assertEqual('refs/heads/chrome/m42',
1711 git_cl.GetTargetRef('origin',
1712 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001713 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001714
1715 # Check target refs for user-specified target branch.
1716 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1717 'refs/remotes/branch-heads/123'):
1718 self.assertEqual('refs/branch-heads/123',
1719 git_cl.GetTargetRef('origin',
1720 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001721 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001722 for branch in ('origin/master', 'remotes/origin/master',
1723 'refs/remotes/origin/master'):
1724 self.assertEqual('refs/heads/master',
1725 git_cl.GetTargetRef('origin',
1726 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001727 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001728 for branch in ('master', 'heads/master', 'refs/heads/master'):
1729 self.assertEqual('refs/heads/master',
1730 git_cl.GetTargetRef('origin',
1731 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001732 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001733
wychen@chromium.orga872e752015-04-28 23:42:18 +00001734 def test_patch_when_dirty(self):
1735 # Patch when local tree is dirty
1736 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1737 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1738
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001739 @staticmethod
1740 def _get_gerrit_codereview_server_calls(branch, value=None,
1741 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001742 detect_branch=True,
1743 detect_server=True):
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001744 """Returns calls executed by _GerritChangelistImpl.GetCodereviewServer.
1745
1746 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1747 """
1748 calls = []
1749 if detect_branch:
1750 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001751 if detect_server:
1752 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1753 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001754 if value is None:
1755 calls += [
1756 ((['git', 'config', 'branch.' + branch + '.merge'],),
1757 'refs/heads' + branch),
1758 ((['git', 'config', 'branch.' + branch + '.remote'],),
1759 'origin'),
1760 ((['git', 'config', 'remote.origin.url'],),
1761 'https://%s.googlesource.com/my/repo' % git_short_host),
1762 ]
1763 return calls
1764
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001765 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001766 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001767 detect_gerrit_server=False,
1768 actual_codereview=None,
1769 codereview_in_url=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001770 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001771 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1772 lambda x: '60001')
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001773 self.mock(git_cl._RietveldChangelistImpl, 'FetchDescription',
Kenneth Russell61e2ed42017-02-15 11:47:13 -08001774 lambda *a, **kw: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001775 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1776
tandriidf09a462016-08-18 16:23:55 -07001777 if new_branch:
1778 self.calls = [((['git', 'new-branch', 'master'],), ''),]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001779
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001780 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001781 self.calls += [
1782 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001783 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001784 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001785
1786 if not force_codereview and not codereview_in_url:
1787 # These calls detect codereview to use.
1788 self.calls += [
1789 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1790 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
1791 ((['git', 'config', 'branch.master.gerritissue'],), CERR1),
1792 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
1793 ((['git', 'config', 'gerrit.host'],), 'true'),
1794 ]
1795 if detect_gerrit_server:
1796 self.calls += self._get_gerrit_codereview_server_calls(
1797 'master', git_short_host=git_short_host,
1798 detect_branch=not new_branch and force_codereview)
1799 actual_codereview = 'gerrit'
1800
1801 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001802 self.calls += [
1803 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001804 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001805 {
1806 'current_revision': '7777777777',
1807 'revisions': {
1808 '1111111111': {
1809 '_number': 1,
1810 'fetch': {'http': {
1811 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1812 'ref': 'refs/changes/56/123456/1',
1813 }},
1814 },
1815 '7777777777': {
1816 '_number': 7,
1817 'fetch': {'http': {
1818 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1819 'ref': 'refs/changes/56/123456/7',
1820 }},
1821 },
1822 },
1823 }),
1824 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001825
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001826 def test_patch_rietveld_guess_by_url(self):
1827 self._patch_common(actual_codereview='rietveld', codereview_in_url=True)
wychen@chromium.orga872e752015-04-28 23:42:18 +00001828 self.calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001829 ((['git', 'config', 'branch.master.rietveldissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001830 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001831 ((['git', 'config', 'branch.master.rietveldserver',
1832 'https://codereview.example.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001833 ((['git', 'config', 'branch.master.rietveldpatchset', '60001'],),
tandrii5d48c322016-08-18 16:19:37 -07001834 ''),
Aaron Gabled343c632017-03-15 11:02:26 -07001835 ((['git', 'commit', '-m',
1836 'Description\n\n' +
1837 'patch from issue 123456 at patchset 60001 ' +
1838 '(http://crrev.com/123456#ps60001)'],), ''),
wychen@chromium.orga872e752015-04-28 23:42:18 +00001839 ]
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001840 self.assertEqual(git_cl.main(
1841 ['patch', 'https://codereview.example.com/123456']), 0)
1842
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001843 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001844 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001845 self.calls += [
1846 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1847 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001848 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001849 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001850 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001851 ((['git', 'config', 'branch.master.gerritserver',
1852 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001853 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001854 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1855 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1856 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001857 ]
1858 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1859
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001860 def test_patch_gerrit_new_branch(self):
1861 self._patch_common(
1862 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1863 self.calls += [
1864 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1865 'refs/changes/56/123456/7'],), ''),
1866 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1867 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1868 ''),
1869 ((['git', 'config', 'branch.master.gerritserver',
1870 'https://chromium-review.googlesource.com'],), ''),
1871 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1872 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1873 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1874 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1875 ]
1876 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1877
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001878 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001879 self._patch_common(
1880 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001881 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001882 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001883 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001884 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001885 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001886 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001887 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001888 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001889 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001890 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1891 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1892 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001893 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001894 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001895
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001896 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001897 self.calls += self._get_gerrit_codereview_server_calls(
1898 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001899 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001900 actual_codereview='gerrit', git_short_host='else',
1901 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001902 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001903 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001904 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001905 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001906 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001907 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001908 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001909 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001910 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001911 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1912 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1913 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001914 ]
1915 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001916 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001917
Aaron Gable697a91b2018-01-19 15:20:15 -08001918 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001919 self.calls += self._get_gerrit_codereview_server_calls(
1920 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001921 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001922 actual_codereview='gerrit', git_short_host='else',
1923 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001924 self.calls += [
1925 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1926 'refs/changes/56/123456/1'],), ''),
1927 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1928 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1929 ''),
1930 ((['git', 'config', 'branch.master.gerritserver',
1931 'https://else-review.googlesource.com'],), ''),
1932 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1933 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1934 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1935 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1936 ]
1937 self.assertEqual(git_cl.main(
1938 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1939 0)
1940
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001941 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001942 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001943 self.calls += [
1944 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001945 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001946 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1947 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1948 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001949 ]
1950 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001951 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001952
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001953 def test_patch_gerrit_not_exists(self):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001954 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001955 raise git_cl.gerrit_util.GerritError(404, '')
1956 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1957
tandriic2405f52016-10-10 08:13:15 -07001958 self.calls = [
1959 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandriic2405f52016-10-10 08:13:15 -07001960 ((['git', 'config', 'branch.master.rietveldissue'],), CERR1),
1961 ((['git', 'config', 'branch.master.gerritissue'],), CERR1),
1962 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
1963 ((['git', 'config', 'gerrit.host'],), 'true'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001964 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1965 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1966 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1967 ((['git', 'config', 'remote.origin.url'],),
1968 'https://chromium.googlesource.com/my/repo'),
1969 ((['DieWithError',
1970 'change 123456 at https://chromium-review.googlesource.com does not '
1971 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001972 ]
1973 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001974 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001975
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001976 def _checkout_calls(self):
1977 return [
1978 ((['git', 'config', '--local', '--get-regexp',
1979 'branch\\..*\\.rietveldissue'], ),
1980 ('branch.retrying.rietveldissue 1111111111\n'
1981 'branch.some-fix.rietveldissue 2222222222\n')),
1982 ((['git', 'config', '--local', '--get-regexp',
1983 'branch\\..*\\.gerritissue'], ),
1984 ('branch.ger-branch.gerritissue 123456\n'
1985 'branch.gbranch654.gerritissue 654321\n')),
1986 ]
1987
1988 def test_checkout_gerrit(self):
1989 """Tests git cl checkout <issue>."""
1990 self.calls = self._checkout_calls()
1991 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1992 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1993
1994 def test_checkout_rietveld(self):
1995 """Tests git cl checkout <issue>."""
1996 self.calls = self._checkout_calls()
1997 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1998 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1999
2000 def test_checkout_not_found(self):
2001 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00002002 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00002003 self.calls = self._checkout_calls()
2004 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2005
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002006 def test_checkout_no_branch_issues(self):
2007 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00002008 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002009 self.calls = [
2010 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07002011 'branch\\..*\\.rietveldissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002012 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07002013 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00002014 ]
2015 self.assertEqual(1, git_cl.main(['checkout', '99999']))
2016
tandrii@chromium.org28253532016-04-14 13:46:56 +00002017 def _test_gerrit_ensure_authenticated_common(self, auth,
2018 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002019 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2020 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
2021 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11002022 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00002023 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002024 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00002025 cl.branch = 'master'
2026 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002027 cl.lookedup_issue = True
2028 return cl
2029
2030 def test_gerrit_ensure_authenticated_missing(self):
2031 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002032 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002033 })
2034 self.calls.append(
2035 ((['DieWithError',
2036 'Credentials for the following hosts are required:\n'
2037 ' chromium-review.googlesource.com\n'
2038 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002039 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002040 'https://chromium-review.googlesource.com/new-password'],), ''),)
2041 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2042
2043 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00002044 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002045 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002046 'chromium.googlesource.com':
2047 ('git-one.example.com', None, 'secret1'),
2048 'chromium-review.googlesource.com':
2049 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002050 })
2051 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002052 (('ask_for_data', 'If you know what you are doing '
2053 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002054 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2055
2056 def test_gerrit_ensure_authenticated_ok(self):
2057 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002058 'chromium.googlesource.com':
2059 ('git-same.example.com', None, 'secret'),
2060 'chromium-review.googlesource.com':
2061 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002062 })
2063 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2064
tandrii@chromium.org28253532016-04-14 13:46:56 +00002065 def test_gerrit_ensure_authenticated_skipped(self):
2066 cl = self._test_gerrit_ensure_authenticated_common(
2067 auth={}, skip_auth_check=True)
2068 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2069
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002070 def test_cmd_set_commit_rietveld(self):
tandrii4d843592016-07-27 08:22:56 -07002071 self.mock(git_cl._RietveldChangelistImpl, 'SetFlags',
2072 lambda _, v: self._mocked_call(['SetFlags', v]))
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002073 self.calls = [
2074 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002075 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002076 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2077 ((['git', 'config', 'rietveld.server'],), ''),
2078 ((['git', 'config', 'rietveld.server'],), ''),
2079 ((['git', 'config', 'branch.feature.rietveldserver'],),
2080 'https://codereview.chromium.org'),
tandrii4d843592016-07-27 08:22:56 -07002081 ((['SetFlags', {'commit': '1', 'cq_dry_run': '0'}], ), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002082 ]
2083 self.assertEqual(0, git_cl.main(['set-commit']))
2084
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002085 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002086 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002087 lambda h, i, labels, notify=None:
2088 self._mocked_call(['SetReview', h, i, labels, notify]))
2089
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002090 self.calls = [
2091 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002092 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2093 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002094 ((['git', 'config', 'branch.feature.gerritserver'],),
2095 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002096 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2097 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2098 ((['git', 'config', 'remote.origin.url'],),
2099 'https://chromium.googlesource.com/infra/infra.git'),
2100 ((['SetReview', 'chromium-review.googlesource.com',
2101 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002102 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002103 ]
tandriid9e5ce52016-07-13 02:32:59 -07002104
2105 def test_cmd_set_commit_gerrit_clear(self):
2106 self._cmd_set_commit_gerrit_common(0)
2107 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2108
2109 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002110 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002111 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2112
tandriid9e5ce52016-07-13 02:32:59 -07002113 def test_cmd_set_commit_gerrit(self):
2114 self._cmd_set_commit_gerrit_common(2)
2115 self.assertEqual(0, git_cl.main(['set-commit']))
2116
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002117 def test_description_display(self):
2118 out = StringIO.StringIO()
2119 self.mock(git_cl.sys, 'stdout', out)
2120
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002121 self.mock(git_cl, 'Changelist', ChangelistMock)
2122 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002123
2124 self.assertEqual(0, git_cl.main(['description', '-d']))
2125 self.assertEqual('foo\n', out.getvalue())
2126
2127 def test_description_rietveld(self):
2128 out = StringIO.StringIO()
2129 self.mock(git_cl.sys, 'stdout', out)
martiniss6eda05f2016-06-30 10:18:35 -07002130 self.mock(git_cl.Changelist, 'GetDescription', lambda *args: 'foobar')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002131
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002132 self.assertEqual(0, git_cl.main([
Andrii Shyshkalov28d840e2017-04-10 15:45:09 +02002133 'description', '-d', '--rietveld', 'https://code.review.org/123123']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002134 self.assertEqual('foobar\n', out.getvalue())
2135
iannucci3c972b92016-08-17 13:24:10 -07002136 def test_StatusFieldOverrideIssueMissingArgs(self):
2137 out = StringIO.StringIO()
2138 self.mock(git_cl.sys, 'stderr', out)
2139
2140 try:
2141 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2142 except SystemExit as ex:
2143 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002144 self.assertRegexpMatches(out.getvalue(), r'--issue must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002145
2146 out = StringIO.StringIO()
2147 self.mock(git_cl.sys, 'stderr', out)
2148
2149 try:
2150 self.assertEqual(git_cl.main(['status', '--issue', '1', '--rietveld']), 0)
2151 except SystemExit as ex:
2152 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002153 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002154
2155 def test_StatusFieldOverrideIssue(self):
2156 out = StringIO.StringIO()
2157 self.mock(git_cl.sys, 'stdout', out)
2158
2159 def assertIssue(cl_self, *_args):
2160 self.assertEquals(cl_self.issue, 1)
2161 return 'foobar'
2162
2163 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2164 self.calls = [
2165 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2166 ((['git', 'config', 'rietveld.server'],), ''),
2167 ((['git', 'config', 'rietveld.server'],), ''),
2168 ]
iannuccie53c9352016-08-17 14:40:40 -07002169 self.assertEqual(
2170 git_cl.main(['status', '--issue', '1', '--rietveld', '--field', 'desc']),
2171 0)
iannucci3c972b92016-08-17 13:24:10 -07002172 self.assertEqual(out.getvalue(), 'foobar\n')
2173
iannuccie53c9352016-08-17 14:40:40 -07002174 def test_SetCloseOverrideIssue(self):
2175 def assertIssue(cl_self, *_args):
2176 self.assertEquals(cl_self.issue, 1)
2177 return 'foobar'
2178
2179 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2180 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
2181 self.calls = [
2182 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2183 ((['git', 'config', 'rietveld.server'],), ''),
2184 ((['git', 'config', 'rietveld.server'],), ''),
2185 ]
2186 self.assertEqual(
2187 git_cl.main(['set-close', '--issue', '1', '--rietveld']), 0)
2188
2189 def test_SetCommitOverrideIssue(self):
2190 def assertIssue(cl_self, *_args):
2191 self.assertEquals(cl_self.issue, 1)
2192 return 'foobar'
2193
2194 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2195 self.mock(git_cl.Changelist, 'SetCQState', lambda *_: None)
2196 self.calls = [
2197 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2198 ((['git', 'config', 'rietveld.server'],), ''),
2199 ((['git', 'config', 'rietveld.server'],), ''),
2200 ((['git', 'symbolic-ref', 'HEAD'],), ''),
2201 ((['git', 'config', 'rietveld.server'],), ''),
2202 ((['git', 'config', 'rietveld.server'],), ''),
2203 ]
2204 self.assertEqual(
2205 git_cl.main(['set-close', '--issue', '1', '--rietveld']), 0)
2206
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002207 def test_description_gerrit(self):
2208 out = StringIO.StringIO()
2209 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002210 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002211 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2212 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2213 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2214 ((['git', 'config', 'remote.origin.url'],),
2215 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalov8039be72017-01-26 09:38:18 +01002216 (('GetChangeDetail', 'code.review.org',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002217 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002218 {
2219 'current_revision': 'sha1',
2220 'revisions': {'sha1': {
2221 'commit': {'message': 'foobar'},
2222 }},
2223 }),
2224 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002225 self.assertEqual(0, git_cl.main([
2226 'description', 'https://code.review.org/123123', '-d', '--gerrit']))
2227 self.assertEqual('foobar\n', out.getvalue())
2228
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002229 def test_description_set_raw(self):
2230 out = StringIO.StringIO()
2231 self.mock(git_cl.sys, 'stdout', out)
2232
2233 self.mock(git_cl, 'Changelist', ChangelistMock)
2234 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
2235
2236 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2237 self.assertEqual('hihi', ChangelistMock.desc)
2238
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002239 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002240 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002241
2242 def RunEditor(desc, _, **kwargs):
2243 self.assertEquals(
2244 '# Enter a description of the change.\n'
2245 '# This will be displayed on the codereview site.\n'
2246 '# The first line will also be used as the subject of the review.\n'
2247 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002248 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002249 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002250 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002251 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002252 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002253
dsansomee2d6fd92016-09-08 00:10:47 -07002254 def UpdateDescriptionRemote(_, desc, force=False):
Aaron Gable3a16ed12017-03-23 10:51:55 -07002255 self.assertEquals(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002256
2257 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2258 self.mock(git_cl.Changelist, 'GetDescription',
2259 lambda *args: current_desc)
2260 self.mock(git_cl._GerritChangelistImpl, 'UpdateDescriptionRemote',
2261 UpdateDescriptionRemote)
2262 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2263
2264 self.calls = [
2265 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002266 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002267 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2268 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002269 ((['git', 'config', 'core.editor'],), 'vi'),
2270 ]
2271 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2272
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002273 def test_description_set_stdin(self):
2274 out = StringIO.StringIO()
2275 self.mock(git_cl.sys, 'stdout', out)
2276
2277 self.mock(git_cl, 'Changelist', ChangelistMock)
2278 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
2279
2280 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2281 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2282
kmarshall3bff56b2016-06-06 18:31:47 -07002283 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07002284 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2285
kmarshall3bff56b2016-06-06 18:31:47 -07002286 self.calls = \
2287 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2288 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
tandrii33a46ff2016-08-23 05:53:40 -07002289 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
tandrii5d48c322016-08-18 16:19:37 -07002290 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2291 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
tandrii33a46ff2016-08-23 05:53:40 -07002292 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
2293 ((['git', 'config', 'branch.bar.rietveldissue'],), CERR1),
2294 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
kmarshall3bff56b2016-06-06 18:31:47 -07002295 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2296 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
2297 ((['git', 'branch', '-D', 'foo'],), '')]
2298
kmarshall3bff56b2016-06-06 18:31:47 -07002299 self.mock(git_cl, 'get_cl_statuses',
2300 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002301 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2302 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2303 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002304
2305 self.assertEqual(0, git_cl.main(['archive', '-f']))
2306
2307 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07002308 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
kmarshall3bff56b2016-06-06 18:31:47 -07002309 self.calls = \
2310 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2311 'refs/heads/master'),
tandrii33a46ff2016-08-23 05:53:40 -07002312 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
tandrii5d48c322016-08-18 16:19:37 -07002313 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2314 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
kmarshall3bff56b2016-06-06 18:31:47 -07002315 ((['git', 'symbolic-ref', 'HEAD'],), 'master')]
2316
kmarshall9249e012016-08-23 12:02:16 -07002317 self.mock(git_cl, 'get_cl_statuses',
2318 lambda branches, fine_grained, max_processes:
2319 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2320
2321 self.assertEqual(1, git_cl.main(['archive', '-f']))
2322
2323 def test_archive_dry_run(self):
2324 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2325
2326 self.calls = \
2327 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2328 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2329 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
2330 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2331 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
2332 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
2333 ((['git', 'config', 'branch.bar.rietveldissue'],), CERR1),
2334 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
2335 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),]
kmarshall3bff56b2016-06-06 18:31:47 -07002336
2337 self.mock(git_cl, 'get_cl_statuses',
2338 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002339 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2340 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2341 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002342
kmarshall9249e012016-08-23 12:02:16 -07002343 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2344
2345 def test_archive_no_tags(self):
2346 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2347
2348 self.calls = \
2349 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2350 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
2351 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
2352 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2353 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
2354 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
2355 ((['git', 'config', 'branch.bar.rietveldissue'],), CERR1),
2356 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
2357 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2358 ((['git', 'branch', '-D', 'foo'],), '')]
2359
2360 self.mock(git_cl, 'get_cl_statuses',
2361 lambda branches, fine_grained, max_processes:
2362 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2363 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2364 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2365
2366 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002367
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002368 def test_cmd_issue_erase_existing(self):
2369 out = StringIO.StringIO()
2370 self.mock(git_cl.sys, 'stdout', out)
2371 self.calls = [
2372 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002373 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2374 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002375 # Let this command raise exception (retcode=1) - it should be ignored.
2376 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002377 CERR1),
2378 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2379 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002380 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2381 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2382 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002383 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002384 ]
2385 self.assertEqual(0, git_cl.main(['issue', '0']))
2386
Aaron Gable400e9892017-07-12 15:31:21 -07002387 def test_cmd_issue_erase_existing_with_change_id(self):
2388 out = StringIO.StringIO()
2389 self.mock(git_cl.sys, 'stdout', out)
2390 self.mock(git_cl.Changelist, 'GetDescription',
2391 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2392 self.calls = [
2393 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2394 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2395 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
Aaron Gable400e9892017-07-12 15:31:21 -07002396 # Let this command raise exception (retcode=1) - it should be ignored.
2397 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2398 CERR1),
2399 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2400 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2401 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2402 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2403 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002404 ((['git', 'log', '-1', '--format=%B'],),
2405 'This is a description\n\nChange-Id: Ideadbeef'),
2406 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002407 ]
2408 self.assertEqual(0, git_cl.main(['issue', '0']))
2409
phajdan.jre328cf92016-08-22 04:12:17 -07002410 def test_cmd_issue_json(self):
2411 out = StringIO.StringIO()
2412 self.mock(git_cl.sys, 'stdout', out)
2413 self.calls = [
2414 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002415 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
phajdan.jre328cf92016-08-22 04:12:17 -07002416 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2417 ((['git', 'config', 'rietveld.server'],),
2418 'https://codereview.chromium.org'),
2419 ((['git', 'config', 'branch.feature.rietveldserver'],), ''),
2420 (('write_json', 'output.json',
2421 {'issue': 123, 'issue_url': 'https://codereview.chromium.org/123'}),
2422 ''),
2423 ]
2424 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2425
tandriide281ae2016-10-12 06:02:30 -07002426 def test_git_cl_try_default_cq_dry_run(self):
tandrii9de9ec62016-07-13 03:01:59 -07002427 self.mock(git_cl.Changelist, 'GetChange',
2428 lambda _, *a: (
2429 self._mocked_call(['GetChange']+list(a))))
2430 self.mock(git_cl.presubmit_support, 'DoGetTryMasters',
2431 lambda *_, **__: (
2432 self._mocked_call(['DoGetTryMasters'])))
tandrii9de9ec62016-07-13 03:01:59 -07002433 self.mock(git_cl._RietveldChangelistImpl, 'SetCQState',
2434 lambda _, s: self._mocked_call(['SetCQState', s]))
2435 self.calls = [
2436 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002437 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
tandrii9de9ec62016-07-13 03:01:59 -07002438 ((['git', 'config', 'rietveld.autoupdate'],), ''),
2439 ((['git', 'config', 'rietveld.server'],),
2440 'https://codereview.chromium.org'),
2441 ((['git', 'config', 'branch.feature.rietveldserver'],), ''),
2442 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2443 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2444 ((['get_or_create_merge_base', 'feature', 'feature'],),
2445 'fake_ancestor_sha'),
2446 ((['GetChange', 'fake_ancestor_sha', None], ),
2447 git_cl.presubmit_support.GitChange(
2448 '', '', '', '', '', '', '', '')),
2449 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2450 ((['DoGetTryMasters'], ), None),
tandrii9de9ec62016-07-13 03:01:59 -07002451 ((['SetCQState', git_cl._CQState.DRY_RUN], ), None),
2452 ]
2453 out = StringIO.StringIO()
2454 self.mock(git_cl.sys, 'stdout', out)
2455 self.assertEqual(0, git_cl.main(['try']))
2456 self.assertEqual(
2457 out.getvalue(),
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07002458 'Scheduling CQ dry run on: https://codereview.chromium.org/123\n')
tandrii9de9ec62016-07-13 03:01:59 -07002459
tandrii8c5a3532016-11-04 07:52:02 -07002460 def test_git_cl_try_default_cq_dry_run_gerrit(self):
2461 self.mock(git_cl.Changelist, 'GetChange',
2462 lambda _, *a: (
2463 self._mocked_call(['GetChange']+list(a))))
2464 self.mock(git_cl.presubmit_support, 'DoGetTryMasters',
2465 lambda *_, **__: (
2466 self._mocked_call(['DoGetTryMasters'])))
2467 self.mock(git_cl._GerritChangelistImpl, 'SetCQState',
2468 lambda _, s: self._mocked_call(['SetCQState', s]))
2469
tandrii8c5a3532016-11-04 07:52:02 -07002470 self.calls = [
2471 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2472 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2473 ((['git', 'config', 'branch.feature.gerritissue'],), '123456'),
2474 ((['git', 'config', 'branch.feature.gerritserver'],),
2475 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002476 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2477 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2478 ((['git', 'config', 'remote.origin.url'],),
2479 'https://chromium.googlesource.com/depot_tools'),
2480 (('GetChangeDetail', 'chromium-review.googlesource.com',
2481 'depot_tools~123456',
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01002482 ['DETAILED_ACCOUNTS', 'ALL_REVISIONS', 'CURRENT_COMMIT']), {
2483 'project': 'depot_tools',
2484 'status': 'OPEN',
2485 'owner': {'email': 'owner@e.mail'},
2486 'revisions': {
2487 'deadbeaf': {
2488 '_number': 6,
2489 },
2490 'beeeeeef': {
2491 '_number': 7,
2492 'fetch': {'http': {
2493 'url': 'https://chromium.googlesource.com/depot_tools',
2494 'ref': 'refs/changes/56/123456/7'
2495 }},
2496 },
2497 },
2498 }),
tandrii8c5a3532016-11-04 07:52:02 -07002499 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2500 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2501 ((['get_or_create_merge_base', 'feature', 'feature'],),
2502 'fake_ancestor_sha'),
2503 ((['GetChange', 'fake_ancestor_sha', None], ),
2504 git_cl.presubmit_support.GitChange(
2505 '', '', '', '', '', '', '', '')),
2506 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2507 ((['DoGetTryMasters'], ), None),
2508 ((['SetCQState', git_cl._CQState.DRY_RUN], ), None),
2509 ]
2510 out = StringIO.StringIO()
2511 self.mock(git_cl.sys, 'stdout', out)
2512 self.assertEqual(0, git_cl.main(['try']))
2513 self.assertEqual(
2514 out.getvalue(),
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07002515 'Scheduling CQ dry run on: '
tandrii8c5a3532016-11-04 07:52:02 -07002516 'https://chromium-review.googlesource.com/123456\n')
2517
2518 def test_git_cl_try_buildbucket_with_properties_rietveld(self):
2519 self.mock(git_cl._RietveldChangelistImpl, 'GetIssueProperties',
2520 lambda _: {
2521 'owner_email': 'owner@e.mail',
2522 'private': False,
2523 'closed': False,
2524 'project': 'depot_tools',
2525 'patchsets': [20001],
2526 })
tandriide281ae2016-10-12 06:02:30 -07002527 self.mock(git_cl.uuid, 'uuid4', lambda: 'uuid4')
2528 self.calls = [
2529 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2530 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
2531 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2532 ((['git', 'config', 'rietveld.server'],),
2533 'https://codereview.chromium.org'),
tandriide281ae2016-10-12 06:02:30 -07002534 ((['git', 'config', 'branch.feature.rietveldpatchset'],), '20001'),
tandrii8c5a3532016-11-04 07:52:02 -07002535 ((['git', 'config', 'branch.feature.rietveldserver'],), CERR1),
tandriide281ae2016-10-12 06:02:30 -07002536 ]
2537
2538 def _buildbucket_retry(*_, **kw):
2539 # self.maxDiff = 10000
2540 body = json.loads(kw['body'])
2541 self.assertEqual(len(body['builds']), 1)
2542 build = body['builds'][0]
2543 params = json.loads(build.pop('parameters_json'))
2544 self.assertEqual(params, {
2545 u'builder_name': u'win',
2546 u'changes': [{u'author': {u'email': u'owner@e.mail'},
2547 u'revision': None}],
2548 u'properties': {
2549 u'category': u'git_cl_try',
2550 u'issue': 123,
2551 u'key': u'val',
2552 u'json': [{u'a': 1}, None],
2553 u'master': u'tryserver.chromium',
2554 u'patch_project': u'depot_tools',
2555 u'patch_storage': u'rietveld',
2556 u'patchset': 20001,
tandriide281ae2016-10-12 06:02:30 -07002557 u'rietveld': u'https://codereview.chromium.org',
2558 }
2559 })
2560 self.assertEqual(build, {
2561 u'bucket': u'master.tryserver.chromium',
2562 u'client_operation_id': u'uuid4',
2563 u'tags': [u'builder:win',
2564 u'buildset:patch/rietveld/codereview.chromium.org/123/20001',
borenet6c0efe62016-10-19 08:13:29 -07002565 u'user_agent:git_cl_try',
2566 u'master:tryserver.chromium'],
tandriide281ae2016-10-12 06:02:30 -07002567 })
2568
2569 self.mock(git_cl, '_buildbucket_retry', _buildbucket_retry)
2570
2571 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2572 self.assertEqual(0, git_cl.main([
2573 'try', '-m', 'tryserver.chromium', '-b', 'win',
2574 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
2575 self.assertRegexpMatches(
2576 git_cl.sys.stdout.getvalue(),
borenet6c0efe62016-10-19 08:13:29 -07002577 'Tried jobs on:\nBucket: master.tryserver.chromium')
2578
tandrii8c5a3532016-11-04 07:52:02 -07002579 def test_git_cl_try_buildbucket_with_properties_gerrit(self):
2580 self.mock(git_cl.Changelist, 'GetMostRecentPatchset', lambda _: 7)
2581 self.mock(git_cl.uuid, 'uuid4', lambda: 'uuid4')
2582
tandrii8c5a3532016-11-04 07:52:02 -07002583 self.calls = [
2584 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2585 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2586 ((['git', 'config', 'branch.feature.gerritissue'],), '123456'),
2587 ((['git', 'config', 'branch.feature.gerritserver'],),
2588 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002589 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2590 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2591 ((['git', 'config', 'remote.origin.url'],),
2592 'https://chromium.googlesource.com/depot_tools'),
2593 (('GetChangeDetail', 'chromium-review.googlesource.com',
2594 'depot_tools~123456',
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01002595 ['DETAILED_ACCOUNTS', 'ALL_REVISIONS', 'CURRENT_COMMIT']), {
tandrii8c5a3532016-11-04 07:52:02 -07002596 'project': 'depot_tools',
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01002597 'status': 'OPEN',
2598 'owner': {'email': 'owner@e.mail'},
tandrii8c5a3532016-11-04 07:52:02 -07002599 'revisions': {
2600 'deadbeaf': {
2601 '_number': 6,
2602 },
2603 'beeeeeef': {
2604 '_number': 7,
2605 'fetch': {'http': {
2606 'url': 'https://chromium.googlesource.com/depot_tools',
2607 'ref': 'refs/changes/56/123456/7'
2608 }},
2609 },
2610 },
2611 }),
2612 ]
2613
2614 def _buildbucket_retry(*_, **kw):
2615 # self.maxDiff = 10000
2616 body = json.loads(kw['body'])
2617 self.assertEqual(len(body['builds']), 1)
2618 build = body['builds'][0]
2619 params = json.loads(build.pop('parameters_json'))
2620 self.assertEqual(params, {
2621 u'builder_name': u'win',
2622 u'changes': [{u'author': {u'email': u'owner@e.mail'},
2623 u'revision': None}],
2624 u'properties': {
2625 u'category': u'git_cl_try',
2626 u'key': u'val',
2627 u'json': [{u'a': 1}, None],
2628 u'master': u'tryserver.chromium',
2629
2630 u'patch_gerrit_url':
2631 u'https://chromium-review.googlesource.com',
2632 u'patch_issue': 123456,
2633 u'patch_project': u'depot_tools',
2634 u'patch_ref': u'refs/changes/56/123456/7',
2635 u'patch_repository_url':
2636 u'https://chromium.googlesource.com/depot_tools',
2637 u'patch_set': 7,
2638 u'patch_storage': u'gerrit',
2639 }
2640 })
2641 self.assertEqual(build, {
2642 u'bucket': u'master.tryserver.chromium',
2643 u'client_operation_id': u'uuid4',
2644 u'tags': [
2645 u'builder:win',
2646 u'buildset:patch/gerrit/chromium-review.googlesource.com/123456/7',
2647 u'user_agent:git_cl_try',
2648 u'master:tryserver.chromium'],
2649 })
2650
2651 self.mock(git_cl, '_buildbucket_retry', _buildbucket_retry)
2652
2653 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2654 self.assertEqual(0, git_cl.main([
2655 'try', '-m', 'tryserver.chromium', '-b', 'win',
2656 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
2657 self.assertRegexpMatches(
2658 git_cl.sys.stdout.getvalue(),
2659 'Tried jobs on:\nBucket: master.tryserver.chromium')
2660
borenet6c0efe62016-10-19 08:13:29 -07002661 def test_git_cl_try_buildbucket_bucket_flag(self):
tandrii8c5a3532016-11-04 07:52:02 -07002662 self.mock(git_cl._RietveldChangelistImpl, 'GetIssueProperties',
2663 lambda _: {
2664 'owner_email': 'owner@e.mail',
2665 'private': False,
2666 'closed': False,
2667 'project': 'depot_tools',
2668 'patchsets': [20001],
2669 })
borenet6c0efe62016-10-19 08:13:29 -07002670 self.mock(git_cl.uuid, 'uuid4', lambda: 'uuid4')
2671 self.calls = [
2672 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2673 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
2674 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2675 ((['git', 'config', 'rietveld.server'],),
2676 'https://codereview.chromium.org'),
borenet6c0efe62016-10-19 08:13:29 -07002677 ((['git', 'config', 'branch.feature.rietveldpatchset'],), '20001'),
tandrii8c5a3532016-11-04 07:52:02 -07002678 ((['git', 'config', 'branch.feature.rietveldserver'],), CERR1),
borenet6c0efe62016-10-19 08:13:29 -07002679 ]
2680
2681 def _buildbucket_retry(*_, **kw):
borenet6c0efe62016-10-19 08:13:29 -07002682 body = json.loads(kw['body'])
2683 self.assertEqual(len(body['builds']), 1)
2684 build = body['builds'][0]
2685 params = json.loads(build.pop('parameters_json'))
2686 self.assertEqual(params, {
2687 u'builder_name': u'win',
2688 u'changes': [{u'author': {u'email': u'owner@e.mail'},
2689 u'revision': None}],
2690 u'properties': {
2691 u'category': u'git_cl_try',
2692 u'issue': 123,
2693 u'patch_project': u'depot_tools',
2694 u'patch_storage': u'rietveld',
2695 u'patchset': 20001,
borenet6c0efe62016-10-19 08:13:29 -07002696 u'rietveld': u'https://codereview.chromium.org',
2697 }
2698 })
2699 self.assertEqual(build, {
2700 u'bucket': u'test.bucket',
2701 u'client_operation_id': u'uuid4',
2702 u'tags': [u'builder:win',
2703 u'buildset:patch/rietveld/codereview.chromium.org/123/20001',
2704 u'user_agent:git_cl_try'],
2705 })
2706
2707 self.mock(git_cl, '_buildbucket_retry', _buildbucket_retry)
2708
2709 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2710 self.assertEqual(0, git_cl.main([
2711 'try', '-B', 'test.bucket', '-b', 'win']))
2712 self.assertRegexpMatches(
2713 git_cl.sys.stdout.getvalue(),
2714 'Tried jobs on:\nBucket: test.bucket')
tandriide281ae2016-10-12 06:02:30 -07002715
qyearsley123a4682016-10-26 09:12:17 -07002716 def test_git_cl_try_bots_on_multiple_masters(self):
2717 self.mock(git_cl.Changelist, 'GetMostRecentPatchset', lambda _: 20001)
2718 self.calls = [
2719 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2720 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
2721 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2722 ((['git', 'config', 'rietveld.server'],),
tandrii8c5a3532016-11-04 07:52:02 -07002723 'https://codereview.chromium.org'),
qyearsley123a4682016-10-26 09:12:17 -07002724 ((['git', 'config', 'branch.feature.rietveldserver'],), CERR1),
2725 ((['git', 'config', 'branch.feature.rietveldpatchset'],), '20001'),
2726 ]
2727
2728 def _buildbucket_retry(*_, **kw):
2729 body = json.loads(kw['body'])
2730 self.assertEqual(len(body['builds']), 2)
2731
Nodir Turakulovb422e682018-02-20 22:51:30 -08002732 self.assertEqual(body['builds'][0]['bucket'], 'bucket1')
2733 params = json.loads(body['builds'][0]['parameters_json'])
2734 self.assertEqual(params['builder_name'], 'builder1')
qyearsley123a4682016-10-26 09:12:17 -07002735
Nodir Turakulovb422e682018-02-20 22:51:30 -08002736 self.assertEqual(body['builds'][1]['bucket'], 'bucket2')
2737 params = json.loads(body['builds'][1]['parameters_json'])
2738 self.assertEqual(params['builder_name'], 'builder2')
qyearsley123a4682016-10-26 09:12:17 -07002739
2740 self.mock(git_cl, '_buildbucket_retry', _buildbucket_retry)
2741
2742 self.mock(git_cl.urllib2, 'urlopen', lambda _: StringIO.StringIO(
Nodir Turakulovb422e682018-02-20 22:51:30 -08002743 json.dumps({
2744 'builder1': {'bucket': 'bucket1'},
2745 'builder2': {'bucket': 'bucket2'},
2746 })))
qyearsley123a4682016-10-26 09:12:17 -07002747
2748 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2749 self.assertEqual(
2750 0, git_cl.main(['try', '-b', 'builder1', '-b', 'builder2']))
2751 self.assertEqual(
2752 git_cl.sys.stdout.getvalue(),
2753 'Tried jobs on:\n'
Nodir Turakulovb422e682018-02-20 22:51:30 -08002754 'Bucket: bucket1\n'
qyearsley123a4682016-10-26 09:12:17 -07002755 ' builder1: []\n'
Nodir Turakulovb422e682018-02-20 22:51:30 -08002756 'Bucket: bucket2\n'
qyearsley123a4682016-10-26 09:12:17 -07002757 ' builder2: []\n'
2758 'To see results here, run: git cl try-results\n'
2759 'To see results in browser, run: git cl web\n')
2760
tandrii16e0b4e2016-06-07 10:34:28 -07002761 def _common_GerritCommitMsgHookCheck(self):
2762 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
2763 self.mock(git_cl.os.path, 'abspath',
2764 lambda path: self._mocked_call(['abspath', path]))
2765 self.mock(git_cl.os.path, 'exists',
2766 lambda path: self._mocked_call(['exists', path]))
2767 self.mock(git_cl.gclient_utils, 'FileRead',
2768 lambda path: self._mocked_call(['FileRead', path]))
2769 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2770 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2771 self.calls = [
2772 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2773 ((['abspath', '../'],), '/abs/git_repo_root'),
2774 ]
2775 return git_cl.Changelist(codereview='gerrit', issue=123)
2776
2777 def test_GerritCommitMsgHookCheck_custom_hook(self):
2778 cl = self._common_GerritCommitMsgHookCheck()
2779 self.calls += [
2780 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2781 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2782 '#!/bin/sh\necho "custom hook"')
2783 ]
2784 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
2785
2786 def test_GerritCommitMsgHookCheck_not_exists(self):
2787 cl = self._common_GerritCommitMsgHookCheck()
2788 self.calls += [
2789 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2790 ]
2791 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
2792
2793 def test_GerritCommitMsgHookCheck(self):
2794 cl = self._common_GerritCommitMsgHookCheck()
2795 self.calls += [
2796 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2797 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2798 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002799 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002800 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2801 ''),
2802 ]
2803 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
2804
tandriic4344b52016-08-29 06:04:54 -07002805 def test_GerritCmdLand(self):
2806 self.calls += [
2807 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2808 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2809 'deadbeaf'),
2810 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2811 ((['git', 'config', 'branch.feature.gerritserver'],),
2812 'chromium-review.googlesource.com'),
2813 ]
2814 cl = git_cl.Changelist(issue=123, codereview='gerrit')
2815 cl._codereview_impl._GetChangeDetail = lambda _: {
2816 'labels': {},
2817 'current_revision': 'deadbeaf',
2818 }
agable32978d92016-11-01 12:55:02 -07002819 cl._codereview_impl._GetChangeCommit = lambda: {
2820 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002821 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002822 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2823 }
tandriic4344b52016-08-29 06:04:54 -07002824 cl._codereview_impl.SubmitIssue = lambda wait_for_merge: None
tandrii8da412c2016-09-07 16:01:07 -07002825 out = StringIO.StringIO()
2826 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002827 self.assertEqual(0, cl.CMDLand(force=True,
2828 bypass_hooks=True,
2829 verbose=True,
2830 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002831 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002832 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002833
tandrii221ab252016-10-06 08:12:04 -07002834 BUILDBUCKET_BUILDS_MAP = {
Quinten Yearsleya563d722017-12-11 16:36:54 -08002835 '9000': {
2836 'id': '9000',
2837 'bucket': 'master.x.y',
2838 'created_by': 'user:someone@chromium.org',
2839 'created_ts': '147200002222000',
2840 'experimental': False,
2841 'parameters_json': json.dumps({
2842 'builder_name': 'my-bot',
2843 'properties': {'category': 'cq'},
2844 }),
2845 'status': 'STARTED',
2846 'tags': [
2847 'build_address:x.y/my-bot/2',
2848 'builder:my-bot',
2849 'experimental:false',
2850 'user_agent:cq',
2851 ],
2852 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2853 },
2854 '8000': {
2855 'id': '8000',
2856 'bucket': 'master.x.y',
2857 'created_by': 'user:someone@chromium.org',
2858 'created_ts': '147200001111000',
2859 'experimental': False,
2860 'failure_reason': 'BUILD_FAILURE',
2861 'parameters_json': json.dumps({
2862 'builder_name': 'my-bot',
2863 'properties': {'category': 'cq'},
2864 }),
2865 'result_details_json': json.dumps({
2866 'properties': {'buildnumber': 1},
2867 }),
2868 'result': 'FAILURE',
2869 'status': 'COMPLETED',
2870 'tags': [
2871 'build_address:x.y/my-bot/1',
2872 'builder:my-bot',
2873 'experimental:false',
2874 'user_agent:cq',
2875 ],
2876 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2877 },
2878 }
tandrii221ab252016-10-06 08:12:04 -07002879
2880 def test_write_try_results_json(self):
2881 expected_output = [
Quinten Yearsleya563d722017-12-11 16:36:54 -08002882 {
2883 'bucket': 'master.x.y',
2884 'buildbucket_id': '8000',
2885 'builder_name': 'my-bot',
2886 'created_ts': '147200001111000',
2887 'experimental': False,
2888 'failure_reason': 'BUILD_FAILURE',
2889 'result': 'FAILURE',
2890 'status': 'COMPLETED',
2891 'tags': [
2892 'build_address:x.y/my-bot/1',
2893 'builder:my-bot',
2894 'experimental:false',
2895 'user_agent:cq',
2896 ],
2897 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/1',
2898 },
2899 {
2900 'bucket': 'master.x.y',
2901 'buildbucket_id': '9000',
2902 'builder_name': 'my-bot',
2903 'created_ts': '147200002222000',
2904 'experimental': False,
2905 'failure_reason': None,
2906 'result': None,
2907 'status': 'STARTED',
2908 'tags': [
2909 'build_address:x.y/my-bot/2',
2910 'builder:my-bot',
2911 'experimental:false',
2912 'user_agent:cq',
2913 ],
2914 'url': 'http://build.cr.org/p/x.y/builders/my-bot/builds/2',
2915 },
tandrii221ab252016-10-06 08:12:04 -07002916 ]
2917 self.calls = [(('write_json', 'output.json', expected_output), '')]
2918 git_cl.write_try_results_json('output.json', self.BUILDBUCKET_BUILDS_MAP)
2919
tandrii45b2a582016-10-11 03:14:16 -07002920 def _setup_fetch_try_jobs(self, most_recent_patchset=20001):
tandrii221ab252016-10-06 08:12:04 -07002921 out = StringIO.StringIO()
2922 self.mock(sys, 'stdout', out)
tandrii45b2a582016-10-11 03:14:16 -07002923 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
2924 lambda *args: most_recent_patchset)
tandrii221ab252016-10-06 08:12:04 -07002925 self.mock(git_cl.auth, 'get_authenticator_for_host', lambda host, _cfg:
2926 self._mocked_call(['get_authenticator_for_host', host]))
2927 self.mock(git_cl, '_buildbucket_retry', lambda *_, **__:
2928 self._mocked_call(['_buildbucket_retry']))
tandrii45b2a582016-10-11 03:14:16 -07002929
2930 def _setup_fetch_try_jobs_rietveld(self, *request_results):
2931 self._setup_fetch_try_jobs(most_recent_patchset=20001)
tandrii221ab252016-10-06 08:12:04 -07002932 self.calls += [
2933 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2934 ((['git', 'config', 'branch.feature.rietveldissue'],), '1'),
2935 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2936 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
2937 ((['git', 'config', 'branch.feature.rietveldpatchset'],), '20001'),
2938 ((['git', 'config', 'branch.feature.rietveldserver'],),
2939 'codereview.example.com'),
2940 ((['get_authenticator_for_host', 'codereview.example.com'],),
2941 AuthenticatorMock()),
2942 ] + [((['_buildbucket_retry'],), r) for r in request_results]
2943
2944 def test_fetch_try_jobs_none_rietveld(self):
2945 self._setup_fetch_try_jobs_rietveld({})
tandrii45b2a582016-10-11 03:14:16 -07002946 # Simulate that user isn't logged in.
2947 self.mock(AuthenticatorMock, 'has_cached_credentials', lambda _: False)
tandrii221ab252016-10-06 08:12:04 -07002948 self.assertEqual(0, git_cl.main(['try-results']))
tandrii45b2a582016-10-11 03:14:16 -07002949 self.assertRegexpMatches(sys.stdout.getvalue(),
2950 'Warning: Some results might be missing')
tandrii221ab252016-10-06 08:12:04 -07002951 self.assertRegexpMatches(sys.stdout.getvalue(), 'No try jobs')
2952
2953 def test_fetch_try_jobs_some_rietveld(self):
2954 self._setup_fetch_try_jobs_rietveld({
2955 'builds': self.BUILDBUCKET_BUILDS_MAP.values(),
2956 })
2957 self.assertEqual(0, git_cl.main(['try-results']))
tandrii45b2a582016-10-11 03:14:16 -07002958 self.assertRegexpMatches(sys.stdout.getvalue(), '^Failures:')
2959 self.assertRegexpMatches(sys.stdout.getvalue(), 'Started:')
2960 self.assertRegexpMatches(sys.stdout.getvalue(), '2 try jobs')
2961
2962 def _setup_fetch_try_jobs_gerrit(self, *request_results):
2963 self._setup_fetch_try_jobs(most_recent_patchset=13)
2964 self.calls += [
2965 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2966 ((['git', 'config', 'branch.feature.rietveldissue'],), CERR1),
2967 ((['git', 'config', 'branch.feature.gerritissue'],), '1'),
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002968 # TODO(tandrii): Uncomment the below if we decide to support checking
2969 # patchsets for Gerrit.
tandrii45b2a582016-10-11 03:14:16 -07002970 # Simulate that Gerrit has more patchsets than local.
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002971 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'),
tandrii45b2a582016-10-11 03:14:16 -07002972 ((['git', 'config', 'branch.feature.gerritserver'],),
2973 'https://x-review.googlesource.com'),
2974 ((['get_authenticator_for_host', 'x-review.googlesource.com'],),
2975 AuthenticatorMock()),
2976 ] + [((['_buildbucket_retry'],), r) for r in request_results]
2977
2978 def test_fetch_try_jobs_none_gerrit(self):
2979 self._setup_fetch_try_jobs_gerrit({})
2980 self.assertEqual(0, git_cl.main(['try-results']))
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002981 # TODO(tandrii): Uncomment the below if we decide to support checking
2982 # patchsets for Gerrit.
2983 # self.assertRegexpMatches(
2984 # sys.stdout.getvalue(),
2985 # r'Warning: Codereview server has newer patchsets \(13\)')
tandrii45b2a582016-10-11 03:14:16 -07002986 self.assertRegexpMatches(sys.stdout.getvalue(), 'No try jobs')
2987
2988 def test_fetch_try_jobs_some_gerrit(self):
2989 self._setup_fetch_try_jobs_gerrit({
2990 'builds': self.BUILDBUCKET_BUILDS_MAP.values(),
2991 })
Ravi Mistryfda50ca2016-11-14 10:19:18 -05002992 # TODO(tandrii): Uncomment the below if we decide to support checking
2993 # patchsets for Gerrit.
2994 # self.calls.remove(
2995 # ((['git', 'config', 'branch.feature.gerritpatchset'],), '12'))
tandrii45b2a582016-10-11 03:14:16 -07002996 self.assertEqual(0, git_cl.main(['try-results', '--patchset', '5']))
2997
2998 # ... and doesn't result in warning.
2999 self.assertNotRegexpMatches(sys.stdout.getvalue(), 'Warning')
3000 self.assertRegexpMatches(sys.stdout.getvalue(), '^Failures:')
tandrii221ab252016-10-06 08:12:04 -07003001 self.assertRegexpMatches(sys.stdout.getvalue(), 'Started:')
3002 self.assertRegexpMatches(sys.stdout.getvalue(), '2 try jobs')
3003
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003004 def _mock_gerrit_changes_for_detail_cache(self):
3005 self.mock(git_cl._GerritChangelistImpl, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003006
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003007 def test_gerrit_change_detail_cache_simple(self):
3008 self._mock_gerrit_changes_for_detail_cache()
3009 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003010 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
3011 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
3012 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003013 ]
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00003014 cl1 = git_cl.Changelist(issue=1, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003015 cl1._cached_remote_url = (
3016 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00003017 cl2 = git_cl.Changelist(issue=2, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003018 cl2._cached_remote_url = (
3019 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00003020 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
3021 self.assertEqual(cl1._GetChangeDetail(), 'a')
3022 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
3023 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
3024 self.assertEqual(cl1._GetChangeDetail(), 'a')
3025 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003026
3027 def test_gerrit_change_detail_cache_options(self):
3028 self._mock_gerrit_changes_for_detail_cache()
3029 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003030 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
3031 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
3032 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
3033 # no longer in cache.
3034 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003035 ]
3036 cl = git_cl.Changelist(issue=1, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003037 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01003038 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
3039 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
3040 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
3041 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
3042 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
3043 self.assertEqual(cl._GetChangeDetail(), 'cab')
3044
3045 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
3046 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
3047 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
3048 self.assertEqual(cl._GetChangeDetail(), 'cab')
3049
3050 # Finally, no_cache should invalidate all caches for given change.
3051 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
3052 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
3053
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01003054 def test_gerrit_description_caching(self):
3055 def gen_detail(rev, desc):
3056 return {
3057 'current_revision': rev,
3058 'revisions': {rev: {'commit': {'message': desc}}}
3059 }
3060 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003061 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01003062 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
3063 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003064 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01003065 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
3066 gen_detail('rev2', 'desc2')),
3067 ]
3068
3069 self._mock_gerrit_changes_for_detail_cache()
3070 cl = git_cl.Changelist(issue=1, codereview='gerrit')
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003071 cl._cached_remote_url = (
3072 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01003073 self.assertEqual(cl.GetDescription(), 'desc1')
3074 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
3075 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00003076
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003077 def test_print_current_creds(self):
3078 class CookiesAuthenticatorMock(object):
3079 def __init__(self):
3080 self.gitcookies = {
3081 'host.googlesource.com': ('user', 'pass'),
3082 'host-review.googlesource.com': ('user', 'pass'),
3083 }
3084 self.netrc = self
3085 self.netrc.hosts = {
3086 'github.com': ('user2', None, 'pass2'),
3087 'host2.googlesource.com': ('user3', None, 'pass'),
3088 }
3089 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
3090 CookiesAuthenticatorMock)
3091 self.mock(sys, 'stdout', StringIO.StringIO())
3092 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
3093 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
3094 ' Host\t User\t Which file',
3095 '============================\t=====\t===========',
3096 'host-review.googlesource.com\t user\t.gitcookies',
3097 ' host.googlesource.com\t user\t.gitcookies',
3098 ' host2.googlesource.com\tuser3\t .netrc',
3099 ])
3100 sys.stdout.buf = ''
3101 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
3102 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
3103 ' Host\tUser\t Which file',
3104 '============================\t====\t===========',
3105 'host-review.googlesource.com\tuser\t.gitcookies',
3106 ' host.googlesource.com\tuser\t.gitcookies',
3107 ])
3108
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003109 def _common_creds_check_mocks(self):
3110 def exists_mock(path):
3111 dirname = os.path.dirname(path)
3112 if dirname == os.path.expanduser('~'):
3113 dirname = '~'
3114 base = os.path.basename(path)
3115 if base in ('.netrc', '.gitcookies'):
3116 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
3117 # git cl also checks for existence other files not relevant to this test.
3118 return None
3119 self.mock(os.path, 'exists', exists_mock)
3120 self.mock(sys, 'stdout', StringIO.StringIO())
3121
3122 def test_creds_check_gitcookies_not_configured(self):
3123 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003124 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003125 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003126 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08003127 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003128 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
3129 (('os.path.exists', '~/.netrc'), True),
3130 (('ask_for_data', 'Press Enter to setup .gitcookies, '
3131 'or Ctrl+C to abort'), ''),
3132 ((['git', 'config', '--global', 'http.cookiefile',
3133 os.path.expanduser('~/.gitcookies')], ), ''),
3134 ]
3135 self.assertEqual(0, git_cl.main(['creds-check']))
3136 self.assertRegexpMatches(
3137 sys.stdout.getvalue(),
3138 '^You seem to be using outdated .netrc for git credentials:')
3139 self.assertRegexpMatches(
3140 sys.stdout.getvalue(),
3141 '\nConfigured git to use .gitcookies from')
3142
3143 def test_creds_check_gitcookies_configured_custom_broken(self):
3144 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003145 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003146 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003147 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08003148 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003149 ((['git', 'config', '--global', 'http.cookiefile'],),
3150 '/custom/.gitcookies'),
3151 (('os.path.exists', '/custom/.gitcookies'), False),
3152 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
3153 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
3154 ((['git', 'config', '--global', 'http.cookiefile',
3155 os.path.expanduser('~/.gitcookies')], ), ''),
3156 ]
3157 self.assertEqual(0, git_cl.main(['creds-check']))
3158 self.assertRegexpMatches(
3159 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003160 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003161 self.assertRegexpMatches(
3162 sys.stdout.getvalue(),
3163 'However, your configured .gitcookies file is missing.')
3164
Andrii Shyshkalov0d6b46e2017-03-17 22:23:22 +01003165 def test_git_cl_comment_add_rietveld(self):
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01003166 self.mock(git_cl._RietveldChangelistImpl, 'AddComment',
Aaron Gable636b13f2017-07-14 10:42:48 -07003167 lambda _, message, publish: self._mocked_call(
3168 'AddComment', message, publish))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01003169 self.calls = [
3170 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
3171 ((['git', 'config', 'rietveld.server'],), 'codereview.chromium.org'),
Aaron Gable636b13f2017-07-14 10:42:48 -07003172 (('AddComment', 'msg', None), ''),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01003173 ]
Andrii Shyshkalov0d6b46e2017-03-17 22:23:22 +01003174 self.assertEqual(0, git_cl.main(['comment', '--rietveld',
3175 '-i', '10', '-a', 'msg']))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01003176
3177 def test_git_cl_comment_add_gerrit(self):
3178 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07003179 lambda host, change, msg, ready:
3180 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01003181 self.calls = [
3182 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
3183 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
3184 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
3185 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
3186 'origin/master'),
3187 ((['git', 'config', 'remote.origin.url'],),
3188 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00003189 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
3190 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07003191 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01003192 ]
3193 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
3194 '-a', 'msg']))
3195
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003196 def test_git_cl_comments_fetch_rietveld(self):
3197 self.mock(sys, 'stdout', StringIO.StringIO())
3198 self.calls = [
3199 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
3200 ((['git', 'config', 'rietveld.server'],), 'codereview.chromium.org'),
Leszek Swirski45b20c42018-09-17 17:05:26 +00003201 ] * 2 + [
3202 (('write_json', 'output.json', [
3203 {
3204 'date': '2000-03-13 20:49:34.515270',
3205 'message': 'PTAL',
3206 'approval': False,
3207 'disapproval': False,
3208 'sender': 'owner@example.com'
3209 }, {
3210 'date': '2017-03-13 20:49:34.515270',
3211 'message': 'lgtm',
3212 'approval': True,
3213 'disapproval': False,
3214 'sender': 'r@example.com'
3215 }, {
3216 'date': '2017-03-13 21:50:34.515270',
3217 'message': 'not lgtm',
3218 'approval': False,
3219 'disapproval': True,
3220 'sender': 'r2@example.com'
3221 }
3222 ]),'')
3223 ]
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003224 self.mock(git_cl._RietveldChangelistImpl, 'GetIssueProperties', lambda _: {
3225 'messages': [
3226 {'text': 'lgtm', 'date': '2017-03-13 20:49:34.515270',
3227 'disapproval': False, 'approval': True, 'sender': 'r@example.com'},
3228 {'text': 'not lgtm', 'date': '2017-03-13 21:50:34.515270',
3229 'disapproval': True, 'approval': False, 'sender': 'r2@example.com'},
3230 # Intentionally wrong order here.
3231 {'text': 'PTAL', 'date': '2000-03-13 20:49:34.515270',
3232 'disapproval': False, 'approval': False,
3233 'sender': 'owner@example.com'},
3234 ],
3235 'owner_email': 'owner@example.com',
3236 })
3237 expected_comments_summary = [
3238 git_cl._CommentSummary(
3239 message='lgtm',
3240 date=datetime.datetime(2017, 3, 13, 20, 49, 34, 515270),
3241 disapproval=False, approval=True, sender='r@example.com'),
3242 git_cl._CommentSummary(
3243 message='not lgtm',
3244 date=datetime.datetime(2017, 3, 13, 21, 50, 34, 515270),
3245 disapproval=True, approval=False, sender='r2@example.com'),
3246 # Note: same order as in whatever Rietveld returns.
3247 git_cl._CommentSummary(
3248 message='PTAL',
3249 date=datetime.datetime(2000, 3, 13, 20, 49, 34, 515270),
3250 disapproval=False, approval=False, sender='owner@example.com'),
3251 ]
3252 cl = git_cl.Changelist(codereview='rietveld', issue=1)
3253 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Leszek Swirski45b20c42018-09-17 17:05:26 +00003254 self.assertEqual(0, git_cl.main(['comment', '--rietveld', '-i', '10',
3255 '-j', 'output.json']))
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003256
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003257 def test_git_cl_comments_fetch_gerrit(self):
3258 self.mock(sys, 'stdout', StringIO.StringIO())
3259 self.calls = [
3260 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
3261 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
3262 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
3263 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
3264 'origin/master'),
3265 ((['git', 'config', 'remote.origin.url'],),
3266 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00003267 (('GetChangeDetail', 'chromium-review.googlesource.com',
3268 'infra%2Finfra~1',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003269 ['MESSAGES', 'DETAILED_ACCOUNTS']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003270 'owner': {'email': 'owner@example.com'},
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003271 'messages': [
3272 {
3273 u'_revision_number': 1,
3274 u'author': {
3275 u'_account_id': 1111084,
3276 u'email': u'commit-bot@chromium.org',
3277 u'name': u'Commit Bot'
3278 },
3279 u'date': u'2017-03-15 20:08:45.000000000',
3280 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07003281 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003282 u'tag': u'autogenerated:cq:dry-run'
3283 },
3284 {
3285 u'_revision_number': 2,
3286 u'author': {
3287 u'_account_id': 11151243,
3288 u'email': u'owner@example.com',
3289 u'name': u'owner'
3290 },
3291 u'date': u'2017-03-16 20:00:41.000000000',
3292 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
3293 u'message': u'PTAL',
3294 },
3295 {
3296 u'_revision_number': 2,
3297 u'author': {
3298 u'_account_id': 148512 ,
3299 u'email': u'reviewer@example.com',
3300 u'name': u'reviewer'
3301 },
3302 u'date': u'2017-03-17 05:19:37.500000000',
3303 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
3304 u'message': u'Patch Set 2: Code-Review+1',
3305 },
3306 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003307 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00003308 (('GetChangeComments', 'chromium-review.googlesource.com',
3309 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003310 '/COMMIT_MSG': [
3311 {
3312 'author': {'email': u'reviewer@example.com'},
3313 'updated': u'2017-03-17 05:19:37.500000000',
3314 'patch_set': 2,
3315 'side': 'REVISION',
3316 'message': 'Please include a bug link',
3317 },
3318 ],
3319 'codereview.settings': [
3320 {
3321 'author': {'email': u'owner@example.com'},
3322 'updated': u'2017-03-16 20:00:41.000000000',
3323 'patch_set': 2,
3324 'side': 'PARENT',
3325 'line': 42,
3326 'message': 'I removed this because it is bad',
3327 },
3328 ]
Leszek Swirski45b20c42018-09-17 17:05:26 +00003329 })
3330 ] * 2 + [
3331 (('write_json', 'output.json', [
3332 {
3333 u'date': u'2017-03-16 20:00:41.000000',
3334 u'message': (
3335 u'PTAL\n' +
3336 u'\n' +
3337 u'codereview.settings\n' +
3338 u' Base, Line 42: https://chromium-review.googlesource.com/' +
3339 u'c/1/2/codereview.settings#b42\n' +
3340 u' I removed this because it is bad\n'),
3341 u'approval': False,
3342 u'disapproval': False,
3343 u'sender': u'owner@example.com'
3344 }, {
3345 u'date': u'2017-03-17 05:19:37.500000',
3346 u'message': (
3347 u'Patch Set 2: Code-Review+1\n' +
3348 u'\n' +
3349 u'/COMMIT_MSG\n' +
3350 u' PS2, File comment: https://chromium-review.googlesource' +
3351 u'.com/c/1/2//COMMIT_MSG#\n' +
3352 u' Please include a bug link\n'),
3353 u'approval': False,
3354 u'disapproval': False,
3355 u'sender': u'reviewer@example.com'
3356 }
3357 ]),'')
3358 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003359 expected_comments_summary = [
3360 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003361 message=(
3362 u'PTAL\n' +
3363 u'\n' +
3364 u'codereview.settings\n' +
3365 u' Base, Line 42: https://chromium-review.googlesource.com/' +
3366 u'c/1/2/codereview.settings#b42\n' +
3367 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003368 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
3369 disapproval=False, approval=False, sender=u'owner@example.com'),
3370 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003371 message=(
3372 u'Patch Set 2: Code-Review+1\n' +
3373 u'\n' +
3374 u'/COMMIT_MSG\n' +
3375 u' PS2, File comment: https://chromium-review.googlesource.com/' +
3376 u'c/1/2//COMMIT_MSG#\n' +
3377 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01003378 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
3379 disapproval=False, approval=False, sender=u'reviewer@example.com'),
3380 ]
3381 cl = git_cl.Changelist(codereview='gerrit', issue=1)
3382 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Leszek Swirski45b20c42018-09-17 17:05:26 +00003383 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '1',
3384 '-j', 'output.json']))
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003385
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00003386 def test_get_remote_url_with_mirror(self):
3387 original_os_path_isdir = os.path.isdir
3388 def selective_os_path_isdir_mock(path):
3389 if path == '/cache/this-dir-exists':
3390 return self._mocked_call('os.path.isdir', path)
3391 return original_os_path_isdir(path)
3392 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
3393
3394 url = 'https://chromium.googlesource.com/my/repo'
3395 self.calls = [
3396 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3397 ((['git', 'config', 'branch.master.merge'],), 'master'),
3398 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3399 ((['git', 'config', 'remote.origin.url'],),
3400 '/cache/this-dir-exists'),
3401 (('os.path.isdir', '/cache/this-dir-exists'),
3402 True),
3403 # Runs in /cache/this-dir-exists.
3404 ((['git', 'config', 'remote.origin.url'],),
3405 url),
3406 ]
3407 cl = git_cl.Changelist(codereview='gerrit', issue=1)
3408 self.assertEqual(cl.GetRemoteUrl(), url)
3409 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
3410
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003411 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003412 self.calls = [
3413 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3414 ((['git', 'config', 'branch.master.merge'],), 'master'),
3415 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3416 ((['git', 'config', 'remote.origin.url'],),
3417 'https://chromium.googlesource.com/a/my/repo.git/'),
3418 ]
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003419 cl = git_cl.Changelist(codereview='gerrit', issue=123456)
3420 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3421
3422 def test_gerrit_change_identifier_without_project(self):
3423 self.calls = [
3424 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3425 ((['git', 'config', 'branch.master.merge'],), 'master'),
3426 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3427 ((['git', 'config', 'remote.origin.url'],), CERR1),
3428 ]
3429 cl = git_cl.Changelist(codereview='gerrit', issue=123456)
3430 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003431
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003432
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003433if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003434 logging.basicConfig(
3435 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003436 unittest.main()