blob: c500b815323a9ceb0dec3205af4faf258237564d [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
tandriif9aefb72016-07-01 09:06:51 -0700211 def test_get_bug_line_values(self):
212 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
213 self.assertEqual(f('', ''), [])
214 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
215 self.assertEqual(f('v8', '456'), ['v8:456'])
216 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
217 # Not nice, but not worth carying.
218 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
219 ['v8:456', 'chromium:123', 'v8:123'])
220
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000221
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000222class TestGitCl(TestCase):
223 def setUp(self):
224 super(TestGitCl, self).setUp()
225 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700226 self._calls_done = []
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000227 self.mock(subprocess2, 'call', self._mocked_call)
228 self.mock(subprocess2, 'check_call', self._mocked_call)
229 self.mock(subprocess2, 'check_output', self._mocked_call)
230 self.mock(subprocess2, 'communicate', self._mocked_call)
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000231 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000232 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000233 self.mock(git_common, 'get_or_create_merge_base',
234 lambda *a: (
235 self._mocked_call(['get_or_create_merge_base']+list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000236 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000237 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000238 self.mock(git_cl, 'ask_for_data', self._mocked_call)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000239 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000240 self.mock(git_cl.rietveld, 'Rietveld', RietveldMock)
maruel@chromium.org4bac4b52012-11-27 20:33:52 +0000241 self.mock(git_cl.rietveld, 'CachingRietveld', RietveldMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000242 self.mock(git_cl.upload, 'RealMain', self.fail)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000243 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000244 self.mock(git_cl.auth, 'get_authenticator_for_host', AuthenticatorMock)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000245 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
246 classmethod(lambda _: False))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000247 # It's important to reset settings to not have inter-tests interference.
248 git_cl.settings = None
249
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000250
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000251 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000252 try:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000253 # Note: has_failed returns True if at least 1 test ran so far, current
254 # included, has failed. That means current test may have actually ran
255 # fine, and the check for no leftover calls would be skipped.
wychen@chromium.org445c8962015-04-28 23:30:05 +0000256 if not self.has_failed():
257 self.assertEquals([], self.calls)
258 finally:
259 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000260
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000261 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000262 self.assertTrue(
263 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700264 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000265 top = self.calls.pop(0)
266 if len(top) > 2 and top[2]:
267 raise top[2]
268 expected_args, result = top
269
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000270 # Also logs otherwise it could get caught in a try/finally and be hard to
271 # diagnose.
272 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700273 N = 5
274 prior_calls = '\n '.join(
275 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
276 for i, c in enumerate(self._calls_done[-N:]))
277 following_calls = '\n '.join(
278 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
279 for i, c in enumerate(self.calls[:N]))
280 extended_msg = (
281 'A few prior calls:\n %s\n\n'
282 'This (expected):\n @%d: %r\n'
283 'This (actual):\n @%d: %r\n\n'
284 'A few following expected calls:\n %s' %
285 (prior_calls, len(self._calls_done), expected_args,
286 len(self._calls_done), args, following_calls))
287 git_cl.logging.error(extended_msg)
288
289 self.fail('@%d Expected: %r Actual: %r' % (
290 len(self._calls_done), expected_args, args))
291
292 self._calls_done.append(top)
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000293 return result
294
maruel@chromium.orga3353652011-11-30 14:26:57 +0000295 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000296 def _is_gerrit_calls(cls, gerrit=False):
297 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
298 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
299
300 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000301 def _upload_calls(cls, similarity, find_copies, private):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000302 return (cls._git_base_calls(similarity, find_copies) +
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000303 cls._git_upload_calls(private))
maruel@chromium.orga3353652011-11-30 14:26:57 +0000304
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000305 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000306 def _upload_no_rev_calls(cls, similarity, find_copies):
307 return (cls._git_base_calls(similarity, find_copies) +
308 cls._git_upload_no_rev_calls())
309
310 @classmethod
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000311 def _git_base_calls(cls, similarity, find_copies):
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000312 if similarity is None:
313 similarity = '50'
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000314 similarity_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000315 'branch.master.git-cl-similarity'],), '')
316 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000317 similarity_call = ((['git', 'config', '--int',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000318 'branch.master.git-cl-similarity', similarity],), '')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000319
320 if find_copies is None:
321 find_copies = True
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000322 find_copies_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000323 'branch.master.git-find-copies'],), '')
324 else:
325 val = str(int(find_copies))
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000326 find_copies_call = ((['git', 'config', '--int',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000327 'branch.master.git-find-copies', val],), '')
328
329 if find_copies:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000330 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000331 '--find-copies-harder', '-l100000', '-C'+similarity,
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000332 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000333 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000334 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000335 '-M'+similarity, 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000336
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000337 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000338 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000339 similarity_call,
340 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
341 find_copies_call,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000342 ] + cls._is_gerrit_calls() + [
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000343 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000344 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
345 ((['git', 'config', 'branch.master.gerritissue'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000346 ((['git', 'config', 'rietveld.server'],),
347 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000348 ((['git', 'config', 'branch.master.merge'],), 'master'),
349 ((['git', 'config', 'branch.master.remote'],), 'origin'),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000350 ((['get_or_create_merge_base', 'master', 'master'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000351 'fake_ancestor_sha'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000352 ] + cls._git_sanity_checks('fake_ancestor_sha', 'master') + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000353 ((['git', 'rev-parse', '--show-cdup'],), ''),
354 ((['git', 'rev-parse', 'HEAD'],), '12345'),
355 ((['git', 'diff', '--name-status', '--no-renames', '-r',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000356 'fake_ancestor_sha...', '.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000357 'M\t.gitignore\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000358 ((['git', 'config', 'branch.master.rietveldpatchset'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000359 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000360 ((['git', 'log', '--pretty=format:%s%n%n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000361 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000362 'foo'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000363 ((['git', 'config', 'user.email'],), 'me@example.com'),
iannucci@chromium.org79540052012-10-19 23:15:26 +0000364 stat_call,
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000365 ((['git', 'log', '--pretty=format:%s\n\n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000366 'fake_ancestor_sha..HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000367 'desc\n'),
rmistry@google.com90752582014-01-14 21:04:50 +0000368 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
maruel@chromium.orga3353652011-11-30 14:26:57 +0000369 ]
370
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000371 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000372 def _git_upload_no_rev_calls(cls):
373 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000374 ((['git', 'config', 'core.editor'],), ''),
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000375 ]
376
377 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000378 def _git_upload_calls(cls, private):
379 if private:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000380 cc_call = []
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000381 private_call = []
382 else:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000383 cc_call = [((['git', 'config', 'rietveld.cc'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000384 private_call = [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000385 ((['git', 'config', 'rietveld.private'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000386
maruel@chromium.orga3353652011-11-30 14:26:57 +0000387 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000388 ((['git', 'config', 'core.editor'],), ''),
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000389 ] + cc_call + private_call + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000390 ((['git', 'config', 'branch.master.base-url'],), ''),
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000391 ((['git', 'config', 'rietveld.pending-ref-prefix'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000392 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000393 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
394 (('', None), 0)),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000395 ((['git', 'rev-parse', '--show-cdup'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000396 ((['git', 'svn', 'info'],), ''),
sheyang@chromium.org152cf832014-06-11 21:37:49 +0000397 ((['git', 'config', 'rietveld.project'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000398 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000399 'config', 'branch.master.rietveldissue', '1'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000400 ((['git', 'config', 'branch.master.rietveldserver',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000401 'https://codereview.example.com'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000402 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000403 'config', 'branch.master.rietveldpatchset', '2'],), ''),
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000404 ] + cls._git_post_upload_calls()
405
406 @classmethod
407 def _git_post_upload_calls(cls):
408 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000409 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
410 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
411 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000412 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000413 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000414 ]
415
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000416 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000417 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000418 fake_ancestor = 'fake_ancestor'
419 fake_cl = 'fake_cl_for_patch'
420 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000421 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000422 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000423 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000424 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000425 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000426 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000427 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000428 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000429 'config', 'gitcl.remotebranch'],), (('', None), 1)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000430 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000431 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000432 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000433 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000434 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000435 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000436 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000437 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000438 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000439 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000440 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000441
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000442 @classmethod
443 def _dcommit_calls_1(cls):
444 return [
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000445 ((['git', 'config', 'rietveld.autoupdate'],),
446 ''),
447 ((['git', 'config', 'rietveld.pending-ref-prefix'],),
448 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000449 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000450 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000451 ((('svn-remote.svn.url svn://svn.chromium.org/chrome\n'
452 'svn-remote.svn.fetch trunk/src:refs/remotes/origin/master'),
453 None),
454 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000455 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
456 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000457 'branch.working.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000458 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
459 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000460 'branch.working.git-find-copies'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000461 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
462 ((['git',
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000463 'config', 'branch.working.rietveldissue'],), '12345'),
464 ((['git',
465 'config', 'rietveld.server'],), 'codereview.example.com'),
466 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000467 'config', 'branch.working.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000468 ((['git', 'config', 'branch.working.remote'],), 'origin'),
iannucci@chromium.org5724c962014-04-11 09:32:56 +0000469 ((['git', 'config', 'branch.working.merge'],),
470 'refs/heads/master'),
471 ((['git', 'config', 'branch.working.remote'],), 'origin'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000472 ((['git', 'rev-list', '--merges',
szager@chromium.orge84b7542012-06-15 21:26:58 +0000473 '--grep=^SVN changes up to revision [0-9]*$',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000474 'refs/remotes/origin/master^!'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000475 ((['git', 'rev-list', '^refs/heads/working',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000476 'refs/remotes/origin/master'],),
477 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000478 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000479 'log', '--grep=^git-svn-id:', '-1', '--pretty=format:%H'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000480 '3fc18b62c4966193eb435baabe2d18a3810ec82e'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000481 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000482 'rev-list', '^3fc18b62c4966193eb435baabe2d18a3810ec82e',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000483 'refs/remotes/origin/master'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000484 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000485 'merge-base', 'refs/remotes/origin/master', 'HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000486 'fake_ancestor_sha'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000487 ]
488
489 @classmethod
490 def _dcommit_calls_normal(cls):
491 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000492 ((['git', 'rev-parse', '--show-cdup'],), ''),
493 ((['git', 'rev-parse', 'HEAD'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000494 '00ff397798ea57439712ed7e04ab96e13969ef40'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000495 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000496 'diff', '--name-status', '--no-renames', '-r', 'fake_ancestor_sha...',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000497 '.'],),
498 'M\tPRESUBMIT.py'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000499 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000500 'config', 'branch.working.rietveldpatchset'],), '31137'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000501 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000502 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000503 ((['git', 'config', 'user.email'],), 'author@example.com'),
504 ((['git', 'config', 'rietveld.tree-status-url'],), ''),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000505 ]
506
507 @classmethod
508 def _dcommit_calls_bypassed(cls):
509 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000510 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000511 'codereview.example.com'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000512 ]
513
514 @classmethod
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000515 def _dcommit_calls_3(cls):
516 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000517 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000518 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000519 '-l100000', '-C50', 'fake_ancestor_sha',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000520 'refs/heads/working'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000521 (' PRESUBMIT.py | 2 +-\n'
522 ' 1 files changed, 1 insertions(+), 1 deletions(-)\n')),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000523 ((['git', 'show-ref', '--quiet', '--verify',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000524 'refs/heads/git-cl-commit'],),
525 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000526 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
527 ((['git', 'show-ref', '--quiet', '--verify',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000528 'refs/heads/git-cl-cherry-pick'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000529 ((['git', 'rev-parse', '--show-cdup'],), '\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000530 ((['git', 'checkout', '-q', '-b', 'git-cl-commit'],), ''),
531 ((['git', 'reset', '--soft', 'fake_ancestor_sha'],), ''),
532 ((['git', 'commit', '-m',
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000533 'Issue: 12345\n\nR=john@chromium.org\n\n'
sergiyb@chromium.org4b39c5f2015-07-07 10:33:12 +0000534 'Review URL: https://codereview.example.com/12345 .'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000535 ''),
kjellander@chromium.org6abc6522014-12-02 07:34:49 +0000536 ((['git', 'config', 'rietveld.force-https-commit-url'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000537 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000538 'svn', 'dcommit', '-C50', '--no-rebase', '--rmdir'],),
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000539 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000540 ((['git', 'checkout', '-q', 'working'],), ''),
541 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000542 ]
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000543
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000544 @staticmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000545 def _cmd_line(description, args, similarity, find_copies, private):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000546 """Returns the upload command line passed to upload.RealMain()."""
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000547 return [
548 'upload', '--assume_yes', '--server',
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +0000549 'https://codereview.example.com',
maruel@chromium.org71e12a92012-02-14 02:34:15 +0000550 '--message', description
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000551 ] + args + [
552 '--cc', 'joe@example.com',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000553 ] + (['--private'] if private else []) + [
iannucci@chromium.org79540052012-10-19 23:15:26 +0000554 '--git_similarity', similarity or '50'
555 ] + (['--git_no_find_copies'] if find_copies == False else []) + [
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000556 'fake_ancestor_sha', 'HEAD'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000557 ]
558
559 def _run_reviewer_test(
560 self,
561 upload_args,
562 expected_description,
563 returned_description,
564 final_description,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000565 reviewers,
566 private=False):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000567 """Generic reviewer test framework."""
tandrii@chromium.org28253532016-04-14 13:46:56 +0000568 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000569 try:
570 similarity = upload_args[upload_args.index('--similarity')+1]
571 except ValueError:
572 similarity = None
iannucci@chromium.org79540052012-10-19 23:15:26 +0000573
574 if '--find-copies' in upload_args:
575 find_copies = True
576 elif '--no-find-copies' in upload_args:
577 find_copies = False
578 else:
579 find_copies = None
580
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000581 private = '--private' in upload_args
582
583 self.calls = self._upload_calls(similarity, find_copies, private)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000584
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000585 def RunEditor(desc, _, **kwargs):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000586 self.assertEquals(
587 '# Enter a description of the change.\n'
janx@chromium.org104b2db2013-04-18 12:58:40 +0000588 '# This will be displayed on the codereview site.\n'
alancutter@chromium.org63a4d7f2013-05-31 02:22:45 +0000589 '# The first line will also be used as the subject of the review.\n'
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +0000590 '#--------------------This line is 72 characters long'
591 '--------------------\n' +
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000592 expected_description,
593 desc)
594 return returned_description
595 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000596
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000597 def check_upload(args):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000598 cmd_line = self._cmd_line(final_description, reviewers, similarity,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000599 find_copies, private)
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000600 self.assertEquals(cmd_line, args)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000601 return 1, 2
602 self.mock(git_cl.upload, 'RealMain', check_upload)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000603
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000604 git_cl.main(['upload'] + upload_args)
605
606 def test_no_reviewer(self):
607 self._run_reviewer_test(
608 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000609 'desc\n\nBUG=',
610 '# Blah blah comment.\ndesc\n\nBUG=',
611 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000612 [])
613
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000614 def test_keep_similarity(self):
615 self._run_reviewer_test(
616 ['--similarity', '70'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000617 'desc\n\nBUG=',
618 '# Blah blah comment.\ndesc\n\nBUG=',
619 'desc\n\nBUG=',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000620 [])
621
iannucci@chromium.org79540052012-10-19 23:15:26 +0000622 def test_keep_find_copies(self):
623 self._run_reviewer_test(
624 ['--no-find-copies'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000625 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000626 '# Blah blah comment.\ndesc\n\nBUG=\n',
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000627 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000628 [])
629
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000630 def test_private(self):
631 self._run_reviewer_test(
632 ['--private'],
633 'desc\n\nBUG=',
634 '# Blah blah comment.\ndesc\n\nBUG=\n',
635 'desc\n\nBUG=',
636 [])
637
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000638 def test_reviewers_cmd_line(self):
639 # Reviewer is passed as-is
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000640 description = 'desc\n\nR=foo@example.com\nBUG='
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000641 self._run_reviewer_test(
642 ['-r' 'foo@example.com'],
643 description,
644 '\n%s\n' % description,
645 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000646 ['--reviewers=foo@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000647
648 def test_reviewer_tbr_overriden(self):
649 # Reviewer is overriden with TBR
650 # Also verifies the regexp work without a trailing LF
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000651 description = 'Foo Bar\n\nTBR=reviewer@example.com'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000652 self._run_reviewer_test(
653 ['-r' 'foo@example.com'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000654 'desc\n\nR=foo@example.com\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000655 description.strip('\n'),
656 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000657 ['--reviewers=reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000658
659 def test_reviewer_multiple(self):
660 # Handles multiple R= or TBR= lines.
661 description = (
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000662 'Foo Bar\nTBR=reviewer@example.com\nBUG=\nR=another@example.com')
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000663 self._run_reviewer_test(
664 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000665 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000666 description,
667 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000668 ['--reviewers=another@example.com,reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000669
maruel@chromium.orga3353652011-11-30 14:26:57 +0000670 def test_reviewer_send_mail(self):
671 # --send-mail can be used without -r if R= is used
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000672 description = 'Foo Bar\nR=reviewer@example.com'
maruel@chromium.orga3353652011-11-30 14:26:57 +0000673 self._run_reviewer_test(
674 ['--send-mail'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000675 'desc\n\nBUG=',
maruel@chromium.orga3353652011-11-30 14:26:57 +0000676 description.strip('\n'),
677 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000678 ['--reviewers=reviewer@example.com', '--send_mail'])
maruel@chromium.orga3353652011-11-30 14:26:57 +0000679
680 def test_reviewer_send_mail_no_rev(self):
681 # Fails without a reviewer.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000682 stdout = StringIO.StringIO()
683 stderr = StringIO.StringIO()
maruel@chromium.orga3353652011-11-30 14:26:57 +0000684 try:
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000685 self.calls = self._upload_no_rev_calls(None, None)
686 def RunEditor(desc, _, **kwargs):
maruel@chromium.orga3353652011-11-30 14:26:57 +0000687 return desc
688 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000689 self.mock(sys, 'stdout', stdout)
690 self.mock(sys, 'stderr', stderr)
maruel@chromium.orga3353652011-11-30 14:26:57 +0000691 git_cl.main(['upload', '--send-mail'])
692 self.fail()
693 except SystemExit:
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000694 self.assertEqual(
695 'Using 50% similarity for rename/copy detection. Override with '
696 '--similarity.\n',
697 stdout.getvalue())
698 self.assertEqual(
699 'Must specify reviewers to send email.\n', stderr.getvalue())
maruel@chromium.orga3353652011-11-30 14:26:57 +0000700
tandriif9aefb72016-07-01 09:06:51 -0700701 def test_bug_on_cmd(self):
702 self._run_reviewer_test(
703 ['--bug=500658,proj:123'],
704 'desc\n\nBUG=500658\nBUG=proj:123',
705 '# Blah blah comment.\ndesc\n\nBUG=500658\nBUG=proj:1234',
706 'desc\n\nBUG=500658\nBUG=proj:1234',
707 [])
708
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000709 def test_dcommit(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000710 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000711 self.calls = (
712 self._dcommit_calls_1() +
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000713 self._git_sanity_checks('fake_ancestor_sha', 'working') +
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000714 self._dcommit_calls_normal() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000715 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000716 git_cl.main(['dcommit'])
717
718 def test_dcommit_bypass_hooks(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000719 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000720 self.calls = (
721 self._dcommit_calls_1() +
722 self._dcommit_calls_bypassed() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000723 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000724 git_cl.main(['dcommit', '--bypass-hooks'])
725
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000726
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000727 @classmethod
tandrii@chromium.org28253532016-04-14 13:46:56 +0000728 def _gerrit_ensure_auth_calls(cls, issue=None, skip_auth_check=False):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000729 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000730 if skip_auth_check:
731 return [((cmd, ), 'true')]
732
733 calls = [((cmd, ), '', subprocess2.CalledProcessError(1, '', '', '', ''))]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000734 if issue:
735 calls.extend([
736 ((['git', 'config', 'branch.master.gerritserver'],), ''),
737 ])
738 calls.extend([
739 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
740 ((['git', 'config', 'branch.master.remote'],), 'origin'),
741 ((['git', 'config', 'remote.origin.url'],),
742 'https://chromium.googlesource.com/my/repo'),
743 ((['git', 'config', 'remote.origin.url'],),
744 'https://chromium.googlesource.com/my/repo'),
745 ])
746 return calls
747
748 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000749 def _gerrit_base_calls(cls, issue=None):
ukai@chromium.orge8077812012-02-03 03:41:46 +0000750 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000751 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
752 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000753 'branch.master.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000754 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
755 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000756 'branch.master.git-find-copies'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000757 ] + cls._is_gerrit_calls(True) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000758 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000759 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000760 ((['git', 'config', 'branch.master.gerritissue'],),
761 '' if issue is None else str(issue)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000762 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000763 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000764 ((['get_or_create_merge_base', 'master',
765 'refs/remotes/origin/master'],),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000766 'fake_ancestor_sha'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000767 # Calls to verify branch point is ancestor
768 ] + (cls._gerrit_ensure_auth_calls(issue=issue) +
769 cls._git_sanity_checks('fake_ancestor_sha', 'master',
770 get_remote_branch=False)) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000771 ((['git', 'rev-parse', '--show-cdup'],), ''),
772 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000773
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000774 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000775 'diff', '--name-status', '--no-renames', '-r',
776 'fake_ancestor_sha...', '.'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000777 'M\t.gitignore\n'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000778 ((['git', 'config', 'branch.master.gerritpatchset'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000779 ] + ([] if issue else [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000780 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000781 'log', '--pretty=format:%s%n%n%b', 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000782 'foo'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000783 ]) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000784 ((['git', 'config', 'user.email'],), 'me@example.com'),
785 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000786 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000787 '-l100000', '-C50', 'fake_ancestor_sha', 'HEAD'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000788 '+dat'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000789 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000790
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000791 @classmethod
792 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700793 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000794 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000795 ref_suffix='', notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000796 post_amend_description=None, issue=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000797 if post_amend_description is None:
798 post_amend_description = description
tandriia60502f2016-06-20 02:01:53 -0700799 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000800
tandriia60502f2016-06-20 02:01:53 -0700801 if squash_mode == 'default':
802 calls.extend([
803 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
804 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
805 ])
806 elif squash_mode in ('override_squash', 'override_nosquash'):
807 calls.extend([
808 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
809 'true' if squash_mode == 'override_squash' else 'false'),
810 ])
811 else:
812 assert squash_mode in ('squash', 'nosquash')
813
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000814 # If issue is given, then description is fetched from Gerrit instead.
815 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000816 calls += [
817 ((['git', 'log', '--pretty=format:%s\n\n%b',
818 'fake_ancestor_sha..HEAD'],),
819 description)]
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000820 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000821 calls += [
tandrii@chromium.org10625002016-03-04 20:03:47 +0000822 # DownloadGerritHook(False)
823 ((False, ),
824 ''),
825 # Amending of commit message to get the Change-Id.
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000826 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000827 'fake_ancestor_sha..HEAD'],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000828 description),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000829 ((['git', 'commit', '--amend', '-m', description],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000830 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000831 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000832 'fake_ancestor_sha..HEAD'],),
tandrii@chromium.org10625002016-03-04 20:03:47 +0000833 post_amend_description)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000834 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000835 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000836 if not issue:
837 # Prompting to edit description on first upload.
838 calls += [
839 ((['git', 'config', 'core.editor'],), ''),
840 ((['RunEditor'],), description),
841 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000842 ref_to_push = 'abcdef0123456789'
843 calls += [
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000844 ((['git', 'config', 'branch.master.merge'],),
845 'refs/heads/master'),
846 ((['git', 'config', 'branch.master.remote'],),
847 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000848 ((['get_or_create_merge_base', 'master',
849 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000850 'origin/master'),
851 ((['git', 'rev-parse', 'HEAD:'],),
852 '0123456789abcdef'),
853 ((['git', 'commit-tree', '0123456789abcdef', '-p',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000854 'origin/master', '-m', description],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000855 ref_to_push),
856 ]
857 else:
858 ref_to_push = 'HEAD'
859
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000860 calls += [
luqui@chromium.org609f3952015-05-04 22:47:04 +0000861 ((['git', 'rev-list',
862 expected_upstream_ref + '..' + ref_to_push],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000863 ((['git', 'config', 'rietveld.cc'],), '')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000864 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000865
866 notify_suffix = 'notify=%s' % ('ALL' if notify else 'NONE')
867 if ref_suffix:
868 ref_suffix += ',' + notify_suffix
869 else:
870 ref_suffix = '%' + notify_suffix
tandrii@chromium.org074c2af2016-06-03 23:18:40 +0000871
872 # Add cc from watch list.
873 ref_suffix += ',cc=joe@example.com'
874
ukai@chromium.orge8077812012-02-03 03:41:46 +0000875 if reviewers:
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000876 ref_suffix += ',' + ','.join('r=%s' % email
877 for email in sorted(reviewers))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000878 calls += [
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000879 ((['git', 'push', 'origin',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000880 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000881 ('remote:\n'
882 'remote: Processing changes: (\)\n'
883 'remote: Processing changes: (|)\n'
884 'remote: Processing changes: (/)\n'
885 'remote: Processing changes: (-)\n'
886 'remote: Processing changes: new: 1 (/)\n'
887 'remote: Processing changes: new: 1, done\n'
888 'remote:\n'
889 'remote: New Changes:\n'
890 'remote: https://chromium-review.googlesource.com/123456 XXX.\n'
891 'remote:\n'
892 'To https://chromium.googlesource.com/yyy/zzz\n'
893 ' * [new branch] hhhh -> refs/for/refs/heads/master\n')),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000894 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000895 if squash:
896 calls += [
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000897 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000898 ((['git', 'config', 'branch.master.gerritserver',
899 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000900 ((['git', 'config', 'branch.master.gerritsquashhash',
901 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000902 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000903 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +0000904 return calls
905
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000906 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000907 self,
908 upload_args,
909 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000910 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700911 squash=True,
912 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000913 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000914 ref_suffix='',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000915 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000916 post_amend_description=None,
917 issue=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000918 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700919 if squash_mode is None:
920 if '--no-squash' in upload_args:
921 squash_mode = 'nosquash'
922 elif '--squash' in upload_args:
923 squash_mode = 'squash'
924 else:
925 squash_mode = 'default'
926
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000927 reviewers = reviewers or []
tandrii@chromium.org28253532016-04-14 13:46:56 +0000928 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -0700929 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000930 CookiesAuthenticatorMockFactory(same_cookie='same_cred'))
tandrii16e0b4e2016-06-07 10:34:28 -0700931 self.mock(git_cl._GerritChangelistImpl, '_GerritCommitMsgHookCheck',
932 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -0700933 self.mock(git_cl.gclient_utils, 'RunEditor',
934 lambda *_, **__: self._mocked_call(['RunEditor']))
935 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
936
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000937 self.calls = self._gerrit_base_calls(issue=issue)
luqui@chromium.org609f3952015-05-04 22:47:04 +0000938 self.calls += self._gerrit_upload_calls(
939 description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700940 squash_mode=squash_mode,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000941 expected_upstream_ref=expected_upstream_ref,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000942 ref_suffix=ref_suffix, notify=notify,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000943 post_amend_description=post_amend_description,
944 issue=issue)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000945 # Uncomment when debugging.
946 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000947 git_cl.main(['upload'] + upload_args)
948
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000949 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -0700950 self._run_gerrit_upload_test(
951 ['--no-squash'],
952 'desc\n\nBUG=\n',
953 [],
954 squash=False,
955 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
956
957 def test_gerrit_upload_without_change_id_override_nosquash(self):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000958 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000959 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000960 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +0000961 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000962 [],
tandriia60502f2016-06-20 02:01:53 -0700963 squash=False,
964 squash_mode='override_nosquash',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000965 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000966
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000967 def test_gerrit_no_reviewer(self):
968 self._run_gerrit_upload_test(
969 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000970 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700971 [],
972 squash=False,
973 squash_mode='override_nosquash')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000974
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000975 def test_gerrit_patch_title(self):
976 self._run_gerrit_upload_test(
977 ['-t', 'Don\'t put under_scores as they become spaces'],
978 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandriia60502f2016-06-20 02:01:53 -0700979 squash=False,
980 squash_mode='override_nosquash',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000981 ref_suffix='%m=Don\'t_put_under_scores_as_they_become_spaces')
982
ukai@chromium.orge8077812012-02-03 03:41:46 +0000983 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000984 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000985 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000986 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000987 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -0700988 squash=False,
989 squash_mode='override_nosquash',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000990 notify=True)
ukai@chromium.orge8077812012-02-03 03:41:46 +0000991
992 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000993 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000994 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000995 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n\n'
996 'Change-Id: 123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700997 ['reviewer@example.com', 'another@example.com'],
998 squash=False,
999 squash_mode='override_nosquash')
1000
1001 def test_gerrit_upload_squash_first_is_default(self):
1002 # Mock Gerrit CL description to indicate the first upload.
1003 self.mock(git_cl.Changelist, 'GetDescription',
1004 lambda *_: None)
1005 self._run_gerrit_upload_test(
1006 [],
1007 'desc\nBUG=\n\nChange-Id: 123456789',
1008 [],
1009 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001010
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001011 def test_gerrit_upload_squash_first(self):
1012 # Mock Gerrit CL description to indicate the first upload.
1013 self.mock(git_cl.Changelist, 'GetDescription',
1014 lambda *_: None)
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001015 self._run_gerrit_upload_test(
1016 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001017 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001018 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001019 squash=True,
1020 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001021
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001022 def test_gerrit_upload_squash_reupload(self):
1023 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1024 # Mock Gerrit CL description to indicate re-upload.
1025 self.mock(git_cl.Changelist, 'GetDescription',
1026 lambda *args: description)
1027 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
1028 lambda *args: 1)
1029 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1030 lambda *args: {'change_id': '123456789'})
1031 self._run_gerrit_upload_test(
1032 ['--squash'],
1033 description,
1034 [],
1035 squash=True,
1036 expected_upstream_ref='origin/master',
1037 issue=123456)
1038
rmistry@google.com2dd99862015-06-22 12:22:18 +00001039 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001040 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001041 def mock_run_git(*args, **_kwargs):
1042 if args[0] == ['for-each-ref',
1043 '--format=%(refname:short) %(upstream:short)',
1044 'refs/heads']:
1045 # Create a local branch dependency tree that looks like this:
1046 # test1 -> test2 -> test3 -> test4 -> test5
1047 # -> test3.1
1048 # test6 -> test0
1049 branch_deps = [
1050 'test2 test1', # test1 -> test2
1051 'test3 test2', # test2 -> test3
1052 'test3.1 test2', # test2 -> test3.1
1053 'test4 test3', # test3 -> test4
1054 'test5 test4', # test4 -> test5
1055 'test6 test0', # test0 -> test6
1056 'test7', # test7
1057 ]
1058 return '\n'.join(branch_deps)
1059 self.mock(git_cl, 'RunGit', mock_run_git)
1060
1061 class RecordCalls:
1062 times_called = 0
1063 record_calls = RecordCalls()
1064 def mock_CMDupload(*args, **_kwargs):
1065 record_calls.times_called += 1
1066 return 0
1067 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1068
1069 self.calls = [
1070 (('[Press enter to continue or ctrl-C to quit]',), ''),
1071 ]
1072
1073 class MockChangelist():
1074 def __init__(self):
1075 pass
1076 def GetBranch(self):
1077 return 'test1'
1078 def GetIssue(self):
1079 return '123'
1080 def GetPatchset(self):
1081 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001082 def IsGerrit(self):
1083 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001084
1085 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1086 # CMDupload should have been called 5 times because of 5 dependent branches.
1087 self.assertEquals(5, record_calls.times_called)
1088 self.assertEquals(0, ret)
1089
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001090 def test_gerrit_change_id(self):
1091 self.calls = [
1092 ((['git', 'write-tree'], ),
1093 'hashtree'),
1094 ((['git', 'rev-parse', 'HEAD~0'], ),
1095 'branch-parent'),
1096 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1097 'A B <a@b.org> 1456848326 +0100'),
1098 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1099 'C D <c@d.org> 1456858326 +0100'),
1100 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1101 'hashchange'),
1102 ]
1103 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1104 self.assertEqual(change_id, 'Ihashchange')
1105
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001106 def test_desecription_append_footer(self):
1107 for init_desc, footer_line, expected_desc in [
1108 # Use unique desc first lines for easy test failure identification.
1109 ('foo', 'R=one', 'foo\n\nR=one'),
1110 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1111 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1112 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1113 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1114 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1115 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1116 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1117 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1118 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1119 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1120 ]:
1121 desc = git_cl.ChangeDescription(init_desc)
1122 desc.append_footer(footer_line)
1123 self.assertEqual(desc.description, expected_desc)
1124
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001125 def test_update_reviewers(self):
1126 data = [
1127 ('foo', [], 'foo'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001128 ('foo\nR=xx', [], 'foo\nR=xx'),
1129 ('foo\nTBR=xx', [], 'foo\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001130 ('foo', ['a@c'], 'foo\n\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001131 ('foo\nR=xx', ['a@c'], 'foo\n\nR=a@c, xx'),
1132 ('foo\nTBR=xx', ['a@c'], 'foo\n\nR=a@c\nTBR=xx'),
1133 ('foo\nTBR=xx\nR=yy', ['a@c'], 'foo\n\nR=a@c, yy\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001134 ('foo\nBUG=', ['a@c'], 'foo\nBUG=\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001135 ('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 +00001136 ('foo', ['a@c', 'b@c'], 'foo\n\nR=a@c, b@c'),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001137 ('foo\nBar\n\nR=\nBUG=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1138 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1139 # Same as the line before, but full of whitespaces.
1140 (
1141 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'],
1142 'foo\nBar\n\nR=c@c\n BUG =',
1143 ),
1144 # Whitespaces aren't interpreted as new lines.
1145 ('foo BUG=allo R=joe ', ['c@c'], 'foo BUG=allo R=joe\n\nR=c@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001146 ]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001147 expected = [i[2] for i in data]
1148 actual = []
1149 for orig, reviewers, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001150 obj = git_cl.ChangeDescription(orig)
1151 obj.update_reviewers(reviewers)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001152 actual.append(obj.description)
1153 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001154
wittman@chromium.org455dc922015-01-26 20:15:50 +00001155 def test_get_target_ref(self):
1156 # Check remote or remote branch not present.
1157 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master', None))
1158 self.assertEqual(None, git_cl.GetTargetRef(None,
1159 'refs/remotes/origin/master',
1160 'master', None))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001161
wittman@chromium.org455dc922015-01-26 20:15:50 +00001162 # Check default target refs for branches.
1163 self.assertEqual('refs/heads/master',
1164 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1165 None, None))
1166 self.assertEqual('refs/heads/master',
1167 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
1168 None, None))
1169 self.assertEqual('refs/heads/master',
1170 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
1171 None, None))
1172 self.assertEqual('refs/branch-heads/123',
1173 git_cl.GetTargetRef('origin',
1174 'refs/remotes/branch-heads/123',
1175 None, None))
1176 self.assertEqual('refs/diff/test',
1177 git_cl.GetTargetRef('origin',
1178 'refs/remotes/origin/refs/diff/test',
1179 None, None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001180 self.assertEqual('refs/heads/chrome/m42',
1181 git_cl.GetTargetRef('origin',
1182 'refs/remotes/origin/chrome/m42',
1183 None, None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001184
1185 # Check target refs for user-specified target branch.
1186 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1187 'refs/remotes/branch-heads/123'):
1188 self.assertEqual('refs/branch-heads/123',
1189 git_cl.GetTargetRef('origin',
1190 'refs/remotes/origin/master',
1191 branch, None))
1192 for branch in ('origin/master', 'remotes/origin/master',
1193 'refs/remotes/origin/master'):
1194 self.assertEqual('refs/heads/master',
1195 git_cl.GetTargetRef('origin',
1196 'refs/remotes/branch-heads/123',
1197 branch, None))
1198 for branch in ('master', 'heads/master', 'refs/heads/master'):
1199 self.assertEqual('refs/heads/master',
1200 git_cl.GetTargetRef('origin',
1201 'refs/remotes/branch-heads/123',
1202 branch, None))
1203
1204 # Check target refs for pending prefix.
1205 self.assertEqual('prefix/heads/master',
1206 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1207 None, 'prefix/'))
1208
wychen@chromium.orga872e752015-04-28 23:42:18 +00001209 def test_patch_when_dirty(self):
1210 # Patch when local tree is dirty
1211 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1212 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1213
1214 def test_diff_when_dirty(self):
1215 # Do 'git cl diff' when local tree is dirty
1216 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1217 self.assertNotEqual(git_cl.main(['diff']), 0)
1218
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001219 def _patch_common(self, is_gerrit=False, force_codereview=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001220 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001221 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1222 lambda x: '60001')
1223 self.mock(git_cl._RietveldChangelistImpl, 'GetPatchSetDiff',
1224 lambda *args: None)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001225 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1226 lambda *args: {
1227 'current_revision': '7777777777',
1228 'revisions': {
1229 '1111111111': {
1230 '_number': 1,
1231 'fetch': {'http': {
1232 'url': 'https://chromium.googlesource.com/my/repo',
1233 'ref': 'refs/changes/56/123456/1',
1234 }},
1235 },
1236 '7777777777': {
1237 '_number': 7,
1238 'fetch': {'http': {
1239 'url': 'https://chromium.googlesource.com/my/repo',
1240 'ref': 'refs/changes/56/123456/7',
1241 }},
1242 },
1243 },
1244 })
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001245 self.mock(git_cl.Changelist, 'GetDescription',
1246 lambda *args: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001247 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1248
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001249 self.calls = self.calls or []
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001250 if not force_codereview:
1251 # These calls detect codereview to use.
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001252 self.calls += [
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001253 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1254 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
1255 ((['git', 'config', 'branch.master.gerritissue'],), ''),
1256 ((['git', 'config', 'rietveld.autoupdate'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001257 ]
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001258
1259 if is_gerrit:
1260 if not force_codereview:
1261 self.calls += [
1262 ((['git', 'config', 'gerrit.host'],), 'true'),
1263 ]
1264 else:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001265 self.calls += [
1266 ((['git', 'config', 'gerrit.host'],), ''),
1267 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
1268 ((['git', 'rev-parse', '--show-cdup'],), ''),
1269 ((['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'],), ''),
1270 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001271
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001272 def _common_patch_successful(self):
wychen@chromium.orga872e752015-04-28 23:42:18 +00001273 self._patch_common()
1274 self.calls += [
1275 ((['git', 'apply', '--index', '-p0', '--3way'],), ''),
1276 ((['git', 'commit', '-m',
wychen@chromium.org5b3bebb2015-05-28 21:41:43 +00001277 'Description\n\n' +
wychen@chromium.orga872e752015-04-28 23:42:18 +00001278 'patch from issue 123456 at patchset 60001 ' +
1279 '(http://crrev.com/123456#ps60001)'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001280 ((['git', 'config', 'branch.master.rietveldissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001281 ((['git', 'config', 'branch.master.rietveldserver'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001282 ((['git', 'config', 'branch.master.rietveldserver',
1283 'https://codereview.example.com'],), ''),
1284 ((['git', 'config', 'branch.master.rietveldpatchset', '60001'],), ''),
wychen@chromium.orga872e752015-04-28 23:42:18 +00001285 ]
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001286
1287 def test_patch_successful(self):
1288 self._common_patch_successful()
wychen@chromium.orga872e752015-04-28 23:42:18 +00001289 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1290
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001291 def test_patch_successful_new_branch(self):
1292 self.calls = [ ((['git', 'new-branch', 'master'],), ''), ]
1293 self._common_patch_successful()
1294 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1295
wychen@chromium.orga872e752015-04-28 23:42:18 +00001296 def test_patch_conflict(self):
1297 self._patch_common()
1298 self.calls += [
1299 ((['git', 'apply', '--index', '-p0', '--3way'],), '',
1300 subprocess2.CalledProcessError(1, '', '', '', '')),
1301 ]
1302 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
wittman@chromium.org455dc922015-01-26 20:15:50 +00001303
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001304 def test_gerrit_patch_successful(self):
1305 self._patch_common(is_gerrit=True)
1306 self.calls += [
1307 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1308 'refs/changes/56/123456/7'],), ''),
1309 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1310 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1311 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1312 ((['git', 'config', 'branch.master.merge'],), 'master'),
1313 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1314 ((['git', 'config', 'remote.origin.url'],),
1315 'https://chromium.googlesource.com/my/repo'),
1316 ((['git', 'config', 'branch.master.gerritserver',
1317 'https://chromium-review.googlesource.com'],), ''),
1318 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1319 ]
1320 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1321
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001322 def test_patch_force_codereview(self):
1323 self._patch_common(is_gerrit=True, force_codereview=True)
1324 self.calls += [
1325 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1326 'refs/changes/56/123456/7'],), ''),
1327 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1328 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1329 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1330 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1331 ((['git', 'config', 'branch.master.merge'],), 'master'),
1332 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1333 ((['git', 'config', 'remote.origin.url'],),
1334 'https://chromium.googlesource.com/my/repo'),
1335 ((['git', 'config', 'branch.master.gerritserver',
1336 'https://chromium-review.googlesource.com'],), ''),
1337 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1338 ]
1339 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456']), 0)
1340
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001341 def test_gerrit_patch_url_successful(self):
1342 self._patch_common(is_gerrit=True)
1343 self.calls += [
1344 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1345 'refs/changes/56/123456/1'],), ''),
1346 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1347 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1348 ((['git', 'config', 'branch.master.gerritserver',
1349 'https://chromium-review.googlesource.com'],), ''),
1350 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1351 ]
1352 self.assertEqual(git_cl.main(
1353 ['patch', 'https://chromium-review.googlesource.com/#/c/123456/1']), 0)
1354
1355 def test_gerrit_patch_conflict(self):
1356 self._patch_common(is_gerrit=True)
1357 self.mock(git_cl, 'DieWithError',
1358 lambda msg: self._mocked_call(['DieWithError', msg]))
1359 class SystemExitMock(Exception):
1360 pass
1361 self.calls += [
1362 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1363 'refs/changes/56/123456/1'],), ''),
1364 ((['git', 'cherry-pick', 'FETCH_HEAD'],),
1365 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1366 ((['DieWithError', 'git cherry-pick FETCH_HEAD" failed.\n'],),
1367 '', SystemExitMock()),
1368 ]
1369 with self.assertRaises(SystemExitMock):
1370 git_cl.main(['patch',
1371 'https://chromium-review.googlesource.com/#/c/123456/1'])
1372
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001373 def _checkout_calls(self):
1374 return [
1375 ((['git', 'config', '--local', '--get-regexp',
1376 'branch\\..*\\.rietveldissue'], ),
1377 ('branch.retrying.rietveldissue 1111111111\n'
1378 'branch.some-fix.rietveldissue 2222222222\n')),
1379 ((['git', 'config', '--local', '--get-regexp',
1380 'branch\\..*\\.gerritissue'], ),
1381 ('branch.ger-branch.gerritissue 123456\n'
1382 'branch.gbranch654.gerritissue 654321\n')),
1383 ]
1384
1385 def test_checkout_gerrit(self):
1386 """Tests git cl checkout <issue>."""
1387 self.calls = self._checkout_calls()
1388 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1389 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1390
1391 def test_checkout_rietveld(self):
1392 """Tests git cl checkout <issue>."""
1393 self.calls = self._checkout_calls()
1394 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1395 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1396
1397 def test_checkout_not_found(self):
1398 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001399 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001400 self.calls = self._checkout_calls()
1401 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1402
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001403 def test_checkout_no_branch_issues(self):
1404 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001405 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001406 self.calls = [
1407 ((['git', 'config', '--local', '--get-regexp',
1408 'branch\\..*\\.rietveldissue'], ), '',
1409 subprocess2.CalledProcessError(1, '', '', '', '')),
1410 ((['git', 'config', '--local', '--get-regexp',
1411 'branch\\..*\\.gerritissue'], ), '',
1412 subprocess2.CalledProcessError(1, '', '', '', '')),
1413
1414 ]
1415 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1416
tandrii@chromium.org28253532016-04-14 13:46:56 +00001417 def _test_gerrit_ensure_authenticated_common(self, auth,
1418 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001419 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1420 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1421 self.mock(git_cl, 'DieWithError',
1422 lambda msg: self._mocked_call(['DieWithError', msg]))
1423 self.mock(git_cl, 'ask_for_data',
1424 lambda msg: self._mocked_call(['ask_for_data', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001425 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001426 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00001427 cl.branch = 'master'
1428 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001429 cl.lookedup_issue = True
1430 return cl
1431
1432 def test_gerrit_ensure_authenticated_missing(self):
1433 cl = self._test_gerrit_ensure_authenticated_common(auth={
1434 'chromium.googlesource.com': 'git is ok, but gerrit one is missing',
1435 })
1436 self.calls.append(
1437 ((['DieWithError',
1438 'Credentials for the following hosts are required:\n'
1439 ' chromium-review.googlesource.com\n'
1440 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1441 'You can (re)generate your credentails by visiting '
1442 'https://chromium-review.googlesource.com/new-password'],), ''),)
1443 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1444
1445 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001446 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001447 cl = self._test_gerrit_ensure_authenticated_common(auth={
1448 'chromium.googlesource.com': 'one',
1449 'chromium-review.googlesource.com': 'other',
1450 })
1451 self.calls.append(
1452 ((['ask_for_data', 'If you know what you are doing, '
1453 'press Enter to continue, Ctrl+C to abort.'],), ''))
1454 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1455
1456 def test_gerrit_ensure_authenticated_ok(self):
1457 cl = self._test_gerrit_ensure_authenticated_common(auth={
1458 'chromium.googlesource.com': 'same',
1459 'chromium-review.googlesource.com': 'same',
1460 })
1461 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1462
tandrii@chromium.org28253532016-04-14 13:46:56 +00001463 def test_gerrit_ensure_authenticated_skipped(self):
1464 cl = self._test_gerrit_ensure_authenticated_common(
1465 auth={}, skip_auth_check=True)
1466 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1467
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001468 def test_cmd_set_commit_rietveld(self):
1469 self.mock(git_cl._RietveldChangelistImpl, 'SetFlag',
1470 lambda _, f, v: self._mocked_call(['SetFlag', f, v]))
1471 self.calls = [
1472 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1473 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
1474 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1475 ((['git', 'config', 'rietveld.server'],), ''),
1476 ((['git', 'config', 'rietveld.server'],), ''),
1477 ((['git', 'config', 'branch.feature.rietveldserver'],),
1478 'https://codereview.chromium.org'),
1479 ((['SetFlag', 'commit', '1'], ), ''),
1480 ]
1481 self.assertEqual(0, git_cl.main(['set-commit']))
1482
1483 def test_cmd_set_commit_gerrit(self):
1484 self.mock(git_cl.gerrit_util, 'SetReview',
1485 lambda h, i, labels: self._mocked_call(
1486 ['SetReview', h, i, labels]))
1487 self.calls = [
1488 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1489 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1490 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1491 ((['git', 'config', 'branch.feature.gerritserver'],),
1492 'https://chromium-review.googlesource.com'),
1493 ((['SetReview', 'chromium-review.googlesource.com', 123,
1494 {'Commit-Queue': 1}],), ''),
1495 ]
tandrii@chromium.org1a8ef442016-04-13 18:41:37 +00001496 # TODO(tandrii): consider testing just set-commit and set-commit --clear,
1497 # but without copy-pasting tons of expectations, as modifying them later is
1498 # super tedious.
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001499 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1500
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001501 def test_description_display(self):
1502 out = StringIO.StringIO()
1503 self.mock(git_cl.sys, 'stdout', out)
1504
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001505 self.mock(git_cl, 'Changelist', ChangelistMock)
1506 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001507
1508 self.assertEqual(0, git_cl.main(['description', '-d']))
1509 self.assertEqual('foo\n', out.getvalue())
1510
1511 def test_description_rietveld(self):
1512 out = StringIO.StringIO()
1513 self.mock(git_cl.sys, 'stdout', out)
martiniss6eda05f2016-06-30 10:18:35 -07001514 self.mock(git_cl.Changelist, 'GetDescription', lambda *args: 'foobar')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001515
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001516 self.assertEqual(0, git_cl.main([
1517 'description', 'https://code.review.org/123123', '-d', '--rietveld']))
1518 self.assertEqual('foobar\n', out.getvalue())
1519
1520 def test_description_gerrit(self):
1521 out = StringIO.StringIO()
1522 self.mock(git_cl.sys, 'stdout', out)
martiniss6eda05f2016-06-30 10:18:35 -07001523 self.mock(git_cl.Changelist, 'GetDescription', lambda *args: 'foobar')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001524
1525 self.assertEqual(0, git_cl.main([
1526 'description', 'https://code.review.org/123123', '-d', '--gerrit']))
1527 self.assertEqual('foobar\n', out.getvalue())
1528
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001529 def test_description_set_raw(self):
1530 out = StringIO.StringIO()
1531 self.mock(git_cl.sys, 'stdout', out)
1532
1533 self.mock(git_cl, 'Changelist', ChangelistMock)
1534 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
1535
1536 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1537 self.assertEqual('hihi', ChangelistMock.desc)
1538
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001539 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001540 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001541
1542 def RunEditor(desc, _, **kwargs):
1543 self.assertEquals(
1544 '# Enter a description of the change.\n'
1545 '# This will be displayed on the codereview site.\n'
1546 '# The first line will also be used as the subject of the review.\n'
1547 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001548 '--------------------\n'
1549 'Some.\n\nBUG=\n\nChange-Id: xxx',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001550 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001551 # Simulate user changing something.
1552 return 'Some.\n\nBUG=123\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001553
1554 def UpdateDescriptionRemote(_, desc):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001555 self.assertEquals(desc, 'Some.\n\nBUG=123\n\nChange-Id: xxx')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001556
1557 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1558 self.mock(git_cl.Changelist, 'GetDescription',
1559 lambda *args: current_desc)
1560 self.mock(git_cl._GerritChangelistImpl, 'UpdateDescriptionRemote',
1561 UpdateDescriptionRemote)
1562 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
1563
1564 self.calls = [
1565 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1566 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1567 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1568 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
1569 ((['git', 'config', 'core.editor'],), 'vi'),
1570 ]
1571 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
1572
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001573 def test_description_set_stdin(self):
1574 out = StringIO.StringIO()
1575 self.mock(git_cl.sys, 'stdout', out)
1576
1577 self.mock(git_cl, 'Changelist', ChangelistMock)
1578 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
1579
1580 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1581 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1582
kmarshall3bff56b2016-06-06 18:31:47 -07001583 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07001584 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1585
kmarshall3bff56b2016-06-06 18:31:47 -07001586 self.calls = \
1587 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1588 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1589 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1590 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1591 ((['git', 'config', 'rietveld.server'],), ''),
1592 ((['git', 'config', 'rietveld.server'],), ''),
1593 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
1594 ((['git', 'config', 'rietveld.server'],), ''),
1595 ((['git', 'config', 'rietveld.server'],), ''),
1596 ((['git', 'config', 'branch.bar.rietveldissue'],), ''),
1597 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
1598 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1599 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
1600 ((['git', 'branch', '-D', 'foo'],), '')]
1601
1602 class MockChangelist():
1603 def __init__(self, branch, issue):
1604 self.branch = branch
1605 self.issue = issue
1606 def GetBranch(self):
1607 return self.branch
1608 def GetIssue(self):
1609 return self.issue
1610
1611 self.mock(git_cl, 'get_cl_statuses',
1612 lambda branches, fine_grained, max_processes:
1613 [(MockChangelist('master', 1), 'open'),
1614 (MockChangelist('foo', 456), 'closed'),
1615 (MockChangelist('bar', 789), 'open')])
1616
1617 self.assertEqual(0, git_cl.main(['archive', '-f']))
1618
1619 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07001620 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
kmarshall3bff56b2016-06-06 18:31:47 -07001621 self.calls = \
1622 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1623 'refs/heads/master'),
1624 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1625 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1626 ((['git', 'config', 'rietveld.server'],), ''),
1627 ((['git', 'config', 'rietveld.server'],), ''),
1628 ((['git', 'symbolic-ref', 'HEAD'],), 'master')]
1629
1630 class MockChangelist():
1631 def __init__(self, branch, issue):
1632 self.branch = branch
1633 self.issue = issue
1634 def GetBranch(self):
1635 return self.branch
1636 def GetIssue(self):
1637 return self.issue
1638
1639 self.mock(git_cl, 'get_cl_statuses',
1640 lambda branches, fine_grained, max_processes:
1641 [(MockChangelist('master', 1), 'closed')])
1642
1643 self.assertEqual(1, git_cl.main(['archive', '-f']))
1644
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00001645 def test_cmd_issue_erase_existing(self):
1646 out = StringIO.StringIO()
1647 self.mock(git_cl.sys, 'stdout', out)
1648 self.calls = [
1649 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1650 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1651 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1652 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
1653 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
1654 # Let this command raise exception (retcode=1) - it should be ignored.
1655 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
1656 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1657 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
1658 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
1659 ''),
1660 ]
1661 self.assertEqual(0, git_cl.main(['issue', '0']))
1662
tandrii16e0b4e2016-06-07 10:34:28 -07001663 def _common_GerritCommitMsgHookCheck(self):
1664 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1665 self.mock(git_cl.os.path, 'abspath',
1666 lambda path: self._mocked_call(['abspath', path]))
1667 self.mock(git_cl.os.path, 'exists',
1668 lambda path: self._mocked_call(['exists', path]))
1669 self.mock(git_cl.gclient_utils, 'FileRead',
1670 lambda path: self._mocked_call(['FileRead', path]))
1671 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
1672 lambda path: self._mocked_call(['rm_file_or_tree', path]))
1673 self.calls = [
1674 ((['git', 'rev-parse', '--show-cdup'],), '../'),
1675 ((['abspath', '../'],), '/abs/git_repo_root'),
1676 ]
1677 return git_cl.Changelist(codereview='gerrit', issue=123)
1678
1679 def test_GerritCommitMsgHookCheck_custom_hook(self):
1680 cl = self._common_GerritCommitMsgHookCheck()
1681 self.calls += [
1682 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1683 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1684 '#!/bin/sh\necho "custom hook"')
1685 ]
1686 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1687
1688 def test_GerritCommitMsgHookCheck_not_exists(self):
1689 cl = self._common_GerritCommitMsgHookCheck()
1690 self.calls += [
1691 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
1692 ]
1693 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1694
1695 def test_GerritCommitMsgHookCheck(self):
1696 cl = self._common_GerritCommitMsgHookCheck()
1697 self.calls += [
1698 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1699 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1700 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
1701 (('Do you want to remove it now? [Yes/No]',), 'Yes'),
1702 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1703 ''),
1704 ]
1705 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1706
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001707
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001708if __name__ == '__main__':
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001709 git_cl.logging.basicConfig(
1710 level=git_cl.logging.DEBUG if '-v' in sys.argv else git_cl.logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001711 unittest.main()