blob: 03fbf9dbc927d8ab978a48c5ac0dabfcc88929bc [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
8import os
maruel@chromium.orga3353652011-11-30 14:26:57 +00009import StringIO
ukai@chromium.org78c4b982012-02-14 02:20:26 +000010import stat
maruel@chromium.orgddd59412011-11-30 14:20:38 +000011import sys
12import unittest
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +000013import urlparse
maruel@chromium.orgddd59412011-11-30 14:20:38 +000014
15sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
16
17from testing_support.auto_stub import TestCase
18
19import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000020import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000021import git_footers
maruel@chromium.orgddd59412011-11-30 14:20:38 +000022import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000023
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000024class ChangelistMock(object):
25 # A class variable so we can access it when we don't have access to the
26 # instance that's being set.
27 desc = ""
28 def __init__(self, **kwargs):
29 pass
30 def GetIssue(self):
31 return 1
32 def GetDescription(self):
33 return ChangelistMock.desc
34 def UpdateDescription(self, desc):
35 ChangelistMock.desc = desc
36
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000037class PresubmitMock(object):
38 def __init__(self, *args, **kwargs):
39 self.reviewers = []
40 @staticmethod
41 def should_continue():
42 return True
43
44
45class RietveldMock(object):
46 def __init__(self, *args, **kwargs):
47 pass
maruel@chromium.org78936cb2013-04-11 00:17:52 +000048
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000049 @staticmethod
50 def get_description(issue):
51 return 'Issue: %d' % issue
52
maruel@chromium.org78936cb2013-04-11 00:17:52 +000053 @staticmethod
54 def get_issue_properties(_issue, _messages):
55 return {
56 'reviewers': ['joe@chromium.org', 'john@chromium.org'],
57 'messages': [
58 {
59 'approval': True,
60 'sender': 'john@chromium.org',
61 },
62 ],
63 }
64
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000065
66class WatchlistsMock(object):
67 def __init__(self, _):
68 pass
69 @staticmethod
70 def GetWatchersForPaths(_):
71 return ['joe@example.com']
72
73
ukai@chromium.org78c4b982012-02-14 02:20:26 +000074class CodereviewSettingsFileMock(object):
75 def __init__(self):
76 pass
77 # pylint: disable=R0201
78 def read(self):
79 return ("CODE_REVIEW_SERVER: gerrit.chromium.org\n" +
andybons@chromium.org11f46eb2016-02-02 19:26:51 +000080 "GERRIT_HOST: True\n")
ukai@chromium.org78c4b982012-02-14 02:20:26 +000081
82
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +000083class AuthenticatorMock(object):
84 def __init__(self, *_args):
85 pass
86 def has_cached_credentials(self):
87 return True
88
89
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +000090def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_cookie=False):
91 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
92
93 Usage:
94 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
95 CookiesAuthenticatorMockFactory({'host1': 'cookie1'}))
96
97 OR
98 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
99 CookiesAuthenticatorMockFactory(cookie='cookie'))
100 """
101 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
102 def __init__(self): # pylint: disable=W0231
103 # Intentionally not calling super() because it reads actual cookie files.
104 pass
105 @classmethod
106 def get_gitcookies_path(cls):
107 return '~/.gitcookies'
108 @classmethod
109 def get_netrc_path(cls):
110 return '~/.netrc'
111 def get_auth_header(self, host):
112 if same_cookie:
113 return same_cookie
114 return (hosts_with_creds or {}).get(host)
115 return CookiesAuthenticatorMock
116
117
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000118class TestGitClBasic(unittest.TestCase):
119 def _test_ParseIssueUrl(self, func, url, issue, patchset, hostname, fail):
120 parsed = urlparse.urlparse(url)
121 result = func(parsed)
122 if fail:
123 self.assertIsNone(result)
124 return None
125 self.assertIsNotNone(result)
126 self.assertEqual(result.issue, issue)
127 self.assertEqual(result.patchset, patchset)
128 self.assertEqual(result.hostname, hostname)
129 return result
130
131 def test_ParseIssueURL_rietveld(self):
132 def test(url, issue=None, patchset=None, hostname=None, patch_url=None,
133 fail=None):
134 result = self._test_ParseIssueUrl(
135 git_cl._RietveldChangelistImpl.ParseIssueURL,
136 url, issue, patchset, hostname, fail)
137 if not fail:
138 self.assertEqual(result.patch_url, patch_url)
139
140 test('http://codereview.chromium.org/123',
141 123, None, 'codereview.chromium.org')
142 test('https://codereview.chromium.org/123',
143 123, None, 'codereview.chromium.org')
144 test('https://codereview.chromium.org/123/',
145 123, None, 'codereview.chromium.org')
146 test('https://codereview.chromium.org/123/whatever',
147 123, None, 'codereview.chromium.org')
wychen3c1c1722016-08-04 11:46:36 -0700148 test('https://codereview.chromium.org/123/#ps20001',
149 123, 20001, 'codereview.chromium.org')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000150 test('http://codereview.chromium.org/download/issue123_4.diff',
151 123, 4, 'codereview.chromium.org',
152 patch_url='https://codereview.chromium.org/download/issue123_4.diff')
153 # This looks like bad Gerrit, but is actually valid Rietveld.
154 test('https://chrome-review.source.com/123/4/',
155 123, None, 'chrome-review.source.com')
156
157 test('https://codereview.chromium.org/deadbeaf', fail=True)
158 test('https://codereview.chromium.org/api/123', fail=True)
159 test('bad://codereview.chromium.org/123', fail=True)
160 test('http://codereview.chromium.org/download/issue123_4.diffff', fail=True)
161
162 def test_ParseIssueURL_gerrit(self):
163 def test(url, issue=None, patchset=None, hostname=None, fail=None):
164 self._test_ParseIssueUrl(
165 git_cl._GerritChangelistImpl.ParseIssueURL,
166 url, issue, patchset, hostname, fail)
167
168 test('http://chrome-review.source.com/c/123',
169 123, None, 'chrome-review.source.com')
170 test('https://chrome-review.source.com/c/123/',
171 123, None, 'chrome-review.source.com')
172 test('https://chrome-review.source.com/c/123/4',
173 123, 4, 'chrome-review.source.com')
174 test('https://chrome-review.source.com/#/c/123/4',
175 123, 4, 'chrome-review.source.com')
176 test('https://chrome-review.source.com/c/123/4',
177 123, 4, 'chrome-review.source.com')
178 test('https://chrome-review.source.com/123',
179 123, None, 'chrome-review.source.com')
180 test('https://chrome-review.source.com/123/4',
181 123, 4, 'chrome-review.source.com')
182
183 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
184 test('https://chrome-review.source.com/c/abc/', fail=True)
185 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
186
187 def test_ParseIssueNumberArgument(self):
188 def test(arg, issue=None, patchset=None, hostname=None, fail=False):
189 result = git_cl.ParseIssueNumberArgument(arg)
190 self.assertIsNotNone(result)
191 if fail:
192 self.assertFalse(result.valid)
193 else:
194 self.assertEqual(result.issue, issue)
195 self.assertEqual(result.patchset, patchset)
196 self.assertEqual(result.hostname, hostname)
197
198 test('123', 123)
199 test('', fail=True)
200 test('abc', fail=True)
201 test('123/1', fail=True)
202 test('123a', fail=True)
203 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
204 # Rietveld.
205 test('https://codereview.source.com/123',
206 123, None, 'codereview.source.com')
207 test('https://codereview.source.com/www123', fail=True)
208 # Gerrrit.
209 test('https://chrome-review.source.com/c/123/4',
210 123, 4, 'chrome-review.source.com')
211 test('https://chrome-review.source.com/bad/123/4', fail=True)
212
tandriif9aefb72016-07-01 09:06:51 -0700213 def test_get_bug_line_values(self):
214 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
215 self.assertEqual(f('', ''), [])
216 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
217 self.assertEqual(f('v8', '456'), ['v8:456'])
218 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
219 # Not nice, but not worth carying.
220 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
221 ['v8:456', 'chromium:123', 'v8:123'])
222
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000223
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000224class TestGitCl(TestCase):
225 def setUp(self):
226 super(TestGitCl, self).setUp()
227 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700228 self._calls_done = []
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000229 self.mock(subprocess2, 'call', self._mocked_call)
230 self.mock(subprocess2, 'check_call', self._mocked_call)
231 self.mock(subprocess2, 'check_output', self._mocked_call)
232 self.mock(subprocess2, 'communicate', self._mocked_call)
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000233 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000234 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000235 self.mock(git_common, 'get_or_create_merge_base',
236 lambda *a: (
237 self._mocked_call(['get_or_create_merge_base']+list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000238 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000239 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000240 self.mock(git_cl, 'ask_for_data', self._mocked_call)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000241 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000242 self.mock(git_cl.rietveld, 'Rietveld', RietveldMock)
maruel@chromium.org4bac4b52012-11-27 20:33:52 +0000243 self.mock(git_cl.rietveld, 'CachingRietveld', RietveldMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000244 self.mock(git_cl.upload, 'RealMain', self.fail)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000245 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000246 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000247 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
248 classmethod(lambda _: False))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000249 # It's important to reset settings to not have inter-tests interference.
250 git_cl.settings = None
251
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000252
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000253 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000254 try:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000255 # Note: has_failed returns True if at least 1 test ran so far, current
256 # included, has failed. That means current test may have actually ran
257 # fine, and the check for no leftover calls would be skipped.
wychen@chromium.org445c8962015-04-28 23:30:05 +0000258 if not self.has_failed():
259 self.assertEquals([], self.calls)
260 finally:
261 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000262
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000263 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000264 self.assertTrue(
265 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700266 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000267 top = self.calls.pop(0)
268 if len(top) > 2 and top[2]:
269 raise top[2]
270 expected_args, result = top
271
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000272 # Also logs otherwise it could get caught in a try/finally and be hard to
273 # diagnose.
274 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700275 N = 5
276 prior_calls = '\n '.join(
277 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
278 for i, c in enumerate(self._calls_done[-N:]))
279 following_calls = '\n '.join(
280 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
281 for i, c in enumerate(self.calls[:N]))
282 extended_msg = (
283 'A few prior calls:\n %s\n\n'
284 'This (expected):\n @%d: %r\n'
285 'This (actual):\n @%d: %r\n\n'
286 'A few following expected calls:\n %s' %
287 (prior_calls, len(self._calls_done), expected_args,
288 len(self._calls_done), args, following_calls))
289 git_cl.logging.error(extended_msg)
290
tandrii99a72f22016-08-17 14:33:24 -0700291 self.fail('@%d\n'
292 ' Expected: %r\n'
293 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700294 len(self._calls_done), expected_args, args))
295
296 self._calls_done.append(top)
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000297 return result
298
maruel@chromium.orga3353652011-11-30 14:26:57 +0000299 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000300 def _is_gerrit_calls(cls, gerrit=False):
301 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
302 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
303
304 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000305 def _upload_calls(cls, similarity, find_copies, private):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000306 return (cls._git_base_calls(similarity, find_copies) +
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000307 cls._git_upload_calls(private))
maruel@chromium.orga3353652011-11-30 14:26:57 +0000308
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000309 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000310 def _upload_no_rev_calls(cls, similarity, find_copies):
311 return (cls._git_base_calls(similarity, find_copies) +
312 cls._git_upload_no_rev_calls())
313
314 @classmethod
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000315 def _git_base_calls(cls, similarity, find_copies):
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000316 if similarity is None:
317 similarity = '50'
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000318 similarity_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000319 'branch.master.git-cl-similarity'],), '')
320 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000321 similarity_call = ((['git', 'config', '--int',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000322 'branch.master.git-cl-similarity', similarity],), '')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000323
324 if find_copies is None:
325 find_copies = True
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000326 find_copies_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000327 'branch.master.git-find-copies'],), '')
328 else:
329 val = str(int(find_copies))
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000330 find_copies_call = ((['git', 'config', '--int',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000331 'branch.master.git-find-copies', val],), '')
332
333 if find_copies:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000334 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000335 '--find-copies-harder', '-l100000', '-C'+similarity,
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000336 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000337 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000338 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000339 '-M'+similarity, 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000340
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000341 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000342 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000343 similarity_call,
344 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
345 find_copies_call,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000346 ] + cls._is_gerrit_calls() + [
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000347 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000348 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
349 ((['git', 'config', 'branch.master.gerritissue'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000350 ((['git', 'config', 'rietveld.server'],),
351 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000352 ((['git', 'config', 'branch.master.merge'],), 'master'),
353 ((['git', 'config', 'branch.master.remote'],), 'origin'),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000354 ((['get_or_create_merge_base', 'master', 'master'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000355 'fake_ancestor_sha'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000356 ] + cls._git_sanity_checks('fake_ancestor_sha', 'master') + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000357 ((['git', 'rev-parse', '--show-cdup'],), ''),
358 ((['git', 'rev-parse', 'HEAD'],), '12345'),
359 ((['git', 'diff', '--name-status', '--no-renames', '-r',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000360 'fake_ancestor_sha...', '.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000361 'M\t.gitignore\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000362 ((['git', 'config', 'branch.master.rietveldpatchset'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000363 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000364 ((['git', 'log', '--pretty=format:%s%n%n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000365 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000366 'foo'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000367 ((['git', 'config', 'user.email'],), 'me@example.com'),
iannucci@chromium.org79540052012-10-19 23:15:26 +0000368 stat_call,
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000369 ((['git', 'log', '--pretty=format:%s\n\n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000370 'fake_ancestor_sha..HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000371 'desc\n'),
rmistry@google.com90752582014-01-14 21:04:50 +0000372 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
maruel@chromium.orga3353652011-11-30 14:26:57 +0000373 ]
374
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000375 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000376 def _git_upload_no_rev_calls(cls):
377 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000378 ((['git', 'config', 'core.editor'],), ''),
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000379 ]
380
381 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000382 def _git_upload_calls(cls, private):
383 if private:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000384 cc_call = []
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000385 private_call = []
386 else:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000387 cc_call = [((['git', 'config', 'rietveld.cc'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000388 private_call = [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000389 ((['git', 'config', 'rietveld.private'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000390
maruel@chromium.orga3353652011-11-30 14:26:57 +0000391 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000392 ((['git', 'config', 'core.editor'],), ''),
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000393 ] + cc_call + private_call + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000394 ((['git', 'config', 'branch.master.base-url'],), ''),
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000395 ((['git', 'config', 'rietveld.pending-ref-prefix'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000396 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000397 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
398 (('', None), 0)),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000399 ((['git', 'rev-parse', '--show-cdup'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000400 ((['git', 'svn', 'info'],), ''),
sheyang@chromium.org152cf832014-06-11 21:37:49 +0000401 ((['git', 'config', 'rietveld.project'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000402 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000403 'config', 'branch.master.rietveldissue', '1'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000404 ((['git', 'config', 'branch.master.rietveldserver',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000405 'https://codereview.example.com'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000406 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000407 'config', 'branch.master.rietveldpatchset', '2'],), ''),
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000408 ] + cls._git_post_upload_calls()
409
410 @classmethod
411 def _git_post_upload_calls(cls):
412 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000413 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
414 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
415 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000416 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000417 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000418 ]
419
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000420 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000421 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000422 fake_ancestor = 'fake_ancestor'
423 fake_cl = 'fake_cl_for_patch'
424 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000425 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000426 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000427 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000428 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000429 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000430 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000431 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000432 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000433 'config', 'gitcl.remotebranch'],), (('', None), 1)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000434 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000435 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000436 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000437 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000438 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000439 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000440 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000441 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000442 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000443 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000444 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000445
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000446 @classmethod
447 def _dcommit_calls_1(cls):
448 return [
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000449 ((['git', 'config', 'rietveld.autoupdate'],),
450 ''),
451 ((['git', 'config', 'rietveld.pending-ref-prefix'],),
452 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000453 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000454 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000455 ((('svn-remote.svn.url svn://svn.chromium.org/chrome\n'
456 'svn-remote.svn.fetch trunk/src:refs/remotes/origin/master'),
457 None),
458 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000459 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
460 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000461 'branch.working.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000462 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
463 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000464 'branch.working.git-find-copies'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000465 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
466 ((['git',
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000467 'config', 'branch.working.rietveldissue'],), '12345'),
468 ((['git',
469 'config', 'rietveld.server'],), 'codereview.example.com'),
470 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000471 'config', 'branch.working.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000472 ((['git', 'config', 'branch.working.remote'],), 'origin'),
iannucci@chromium.org5724c962014-04-11 09:32:56 +0000473 ((['git', 'config', 'branch.working.merge'],),
474 'refs/heads/master'),
475 ((['git', 'config', 'branch.working.remote'],), 'origin'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000476 ((['git', 'rev-list', '--merges',
szager@chromium.orge84b7542012-06-15 21:26:58 +0000477 '--grep=^SVN changes up to revision [0-9]*$',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000478 'refs/remotes/origin/master^!'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000479 ((['git', 'rev-list', '^refs/heads/working',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000480 'refs/remotes/origin/master'],),
481 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000482 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000483 'log', '--grep=^git-svn-id:', '-1', '--pretty=format:%H'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000484 '3fc18b62c4966193eb435baabe2d18a3810ec82e'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000485 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000486 'rev-list', '^3fc18b62c4966193eb435baabe2d18a3810ec82e',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000487 'refs/remotes/origin/master'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000488 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000489 'merge-base', 'refs/remotes/origin/master', 'HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000490 'fake_ancestor_sha'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000491 ]
492
493 @classmethod
494 def _dcommit_calls_normal(cls):
495 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000496 ((['git', 'rev-parse', '--show-cdup'],), ''),
497 ((['git', 'rev-parse', 'HEAD'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000498 '00ff397798ea57439712ed7e04ab96e13969ef40'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000499 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000500 'diff', '--name-status', '--no-renames', '-r', 'fake_ancestor_sha...',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000501 '.'],),
502 'M\tPRESUBMIT.py'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000503 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000504 'config', 'branch.working.rietveldpatchset'],), '31137'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000505 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000506 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000507 ((['git', 'config', 'user.email'],), 'author@example.com'),
508 ((['git', 'config', 'rietveld.tree-status-url'],), ''),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000509 ]
510
511 @classmethod
512 def _dcommit_calls_bypassed(cls):
513 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000514 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000515 'codereview.example.com'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000516 ]
517
518 @classmethod
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000519 def _dcommit_calls_3(cls):
520 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000521 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000522 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000523 '-l100000', '-C50', 'fake_ancestor_sha',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000524 'refs/heads/working'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000525 (' PRESUBMIT.py | 2 +-\n'
526 ' 1 files changed, 1 insertions(+), 1 deletions(-)\n')),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000527 ((['git', 'show-ref', '--quiet', '--verify',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000528 'refs/heads/git-cl-commit'],),
529 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000530 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
531 ((['git', 'show-ref', '--quiet', '--verify',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000532 'refs/heads/git-cl-cherry-pick'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000533 ((['git', 'rev-parse', '--show-cdup'],), '\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000534 ((['git', 'checkout', '-q', '-b', 'git-cl-commit'],), ''),
535 ((['git', 'reset', '--soft', 'fake_ancestor_sha'],), ''),
536 ((['git', 'commit', '-m',
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000537 'Issue: 12345\n\nR=john@chromium.org\n\n'
sergiyb@chromium.org4b39c5f2015-07-07 10:33:12 +0000538 'Review URL: https://codereview.example.com/12345 .'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000539 ''),
kjellander@chromium.org6abc6522014-12-02 07:34:49 +0000540 ((['git', 'config', 'rietveld.force-https-commit-url'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000541 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000542 'svn', 'dcommit', '-C50', '--no-rebase', '--rmdir'],),
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000543 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000544 ((['git', 'checkout', '-q', 'working'],), ''),
545 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000546 ]
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000547
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000548 @staticmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000549 def _cmd_line(description, args, similarity, find_copies, private):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000550 """Returns the upload command line passed to upload.RealMain()."""
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000551 return [
552 'upload', '--assume_yes', '--server',
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +0000553 'https://codereview.example.com',
maruel@chromium.org71e12a92012-02-14 02:34:15 +0000554 '--message', description
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000555 ] + args + [
556 '--cc', 'joe@example.com',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000557 ] + (['--private'] if private else []) + [
iannucci@chromium.org79540052012-10-19 23:15:26 +0000558 '--git_similarity', similarity or '50'
559 ] + (['--git_no_find_copies'] if find_copies == False else []) + [
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000560 'fake_ancestor_sha', 'HEAD'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000561 ]
562
563 def _run_reviewer_test(
564 self,
565 upload_args,
566 expected_description,
567 returned_description,
568 final_description,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000569 reviewers,
570 private=False):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000571 """Generic reviewer test framework."""
tandrii@chromium.org28253532016-04-14 13:46:56 +0000572 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000573 try:
574 similarity = upload_args[upload_args.index('--similarity')+1]
575 except ValueError:
576 similarity = None
iannucci@chromium.org79540052012-10-19 23:15:26 +0000577
578 if '--find-copies' in upload_args:
579 find_copies = True
580 elif '--no-find-copies' in upload_args:
581 find_copies = False
582 else:
583 find_copies = None
584
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000585 private = '--private' in upload_args
586
587 self.calls = self._upload_calls(similarity, find_copies, private)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000588
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000589 def RunEditor(desc, _, **kwargs):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000590 self.assertEquals(
591 '# Enter a description of the change.\n'
janx@chromium.org104b2db2013-04-18 12:58:40 +0000592 '# This will be displayed on the codereview site.\n'
alancutter@chromium.org63a4d7f2013-05-31 02:22:45 +0000593 '# The first line will also be used as the subject of the review.\n'
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +0000594 '#--------------------This line is 72 characters long'
595 '--------------------\n' +
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000596 expected_description,
597 desc)
598 return returned_description
599 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000600
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000601 def check_upload(args):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000602 cmd_line = self._cmd_line(final_description, reviewers, similarity,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000603 find_copies, private)
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000604 self.assertEquals(cmd_line, args)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000605 return 1, 2
606 self.mock(git_cl.upload, 'RealMain', check_upload)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000607
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000608 git_cl.main(['upload'] + upload_args)
609
610 def test_no_reviewer(self):
611 self._run_reviewer_test(
612 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000613 'desc\n\nBUG=',
614 '# Blah blah comment.\ndesc\n\nBUG=',
615 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000616 [])
617
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000618 def test_keep_similarity(self):
619 self._run_reviewer_test(
620 ['--similarity', '70'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000621 'desc\n\nBUG=',
622 '# Blah blah comment.\ndesc\n\nBUG=',
623 'desc\n\nBUG=',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000624 [])
625
iannucci@chromium.org79540052012-10-19 23:15:26 +0000626 def test_keep_find_copies(self):
627 self._run_reviewer_test(
628 ['--no-find-copies'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000629 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000630 '# Blah blah comment.\ndesc\n\nBUG=\n',
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000631 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000632 [])
633
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000634 def test_private(self):
635 self._run_reviewer_test(
636 ['--private'],
637 'desc\n\nBUG=',
638 '# Blah blah comment.\ndesc\n\nBUG=\n',
639 'desc\n\nBUG=',
640 [])
641
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000642 def test_reviewers_cmd_line(self):
643 # Reviewer is passed as-is
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000644 description = 'desc\n\nR=foo@example.com\nBUG='
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000645 self._run_reviewer_test(
646 ['-r' 'foo@example.com'],
647 description,
648 '\n%s\n' % description,
649 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000650 ['--reviewers=foo@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000651
652 def test_reviewer_tbr_overriden(self):
653 # Reviewer is overriden with TBR
654 # Also verifies the regexp work without a trailing LF
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000655 description = 'Foo Bar\n\nTBR=reviewer@example.com'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000656 self._run_reviewer_test(
657 ['-r' 'foo@example.com'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000658 'desc\n\nR=foo@example.com\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000659 description.strip('\n'),
660 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000661 ['--reviewers=reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000662
663 def test_reviewer_multiple(self):
664 # Handles multiple R= or TBR= lines.
665 description = (
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000666 'Foo Bar\nTBR=reviewer@example.com\nBUG=\nR=another@example.com')
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000667 self._run_reviewer_test(
668 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000669 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000670 description,
671 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000672 ['--reviewers=another@example.com,reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000673
maruel@chromium.orga3353652011-11-30 14:26:57 +0000674 def test_reviewer_send_mail(self):
675 # --send-mail can be used without -r if R= is used
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000676 description = 'Foo Bar\nR=reviewer@example.com'
maruel@chromium.orga3353652011-11-30 14:26:57 +0000677 self._run_reviewer_test(
678 ['--send-mail'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000679 'desc\n\nBUG=',
maruel@chromium.orga3353652011-11-30 14:26:57 +0000680 description.strip('\n'),
681 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000682 ['--reviewers=reviewer@example.com', '--send_mail'])
maruel@chromium.orga3353652011-11-30 14:26:57 +0000683
684 def test_reviewer_send_mail_no_rev(self):
685 # Fails without a reviewer.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000686 stdout = StringIO.StringIO()
687 stderr = StringIO.StringIO()
maruel@chromium.orga3353652011-11-30 14:26:57 +0000688 try:
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000689 self.calls = self._upload_no_rev_calls(None, None)
690 def RunEditor(desc, _, **kwargs):
maruel@chromium.orga3353652011-11-30 14:26:57 +0000691 return desc
692 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000693 self.mock(sys, 'stdout', stdout)
694 self.mock(sys, 'stderr', stderr)
maruel@chromium.orga3353652011-11-30 14:26:57 +0000695 git_cl.main(['upload', '--send-mail'])
696 self.fail()
697 except SystemExit:
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000698 self.assertEqual(
699 'Using 50% similarity for rename/copy detection. Override with '
700 '--similarity.\n',
701 stdout.getvalue())
702 self.assertEqual(
703 'Must specify reviewers to send email.\n', stderr.getvalue())
maruel@chromium.orga3353652011-11-30 14:26:57 +0000704
tandriif9aefb72016-07-01 09:06:51 -0700705 def test_bug_on_cmd(self):
706 self._run_reviewer_test(
707 ['--bug=500658,proj:123'],
708 'desc\n\nBUG=500658\nBUG=proj:123',
709 '# Blah blah comment.\ndesc\n\nBUG=500658\nBUG=proj:1234',
710 'desc\n\nBUG=500658\nBUG=proj:1234',
711 [])
712
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000713 def test_dcommit(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000714 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000715 self.calls = (
716 self._dcommit_calls_1() +
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000717 self._git_sanity_checks('fake_ancestor_sha', 'working') +
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000718 self._dcommit_calls_normal() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000719 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000720 git_cl.main(['dcommit'])
721
722 def test_dcommit_bypass_hooks(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000723 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000724 self.calls = (
725 self._dcommit_calls_1() +
726 self._dcommit_calls_bypassed() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000727 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000728 git_cl.main(['dcommit', '--bypass-hooks'])
729
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000730
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000731 @classmethod
tandrii@chromium.org28253532016-04-14 13:46:56 +0000732 def _gerrit_ensure_auth_calls(cls, issue=None, skip_auth_check=False):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000733 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000734 if skip_auth_check:
735 return [((cmd, ), 'true')]
736
737 calls = [((cmd, ), '', subprocess2.CalledProcessError(1, '', '', '', ''))]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000738 if issue:
739 calls.extend([
740 ((['git', 'config', 'branch.master.gerritserver'],), ''),
741 ])
742 calls.extend([
743 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
744 ((['git', 'config', 'branch.master.remote'],), 'origin'),
745 ((['git', 'config', 'remote.origin.url'],),
746 'https://chromium.googlesource.com/my/repo'),
747 ((['git', 'config', 'remote.origin.url'],),
748 'https://chromium.googlesource.com/my/repo'),
749 ])
750 return calls
751
752 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000753 def _gerrit_base_calls(cls, issue=None):
ukai@chromium.orge8077812012-02-03 03:41:46 +0000754 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000755 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
756 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000757 'branch.master.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000758 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
759 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000760 'branch.master.git-find-copies'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000761 ] + cls._is_gerrit_calls(True) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000762 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000763 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000764 ((['git', 'config', 'branch.master.gerritissue'],),
765 '' if issue is None else str(issue)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000766 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000767 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000768 ((['get_or_create_merge_base', 'master',
769 'refs/remotes/origin/master'],),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000770 'fake_ancestor_sha'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000771 # Calls to verify branch point is ancestor
772 ] + (cls._gerrit_ensure_auth_calls(issue=issue) +
773 cls._git_sanity_checks('fake_ancestor_sha', 'master',
774 get_remote_branch=False)) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000775 ((['git', 'rev-parse', '--show-cdup'],), ''),
776 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000777
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000778 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000779 'diff', '--name-status', '--no-renames', '-r',
780 'fake_ancestor_sha...', '.'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000781 'M\t.gitignore\n'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000782 ((['git', 'config', 'branch.master.gerritpatchset'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000783 ] + ([] if issue else [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000784 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000785 'log', '--pretty=format:%s%n%n%b', 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000786 'foo'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000787 ]) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000788 ((['git', 'config', 'user.email'],), 'me@example.com'),
789 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000790 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000791 '-l100000', '-C50', 'fake_ancestor_sha', 'HEAD'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000792 '+dat'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000793 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000794
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000795 @classmethod
796 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700797 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000798 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000799 ref_suffix='', notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000800 post_amend_description=None, issue=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000801 if post_amend_description is None:
802 post_amend_description = description
tandriia60502f2016-06-20 02:01:53 -0700803 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000804
tandriia60502f2016-06-20 02:01:53 -0700805 if squash_mode == 'default':
806 calls.extend([
807 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
808 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
809 ])
810 elif squash_mode in ('override_squash', 'override_nosquash'):
811 calls.extend([
812 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
813 'true' if squash_mode == 'override_squash' else 'false'),
814 ])
815 else:
816 assert squash_mode in ('squash', 'nosquash')
817
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000818 # If issue is given, then description is fetched from Gerrit instead.
819 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000820 calls += [
821 ((['git', 'log', '--pretty=format:%s\n\n%b',
822 'fake_ancestor_sha..HEAD'],),
823 description)]
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000824 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000825 calls += [
tandrii@chromium.org10625002016-03-04 20:03:47 +0000826 # DownloadGerritHook(False)
827 ((False, ),
828 ''),
829 # Amending of commit message to get the Change-Id.
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000830 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000831 'fake_ancestor_sha..HEAD'],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000832 description),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000833 ((['git', 'commit', '--amend', '-m', description],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000834 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000835 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000836 'fake_ancestor_sha..HEAD'],),
tandrii@chromium.org10625002016-03-04 20:03:47 +0000837 post_amend_description)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000838 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000839 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000840 if not issue:
841 # Prompting to edit description on first upload.
842 calls += [
843 ((['git', 'config', 'core.editor'],), ''),
844 ((['RunEditor'],), description),
845 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000846 ref_to_push = 'abcdef0123456789'
847 calls += [
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000848 ((['git', 'config', 'branch.master.merge'],),
849 'refs/heads/master'),
850 ((['git', 'config', 'branch.master.remote'],),
851 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000852 ((['get_or_create_merge_base', 'master',
853 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000854 'origin/master'),
855 ((['git', 'rev-parse', 'HEAD:'],),
856 '0123456789abcdef'),
857 ((['git', 'commit-tree', '0123456789abcdef', '-p',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000858 'origin/master', '-m', description],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000859 ref_to_push),
860 ]
861 else:
862 ref_to_push = 'HEAD'
863
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000864 calls += [
luqui@chromium.org609f3952015-05-04 22:47:04 +0000865 ((['git', 'rev-list',
866 expected_upstream_ref + '..' + ref_to_push],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000867 ((['git', 'config', 'rietveld.cc'],), '')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000868 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000869
870 notify_suffix = 'notify=%s' % ('ALL' if notify else 'NONE')
871 if ref_suffix:
872 ref_suffix += ',' + notify_suffix
873 else:
874 ref_suffix = '%' + notify_suffix
tandrii@chromium.org074c2af2016-06-03 23:18:40 +0000875
876 # Add cc from watch list.
877 ref_suffix += ',cc=joe@example.com'
878
ukai@chromium.orge8077812012-02-03 03:41:46 +0000879 if reviewers:
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000880 ref_suffix += ',' + ','.join('r=%s' % email
881 for email in sorted(reviewers))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000882 calls += [
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000883 ((['git', 'push', 'origin',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000884 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000885 ('remote:\n'
886 'remote: Processing changes: (\)\n'
887 'remote: Processing changes: (|)\n'
888 'remote: Processing changes: (/)\n'
889 'remote: Processing changes: (-)\n'
890 'remote: Processing changes: new: 1 (/)\n'
891 'remote: Processing changes: new: 1, done\n'
892 'remote:\n'
893 'remote: New Changes:\n'
894 'remote: https://chromium-review.googlesource.com/123456 XXX.\n'
895 'remote:\n'
896 'To https://chromium.googlesource.com/yyy/zzz\n'
897 ' * [new branch] hhhh -> refs/for/refs/heads/master\n')),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000898 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000899 if squash:
900 calls += [
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000901 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000902 ((['git', 'config', 'branch.master.gerritserver',
903 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000904 ((['git', 'config', 'branch.master.gerritsquashhash',
905 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000906 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000907 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +0000908 return calls
909
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000910 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000911 self,
912 upload_args,
913 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000914 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700915 squash=True,
916 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000917 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000918 ref_suffix='',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000919 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000920 post_amend_description=None,
921 issue=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000922 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700923 if squash_mode is None:
924 if '--no-squash' in upload_args:
925 squash_mode = 'nosquash'
926 elif '--squash' in upload_args:
927 squash_mode = 'squash'
928 else:
929 squash_mode = 'default'
930
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000931 reviewers = reviewers or []
tandrii@chromium.org28253532016-04-14 13:46:56 +0000932 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -0700933 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000934 CookiesAuthenticatorMockFactory(same_cookie='same_cred'))
tandrii16e0b4e2016-06-07 10:34:28 -0700935 self.mock(git_cl._GerritChangelistImpl, '_GerritCommitMsgHookCheck',
936 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -0700937 self.mock(git_cl.gclient_utils, 'RunEditor',
938 lambda *_, **__: self._mocked_call(['RunEditor']))
939 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
940
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000941 self.calls = self._gerrit_base_calls(issue=issue)
luqui@chromium.org609f3952015-05-04 22:47:04 +0000942 self.calls += self._gerrit_upload_calls(
943 description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700944 squash_mode=squash_mode,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000945 expected_upstream_ref=expected_upstream_ref,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000946 ref_suffix=ref_suffix, notify=notify,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000947 post_amend_description=post_amend_description,
948 issue=issue)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000949 # Uncomment when debugging.
950 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000951 git_cl.main(['upload'] + upload_args)
952
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000953 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -0700954 self._run_gerrit_upload_test(
955 ['--no-squash'],
956 'desc\n\nBUG=\n',
957 [],
958 squash=False,
959 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
960
961 def test_gerrit_upload_without_change_id_override_nosquash(self):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000962 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000963 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000964 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +0000965 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000966 [],
tandriia60502f2016-06-20 02:01:53 -0700967 squash=False,
968 squash_mode='override_nosquash',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000969 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000970
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000971 def test_gerrit_no_reviewer(self):
972 self._run_gerrit_upload_test(
973 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000974 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700975 [],
976 squash=False,
977 squash_mode='override_nosquash')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000978
tandriieefe8322016-08-17 10:12:24 -0700979 def test_gerrit_patch_bad_chars(self):
980 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000981 self._run_gerrit_upload_test(
tandriieefe8322016-08-17 10:12:24 -0700982 ['-f', '-t', 'Don\'t put bad cha,.rs'],
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000983 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandriia60502f2016-06-20 02:01:53 -0700984 squash=False,
985 squash_mode='override_nosquash',
tandriieefe8322016-08-17 10:12:24 -0700986 ref_suffix='%m=Dont_put_bad_chars')
987 self.assertIn(
988 'WARNING: Patchset title may only contain alphanumeric chars '
989 'and spaces. Cleaned up title:\nDont put bad chars\n',
990 git_cl.sys.stdout.getvalue())
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000991
ukai@chromium.orge8077812012-02-03 03:41:46 +0000992 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000993 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000994 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000995 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000996 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -0700997 squash=False,
998 squash_mode='override_nosquash',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000999 notify=True)
ukai@chromium.orge8077812012-02-03 03:41:46 +00001000
1001 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001002 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001003 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001004 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n\n'
1005 'Change-Id: 123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001006 ['reviewer@example.com', 'another@example.com'],
1007 squash=False,
tandrii99a72f22016-08-17 14:33:24 -07001008 squash_mode='override_nosquash',
1009 ref_suffix='%l=Code-Review+1')
tandriia60502f2016-06-20 02:01:53 -07001010
1011 def test_gerrit_upload_squash_first_is_default(self):
1012 # Mock Gerrit CL description to indicate the first upload.
1013 self.mock(git_cl.Changelist, 'GetDescription',
1014 lambda *_: None)
1015 self._run_gerrit_upload_test(
1016 [],
1017 'desc\nBUG=\n\nChange-Id: 123456789',
1018 [],
1019 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001020
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001021 def test_gerrit_upload_squash_first(self):
1022 # Mock Gerrit CL description to indicate the first upload.
1023 self.mock(git_cl.Changelist, 'GetDescription',
1024 lambda *_: None)
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001025 self._run_gerrit_upload_test(
1026 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001027 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001028 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001029 squash=True,
1030 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001031
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001032 def test_gerrit_upload_squash_reupload(self):
1033 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1034 # Mock Gerrit CL description to indicate re-upload.
1035 self.mock(git_cl.Changelist, 'GetDescription',
1036 lambda *args: description)
1037 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
1038 lambda *args: 1)
1039 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1040 lambda *args: {'change_id': '123456789'})
1041 self._run_gerrit_upload_test(
1042 ['--squash'],
1043 description,
1044 [],
1045 squash=True,
1046 expected_upstream_ref='origin/master',
1047 issue=123456)
1048
rmistry@google.com2dd99862015-06-22 12:22:18 +00001049 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001050 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001051 def mock_run_git(*args, **_kwargs):
1052 if args[0] == ['for-each-ref',
1053 '--format=%(refname:short) %(upstream:short)',
1054 'refs/heads']:
1055 # Create a local branch dependency tree that looks like this:
1056 # test1 -> test2 -> test3 -> test4 -> test5
1057 # -> test3.1
1058 # test6 -> test0
1059 branch_deps = [
1060 'test2 test1', # test1 -> test2
1061 'test3 test2', # test2 -> test3
1062 'test3.1 test2', # test2 -> test3.1
1063 'test4 test3', # test3 -> test4
1064 'test5 test4', # test4 -> test5
1065 'test6 test0', # test0 -> test6
1066 'test7', # test7
1067 ]
1068 return '\n'.join(branch_deps)
1069 self.mock(git_cl, 'RunGit', mock_run_git)
1070
1071 class RecordCalls:
1072 times_called = 0
1073 record_calls = RecordCalls()
1074 def mock_CMDupload(*args, **_kwargs):
1075 record_calls.times_called += 1
1076 return 0
1077 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1078
1079 self.calls = [
1080 (('[Press enter to continue or ctrl-C to quit]',), ''),
1081 ]
1082
1083 class MockChangelist():
1084 def __init__(self):
1085 pass
1086 def GetBranch(self):
1087 return 'test1'
1088 def GetIssue(self):
1089 return '123'
1090 def GetPatchset(self):
1091 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001092 def IsGerrit(self):
1093 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001094
1095 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1096 # CMDupload should have been called 5 times because of 5 dependent branches.
1097 self.assertEquals(5, record_calls.times_called)
1098 self.assertEquals(0, ret)
1099
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001100 def test_gerrit_change_id(self):
1101 self.calls = [
1102 ((['git', 'write-tree'], ),
1103 'hashtree'),
1104 ((['git', 'rev-parse', 'HEAD~0'], ),
1105 'branch-parent'),
1106 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1107 'A B <a@b.org> 1456848326 +0100'),
1108 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1109 'C D <c@d.org> 1456858326 +0100'),
1110 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1111 'hashchange'),
1112 ]
1113 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1114 self.assertEqual(change_id, 'Ihashchange')
1115
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001116 def test_desecription_append_footer(self):
1117 for init_desc, footer_line, expected_desc in [
1118 # Use unique desc first lines for easy test failure identification.
1119 ('foo', 'R=one', 'foo\n\nR=one'),
1120 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1121 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1122 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1123 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1124 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1125 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1126 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1127 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1128 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1129 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1130 ]:
1131 desc = git_cl.ChangeDescription(init_desc)
1132 desc.append_footer(footer_line)
1133 self.assertEqual(desc.description, expected_desc)
1134
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001135 def test_update_reviewers(self):
1136 data = [
1137 ('foo', [], 'foo'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001138 ('foo\nR=xx', [], 'foo\nR=xx'),
1139 ('foo\nTBR=xx', [], 'foo\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001140 ('foo', ['a@c'], 'foo\n\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001141 ('foo\nR=xx', ['a@c'], 'foo\n\nR=a@c, xx'),
1142 ('foo\nTBR=xx', ['a@c'], 'foo\n\nR=a@c\nTBR=xx'),
1143 ('foo\nTBR=xx\nR=yy', ['a@c'], 'foo\n\nR=a@c, yy\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001144 ('foo\nBUG=', ['a@c'], 'foo\nBUG=\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001145 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], 'foo\n\nR=a@c, xx, bar\nTBR=yy'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001146 ('foo', ['a@c', 'b@c'], 'foo\n\nR=a@c, b@c'),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001147 ('foo\nBar\n\nR=\nBUG=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1148 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1149 # Same as the line before, but full of whitespaces.
1150 (
1151 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'],
1152 'foo\nBar\n\nR=c@c\n BUG =',
1153 ),
1154 # Whitespaces aren't interpreted as new lines.
1155 ('foo BUG=allo R=joe ', ['c@c'], 'foo BUG=allo R=joe\n\nR=c@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001156 ]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001157 expected = [i[2] for i in data]
1158 actual = []
1159 for orig, reviewers, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001160 obj = git_cl.ChangeDescription(orig)
1161 obj.update_reviewers(reviewers)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001162 actual.append(obj.description)
1163 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001164
wittman@chromium.org455dc922015-01-26 20:15:50 +00001165 def test_get_target_ref(self):
1166 # Check remote or remote branch not present.
1167 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master', None))
1168 self.assertEqual(None, git_cl.GetTargetRef(None,
1169 'refs/remotes/origin/master',
1170 'master', None))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001171
wittman@chromium.org455dc922015-01-26 20:15:50 +00001172 # Check default target refs for branches.
1173 self.assertEqual('refs/heads/master',
1174 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1175 None, None))
1176 self.assertEqual('refs/heads/master',
1177 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
1178 None, None))
1179 self.assertEqual('refs/heads/master',
1180 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
1181 None, None))
1182 self.assertEqual('refs/branch-heads/123',
1183 git_cl.GetTargetRef('origin',
1184 'refs/remotes/branch-heads/123',
1185 None, None))
1186 self.assertEqual('refs/diff/test',
1187 git_cl.GetTargetRef('origin',
1188 'refs/remotes/origin/refs/diff/test',
1189 None, None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001190 self.assertEqual('refs/heads/chrome/m42',
1191 git_cl.GetTargetRef('origin',
1192 'refs/remotes/origin/chrome/m42',
1193 None, None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001194
1195 # Check target refs for user-specified target branch.
1196 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1197 'refs/remotes/branch-heads/123'):
1198 self.assertEqual('refs/branch-heads/123',
1199 git_cl.GetTargetRef('origin',
1200 'refs/remotes/origin/master',
1201 branch, None))
1202 for branch in ('origin/master', 'remotes/origin/master',
1203 'refs/remotes/origin/master'):
1204 self.assertEqual('refs/heads/master',
1205 git_cl.GetTargetRef('origin',
1206 'refs/remotes/branch-heads/123',
1207 branch, None))
1208 for branch in ('master', 'heads/master', 'refs/heads/master'):
1209 self.assertEqual('refs/heads/master',
1210 git_cl.GetTargetRef('origin',
1211 'refs/remotes/branch-heads/123',
1212 branch, None))
1213
1214 # Check target refs for pending prefix.
1215 self.assertEqual('prefix/heads/master',
1216 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1217 None, 'prefix/'))
1218
wychen@chromium.orga872e752015-04-28 23:42:18 +00001219 def test_patch_when_dirty(self):
1220 # Patch when local tree is dirty
1221 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1222 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1223
1224 def test_diff_when_dirty(self):
1225 # Do 'git cl diff' when local tree is dirty
1226 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1227 self.assertNotEqual(git_cl.main(['diff']), 0)
1228
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001229 def _patch_common(self, is_gerrit=False, force_codereview=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001230 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001231 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1232 lambda x: '60001')
1233 self.mock(git_cl._RietveldChangelistImpl, 'GetPatchSetDiff',
1234 lambda *args: None)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001235 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1236 lambda *args: {
1237 'current_revision': '7777777777',
1238 'revisions': {
1239 '1111111111': {
1240 '_number': 1,
1241 'fetch': {'http': {
1242 'url': 'https://chromium.googlesource.com/my/repo',
1243 'ref': 'refs/changes/56/123456/1',
1244 }},
1245 },
1246 '7777777777': {
1247 '_number': 7,
1248 'fetch': {'http': {
1249 'url': 'https://chromium.googlesource.com/my/repo',
1250 'ref': 'refs/changes/56/123456/7',
1251 }},
1252 },
1253 },
1254 })
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001255 self.mock(git_cl.Changelist, 'GetDescription',
1256 lambda *args: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001257 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1258
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001259 self.calls = self.calls or []
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001260 if not force_codereview:
1261 # These calls detect codereview to use.
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001262 self.calls += [
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001263 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1264 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
1265 ((['git', 'config', 'branch.master.gerritissue'],), ''),
1266 ((['git', 'config', 'rietveld.autoupdate'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001267 ]
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001268
1269 if is_gerrit:
1270 if not force_codereview:
1271 self.calls += [
1272 ((['git', 'config', 'gerrit.host'],), 'true'),
1273 ]
1274 else:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001275 self.calls += [
1276 ((['git', 'config', 'gerrit.host'],), ''),
1277 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
1278 ((['git', 'rev-parse', '--show-cdup'],), ''),
1279 ((['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'],), ''),
1280 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001281
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001282 def _common_patch_successful(self):
wychen@chromium.orga872e752015-04-28 23:42:18 +00001283 self._patch_common()
1284 self.calls += [
1285 ((['git', 'apply', '--index', '-p0', '--3way'],), ''),
1286 ((['git', 'commit', '-m',
wychen@chromium.org5b3bebb2015-05-28 21:41:43 +00001287 'Description\n\n' +
wychen@chromium.orga872e752015-04-28 23:42:18 +00001288 'patch from issue 123456 at patchset 60001 ' +
1289 '(http://crrev.com/123456#ps60001)'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001290 ((['git', 'config', 'branch.master.rietveldissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001291 ((['git', 'config', 'branch.master.rietveldserver'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001292 ((['git', 'config', 'branch.master.rietveldserver',
1293 'https://codereview.example.com'],), ''),
1294 ((['git', 'config', 'branch.master.rietveldpatchset', '60001'],), ''),
wychen@chromium.orga872e752015-04-28 23:42:18 +00001295 ]
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001296
1297 def test_patch_successful(self):
1298 self._common_patch_successful()
wychen@chromium.orga872e752015-04-28 23:42:18 +00001299 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1300
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001301 def test_patch_successful_new_branch(self):
1302 self.calls = [ ((['git', 'new-branch', 'master'],), ''), ]
1303 self._common_patch_successful()
1304 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1305
wychen@chromium.orga872e752015-04-28 23:42:18 +00001306 def test_patch_conflict(self):
1307 self._patch_common()
1308 self.calls += [
1309 ((['git', 'apply', '--index', '-p0', '--3way'],), '',
1310 subprocess2.CalledProcessError(1, '', '', '', '')),
1311 ]
1312 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
wittman@chromium.org455dc922015-01-26 20:15:50 +00001313
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001314 def test_gerrit_patch_successful(self):
1315 self._patch_common(is_gerrit=True)
1316 self.calls += [
1317 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1318 'refs/changes/56/123456/7'],), ''),
1319 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1320 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1321 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1322 ((['git', 'config', 'branch.master.merge'],), 'master'),
1323 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1324 ((['git', 'config', 'remote.origin.url'],),
1325 'https://chromium.googlesource.com/my/repo'),
1326 ((['git', 'config', 'branch.master.gerritserver',
1327 'https://chromium-review.googlesource.com'],), ''),
1328 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1329 ]
1330 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1331
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001332 def test_patch_force_codereview(self):
1333 self._patch_common(is_gerrit=True, force_codereview=True)
1334 self.calls += [
1335 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1336 'refs/changes/56/123456/7'],), ''),
1337 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1338 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1339 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1340 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1341 ((['git', 'config', 'branch.master.merge'],), 'master'),
1342 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1343 ((['git', 'config', 'remote.origin.url'],),
1344 'https://chromium.googlesource.com/my/repo'),
1345 ((['git', 'config', 'branch.master.gerritserver',
1346 'https://chromium-review.googlesource.com'],), ''),
1347 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1348 ]
1349 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456']), 0)
1350
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001351 def test_gerrit_patch_url_successful(self):
1352 self._patch_common(is_gerrit=True)
1353 self.calls += [
1354 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1355 'refs/changes/56/123456/1'],), ''),
1356 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1357 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1358 ((['git', 'config', 'branch.master.gerritserver',
1359 'https://chromium-review.googlesource.com'],), ''),
1360 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1361 ]
1362 self.assertEqual(git_cl.main(
1363 ['patch', 'https://chromium-review.googlesource.com/#/c/123456/1']), 0)
1364
1365 def test_gerrit_patch_conflict(self):
1366 self._patch_common(is_gerrit=True)
1367 self.mock(git_cl, 'DieWithError',
1368 lambda msg: self._mocked_call(['DieWithError', msg]))
1369 class SystemExitMock(Exception):
1370 pass
1371 self.calls += [
1372 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1373 'refs/changes/56/123456/1'],), ''),
1374 ((['git', 'cherry-pick', 'FETCH_HEAD'],),
1375 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1376 ((['DieWithError', 'git cherry-pick FETCH_HEAD" failed.\n'],),
1377 '', SystemExitMock()),
1378 ]
1379 with self.assertRaises(SystemExitMock):
1380 git_cl.main(['patch',
1381 'https://chromium-review.googlesource.com/#/c/123456/1'])
1382
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001383 def _checkout_calls(self):
1384 return [
1385 ((['git', 'config', '--local', '--get-regexp',
1386 'branch\\..*\\.rietveldissue'], ),
1387 ('branch.retrying.rietveldissue 1111111111\n'
1388 'branch.some-fix.rietveldissue 2222222222\n')),
1389 ((['git', 'config', '--local', '--get-regexp',
1390 'branch\\..*\\.gerritissue'], ),
1391 ('branch.ger-branch.gerritissue 123456\n'
1392 'branch.gbranch654.gerritissue 654321\n')),
1393 ]
1394
1395 def test_checkout_gerrit(self):
1396 """Tests git cl checkout <issue>."""
1397 self.calls = self._checkout_calls()
1398 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1399 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1400
1401 def test_checkout_rietveld(self):
1402 """Tests git cl checkout <issue>."""
1403 self.calls = self._checkout_calls()
1404 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1405 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1406
1407 def test_checkout_not_found(self):
1408 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001409 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001410 self.calls = self._checkout_calls()
1411 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1412
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001413 def test_checkout_no_branch_issues(self):
1414 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001415 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001416 self.calls = [
1417 ((['git', 'config', '--local', '--get-regexp',
1418 'branch\\..*\\.rietveldissue'], ), '',
1419 subprocess2.CalledProcessError(1, '', '', '', '')),
1420 ((['git', 'config', '--local', '--get-regexp',
1421 'branch\\..*\\.gerritissue'], ), '',
1422 subprocess2.CalledProcessError(1, '', '', '', '')),
1423
1424 ]
1425 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1426
tandrii@chromium.org28253532016-04-14 13:46:56 +00001427 def _test_gerrit_ensure_authenticated_common(self, auth,
1428 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001429 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1430 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1431 self.mock(git_cl, 'DieWithError',
1432 lambda msg: self._mocked_call(['DieWithError', msg]))
1433 self.mock(git_cl, 'ask_for_data',
1434 lambda msg: self._mocked_call(['ask_for_data', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001435 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001436 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00001437 cl.branch = 'master'
1438 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001439 cl.lookedup_issue = True
1440 return cl
1441
1442 def test_gerrit_ensure_authenticated_missing(self):
1443 cl = self._test_gerrit_ensure_authenticated_common(auth={
1444 'chromium.googlesource.com': 'git is ok, but gerrit one is missing',
1445 })
1446 self.calls.append(
1447 ((['DieWithError',
1448 'Credentials for the following hosts are required:\n'
1449 ' chromium-review.googlesource.com\n'
1450 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1451 'You can (re)generate your credentails by visiting '
1452 'https://chromium-review.googlesource.com/new-password'],), ''),)
1453 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1454
1455 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001456 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001457 cl = self._test_gerrit_ensure_authenticated_common(auth={
1458 'chromium.googlesource.com': 'one',
1459 'chromium-review.googlesource.com': 'other',
1460 })
1461 self.calls.append(
1462 ((['ask_for_data', 'If you know what you are doing, '
1463 'press Enter to continue, Ctrl+C to abort.'],), ''))
1464 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1465
1466 def test_gerrit_ensure_authenticated_ok(self):
1467 cl = self._test_gerrit_ensure_authenticated_common(auth={
1468 'chromium.googlesource.com': 'same',
1469 'chromium-review.googlesource.com': 'same',
1470 })
1471 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1472
tandrii@chromium.org28253532016-04-14 13:46:56 +00001473 def test_gerrit_ensure_authenticated_skipped(self):
1474 cl = self._test_gerrit_ensure_authenticated_common(
1475 auth={}, skip_auth_check=True)
1476 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1477
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001478 def test_cmd_set_commit_rietveld(self):
tandrii4d843592016-07-27 08:22:56 -07001479 self.mock(git_cl._RietveldChangelistImpl, 'SetFlags',
1480 lambda _, v: self._mocked_call(['SetFlags', v]))
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001481 self.calls = [
1482 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1483 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
1484 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1485 ((['git', 'config', 'rietveld.server'],), ''),
1486 ((['git', 'config', 'rietveld.server'],), ''),
1487 ((['git', 'config', 'branch.feature.rietveldserver'],),
1488 'https://codereview.chromium.org'),
tandrii4d843592016-07-27 08:22:56 -07001489 ((['SetFlags', {'commit': '1', 'cq_dry_run': '0'}], ), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001490 ]
1491 self.assertEqual(0, git_cl.main(['set-commit']))
1492
tandriid9e5ce52016-07-13 02:32:59 -07001493 def _cmd_set_commit_gerrit_common(self, vote):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001494 self.mock(git_cl.gerrit_util, 'SetReview',
1495 lambda h, i, labels: self._mocked_call(
1496 ['SetReview', h, i, labels]))
1497 self.calls = [
1498 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1499 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1500 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1501 ((['git', 'config', 'branch.feature.gerritserver'],),
1502 'https://chromium-review.googlesource.com'),
1503 ((['SetReview', 'chromium-review.googlesource.com', 123,
tandriid9e5ce52016-07-13 02:32:59 -07001504 {'Commit-Queue': vote}],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001505 ]
tandriid9e5ce52016-07-13 02:32:59 -07001506
1507 def test_cmd_set_commit_gerrit_clear(self):
1508 self._cmd_set_commit_gerrit_common(0)
1509 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
1510
1511 def test_cmd_set_commit_gerrit_dry(self):
1512 self._cmd_set_commit_gerrit_common(1)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001513 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1514
tandriid9e5ce52016-07-13 02:32:59 -07001515 def test_cmd_set_commit_gerrit(self):
1516 self._cmd_set_commit_gerrit_common(2)
1517 self.assertEqual(0, git_cl.main(['set-commit']))
1518
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001519 def test_description_display(self):
1520 out = StringIO.StringIO()
1521 self.mock(git_cl.sys, 'stdout', out)
1522
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001523 self.mock(git_cl, 'Changelist', ChangelistMock)
1524 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001525
1526 self.assertEqual(0, git_cl.main(['description', '-d']))
1527 self.assertEqual('foo\n', out.getvalue())
1528
1529 def test_description_rietveld(self):
1530 out = StringIO.StringIO()
1531 self.mock(git_cl.sys, 'stdout', out)
martiniss6eda05f2016-06-30 10:18:35 -07001532 self.mock(git_cl.Changelist, 'GetDescription', lambda *args: 'foobar')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001533
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001534 self.assertEqual(0, git_cl.main([
1535 'description', 'https://code.review.org/123123', '-d', '--rietveld']))
1536 self.assertEqual('foobar\n', out.getvalue())
1537
iannucci3c972b92016-08-17 13:24:10 -07001538 def test_StatusFieldOverrideIssueMissingArgs(self):
1539 out = StringIO.StringIO()
1540 self.mock(git_cl.sys, 'stderr', out)
1541
1542 try:
1543 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
1544 except SystemExit as ex:
1545 self.assertEqual(ex.code, 2)
1546 self.assertRegexpMatches(out.getvalue(), r'--issue may only be specified')
1547
1548 out = StringIO.StringIO()
1549 self.mock(git_cl.sys, 'stderr', out)
1550
1551 try:
1552 self.assertEqual(git_cl.main(['status', '--issue', '1', '--rietveld']), 0)
1553 except SystemExit as ex:
1554 self.assertEqual(ex.code, 2)
1555 self.assertRegexpMatches(out.getvalue(), r'--issue may only be specified')
1556
1557 def test_StatusFieldOverrideIssue(self):
1558 out = StringIO.StringIO()
1559 self.mock(git_cl.sys, 'stdout', out)
1560
1561 def assertIssue(cl_self, *_args):
1562 self.assertEquals(cl_self.issue, 1)
1563 return 'foobar'
1564
1565 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
1566 self.calls = [
1567 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1568 ((['git', 'config', 'rietveld.server'],), ''),
1569 ((['git', 'config', 'rietveld.server'],), ''),
1570 ]
1571 git_cl.main(['status', '--issue', '1', '--rietveld', '--field', 'desc'])
1572 self.assertEqual(out.getvalue(), 'foobar\n')
1573
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001574 def test_description_gerrit(self):
1575 out = StringIO.StringIO()
1576 self.mock(git_cl.sys, 'stdout', out)
martiniss6eda05f2016-06-30 10:18:35 -07001577 self.mock(git_cl.Changelist, 'GetDescription', lambda *args: 'foobar')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001578
1579 self.assertEqual(0, git_cl.main([
1580 'description', 'https://code.review.org/123123', '-d', '--gerrit']))
1581 self.assertEqual('foobar\n', out.getvalue())
1582
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001583 def test_description_set_raw(self):
1584 out = StringIO.StringIO()
1585 self.mock(git_cl.sys, 'stdout', out)
1586
1587 self.mock(git_cl, 'Changelist', ChangelistMock)
1588 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
1589
1590 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1591 self.assertEqual('hihi', ChangelistMock.desc)
1592
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001593 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001594 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001595
1596 def RunEditor(desc, _, **kwargs):
1597 self.assertEquals(
1598 '# Enter a description of the change.\n'
1599 '# This will be displayed on the codereview site.\n'
1600 '# The first line will also be used as the subject of the review.\n'
1601 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001602 '--------------------\n'
1603 'Some.\n\nBUG=\n\nChange-Id: xxx',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001604 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001605 # Simulate user changing something.
1606 return 'Some.\n\nBUG=123\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001607
1608 def UpdateDescriptionRemote(_, desc):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001609 self.assertEquals(desc, 'Some.\n\nBUG=123\n\nChange-Id: xxx')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001610
1611 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1612 self.mock(git_cl.Changelist, 'GetDescription',
1613 lambda *args: current_desc)
1614 self.mock(git_cl._GerritChangelistImpl, 'UpdateDescriptionRemote',
1615 UpdateDescriptionRemote)
1616 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
1617
1618 self.calls = [
1619 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1620 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1621 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1622 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
1623 ((['git', 'config', 'core.editor'],), 'vi'),
1624 ]
1625 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
1626
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001627 def test_description_set_stdin(self):
1628 out = StringIO.StringIO()
1629 self.mock(git_cl.sys, 'stdout', out)
1630
1631 self.mock(git_cl, 'Changelist', ChangelistMock)
1632 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
1633
1634 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1635 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1636
kmarshall3bff56b2016-06-06 18:31:47 -07001637 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07001638 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1639
kmarshall3bff56b2016-06-06 18:31:47 -07001640 self.calls = \
1641 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1642 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1643 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1644 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1645 ((['git', 'config', 'rietveld.server'],), ''),
1646 ((['git', 'config', 'rietveld.server'],), ''),
1647 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
1648 ((['git', 'config', 'rietveld.server'],), ''),
1649 ((['git', 'config', 'rietveld.server'],), ''),
1650 ((['git', 'config', 'branch.bar.rietveldissue'],), ''),
1651 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
1652 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1653 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
1654 ((['git', 'branch', '-D', 'foo'],), '')]
1655
1656 class MockChangelist():
1657 def __init__(self, branch, issue):
1658 self.branch = branch
1659 self.issue = issue
1660 def GetBranch(self):
1661 return self.branch
1662 def GetIssue(self):
1663 return self.issue
1664
1665 self.mock(git_cl, 'get_cl_statuses',
1666 lambda branches, fine_grained, max_processes:
1667 [(MockChangelist('master', 1), 'open'),
1668 (MockChangelist('foo', 456), 'closed'),
1669 (MockChangelist('bar', 789), 'open')])
1670
1671 self.assertEqual(0, git_cl.main(['archive', '-f']))
1672
1673 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07001674 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
kmarshall3bff56b2016-06-06 18:31:47 -07001675 self.calls = \
1676 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1677 'refs/heads/master'),
1678 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1679 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1680 ((['git', 'config', 'rietveld.server'],), ''),
1681 ((['git', 'config', 'rietveld.server'],), ''),
1682 ((['git', 'symbolic-ref', 'HEAD'],), 'master')]
1683
1684 class MockChangelist():
1685 def __init__(self, branch, issue):
1686 self.branch = branch
1687 self.issue = issue
1688 def GetBranch(self):
1689 return self.branch
1690 def GetIssue(self):
1691 return self.issue
1692
1693 self.mock(git_cl, 'get_cl_statuses',
1694 lambda branches, fine_grained, max_processes:
1695 [(MockChangelist('master', 1), 'closed')])
1696
1697 self.assertEqual(1, git_cl.main(['archive', '-f']))
1698
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00001699 def test_cmd_issue_erase_existing(self):
1700 out = StringIO.StringIO()
1701 self.mock(git_cl.sys, 'stdout', out)
1702 self.calls = [
1703 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1704 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1705 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1706 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
1707 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
1708 # Let this command raise exception (retcode=1) - it should be ignored.
1709 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
1710 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1711 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
1712 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
1713 ''),
1714 ]
1715 self.assertEqual(0, git_cl.main(['issue', '0']))
1716
tandrii9de9ec62016-07-13 03:01:59 -07001717 def test_git_cl_try_default(self):
1718 self.mock(git_cl.Changelist, 'GetChange',
1719 lambda _, *a: (
1720 self._mocked_call(['GetChange']+list(a))))
1721 self.mock(git_cl.presubmit_support, 'DoGetTryMasters',
1722 lambda *_, **__: (
1723 self._mocked_call(['DoGetTryMasters'])))
1724 self.mock(git_cl.presubmit_support, 'DoGetTrySlaves',
1725 lambda *_, **__: (
1726 self._mocked_call(['DoGetTrySlaves'])))
1727 self.mock(git_cl._RietveldChangelistImpl, 'SetCQState',
1728 lambda _, s: self._mocked_call(['SetCQState', s]))
1729 self.calls = [
1730 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1731 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
1732 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1733 ((['git', 'config', 'rietveld.server'],),
1734 'https://codereview.chromium.org'),
1735 ((['git', 'config', 'branch.feature.rietveldserver'],), ''),
1736 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
1737 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
1738 ((['get_or_create_merge_base', 'feature', 'feature'],),
1739 'fake_ancestor_sha'),
1740 ((['GetChange', 'fake_ancestor_sha', None], ),
1741 git_cl.presubmit_support.GitChange(
1742 '', '', '', '', '', '', '', '')),
1743 ((['git', 'rev-parse', '--show-cdup'],), '../'),
1744 ((['DoGetTryMasters'], ), None),
1745 ((['DoGetTrySlaves'], ), None),
1746 ((['SetCQState', git_cl._CQState.DRY_RUN], ), None),
1747 ]
1748 out = StringIO.StringIO()
1749 self.mock(git_cl.sys, 'stdout', out)
1750 self.assertEqual(0, git_cl.main(['try']))
1751 self.assertEqual(
1752 out.getvalue(),
1753 'scheduled CQ Dry Run on https://codereview.chromium.org/123\n')
1754
tandrii16e0b4e2016-06-07 10:34:28 -07001755 def _common_GerritCommitMsgHookCheck(self):
1756 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1757 self.mock(git_cl.os.path, 'abspath',
1758 lambda path: self._mocked_call(['abspath', path]))
1759 self.mock(git_cl.os.path, 'exists',
1760 lambda path: self._mocked_call(['exists', path]))
1761 self.mock(git_cl.gclient_utils, 'FileRead',
1762 lambda path: self._mocked_call(['FileRead', path]))
1763 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
1764 lambda path: self._mocked_call(['rm_file_or_tree', path]))
1765 self.calls = [
1766 ((['git', 'rev-parse', '--show-cdup'],), '../'),
1767 ((['abspath', '../'],), '/abs/git_repo_root'),
1768 ]
1769 return git_cl.Changelist(codereview='gerrit', issue=123)
1770
1771 def test_GerritCommitMsgHookCheck_custom_hook(self):
1772 cl = self._common_GerritCommitMsgHookCheck()
1773 self.calls += [
1774 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1775 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1776 '#!/bin/sh\necho "custom hook"')
1777 ]
1778 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1779
1780 def test_GerritCommitMsgHookCheck_not_exists(self):
1781 cl = self._common_GerritCommitMsgHookCheck()
1782 self.calls += [
1783 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
1784 ]
1785 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1786
1787 def test_GerritCommitMsgHookCheck(self):
1788 cl = self._common_GerritCommitMsgHookCheck()
1789 self.calls += [
1790 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1791 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1792 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
1793 (('Do you want to remove it now? [Yes/No]',), 'Yes'),
1794 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1795 ''),
1796 ]
1797 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1798
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001799
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001800if __name__ == '__main__':
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001801 git_cl.logging.basicConfig(
1802 level=git_cl.logging.DEBUG if '-v' in sys.argv else git_cl.logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001803 unittest.main()