blob: ed24c84cae0ffa203256befc590af4fd423bedcb [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
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000024class PresubmitMock(object):
25 def __init__(self, *args, **kwargs):
26 self.reviewers = []
27 @staticmethod
28 def should_continue():
29 return True
30
31
32class RietveldMock(object):
33 def __init__(self, *args, **kwargs):
34 pass
maruel@chromium.org78936cb2013-04-11 00:17:52 +000035
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000036 @staticmethod
37 def get_description(issue):
38 return 'Issue: %d' % issue
39
maruel@chromium.org78936cb2013-04-11 00:17:52 +000040 @staticmethod
41 def get_issue_properties(_issue, _messages):
42 return {
43 'reviewers': ['joe@chromium.org', 'john@chromium.org'],
44 'messages': [
45 {
46 'approval': True,
47 'sender': 'john@chromium.org',
48 },
49 ],
50 }
51
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000052
53class WatchlistsMock(object):
54 def __init__(self, _):
55 pass
56 @staticmethod
57 def GetWatchersForPaths(_):
58 return ['joe@example.com']
59
60
ukai@chromium.org78c4b982012-02-14 02:20:26 +000061class CodereviewSettingsFileMock(object):
62 def __init__(self):
63 pass
64 # pylint: disable=R0201
65 def read(self):
66 return ("CODE_REVIEW_SERVER: gerrit.chromium.org\n" +
andybons@chromium.org11f46eb2016-02-02 19:26:51 +000067 "GERRIT_HOST: True\n")
ukai@chromium.org78c4b982012-02-14 02:20:26 +000068
69
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +000070class AuthenticatorMock(object):
71 def __init__(self, *_args):
72 pass
73 def has_cached_credentials(self):
74 return True
75
76
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +000077def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_cookie=False):
78 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
79
80 Usage:
81 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
82 CookiesAuthenticatorMockFactory({'host1': 'cookie1'}))
83
84 OR
85 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
86 CookiesAuthenticatorMockFactory(cookie='cookie'))
87 """
88 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
89 def __init__(self): # pylint: disable=W0231
90 # Intentionally not calling super() because it reads actual cookie files.
91 pass
92 @classmethod
93 def get_gitcookies_path(cls):
94 return '~/.gitcookies'
95 @classmethod
96 def get_netrc_path(cls):
97 return '~/.netrc'
98 def get_auth_header(self, host):
99 if same_cookie:
100 return same_cookie
101 return (hosts_with_creds or {}).get(host)
102 return CookiesAuthenticatorMock
103
104
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000105class TestGitClBasic(unittest.TestCase):
106 def _test_ParseIssueUrl(self, func, url, issue, patchset, hostname, fail):
107 parsed = urlparse.urlparse(url)
108 result = func(parsed)
109 if fail:
110 self.assertIsNone(result)
111 return None
112 self.assertIsNotNone(result)
113 self.assertEqual(result.issue, issue)
114 self.assertEqual(result.patchset, patchset)
115 self.assertEqual(result.hostname, hostname)
116 return result
117
118 def test_ParseIssueURL_rietveld(self):
119 def test(url, issue=None, patchset=None, hostname=None, patch_url=None,
120 fail=None):
121 result = self._test_ParseIssueUrl(
122 git_cl._RietveldChangelistImpl.ParseIssueURL,
123 url, issue, patchset, hostname, fail)
124 if not fail:
125 self.assertEqual(result.patch_url, patch_url)
126
127 test('http://codereview.chromium.org/123',
128 123, None, 'codereview.chromium.org')
129 test('https://codereview.chromium.org/123',
130 123, None, 'codereview.chromium.org')
131 test('https://codereview.chromium.org/123/',
132 123, None, 'codereview.chromium.org')
133 test('https://codereview.chromium.org/123/whatever',
134 123, None, 'codereview.chromium.org')
135 test('http://codereview.chromium.org/download/issue123_4.diff',
136 123, 4, 'codereview.chromium.org',
137 patch_url='https://codereview.chromium.org/download/issue123_4.diff')
138 # This looks like bad Gerrit, but is actually valid Rietveld.
139 test('https://chrome-review.source.com/123/4/',
140 123, None, 'chrome-review.source.com')
141
142 test('https://codereview.chromium.org/deadbeaf', fail=True)
143 test('https://codereview.chromium.org/api/123', fail=True)
144 test('bad://codereview.chromium.org/123', fail=True)
145 test('http://codereview.chromium.org/download/issue123_4.diffff', fail=True)
146
147 def test_ParseIssueURL_gerrit(self):
148 def test(url, issue=None, patchset=None, hostname=None, fail=None):
149 self._test_ParseIssueUrl(
150 git_cl._GerritChangelistImpl.ParseIssueURL,
151 url, issue, patchset, hostname, fail)
152
153 test('http://chrome-review.source.com/c/123',
154 123, None, 'chrome-review.source.com')
155 test('https://chrome-review.source.com/c/123/',
156 123, None, 'chrome-review.source.com')
157 test('https://chrome-review.source.com/c/123/4',
158 123, 4, 'chrome-review.source.com')
159 test('https://chrome-review.source.com/#/c/123/4',
160 123, 4, 'chrome-review.source.com')
161 test('https://chrome-review.source.com/c/123/4',
162 123, 4, 'chrome-review.source.com')
163 test('https://chrome-review.source.com/123',
164 123, None, 'chrome-review.source.com')
165 test('https://chrome-review.source.com/123/4',
166 123, 4, 'chrome-review.source.com')
167
168 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
169 test('https://chrome-review.source.com/c/abc/', fail=True)
170 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
171
172 def test_ParseIssueNumberArgument(self):
173 def test(arg, issue=None, patchset=None, hostname=None, fail=False):
174 result = git_cl.ParseIssueNumberArgument(arg)
175 self.assertIsNotNone(result)
176 if fail:
177 self.assertFalse(result.valid)
178 else:
179 self.assertEqual(result.issue, issue)
180 self.assertEqual(result.patchset, patchset)
181 self.assertEqual(result.hostname, hostname)
182
183 test('123', 123)
184 test('', fail=True)
185 test('abc', fail=True)
186 test('123/1', fail=True)
187 test('123a', fail=True)
188 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
189 # Rietveld.
190 test('https://codereview.source.com/123',
191 123, None, 'codereview.source.com')
192 test('https://codereview.source.com/www123', fail=True)
193 # Gerrrit.
194 test('https://chrome-review.source.com/c/123/4',
195 123, 4, 'chrome-review.source.com')
196 test('https://chrome-review.source.com/bad/123/4', fail=True)
197
198
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000199class TestGitCl(TestCase):
200 def setUp(self):
201 super(TestGitCl, self).setUp()
202 self.calls = []
203 self._calls_done = 0
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000204 self.mock(subprocess2, 'call', self._mocked_call)
205 self.mock(subprocess2, 'check_call', self._mocked_call)
206 self.mock(subprocess2, 'check_output', self._mocked_call)
207 self.mock(subprocess2, 'communicate', self._mocked_call)
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000208 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000209 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000210 self.mock(git_common, 'get_or_create_merge_base',
211 lambda *a: (
212 self._mocked_call(['get_or_create_merge_base']+list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000213 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000214 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000215 self.mock(git_cl, 'ask_for_data', self._mocked_call)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000216 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000217 self.mock(git_cl.rietveld, 'Rietveld', RietveldMock)
maruel@chromium.org4bac4b52012-11-27 20:33:52 +0000218 self.mock(git_cl.rietveld, 'CachingRietveld', RietveldMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000219 self.mock(git_cl.upload, 'RealMain', self.fail)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000220 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000221 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000222 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
223 classmethod(lambda _: False))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000224 # It's important to reset settings to not have inter-tests interference.
225 git_cl.settings = None
226
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000227
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000228 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000229 try:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000230 # Note: has_failed returns True if at least 1 test ran so far, current
231 # included, has failed. That means current test may have actually ran
232 # fine, and the check for no leftover calls would be skipped.
wychen@chromium.org445c8962015-04-28 23:30:05 +0000233 if not self.has_failed():
234 self.assertEquals([], self.calls)
235 finally:
236 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000237
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000238 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000239 self.assertTrue(
240 self.calls,
241 '@%d Expected: <Missing> Actual: %r' % (self._calls_done, args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000242 top = self.calls.pop(0)
243 if len(top) > 2 and top[2]:
244 raise top[2]
245 expected_args, result = top
246
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000247 # Also logs otherwise it could get caught in a try/finally and be hard to
248 # diagnose.
249 if expected_args != args:
250 msg = '@%d Expected: %r Actual: %r' % (
251 self._calls_done, expected_args, args)
252 git_cl.logging.error(msg)
253 self.fail(msg)
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000254 self._calls_done += 1
255 return result
256
maruel@chromium.orga3353652011-11-30 14:26:57 +0000257 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000258 def _is_gerrit_calls(cls, gerrit=False):
259 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
260 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
261
262 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000263 def _upload_calls(cls, similarity, find_copies, private):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000264 return (cls._git_base_calls(similarity, find_copies) +
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000265 cls._git_upload_calls(private))
maruel@chromium.orga3353652011-11-30 14:26:57 +0000266
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000267 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000268 def _upload_no_rev_calls(cls, similarity, find_copies):
269 return (cls._git_base_calls(similarity, find_copies) +
270 cls._git_upload_no_rev_calls())
271
272 @classmethod
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000273 def _git_base_calls(cls, similarity, find_copies):
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000274 if similarity is None:
275 similarity = '50'
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000276 similarity_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000277 'branch.master.git-cl-similarity'],), '')
278 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000279 similarity_call = ((['git', 'config', '--int',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000280 'branch.master.git-cl-similarity', similarity],), '')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000281
282 if find_copies is None:
283 find_copies = True
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000284 find_copies_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000285 'branch.master.git-find-copies'],), '')
286 else:
287 val = str(int(find_copies))
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000288 find_copies_call = ((['git', 'config', '--int',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000289 'branch.master.git-find-copies', val],), '')
290
291 if find_copies:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000292 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000293 '--find-copies-harder', '-l100000', '-C'+similarity,
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000294 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000295 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000296 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000297 '-M'+similarity, 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000298
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000299 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000300 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000301 similarity_call,
302 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
303 find_copies_call,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000304 ] + cls._is_gerrit_calls() + [
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000305 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000306 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
307 ((['git', 'config', 'branch.master.gerritissue'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000308 ((['git', 'config', 'rietveld.server'],),
309 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000310 ((['git', 'config', 'branch.master.merge'],), 'master'),
311 ((['git', 'config', 'branch.master.remote'],), 'origin'),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000312 ((['get_or_create_merge_base', 'master', 'master'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000313 'fake_ancestor_sha'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000314 ] + cls._git_sanity_checks('fake_ancestor_sha', 'master') + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000315 ((['git', 'rev-parse', '--show-cdup'],), ''),
316 ((['git', 'rev-parse', 'HEAD'],), '12345'),
317 ((['git', 'diff', '--name-status', '--no-renames', '-r',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000318 'fake_ancestor_sha...', '.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000319 'M\t.gitignore\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000320 ((['git', 'config', 'branch.master.rietveldpatchset'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000321 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000322 ((['git', 'log', '--pretty=format:%s%n%n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000323 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000324 'foo'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000325 ((['git', 'config', 'user.email'],), 'me@example.com'),
iannucci@chromium.org79540052012-10-19 23:15:26 +0000326 stat_call,
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000327 ((['git', 'log', '--pretty=format:%s\n\n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000328 'fake_ancestor_sha..HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000329 'desc\n'),
rmistry@google.com90752582014-01-14 21:04:50 +0000330 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
maruel@chromium.orga3353652011-11-30 14:26:57 +0000331 ]
332
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000333 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000334 def _git_upload_no_rev_calls(cls):
335 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000336 ((['git', 'config', 'core.editor'],), ''),
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000337 ]
338
339 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000340 def _git_upload_calls(cls, private):
341 if private:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000342 cc_call = []
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000343 private_call = []
344 else:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000345 cc_call = [((['git', 'config', 'rietveld.cc'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000346 private_call = [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000347 ((['git', 'config', 'rietveld.private'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000348
maruel@chromium.orga3353652011-11-30 14:26:57 +0000349 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000350 ((['git', 'config', 'core.editor'],), ''),
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000351 ] + cc_call + private_call + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000352 ((['git', 'config', 'branch.master.base-url'],), ''),
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000353 ((['git', 'config', 'rietveld.pending-ref-prefix'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000354 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000355 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
356 (('', None), 0)),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000357 ((['git', 'rev-parse', '--show-cdup'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000358 ((['git', 'svn', 'info'],), ''),
sheyang@chromium.org152cf832014-06-11 21:37:49 +0000359 ((['git', 'config', 'rietveld.project'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000360 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000361 'config', 'branch.master.rietveldissue', '1'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000362 ((['git', 'config', 'branch.master.rietveldserver',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000363 'https://codereview.example.com'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000364 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000365 'config', 'branch.master.rietveldpatchset', '2'],), ''),
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000366 ] + cls._git_post_upload_calls()
367
368 @classmethod
369 def _git_post_upload_calls(cls):
370 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000371 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
372 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
373 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000374 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000375 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000376 ]
377
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000378 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000379 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000380 fake_ancestor = 'fake_ancestor'
381 fake_cl = 'fake_cl_for_patch'
382 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000383 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000384 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000385 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000386 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000387 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000388 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000389 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000390 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000391 'config', 'gitcl.remotebranch'],), (('', None), 1)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000392 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000393 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000394 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000395 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000396 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000397 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000398 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000399 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000400 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000401 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000402 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000403
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000404 @classmethod
405 def _dcommit_calls_1(cls):
406 return [
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000407 ((['git', 'config', 'rietveld.autoupdate'],),
408 ''),
409 ((['git', 'config', 'rietveld.pending-ref-prefix'],),
410 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000411 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000412 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000413 ((('svn-remote.svn.url svn://svn.chromium.org/chrome\n'
414 'svn-remote.svn.fetch trunk/src:refs/remotes/origin/master'),
415 None),
416 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000417 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
418 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000419 'branch.working.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000420 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
421 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000422 'branch.working.git-find-copies'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000423 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
424 ((['git',
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000425 'config', 'branch.working.rietveldissue'],), '12345'),
426 ((['git',
427 'config', 'rietveld.server'],), 'codereview.example.com'),
428 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000429 'config', 'branch.working.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000430 ((['git', 'config', 'branch.working.remote'],), 'origin'),
iannucci@chromium.org5724c962014-04-11 09:32:56 +0000431 ((['git', 'config', 'branch.working.merge'],),
432 'refs/heads/master'),
433 ((['git', 'config', 'branch.working.remote'],), 'origin'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000434 ((['git', 'rev-list', '--merges',
szager@chromium.orge84b7542012-06-15 21:26:58 +0000435 '--grep=^SVN changes up to revision [0-9]*$',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000436 'refs/remotes/origin/master^!'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000437 ((['git', 'rev-list', '^refs/heads/working',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000438 'refs/remotes/origin/master'],),
439 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000440 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000441 'log', '--grep=^git-svn-id:', '-1', '--pretty=format:%H'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000442 '3fc18b62c4966193eb435baabe2d18a3810ec82e'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000443 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000444 'rev-list', '^3fc18b62c4966193eb435baabe2d18a3810ec82e',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000445 'refs/remotes/origin/master'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000446 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000447 'merge-base', 'refs/remotes/origin/master', 'HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000448 'fake_ancestor_sha'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000449 ]
450
451 @classmethod
452 def _dcommit_calls_normal(cls):
453 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000454 ((['git', 'rev-parse', '--show-cdup'],), ''),
455 ((['git', 'rev-parse', 'HEAD'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000456 '00ff397798ea57439712ed7e04ab96e13969ef40'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000457 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000458 'diff', '--name-status', '--no-renames', '-r', 'fake_ancestor_sha...',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000459 '.'],),
460 'M\tPRESUBMIT.py'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000461 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000462 'config', 'branch.working.rietveldpatchset'],), '31137'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000463 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000464 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000465 ((['git', 'config', 'user.email'],), 'author@example.com'),
466 ((['git', 'config', 'rietveld.tree-status-url'],), ''),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000467 ]
468
469 @classmethod
470 def _dcommit_calls_bypassed(cls):
471 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000472 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000473 'codereview.example.com'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000474 ]
475
476 @classmethod
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000477 def _dcommit_calls_3(cls):
478 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000479 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000480 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000481 '-l100000', '-C50', 'fake_ancestor_sha',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000482 'refs/heads/working'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000483 (' PRESUBMIT.py | 2 +-\n'
484 ' 1 files changed, 1 insertions(+), 1 deletions(-)\n')),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000485 ((['git', 'show-ref', '--quiet', '--verify',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000486 'refs/heads/git-cl-commit'],),
487 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000488 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
489 ((['git', 'show-ref', '--quiet', '--verify',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000490 'refs/heads/git-cl-cherry-pick'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000491 ((['git', 'rev-parse', '--show-cdup'],), '\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000492 ((['git', 'checkout', '-q', '-b', 'git-cl-commit'],), ''),
493 ((['git', 'reset', '--soft', 'fake_ancestor_sha'],), ''),
494 ((['git', 'commit', '-m',
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000495 'Issue: 12345\n\nR=john@chromium.org\n\n'
sergiyb@chromium.org4b39c5f2015-07-07 10:33:12 +0000496 'Review URL: https://codereview.example.com/12345 .'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000497 ''),
kjellander@chromium.org6abc6522014-12-02 07:34:49 +0000498 ((['git', 'config', 'rietveld.force-https-commit-url'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000499 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000500 'svn', 'dcommit', '-C50', '--no-rebase', '--rmdir'],),
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000501 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000502 ((['git', 'checkout', '-q', 'working'],), ''),
503 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000504 ]
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000505
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000506 @staticmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000507 def _cmd_line(description, args, similarity, find_copies, private):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000508 """Returns the upload command line passed to upload.RealMain()."""
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000509 return [
510 'upload', '--assume_yes', '--server',
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +0000511 'https://codereview.example.com',
maruel@chromium.org71e12a92012-02-14 02:34:15 +0000512 '--message', description
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000513 ] + args + [
514 '--cc', 'joe@example.com',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000515 ] + (['--private'] if private else []) + [
iannucci@chromium.org79540052012-10-19 23:15:26 +0000516 '--git_similarity', similarity or '50'
517 ] + (['--git_no_find_copies'] if find_copies == False else []) + [
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000518 'fake_ancestor_sha', 'HEAD'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000519 ]
520
521 def _run_reviewer_test(
522 self,
523 upload_args,
524 expected_description,
525 returned_description,
526 final_description,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000527 reviewers,
528 private=False):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000529 """Generic reviewer test framework."""
tandrii@chromium.org28253532016-04-14 13:46:56 +0000530 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000531 try:
532 similarity = upload_args[upload_args.index('--similarity')+1]
533 except ValueError:
534 similarity = None
iannucci@chromium.org79540052012-10-19 23:15:26 +0000535
536 if '--find-copies' in upload_args:
537 find_copies = True
538 elif '--no-find-copies' in upload_args:
539 find_copies = False
540 else:
541 find_copies = None
542
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000543 private = '--private' in upload_args
544
545 self.calls = self._upload_calls(similarity, find_copies, private)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000546
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000547 def RunEditor(desc, _, **kwargs):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000548 self.assertEquals(
549 '# Enter a description of the change.\n'
janx@chromium.org104b2db2013-04-18 12:58:40 +0000550 '# This will be displayed on the codereview site.\n'
alancutter@chromium.org63a4d7f2013-05-31 02:22:45 +0000551 '# The first line will also be used as the subject of the review.\n'
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +0000552 '#--------------------This line is 72 characters long'
553 '--------------------\n' +
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000554 expected_description,
555 desc)
556 return returned_description
557 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000558
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000559 def check_upload(args):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000560 cmd_line = self._cmd_line(final_description, reviewers, similarity,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000561 find_copies, private)
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000562 self.assertEquals(cmd_line, args)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000563 return 1, 2
564 self.mock(git_cl.upload, 'RealMain', check_upload)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000565
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000566 git_cl.main(['upload'] + upload_args)
567
568 def test_no_reviewer(self):
569 self._run_reviewer_test(
570 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000571 'desc\n\nBUG=',
572 '# Blah blah comment.\ndesc\n\nBUG=',
573 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000574 [])
575
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000576 def test_keep_similarity(self):
577 self._run_reviewer_test(
578 ['--similarity', '70'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000579 'desc\n\nBUG=',
580 '# Blah blah comment.\ndesc\n\nBUG=',
581 'desc\n\nBUG=',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000582 [])
583
iannucci@chromium.org79540052012-10-19 23:15:26 +0000584 def test_keep_find_copies(self):
585 self._run_reviewer_test(
586 ['--no-find-copies'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000587 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000588 '# Blah blah comment.\ndesc\n\nBUG=\n',
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000589 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000590 [])
591
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000592 def test_private(self):
593 self._run_reviewer_test(
594 ['--private'],
595 'desc\n\nBUG=',
596 '# Blah blah comment.\ndesc\n\nBUG=\n',
597 'desc\n\nBUG=',
598 [])
599
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000600 def test_reviewers_cmd_line(self):
601 # Reviewer is passed as-is
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000602 description = 'desc\n\nR=foo@example.com\nBUG='
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000603 self._run_reviewer_test(
604 ['-r' 'foo@example.com'],
605 description,
606 '\n%s\n' % description,
607 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000608 ['--reviewers=foo@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000609
610 def test_reviewer_tbr_overriden(self):
611 # Reviewer is overriden with TBR
612 # Also verifies the regexp work without a trailing LF
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000613 description = 'Foo Bar\n\nTBR=reviewer@example.com'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000614 self._run_reviewer_test(
615 ['-r' 'foo@example.com'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000616 'desc\n\nR=foo@example.com\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000617 description.strip('\n'),
618 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000619 ['--reviewers=reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000620
621 def test_reviewer_multiple(self):
622 # Handles multiple R= or TBR= lines.
623 description = (
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000624 'Foo Bar\nTBR=reviewer@example.com\nBUG=\nR=another@example.com')
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000625 self._run_reviewer_test(
626 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000627 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000628 description,
629 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000630 ['--reviewers=another@example.com,reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000631
maruel@chromium.orga3353652011-11-30 14:26:57 +0000632 def test_reviewer_send_mail(self):
633 # --send-mail can be used without -r if R= is used
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000634 description = 'Foo Bar\nR=reviewer@example.com'
maruel@chromium.orga3353652011-11-30 14:26:57 +0000635 self._run_reviewer_test(
636 ['--send-mail'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000637 'desc\n\nBUG=',
maruel@chromium.orga3353652011-11-30 14:26:57 +0000638 description.strip('\n'),
639 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000640 ['--reviewers=reviewer@example.com', '--send_mail'])
maruel@chromium.orga3353652011-11-30 14:26:57 +0000641
642 def test_reviewer_send_mail_no_rev(self):
643 # Fails without a reviewer.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000644 stdout = StringIO.StringIO()
645 stderr = StringIO.StringIO()
maruel@chromium.orga3353652011-11-30 14:26:57 +0000646 try:
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000647 self.calls = self._upload_no_rev_calls(None, None)
648 def RunEditor(desc, _, **kwargs):
maruel@chromium.orga3353652011-11-30 14:26:57 +0000649 return desc
650 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000651 self.mock(sys, 'stdout', stdout)
652 self.mock(sys, 'stderr', stderr)
maruel@chromium.orga3353652011-11-30 14:26:57 +0000653 git_cl.main(['upload', '--send-mail'])
654 self.fail()
655 except SystemExit:
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000656 self.assertEqual(
657 'Using 50% similarity for rename/copy detection. Override with '
658 '--similarity.\n',
659 stdout.getvalue())
660 self.assertEqual(
661 'Must specify reviewers to send email.\n', stderr.getvalue())
maruel@chromium.orga3353652011-11-30 14:26:57 +0000662
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000663 def test_dcommit(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000664 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000665 self.calls = (
666 self._dcommit_calls_1() +
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000667 self._git_sanity_checks('fake_ancestor_sha', 'working') +
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000668 self._dcommit_calls_normal() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000669 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000670 git_cl.main(['dcommit'])
671
672 def test_dcommit_bypass_hooks(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000673 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000674 self.calls = (
675 self._dcommit_calls_1() +
676 self._dcommit_calls_bypassed() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000677 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000678 git_cl.main(['dcommit', '--bypass-hooks'])
679
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000680
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000681 @classmethod
tandrii@chromium.org28253532016-04-14 13:46:56 +0000682 def _gerrit_ensure_auth_calls(cls, issue=None, skip_auth_check=False):
683 cmd = ['git', 'config', '--bool', 'gerrit.skip_ensure_authenticated']
684 if skip_auth_check:
685 return [((cmd, ), 'true')]
686
687 calls = [((cmd, ), '', subprocess2.CalledProcessError(1, '', '', '', ''))]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000688 if issue:
689 calls.extend([
690 ((['git', 'config', 'branch.master.gerritserver'],), ''),
691 ])
692 calls.extend([
693 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
694 ((['git', 'config', 'branch.master.remote'],), 'origin'),
695 ((['git', 'config', 'remote.origin.url'],),
696 'https://chromium.googlesource.com/my/repo'),
697 ((['git', 'config', 'remote.origin.url'],),
698 'https://chromium.googlesource.com/my/repo'),
699 ])
700 return calls
701
702 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000703 def _gerrit_base_calls(cls, issue=None):
ukai@chromium.orge8077812012-02-03 03:41:46 +0000704 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000705 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
706 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000707 'branch.master.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000708 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
709 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000710 'branch.master.git-find-copies'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000711 ] + cls._is_gerrit_calls(True) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000712 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000713 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000714 ((['git', 'config', 'branch.master.gerritissue'],),
715 '' if issue is None else str(issue)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000716 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000717 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000718 ((['get_or_create_merge_base', 'master',
719 'refs/remotes/origin/master'],),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000720 'fake_ancestor_sha'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000721 # Calls to verify branch point is ancestor
722 ] + (cls._gerrit_ensure_auth_calls(issue=issue) +
723 cls._git_sanity_checks('fake_ancestor_sha', 'master',
724 get_remote_branch=False)) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000725 ((['git', 'rev-parse', '--show-cdup'],), ''),
726 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000727
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000728 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000729 'diff', '--name-status', '--no-renames', '-r',
730 'fake_ancestor_sha...', '.'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000731 'M\t.gitignore\n'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000732 ((['git', 'config', 'branch.master.gerritpatchset'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000733 ] + ([] if issue else [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000734 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000735 'log', '--pretty=format:%s%n%n%b', 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000736 'foo'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000737 ]) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000738 ((['git', 'config', 'user.email'],), 'me@example.com'),
739 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000740 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000741 '-l100000', '-C50', 'fake_ancestor_sha', 'HEAD'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000742 '+dat'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000743 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000744
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000745 @classmethod
746 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000747 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000748 ref_suffix='',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000749 post_amend_description=None, issue=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000750 if post_amend_description is None:
751 post_amend_description = description
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000752
ukai@chromium.orge8077812012-02-03 03:41:46 +0000753 calls = [
bauerb@chromium.org54b400c2016-01-14 10:08:25 +0000754 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), 'false'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000755 ]
756 # If issue is given, then description is fetched from Gerrit instead.
757 if issue is None:
758 if squash:
759 calls += [
760 ((['git', 'show', '--format=%B', '-s',
761 'refs/heads/git_cl_uploads/master'],), '')]
762 calls += [
763 ((['git', 'log', '--pretty=format:%s\n\n%b',
764 'fake_ancestor_sha..HEAD'],),
765 description)]
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000766 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000767 calls += [
tandrii@chromium.org10625002016-03-04 20:03:47 +0000768 # DownloadGerritHook(False)
769 ((False, ),
770 ''),
771 # Amending of commit message to get the Change-Id.
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000772 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000773 'fake_ancestor_sha..HEAD'],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000774 description),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000775 ((['git', 'commit', '--amend', '-m', description],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000776 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000777 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000778 'fake_ancestor_sha..HEAD'],),
tandrii@chromium.org10625002016-03-04 20:03:47 +0000779 post_amend_description)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000780 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000781 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000782 if not issue:
783 # Prompting to edit description on first upload.
784 calls += [
785 ((['git', 'config', 'core.editor'],), ''),
786 ((['RunEditor'],), description),
787 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000788 ref_to_push = 'abcdef0123456789'
789 calls += [
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000790 ((['git', 'config', 'branch.master.merge'],),
791 'refs/heads/master'),
792 ((['git', 'config', 'branch.master.remote'],),
793 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000794 ((['get_or_create_merge_base', 'master',
795 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000796 'origin/master'),
797 ((['git', 'rev-parse', 'HEAD:'],),
798 '0123456789abcdef'),
799 ((['git', 'commit-tree', '0123456789abcdef', '-p',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000800 'origin/master', '-m', description],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000801 ref_to_push),
802 ]
803 else:
804 ref_to_push = 'HEAD'
805
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000806 calls += [
luqui@chromium.org609f3952015-05-04 22:47:04 +0000807 ((['git', 'rev-list',
808 expected_upstream_ref + '..' + ref_to_push],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000809 ((['git', 'config', 'rietveld.cc'],), '')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000810 ]
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000811 # Add cc from watch list.
812 if ref_suffix == '':
813 ref_suffix = '%cc=joe@example.com'
814 else:
815 ref_suffix += ',cc=joe@example.com'
ukai@chromium.orge8077812012-02-03 03:41:46 +0000816 if reviewers:
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000817 ref_suffix += ',' + ','.join('r=%s' % email
818 for email in sorted(reviewers))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000819 calls += [
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000820 ((['git', 'push', 'origin',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000821 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000822 ('remote:\n'
823 'remote: Processing changes: (\)\n'
824 'remote: Processing changes: (|)\n'
825 'remote: Processing changes: (/)\n'
826 'remote: Processing changes: (-)\n'
827 'remote: Processing changes: new: 1 (/)\n'
828 'remote: Processing changes: new: 1, done\n'
829 'remote:\n'
830 'remote: New Changes:\n'
831 'remote: https://chromium-review.googlesource.com/123456 XXX.\n'
832 'remote:\n'
833 'To https://chromium.googlesource.com/yyy/zzz\n'
834 ' * [new branch] hhhh -> refs/for/refs/heads/master\n')),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000835 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000836 if squash:
837 calls += [
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000838 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000839 ((['git', 'config', 'branch.master.gerritserver',
840 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000841 ((['git', 'config', 'branch.master.gerritsquashhash',
842 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000843 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000844 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +0000845 return calls
846
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000847 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000848 self,
849 upload_args,
850 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000851 reviewers=None,
luqui@chromium.org609f3952015-05-04 22:47:04 +0000852 squash=False,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000853 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000854 ref_suffix='',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000855 post_amend_description=None,
856 issue=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000857 """Generic gerrit upload test framework."""
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000858 reviewers = reviewers or []
tandrii@chromium.org28253532016-04-14 13:46:56 +0000859 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000860 self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
861 CookiesAuthenticatorMockFactory(same_cookie='same_cred'))
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000862 self.calls = self._gerrit_base_calls(issue=issue)
luqui@chromium.org609f3952015-05-04 22:47:04 +0000863 self.calls += self._gerrit_upload_calls(
864 description, reviewers, squash,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000865 expected_upstream_ref=expected_upstream_ref,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000866 ref_suffix=ref_suffix,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000867 post_amend_description=post_amend_description,
868 issue=issue)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000869 # Uncomment when debugging.
870 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000871 git_cl.main(['upload'] + upload_args)
872
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000873 def test_gerrit_upload_without_change_id(self):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000874 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000875 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000876 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +0000877 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000878 [],
879 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000880
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000881 def test_gerrit_no_reviewer(self):
882 self._run_gerrit_upload_test(
883 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000884 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000885 [])
886
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000887 def test_gerrit_patch_title(self):
888 self._run_gerrit_upload_test(
889 ['-t', 'Don\'t put under_scores as they become spaces'],
890 'desc\n\nBUG=\n\nChange-Id: I123456789',
891 ref_suffix='%m=Don\'t_put_under_scores_as_they_become_spaces')
892
ukai@chromium.orge8077812012-02-03 03:41:46 +0000893 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000894 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000895 ['-r', 'foo@example.com'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000896 'desc\n\nBUG=\n\nChange-Id: I123456789',
ukai@chromium.orge8077812012-02-03 03:41:46 +0000897 ['foo@example.com'])
898
899 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000900 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000901 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000902 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n\n'
903 'Change-Id: 123456789\n',
ukai@chromium.orge8077812012-02-03 03:41:46 +0000904 ['reviewer@example.com', 'another@example.com'])
905
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000906 def test_gerrit_upload_squash_first(self):
907 # Mock Gerrit CL description to indicate the first upload.
908 self.mock(git_cl.Changelist, 'GetDescription',
909 lambda *_: None)
910 self.mock(git_cl.gclient_utils, 'RunEditor',
911 lambda *_, **__: self._mocked_call(['RunEditor']))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000912 self._run_gerrit_upload_test(
913 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000914 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000915 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +0000916 squash=True,
917 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000918
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000919 def test_gerrit_upload_squash_reupload(self):
920 description = 'desc\nBUG=\n\nChange-Id: 123456789'
921 # Mock Gerrit CL description to indicate re-upload.
922 self.mock(git_cl.Changelist, 'GetDescription',
923 lambda *args: description)
924 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
925 lambda *args: 1)
926 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
927 lambda *args: {'change_id': '123456789'})
928 self._run_gerrit_upload_test(
929 ['--squash'],
930 description,
931 [],
932 squash=True,
933 expected_upstream_ref='origin/master',
934 issue=123456)
935
rmistry@google.com2dd99862015-06-22 12:22:18 +0000936 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000937 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +0000938 def mock_run_git(*args, **_kwargs):
939 if args[0] == ['for-each-ref',
940 '--format=%(refname:short) %(upstream:short)',
941 'refs/heads']:
942 # Create a local branch dependency tree that looks like this:
943 # test1 -> test2 -> test3 -> test4 -> test5
944 # -> test3.1
945 # test6 -> test0
946 branch_deps = [
947 'test2 test1', # test1 -> test2
948 'test3 test2', # test2 -> test3
949 'test3.1 test2', # test2 -> test3.1
950 'test4 test3', # test3 -> test4
951 'test5 test4', # test4 -> test5
952 'test6 test0', # test0 -> test6
953 'test7', # test7
954 ]
955 return '\n'.join(branch_deps)
956 self.mock(git_cl, 'RunGit', mock_run_git)
957
958 class RecordCalls:
959 times_called = 0
960 record_calls = RecordCalls()
961 def mock_CMDupload(*args, **_kwargs):
962 record_calls.times_called += 1
963 return 0
964 self.mock(git_cl, 'CMDupload', mock_CMDupload)
965
966 self.calls = [
967 (('[Press enter to continue or ctrl-C to quit]',), ''),
968 ]
969
970 class MockChangelist():
971 def __init__(self):
972 pass
973 def GetBranch(self):
974 return 'test1'
975 def GetIssue(self):
976 return '123'
977 def GetPatchset(self):
978 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +0000979 def IsGerrit(self):
980 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +0000981
982 ret = git_cl.upload_branch_deps(MockChangelist(), [])
983 # CMDupload should have been called 5 times because of 5 dependent branches.
984 self.assertEquals(5, record_calls.times_called)
985 self.assertEquals(0, ret)
986
tandrii@chromium.org65874e12016-03-04 12:03:02 +0000987 def test_gerrit_change_id(self):
988 self.calls = [
989 ((['git', 'write-tree'], ),
990 'hashtree'),
991 ((['git', 'rev-parse', 'HEAD~0'], ),
992 'branch-parent'),
993 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
994 'A B <a@b.org> 1456848326 +0100'),
995 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
996 'C D <c@d.org> 1456858326 +0100'),
997 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
998 'hashchange'),
999 ]
1000 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1001 self.assertEqual(change_id, 'Ihashchange')
1002
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001003 def test_update_reviewers(self):
1004 data = [
1005 ('foo', [], 'foo'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001006 ('foo\nR=xx', [], 'foo\nR=xx'),
1007 ('foo\nTBR=xx', [], 'foo\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001008 ('foo', ['a@c'], 'foo\n\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001009 ('foo\nR=xx', ['a@c'], 'foo\n\nR=a@c, xx'),
1010 ('foo\nTBR=xx', ['a@c'], 'foo\n\nR=a@c\nTBR=xx'),
1011 ('foo\nTBR=xx\nR=yy', ['a@c'], 'foo\n\nR=a@c, yy\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001012 ('foo\nBUG=', ['a@c'], 'foo\nBUG=\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001013 ('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 +00001014 ('foo', ['a@c', 'b@c'], 'foo\n\nR=a@c, b@c'),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001015 ('foo\nBar\n\nR=\nBUG=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1016 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1017 # Same as the line before, but full of whitespaces.
1018 (
1019 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'],
1020 'foo\nBar\n\nR=c@c\n BUG =',
1021 ),
1022 # Whitespaces aren't interpreted as new lines.
1023 ('foo BUG=allo R=joe ', ['c@c'], 'foo BUG=allo R=joe\n\nR=c@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001024 ]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001025 expected = [i[2] for i in data]
1026 actual = []
1027 for orig, reviewers, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001028 obj = git_cl.ChangeDescription(orig)
1029 obj.update_reviewers(reviewers)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001030 actual.append(obj.description)
1031 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001032
wittman@chromium.org455dc922015-01-26 20:15:50 +00001033 def test_get_target_ref(self):
1034 # Check remote or remote branch not present.
1035 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master', None))
1036 self.assertEqual(None, git_cl.GetTargetRef(None,
1037 'refs/remotes/origin/master',
1038 'master', None))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001039
wittman@chromium.org455dc922015-01-26 20:15:50 +00001040 # Check default target refs for branches.
1041 self.assertEqual('refs/heads/master',
1042 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1043 None, None))
1044 self.assertEqual('refs/heads/master',
1045 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
1046 None, None))
1047 self.assertEqual('refs/heads/master',
1048 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
1049 None, None))
1050 self.assertEqual('refs/branch-heads/123',
1051 git_cl.GetTargetRef('origin',
1052 'refs/remotes/branch-heads/123',
1053 None, None))
1054 self.assertEqual('refs/diff/test',
1055 git_cl.GetTargetRef('origin',
1056 'refs/remotes/origin/refs/diff/test',
1057 None, None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001058 self.assertEqual('refs/heads/chrome/m42',
1059 git_cl.GetTargetRef('origin',
1060 'refs/remotes/origin/chrome/m42',
1061 None, None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001062
1063 # Check target refs for user-specified target branch.
1064 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1065 'refs/remotes/branch-heads/123'):
1066 self.assertEqual('refs/branch-heads/123',
1067 git_cl.GetTargetRef('origin',
1068 'refs/remotes/origin/master',
1069 branch, None))
1070 for branch in ('origin/master', 'remotes/origin/master',
1071 'refs/remotes/origin/master'):
1072 self.assertEqual('refs/heads/master',
1073 git_cl.GetTargetRef('origin',
1074 'refs/remotes/branch-heads/123',
1075 branch, None))
1076 for branch in ('master', 'heads/master', 'refs/heads/master'):
1077 self.assertEqual('refs/heads/master',
1078 git_cl.GetTargetRef('origin',
1079 'refs/remotes/branch-heads/123',
1080 branch, None))
1081
1082 # Check target refs for pending prefix.
1083 self.assertEqual('prefix/heads/master',
1084 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1085 None, 'prefix/'))
1086
wychen@chromium.orga872e752015-04-28 23:42:18 +00001087 def test_patch_when_dirty(self):
1088 # Patch when local tree is dirty
1089 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001090 self.calls = [
1091 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1092 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
1093 ((['git', 'config', 'branch.master.gerritissue'],), ''),
1094 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1095 ((['git', 'config', 'gerrit.host'],), ''),
1096 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
1097 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001098 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1099
1100 def test_diff_when_dirty(self):
1101 # Do 'git cl diff' when local tree is dirty
1102 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1103 self.assertNotEqual(git_cl.main(['diff']), 0)
1104
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001105 def _patch_common(self, is_gerrit=False, force_codereview=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001106 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001107 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1108 lambda x: '60001')
1109 self.mock(git_cl._RietveldChangelistImpl, 'GetPatchSetDiff',
1110 lambda *args: None)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001111 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1112 lambda *args: {
1113 'current_revision': '7777777777',
1114 'revisions': {
1115 '1111111111': {
1116 '_number': 1,
1117 'fetch': {'http': {
1118 'url': 'https://chromium.googlesource.com/my/repo',
1119 'ref': 'refs/changes/56/123456/1',
1120 }},
1121 },
1122 '7777777777': {
1123 '_number': 7,
1124 'fetch': {'http': {
1125 'url': 'https://chromium.googlesource.com/my/repo',
1126 'ref': 'refs/changes/56/123456/7',
1127 }},
1128 },
1129 },
1130 })
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001131 self.mock(git_cl.Changelist, 'GetDescription',
1132 lambda *args: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001133 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1134
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001135 if not force_codereview:
1136 # These calls detect codereview to use.
1137 self.calls = [
1138 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1139 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
1140 ((['git', 'config', 'branch.master.gerritissue'],), ''),
1141 ((['git', 'config', 'rietveld.autoupdate'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001142 ]
1143 else:
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001144 self.calls = []
1145
1146 if is_gerrit:
1147 if not force_codereview:
1148 self.calls += [
1149 ((['git', 'config', 'gerrit.host'],), 'true'),
1150 ]
1151 else:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001152 self.calls += [
1153 ((['git', 'config', 'gerrit.host'],), ''),
1154 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
1155 ((['git', 'rev-parse', '--show-cdup'],), ''),
1156 ((['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'],), ''),
1157 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001158
1159 def test_patch_successful(self):
1160 self._patch_common()
1161 self.calls += [
1162 ((['git', 'apply', '--index', '-p0', '--3way'],), ''),
1163 ((['git', 'commit', '-m',
wychen@chromium.org5b3bebb2015-05-28 21:41:43 +00001164 'Description\n\n' +
wychen@chromium.orga872e752015-04-28 23:42:18 +00001165 'patch from issue 123456 at patchset 60001 ' +
1166 '(http://crrev.com/123456#ps60001)'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001167 ((['git', 'config', 'branch.master.rietveldissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001168 ((['git', 'config', 'branch.master.rietveldserver'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001169 ((['git', 'config', 'branch.master.rietveldserver',
1170 'https://codereview.example.com'],), ''),
1171 ((['git', 'config', 'branch.master.rietveldpatchset', '60001'],), ''),
wychen@chromium.orga872e752015-04-28 23:42:18 +00001172 ]
1173 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1174
1175 def test_patch_conflict(self):
1176 self._patch_common()
1177 self.calls += [
1178 ((['git', 'apply', '--index', '-p0', '--3way'],), '',
1179 subprocess2.CalledProcessError(1, '', '', '', '')),
1180 ]
1181 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
wittman@chromium.org455dc922015-01-26 20:15:50 +00001182
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001183 def test_gerrit_patch_successful(self):
1184 self._patch_common(is_gerrit=True)
1185 self.calls += [
1186 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1187 'refs/changes/56/123456/7'],), ''),
1188 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1189 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1190 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1191 ((['git', 'config', 'branch.master.merge'],), 'master'),
1192 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1193 ((['git', 'config', 'remote.origin.url'],),
1194 'https://chromium.googlesource.com/my/repo'),
1195 ((['git', 'config', 'branch.master.gerritserver',
1196 'https://chromium-review.googlesource.com'],), ''),
1197 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1198 ]
1199 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1200
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001201 def test_patch_force_codereview(self):
1202 self._patch_common(is_gerrit=True, force_codereview=True)
1203 self.calls += [
1204 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1205 'refs/changes/56/123456/7'],), ''),
1206 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1207 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1208 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1209 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1210 ((['git', 'config', 'branch.master.merge'],), 'master'),
1211 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1212 ((['git', 'config', 'remote.origin.url'],),
1213 'https://chromium.googlesource.com/my/repo'),
1214 ((['git', 'config', 'branch.master.gerritserver',
1215 'https://chromium-review.googlesource.com'],), ''),
1216 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1217 ]
1218 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456']), 0)
1219
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001220 def test_gerrit_patch_url_successful(self):
1221 self._patch_common(is_gerrit=True)
1222 self.calls += [
1223 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1224 'refs/changes/56/123456/1'],), ''),
1225 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1226 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1227 ((['git', 'config', 'branch.master.gerritserver',
1228 'https://chromium-review.googlesource.com'],), ''),
1229 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1230 ]
1231 self.assertEqual(git_cl.main(
1232 ['patch', 'https://chromium-review.googlesource.com/#/c/123456/1']), 0)
1233
1234 def test_gerrit_patch_conflict(self):
1235 self._patch_common(is_gerrit=True)
1236 self.mock(git_cl, 'DieWithError',
1237 lambda msg: self._mocked_call(['DieWithError', msg]))
1238 class SystemExitMock(Exception):
1239 pass
1240 self.calls += [
1241 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1242 'refs/changes/56/123456/1'],), ''),
1243 ((['git', 'cherry-pick', 'FETCH_HEAD'],),
1244 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1245 ((['DieWithError', 'git cherry-pick FETCH_HEAD" failed.\n'],),
1246 '', SystemExitMock()),
1247 ]
1248 with self.assertRaises(SystemExitMock):
1249 git_cl.main(['patch',
1250 'https://chromium-review.googlesource.com/#/c/123456/1'])
1251
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001252 def _checkout_calls(self):
1253 return [
1254 ((['git', 'config', '--local', '--get-regexp',
1255 'branch\\..*\\.rietveldissue'], ),
1256 ('branch.retrying.rietveldissue 1111111111\n'
1257 'branch.some-fix.rietveldissue 2222222222\n')),
1258 ((['git', 'config', '--local', '--get-regexp',
1259 'branch\\..*\\.gerritissue'], ),
1260 ('branch.ger-branch.gerritissue 123456\n'
1261 'branch.gbranch654.gerritissue 654321\n')),
1262 ]
1263
1264 def test_checkout_gerrit(self):
1265 """Tests git cl checkout <issue>."""
1266 self.calls = self._checkout_calls()
1267 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1268 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1269
1270 def test_checkout_rietveld(self):
1271 """Tests git cl checkout <issue>."""
1272 self.calls = self._checkout_calls()
1273 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1274 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1275
1276 def test_checkout_not_found(self):
1277 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001278 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001279 self.calls = self._checkout_calls()
1280 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1281
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001282 def test_checkout_no_branch_issues(self):
1283 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001284 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001285 self.calls = [
1286 ((['git', 'config', '--local', '--get-regexp',
1287 'branch\\..*\\.rietveldissue'], ), '',
1288 subprocess2.CalledProcessError(1, '', '', '', '')),
1289 ((['git', 'config', '--local', '--get-regexp',
1290 'branch\\..*\\.gerritissue'], ), '',
1291 subprocess2.CalledProcessError(1, '', '', '', '')),
1292
1293 ]
1294 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1295
tandrii@chromium.org28253532016-04-14 13:46:56 +00001296 def _test_gerrit_ensure_authenticated_common(self, auth,
1297 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001298 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1299 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1300 self.mock(git_cl, 'DieWithError',
1301 lambda msg: self._mocked_call(['DieWithError', msg]))
1302 self.mock(git_cl, 'ask_for_data',
1303 lambda msg: self._mocked_call(['ask_for_data', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001304 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001305 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00001306 cl.branch = 'master'
1307 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001308 cl.lookedup_issue = True
1309 return cl
1310
1311 def test_gerrit_ensure_authenticated_missing(self):
1312 cl = self._test_gerrit_ensure_authenticated_common(auth={
1313 'chromium.googlesource.com': 'git is ok, but gerrit one is missing',
1314 })
1315 self.calls.append(
1316 ((['DieWithError',
1317 'Credentials for the following hosts are required:\n'
1318 ' chromium-review.googlesource.com\n'
1319 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1320 'You can (re)generate your credentails by visiting '
1321 'https://chromium-review.googlesource.com/new-password'],), ''),)
1322 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1323
1324 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001325 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001326 cl = self._test_gerrit_ensure_authenticated_common(auth={
1327 'chromium.googlesource.com': 'one',
1328 'chromium-review.googlesource.com': 'other',
1329 })
1330 self.calls.append(
1331 ((['ask_for_data', 'If you know what you are doing, '
1332 'press Enter to continue, Ctrl+C to abort.'],), ''))
1333 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1334
1335 def test_gerrit_ensure_authenticated_ok(self):
1336 cl = self._test_gerrit_ensure_authenticated_common(auth={
1337 'chromium.googlesource.com': 'same',
1338 'chromium-review.googlesource.com': 'same',
1339 })
1340 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1341
tandrii@chromium.org28253532016-04-14 13:46:56 +00001342 def test_gerrit_ensure_authenticated_skipped(self):
1343 cl = self._test_gerrit_ensure_authenticated_common(
1344 auth={}, skip_auth_check=True)
1345 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1346
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001347 def test_cmd_set_commit_rietveld(self):
1348 self.mock(git_cl._RietveldChangelistImpl, 'SetFlag',
1349 lambda _, f, v: self._mocked_call(['SetFlag', f, v]))
1350 self.calls = [
1351 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1352 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
1353 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1354 ((['git', 'config', 'rietveld.server'],), ''),
1355 ((['git', 'config', 'rietveld.server'],), ''),
1356 ((['git', 'config', 'branch.feature.rietveldserver'],),
1357 'https://codereview.chromium.org'),
1358 ((['SetFlag', 'commit', '1'], ), ''),
1359 ]
1360 self.assertEqual(0, git_cl.main(['set-commit']))
1361
1362 def test_cmd_set_commit_gerrit(self):
1363 self.mock(git_cl.gerrit_util, 'SetReview',
1364 lambda h, i, labels: self._mocked_call(
1365 ['SetReview', h, i, labels]))
1366 self.calls = [
1367 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1368 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1369 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1370 ((['git', 'config', 'branch.feature.gerritserver'],),
1371 'https://chromium-review.googlesource.com'),
1372 ((['SetReview', 'chromium-review.googlesource.com', 123,
1373 {'Commit-Queue': 1}],), ''),
1374 ]
tandrii@chromium.org1a8ef442016-04-13 18:41:37 +00001375 # TODO(tandrii): consider testing just set-commit and set-commit --clear,
1376 # but without copy-pasting tons of expectations, as modifying them later is
1377 # super tedious.
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001378 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1379
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001380
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001381if __name__ == '__main__':
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001382 git_cl.logging.basicConfig(
1383 level=git_cl.logging.DEBUG if '-v' in sys.argv else git_cl.logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001384 unittest.main()