blob: cc01ae3b829da5dbb5a2862a7a10aee44ade7886 [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')
148 test('http://codereview.chromium.org/download/issue123_4.diff',
149 123, 4, 'codereview.chromium.org',
150 patch_url='https://codereview.chromium.org/download/issue123_4.diff')
151 # This looks like bad Gerrit, but is actually valid Rietveld.
152 test('https://chrome-review.source.com/123/4/',
153 123, None, 'chrome-review.source.com')
154
155 test('https://codereview.chromium.org/deadbeaf', fail=True)
156 test('https://codereview.chromium.org/api/123', fail=True)
157 test('bad://codereview.chromium.org/123', fail=True)
158 test('http://codereview.chromium.org/download/issue123_4.diffff', fail=True)
159
160 def test_ParseIssueURL_gerrit(self):
161 def test(url, issue=None, patchset=None, hostname=None, fail=None):
162 self._test_ParseIssueUrl(
163 git_cl._GerritChangelistImpl.ParseIssueURL,
164 url, issue, patchset, hostname, fail)
165
166 test('http://chrome-review.source.com/c/123',
167 123, None, 'chrome-review.source.com')
168 test('https://chrome-review.source.com/c/123/',
169 123, None, 'chrome-review.source.com')
170 test('https://chrome-review.source.com/c/123/4',
171 123, 4, '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/123',
177 123, None, 'chrome-review.source.com')
178 test('https://chrome-review.source.com/123/4',
179 123, 4, 'chrome-review.source.com')
180
181 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
182 test('https://chrome-review.source.com/c/abc/', fail=True)
183 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
184
185 def test_ParseIssueNumberArgument(self):
186 def test(arg, issue=None, patchset=None, hostname=None, fail=False):
187 result = git_cl.ParseIssueNumberArgument(arg)
188 self.assertIsNotNone(result)
189 if fail:
190 self.assertFalse(result.valid)
191 else:
192 self.assertEqual(result.issue, issue)
193 self.assertEqual(result.patchset, patchset)
194 self.assertEqual(result.hostname, hostname)
195
196 test('123', 123)
197 test('', fail=True)
198 test('abc', fail=True)
199 test('123/1', fail=True)
200 test('123a', fail=True)
201 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
202 # Rietveld.
203 test('https://codereview.source.com/123',
204 123, None, 'codereview.source.com')
205 test('https://codereview.source.com/www123', fail=True)
206 # Gerrrit.
207 test('https://chrome-review.source.com/c/123/4',
208 123, 4, 'chrome-review.source.com')
209 test('https://chrome-review.source.com/bad/123/4', fail=True)
210
211
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000212class TestGitCl(TestCase):
213 def setUp(self):
214 super(TestGitCl, self).setUp()
215 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700216 self._calls_done = []
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000217 self.mock(subprocess2, 'call', self._mocked_call)
218 self.mock(subprocess2, 'check_call', self._mocked_call)
219 self.mock(subprocess2, 'check_output', self._mocked_call)
220 self.mock(subprocess2, 'communicate', self._mocked_call)
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000221 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000222 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000223 self.mock(git_common, 'get_or_create_merge_base',
224 lambda *a: (
225 self._mocked_call(['get_or_create_merge_base']+list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000226 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000227 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000228 self.mock(git_cl, 'ask_for_data', self._mocked_call)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000229 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000230 self.mock(git_cl.rietveld, 'Rietveld', RietveldMock)
maruel@chromium.org4bac4b52012-11-27 20:33:52 +0000231 self.mock(git_cl.rietveld, 'CachingRietveld', RietveldMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000232 self.mock(git_cl.upload, 'RealMain', self.fail)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000233 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000234 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000235 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
236 classmethod(lambda _: False))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000237 # It's important to reset settings to not have inter-tests interference.
238 git_cl.settings = None
239
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000240
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000241 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000242 try:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000243 # Note: has_failed returns True if at least 1 test ran so far, current
244 # included, has failed. That means current test may have actually ran
245 # fine, and the check for no leftover calls would be skipped.
wychen@chromium.org445c8962015-04-28 23:30:05 +0000246 if not self.has_failed():
247 self.assertEquals([], self.calls)
248 finally:
249 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000250
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000251 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000252 self.assertTrue(
253 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700254 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000255 top = self.calls.pop(0)
256 if len(top) > 2 and top[2]:
257 raise top[2]
258 expected_args, result = top
259
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000260 # Also logs otherwise it could get caught in a try/finally and be hard to
261 # diagnose.
262 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700263 N = 5
264 prior_calls = '\n '.join(
265 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
266 for i, c in enumerate(self._calls_done[-N:]))
267 following_calls = '\n '.join(
268 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
269 for i, c in enumerate(self.calls[:N]))
270 extended_msg = (
271 'A few prior calls:\n %s\n\n'
272 'This (expected):\n @%d: %r\n'
273 'This (actual):\n @%d: %r\n\n'
274 'A few following expected calls:\n %s' %
275 (prior_calls, len(self._calls_done), expected_args,
276 len(self._calls_done), args, following_calls))
277 git_cl.logging.error(extended_msg)
278
279 self.fail('@%d Expected: %r Actual: %r' % (
280 len(self._calls_done), expected_args, args))
281
282 self._calls_done.append(top)
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000283 return result
284
maruel@chromium.orga3353652011-11-30 14:26:57 +0000285 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000286 def _is_gerrit_calls(cls, gerrit=False):
287 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
288 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
289
290 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000291 def _upload_calls(cls, similarity, find_copies, private):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000292 return (cls._git_base_calls(similarity, find_copies) +
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000293 cls._git_upload_calls(private))
maruel@chromium.orga3353652011-11-30 14:26:57 +0000294
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000295 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000296 def _upload_no_rev_calls(cls, similarity, find_copies):
297 return (cls._git_base_calls(similarity, find_copies) +
298 cls._git_upload_no_rev_calls())
299
300 @classmethod
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000301 def _git_base_calls(cls, similarity, find_copies):
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000302 if similarity is None:
303 similarity = '50'
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000304 similarity_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000305 'branch.master.git-cl-similarity'],), '')
306 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000307 similarity_call = ((['git', 'config', '--int',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000308 'branch.master.git-cl-similarity', similarity],), '')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000309
310 if find_copies is None:
311 find_copies = True
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000312 find_copies_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000313 'branch.master.git-find-copies'],), '')
314 else:
315 val = str(int(find_copies))
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000316 find_copies_call = ((['git', 'config', '--int',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000317 'branch.master.git-find-copies', val],), '')
318
319 if find_copies:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000320 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000321 '--find-copies-harder', '-l100000', '-C'+similarity,
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000322 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000323 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000324 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000325 '-M'+similarity, 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000326
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000327 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000328 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000329 similarity_call,
330 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
331 find_copies_call,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000332 ] + cls._is_gerrit_calls() + [
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000333 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000334 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
335 ((['git', 'config', 'branch.master.gerritissue'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000336 ((['git', 'config', 'rietveld.server'],),
337 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000338 ((['git', 'config', 'branch.master.merge'],), 'master'),
339 ((['git', 'config', 'branch.master.remote'],), 'origin'),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000340 ((['get_or_create_merge_base', 'master', 'master'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000341 'fake_ancestor_sha'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000342 ] + cls._git_sanity_checks('fake_ancestor_sha', 'master') + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000343 ((['git', 'rev-parse', '--show-cdup'],), ''),
344 ((['git', 'rev-parse', 'HEAD'],), '12345'),
345 ((['git', 'diff', '--name-status', '--no-renames', '-r',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000346 'fake_ancestor_sha...', '.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000347 'M\t.gitignore\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000348 ((['git', 'config', 'branch.master.rietveldpatchset'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000349 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000350 ((['git', 'log', '--pretty=format:%s%n%n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000351 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000352 'foo'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000353 ((['git', 'config', 'user.email'],), 'me@example.com'),
iannucci@chromium.org79540052012-10-19 23:15:26 +0000354 stat_call,
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000355 ((['git', 'log', '--pretty=format:%s\n\n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000356 'fake_ancestor_sha..HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000357 'desc\n'),
rmistry@google.com90752582014-01-14 21:04:50 +0000358 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
maruel@chromium.orga3353652011-11-30 14:26:57 +0000359 ]
360
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000361 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000362 def _git_upload_no_rev_calls(cls):
363 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000364 ((['git', 'config', 'core.editor'],), ''),
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000365 ]
366
367 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000368 def _git_upload_calls(cls, private):
369 if private:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000370 cc_call = []
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000371 private_call = []
372 else:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000373 cc_call = [((['git', 'config', 'rietveld.cc'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000374 private_call = [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000375 ((['git', 'config', 'rietveld.private'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000376
maruel@chromium.orga3353652011-11-30 14:26:57 +0000377 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000378 ((['git', 'config', 'core.editor'],), ''),
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000379 ] + cc_call + private_call + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000380 ((['git', 'config', 'branch.master.base-url'],), ''),
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000381 ((['git', 'config', 'rietveld.pending-ref-prefix'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000382 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000383 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
384 (('', None), 0)),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000385 ((['git', 'rev-parse', '--show-cdup'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000386 ((['git', 'svn', 'info'],), ''),
sheyang@chromium.org152cf832014-06-11 21:37:49 +0000387 ((['git', 'config', 'rietveld.project'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000388 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000389 'config', 'branch.master.rietveldissue', '1'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000390 ((['git', 'config', 'branch.master.rietveldserver',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000391 'https://codereview.example.com'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000392 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000393 'config', 'branch.master.rietveldpatchset', '2'],), ''),
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000394 ] + cls._git_post_upload_calls()
395
396 @classmethod
397 def _git_post_upload_calls(cls):
398 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000399 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
400 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
401 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000402 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000403 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000404 ]
405
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000406 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000407 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000408 fake_ancestor = 'fake_ancestor'
409 fake_cl = 'fake_cl_for_patch'
410 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000411 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000412 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000413 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000414 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000415 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000416 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000417 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000418 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000419 'config', 'gitcl.remotebranch'],), (('', None), 1)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000420 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000421 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000422 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000423 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000424 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000425 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000426 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000427 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000428 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000429 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000430 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000431
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000432 @classmethod
433 def _dcommit_calls_1(cls):
434 return [
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000435 ((['git', 'config', 'rietveld.autoupdate'],),
436 ''),
437 ((['git', 'config', 'rietveld.pending-ref-prefix'],),
438 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000439 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000440 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000441 ((('svn-remote.svn.url svn://svn.chromium.org/chrome\n'
442 'svn-remote.svn.fetch trunk/src:refs/remotes/origin/master'),
443 None),
444 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000445 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
446 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000447 'branch.working.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000448 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
449 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000450 'branch.working.git-find-copies'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000451 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
452 ((['git',
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000453 'config', 'branch.working.rietveldissue'],), '12345'),
454 ((['git',
455 'config', 'rietveld.server'],), 'codereview.example.com'),
456 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000457 'config', 'branch.working.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000458 ((['git', 'config', 'branch.working.remote'],), 'origin'),
iannucci@chromium.org5724c962014-04-11 09:32:56 +0000459 ((['git', 'config', 'branch.working.merge'],),
460 'refs/heads/master'),
461 ((['git', 'config', 'branch.working.remote'],), 'origin'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000462 ((['git', 'rev-list', '--merges',
szager@chromium.orge84b7542012-06-15 21:26:58 +0000463 '--grep=^SVN changes up to revision [0-9]*$',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000464 'refs/remotes/origin/master^!'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000465 ((['git', 'rev-list', '^refs/heads/working',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000466 'refs/remotes/origin/master'],),
467 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000468 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000469 'log', '--grep=^git-svn-id:', '-1', '--pretty=format:%H'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000470 '3fc18b62c4966193eb435baabe2d18a3810ec82e'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000471 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000472 'rev-list', '^3fc18b62c4966193eb435baabe2d18a3810ec82e',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000473 'refs/remotes/origin/master'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000474 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000475 'merge-base', 'refs/remotes/origin/master', 'HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000476 'fake_ancestor_sha'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000477 ]
478
479 @classmethod
480 def _dcommit_calls_normal(cls):
481 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000482 ((['git', 'rev-parse', '--show-cdup'],), ''),
483 ((['git', 'rev-parse', 'HEAD'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000484 '00ff397798ea57439712ed7e04ab96e13969ef40'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000485 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000486 'diff', '--name-status', '--no-renames', '-r', 'fake_ancestor_sha...',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000487 '.'],),
488 'M\tPRESUBMIT.py'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000489 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000490 'config', 'branch.working.rietveldpatchset'],), '31137'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000491 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000492 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000493 ((['git', 'config', 'user.email'],), 'author@example.com'),
494 ((['git', 'config', 'rietveld.tree-status-url'],), ''),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000495 ]
496
497 @classmethod
498 def _dcommit_calls_bypassed(cls):
499 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000500 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000501 'codereview.example.com'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000502 ]
503
504 @classmethod
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000505 def _dcommit_calls_3(cls):
506 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000507 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000508 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000509 '-l100000', '-C50', 'fake_ancestor_sha',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000510 'refs/heads/working'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000511 (' PRESUBMIT.py | 2 +-\n'
512 ' 1 files changed, 1 insertions(+), 1 deletions(-)\n')),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000513 ((['git', 'show-ref', '--quiet', '--verify',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000514 'refs/heads/git-cl-commit'],),
515 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000516 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
517 ((['git', 'show-ref', '--quiet', '--verify',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000518 'refs/heads/git-cl-cherry-pick'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000519 ((['git', 'rev-parse', '--show-cdup'],), '\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000520 ((['git', 'checkout', '-q', '-b', 'git-cl-commit'],), ''),
521 ((['git', 'reset', '--soft', 'fake_ancestor_sha'],), ''),
522 ((['git', 'commit', '-m',
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000523 'Issue: 12345\n\nR=john@chromium.org\n\n'
sergiyb@chromium.org4b39c5f2015-07-07 10:33:12 +0000524 'Review URL: https://codereview.example.com/12345 .'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000525 ''),
kjellander@chromium.org6abc6522014-12-02 07:34:49 +0000526 ((['git', 'config', 'rietveld.force-https-commit-url'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000527 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000528 'svn', 'dcommit', '-C50', '--no-rebase', '--rmdir'],),
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000529 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000530 ((['git', 'checkout', '-q', 'working'],), ''),
531 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000532 ]
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000533
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000534 @staticmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000535 def _cmd_line(description, args, similarity, find_copies, private):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000536 """Returns the upload command line passed to upload.RealMain()."""
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000537 return [
538 'upload', '--assume_yes', '--server',
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +0000539 'https://codereview.example.com',
maruel@chromium.org71e12a92012-02-14 02:34:15 +0000540 '--message', description
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000541 ] + args + [
542 '--cc', 'joe@example.com',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000543 ] + (['--private'] if private else []) + [
iannucci@chromium.org79540052012-10-19 23:15:26 +0000544 '--git_similarity', similarity or '50'
545 ] + (['--git_no_find_copies'] if find_copies == False else []) + [
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000546 'fake_ancestor_sha', 'HEAD'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000547 ]
548
549 def _run_reviewer_test(
550 self,
551 upload_args,
552 expected_description,
553 returned_description,
554 final_description,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000555 reviewers,
556 private=False):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000557 """Generic reviewer test framework."""
tandrii@chromium.org28253532016-04-14 13:46:56 +0000558 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000559 try:
560 similarity = upload_args[upload_args.index('--similarity')+1]
561 except ValueError:
562 similarity = None
iannucci@chromium.org79540052012-10-19 23:15:26 +0000563
564 if '--find-copies' in upload_args:
565 find_copies = True
566 elif '--no-find-copies' in upload_args:
567 find_copies = False
568 else:
569 find_copies = None
570
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000571 private = '--private' in upload_args
572
573 self.calls = self._upload_calls(similarity, find_copies, private)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000574
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000575 def RunEditor(desc, _, **kwargs):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000576 self.assertEquals(
577 '# Enter a description of the change.\n'
janx@chromium.org104b2db2013-04-18 12:58:40 +0000578 '# This will be displayed on the codereview site.\n'
alancutter@chromium.org63a4d7f2013-05-31 02:22:45 +0000579 '# The first line will also be used as the subject of the review.\n'
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +0000580 '#--------------------This line is 72 characters long'
581 '--------------------\n' +
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000582 expected_description,
583 desc)
584 return returned_description
585 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000586
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000587 def check_upload(args):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000588 cmd_line = self._cmd_line(final_description, reviewers, similarity,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000589 find_copies, private)
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000590 self.assertEquals(cmd_line, args)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000591 return 1, 2
592 self.mock(git_cl.upload, 'RealMain', check_upload)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000593
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000594 git_cl.main(['upload'] + upload_args)
595
596 def test_no_reviewer(self):
597 self._run_reviewer_test(
598 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000599 'desc\n\nBUG=',
600 '# Blah blah comment.\ndesc\n\nBUG=',
601 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000602 [])
603
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000604 def test_keep_similarity(self):
605 self._run_reviewer_test(
606 ['--similarity', '70'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000607 'desc\n\nBUG=',
608 '# Blah blah comment.\ndesc\n\nBUG=',
609 'desc\n\nBUG=',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000610 [])
611
iannucci@chromium.org79540052012-10-19 23:15:26 +0000612 def test_keep_find_copies(self):
613 self._run_reviewer_test(
614 ['--no-find-copies'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000615 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000616 '# Blah blah comment.\ndesc\n\nBUG=\n',
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000617 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000618 [])
619
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000620 def test_private(self):
621 self._run_reviewer_test(
622 ['--private'],
623 'desc\n\nBUG=',
624 '# Blah blah comment.\ndesc\n\nBUG=\n',
625 'desc\n\nBUG=',
626 [])
627
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000628 def test_reviewers_cmd_line(self):
629 # Reviewer is passed as-is
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000630 description = 'desc\n\nR=foo@example.com\nBUG='
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000631 self._run_reviewer_test(
632 ['-r' 'foo@example.com'],
633 description,
634 '\n%s\n' % description,
635 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000636 ['--reviewers=foo@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000637
638 def test_reviewer_tbr_overriden(self):
639 # Reviewer is overriden with TBR
640 # Also verifies the regexp work without a trailing LF
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000641 description = 'Foo Bar\n\nTBR=reviewer@example.com'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000642 self._run_reviewer_test(
643 ['-r' 'foo@example.com'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000644 'desc\n\nR=foo@example.com\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000645 description.strip('\n'),
646 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000647 ['--reviewers=reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000648
649 def test_reviewer_multiple(self):
650 # Handles multiple R= or TBR= lines.
651 description = (
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000652 'Foo Bar\nTBR=reviewer@example.com\nBUG=\nR=another@example.com')
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000653 self._run_reviewer_test(
654 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000655 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000656 description,
657 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000658 ['--reviewers=another@example.com,reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000659
maruel@chromium.orga3353652011-11-30 14:26:57 +0000660 def test_reviewer_send_mail(self):
661 # --send-mail can be used without -r if R= is used
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000662 description = 'Foo Bar\nR=reviewer@example.com'
maruel@chromium.orga3353652011-11-30 14:26:57 +0000663 self._run_reviewer_test(
664 ['--send-mail'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000665 'desc\n\nBUG=',
maruel@chromium.orga3353652011-11-30 14:26:57 +0000666 description.strip('\n'),
667 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000668 ['--reviewers=reviewer@example.com', '--send_mail'])
maruel@chromium.orga3353652011-11-30 14:26:57 +0000669
670 def test_reviewer_send_mail_no_rev(self):
671 # Fails without a reviewer.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000672 stdout = StringIO.StringIO()
673 stderr = StringIO.StringIO()
maruel@chromium.orga3353652011-11-30 14:26:57 +0000674 try:
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000675 self.calls = self._upload_no_rev_calls(None, None)
676 def RunEditor(desc, _, **kwargs):
maruel@chromium.orga3353652011-11-30 14:26:57 +0000677 return desc
678 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000679 self.mock(sys, 'stdout', stdout)
680 self.mock(sys, 'stderr', stderr)
maruel@chromium.orga3353652011-11-30 14:26:57 +0000681 git_cl.main(['upload', '--send-mail'])
682 self.fail()
683 except SystemExit:
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000684 self.assertEqual(
685 'Using 50% similarity for rename/copy detection. Override with '
686 '--similarity.\n',
687 stdout.getvalue())
688 self.assertEqual(
689 'Must specify reviewers to send email.\n', stderr.getvalue())
maruel@chromium.orga3353652011-11-30 14:26:57 +0000690
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000691 def test_dcommit(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000692 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000693 self.calls = (
694 self._dcommit_calls_1() +
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000695 self._git_sanity_checks('fake_ancestor_sha', 'working') +
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000696 self._dcommit_calls_normal() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000697 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000698 git_cl.main(['dcommit'])
699
700 def test_dcommit_bypass_hooks(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000701 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000702 self.calls = (
703 self._dcommit_calls_1() +
704 self._dcommit_calls_bypassed() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000705 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000706 git_cl.main(['dcommit', '--bypass-hooks'])
707
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000708
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000709 @classmethod
tandrii@chromium.org28253532016-04-14 13:46:56 +0000710 def _gerrit_ensure_auth_calls(cls, issue=None, skip_auth_check=False):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000711 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000712 if skip_auth_check:
713 return [((cmd, ), 'true')]
714
715 calls = [((cmd, ), '', subprocess2.CalledProcessError(1, '', '', '', ''))]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000716 if issue:
717 calls.extend([
718 ((['git', 'config', 'branch.master.gerritserver'],), ''),
719 ])
720 calls.extend([
721 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
722 ((['git', 'config', 'branch.master.remote'],), 'origin'),
723 ((['git', 'config', 'remote.origin.url'],),
724 'https://chromium.googlesource.com/my/repo'),
725 ((['git', 'config', 'remote.origin.url'],),
726 'https://chromium.googlesource.com/my/repo'),
727 ])
728 return calls
729
730 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000731 def _gerrit_base_calls(cls, issue=None):
ukai@chromium.orge8077812012-02-03 03:41:46 +0000732 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000733 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
734 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000735 'branch.master.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000736 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
737 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000738 'branch.master.git-find-copies'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000739 ] + cls._is_gerrit_calls(True) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000740 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000741 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000742 ((['git', 'config', 'branch.master.gerritissue'],),
743 '' if issue is None else str(issue)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000744 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000745 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000746 ((['get_or_create_merge_base', 'master',
747 'refs/remotes/origin/master'],),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000748 'fake_ancestor_sha'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000749 # Calls to verify branch point is ancestor
750 ] + (cls._gerrit_ensure_auth_calls(issue=issue) +
751 cls._git_sanity_checks('fake_ancestor_sha', 'master',
752 get_remote_branch=False)) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000753 ((['git', 'rev-parse', '--show-cdup'],), ''),
754 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000755
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000756 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000757 'diff', '--name-status', '--no-renames', '-r',
758 'fake_ancestor_sha...', '.'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000759 'M\t.gitignore\n'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000760 ((['git', 'config', 'branch.master.gerritpatchset'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000761 ] + ([] if issue else [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000762 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000763 'log', '--pretty=format:%s%n%n%b', 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000764 'foo'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000765 ]) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000766 ((['git', 'config', 'user.email'],), 'me@example.com'),
767 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000768 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000769 '-l100000', '-C50', 'fake_ancestor_sha', 'HEAD'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000770 '+dat'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000771 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000772
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000773 @classmethod
774 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700775 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000776 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000777 ref_suffix='', notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000778 post_amend_description=None, issue=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000779 if post_amend_description is None:
780 post_amend_description = description
tandriia60502f2016-06-20 02:01:53 -0700781 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000782
tandriia60502f2016-06-20 02:01:53 -0700783 if squash_mode == 'default':
784 calls.extend([
785 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
786 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
787 ])
788 elif squash_mode in ('override_squash', 'override_nosquash'):
789 calls.extend([
790 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
791 'true' if squash_mode == 'override_squash' else 'false'),
792 ])
793 else:
794 assert squash_mode in ('squash', 'nosquash')
795
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000796 # If issue is given, then description is fetched from Gerrit instead.
797 if issue is None:
798 if squash:
799 calls += [
800 ((['git', 'show', '--format=%B', '-s',
801 'refs/heads/git_cl_uploads/master'],), '')]
802 calls += [
803 ((['git', 'log', '--pretty=format:%s\n\n%b',
804 'fake_ancestor_sha..HEAD'],),
805 description)]
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000806 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000807 calls += [
tandrii@chromium.org10625002016-03-04 20:03:47 +0000808 # DownloadGerritHook(False)
809 ((False, ),
810 ''),
811 # Amending of commit message to get the Change-Id.
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000812 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000813 'fake_ancestor_sha..HEAD'],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000814 description),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000815 ((['git', 'commit', '--amend', '-m', description],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000816 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000817 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000818 'fake_ancestor_sha..HEAD'],),
tandrii@chromium.org10625002016-03-04 20:03:47 +0000819 post_amend_description)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000820 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000821 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000822 if not issue:
823 # Prompting to edit description on first upload.
824 calls += [
825 ((['git', 'config', 'core.editor'],), ''),
826 ((['RunEditor'],), description),
827 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000828 ref_to_push = 'abcdef0123456789'
829 calls += [
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000830 ((['git', 'config', 'branch.master.merge'],),
831 'refs/heads/master'),
832 ((['git', 'config', 'branch.master.remote'],),
833 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000834 ((['get_or_create_merge_base', 'master',
835 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000836 'origin/master'),
837 ((['git', 'rev-parse', 'HEAD:'],),
838 '0123456789abcdef'),
839 ((['git', 'commit-tree', '0123456789abcdef', '-p',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000840 'origin/master', '-m', description],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000841 ref_to_push),
842 ]
843 else:
844 ref_to_push = 'HEAD'
845
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000846 calls += [
luqui@chromium.org609f3952015-05-04 22:47:04 +0000847 ((['git', 'rev-list',
848 expected_upstream_ref + '..' + ref_to_push],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000849 ((['git', 'config', 'rietveld.cc'],), '')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000850 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000851
852 notify_suffix = 'notify=%s' % ('ALL' if notify else 'NONE')
853 if ref_suffix:
854 ref_suffix += ',' + notify_suffix
855 else:
856 ref_suffix = '%' + notify_suffix
tandrii@chromium.org074c2af2016-06-03 23:18:40 +0000857
858 # Add cc from watch list.
859 ref_suffix += ',cc=joe@example.com'
860
ukai@chromium.orge8077812012-02-03 03:41:46 +0000861 if reviewers:
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000862 ref_suffix += ',' + ','.join('r=%s' % email
863 for email in sorted(reviewers))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000864 calls += [
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000865 ((['git', 'push', 'origin',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000866 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000867 ('remote:\n'
868 'remote: Processing changes: (\)\n'
869 'remote: Processing changes: (|)\n'
870 'remote: Processing changes: (/)\n'
871 'remote: Processing changes: (-)\n'
872 'remote: Processing changes: new: 1 (/)\n'
873 'remote: Processing changes: new: 1, done\n'
874 'remote:\n'
875 'remote: New Changes:\n'
876 'remote: https://chromium-review.googlesource.com/123456 XXX.\n'
877 'remote:\n'
878 'To https://chromium.googlesource.com/yyy/zzz\n'
879 ' * [new branch] hhhh -> refs/for/refs/heads/master\n')),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000880 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000881 if squash:
882 calls += [
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000883 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000884 ((['git', 'config', 'branch.master.gerritserver',
885 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000886 ((['git', 'config', 'branch.master.gerritsquashhash',
887 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000888 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000889 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +0000890 return calls
891
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000892 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000893 self,
894 upload_args,
895 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000896 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700897 squash=True,
898 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000899 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000900 ref_suffix='',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000901 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000902 post_amend_description=None,
903 issue=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000904 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700905 if squash_mode is None:
906 if '--no-squash' in upload_args:
907 squash_mode = 'nosquash'
908 elif '--squash' in upload_args:
909 squash_mode = 'squash'
910 else:
911 squash_mode = 'default'
912
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000913 reviewers = reviewers or []
tandrii@chromium.org28253532016-04-14 13:46:56 +0000914 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -0700915 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000916 CookiesAuthenticatorMockFactory(same_cookie='same_cred'))
tandrii16e0b4e2016-06-07 10:34:28 -0700917 self.mock(git_cl._GerritChangelistImpl, '_GerritCommitMsgHookCheck',
918 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -0700919 self.mock(git_cl.gclient_utils, 'RunEditor',
920 lambda *_, **__: self._mocked_call(['RunEditor']))
921 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
922
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000923 self.calls = self._gerrit_base_calls(issue=issue)
luqui@chromium.org609f3952015-05-04 22:47:04 +0000924 self.calls += self._gerrit_upload_calls(
925 description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700926 squash_mode=squash_mode,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000927 expected_upstream_ref=expected_upstream_ref,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000928 ref_suffix=ref_suffix, notify=notify,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000929 post_amend_description=post_amend_description,
930 issue=issue)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000931 # Uncomment when debugging.
932 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000933 git_cl.main(['upload'] + upload_args)
934
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000935 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -0700936 self._run_gerrit_upload_test(
937 ['--no-squash'],
938 'desc\n\nBUG=\n',
939 [],
940 squash=False,
941 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
942
943 def test_gerrit_upload_without_change_id_override_nosquash(self):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000944 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000945 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000946 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +0000947 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000948 [],
tandriia60502f2016-06-20 02:01:53 -0700949 squash=False,
950 squash_mode='override_nosquash',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000951 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000952
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000953 def test_gerrit_no_reviewer(self):
954 self._run_gerrit_upload_test(
955 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000956 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700957 [],
958 squash=False,
959 squash_mode='override_nosquash')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000960
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000961 def test_gerrit_patch_title(self):
962 self._run_gerrit_upload_test(
963 ['-t', 'Don\'t put under_scores as they become spaces'],
964 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandriia60502f2016-06-20 02:01:53 -0700965 squash=False,
966 squash_mode='override_nosquash',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000967 ref_suffix='%m=Don\'t_put_under_scores_as_they_become_spaces')
968
ukai@chromium.orge8077812012-02-03 03:41:46 +0000969 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000970 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000971 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000972 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000973 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -0700974 squash=False,
975 squash_mode='override_nosquash',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000976 notify=True)
ukai@chromium.orge8077812012-02-03 03:41:46 +0000977
978 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000979 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000980 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000981 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n\n'
982 'Change-Id: 123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700983 ['reviewer@example.com', 'another@example.com'],
984 squash=False,
985 squash_mode='override_nosquash')
986
987 def test_gerrit_upload_squash_first_is_default(self):
988 # Mock Gerrit CL description to indicate the first upload.
989 self.mock(git_cl.Changelist, 'GetDescription',
990 lambda *_: None)
991 self._run_gerrit_upload_test(
992 [],
993 'desc\nBUG=\n\nChange-Id: 123456789',
994 [],
995 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000996
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000997 def test_gerrit_upload_squash_first(self):
998 # Mock Gerrit CL description to indicate the first upload.
999 self.mock(git_cl.Changelist, 'GetDescription',
1000 lambda *_: None)
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001001 self._run_gerrit_upload_test(
1002 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001003 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001004 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001005 squash=True,
1006 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001007
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001008 def test_gerrit_upload_squash_reupload(self):
1009 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1010 # Mock Gerrit CL description to indicate re-upload.
1011 self.mock(git_cl.Changelist, 'GetDescription',
1012 lambda *args: description)
1013 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
1014 lambda *args: 1)
1015 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1016 lambda *args: {'change_id': '123456789'})
1017 self._run_gerrit_upload_test(
1018 ['--squash'],
1019 description,
1020 [],
1021 squash=True,
1022 expected_upstream_ref='origin/master',
1023 issue=123456)
1024
rmistry@google.com2dd99862015-06-22 12:22:18 +00001025 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001026 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001027 def mock_run_git(*args, **_kwargs):
1028 if args[0] == ['for-each-ref',
1029 '--format=%(refname:short) %(upstream:short)',
1030 'refs/heads']:
1031 # Create a local branch dependency tree that looks like this:
1032 # test1 -> test2 -> test3 -> test4 -> test5
1033 # -> test3.1
1034 # test6 -> test0
1035 branch_deps = [
1036 'test2 test1', # test1 -> test2
1037 'test3 test2', # test2 -> test3
1038 'test3.1 test2', # test2 -> test3.1
1039 'test4 test3', # test3 -> test4
1040 'test5 test4', # test4 -> test5
1041 'test6 test0', # test0 -> test6
1042 'test7', # test7
1043 ]
1044 return '\n'.join(branch_deps)
1045 self.mock(git_cl, 'RunGit', mock_run_git)
1046
1047 class RecordCalls:
1048 times_called = 0
1049 record_calls = RecordCalls()
1050 def mock_CMDupload(*args, **_kwargs):
1051 record_calls.times_called += 1
1052 return 0
1053 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1054
1055 self.calls = [
1056 (('[Press enter to continue or ctrl-C to quit]',), ''),
1057 ]
1058
1059 class MockChangelist():
1060 def __init__(self):
1061 pass
1062 def GetBranch(self):
1063 return 'test1'
1064 def GetIssue(self):
1065 return '123'
1066 def GetPatchset(self):
1067 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001068 def IsGerrit(self):
1069 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001070
1071 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1072 # CMDupload should have been called 5 times because of 5 dependent branches.
1073 self.assertEquals(5, record_calls.times_called)
1074 self.assertEquals(0, ret)
1075
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001076 def test_gerrit_change_id(self):
1077 self.calls = [
1078 ((['git', 'write-tree'], ),
1079 'hashtree'),
1080 ((['git', 'rev-parse', 'HEAD~0'], ),
1081 'branch-parent'),
1082 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1083 'A B <a@b.org> 1456848326 +0100'),
1084 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1085 'C D <c@d.org> 1456858326 +0100'),
1086 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1087 'hashchange'),
1088 ]
1089 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1090 self.assertEqual(change_id, 'Ihashchange')
1091
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001092 def test_desecription_append_footer(self):
1093 for init_desc, footer_line, expected_desc in [
1094 # Use unique desc first lines for easy test failure identification.
1095 ('foo', 'R=one', 'foo\n\nR=one'),
1096 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1097 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1098 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1099 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1100 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1101 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1102 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1103 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1104 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1105 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1106 ]:
1107 desc = git_cl.ChangeDescription(init_desc)
1108 desc.append_footer(footer_line)
1109 self.assertEqual(desc.description, expected_desc)
1110
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001111 def test_update_reviewers(self):
1112 data = [
1113 ('foo', [], 'foo'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001114 ('foo\nR=xx', [], 'foo\nR=xx'),
1115 ('foo\nTBR=xx', [], 'foo\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001116 ('foo', ['a@c'], 'foo\n\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001117 ('foo\nR=xx', ['a@c'], 'foo\n\nR=a@c, xx'),
1118 ('foo\nTBR=xx', ['a@c'], 'foo\n\nR=a@c\nTBR=xx'),
1119 ('foo\nTBR=xx\nR=yy', ['a@c'], 'foo\n\nR=a@c, yy\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001120 ('foo\nBUG=', ['a@c'], 'foo\nBUG=\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001121 ('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 +00001122 ('foo', ['a@c', 'b@c'], 'foo\n\nR=a@c, b@c'),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001123 ('foo\nBar\n\nR=\nBUG=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1124 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1125 # Same as the line before, but full of whitespaces.
1126 (
1127 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'],
1128 'foo\nBar\n\nR=c@c\n BUG =',
1129 ),
1130 # Whitespaces aren't interpreted as new lines.
1131 ('foo BUG=allo R=joe ', ['c@c'], 'foo BUG=allo R=joe\n\nR=c@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001132 ]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001133 expected = [i[2] for i in data]
1134 actual = []
1135 for orig, reviewers, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001136 obj = git_cl.ChangeDescription(orig)
1137 obj.update_reviewers(reviewers)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001138 actual.append(obj.description)
1139 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001140
wittman@chromium.org455dc922015-01-26 20:15:50 +00001141 def test_get_target_ref(self):
1142 # Check remote or remote branch not present.
1143 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master', None))
1144 self.assertEqual(None, git_cl.GetTargetRef(None,
1145 'refs/remotes/origin/master',
1146 'master', None))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001147
wittman@chromium.org455dc922015-01-26 20:15:50 +00001148 # Check default target refs for branches.
1149 self.assertEqual('refs/heads/master',
1150 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1151 None, None))
1152 self.assertEqual('refs/heads/master',
1153 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
1154 None, None))
1155 self.assertEqual('refs/heads/master',
1156 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
1157 None, None))
1158 self.assertEqual('refs/branch-heads/123',
1159 git_cl.GetTargetRef('origin',
1160 'refs/remotes/branch-heads/123',
1161 None, None))
1162 self.assertEqual('refs/diff/test',
1163 git_cl.GetTargetRef('origin',
1164 'refs/remotes/origin/refs/diff/test',
1165 None, None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001166 self.assertEqual('refs/heads/chrome/m42',
1167 git_cl.GetTargetRef('origin',
1168 'refs/remotes/origin/chrome/m42',
1169 None, None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001170
1171 # Check target refs for user-specified target branch.
1172 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1173 'refs/remotes/branch-heads/123'):
1174 self.assertEqual('refs/branch-heads/123',
1175 git_cl.GetTargetRef('origin',
1176 'refs/remotes/origin/master',
1177 branch, None))
1178 for branch in ('origin/master', 'remotes/origin/master',
1179 'refs/remotes/origin/master'):
1180 self.assertEqual('refs/heads/master',
1181 git_cl.GetTargetRef('origin',
1182 'refs/remotes/branch-heads/123',
1183 branch, None))
1184 for branch in ('master', 'heads/master', 'refs/heads/master'):
1185 self.assertEqual('refs/heads/master',
1186 git_cl.GetTargetRef('origin',
1187 'refs/remotes/branch-heads/123',
1188 branch, None))
1189
1190 # Check target refs for pending prefix.
1191 self.assertEqual('prefix/heads/master',
1192 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1193 None, 'prefix/'))
1194
wychen@chromium.orga872e752015-04-28 23:42:18 +00001195 def test_patch_when_dirty(self):
1196 # Patch when local tree is dirty
1197 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1198 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1199
1200 def test_diff_when_dirty(self):
1201 # Do 'git cl diff' when local tree is dirty
1202 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1203 self.assertNotEqual(git_cl.main(['diff']), 0)
1204
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001205 def _patch_common(self, is_gerrit=False, force_codereview=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001206 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001207 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1208 lambda x: '60001')
1209 self.mock(git_cl._RietveldChangelistImpl, 'GetPatchSetDiff',
1210 lambda *args: None)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001211 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1212 lambda *args: {
1213 'current_revision': '7777777777',
1214 'revisions': {
1215 '1111111111': {
1216 '_number': 1,
1217 'fetch': {'http': {
1218 'url': 'https://chromium.googlesource.com/my/repo',
1219 'ref': 'refs/changes/56/123456/1',
1220 }},
1221 },
1222 '7777777777': {
1223 '_number': 7,
1224 'fetch': {'http': {
1225 'url': 'https://chromium.googlesource.com/my/repo',
1226 'ref': 'refs/changes/56/123456/7',
1227 }},
1228 },
1229 },
1230 })
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001231 self.mock(git_cl.Changelist, 'GetDescription',
1232 lambda *args: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001233 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1234
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001235 self.calls = self.calls or []
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001236 if not force_codereview:
1237 # These calls detect codereview to use.
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001238 self.calls += [
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001239 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1240 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
1241 ((['git', 'config', 'branch.master.gerritissue'],), ''),
1242 ((['git', 'config', 'rietveld.autoupdate'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001243 ]
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001244
1245 if is_gerrit:
1246 if not force_codereview:
1247 self.calls += [
1248 ((['git', 'config', 'gerrit.host'],), 'true'),
1249 ]
1250 else:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001251 self.calls += [
1252 ((['git', 'config', 'gerrit.host'],), ''),
1253 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
1254 ((['git', 'rev-parse', '--show-cdup'],), ''),
1255 ((['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'],), ''),
1256 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001257
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001258 def _common_patch_successful(self):
wychen@chromium.orga872e752015-04-28 23:42:18 +00001259 self._patch_common()
1260 self.calls += [
1261 ((['git', 'apply', '--index', '-p0', '--3way'],), ''),
1262 ((['git', 'commit', '-m',
wychen@chromium.org5b3bebb2015-05-28 21:41:43 +00001263 'Description\n\n' +
wychen@chromium.orga872e752015-04-28 23:42:18 +00001264 'patch from issue 123456 at patchset 60001 ' +
1265 '(http://crrev.com/123456#ps60001)'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001266 ((['git', 'config', 'branch.master.rietveldissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001267 ((['git', 'config', 'branch.master.rietveldserver'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001268 ((['git', 'config', 'branch.master.rietveldserver',
1269 'https://codereview.example.com'],), ''),
1270 ((['git', 'config', 'branch.master.rietveldpatchset', '60001'],), ''),
wychen@chromium.orga872e752015-04-28 23:42:18 +00001271 ]
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001272
1273 def test_patch_successful(self):
1274 self._common_patch_successful()
wychen@chromium.orga872e752015-04-28 23:42:18 +00001275 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1276
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001277 def test_patch_successful_new_branch(self):
1278 self.calls = [ ((['git', 'new-branch', 'master'],), ''), ]
1279 self._common_patch_successful()
1280 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1281
wychen@chromium.orga872e752015-04-28 23:42:18 +00001282 def test_patch_conflict(self):
1283 self._patch_common()
1284 self.calls += [
1285 ((['git', 'apply', '--index', '-p0', '--3way'],), '',
1286 subprocess2.CalledProcessError(1, '', '', '', '')),
1287 ]
1288 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
wittman@chromium.org455dc922015-01-26 20:15:50 +00001289
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001290 def test_gerrit_patch_successful(self):
1291 self._patch_common(is_gerrit=True)
1292 self.calls += [
1293 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1294 'refs/changes/56/123456/7'],), ''),
1295 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1296 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1297 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1298 ((['git', 'config', 'branch.master.merge'],), 'master'),
1299 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1300 ((['git', 'config', 'remote.origin.url'],),
1301 'https://chromium.googlesource.com/my/repo'),
1302 ((['git', 'config', 'branch.master.gerritserver',
1303 'https://chromium-review.googlesource.com'],), ''),
1304 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1305 ]
1306 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1307
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001308 def test_patch_force_codereview(self):
1309 self._patch_common(is_gerrit=True, force_codereview=True)
1310 self.calls += [
1311 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1312 'refs/changes/56/123456/7'],), ''),
1313 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1314 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1315 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1316 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1317 ((['git', 'config', 'branch.master.merge'],), 'master'),
1318 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1319 ((['git', 'config', 'remote.origin.url'],),
1320 'https://chromium.googlesource.com/my/repo'),
1321 ((['git', 'config', 'branch.master.gerritserver',
1322 'https://chromium-review.googlesource.com'],), ''),
1323 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1324 ]
1325 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456']), 0)
1326
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001327 def test_gerrit_patch_url_successful(self):
1328 self._patch_common(is_gerrit=True)
1329 self.calls += [
1330 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1331 'refs/changes/56/123456/1'],), ''),
1332 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1333 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1334 ((['git', 'config', 'branch.master.gerritserver',
1335 'https://chromium-review.googlesource.com'],), ''),
1336 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1337 ]
1338 self.assertEqual(git_cl.main(
1339 ['patch', 'https://chromium-review.googlesource.com/#/c/123456/1']), 0)
1340
1341 def test_gerrit_patch_conflict(self):
1342 self._patch_common(is_gerrit=True)
1343 self.mock(git_cl, 'DieWithError',
1344 lambda msg: self._mocked_call(['DieWithError', msg]))
1345 class SystemExitMock(Exception):
1346 pass
1347 self.calls += [
1348 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1349 'refs/changes/56/123456/1'],), ''),
1350 ((['git', 'cherry-pick', 'FETCH_HEAD'],),
1351 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1352 ((['DieWithError', 'git cherry-pick FETCH_HEAD" failed.\n'],),
1353 '', SystemExitMock()),
1354 ]
1355 with self.assertRaises(SystemExitMock):
1356 git_cl.main(['patch',
1357 'https://chromium-review.googlesource.com/#/c/123456/1'])
1358
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001359 def _checkout_calls(self):
1360 return [
1361 ((['git', 'config', '--local', '--get-regexp',
1362 'branch\\..*\\.rietveldissue'], ),
1363 ('branch.retrying.rietveldissue 1111111111\n'
1364 'branch.some-fix.rietveldissue 2222222222\n')),
1365 ((['git', 'config', '--local', '--get-regexp',
1366 'branch\\..*\\.gerritissue'], ),
1367 ('branch.ger-branch.gerritissue 123456\n'
1368 'branch.gbranch654.gerritissue 654321\n')),
1369 ]
1370
1371 def test_checkout_gerrit(self):
1372 """Tests git cl checkout <issue>."""
1373 self.calls = self._checkout_calls()
1374 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1375 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1376
1377 def test_checkout_rietveld(self):
1378 """Tests git cl checkout <issue>."""
1379 self.calls = self._checkout_calls()
1380 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1381 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1382
1383 def test_checkout_not_found(self):
1384 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001385 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001386 self.calls = self._checkout_calls()
1387 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1388
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001389 def test_checkout_no_branch_issues(self):
1390 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001391 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001392 self.calls = [
1393 ((['git', 'config', '--local', '--get-regexp',
1394 'branch\\..*\\.rietveldissue'], ), '',
1395 subprocess2.CalledProcessError(1, '', '', '', '')),
1396 ((['git', 'config', '--local', '--get-regexp',
1397 'branch\\..*\\.gerritissue'], ), '',
1398 subprocess2.CalledProcessError(1, '', '', '', '')),
1399
1400 ]
1401 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1402
tandrii@chromium.org28253532016-04-14 13:46:56 +00001403 def _test_gerrit_ensure_authenticated_common(self, auth,
1404 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001405 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1406 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1407 self.mock(git_cl, 'DieWithError',
1408 lambda msg: self._mocked_call(['DieWithError', msg]))
1409 self.mock(git_cl, 'ask_for_data',
1410 lambda msg: self._mocked_call(['ask_for_data', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001411 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001412 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00001413 cl.branch = 'master'
1414 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001415 cl.lookedup_issue = True
1416 return cl
1417
1418 def test_gerrit_ensure_authenticated_missing(self):
1419 cl = self._test_gerrit_ensure_authenticated_common(auth={
1420 'chromium.googlesource.com': 'git is ok, but gerrit one is missing',
1421 })
1422 self.calls.append(
1423 ((['DieWithError',
1424 'Credentials for the following hosts are required:\n'
1425 ' chromium-review.googlesource.com\n'
1426 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1427 'You can (re)generate your credentails by visiting '
1428 'https://chromium-review.googlesource.com/new-password'],), ''),)
1429 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1430
1431 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001432 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001433 cl = self._test_gerrit_ensure_authenticated_common(auth={
1434 'chromium.googlesource.com': 'one',
1435 'chromium-review.googlesource.com': 'other',
1436 })
1437 self.calls.append(
1438 ((['ask_for_data', 'If you know what you are doing, '
1439 'press Enter to continue, Ctrl+C to abort.'],), ''))
1440 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1441
1442 def test_gerrit_ensure_authenticated_ok(self):
1443 cl = self._test_gerrit_ensure_authenticated_common(auth={
1444 'chromium.googlesource.com': 'same',
1445 'chromium-review.googlesource.com': 'same',
1446 })
1447 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1448
tandrii@chromium.org28253532016-04-14 13:46:56 +00001449 def test_gerrit_ensure_authenticated_skipped(self):
1450 cl = self._test_gerrit_ensure_authenticated_common(
1451 auth={}, skip_auth_check=True)
1452 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1453
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001454 def test_cmd_set_commit_rietveld(self):
1455 self.mock(git_cl._RietveldChangelistImpl, 'SetFlag',
1456 lambda _, f, v: self._mocked_call(['SetFlag', f, v]))
1457 self.calls = [
1458 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1459 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
1460 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1461 ((['git', 'config', 'rietveld.server'],), ''),
1462 ((['git', 'config', 'rietveld.server'],), ''),
1463 ((['git', 'config', 'branch.feature.rietveldserver'],),
1464 'https://codereview.chromium.org'),
1465 ((['SetFlag', 'commit', '1'], ), ''),
1466 ]
1467 self.assertEqual(0, git_cl.main(['set-commit']))
1468
1469 def test_cmd_set_commit_gerrit(self):
1470 self.mock(git_cl.gerrit_util, 'SetReview',
1471 lambda h, i, labels: self._mocked_call(
1472 ['SetReview', h, i, labels]))
1473 self.calls = [
1474 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1475 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1476 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1477 ((['git', 'config', 'branch.feature.gerritserver'],),
1478 'https://chromium-review.googlesource.com'),
1479 ((['SetReview', 'chromium-review.googlesource.com', 123,
1480 {'Commit-Queue': 1}],), ''),
1481 ]
tandrii@chromium.org1a8ef442016-04-13 18:41:37 +00001482 # TODO(tandrii): consider testing just set-commit and set-commit --clear,
1483 # but without copy-pasting tons of expectations, as modifying them later is
1484 # super tedious.
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001485 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1486
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001487 def test_description_display(self):
1488 out = StringIO.StringIO()
1489 self.mock(git_cl.sys, 'stdout', out)
1490
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001491 self.mock(git_cl, 'Changelist', ChangelistMock)
1492 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001493
1494 self.assertEqual(0, git_cl.main(['description', '-d']))
1495 self.assertEqual('foo\n', out.getvalue())
1496
1497 def test_description_rietveld(self):
1498 out = StringIO.StringIO()
1499 self.mock(git_cl.sys, 'stdout', out)
1500 self.mock(git_cl.Changelist, 'GetDescription',
1501 lambda *args: 'foobar')
1502
1503 self.calls = [
1504 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1505 ((['git', 'config', 'rietveld.server'],), ''),
1506 ((['git', 'config', 'rietveld.server'],), ''),
1507 ]
1508 self.assertEqual(0, git_cl.main([
1509 'description', 'https://code.review.org/123123', '-d', '--rietveld']))
1510 self.assertEqual('foobar\n', out.getvalue())
1511
1512 def test_description_gerrit(self):
1513 out = StringIO.StringIO()
1514 self.mock(git_cl.sys, 'stdout', out)
1515 self.mock(git_cl.Changelist, 'GetDescription',
1516 lambda *args: 'foobar')
1517
1518 self.assertEqual(0, git_cl.main([
1519 'description', 'https://code.review.org/123123', '-d', '--gerrit']))
1520 self.assertEqual('foobar\n', out.getvalue())
1521
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001522 def test_description_set_raw(self):
1523 out = StringIO.StringIO()
1524 self.mock(git_cl.sys, 'stdout', out)
1525
1526 self.mock(git_cl, 'Changelist', ChangelistMock)
1527 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
1528
1529 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1530 self.assertEqual('hihi', ChangelistMock.desc)
1531
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001532 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001533 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001534
1535 def RunEditor(desc, _, **kwargs):
1536 self.assertEquals(
1537 '# Enter a description of the change.\n'
1538 '# This will be displayed on the codereview site.\n'
1539 '# The first line will also be used as the subject of the review.\n'
1540 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001541 '--------------------\n'
1542 'Some.\n\nBUG=\n\nChange-Id: xxx',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001543 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001544 # Simulate user changing something.
1545 return 'Some.\n\nBUG=123\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001546
1547 def UpdateDescriptionRemote(_, desc):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001548 self.assertEquals(desc, 'Some.\n\nBUG=123\n\nChange-Id: xxx')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001549
1550 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1551 self.mock(git_cl.Changelist, 'GetDescription',
1552 lambda *args: current_desc)
1553 self.mock(git_cl._GerritChangelistImpl, 'UpdateDescriptionRemote',
1554 UpdateDescriptionRemote)
1555 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
1556
1557 self.calls = [
1558 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1559 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1560 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1561 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
1562 ((['git', 'config', 'core.editor'],), 'vi'),
1563 ]
1564 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
1565
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001566 def test_description_set_stdin(self):
1567 out = StringIO.StringIO()
1568 self.mock(git_cl.sys, 'stdout', out)
1569
1570 self.mock(git_cl, 'Changelist', ChangelistMock)
1571 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
1572
1573 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1574 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1575
kmarshall3bff56b2016-06-06 18:31:47 -07001576 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07001577 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1578
kmarshall3bff56b2016-06-06 18:31:47 -07001579 self.calls = \
1580 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1581 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1582 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1583 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1584 ((['git', 'config', 'rietveld.server'],), ''),
1585 ((['git', 'config', 'rietveld.server'],), ''),
1586 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
1587 ((['git', 'config', 'rietveld.server'],), ''),
1588 ((['git', 'config', 'rietveld.server'],), ''),
1589 ((['git', 'config', 'branch.bar.rietveldissue'],), ''),
1590 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
1591 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1592 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
1593 ((['git', 'branch', '-D', 'foo'],), '')]
1594
1595 class MockChangelist():
1596 def __init__(self, branch, issue):
1597 self.branch = branch
1598 self.issue = issue
1599 def GetBranch(self):
1600 return self.branch
1601 def GetIssue(self):
1602 return self.issue
1603
1604 self.mock(git_cl, 'get_cl_statuses',
1605 lambda branches, fine_grained, max_processes:
1606 [(MockChangelist('master', 1), 'open'),
1607 (MockChangelist('foo', 456), 'closed'),
1608 (MockChangelist('bar', 789), 'open')])
1609
1610 self.assertEqual(0, git_cl.main(['archive', '-f']))
1611
1612 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07001613 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
kmarshall3bff56b2016-06-06 18:31:47 -07001614 self.calls = \
1615 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1616 'refs/heads/master'),
1617 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1618 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1619 ((['git', 'config', 'rietveld.server'],), ''),
1620 ((['git', 'config', 'rietveld.server'],), ''),
1621 ((['git', 'symbolic-ref', 'HEAD'],), 'master')]
1622
1623 class MockChangelist():
1624 def __init__(self, branch, issue):
1625 self.branch = branch
1626 self.issue = issue
1627 def GetBranch(self):
1628 return self.branch
1629 def GetIssue(self):
1630 return self.issue
1631
1632 self.mock(git_cl, 'get_cl_statuses',
1633 lambda branches, fine_grained, max_processes:
1634 [(MockChangelist('master', 1), 'closed')])
1635
1636 self.assertEqual(1, git_cl.main(['archive', '-f']))
1637
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00001638 def test_cmd_issue_erase_existing(self):
1639 out = StringIO.StringIO()
1640 self.mock(git_cl.sys, 'stdout', out)
1641 self.calls = [
1642 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1643 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1644 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1645 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
1646 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
1647 # Let this command raise exception (retcode=1) - it should be ignored.
1648 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
1649 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1650 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
1651 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
1652 ''),
1653 ]
1654 self.assertEqual(0, git_cl.main(['issue', '0']))
1655
tandrii16e0b4e2016-06-07 10:34:28 -07001656 def _common_GerritCommitMsgHookCheck(self):
1657 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1658 self.mock(git_cl.os.path, 'abspath',
1659 lambda path: self._mocked_call(['abspath', path]))
1660 self.mock(git_cl.os.path, 'exists',
1661 lambda path: self._mocked_call(['exists', path]))
1662 self.mock(git_cl.gclient_utils, 'FileRead',
1663 lambda path: self._mocked_call(['FileRead', path]))
1664 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
1665 lambda path: self._mocked_call(['rm_file_or_tree', path]))
1666 self.calls = [
1667 ((['git', 'rev-parse', '--show-cdup'],), '../'),
1668 ((['abspath', '../'],), '/abs/git_repo_root'),
1669 ]
1670 return git_cl.Changelist(codereview='gerrit', issue=123)
1671
1672 def test_GerritCommitMsgHookCheck_custom_hook(self):
1673 cl = self._common_GerritCommitMsgHookCheck()
1674 self.calls += [
1675 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1676 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1677 '#!/bin/sh\necho "custom hook"')
1678 ]
1679 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1680
1681 def test_GerritCommitMsgHookCheck_not_exists(self):
1682 cl = self._common_GerritCommitMsgHookCheck()
1683 self.calls += [
1684 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
1685 ]
1686 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1687
1688 def test_GerritCommitMsgHookCheck(self):
1689 cl = self._common_GerritCommitMsgHookCheck()
1690 self.calls += [
1691 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1692 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1693 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
1694 (('Do you want to remove it now? [Yes/No]',), 'Yes'),
1695 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1696 ''),
1697 ]
1698 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1699
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001700
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001701if __name__ == '__main__':
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001702 git_cl.logging.basicConfig(
1703 level=git_cl.logging.DEBUG if '-v' in sys.argv else git_cl.logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001704 unittest.main()