blob: 53fdacbb2e54d046a748b7eaa19fba4b7c9bf958 [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 = []
216 self._calls_done = 0
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,
254 '@%d Expected: <Missing> Actual: %r' % (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:
263 msg = '@%d Expected: %r Actual: %r' % (
264 self._calls_done, expected_args, args)
265 git_cl.logging.error(msg)
266 self.fail(msg)
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000267 self._calls_done += 1
268 return result
269
maruel@chromium.orga3353652011-11-30 14:26:57 +0000270 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000271 def _is_gerrit_calls(cls, gerrit=False):
272 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
273 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
274
275 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000276 def _upload_calls(cls, similarity, find_copies, private):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000277 return (cls._git_base_calls(similarity, find_copies) +
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000278 cls._git_upload_calls(private))
maruel@chromium.orga3353652011-11-30 14:26:57 +0000279
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000280 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000281 def _upload_no_rev_calls(cls, similarity, find_copies):
282 return (cls._git_base_calls(similarity, find_copies) +
283 cls._git_upload_no_rev_calls())
284
285 @classmethod
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000286 def _git_base_calls(cls, similarity, find_copies):
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000287 if similarity is None:
288 similarity = '50'
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000289 similarity_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000290 'branch.master.git-cl-similarity'],), '')
291 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000292 similarity_call = ((['git', 'config', '--int',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000293 'branch.master.git-cl-similarity', similarity],), '')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000294
295 if find_copies is None:
296 find_copies = True
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000297 find_copies_call = ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000298 'branch.master.git-find-copies'],), '')
299 else:
300 val = str(int(find_copies))
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000301 find_copies_call = ((['git', 'config', '--int',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000302 'branch.master.git-find-copies', val],), '')
303
304 if find_copies:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000305 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000306 '--find-copies-harder', '-l100000', '-C'+similarity,
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000307 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000308 else:
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000309 stat_call = ((['git', 'diff', '--no-ext-diff', '--stat',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000310 '-M'+similarity, 'fake_ancestor_sha', 'HEAD'],), '+dat')
iannucci@chromium.org79540052012-10-19 23:15:26 +0000311
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000312 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000313 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000314 similarity_call,
315 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
316 find_copies_call,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000317 ] + cls._is_gerrit_calls() + [
tandrii@chromium.org87985d22016-03-24 17:33:33 +0000318 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000319 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
320 ((['git', 'config', 'branch.master.gerritissue'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000321 ((['git', 'config', 'rietveld.server'],),
322 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000323 ((['git', 'config', 'branch.master.merge'],), 'master'),
324 ((['git', 'config', 'branch.master.remote'],), 'origin'),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000325 ((['get_or_create_merge_base', 'master', 'master'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000326 'fake_ancestor_sha'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000327 ] + cls._git_sanity_checks('fake_ancestor_sha', 'master') + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000328 ((['git', 'rev-parse', '--show-cdup'],), ''),
329 ((['git', 'rev-parse', 'HEAD'],), '12345'),
330 ((['git', 'diff', '--name-status', '--no-renames', '-r',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000331 'fake_ancestor_sha...', '.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000332 'M\t.gitignore\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000333 ((['git', 'config', 'branch.master.rietveldpatchset'],),
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000334 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000335 ((['git', 'log', '--pretty=format:%s%n%n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000336 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000337 'foo'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000338 ((['git', 'config', 'user.email'],), 'me@example.com'),
iannucci@chromium.org79540052012-10-19 23:15:26 +0000339 stat_call,
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000340 ((['git', 'log', '--pretty=format:%s\n\n%b',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000341 'fake_ancestor_sha..HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000342 'desc\n'),
rmistry@google.com90752582014-01-14 21:04:50 +0000343 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
maruel@chromium.orga3353652011-11-30 14:26:57 +0000344 ]
345
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000346 @classmethod
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000347 def _git_upload_no_rev_calls(cls):
348 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000349 ((['git', 'config', 'core.editor'],), ''),
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000350 ]
351
352 @classmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000353 def _git_upload_calls(cls, private):
354 if private:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000355 cc_call = []
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000356 private_call = []
357 else:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000358 cc_call = [((['git', 'config', 'rietveld.cc'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000359 private_call = [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000360 ((['git', 'config', 'rietveld.private'],), '')]
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000361
maruel@chromium.orga3353652011-11-30 14:26:57 +0000362 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000363 ((['git', 'config', 'core.editor'],), ''),
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +0000364 ] + cc_call + private_call + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000365 ((['git', 'config', 'branch.master.base-url'],), ''),
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000366 ((['git', 'config', 'rietveld.pending-ref-prefix'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000367 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000368 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
369 (('', None), 0)),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000370 ((['git', 'rev-parse', '--show-cdup'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000371 ((['git', 'svn', 'info'],), ''),
sheyang@chromium.org152cf832014-06-11 21:37:49 +0000372 ((['git', 'config', 'rietveld.project'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000373 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000374 'config', 'branch.master.rietveldissue', '1'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000375 ((['git', 'config', 'branch.master.rietveldserver',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000376 'https://codereview.example.com'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000377 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000378 'config', 'branch.master.rietveldpatchset', '2'],), ''),
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000379 ] + cls._git_post_upload_calls()
380
381 @classmethod
382 def _git_post_upload_calls(cls):
383 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000384 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
385 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
386 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000387 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000388 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000389 ]
390
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000391 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000392 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000393 fake_ancestor = 'fake_ancestor'
394 fake_cl = 'fake_cl_for_patch'
395 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000396 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000397 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000398 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000399 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000400 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000401 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000402 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000403 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000404 'config', 'gitcl.remotebranch'],), (('', None), 1)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000405 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000406 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000407 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000408 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000409 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000410 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000411 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000412 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000413 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000414 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000415 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000416
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000417 @classmethod
418 def _dcommit_calls_1(cls):
419 return [
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000420 ((['git', 'config', 'rietveld.autoupdate'],),
421 ''),
422 ((['git', 'config', 'rietveld.pending-ref-prefix'],),
423 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000424 ((['git',
bratell@opera.com05fb9112014-07-07 09:30:23 +0000425 'config', '--local', '--get-regexp', '^svn-remote\\.'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000426 ((('svn-remote.svn.url svn://svn.chromium.org/chrome\n'
427 'svn-remote.svn.fetch trunk/src:refs/remotes/origin/master'),
428 None),
429 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000430 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
431 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000432 'branch.working.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000433 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
434 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000435 'branch.working.git-find-copies'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000436 ((['git', 'symbolic-ref', 'HEAD'],), 'refs/heads/working'),
437 ((['git',
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000438 'config', 'branch.working.rietveldissue'],), '12345'),
439 ((['git',
440 'config', 'rietveld.server'],), 'codereview.example.com'),
441 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000442 'config', 'branch.working.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000443 ((['git', 'config', 'branch.working.remote'],), 'origin'),
iannucci@chromium.org5724c962014-04-11 09:32:56 +0000444 ((['git', 'config', 'branch.working.merge'],),
445 'refs/heads/master'),
446 ((['git', 'config', 'branch.working.remote'],), 'origin'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000447 ((['git', 'rev-list', '--merges',
szager@chromium.orge84b7542012-06-15 21:26:58 +0000448 '--grep=^SVN changes up to revision [0-9]*$',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000449 'refs/remotes/origin/master^!'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000450 ((['git', 'rev-list', '^refs/heads/working',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000451 'refs/remotes/origin/master'],),
452 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000453 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000454 'log', '--grep=^git-svn-id:', '-1', '--pretty=format:%H'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000455 '3fc18b62c4966193eb435baabe2d18a3810ec82e'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000456 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000457 'rev-list', '^3fc18b62c4966193eb435baabe2d18a3810ec82e',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000458 'refs/remotes/origin/master'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000459 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000460 'merge-base', 'refs/remotes/origin/master', 'HEAD'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000461 'fake_ancestor_sha'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000462 ]
463
464 @classmethod
465 def _dcommit_calls_normal(cls):
466 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000467 ((['git', 'rev-parse', '--show-cdup'],), ''),
468 ((['git', 'rev-parse', 'HEAD'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000469 '00ff397798ea57439712ed7e04ab96e13969ef40'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000470 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000471 'diff', '--name-status', '--no-renames', '-r', 'fake_ancestor_sha...',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000472 '.'],),
473 'M\tPRESUBMIT.py'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000474 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000475 'config', 'branch.working.rietveldpatchset'],), '31137'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000476 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000477 'codereview.example.com'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000478 ((['git', 'config', 'user.email'],), 'author@example.com'),
479 ((['git', 'config', 'rietveld.tree-status-url'],), ''),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000480 ]
481
482 @classmethod
483 def _dcommit_calls_bypassed(cls):
484 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000485 ((['git', 'config', 'branch.working.rietveldserver'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000486 'codereview.example.com'),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000487 ]
488
489 @classmethod
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000490 def _dcommit_calls_3(cls):
491 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000492 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000493 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000494 '-l100000', '-C50', 'fake_ancestor_sha',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000495 'refs/heads/working'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000496 (' PRESUBMIT.py | 2 +-\n'
497 ' 1 files changed, 1 insertions(+), 1 deletions(-)\n')),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000498 ((['git', 'show-ref', '--quiet', '--verify',
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000499 'refs/heads/git-cl-commit'],),
500 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000501 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
502 ((['git', 'show-ref', '--quiet', '--verify',
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000503 'refs/heads/git-cl-cherry-pick'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000504 ((['git', 'rev-parse', '--show-cdup'],), '\n'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000505 ((['git', 'checkout', '-q', '-b', 'git-cl-commit'],), ''),
506 ((['git', 'reset', '--soft', 'fake_ancestor_sha'],), ''),
507 ((['git', 'commit', '-m',
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000508 'Issue: 12345\n\nR=john@chromium.org\n\n'
sergiyb@chromium.org4b39c5f2015-07-07 10:33:12 +0000509 'Review URL: https://codereview.example.com/12345 .'],),
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000510 ''),
kjellander@chromium.org6abc6522014-12-02 07:34:49 +0000511 ((['git', 'config', 'rietveld.force-https-commit-url'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000512 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000513 'svn', 'dcommit', '-C50', '--no-rebase', '--rmdir'],),
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000514 (('', None), 0)),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000515 ((['git', 'checkout', '-q', 'working'],), ''),
516 ((['git', 'branch', '-D', 'git-cl-commit'],), ''),
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000517 ]
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000518
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000519 @staticmethod
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000520 def _cmd_line(description, args, similarity, find_copies, private):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000521 """Returns the upload command line passed to upload.RealMain()."""
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000522 return [
523 'upload', '--assume_yes', '--server',
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +0000524 'https://codereview.example.com',
maruel@chromium.org71e12a92012-02-14 02:34:15 +0000525 '--message', description
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000526 ] + args + [
527 '--cc', 'joe@example.com',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000528 ] + (['--private'] if private else []) + [
iannucci@chromium.org79540052012-10-19 23:15:26 +0000529 '--git_similarity', similarity or '50'
530 ] + (['--git_no_find_copies'] if find_copies == False else []) + [
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000531 'fake_ancestor_sha', 'HEAD'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000532 ]
533
534 def _run_reviewer_test(
535 self,
536 upload_args,
537 expected_description,
538 returned_description,
539 final_description,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000540 reviewers,
541 private=False):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000542 """Generic reviewer test framework."""
tandrii@chromium.org28253532016-04-14 13:46:56 +0000543 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000544 try:
545 similarity = upload_args[upload_args.index('--similarity')+1]
546 except ValueError:
547 similarity = None
iannucci@chromium.org79540052012-10-19 23:15:26 +0000548
549 if '--find-copies' in upload_args:
550 find_copies = True
551 elif '--no-find-copies' in upload_args:
552 find_copies = False
553 else:
554 find_copies = None
555
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000556 private = '--private' in upload_args
557
558 self.calls = self._upload_calls(similarity, find_copies, private)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000559
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000560 def RunEditor(desc, _, **kwargs):
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000561 self.assertEquals(
562 '# Enter a description of the change.\n'
janx@chromium.org104b2db2013-04-18 12:58:40 +0000563 '# This will be displayed on the codereview site.\n'
alancutter@chromium.org63a4d7f2013-05-31 02:22:45 +0000564 '# The first line will also be used as the subject of the review.\n'
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +0000565 '#--------------------This line is 72 characters long'
566 '--------------------\n' +
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000567 expected_description,
568 desc)
569 return returned_description
570 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000571
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000572 def check_upload(args):
iannucci@chromium.org79540052012-10-19 23:15:26 +0000573 cmd_line = self._cmd_line(final_description, reviewers, similarity,
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000574 find_copies, private)
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000575 self.assertEquals(cmd_line, args)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000576 return 1, 2
577 self.mock(git_cl.upload, 'RealMain', check_upload)
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000578
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000579 git_cl.main(['upload'] + upload_args)
580
581 def test_no_reviewer(self):
582 self._run_reviewer_test(
583 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000584 'desc\n\nBUG=',
585 '# Blah blah comment.\ndesc\n\nBUG=',
586 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000587 [])
588
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000589 def test_keep_similarity(self):
590 self._run_reviewer_test(
591 ['--similarity', '70'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000592 'desc\n\nBUG=',
593 '# Blah blah comment.\ndesc\n\nBUG=',
594 'desc\n\nBUG=',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000595 [])
596
iannucci@chromium.org79540052012-10-19 23:15:26 +0000597 def test_keep_find_copies(self):
598 self._run_reviewer_test(
599 ['--no-find-copies'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000600 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000601 '# Blah blah comment.\ndesc\n\nBUG=\n',
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000602 'desc\n\nBUG=',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000603 [])
604
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000605 def test_private(self):
606 self._run_reviewer_test(
607 ['--private'],
608 'desc\n\nBUG=',
609 '# Blah blah comment.\ndesc\n\nBUG=\n',
610 'desc\n\nBUG=',
611 [])
612
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000613 def test_reviewers_cmd_line(self):
614 # Reviewer is passed as-is
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000615 description = 'desc\n\nR=foo@example.com\nBUG='
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000616 self._run_reviewer_test(
617 ['-r' 'foo@example.com'],
618 description,
619 '\n%s\n' % description,
620 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000621 ['--reviewers=foo@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000622
623 def test_reviewer_tbr_overriden(self):
624 # Reviewer is overriden with TBR
625 # Also verifies the regexp work without a trailing LF
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000626 description = 'Foo Bar\n\nTBR=reviewer@example.com'
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000627 self._run_reviewer_test(
628 ['-r' 'foo@example.com'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000629 'desc\n\nR=foo@example.com\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000630 description.strip('\n'),
631 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000632 ['--reviewers=reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000633
634 def test_reviewer_multiple(self):
635 # Handles multiple R= or TBR= lines.
636 description = (
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000637 'Foo Bar\nTBR=reviewer@example.com\nBUG=\nR=another@example.com')
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000638 self._run_reviewer_test(
639 [],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000640 'desc\n\nBUG=',
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000641 description,
642 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000643 ['--reviewers=another@example.com,reviewer@example.com'])
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000644
maruel@chromium.orga3353652011-11-30 14:26:57 +0000645 def test_reviewer_send_mail(self):
646 # --send-mail can be used without -r if R= is used
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000647 description = 'Foo Bar\nR=reviewer@example.com'
maruel@chromium.orga3353652011-11-30 14:26:57 +0000648 self._run_reviewer_test(
649 ['--send-mail'],
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000650 'desc\n\nBUG=',
maruel@chromium.orga3353652011-11-30 14:26:57 +0000651 description.strip('\n'),
652 description,
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000653 ['--reviewers=reviewer@example.com', '--send_mail'])
maruel@chromium.orga3353652011-11-30 14:26:57 +0000654
655 def test_reviewer_send_mail_no_rev(self):
656 # Fails without a reviewer.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000657 stdout = StringIO.StringIO()
658 stderr = StringIO.StringIO()
maruel@chromium.orga3353652011-11-30 14:26:57 +0000659 try:
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000660 self.calls = self._upload_no_rev_calls(None, None)
661 def RunEditor(desc, _, **kwargs):
maruel@chromium.orga3353652011-11-30 14:26:57 +0000662 return desc
663 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000664 self.mock(sys, 'stdout', stdout)
665 self.mock(sys, 'stderr', stderr)
maruel@chromium.orga3353652011-11-30 14:26:57 +0000666 git_cl.main(['upload', '--send-mail'])
667 self.fail()
668 except SystemExit:
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000669 self.assertEqual(
670 'Using 50% similarity for rename/copy detection. Override with '
671 '--similarity.\n',
672 stdout.getvalue())
673 self.assertEqual(
674 'Must specify reviewers to send email.\n', stderr.getvalue())
maruel@chromium.orga3353652011-11-30 14:26:57 +0000675
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000676 def test_dcommit(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000677 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000678 self.calls = (
679 self._dcommit_calls_1() +
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000680 self._git_sanity_checks('fake_ancestor_sha', 'working') +
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000681 self._dcommit_calls_normal() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000682 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000683 git_cl.main(['dcommit'])
684
685 def test_dcommit_bypass_hooks(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +0000686 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000687 self.calls = (
688 self._dcommit_calls_1() +
689 self._dcommit_calls_bypassed() +
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000690 self._dcommit_calls_3())
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000691 git_cl.main(['dcommit', '--bypass-hooks'])
692
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000693
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000694 @classmethod
tandrii@chromium.org28253532016-04-14 13:46:56 +0000695 def _gerrit_ensure_auth_calls(cls, issue=None, skip_auth_check=False):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000696 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000697 if skip_auth_check:
698 return [((cmd, ), 'true')]
699
700 calls = [((cmd, ), '', subprocess2.CalledProcessError(1, '', '', '', ''))]
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000701 if issue:
702 calls.extend([
703 ((['git', 'config', 'branch.master.gerritserver'],), ''),
704 ])
705 calls.extend([
706 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
707 ((['git', 'config', 'branch.master.remote'],), 'origin'),
708 ((['git', 'config', 'remote.origin.url'],),
709 'https://chromium.googlesource.com/my/repo'),
710 ((['git', 'config', 'remote.origin.url'],),
711 'https://chromium.googlesource.com/my/repo'),
712 ])
713 return calls
714
715 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000716 def _gerrit_base_calls(cls, issue=None):
ukai@chromium.orge8077812012-02-03 03:41:46 +0000717 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000718 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
719 ((['git', 'config', '--int', '--get',
iannucci@chromium.org53937ba2012-10-02 18:20:43 +0000720 'branch.master.git-cl-similarity'],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000721 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
722 ((['git', 'config', '--int', '--get',
iannucci@chromium.org79540052012-10-19 23:15:26 +0000723 'branch.master.git-find-copies'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000724 ] + cls._is_gerrit_calls(True) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000725 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000726 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000727 ((['git', 'config', 'branch.master.gerritissue'],),
728 '' if issue is None else str(issue)),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000729 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000730 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000731 ((['get_or_create_merge_base', 'master',
732 'refs/remotes/origin/master'],),
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000733 'fake_ancestor_sha'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000734 # Calls to verify branch point is ancestor
735 ] + (cls._gerrit_ensure_auth_calls(issue=issue) +
736 cls._git_sanity_checks('fake_ancestor_sha', 'master',
737 get_remote_branch=False)) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000738 ((['git', 'rev-parse', '--show-cdup'],), ''),
739 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000740
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000741 ((['git',
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000742 'diff', '--name-status', '--no-renames', '-r',
743 'fake_ancestor_sha...', '.'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000744 'M\t.gitignore\n'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000745 ((['git', 'config', 'branch.master.gerritpatchset'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000746 ] + ([] if issue else [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000747 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000748 'log', '--pretty=format:%s%n%n%b', 'fake_ancestor_sha...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000749 'foo'),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000750 ]) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000751 ((['git', 'config', 'user.email'],), 'me@example.com'),
752 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000753 'diff', '--no-ext-diff', '--stat', '--find-copies-harder',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000754 '-l100000', '-C50', 'fake_ancestor_sha', 'HEAD'],),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000755 '+dat'),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000756 ]
ukai@chromium.orge8077812012-02-03 03:41:46 +0000757
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000758 @classmethod
759 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700760 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000761 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000762 ref_suffix='', notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000763 post_amend_description=None, issue=None):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000764 if post_amend_description is None:
765 post_amend_description = description
tandriia60502f2016-06-20 02:01:53 -0700766 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000767
tandriia60502f2016-06-20 02:01:53 -0700768 if squash_mode == 'default':
769 calls.extend([
770 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
771 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
772 ])
773 elif squash_mode in ('override_squash', 'override_nosquash'):
774 calls.extend([
775 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
776 'true' if squash_mode == 'override_squash' else 'false'),
777 ])
778 else:
779 assert squash_mode in ('squash', 'nosquash')
780
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000781 # If issue is given, then description is fetched from Gerrit instead.
782 if issue is None:
783 if squash:
784 calls += [
785 ((['git', 'show', '--format=%B', '-s',
786 'refs/heads/git_cl_uploads/master'],), '')]
787 calls += [
788 ((['git', 'log', '--pretty=format:%s\n\n%b',
789 'fake_ancestor_sha..HEAD'],),
790 description)]
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000791 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000792 calls += [
tandrii@chromium.org10625002016-03-04 20:03:47 +0000793 # DownloadGerritHook(False)
794 ((False, ),
795 ''),
796 # Amending of commit message to get the Change-Id.
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000797 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000798 'fake_ancestor_sha..HEAD'],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000799 description),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000800 ((['git', 'commit', '--amend', '-m', description],),
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000801 ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000802 ((['git', 'log', '--pretty=format:%s\n\n%b',
sbc@chromium.org5e07e062013-02-28 23:55:44 +0000803 'fake_ancestor_sha..HEAD'],),
tandrii@chromium.org10625002016-03-04 20:03:47 +0000804 post_amend_description)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000805 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000806 if squash:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000807 if not issue:
808 # Prompting to edit description on first upload.
809 calls += [
810 ((['git', 'config', 'core.editor'],), ''),
811 ((['RunEditor'],), description),
812 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000813 ref_to_push = 'abcdef0123456789'
814 calls += [
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000815 ((['git', 'config', 'branch.master.merge'],),
816 'refs/heads/master'),
817 ((['git', 'config', 'branch.master.remote'],),
818 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000819 ((['get_or_create_merge_base', 'master',
820 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000821 'origin/master'),
822 ((['git', 'rev-parse', 'HEAD:'],),
823 '0123456789abcdef'),
824 ((['git', 'commit-tree', '0123456789abcdef', '-p',
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000825 'origin/master', '-m', description],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000826 ref_to_push),
827 ]
828 else:
829 ref_to_push = 'HEAD'
830
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000831 calls += [
luqui@chromium.org609f3952015-05-04 22:47:04 +0000832 ((['git', 'rev-list',
833 expected_upstream_ref + '..' + ref_to_push],), ''),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000834 ((['git', 'config', 'rietveld.cc'],), '')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000835 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000836
837 notify_suffix = 'notify=%s' % ('ALL' if notify else 'NONE')
838 if ref_suffix:
839 ref_suffix += ',' + notify_suffix
840 else:
841 ref_suffix = '%' + notify_suffix
tandrii@chromium.org074c2af2016-06-03 23:18:40 +0000842
843 # Add cc from watch list.
844 ref_suffix += ',cc=joe@example.com'
845
ukai@chromium.orge8077812012-02-03 03:41:46 +0000846 if reviewers:
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000847 ref_suffix += ',' + ','.join('r=%s' % email
848 for email in sorted(reviewers))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000849 calls += [
tandrii@chromium.org8acd8332016-04-13 12:56:03 +0000850 ((['git', 'push', 'origin',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000851 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000852 ('remote:\n'
853 'remote: Processing changes: (\)\n'
854 'remote: Processing changes: (|)\n'
855 'remote: Processing changes: (/)\n'
856 'remote: Processing changes: (-)\n'
857 'remote: Processing changes: new: 1 (/)\n'
858 'remote: Processing changes: new: 1, done\n'
859 'remote:\n'
860 'remote: New Changes:\n'
861 'remote: https://chromium-review.googlesource.com/123456 XXX.\n'
862 'remote:\n'
863 'To https://chromium.googlesource.com/yyy/zzz\n'
864 ' * [new branch] hhhh -> refs/for/refs/heads/master\n')),
ukai@chromium.orge8077812012-02-03 03:41:46 +0000865 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000866 if squash:
867 calls += [
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000868 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000869 ((['git', 'config', 'branch.master.gerritserver',
870 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000871 ((['git', 'config', 'branch.master.gerritsquashhash',
872 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000873 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000874 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +0000875 return calls
876
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000877 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000878 self,
879 upload_args,
880 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000881 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -0700882 squash=True,
883 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000884 expected_upstream_ref='origin/refs/heads/master',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000885 ref_suffix='',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000886 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000887 post_amend_description=None,
888 issue=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000889 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -0700890 if squash_mode is None:
891 if '--no-squash' in upload_args:
892 squash_mode = 'nosquash'
893 elif '--squash' in upload_args:
894 squash_mode = 'squash'
895 else:
896 squash_mode = 'default'
897
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000898 reviewers = reviewers or []
tandrii@chromium.org28253532016-04-14 13:46:56 +0000899 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -0700900 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000901 CookiesAuthenticatorMockFactory(same_cookie='same_cred'))
tandrii16e0b4e2016-06-07 10:34:28 -0700902 self.mock(git_cl._GerritChangelistImpl, '_GerritCommitMsgHookCheck',
903 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -0700904 self.mock(git_cl.gclient_utils, 'RunEditor',
905 lambda *_, **__: self._mocked_call(['RunEditor']))
906 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
907
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000908 self.calls = self._gerrit_base_calls(issue=issue)
luqui@chromium.org609f3952015-05-04 22:47:04 +0000909 self.calls += self._gerrit_upload_calls(
910 description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700911 squash_mode=squash_mode,
tandrii@chromium.org10625002016-03-04 20:03:47 +0000912 expected_upstream_ref=expected_upstream_ref,
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000913 ref_suffix=ref_suffix, notify=notify,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000914 post_amend_description=post_amend_description,
915 issue=issue)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000916 # Uncomment when debugging.
917 # print '\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls)))
ukai@chromium.orge8077812012-02-03 03:41:46 +0000918 git_cl.main(['upload'] + upload_args)
919
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000920 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -0700921 self._run_gerrit_upload_test(
922 ['--no-squash'],
923 'desc\n\nBUG=\n',
924 [],
925 squash=False,
926 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
927
928 def test_gerrit_upload_without_change_id_override_nosquash(self):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000929 self.mock(git_cl, 'DownloadGerritHook', self._mocked_call)
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000930 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000931 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +0000932 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000933 [],
tandriia60502f2016-06-20 02:01:53 -0700934 squash=False,
935 squash_mode='override_nosquash',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000936 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000937
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000938 def test_gerrit_no_reviewer(self):
939 self._run_gerrit_upload_test(
940 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000941 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700942 [],
943 squash=False,
944 squash_mode='override_nosquash')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000945
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000946 def test_gerrit_patch_title(self):
947 self._run_gerrit_upload_test(
948 ['-t', 'Don\'t put under_scores as they become spaces'],
949 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandriia60502f2016-06-20 02:01:53 -0700950 squash=False,
951 squash_mode='override_nosquash',
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +0000952 ref_suffix='%m=Don\'t_put_under_scores_as_they_become_spaces')
953
ukai@chromium.orge8077812012-02-03 03:41:46 +0000954 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000955 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000956 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000957 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000958 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -0700959 squash=False,
960 squash_mode='override_nosquash',
tandrii@chromium.org8da45402016-05-24 23:11:03 +0000961 notify=True)
ukai@chromium.orge8077812012-02-03 03:41:46 +0000962
963 def test_gerrit_reviewer_multiple(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000964 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +0000965 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +0000966 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n\n'
967 'Change-Id: 123456789\n',
tandriia60502f2016-06-20 02:01:53 -0700968 ['reviewer@example.com', 'another@example.com'],
969 squash=False,
970 squash_mode='override_nosquash')
971
972 def test_gerrit_upload_squash_first_is_default(self):
973 # Mock Gerrit CL description to indicate the first upload.
974 self.mock(git_cl.Changelist, 'GetDescription',
975 lambda *_: None)
976 self._run_gerrit_upload_test(
977 [],
978 'desc\nBUG=\n\nChange-Id: 123456789',
979 [],
980 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000981
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000982 def test_gerrit_upload_squash_first(self):
983 # Mock Gerrit CL description to indicate the first upload.
984 self.mock(git_cl.Changelist, 'GetDescription',
985 lambda *_: None)
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000986 self._run_gerrit_upload_test(
987 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000988 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000989 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +0000990 squash=True,
991 expected_upstream_ref='origin/master')
ukai@chromium.orge8077812012-02-03 03:41:46 +0000992
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000993 def test_gerrit_upload_squash_reupload(self):
994 description = 'desc\nBUG=\n\nChange-Id: 123456789'
995 # Mock Gerrit CL description to indicate re-upload.
996 self.mock(git_cl.Changelist, 'GetDescription',
997 lambda *args: description)
998 self.mock(git_cl.Changelist, 'GetMostRecentPatchset',
999 lambda *args: 1)
1000 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1001 lambda *args: {'change_id': '123456789'})
1002 self._run_gerrit_upload_test(
1003 ['--squash'],
1004 description,
1005 [],
1006 squash=True,
1007 expected_upstream_ref='origin/master',
1008 issue=123456)
1009
rmistry@google.com2dd99862015-06-22 12:22:18 +00001010 def test_upload_branch_deps(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001011 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001012 def mock_run_git(*args, **_kwargs):
1013 if args[0] == ['for-each-ref',
1014 '--format=%(refname:short) %(upstream:short)',
1015 'refs/heads']:
1016 # Create a local branch dependency tree that looks like this:
1017 # test1 -> test2 -> test3 -> test4 -> test5
1018 # -> test3.1
1019 # test6 -> test0
1020 branch_deps = [
1021 'test2 test1', # test1 -> test2
1022 'test3 test2', # test2 -> test3
1023 'test3.1 test2', # test2 -> test3.1
1024 'test4 test3', # test3 -> test4
1025 'test5 test4', # test4 -> test5
1026 'test6 test0', # test0 -> test6
1027 'test7', # test7
1028 ]
1029 return '\n'.join(branch_deps)
1030 self.mock(git_cl, 'RunGit', mock_run_git)
1031
1032 class RecordCalls:
1033 times_called = 0
1034 record_calls = RecordCalls()
1035 def mock_CMDupload(*args, **_kwargs):
1036 record_calls.times_called += 1
1037 return 0
1038 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1039
1040 self.calls = [
1041 (('[Press enter to continue or ctrl-C to quit]',), ''),
1042 ]
1043
1044 class MockChangelist():
1045 def __init__(self):
1046 pass
1047 def GetBranch(self):
1048 return 'test1'
1049 def GetIssue(self):
1050 return '123'
1051 def GetPatchset(self):
1052 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001053 def IsGerrit(self):
1054 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001055
1056 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1057 # CMDupload should have been called 5 times because of 5 dependent branches.
1058 self.assertEquals(5, record_calls.times_called)
1059 self.assertEquals(0, ret)
1060
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001061 def test_gerrit_change_id(self):
1062 self.calls = [
1063 ((['git', 'write-tree'], ),
1064 'hashtree'),
1065 ((['git', 'rev-parse', 'HEAD~0'], ),
1066 'branch-parent'),
1067 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1068 'A B <a@b.org> 1456848326 +0100'),
1069 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1070 'C D <c@d.org> 1456858326 +0100'),
1071 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1072 'hashchange'),
1073 ]
1074 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1075 self.assertEqual(change_id, 'Ihashchange')
1076
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001077 def test_desecription_append_footer(self):
1078 for init_desc, footer_line, expected_desc in [
1079 # Use unique desc first lines for easy test failure identification.
1080 ('foo', 'R=one', 'foo\n\nR=one'),
1081 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1082 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1083 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1084 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1085 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1086 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1087 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1088 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1089 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1090 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1091 ]:
1092 desc = git_cl.ChangeDescription(init_desc)
1093 desc.append_footer(footer_line)
1094 self.assertEqual(desc.description, expected_desc)
1095
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001096 def test_update_reviewers(self):
1097 data = [
1098 ('foo', [], 'foo'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001099 ('foo\nR=xx', [], 'foo\nR=xx'),
1100 ('foo\nTBR=xx', [], 'foo\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001101 ('foo', ['a@c'], 'foo\n\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001102 ('foo\nR=xx', ['a@c'], 'foo\n\nR=a@c, xx'),
1103 ('foo\nTBR=xx', ['a@c'], 'foo\n\nR=a@c\nTBR=xx'),
1104 ('foo\nTBR=xx\nR=yy', ['a@c'], 'foo\n\nR=a@c, yy\nTBR=xx'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001105 ('foo\nBUG=', ['a@c'], 'foo\nBUG=\nR=a@c'),
agable@chromium.org42c20792013-09-12 17:34:49 +00001106 ('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 +00001107 ('foo', ['a@c', 'b@c'], 'foo\n\nR=a@c, b@c'),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001108 ('foo\nBar\n\nR=\nBUG=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1109 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
1110 # Same as the line before, but full of whitespaces.
1111 (
1112 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'],
1113 'foo\nBar\n\nR=c@c\n BUG =',
1114 ),
1115 # Whitespaces aren't interpreted as new lines.
1116 ('foo BUG=allo R=joe ', ['c@c'], 'foo BUG=allo R=joe\n\nR=c@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001117 ]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001118 expected = [i[2] for i in data]
1119 actual = []
1120 for orig, reviewers, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001121 obj = git_cl.ChangeDescription(orig)
1122 obj.update_reviewers(reviewers)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001123 actual.append(obj.description)
1124 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001125
wittman@chromium.org455dc922015-01-26 20:15:50 +00001126 def test_get_target_ref(self):
1127 # Check remote or remote branch not present.
1128 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master', None))
1129 self.assertEqual(None, git_cl.GetTargetRef(None,
1130 'refs/remotes/origin/master',
1131 'master', None))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001132
wittman@chromium.org455dc922015-01-26 20:15:50 +00001133 # Check default target refs for branches.
1134 self.assertEqual('refs/heads/master',
1135 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1136 None, None))
1137 self.assertEqual('refs/heads/master',
1138 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
1139 None, None))
1140 self.assertEqual('refs/heads/master',
1141 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
1142 None, None))
1143 self.assertEqual('refs/branch-heads/123',
1144 git_cl.GetTargetRef('origin',
1145 'refs/remotes/branch-heads/123',
1146 None, None))
1147 self.assertEqual('refs/diff/test',
1148 git_cl.GetTargetRef('origin',
1149 'refs/remotes/origin/refs/diff/test',
1150 None, None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001151 self.assertEqual('refs/heads/chrome/m42',
1152 git_cl.GetTargetRef('origin',
1153 'refs/remotes/origin/chrome/m42',
1154 None, None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001155
1156 # Check target refs for user-specified target branch.
1157 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1158 'refs/remotes/branch-heads/123'):
1159 self.assertEqual('refs/branch-heads/123',
1160 git_cl.GetTargetRef('origin',
1161 'refs/remotes/origin/master',
1162 branch, None))
1163 for branch in ('origin/master', 'remotes/origin/master',
1164 'refs/remotes/origin/master'):
1165 self.assertEqual('refs/heads/master',
1166 git_cl.GetTargetRef('origin',
1167 'refs/remotes/branch-heads/123',
1168 branch, None))
1169 for branch in ('master', 'heads/master', 'refs/heads/master'):
1170 self.assertEqual('refs/heads/master',
1171 git_cl.GetTargetRef('origin',
1172 'refs/remotes/branch-heads/123',
1173 branch, None))
1174
1175 # Check target refs for pending prefix.
1176 self.assertEqual('prefix/heads/master',
1177 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
1178 None, 'prefix/'))
1179
wychen@chromium.orga872e752015-04-28 23:42:18 +00001180 def test_patch_when_dirty(self):
1181 # Patch when local tree is dirty
1182 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1183 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1184
1185 def test_diff_when_dirty(self):
1186 # Do 'git cl diff' when local tree is dirty
1187 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1188 self.assertNotEqual(git_cl.main(['diff']), 0)
1189
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001190 def _patch_common(self, is_gerrit=False, force_codereview=False):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001191 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001192 self.mock(git_cl._RietveldChangelistImpl, 'GetMostRecentPatchset',
1193 lambda x: '60001')
1194 self.mock(git_cl._RietveldChangelistImpl, 'GetPatchSetDiff',
1195 lambda *args: None)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001196 self.mock(git_cl._GerritChangelistImpl, '_GetChangeDetail',
1197 lambda *args: {
1198 'current_revision': '7777777777',
1199 'revisions': {
1200 '1111111111': {
1201 '_number': 1,
1202 'fetch': {'http': {
1203 'url': 'https://chromium.googlesource.com/my/repo',
1204 'ref': 'refs/changes/56/123456/1',
1205 }},
1206 },
1207 '7777777777': {
1208 '_number': 7,
1209 'fetch': {'http': {
1210 'url': 'https://chromium.googlesource.com/my/repo',
1211 'ref': 'refs/changes/56/123456/7',
1212 }},
1213 },
1214 },
1215 })
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001216 self.mock(git_cl.Changelist, 'GetDescription',
1217 lambda *args: 'Description')
wychen@chromium.orga872e752015-04-28 23:42:18 +00001218 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1219
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001220 self.calls = self.calls or []
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001221 if not force_codereview:
1222 # These calls detect codereview to use.
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001223 self.calls += [
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001224 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1225 ((['git', 'config', 'branch.master.rietveldissue'],), ''),
1226 ((['git', 'config', 'branch.master.gerritissue'],), ''),
1227 ((['git', 'config', 'rietveld.autoupdate'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001228 ]
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001229
1230 if is_gerrit:
1231 if not force_codereview:
1232 self.calls += [
1233 ((['git', 'config', 'gerrit.host'],), 'true'),
1234 ]
1235 else:
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001236 self.calls += [
1237 ((['git', 'config', 'gerrit.host'],), ''),
1238 ((['git', 'config', 'rietveld.server'],), 'codereview.example.com'),
1239 ((['git', 'rev-parse', '--show-cdup'],), ''),
1240 ((['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'],), ''),
1241 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001242
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001243 def _common_patch_successful(self):
wychen@chromium.orga872e752015-04-28 23:42:18 +00001244 self._patch_common()
1245 self.calls += [
1246 ((['git', 'apply', '--index', '-p0', '--3way'],), ''),
1247 ((['git', 'commit', '-m',
wychen@chromium.org5b3bebb2015-05-28 21:41:43 +00001248 'Description\n\n' +
wychen@chromium.orga872e752015-04-28 23:42:18 +00001249 'patch from issue 123456 at patchset 60001 ' +
1250 '(http://crrev.com/123456#ps60001)'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001251 ((['git', 'config', 'branch.master.rietveldissue', '123456'],), ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001252 ((['git', 'config', 'branch.master.rietveldserver'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001253 ((['git', 'config', 'branch.master.rietveldserver',
1254 'https://codereview.example.com'],), ''),
1255 ((['git', 'config', 'branch.master.rietveldpatchset', '60001'],), ''),
wychen@chromium.orga872e752015-04-28 23:42:18 +00001256 ]
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001257
1258 def test_patch_successful(self):
1259 self._common_patch_successful()
wychen@chromium.orga872e752015-04-28 23:42:18 +00001260 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1261
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00001262 def test_patch_successful_new_branch(self):
1263 self.calls = [ ((['git', 'new-branch', 'master'],), ''), ]
1264 self._common_patch_successful()
1265 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1266
wychen@chromium.orga872e752015-04-28 23:42:18 +00001267 def test_patch_conflict(self):
1268 self._patch_common()
1269 self.calls += [
1270 ((['git', 'apply', '--index', '-p0', '--3way'],), '',
1271 subprocess2.CalledProcessError(1, '', '', '', '')),
1272 ]
1273 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
wittman@chromium.org455dc922015-01-26 20:15:50 +00001274
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001275 def test_gerrit_patch_successful(self):
1276 self._patch_common(is_gerrit=True)
1277 self.calls += [
1278 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1279 'refs/changes/56/123456/7'],), ''),
1280 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1281 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1282 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1283 ((['git', 'config', 'branch.master.merge'],), 'master'),
1284 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1285 ((['git', 'config', 'remote.origin.url'],),
1286 'https://chromium.googlesource.com/my/repo'),
1287 ((['git', 'config', 'branch.master.gerritserver',
1288 'https://chromium-review.googlesource.com'],), ''),
1289 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1290 ]
1291 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1292
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001293 def test_patch_force_codereview(self):
1294 self._patch_common(is_gerrit=True, force_codereview=True)
1295 self.calls += [
1296 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1297 'refs/changes/56/123456/7'],), ''),
1298 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1299 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1300 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1301 ((['git', 'config', 'branch.master.gerritserver'],), ''),
1302 ((['git', 'config', 'branch.master.merge'],), 'master'),
1303 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1304 ((['git', 'config', 'remote.origin.url'],),
1305 'https://chromium.googlesource.com/my/repo'),
1306 ((['git', 'config', 'branch.master.gerritserver',
1307 'https://chromium-review.googlesource.com'],), ''),
1308 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1309 ]
1310 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456']), 0)
1311
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001312 def test_gerrit_patch_url_successful(self):
1313 self._patch_common(is_gerrit=True)
1314 self.calls += [
1315 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1316 'refs/changes/56/123456/1'],), ''),
1317 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1318 ((['git', 'config', 'branch.master.gerritissue', '123456'],), ''),
1319 ((['git', 'config', 'branch.master.gerritserver',
1320 'https://chromium-review.googlesource.com'],), ''),
1321 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1322 ]
1323 self.assertEqual(git_cl.main(
1324 ['patch', 'https://chromium-review.googlesource.com/#/c/123456/1']), 0)
1325
1326 def test_gerrit_patch_conflict(self):
1327 self._patch_common(is_gerrit=True)
1328 self.mock(git_cl, 'DieWithError',
1329 lambda msg: self._mocked_call(['DieWithError', msg]))
1330 class SystemExitMock(Exception):
1331 pass
1332 self.calls += [
1333 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1334 'refs/changes/56/123456/1'],), ''),
1335 ((['git', 'cherry-pick', 'FETCH_HEAD'],),
1336 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1337 ((['DieWithError', 'git cherry-pick FETCH_HEAD" failed.\n'],),
1338 '', SystemExitMock()),
1339 ]
1340 with self.assertRaises(SystemExitMock):
1341 git_cl.main(['patch',
1342 'https://chromium-review.googlesource.com/#/c/123456/1'])
1343
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001344 def _checkout_calls(self):
1345 return [
1346 ((['git', 'config', '--local', '--get-regexp',
1347 'branch\\..*\\.rietveldissue'], ),
1348 ('branch.retrying.rietveldissue 1111111111\n'
1349 'branch.some-fix.rietveldissue 2222222222\n')),
1350 ((['git', 'config', '--local', '--get-regexp',
1351 'branch\\..*\\.gerritissue'], ),
1352 ('branch.ger-branch.gerritissue 123456\n'
1353 'branch.gbranch654.gerritissue 654321\n')),
1354 ]
1355
1356 def test_checkout_gerrit(self):
1357 """Tests git cl checkout <issue>."""
1358 self.calls = self._checkout_calls()
1359 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1360 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1361
1362 def test_checkout_rietveld(self):
1363 """Tests git cl checkout <issue>."""
1364 self.calls = self._checkout_calls()
1365 self.calls += [((['git', 'checkout', 'some-fix'], ), '')]
1366 self.assertEqual(0, git_cl.main(['checkout', '2222222222']))
1367
1368 def test_checkout_not_found(self):
1369 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001370 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001371 self.calls = self._checkout_calls()
1372 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1373
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001374 def test_checkout_no_branch_issues(self):
1375 """Tests git cl checkout <issue>."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001376 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001377 self.calls = [
1378 ((['git', 'config', '--local', '--get-regexp',
1379 'branch\\..*\\.rietveldissue'], ), '',
1380 subprocess2.CalledProcessError(1, '', '', '', '')),
1381 ((['git', 'config', '--local', '--get-regexp',
1382 'branch\\..*\\.gerritissue'], ), '',
1383 subprocess2.CalledProcessError(1, '', '', '', '')),
1384
1385 ]
1386 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1387
tandrii@chromium.org28253532016-04-14 13:46:56 +00001388 def _test_gerrit_ensure_authenticated_common(self, auth,
1389 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001390 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1391 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1392 self.mock(git_cl, 'DieWithError',
1393 lambda msg: self._mocked_call(['DieWithError', msg]))
1394 self.mock(git_cl, 'ask_for_data',
1395 lambda msg: self._mocked_call(['ask_for_data', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001396 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001397 cl = git_cl.Changelist(codereview='gerrit')
tandrii@chromium.org28253532016-04-14 13:46:56 +00001398 cl.branch = 'master'
1399 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001400 cl.lookedup_issue = True
1401 return cl
1402
1403 def test_gerrit_ensure_authenticated_missing(self):
1404 cl = self._test_gerrit_ensure_authenticated_common(auth={
1405 'chromium.googlesource.com': 'git is ok, but gerrit one is missing',
1406 })
1407 self.calls.append(
1408 ((['DieWithError',
1409 'Credentials for the following hosts are required:\n'
1410 ' chromium-review.googlesource.com\n'
1411 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
1412 'You can (re)generate your credentails by visiting '
1413 'https://chromium-review.googlesource.com/new-password'],), ''),)
1414 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1415
1416 def test_gerrit_ensure_authenticated_conflict(self):
tandrii@chromium.org28253532016-04-14 13:46:56 +00001417 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001418 cl = self._test_gerrit_ensure_authenticated_common(auth={
1419 'chromium.googlesource.com': 'one',
1420 'chromium-review.googlesource.com': 'other',
1421 })
1422 self.calls.append(
1423 ((['ask_for_data', 'If you know what you are doing, '
1424 'press Enter to continue, Ctrl+C to abort.'],), ''))
1425 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1426
1427 def test_gerrit_ensure_authenticated_ok(self):
1428 cl = self._test_gerrit_ensure_authenticated_common(auth={
1429 'chromium.googlesource.com': 'same',
1430 'chromium-review.googlesource.com': 'same',
1431 })
1432 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1433
tandrii@chromium.org28253532016-04-14 13:46:56 +00001434 def test_gerrit_ensure_authenticated_skipped(self):
1435 cl = self._test_gerrit_ensure_authenticated_common(
1436 auth={}, skip_auth_check=True)
1437 self.assertIsNone(cl.EnsureAuthenticated(force=False))
1438
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001439 def test_cmd_set_commit_rietveld(self):
1440 self.mock(git_cl._RietveldChangelistImpl, 'SetFlag',
1441 lambda _, f, v: self._mocked_call(['SetFlag', f, v]))
1442 self.calls = [
1443 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1444 ((['git', 'config', 'branch.feature.rietveldissue'],), '123'),
1445 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1446 ((['git', 'config', 'rietveld.server'],), ''),
1447 ((['git', 'config', 'rietveld.server'],), ''),
1448 ((['git', 'config', 'branch.feature.rietveldserver'],),
1449 'https://codereview.chromium.org'),
1450 ((['SetFlag', 'commit', '1'], ), ''),
1451 ]
1452 self.assertEqual(0, git_cl.main(['set-commit']))
1453
1454 def test_cmd_set_commit_gerrit(self):
1455 self.mock(git_cl.gerrit_util, 'SetReview',
1456 lambda h, i, labels: self._mocked_call(
1457 ['SetReview', h, i, labels]))
1458 self.calls = [
1459 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1460 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1461 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1462 ((['git', 'config', 'branch.feature.gerritserver'],),
1463 'https://chromium-review.googlesource.com'),
1464 ((['SetReview', 'chromium-review.googlesource.com', 123,
1465 {'Commit-Queue': 1}],), ''),
1466 ]
tandrii@chromium.org1a8ef442016-04-13 18:41:37 +00001467 # TODO(tandrii): consider testing just set-commit and set-commit --clear,
1468 # but without copy-pasting tons of expectations, as modifying them later is
1469 # super tedious.
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001470 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
1471
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001472 def test_description_display(self):
1473 out = StringIO.StringIO()
1474 self.mock(git_cl.sys, 'stdout', out)
1475
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001476 self.mock(git_cl, 'Changelist', ChangelistMock)
1477 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00001478
1479 self.assertEqual(0, git_cl.main(['description', '-d']))
1480 self.assertEqual('foo\n', out.getvalue())
1481
1482 def test_description_rietveld(self):
1483 out = StringIO.StringIO()
1484 self.mock(git_cl.sys, 'stdout', out)
1485 self.mock(git_cl.Changelist, 'GetDescription',
1486 lambda *args: 'foobar')
1487
1488 self.calls = [
1489 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1490 ((['git', 'config', 'rietveld.server'],), ''),
1491 ((['git', 'config', 'rietveld.server'],), ''),
1492 ]
1493 self.assertEqual(0, git_cl.main([
1494 'description', 'https://code.review.org/123123', '-d', '--rietveld']))
1495 self.assertEqual('foobar\n', out.getvalue())
1496
1497 def test_description_gerrit(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.assertEqual(0, git_cl.main([
1504 'description', 'https://code.review.org/123123', '-d', '--gerrit']))
1505 self.assertEqual('foobar\n', out.getvalue())
1506
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001507 def test_description_set_raw(self):
1508 out = StringIO.StringIO()
1509 self.mock(git_cl.sys, 'stdout', out)
1510
1511 self.mock(git_cl, 'Changelist', ChangelistMock)
1512 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
1513
1514 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
1515 self.assertEqual('hihi', ChangelistMock.desc)
1516
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001517 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001518 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001519
1520 def RunEditor(desc, _, **kwargs):
1521 self.assertEquals(
1522 '# Enter a description of the change.\n'
1523 '# This will be displayed on the codereview site.\n'
1524 '# The first line will also be used as the subject of the review.\n'
1525 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001526 '--------------------\n'
1527 'Some.\n\nBUG=\n\nChange-Id: xxx',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001528 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001529 # Simulate user changing something.
1530 return 'Some.\n\nBUG=123\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001531
1532 def UpdateDescriptionRemote(_, desc):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001533 self.assertEquals(desc, 'Some.\n\nBUG=123\n\nChange-Id: xxx')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00001534
1535 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1536 self.mock(git_cl.Changelist, 'GetDescription',
1537 lambda *args: current_desc)
1538 self.mock(git_cl._GerritChangelistImpl, 'UpdateDescriptionRemote',
1539 UpdateDescriptionRemote)
1540 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
1541
1542 self.calls = [
1543 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1544 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1545 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1546 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
1547 ((['git', 'config', 'core.editor'],), 'vi'),
1548 ]
1549 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
1550
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00001551 def test_description_set_stdin(self):
1552 out = StringIO.StringIO()
1553 self.mock(git_cl.sys, 'stdout', out)
1554
1555 self.mock(git_cl, 'Changelist', ChangelistMock)
1556 self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
1557
1558 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
1559 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
1560
kmarshall3bff56b2016-06-06 18:31:47 -07001561 def test_archive(self):
tandrii1c67da62016-06-10 07:35:53 -07001562 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1563
kmarshall3bff56b2016-06-06 18:31:47 -07001564 self.calls = \
1565 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1566 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
1567 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1568 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1569 ((['git', 'config', 'rietveld.server'],), ''),
1570 ((['git', 'config', 'rietveld.server'],), ''),
1571 ((['git', 'config', 'branch.foo.rietveldissue'],), '456'),
1572 ((['git', 'config', 'rietveld.server'],), ''),
1573 ((['git', 'config', 'rietveld.server'],), ''),
1574 ((['git', 'config', 'branch.bar.rietveldissue'],), ''),
1575 ((['git', 'config', 'branch.bar.gerritissue'],), '789'),
1576 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
1577 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
1578 ((['git', 'branch', '-D', 'foo'],), '')]
1579
1580 class MockChangelist():
1581 def __init__(self, branch, issue):
1582 self.branch = branch
1583 self.issue = issue
1584 def GetBranch(self):
1585 return self.branch
1586 def GetIssue(self):
1587 return self.issue
1588
1589 self.mock(git_cl, 'get_cl_statuses',
1590 lambda branches, fine_grained, max_processes:
1591 [(MockChangelist('master', 1), 'open'),
1592 (MockChangelist('foo', 456), 'closed'),
1593 (MockChangelist('bar', 789), 'open')])
1594
1595 self.assertEqual(0, git_cl.main(['archive', '-f']))
1596
1597 def test_archive_current_branch_fails(self):
tandrii1c67da62016-06-10 07:35:53 -07001598 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
kmarshall3bff56b2016-06-06 18:31:47 -07001599 self.calls = \
1600 [((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
1601 'refs/heads/master'),
1602 ((['git', 'config', 'branch.master.rietveldissue'],), '1'),
1603 ((['git', 'config', 'rietveld.autoupdate'],), ''),
1604 ((['git', 'config', 'rietveld.server'],), ''),
1605 ((['git', 'config', 'rietveld.server'],), ''),
1606 ((['git', 'symbolic-ref', 'HEAD'],), 'master')]
1607
1608 class MockChangelist():
1609 def __init__(self, branch, issue):
1610 self.branch = branch
1611 self.issue = issue
1612 def GetBranch(self):
1613 return self.branch
1614 def GetIssue(self):
1615 return self.issue
1616
1617 self.mock(git_cl, 'get_cl_statuses',
1618 lambda branches, fine_grained, max_processes:
1619 [(MockChangelist('master', 1), 'closed')])
1620
1621 self.assertEqual(1, git_cl.main(['archive', '-f']))
1622
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00001623 def test_cmd_issue_erase_existing(self):
1624 out = StringIO.StringIO()
1625 self.mock(git_cl.sys, 'stdout', out)
1626 self.calls = [
1627 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
1628 ((['git', 'config', 'branch.feature.rietveldissue'],), ''),
1629 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
1630 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
1631 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
1632 # Let this command raise exception (retcode=1) - it should be ignored.
1633 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
1634 '', subprocess2.CalledProcessError(1, '', '', '', '')),
1635 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
1636 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
1637 ''),
1638 ]
1639 self.assertEqual(0, git_cl.main(['issue', '0']))
1640
tandrii16e0b4e2016-06-07 10:34:28 -07001641 def _common_GerritCommitMsgHookCheck(self):
1642 self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
1643 self.mock(git_cl.os.path, 'abspath',
1644 lambda path: self._mocked_call(['abspath', path]))
1645 self.mock(git_cl.os.path, 'exists',
1646 lambda path: self._mocked_call(['exists', path]))
1647 self.mock(git_cl.gclient_utils, 'FileRead',
1648 lambda path: self._mocked_call(['FileRead', path]))
1649 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
1650 lambda path: self._mocked_call(['rm_file_or_tree', path]))
1651 self.calls = [
1652 ((['git', 'rev-parse', '--show-cdup'],), '../'),
1653 ((['abspath', '../'],), '/abs/git_repo_root'),
1654 ]
1655 return git_cl.Changelist(codereview='gerrit', issue=123)
1656
1657 def test_GerritCommitMsgHookCheck_custom_hook(self):
1658 cl = self._common_GerritCommitMsgHookCheck()
1659 self.calls += [
1660 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1661 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1662 '#!/bin/sh\necho "custom hook"')
1663 ]
1664 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1665
1666 def test_GerritCommitMsgHookCheck_not_exists(self):
1667 cl = self._common_GerritCommitMsgHookCheck()
1668 self.calls += [
1669 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
1670 ]
1671 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1672
1673 def test_GerritCommitMsgHookCheck(self):
1674 cl = self._common_GerritCommitMsgHookCheck()
1675 self.calls += [
1676 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
1677 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1678 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
1679 (('Do you want to remove it now? [Yes/No]',), 'Yes'),
1680 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
1681 ''),
1682 ]
1683 cl._codereview_impl._GerritCommitMsgHookCheck(offer_removal=True)
1684
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001685
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001686if __name__ == '__main__':
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001687 git_cl.logging.basicConfig(
1688 level=git_cl.logging.DEBUG if '-v' in sys.argv else git_cl.logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00001689 unittest.main()