blob: b95a3ee200a7c3d264db1a0137c782c5909cdd02 [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
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01008import datetime
tandriide281ae2016-10-12 06:02:30 -07009import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010010import logging
maruel@chromium.orgddd59412011-11-30 14:20:38 +000011import os
Brian Sheedy59b06a82019-10-14 17:03:29 +000012import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000013import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070014import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000015import unittest
16
17sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
18
19from testing_support.auto_stub import TestCase
Edward Lemur4c707a22019-09-24 21:13:43 +000020from third_party import mock
maruel@chromium.orgddd59412011-11-30 14:20:38 +000021
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000022import metrics
23# We have to disable monitoring before importing git_cl.
24metrics.DISABLE_METRICS_COLLECTION = True
25
Eric Boren2fb63102018-10-05 13:05:03 +000026import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000027import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000028import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000029import git_footers
maruel@chromium.orgddd59412011-11-30 14:20:38 +000030import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000031
Edward Lemur79d4f992019-11-11 23:49:02 +000032if sys.version_info.major == 2:
33 from StringIO import StringIO
34else:
35 from io import StringIO
36
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000037
tandrii5d48c322016-08-18 16:19:37 -070038def callError(code=1, cmd='', cwd='', stdout='', stderr=''):
39 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
40
41
Edward Lemur4c707a22019-09-24 21:13:43 +000042def _constantFn(return_value):
43 def f(*args, **kwargs):
44 return return_value
45 return f
46
47
tandrii5d48c322016-08-18 16:19:37 -070048CERR1 = callError(1)
49
50
Aaron Gable9a03ae02017-11-03 11:31:07 -070051def MakeNamedTemporaryFileMock(expected_content):
52 class NamedTemporaryFileMock(object):
53 def __init__(self, *args, **kwargs):
54 self.name = '/tmp/named'
55 self.expected_content = expected_content
56
57 def __enter__(self):
58 return self
59
60 def __exit__(self, _type, _value, _tb):
61 pass
62
63 def write(self, content):
64 if self.expected_content:
65 assert content == self.expected_content
66
67 def close(self):
68 pass
69
70 return NamedTemporaryFileMock
71
72
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000073class ChangelistMock(object):
74 # A class variable so we can access it when we don't have access to the
75 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000076 desc = ''
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000077 def __init__(self, **kwargs):
78 pass
79 def GetIssue(self):
80 return 1
Kenneth Russell61e2ed42017-02-15 11:47:13 -080081 def GetDescription(self, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000082 return ChangelistMock.desc
dsansomee2d6fd92016-09-08 00:10:47 -070083 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000084 ChangelistMock.desc = desc
85
tandrii5d48c322016-08-18 16:19:37 -070086
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000087class PresubmitMock(object):
88 def __init__(self, *args, **kwargs):
89 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080090 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
91
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000092 @staticmethod
93 def should_continue():
94 return True
95
96
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000097class WatchlistsMock(object):
98 def __init__(self, _):
99 pass
100 @staticmethod
101 def GetWatchersForPaths(_):
102 return ['joe@example.com']
103
104
Edward Lemur4c707a22019-09-24 21:13:43 +0000105class CodereviewSettingsFileMock(object):
106 def __init__(self):
107 pass
108 # pylint: disable=no-self-use
109 def read(self):
110 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
111 'GERRIT_HOST: True\n')
112
113
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000114class AuthenticatorMock(object):
115 def __init__(self, *_args):
116 pass
117 def has_cached_credentials(self):
118 return True
tandrii221ab252016-10-06 08:12:04 -0700119 def authorize(self, http):
120 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000121
122
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100123def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000124 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
125
126 Usage:
127 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100128 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000129
130 OR
131 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100132 CookiesAuthenticatorMockFactory(
133 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000134 """
135 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800136 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000137 # Intentionally not calling super() because it reads actual cookie files.
138 pass
139 @classmethod
140 def get_gitcookies_path(cls):
141 return '~/.gitcookies'
142 @classmethod
143 def get_netrc_path(cls):
144 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100145 def _get_auth_for_host(self, host):
146 if same_auth:
147 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000148 return (hosts_with_creds or {}).get(host)
149 return CookiesAuthenticatorMock
150
Aaron Gable9a03ae02017-11-03 11:31:07 -0700151
kmarshall9249e012016-08-23 12:02:16 -0700152class MockChangelistWithBranchAndIssue():
153 def __init__(self, branch, issue):
154 self.branch = branch
155 self.issue = issue
156 def GetBranch(self):
157 return self.branch
158 def GetIssue(self):
159 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000160
tandriic2405f52016-10-10 08:13:15 -0700161
162class SystemExitMock(Exception):
163 pass
164
165
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000166class TestGitClBasic(unittest.TestCase):
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100167 def test_get_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000168 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100169 cl.description = 'x'
170 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000171 cl.FetchDescription = lambda *a, **kw: 'y'
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000172 self.assertEqual(cl.GetDescription(), 'x')
173 self.assertEqual(cl.GetDescription(force=True), 'y')
174 self.assertEqual(cl.GetDescription(), 'y')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100175
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700176 def test_description_footers(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000177 cl = git_cl.Changelist(issue=1, codereview_host='host')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700178 cl.description = '\n'.join([
179 'This is some message',
180 '',
181 'It has some lines',
182 'and, also',
183 '',
184 'Some: Really',
185 'Awesome: Footers',
186 ])
187 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000188 cl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700189 msg, footers = cl.GetDescriptionFooters()
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000190 self.assertEqual(
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700191 msg, ['This is some message', '', 'It has some lines', 'and, also'])
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000192 self.assertEqual(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700193
194 msg.append('wut')
195 footers.append(('gnarly-dude', 'beans'))
196 cl.UpdateDescriptionFooters(msg, footers)
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000197 self.assertEqual(cl.GetDescription().splitlines(), [
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700198 'This is some message',
199 '',
200 'It has some lines',
201 'and, also',
202 'wut'
203 '',
204 'Some: Really',
205 'Awesome: Footers',
206 'Gnarly-Dude: beans',
207 ])
208
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000209 def test_set_preserve_tryjobs(self):
210 d = git_cl.ChangeDescription('Simple.')
211 d.set_preserve_tryjobs()
212 self.assertEqual(d.description.splitlines(), [
213 'Simple.',
214 '',
215 'Cq-Do-Not-Cancel-Tryjobs: true',
216 ])
217 before = d.description
218 d.set_preserve_tryjobs()
219 self.assertEqual(before, d.description)
220
221 d = git_cl.ChangeDescription('\n'.join([
222 'One is enough',
223 '',
224 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
225 'Change-Id: Ideadbeef',
226 ]))
227 d.set_preserve_tryjobs()
228 self.assertEqual(d.description.splitlines(), [
229 'One is enough',
230 '',
231 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
232 'Change-Id: Ideadbeef',
233 'Cq-Do-Not-Cancel-Tryjobs: true',
234 ])
235
tandriif9aefb72016-07-01 09:06:51 -0700236 def test_get_bug_line_values(self):
237 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
238 self.assertEqual(f('', ''), [])
239 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
240 self.assertEqual(f('v8', '456'), ['v8:456'])
241 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
242 # Not nice, but not worth carying.
243 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
244 ['v8:456', 'chromium:123', 'v8:123'])
245
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100246 def _test_git_number(self, parent_msg, dest_ref, child_msg,
247 parent_hash='parenthash'):
248 desc = git_cl.ChangeDescription(child_msg)
249 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
250 return desc.description
251
252 def assertEqualByLine(self, actual, expected):
253 self.assertEqual(actual.splitlines(), expected.splitlines())
254
255 def test_git_number_bad_parent(self):
256 with self.assertRaises(ValueError):
257 self._test_git_number('Parent', 'refs/heads/master', 'Child')
258
259 def test_git_number_bad_parent_footer(self):
260 with self.assertRaises(AssertionError):
261 self._test_git_number(
262 'Parent\n'
263 '\n'
264 'Cr-Commit-Position: wrong',
265 'refs/heads/master', 'Child')
266
267 def test_git_number_bad_lineage_ignored(self):
268 actual = self._test_git_number(
269 'Parent\n'
270 '\n'
271 'Cr-Commit-Position: refs/heads/master@{#1}\n'
272 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
273 'refs/heads/master', 'Child')
274 self.assertEqualByLine(
275 actual,
276 'Child\n'
277 '\n'
278 'Cr-Commit-Position: refs/heads/master@{#2}\n'
279 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
280
281 def test_git_number_same_branch(self):
282 actual = self._test_git_number(
283 'Parent\n'
284 '\n'
285 'Cr-Commit-Position: refs/heads/master@{#12}',
286 dest_ref='refs/heads/master',
287 child_msg='Child')
288 self.assertEqualByLine(
289 actual,
290 'Child\n'
291 '\n'
292 'Cr-Commit-Position: refs/heads/master@{#13}')
293
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200294 def test_git_number_same_branch_mixed_footers(self):
295 actual = self._test_git_number(
296 'Parent\n'
297 '\n'
298 'Cr-Commit-Position: refs/heads/master@{#12}',
299 dest_ref='refs/heads/master',
300 child_msg='Child\n'
301 '\n'
302 'Broken-by: design\n'
303 'BUG=123')
304 self.assertEqualByLine(
305 actual,
306 'Child\n'
307 '\n'
308 'Broken-by: design\n'
309 'BUG=123\n'
310 'Cr-Commit-Position: refs/heads/master@{#13}')
311
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100312 def test_git_number_same_branch_with_originals(self):
313 actual = self._test_git_number(
314 'Parent\n'
315 '\n'
316 'Cr-Commit-Position: refs/heads/master@{#12}',
317 dest_ref='refs/heads/master',
318 child_msg='Child\n'
319 '\n'
320 'Some users are smart and insert their own footers\n'
321 '\n'
322 'Cr-Whatever: value\n'
323 'Cr-Commit-Position: refs/copy/paste@{#22}')
324 self.assertEqualByLine(
325 actual,
326 'Child\n'
327 '\n'
328 'Some users are smart and insert their own footers\n'
329 '\n'
330 'Cr-Original-Whatever: value\n'
331 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
332 'Cr-Commit-Position: refs/heads/master@{#13}')
333
334 def test_git_number_new_branch(self):
335 actual = self._test_git_number(
336 'Parent\n'
337 '\n'
338 'Cr-Commit-Position: refs/heads/master@{#12}',
339 dest_ref='refs/heads/branch',
340 child_msg='Child')
341 self.assertEqualByLine(
342 actual,
343 'Child\n'
344 '\n'
345 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
346 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
347
348 def test_git_number_lineage(self):
349 actual = self._test_git_number(
350 'Parent\n'
351 '\n'
352 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
353 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
354 dest_ref='refs/heads/branch',
355 child_msg='Child')
356 self.assertEqualByLine(
357 actual,
358 'Child\n'
359 '\n'
360 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
361 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
362
363 def test_git_number_moooooooore_lineage(self):
364 actual = self._test_git_number(
365 'Parent\n'
366 '\n'
367 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
368 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
369 dest_ref='refs/heads/mooore',
370 child_msg='Child')
371 self.assertEqualByLine(
372 actual,
373 'Child\n'
374 '\n'
375 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
376 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
377 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
378
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100379 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700380 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100381 actual = self._test_git_number(
382 'CQ commit on fresh new branch + numbering.\n'
383 '\n'
384 'NOTRY=True\n'
385 'NOPRESUBMIT=True\n'
386 'BUG=\n'
387 '\n'
388 'Review-Url: https://codereview.chromium.org/2577703003\n'
389 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
390 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
391 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
392 dest_ref='refs/heads/gnumb-test/cl',
393 child_msg='git cl on fresh new branch + numbering.\n'
394 '\n'
395 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
396 self.assertEqualByLine(
397 actual,
398 'git cl on fresh new branch + numbering.\n'
399 '\n'
400 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
401 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
402 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
403 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
404 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100405
406 def test_git_number_cherry_pick(self):
407 actual = self._test_git_number(
408 'Parent\n'
409 '\n'
410 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
411 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
412 dest_ref='refs/heads/branch',
413 child_msg='Child, which is cherry-pick from master\n'
414 '\n'
415 'Cr-Commit-Position: refs/heads/master@{#100}\n'
416 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
417 self.assertEqualByLine(
418 actual,
419 'Child, which is cherry-pick from master\n'
420 '\n'
421 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
422 '\n'
423 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
424 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
425 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
426
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000427 def test_valid_accounts(self):
428 mock_per_account = {
429 'u1': None, # 404, doesn't exist.
430 'u2': {
431 '_account_id': 123124,
432 'avatars': [],
433 'email': 'u2@example.com',
434 'name': 'User Number 2',
435 'status': 'OOO',
436 },
437 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
438 }
439 def GetAccountDetailsMock(_, account):
440 # Poor-man's mock library's side_effect.
441 v = mock_per_account.pop(account)
442 if isinstance(v, Exception):
443 raise v
444 return v
445
446 original = git_cl.gerrit_util.GetAccountDetails
447 try:
448 git_cl.gerrit_util.GetAccountDetails = GetAccountDetailsMock
449 actual = git_cl.gerrit_util.ValidAccounts(
450 'host', ['u1', 'u2', 'u3'], max_threads=1)
451 finally:
452 git_cl.gerrit_util.GetAccountDetails = original
453 self.assertEqual(actual, {
454 'u2': {
455 '_account_id': 123124,
456 'avatars': [],
457 'email': 'u2@example.com',
458 'name': 'User Number 2',
459 'status': 'OOO',
460 },
461 })
462
463
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200464class TestParseIssueURL(unittest.TestCase):
465 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000466 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200467 self.assertIsNotNone(parsed)
468 if fail:
469 self.assertFalse(parsed.valid)
470 return
471 self.assertTrue(parsed.valid)
472 self.assertEqual(parsed.issue, issue)
473 self.assertEqual(parsed.patchset, patchset)
474 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200475
Edward Lemur678a6842019-10-03 22:25:05 +0000476 def test_ParseIssueNumberArgument(self):
477 def test(arg, *args, **kwargs):
478 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200479
Edward Lemur678a6842019-10-03 22:25:05 +0000480 test('123', 123)
481 test('', fail=True)
482 test('abc', fail=True)
483 test('123/1', fail=True)
484 test('123a', fail=True)
485 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200486
Edward Lemur678a6842019-10-03 22:25:05 +0000487 test('https://codereview.source.com/123',
488 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200489 test('http://chrome-review.source.com/c/123',
490 123, None, 'chrome-review.source.com')
491 test('https://chrome-review.source.com/c/123/',
492 123, None, 'chrome-review.source.com')
493 test('https://chrome-review.source.com/c/123/4',
494 123, 4, 'chrome-review.source.com')
495 test('https://chrome-review.source.com/#/c/123/4',
496 123, 4, 'chrome-review.source.com')
497 test('https://chrome-review.source.com/c/123/4',
498 123, 4, 'chrome-review.source.com')
499 test('https://chrome-review.source.com/123',
500 123, None, 'chrome-review.source.com')
501 test('https://chrome-review.source.com/123/4',
502 123, 4, 'chrome-review.source.com')
503
Edward Lemur678a6842019-10-03 22:25:05 +0000504 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200505 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
506 test('https://chrome-review.source.com/c/abc/', fail=True)
507 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
508
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200509
510
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100511class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100512 def setUp(self):
513 super(GitCookiesCheckerTest, self).setUp()
514 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100515 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100516
517 def mock_hosts_creds(self, subhost_identity_pairs):
518 def ensure_googlesource(h):
519 if not h.endswith(self.c._GOOGLESOURCE):
520 assert not h.endswith('.')
521 return h + '.' + self.c._GOOGLESOURCE
522 return h
523 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
524 for h, i in subhost_identity_pairs]
525
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200526 def test_identity_parsing(self):
527 self.assertEqual(self.c._parse_identity('ldap.google.com'),
528 ('ldap', 'google.com'))
529 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
530 ('ldap', 'example.com'))
531 # Specical case because we know there are no subdomains in chromium.org.
532 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
533 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800534 # Pathological: ".period." can be either username OR domain, more likely
535 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200536 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
537 ('note', 'period.example.com'))
538
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100539 def test_analysis_nothing(self):
540 self.c._all_hosts = []
541 self.assertFalse(self.c.has_generic_host())
542 self.assertEqual(set(), self.c.get_conflicting_hosts())
543 self.assertEqual(set(), self.c.get_duplicated_hosts())
544 self.assertEqual(set(), self.c.get_partially_configured_hosts())
545 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
546
547 def test_analysis(self):
548 self.mock_hosts_creds([
549 ('.googlesource.com', 'git-example.chromium.org'),
550
551 ('chromium', 'git-example.google.com'),
552 ('chromium-review', 'git-example.google.com'),
553 ('chrome-internal', 'git-example.chromium.org'),
554 ('chrome-internal-review', 'git-example.chromium.org'),
555 ('conflict', 'git-example.google.com'),
556 ('conflict-review', 'git-example.chromium.org'),
557 ('dup', 'git-example.google.com'),
558 ('dup', 'git-example.google.com'),
559 ('dup-review', 'git-example.google.com'),
560 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200561 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100562 ])
563 self.assertTrue(self.c.has_generic_host())
564 self.assertEqual(set(['conflict.googlesource.com']),
565 self.c.get_conflicting_hosts())
566 self.assertEqual(set(['dup.googlesource.com']),
567 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200568 self.assertEqual(set(['partial.googlesource.com',
569 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100570 self.c.get_partially_configured_hosts())
571 self.assertEqual(set(['chromium.googlesource.com',
572 'chrome-internal.googlesource.com']),
573 self.c.get_hosts_with_wrong_identities())
574
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100575 def test_report_no_problems(self):
576 self.test_analysis_nothing()
Edward Lemur79d4f992019-11-11 23:49:02 +0000577 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100578 self.assertFalse(self.c.find_and_report_problems())
579 self.assertEqual(sys.stdout.getvalue(), '')
580
581 def test_report(self):
582 self.test_analysis()
Edward Lemur79d4f992019-11-11 23:49:02 +0000583 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200584 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
585 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100586 self.assertTrue(self.c.find_and_report_problems())
587 with open(os.path.join(os.path.dirname(__file__),
588 'git_cl_creds_check_report.txt')) as f:
589 expected = f.read()
590 def by_line(text):
591 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700592 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200593 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100594
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800595
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000596class TestGitCl(TestCase):
597 def setUp(self):
598 super(TestGitCl, self).setUp()
599 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700600 self._calls_done = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000601 self.mock(git_cl, 'time_time',
602 lambda: self._mocked_call('time.time'))
603 self.mock(git_cl.metrics.collector, 'add_repeated',
604 lambda *a: self._mocked_call('add_repeated', *a))
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000605 self.mock(subprocess2, 'call', self._mocked_call)
606 self.mock(subprocess2, 'check_call', self._mocked_call)
607 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700608 self.mock(subprocess2, 'communicate',
609 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000610 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000611 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000612 self.mock(git_common, 'get_or_create_merge_base',
613 lambda *a: (
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000614 self._mocked_call(['get_or_create_merge_base'] + list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000615 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000616 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000617 self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
618 self._mocked_call('SaveDescriptionBackup'))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100619 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000620 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700621 self.mock(git_cl, 'write_json', lambda path, contents:
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000622 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000623 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000624 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
Edward Lemur5b929a42019-10-21 17:57:39 +0000625 self.mock(git_cl.auth, 'Authenticator', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100626 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
627 lambda *args, **kwargs: self._mocked_call(
628 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700629 self.mock(git_cl.gerrit_util, 'GetChangeComments',
630 lambda *args, **kwargs: self._mocked_call(
631 'GetChangeComments', *args, **kwargs))
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000632 self.mock(git_cl.gerrit_util, 'GetChangeRobotComments',
633 lambda *args, **kwargs: self._mocked_call(
634 'GetChangeRobotComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100635 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700636 lambda h, i, reviewers, ccs, notify: self._mocked_call(
637 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700638 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700639 lambda h, i, msg=None, labels=None, notify=None:
640 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700641 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
642 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000643 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
644 classmethod(lambda _: False))
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000645 self.mock(git_cl.gerrit_util, 'ValidAccounts',
646 lambda host, accounts:
647 self._mocked_call('ValidAccounts', host, accounts))
tandriic2405f52016-10-10 08:13:15 -0700648 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100649 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000650 # It's important to reset settings to not have inter-tests interference.
651 git_cl.settings = None
652
653 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000654 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000655 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100656 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000657 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100658 raise
659 # Sadly, has_failed() returns True if this OR any other tests before this
660 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200661 git_cl.logging.error(
662 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100663 'There are un-consumed self.calls after this test has finished.\n'
664 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700665 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200666 'If you are already running only this test, then **first** fix the '
667 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100668 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700669 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100670 'and follow instructions above.\n' +
671 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000672 finally:
673 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000674
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000675 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000676 self.assertTrue(
677 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700678 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000679 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000680 expected_args, result = top
681
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000682 # Also logs otherwise it could get caught in a try/finally and be hard to
683 # diagnose.
684 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700685 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000686 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700687 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
688 for i, c in enumerate(self._calls_done[-N:]))
689 following_calls = '\n '.join(
690 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
691 for i, c in enumerate(self.calls[:N]))
692 extended_msg = (
693 'A few prior calls:\n %s\n\n'
694 'This (expected):\n @%d: %r\n'
695 'This (actual):\n @%d: %r\n\n'
696 'A few following expected calls:\n %s' %
697 (prior_calls, len(self._calls_done), expected_args,
698 len(self._calls_done), args, following_calls))
699 git_cl.logging.error(extended_msg)
700
tandrii99a72f22016-08-17 14:33:24 -0700701 self.fail('@%d\n'
702 ' Expected: %r\n'
703 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700704 len(self._calls_done), expected_args, args))
705
706 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700707 if isinstance(result, Exception):
708 raise result
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000709 return result
710
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100711 def test_ask_for_explicit_yes_true(self):
712 self.calls = [
713 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
714 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
715 ]
716 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
717
tandrii48df5812016-10-17 03:55:37 -0700718 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000719 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700720 self.calls = [
721 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700722 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
723 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
724 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
725 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700726 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
727 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700728 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
729 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000730 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
731 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700732 ((['git', 'config', 'gerrit.host', 'true'],), ''),
733 ]
734 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
735
maruel@chromium.orga3353652011-11-30 14:26:57 +0000736 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000737 def _is_gerrit_calls(cls, gerrit=False):
738 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
739 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
740
741 @classmethod
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000742 def _git_post_upload_calls(cls):
743 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000744 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
745 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
746 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000747 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000748 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000749 ]
750
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000751 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000752 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000753 fake_ancestor = 'fake_ancestor'
754 fake_cl = 'fake_cl_for_patch'
755 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000756 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000757 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000758 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000759 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000760 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000761 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000762 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000763 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700764 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000765 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000766 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000767 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000768 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000769 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000770 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000771 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000772 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000773 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000774 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000775 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000776
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000777 @classmethod
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000778 def _gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000779 cls, issue=None, skip_auth_check=False, short_hostname='chromium',
780 custom_cl_base=None):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000781 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000782 if skip_auth_check:
783 return [((cmd, ), 'true')]
784
tandrii5d48c322016-08-18 16:19:37 -0700785 calls = [((cmd, ), CERR1)]
Edward Lemurf38bc172019-09-03 21:02:13 +0000786
787 if custom_cl_base:
788 calls += [
789 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
790 ]
791
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000792 calls.extend([
793 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
794 ((['git', 'config', 'branch.master.remote'],), 'origin'),
795 ((['git', 'config', 'remote.origin.url'],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000796 'https://%s.googlesource.com/my/repo' % short_hostname),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000797 ])
Edward Lemurf38bc172019-09-03 21:02:13 +0000798
799 calls += [
800 ((['git', 'config', 'branch.master.gerritissue'],),
801 CERR1 if issue is None else str(issue)),
802 ]
803
Daniel Chengcf6269b2019-05-18 01:02:12 +0000804 if issue:
805 calls.extend([
806 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
807 ])
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000808 return calls
809
810 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100811 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200812 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000813 custom_cl_base=None, short_hostname='chromium',
814 change_id=None):
Aaron Gable13101a62018-02-09 13:20:41 -0800815 calls = cls._is_gerrit_calls(True)
Edward Lemurf38bc172019-09-03 21:02:13 +0000816 if not custom_cl_base:
817 calls += [
818 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
819 ]
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200820
821 if custom_cl_base:
822 ancestor_revision = custom_cl_base
823 else:
824 # Determine ancestor_revision to be merge base.
825 ancestor_revision = 'fake_ancestor_sha'
826 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000827 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000828 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000829 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200830 'refs/remotes/origin/master'],), ancestor_revision),
831 ]
832
833 # Calls to verify branch point is ancestor
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000834 calls += cls._gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000835 issue=issue, short_hostname=short_hostname,
836 custom_cl_base=custom_cl_base)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100837
838 if issue:
839 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000840 (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +0000841 'my%2Frepo~123456',
Andrii Shyshkalovc4a73562018-09-25 18:40:17 +0000842 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
843 ),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100844 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100845 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Anthony Polito8b955342019-09-24 19:01:36 +0000846 'change_id': (change_id or '123456789'),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100847 'current_revision': 'sha1_of_current_revision',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000848 'revisions': {'sha1_of_current_revision': {
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100849 'commit': {'message': fetched_description},
850 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100851 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100852 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100853 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100854 if fetched_status == 'ABANDONED':
855 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000856 (('DieWithError', 'Change https://%s-review.googlesource.com/'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100857 '123456 has been abandoned, new uploads are not '
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000858 'allowed' % short_hostname), SystemExitMock()),
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100859 ]
860 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100861 if other_cl_owner:
862 calls += [
863 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
864 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100865
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200866 calls += cls._git_sanity_checks(ancestor_revision, 'master',
867 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100868 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200869 ((['git', 'rev-parse', '--show-cdup'],), ''),
870 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000871
Aaron Gable7817f022017-12-12 09:43:17 -0800872 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
873 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200874 'M\t.gitignore\n'),
875 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100876 ]
877
878 if not issue:
879 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200880 ((['git', 'log', '--pretty=format:%s%n%n%b',
881 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000882 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100883 ]
884
885 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200886 ((['git', 'config', 'user.email'],), 'me@example.com'),
Edward Lemur2c48f242019-06-04 16:14:09 +0000887 (('time.time',), 1000,),
888 (('time.time',), 3000,),
889 (('add_repeated', 'sub_commands', {
890 'execution_time': 2000,
891 'command': 'presubmit',
892 'exit_code': 0
893 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200894 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
895 ([custom_cl_base] if custom_cl_base else
896 [ancestor_revision, 'HEAD']),),
897 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100898 ]
899 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000900
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000901 @classmethod
902 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700903 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000904 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700905 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100906 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000907 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000908 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000909 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000910 final_description=None, gitcookies_exists=True,
911 force=False):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000912 if post_amend_description is None:
913 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700914 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200915 # Determined in `_gerrit_base_calls`.
916 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
917
918 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000919
tandriia60502f2016-06-20 02:01:53 -0700920 if squash_mode == 'default':
921 calls.extend([
922 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
923 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
924 ])
925 elif squash_mode in ('override_squash', 'override_nosquash'):
926 calls.extend([
927 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
928 'true' if squash_mode == 'override_squash' else 'false'),
929 ])
930 else:
931 assert squash_mode in ('squash', 'nosquash')
932
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000933 # If issue is given, then description is fetched from Gerrit instead.
934 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000935 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200936 ((['git', 'log', '--pretty=format:%s\n\n%b',
937 ((custom_cl_base + '..') if custom_cl_base else
938 'fake_ancestor_sha..HEAD')],),
939 description),
940 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800941 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000942 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800943 else:
944 if not title:
945 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200946 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
947 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800948 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000949 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000950 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000951 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200952 (('DownloadGerritHook', False), ''),
953 # Amending of commit message to get the Change-Id.
954 ((['git', 'log', '--pretty=format:%s\n\n%b',
955 determined_ancestor_revision + '..HEAD'],),
956 description),
957 ((['git', 'commit', '--amend', '-m', description],), ''),
958 ((['git', 'log', '--pretty=format:%s\n\n%b',
959 determined_ancestor_revision + '..HEAD'],),
960 post_amend_description)
961 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000962 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000963 if force or not issue:
964 if issue:
965 calls += [
966 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
967 ]
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000968 # Prompting to edit description on first upload.
969 calls += [
Jonas Termansend0f79112019-03-22 15:28:26 +0000970 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000971 ]
Anthony Polito8b955342019-09-24 19:01:36 +0000972 if not force:
973 calls += [
974 ((['git', 'config', 'core.editor'],), ''),
975 ((['RunEditor'],), description),
976 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000977 ref_to_push = 'abcdef0123456789'
978 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200979 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
980 ((['git', 'config', 'branch.master.remote'],), 'origin'),
981 ]
982
983 if custom_cl_base is None:
984 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000985 ((['get_or_create_merge_base', 'master',
986 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000987 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200988 ]
989 parent = 'origin/master'
990 else:
991 calls += [
992 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
993 'refs/remotes/origin/master'],),
994 callError(1)), # Means not ancenstor.
995 (('ask_for_data',
996 'Do you take responsibility for cleaning up potential mess '
997 'resulting from proceeding with upload? Press Enter to upload, '
998 'or Ctrl+C to abort'), ''),
999 ]
1000 parent = custom_cl_base
1001
1002 calls += [
1003 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
1004 '0123456789abcdef'),
1005 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -07001006 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001007 ref_to_push),
1008 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001009 else:
1010 ref_to_push = 'HEAD'
1011
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001012 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00001013 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001014 ((['git', 'rev-list',
1015 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1016 ref_to_push],),
1017 '1hashPerLine\n'),
1018 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001019
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001020 metrics_arguments = []
1021
Aaron Gableafd52772017-06-27 16:40:10 -07001022 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001023 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001024 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -07001025 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001026 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001027 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001028 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -07001029 else:
1030 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001031 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -08001032
Aaron Gable70f4e242017-06-26 10:45:59 -07001033 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001034 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001035 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001036
Edward Lemur4508b422019-10-03 21:56:35 +00001037 if issue is None:
1038 calls += [
1039 ((['git', 'config', 'rietveld.cc'],), ''),
1040 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001041 if short_hostname == 'chromium':
1042 # All reviwers and ccs get into ref_suffix.
1043 for r in sorted(reviewers):
1044 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001045 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +00001046 if issue is None:
1047 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
1048 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001049 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001050 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001051 reviewers, cc = [], []
1052 else:
1053 # TODO(crbug/877717): remove this case.
1054 calls += [
1055 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
1056 sorted(reviewers) + ['joe@example.com',
1057 'chromium-reviews+test-more-cc@chromium.org'] + cc),
1058 {
1059 e: {'email': e}
1060 for e in (reviewers + ['joe@example.com'] + cc)
1061 })
1062 ]
1063 for r in sorted(reviewers):
1064 if r != 'bad-account-or-email':
1065 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001066 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001067 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +00001068 if issue is None:
1069 cc += ['joe@example.com']
1070 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001071 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001072 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001073 if c in cc:
1074 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001075
Edward Lemur687ca902018-12-05 02:30:30 +00001076 for k, v in sorted((labels or {}).items()):
1077 ref_suffix += ',l=%s+%d' % (k, v)
1078 metrics_arguments.append('l=%s+%d' % (k, v))
1079
1080 if tbr:
1081 calls += [
1082 (('GetCodeReviewTbrScore',
1083 '%s-review.googlesource.com' % short_hostname,
1084 'my/repo'),
1085 2,),
1086 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001087
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001088 calls += [
1089 (('time.time',), 1000,),
1090 ((['git', 'push',
1091 'https://%s.googlesource.com/my/repo' % short_hostname,
1092 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1093 (('remote:\n'
1094 'remote: Processing changes: (\)\n'
1095 'remote: Processing changes: (|)\n'
1096 'remote: Processing changes: (/)\n'
1097 'remote: Processing changes: (-)\n'
1098 'remote: Processing changes: new: 1 (/)\n'
1099 'remote: Processing changes: new: 1, done\n'
1100 'remote:\n'
1101 'remote: New Changes:\n'
1102 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1103 ' XXX\n'
1104 'remote:\n'
1105 'To https://%s.googlesource.com/my/repo\n'
1106 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1107 ) % (short_hostname, short_hostname)),),
1108 (('time.time',), 2000,),
1109 (('add_repeated',
1110 'sub_commands',
1111 {
1112 'execution_time': 1000,
1113 'command': 'git push',
1114 'exit_code': 0,
1115 'arguments': sorted(metrics_arguments),
1116 }),
1117 None,),
1118 ]
1119
Edward Lemur1b52d872019-05-09 21:12:12 +00001120 final_description = final_description or post_amend_description.strip()
1121 original_title = original_title or title or '<untitled>'
1122 # Trace-related calls
1123 calls += [
1124 # Write a description with context for the current trace.
1125 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001126 'Thu Mar 16 20:00:41 2017\n'
1127 '%(short_hostname)s-review.googlesource.com\n'
1128 '%(change_id)s\n'
1129 '%(title)s\n'
1130 '%(description)s\n'
1131 '1000\n'
1132 '0\n'
1133 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001134 'short_hostname': short_hostname,
1135 'change_id': change_id,
1136 'description': final_description,
1137 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001138 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001139 }],),
1140 None,
1141 ),
1142 # Read traces and shorten git hashes.
1143 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1144 True,
1145 ),
1146 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1147 ('git-hash: 0123456789012345678901234567890123456789\n'
1148 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1149 ),
1150 ((['FileWrite', 'TEMP_DIR/trace-packet',
1151 'git-hash: 012345\n'
1152 'git-hash: abcdea\n'],),
1153 None,
1154 ),
1155 # Make zip file for the git traces.
1156 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1157 'TEMP_DIR'],),
1158 None,
1159 ),
1160 # Collect git config and gitcookies.
1161 ((['git', 'config', '-l'],),
1162 'git-config-output',
1163 ),
1164 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1165 None,
1166 ),
1167 ((['os.path.isfile', '~/.gitcookies'],),
1168 gitcookies_exists,
1169 ),
1170 ]
1171 if gitcookies_exists:
1172 calls += [
1173 ((['FileRead', '~/.gitcookies'],),
1174 'gitcookies 1/SECRET',
1175 ),
1176 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1177 None,
1178 ),
1179 ]
1180 calls += [
1181 # Make zip file for the git config and gitcookies.
1182 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1183 'TEMP_DIR'],),
1184 None,
1185 ),
1186 ]
1187
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001188 if squash:
1189 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001190 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001191 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001192 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001193 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001194 ((['git', 'config', 'branch.master.gerritsquashhash',
1195 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001196 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001197 # TODO(crbug/877717): this should never be used.
1198 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001199 calls += [
1200 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001201 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001202 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001203 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1204 notify),
1205 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001206 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001207 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001208 return calls
1209
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001210 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001211 self,
1212 upload_args,
1213 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001214 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001215 squash=True,
1216 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001217 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001218 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001219 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001220 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001221 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001222 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001223 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001224 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001225 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001226 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001227 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001228 labels=None,
1229 change_id=None,
1230 original_title=None,
1231 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001232 gitcookies_exists=True,
1233 force=False,
1234 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001235 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001236 if squash_mode is None:
1237 if '--no-squash' in upload_args:
1238 squash_mode = 'nosquash'
1239 elif '--squash' in upload_args:
1240 squash_mode = 'squash'
1241 else:
1242 squash_mode = 'default'
1243
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001244 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001245 cc = cc or []
Edward Lemur79d4f992019-11-11 23:49:02 +00001246 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001247 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001248 CookiesAuthenticatorMockFactory(
1249 same_auth=('git-owner.example.com', '', 'pass')))
Edward Lemur125d60a2019-09-13 18:25:41 +00001250 self.mock(git_cl.Changelist, '_GerritCommitMsgHookCheck',
tandrii16e0b4e2016-06-07 10:34:28 -07001251 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001252 self.mock(git_cl.gclient_utils, 'RunEditor',
1253 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001254 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1255 'DownloadGerritHook', force))
Edward Lemur1b52d872019-05-09 21:12:12 +00001256 self.mock(git_cl.gclient_utils, 'FileRead',
1257 lambda path: self._mocked_call(['FileRead', path]))
1258 self.mock(git_cl.gclient_utils, 'FileWrite',
1259 lambda path, contents: self._mocked_call(
1260 ['FileWrite', path, contents]))
1261 self.mock(git_cl, 'datetime_now',
1262 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0))
1263 self.mock(git_cl.tempfile, 'mkdtemp', lambda: 'TEMP_DIR')
1264 self.mock(git_cl, 'TRACES_DIR', 'TRACES_DIR')
Edward Lemur75391d42019-05-14 23:35:56 +00001265 self.mock(git_cl, 'TRACES_README_FORMAT',
1266 '%(now)s\n'
1267 '%(gerrit_host)s\n'
1268 '%(change_id)s\n'
1269 '%(title)s\n'
1270 '%(description)s\n'
1271 '%(execution_time)s\n'
1272 '%(exit_code)s\n'
1273 '%(trace_name)s')
Edward Lemur1b52d872019-05-09 21:12:12 +00001274 self.mock(git_cl.shutil, 'make_archive',
1275 lambda *args: self._mocked_call(['make_archive'] + list(args)))
1276 self.mock(os.path, 'isfile',
1277 lambda path: self._mocked_call(['os.path.isfile', path]))
tandriia60502f2016-06-20 02:01:53 -07001278
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001279 self.calls = self._gerrit_base_calls(
1280 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001281 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001282 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001283 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001284 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001285 short_hostname=short_hostname,
1286 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001287 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001288 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
1289 expected_content=description))
1290 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001291 self.calls += self._gerrit_upload_calls(
1292 description, reviewers, squash,
1293 squash_mode=squash_mode,
1294 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001295 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001296 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001297 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001298 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001299 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001300 labels=labels,
1301 change_id=change_id,
1302 original_title=original_title,
1303 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001304 gitcookies_exists=gitcookies_exists,
1305 force=force)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001306 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001307 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001308 git_cl.main(['upload'] + upload_args)
1309
Edward Lemur1b52d872019-05-09 21:12:12 +00001310 def test_gerrit_upload_traces_no_gitcookies(self):
1311 self._run_gerrit_upload_test(
1312 ['--no-squash'],
1313 'desc\n\nBUG=\n',
1314 [],
1315 squash=False,
1316 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1317 change_id='Ixxx',
1318 gitcookies_exists=False)
1319
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001320 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001321 self._run_gerrit_upload_test(
1322 ['--no-squash'],
1323 'desc\n\nBUG=\n',
1324 [],
1325 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001326 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1327 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001328
1329 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001330 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001331 [],
jamesr@chromium.org35d1a842012-07-27 00:20:43 +00001332 'desc\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001333 [],
tandriia60502f2016-06-20 02:01:53 -07001334 squash=False,
1335 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001336 post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
1337 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001338
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001339 def test_gerrit_no_reviewer(self):
1340 self._run_gerrit_upload_test(
1341 [],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001342 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001343 [],
1344 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001345 squash_mode='override_nosquash',
1346 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001347
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001348 def test_gerrit_no_reviewer_non_chromium_host(self):
1349 # TODO(crbug/877717): remove this test case.
1350 self._run_gerrit_upload_test(
1351 [],
1352 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
1353 [],
1354 squash=False,
1355 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001356 short_hostname='other',
1357 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001358
Nick Carter8692b182017-11-06 16:30:38 -08001359 def test_gerrit_patchset_title_special_chars(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00001360 self.mock(git_cl.sys, 'stdout', StringIO())
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001361 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001362 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001363 'desc\n\nBUG=\n\nChange-Id: I123456789',
1364 squash=False,
1365 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001366 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1367 change_id='I123456789',
1368 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001369
ukai@chromium.orge8077812012-02-03 03:41:46 +00001370 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001371 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001372 ['-r', 'foo@example.com', '--send-mail'],
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001373 'desc\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001374 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001375 squash=False,
1376 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001377 notify=True,
1378 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001379 final_description=(
1380 'desc\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001381
Anthony Polito8b955342019-09-24 19:01:36 +00001382 def test_gerrit_upload_force_sets_bug(self):
1383 self._run_gerrit_upload_test(
1384 ['-b', '10000', '-f'],
1385 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1386 [],
1387 force=True,
1388 expected_upstream_ref='origin/master',
1389 fetched_description='desc=\n\nChange-Id: Ixxx',
1390 original_title='Initial upload',
1391 change_id='Ixxx')
1392
1393 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1394 self._run_gerrit_upload_test(
1395 ['-b', '10000', '-f', '-m', 'Title'],
1396 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1397 [],
1398 force=True,
1399 issue='123456',
1400 expected_upstream_ref='origin/master',
1401 fetched_description='desc=\n\nChange-Id: Ixxxx',
1402 original_title='Title',
1403 title='Title',
1404 change_id='Izzzz')
1405
Dan Beamd8b04ca2019-10-10 21:23:26 +00001406 def test_gerrit_upload_force_sets_fixed(self):
1407 self._run_gerrit_upload_test(
1408 ['-x', '10000', '-f'],
1409 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1410 [],
1411 force=True,
1412 expected_upstream_ref='origin/master',
1413 fetched_description='desc=\n\nChange-Id: Ixxx',
1414 original_title='Initial upload',
1415 change_id='Ixxx')
1416
ukai@chromium.orge8077812012-02-03 03:41:46 +00001417 def test_gerrit_reviewer_multiple(self):
Edward Lemur687ca902018-12-05 02:30:30 +00001418 self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
1419 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001420 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001421 [],
bradnelsond975b302016-10-23 12:20:23 -07001422 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
1423 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001424 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001425 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001426 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001427 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001428 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001429 labels={'Code-Review': 2},
1430 change_id='123456789',
1431 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001432
1433 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001434 self._run_gerrit_upload_test(
1435 [],
1436 'desc\nBUG=\n\nChange-Id: 123456789',
1437 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001438 expected_upstream_ref='origin/master',
1439 change_id='123456789',
1440 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001441
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001442 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001443 self._run_gerrit_upload_test(
1444 ['--squash'],
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001445 'desc\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001446 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001447 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001448 expected_upstream_ref='origin/master',
1449 change_id='123456789',
1450 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001451
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001452 def test_gerrit_upload_squash_first_with_labels(self):
1453 self._run_gerrit_upload_test(
1454 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
1455 'desc\nBUG=\n\nChange-Id: 123456789',
1456 [],
1457 squash=True,
1458 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001459 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1460 change_id='123456789',
1461 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001462
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001463 def test_gerrit_upload_squash_first_against_rev(self):
1464 custom_cl_base = 'custom_cl_base_rev_or_branch'
1465 self._run_gerrit_upload_test(
1466 ['--squash', custom_cl_base],
1467 'desc\nBUG=\n\nChange-Id: 123456789',
1468 [],
1469 squash=True,
1470 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001471 custom_cl_base=custom_cl_base,
1472 change_id='123456789',
1473 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001474 self.assertIn(
1475 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1476 sys.stdout.getvalue())
1477
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001478 def test_gerrit_upload_squash_reupload(self):
1479 description = 'desc\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001480 self._run_gerrit_upload_test(
1481 ['--squash'],
1482 description,
1483 [],
1484 squash=True,
1485 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001486 issue=123456,
1487 change_id='123456789',
1488 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001489
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001490 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1491 self.mock(git_cl, 'DieWithError',
1492 lambda msg, change=None: self._mocked_call('DieWithError', msg))
1493 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1494 with self.assertRaises(SystemExitMock):
1495 self._run_gerrit_upload_test(
1496 ['--squash'],
1497 description,
1498 [],
1499 squash=True,
1500 expected_upstream_ref='origin/master',
1501 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001502 fetched_status='ABANDONED',
1503 change_id='123456789')
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001504
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001505 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1506 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1507 lambda *_, **__: {'email': 'yet-another@example.com'})
1508 description = 'desc\nBUG=\n\nChange-Id: 123456789'
1509 self._run_gerrit_upload_test(
1510 ['--squash'],
1511 description,
1512 [],
1513 squash=True,
1514 expected_upstream_ref='origin/master',
1515 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001516 other_cl_owner='other@example.com',
1517 change_id='123456789',
1518 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001519 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001520 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001521 'authenticate to Gerrit as yet-another@example.com.\n'
1522 'Uploading may fail due to lack of permissions',
1523 git_cl.sys.stdout.getvalue())
1524
rmistry@google.com2dd99862015-06-22 12:22:18 +00001525 def test_upload_branch_deps(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00001526 self.mock(git_cl.sys, 'stdout', StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001527 def mock_run_git(*args, **_kwargs):
1528 if args[0] == ['for-each-ref',
1529 '--format=%(refname:short) %(upstream:short)',
1530 'refs/heads']:
1531 # Create a local branch dependency tree that looks like this:
1532 # test1 -> test2 -> test3 -> test4 -> test5
1533 # -> test3.1
1534 # test6 -> test0
1535 branch_deps = [
1536 'test2 test1', # test1 -> test2
1537 'test3 test2', # test2 -> test3
1538 'test3.1 test2', # test2 -> test3.1
1539 'test4 test3', # test3 -> test4
1540 'test5 test4', # test4 -> test5
1541 'test6 test0', # test0 -> test6
1542 'test7', # test7
1543 ]
1544 return '\n'.join(branch_deps)
1545 self.mock(git_cl, 'RunGit', mock_run_git)
1546
1547 class RecordCalls:
1548 times_called = 0
1549 record_calls = RecordCalls()
1550 def mock_CMDupload(*args, **_kwargs):
1551 record_calls.times_called += 1
1552 return 0
1553 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1554
1555 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001556 (('ask_for_data', 'This command will checkout all dependent branches '
1557 'and run "git cl upload". Press Enter to continue, '
1558 'or Ctrl+C to abort'), ''),
1559 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001560
1561 class MockChangelist():
1562 def __init__(self):
1563 pass
1564 def GetBranch(self):
1565 return 'test1'
1566 def GetIssue(self):
1567 return '123'
1568 def GetPatchset(self):
1569 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001570 def IsGerrit(self):
1571 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001572
1573 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1574 # CMDupload should have been called 5 times because of 5 dependent branches.
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001575 self.assertEqual(5, record_calls.times_called)
1576 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001577
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001578 def test_gerrit_change_id(self):
1579 self.calls = [
1580 ((['git', 'write-tree'], ),
1581 'hashtree'),
1582 ((['git', 'rev-parse', 'HEAD~0'], ),
1583 'branch-parent'),
1584 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1585 'A B <a@b.org> 1456848326 +0100'),
1586 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1587 'C D <c@d.org> 1456858326 +0100'),
1588 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1589 'hashchange'),
1590 ]
1591 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1592 self.assertEqual(change_id, 'Ihashchange')
1593
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001594 def test_desecription_append_footer(self):
1595 for init_desc, footer_line, expected_desc in [
1596 # Use unique desc first lines for easy test failure identification.
1597 ('foo', 'R=one', 'foo\n\nR=one'),
1598 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1599 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1600 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1601 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1602 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1603 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1604 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1605 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1606 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1607 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1608 ]:
1609 desc = git_cl.ChangeDescription(init_desc)
1610 desc.append_footer(footer_line)
1611 self.assertEqual(desc.description, expected_desc)
1612
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001613 def test_update_reviewers(self):
1614 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001615 ('foo', [], [],
1616 'foo'),
1617 ('foo\nR=xx', [], [],
1618 'foo\nR=xx'),
1619 ('foo\nTBR=xx', [], [],
1620 'foo\nTBR=xx'),
1621 ('foo', ['a@c'], [],
1622 'foo\n\nR=a@c'),
1623 ('foo\nR=xx', ['a@c'], [],
1624 'foo\n\nR=a@c, xx'),
1625 ('foo\nTBR=xx', ['a@c'], [],
1626 'foo\n\nR=a@c\nTBR=xx'),
1627 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1628 'foo\n\nR=a@c, yy\nTBR=xx'),
1629 ('foo\nBUG=', ['a@c'], [],
1630 'foo\nBUG=\nR=a@c'),
1631 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1632 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1633 ('foo', ['a@c', 'b@c'], [],
1634 'foo\n\nR=a@c, b@c'),
1635 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1636 'foo\nBar\n\nR=c@c\nBUG='),
1637 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1638 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001639 # Same as the line before, but full of whitespaces.
1640 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001641 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001642 'foo\nBar\n\nR=c@c\n BUG =',
1643 ),
1644 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001645 ('foo BUG=allo R=joe ', ['c@c'], [],
1646 'foo BUG=allo R=joe\n\nR=c@c'),
1647 # Redundant TBRs get promoted to Rs
1648 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1649 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001650 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001651 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001652 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001653 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001654 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001655 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001656 actual.append(obj.description)
1657 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001658
Nodir Turakulov23b82142017-11-16 11:04:25 -08001659 def test_get_hash_tags(self):
1660 cases = [
1661 ('', []),
1662 ('a', []),
1663 ('[a]', ['a']),
1664 ('[aa]', ['aa']),
1665 ('[a ]', ['a']),
1666 ('[a- ]', ['a']),
1667 ('[a- b]', ['a-b']),
1668 ('[a--b]', ['a-b']),
1669 ('[a', []),
1670 ('[a]x', ['a']),
1671 ('[aa]x', ['aa']),
1672 ('[a b]', ['a-b']),
1673 ('[a b]', ['a-b']),
1674 ('[a__b]', ['a-b']),
1675 ('[a] x', ['a']),
1676 ('[a][b]', ['a', 'b']),
1677 ('[a] [b]', ['a', 'b']),
1678 ('[a][b]x', ['a', 'b']),
1679 ('[a][b] x', ['a', 'b']),
1680 ('[a]\n[b]', ['a']),
1681 ('[a\nb]', []),
1682 ('[a][', ['a']),
1683 ('Revert "[a] feature"', ['a']),
1684 ('Reland "[a] feature"', ['a']),
1685 ('Revert: [a] feature', ['a']),
1686 ('Reland: [a] feature', ['a']),
1687 ('Revert "Reland: [a] feature"', ['a']),
1688 ('Foo: feature', ['foo']),
1689 ('Foo Bar: feature', ['foo-bar']),
1690 ('Revert "Foo bar: feature"', ['foo-bar']),
1691 ('Reland "Foo bar: feature"', ['foo-bar']),
1692 ]
1693 for desc, expected in cases:
1694 change_desc = git_cl.ChangeDescription(desc)
1695 actual = change_desc.get_hash_tags()
1696 self.assertEqual(
1697 actual,
1698 expected,
1699 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1700
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001701 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001702 self.assertEqual(None, git_cl.GetTargetRef(None,
1703 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001704 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001705
wittman@chromium.org455dc922015-01-26 20:15:50 +00001706 # Check default target refs for branches.
1707 self.assertEqual('refs/heads/master',
1708 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001709 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001710 self.assertEqual('refs/heads/master',
1711 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001712 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001713 self.assertEqual('refs/heads/master',
1714 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001715 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001716 self.assertEqual('refs/branch-heads/123',
1717 git_cl.GetTargetRef('origin',
1718 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001719 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001720 self.assertEqual('refs/diff/test',
1721 git_cl.GetTargetRef('origin',
1722 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001723 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001724 self.assertEqual('refs/heads/chrome/m42',
1725 git_cl.GetTargetRef('origin',
1726 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001727 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001728
1729 # Check target refs for user-specified target branch.
1730 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1731 'refs/remotes/branch-heads/123'):
1732 self.assertEqual('refs/branch-heads/123',
1733 git_cl.GetTargetRef('origin',
1734 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001735 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001736 for branch in ('origin/master', 'remotes/origin/master',
1737 'refs/remotes/origin/master'):
1738 self.assertEqual('refs/heads/master',
1739 git_cl.GetTargetRef('origin',
1740 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001741 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001742 for branch in ('master', 'heads/master', 'refs/heads/master'):
1743 self.assertEqual('refs/heads/master',
1744 git_cl.GetTargetRef('origin',
1745 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001746 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001747
wychen@chromium.orga872e752015-04-28 23:42:18 +00001748 def test_patch_when_dirty(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001749 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001750 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1751 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1752
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001753 @staticmethod
1754 def _get_gerrit_codereview_server_calls(branch, value=None,
1755 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001756 detect_branch=True,
1757 detect_server=True):
Edward Lemur125d60a2019-09-13 18:25:41 +00001758 """Returns calls executed by Changelist.GetCodereviewServer.
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001759
1760 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1761 """
1762 calls = []
1763 if detect_branch:
1764 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001765 if detect_server:
1766 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1767 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001768 if value is None:
1769 calls += [
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001770 ((['git', 'config', 'branch.' + branch + '.merge'],),
1771 'refs/heads' + branch),
1772 ((['git', 'config', 'branch.' + branch + '.remote'],),
1773 'origin'),
1774 ((['git', 'config', 'remote.origin.url'],),
1775 'https://%s.googlesource.com/my/repo' % git_short_host),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001776 ]
1777 return calls
1778
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001779 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001780 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001781 detect_gerrit_server=False,
1782 actual_codereview=None,
1783 codereview_in_url=False):
Edward Lemur79d4f992019-11-11 23:49:02 +00001784 self.mock(git_cl.sys, 'stdout', StringIO())
wychen@chromium.orga872e752015-04-28 23:42:18 +00001785 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1786
tandriidf09a462016-08-18 16:23:55 -07001787 if new_branch:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001788 self.calls = [((['git', 'new-branch', 'master'],), '')]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001789
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001790 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001791 self.calls += [
1792 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001793 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001794 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001795
1796 if not force_codereview and not codereview_in_url:
1797 # These calls detect codereview to use.
1798 self.calls += [
1799 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001800 ]
1801 if detect_gerrit_server:
1802 self.calls += self._get_gerrit_codereview_server_calls(
1803 'master', git_short_host=git_short_host,
1804 detect_branch=not new_branch and force_codereview)
1805 actual_codereview = 'gerrit'
1806
1807 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001808 self.calls += [
1809 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001810 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001811 {
1812 'current_revision': '7777777777',
1813 'revisions': {
1814 '1111111111': {
1815 '_number': 1,
1816 'fetch': {'http': {
1817 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1818 'ref': 'refs/changes/56/123456/1',
1819 }},
1820 },
1821 '7777777777': {
1822 '_number': 7,
1823 'fetch': {'http': {
1824 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1825 'ref': 'refs/changes/56/123456/7',
1826 }},
1827 },
1828 },
1829 }),
1830 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001831
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001832 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001833 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001834 self.calls += [
1835 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1836 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001837 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001838 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001839 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001840 ((['git', 'config', 'branch.master.gerritserver',
1841 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001842 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001843 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1844 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1845 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001846 ]
1847 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1848
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001849 def test_patch_gerrit_new_branch(self):
1850 self._patch_common(
1851 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1852 self.calls += [
1853 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1854 'refs/changes/56/123456/7'],), ''),
1855 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1856 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1857 ''),
1858 ((['git', 'config', 'branch.master.gerritserver',
1859 'https://chromium-review.googlesource.com'],), ''),
1860 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1861 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1862 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1863 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1864 ]
1865 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1866
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001867 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001868 self._patch_common(
1869 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001870 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001871 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001872 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001873 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001874 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001875 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001876 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001877 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001878 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001879 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1880 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1881 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001882 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001883 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001884
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001885 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001886 self.calls += self._get_gerrit_codereview_server_calls(
1887 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001888 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001889 actual_codereview='gerrit', git_short_host='else',
1890 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001891 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001892 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001893 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001894 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001895 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001896 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001897 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001898 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001899 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001900 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1901 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1902 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001903 ]
1904 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001905 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001906
Aaron Gable697a91b2018-01-19 15:20:15 -08001907 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001908 self.calls += self._get_gerrit_codereview_server_calls(
1909 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001910 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001911 actual_codereview='gerrit', git_short_host='else',
1912 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001913 self.calls += [
1914 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1915 'refs/changes/56/123456/1'],), ''),
1916 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1917 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1918 ''),
1919 ((['git', 'config', 'branch.master.gerritserver',
1920 'https://else-review.googlesource.com'],), ''),
1921 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1922 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1923 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1924 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1925 ]
1926 self.assertEqual(git_cl.main(
1927 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1928 0)
1929
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001930 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001931 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001932 self.calls += [
1933 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001934 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001935 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1936 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1937 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001938 ]
1939 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001940 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001941
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001942 def test_patch_gerrit_not_exists(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001943
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001944 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001945 raise git_cl.gerrit_util.GerritError(404, '')
1946 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1947
tandriic2405f52016-10-10 08:13:15 -07001948 self.calls = [
1949 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001950 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1951 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1952 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1953 ((['git', 'config', 'remote.origin.url'],),
1954 'https://chromium.googlesource.com/my/repo'),
1955 ((['DieWithError',
1956 'change 123456 at https://chromium-review.googlesource.com does not '
1957 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001958 ]
1959 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001960 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001961
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001962 def _checkout_calls(self):
1963 return [
1964 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001965 'branch\\..*\\.gerritissue'], ),
1966 ('branch.ger-branch.gerritissue 123456\n'
1967 'branch.gbranch654.gerritissue 654321\n')),
1968 ]
1969
1970 def test_checkout_gerrit(self):
1971 """Tests git cl checkout <issue>."""
1972 self.calls = self._checkout_calls()
1973 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1974 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1975
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001976 def test_checkout_not_found(self):
1977 """Tests git cl checkout <issue>."""
Edward Lemur79d4f992019-11-11 23:49:02 +00001978 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001979 self.calls = self._checkout_calls()
1980 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1981
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001982 def test_checkout_no_branch_issues(self):
1983 """Tests git cl checkout <issue>."""
Edward Lemur79d4f992019-11-11 23:49:02 +00001984 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001985 self.calls = [
1986 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001987 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001988 ]
1989 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1990
tandrii@chromium.org28253532016-04-14 13:46:56 +00001991 def _test_gerrit_ensure_authenticated_common(self, auth,
1992 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001993 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
1994 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
1995 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11001996 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00001997 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
Edward Lemurf38bc172019-09-03 21:02:13 +00001998 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00001999 cl.branch = 'master'
2000 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002001 return cl
2002
2003 def test_gerrit_ensure_authenticated_missing(self):
2004 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002005 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002006 })
2007 self.calls.append(
2008 ((['DieWithError',
2009 'Credentials for the following hosts are required:\n'
2010 ' chromium-review.googlesource.com\n'
2011 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002012 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002013 'https://chromium-review.googlesource.com/new-password'],), ''),)
2014 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2015
2016 def test_gerrit_ensure_authenticated_conflict(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002017 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002018 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002019 'chromium.googlesource.com':
2020 ('git-one.example.com', None, 'secret1'),
2021 'chromium-review.googlesource.com':
2022 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002023 })
2024 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002025 (('ask_for_data', 'If you know what you are doing '
2026 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002027 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2028
2029 def test_gerrit_ensure_authenticated_ok(self):
2030 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002031 'chromium.googlesource.com':
2032 ('git-same.example.com', None, 'secret'),
2033 'chromium-review.googlesource.com':
2034 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002035 })
2036 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2037
tandrii@chromium.org28253532016-04-14 13:46:56 +00002038 def test_gerrit_ensure_authenticated_skipped(self):
2039 cl = self._test_gerrit_ensure_authenticated_common(
2040 auth={}, skip_auth_check=True)
2041 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2042
Eric Boren2fb63102018-10-05 13:05:03 +00002043 def test_gerrit_ensure_authenticated_bearer_token(self):
2044 cl = self._test_gerrit_ensure_authenticated_common(auth={
2045 'chromium.googlesource.com':
2046 ('', None, 'secret'),
2047 'chromium-review.googlesource.com':
2048 ('', None, 'secret'),
2049 })
2050 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2051 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2052 'chromium.googlesource.com')
2053 self.assertTrue('Bearer' in header)
2054
Daniel Chengcf6269b2019-05-18 01:02:12 +00002055 def test_gerrit_ensure_authenticated_non_https(self):
2056 self.calls = [
2057 ((['git', 'config', '--bool',
2058 'gerrit.skip-ensure-authenticated'],), CERR1),
2059 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
2060 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2061 ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
2062 ]
2063 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2064 CookiesAuthenticatorMockFactory(hosts_with_creds={}))
Edward Lemurf38bc172019-09-03 21:02:13 +00002065 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00002066 cl.branch = 'master'
2067 cl.branchref = 'refs/heads/master'
2068 cl.lookedup_issue = True
2069 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2070
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002071 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002072 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002073 lambda h, i, labels, notify=None:
2074 self._mocked_call(['SetReview', h, i, labels, notify]))
2075
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002076 self.calls = [
2077 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002078 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002079 ((['git', 'config', 'branch.feature.gerritserver'],),
2080 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002081 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2082 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2083 ((['git', 'config', 'remote.origin.url'],),
2084 'https://chromium.googlesource.com/infra/infra.git'),
2085 ((['SetReview', 'chromium-review.googlesource.com',
2086 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002087 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002088 ]
tandriid9e5ce52016-07-13 02:32:59 -07002089
2090 def test_cmd_set_commit_gerrit_clear(self):
2091 self._cmd_set_commit_gerrit_common(0)
2092 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2093
2094 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002095 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002096 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2097
tandriid9e5ce52016-07-13 02:32:59 -07002098 def test_cmd_set_commit_gerrit(self):
2099 self._cmd_set_commit_gerrit_common(2)
2100 self.assertEqual(0, git_cl.main(['set-commit']))
2101
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002102 def test_description_display(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002103 out = StringIO()
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002104 self.mock(git_cl.sys, 'stdout', out)
2105
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002106 self.mock(git_cl, 'Changelist', ChangelistMock)
2107 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002108
2109 self.assertEqual(0, git_cl.main(['description', '-d']))
2110 self.assertEqual('foo\n', out.getvalue())
2111
iannucci3c972b92016-08-17 13:24:10 -07002112 def test_StatusFieldOverrideIssueMissingArgs(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002113 out = StringIO()
iannucci3c972b92016-08-17 13:24:10 -07002114 self.mock(git_cl.sys, 'stderr', out)
2115
2116 try:
2117 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2118 except SystemExit as ex:
2119 self.assertEqual(ex.code, 2)
Edward Lemurf38bc172019-09-03 21:02:13 +00002120 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002121
Edward Lemur79d4f992019-11-11 23:49:02 +00002122 out = StringIO()
iannucci3c972b92016-08-17 13:24:10 -07002123 self.mock(git_cl.sys, 'stderr', out)
2124
2125 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002126 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07002127 except SystemExit as ex:
2128 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002129 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002130
2131 def test_StatusFieldOverrideIssue(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002132 out = StringIO()
iannucci3c972b92016-08-17 13:24:10 -07002133 self.mock(git_cl.sys, 'stdout', out)
2134
2135 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002136 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002137 return 'foobar'
2138
2139 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07002140 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002141 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002142 0)
iannucci3c972b92016-08-17 13:24:10 -07002143 self.assertEqual(out.getvalue(), 'foobar\n')
2144
iannuccie53c9352016-08-17 14:40:40 -07002145 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002146
iannuccie53c9352016-08-17 14:40:40 -07002147 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002148 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002149 return 'foobar'
2150
2151 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2152 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07002153 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002154 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002155
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002156 def test_description(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002157 out = StringIO()
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002158 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002159 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002160 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2161 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2162 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2163 ((['git', 'config', 'remote.origin.url'],),
2164 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002165 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002166 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002167 {
2168 'current_revision': 'sha1',
2169 'revisions': {'sha1': {
2170 'commit': {'message': 'foobar'},
2171 }},
2172 }),
2173 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002174 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002175 'description',
2176 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2177 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002178 self.assertEqual('foobar\n', out.getvalue())
2179
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002180 def test_description_set_raw(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002181 out = StringIO()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002182 self.mock(git_cl.sys, 'stdout', out)
2183
2184 self.mock(git_cl, 'Changelist', ChangelistMock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002185 self.mock(git_cl.sys, 'stdin', StringIO('hihi'))
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002186
2187 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2188 self.assertEqual('hihi', ChangelistMock.desc)
2189
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002190 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002191 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002192
2193 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002194 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002195 '# Enter a description of the change.\n'
2196 '# This will be displayed on the codereview site.\n'
2197 '# The first line will also be used as the subject of the review.\n'
2198 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002199 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002200 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002201 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002202 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002203 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002204
dsansomee2d6fd92016-09-08 00:10:47 -07002205 def UpdateDescriptionRemote(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002206 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002207
Edward Lemur79d4f992019-11-11 23:49:02 +00002208 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002209 self.mock(git_cl.Changelist, 'GetDescription',
2210 lambda *args: current_desc)
Edward Lemur125d60a2019-09-13 18:25:41 +00002211 self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002212 UpdateDescriptionRemote)
2213 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2214
2215 self.calls = [
2216 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002217 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002218 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2219 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002220 ((['git', 'config', 'core.editor'],), 'vi'),
2221 ]
2222 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2223
Dan Beamd8b04ca2019-10-10 21:23:26 +00002224 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2225 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2226
2227 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002228 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002229 '# Enter a description of the change.\n'
2230 '# This will be displayed on the codereview site.\n'
2231 '# The first line will also be used as the subject of the review.\n'
2232 '#--------------------This line is 72 characters long'
2233 '--------------------\n'
2234 'Some.\n\nFixed: 123\nChange-Id: xxx',
2235 desc)
2236 return desc
2237
Edward Lemur79d4f992019-11-11 23:49:02 +00002238 self.mock(git_cl.sys, 'stdout', StringIO())
Dan Beamd8b04ca2019-10-10 21:23:26 +00002239 self.mock(git_cl.Changelist, 'GetDescription',
2240 lambda *args: current_desc)
2241 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2242
2243 self.calls = [
2244 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2245 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2246 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2247 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
2248 ((['git', 'config', 'core.editor'],), 'vi'),
2249 ]
2250 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2251
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002252 def test_description_set_stdin(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002253 out = StringIO()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002254 self.mock(git_cl.sys, 'stdout', out)
2255
2256 self.mock(git_cl, 'Changelist', ChangelistMock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002257 self.mock(git_cl.sys, 'stdin', StringIO('hi \r\n\t there\n\nman'))
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002258
2259 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2260 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2261
kmarshall3bff56b2016-06-06 18:31:47 -07002262 def test_archive(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002263 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii1c67da62016-06-10 07:35:53 -07002264
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002265 self.calls = [
2266 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002267 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002268 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2269 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002270 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002271 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002272
kmarshall3bff56b2016-06-06 18:31:47 -07002273 self.mock(git_cl, 'get_cl_statuses',
2274 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002275 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2276 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2277 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002278
2279 self.assertEqual(0, git_cl.main(['archive', '-f']))
2280
2281 def test_archive_current_branch_fails(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002282 self.mock(git_cl.sys, 'stdout', StringIO())
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002283 self.calls = [
2284 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2285 'refs/heads/master'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002286 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2287 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002288
kmarshall9249e012016-08-23 12:02:16 -07002289 self.mock(git_cl, 'get_cl_statuses',
2290 lambda branches, fine_grained, max_processes:
2291 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2292
2293 self.assertEqual(1, git_cl.main(['archive', '-f']))
2294
2295 def test_archive_dry_run(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002296 self.mock(git_cl.sys, 'stdout', StringIO())
kmarshall9249e012016-08-23 12:02:16 -07002297
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002298 self.calls = [
2299 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2300 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002301 ((['git', 'symbolic-ref', 'HEAD'],), 'master')
2302 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002303
2304 self.mock(git_cl, 'get_cl_statuses',
2305 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002306 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2307 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2308 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002309
kmarshall9249e012016-08-23 12:02:16 -07002310 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2311
2312 def test_archive_no_tags(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002313 self.mock(git_cl.sys, 'stdout', StringIO())
kmarshall9249e012016-08-23 12:02:16 -07002314
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002315 self.calls = [
2316 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2317 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002318 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2319 ((['git', 'branch', '-D', 'foo'],), '')
2320 ]
kmarshall9249e012016-08-23 12:02:16 -07002321
2322 self.mock(git_cl, 'get_cl_statuses',
2323 lambda branches, fine_grained, max_processes:
2324 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2325 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2326 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2327
2328 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002329
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002330 def test_cmd_issue_erase_existing(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002331 out = StringIO()
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002332 self.mock(git_cl.sys, 'stdout', out)
2333 self.calls = [
2334 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002335 # Let this command raise exception (retcode=1) - it should be ignored.
2336 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002337 CERR1),
2338 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2339 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002340 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2341 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2342 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002343 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002344 ]
2345 self.assertEqual(0, git_cl.main(['issue', '0']))
2346
Aaron Gable400e9892017-07-12 15:31:21 -07002347 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002348 out = StringIO()
Aaron Gable400e9892017-07-12 15:31:21 -07002349 self.mock(git_cl.sys, 'stdout', out)
2350 self.mock(git_cl.Changelist, 'GetDescription',
2351 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2352 self.calls = [
2353 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Aaron Gable400e9892017-07-12 15:31:21 -07002354 # Let this command raise exception (retcode=1) - it should be ignored.
2355 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2356 CERR1),
2357 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2358 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2359 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2360 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2361 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002362 ((['git', 'log', '-1', '--format=%B'],),
2363 'This is a description\n\nChange-Id: Ideadbeef'),
2364 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002365 ]
2366 self.assertEqual(0, git_cl.main(['issue', '0']))
2367
phajdan.jre328cf92016-08-22 04:12:17 -07002368 def test_cmd_issue_json(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002369 out = StringIO()
phajdan.jre328cf92016-08-22 04:12:17 -07002370 self.mock(git_cl.sys, 'stdout', out)
2371 self.calls = [
2372 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002373 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2374 ((['git', 'config', 'branch.feature.gerritserver'],),
2375 'https://chromium-review.googlesource.com'),
phajdan.jre328cf92016-08-22 04:12:17 -07002376 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002377 {'issue': 123,
2378 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002379 ''),
2380 ]
2381 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2382
tandrii16e0b4e2016-06-07 10:34:28 -07002383 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002384 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07002385 self.mock(git_cl.os.path, 'abspath',
2386 lambda path: self._mocked_call(['abspath', path]))
2387 self.mock(git_cl.os.path, 'exists',
2388 lambda path: self._mocked_call(['exists', path]))
2389 self.mock(git_cl.gclient_utils, 'FileRead',
2390 lambda path: self._mocked_call(['FileRead', path]))
2391 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2392 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2393 self.calls = [
2394 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2395 ((['abspath', '../'],), '/abs/git_repo_root'),
2396 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002397 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002398
2399 def test_GerritCommitMsgHookCheck_custom_hook(self):
2400 cl = self._common_GerritCommitMsgHookCheck()
2401 self.calls += [
2402 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2403 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2404 '#!/bin/sh\necho "custom hook"')
2405 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002406 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002407
2408 def test_GerritCommitMsgHookCheck_not_exists(self):
2409 cl = self._common_GerritCommitMsgHookCheck()
2410 self.calls += [
2411 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2412 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002413 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002414
2415 def test_GerritCommitMsgHookCheck(self):
2416 cl = self._common_GerritCommitMsgHookCheck()
2417 self.calls += [
2418 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2419 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2420 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002421 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002422 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2423 ''),
2424 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002425 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002426
tandriic4344b52016-08-29 06:04:54 -07002427 def test_GerritCmdLand(self):
2428 self.calls += [
2429 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2430 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2431 'deadbeaf'),
2432 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2433 ((['git', 'config', 'branch.feature.gerritserver'],),
2434 'chromium-review.googlesource.com'),
2435 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002436 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002437 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002438 'labels': {},
2439 'current_revision': 'deadbeaf',
2440 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002441 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002442 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002443 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002444 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2445 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002446 cl.SubmitIssue = lambda wait_for_merge: None
Edward Lemur79d4f992019-11-11 23:49:02 +00002447 out = StringIO()
tandrii8da412c2016-09-07 16:01:07 -07002448 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002449 self.assertEqual(0, cl.CMDLand(force=True,
2450 bypass_hooks=True,
2451 verbose=True,
2452 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002453 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002454 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002455
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002456 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemur125d60a2019-09-13 18:25:41 +00002457 self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002458
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002459 def test_gerrit_change_detail_cache_simple(self):
2460 self._mock_gerrit_changes_for_detail_cache()
2461 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002462 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2463 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2464 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002465 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002466 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002467 cl1._cached_remote_url = (
2468 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002469 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002470 cl2._cached_remote_url = (
2471 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002472 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2473 self.assertEqual(cl1._GetChangeDetail(), 'a')
2474 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2475 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2476 self.assertEqual(cl1._GetChangeDetail(), 'a')
2477 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002478
2479 def test_gerrit_change_detail_cache_options(self):
2480 self._mock_gerrit_changes_for_detail_cache()
2481 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002482 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2483 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2484 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2485 # no longer in cache.
2486 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002487 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002488 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002489 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002490 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2491 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2492 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2493 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2494 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2495 self.assertEqual(cl._GetChangeDetail(), 'cab')
2496
2497 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2498 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2499 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2500 self.assertEqual(cl._GetChangeDetail(), 'cab')
2501
2502 # Finally, no_cache should invalidate all caches for given change.
2503 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2504 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2505
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002506 def test_gerrit_description_caching(self):
2507 def gen_detail(rev, desc):
2508 return {
2509 'current_revision': rev,
2510 'revisions': {rev: {'commit': {'message': desc}}}
2511 }
2512 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002513 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002514 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2515 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002516 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002517 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2518 gen_detail('rev2', 'desc2')),
2519 ]
2520
2521 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002522 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002523 cl._cached_remote_url = (
2524 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002525 self.assertEqual(cl.GetDescription(), 'desc1')
2526 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2527 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002528
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002529 def test_print_current_creds(self):
2530 class CookiesAuthenticatorMock(object):
2531 def __init__(self):
2532 self.gitcookies = {
2533 'host.googlesource.com': ('user', 'pass'),
2534 'host-review.googlesource.com': ('user', 'pass'),
2535 }
2536 self.netrc = self
2537 self.netrc.hosts = {
2538 'github.com': ('user2', None, 'pass2'),
2539 'host2.googlesource.com': ('user3', None, 'pass'),
2540 }
2541 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2542 CookiesAuthenticatorMock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002543 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002544 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2545 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2546 ' Host\t User\t Which file',
2547 '============================\t=====\t===========',
2548 'host-review.googlesource.com\t user\t.gitcookies',
2549 ' host.googlesource.com\t user\t.gitcookies',
2550 ' host2.googlesource.com\tuser3\t .netrc',
2551 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002552 sys.stdout.seek(0)
2553 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002554 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2555 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2556 ' Host\tUser\t Which file',
2557 '============================\t====\t===========',
2558 'host-review.googlesource.com\tuser\t.gitcookies',
2559 ' host.googlesource.com\tuser\t.gitcookies',
2560 ])
2561
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002562 def _common_creds_check_mocks(self):
2563 def exists_mock(path):
2564 dirname = os.path.dirname(path)
2565 if dirname == os.path.expanduser('~'):
2566 dirname = '~'
2567 base = os.path.basename(path)
2568 if base in ('.netrc', '.gitcookies'):
2569 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2570 # git cl also checks for existence other files not relevant to this test.
2571 return None
2572 self.mock(os.path, 'exists', exists_mock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002573 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002574
2575 def test_creds_check_gitcookies_not_configured(self):
2576 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002577 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002578 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002579 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002580 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002581 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2582 (('os.path.exists', '~/.netrc'), True),
2583 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2584 'or Ctrl+C to abort'), ''),
2585 ((['git', 'config', '--global', 'http.cookiefile',
2586 os.path.expanduser('~/.gitcookies')], ), ''),
2587 ]
2588 self.assertEqual(0, git_cl.main(['creds-check']))
2589 self.assertRegexpMatches(
2590 sys.stdout.getvalue(),
2591 '^You seem to be using outdated .netrc for git credentials:')
2592 self.assertRegexpMatches(
2593 sys.stdout.getvalue(),
2594 '\nConfigured git to use .gitcookies from')
2595
2596 def test_creds_check_gitcookies_configured_custom_broken(self):
2597 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002598 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002599 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002600 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002601 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002602 ((['git', 'config', '--global', 'http.cookiefile'],),
2603 '/custom/.gitcookies'),
2604 (('os.path.exists', '/custom/.gitcookies'), False),
2605 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2606 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2607 ((['git', 'config', '--global', 'http.cookiefile',
2608 os.path.expanduser('~/.gitcookies')], ), ''),
2609 ]
2610 self.assertEqual(0, git_cl.main(['creds-check']))
2611 self.assertRegexpMatches(
2612 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002613 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002614 self.assertRegexpMatches(
2615 sys.stdout.getvalue(),
2616 'However, your configured .gitcookies file is missing.')
2617
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002618 def test_git_cl_comment_add_gerrit(self):
2619 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002620 lambda host, change, msg, ready:
2621 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002622 self.calls = [
2623 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2624 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2625 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2626 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2627 'origin/master'),
2628 ((['git', 'config', 'remote.origin.url'],),
2629 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002630 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2631 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002632 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002633 ]
2634 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2635 '-a', 'msg']))
2636
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002637 def test_git_cl_comments_fetch_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002638 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002639 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002640 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2641 ((['git', 'config', 'branch.foo.merge'],), ''),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002642 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2643 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2644 'origin/master'),
2645 ((['git', 'config', 'remote.origin.url'],),
2646 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002647 (('GetChangeDetail', 'chromium-review.googlesource.com',
2648 'infra%2Finfra~1',
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002649 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2650 'CURRENT_COMMIT']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002651 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002652 'current_revision': 'ba5eba11',
2653 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002654 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002655 '_number': 1,
2656 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002657 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002658 '_number': 2,
2659 },
2660 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002661 'messages': [
2662 {
2663 u'_revision_number': 1,
2664 u'author': {
2665 u'_account_id': 1111084,
2666 u'email': u'commit-bot@chromium.org',
2667 u'name': u'Commit Bot'
2668 },
2669 u'date': u'2017-03-15 20:08:45.000000000',
2670 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002671 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002672 u'tag': u'autogenerated:cq:dry-run'
2673 },
2674 {
2675 u'_revision_number': 2,
2676 u'author': {
2677 u'_account_id': 11151243,
2678 u'email': u'owner@example.com',
2679 u'name': u'owner'
2680 },
2681 u'date': u'2017-03-16 20:00:41.000000000',
2682 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2683 u'message': u'PTAL',
2684 },
2685 {
2686 u'_revision_number': 2,
2687 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002688 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002689 u'email': u'reviewer@example.com',
2690 u'name': u'reviewer'
2691 },
2692 u'date': u'2017-03-17 05:19:37.500000000',
2693 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2694 u'message': u'Patch Set 2: Code-Review+1',
2695 },
2696 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002697 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002698 (('GetChangeComments', 'chromium-review.googlesource.com',
2699 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002700 '/COMMIT_MSG': [
2701 {
2702 'author': {'email': u'reviewer@example.com'},
2703 'updated': u'2017-03-17 05:19:37.500000000',
2704 'patch_set': 2,
2705 'side': 'REVISION',
2706 'message': 'Please include a bug link',
2707 },
2708 ],
2709 'codereview.settings': [
2710 {
2711 'author': {'email': u'owner@example.com'},
2712 'updated': u'2017-03-16 20:00:41.000000000',
2713 'patch_set': 2,
2714 'side': 'PARENT',
2715 'line': 42,
2716 'message': 'I removed this because it is bad',
2717 },
2718 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002719 }),
2720 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2721 'infra%2Finfra~1'), {}),
2722 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002723 ] * 2 + [
2724 (('write_json', 'output.json', [
2725 {
2726 u'date': u'2017-03-16 20:00:41.000000',
2727 u'message': (
2728 u'PTAL\n' +
2729 u'\n' +
2730 u'codereview.settings\n' +
2731 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2732 u'c/1/2/codereview.settings#b42\n' +
2733 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002734 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002735 u'approval': False,
2736 u'disapproval': False,
2737 u'sender': u'owner@example.com'
2738 }, {
2739 u'date': u'2017-03-17 05:19:37.500000',
2740 u'message': (
2741 u'Patch Set 2: Code-Review+1\n' +
2742 u'\n' +
2743 u'/COMMIT_MSG\n' +
2744 u' PS2, File comment: https://chromium-review.googlesource' +
2745 u'.com/c/1/2//COMMIT_MSG#\n' +
2746 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002747 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002748 u'approval': False,
2749 u'disapproval': False,
2750 u'sender': u'reviewer@example.com'
2751 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002752 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002753 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002754 expected_comments_summary = [
2755 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002756 message=(
2757 u'PTAL\n' +
2758 u'\n' +
2759 u'codereview.settings\n' +
2760 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2761 u'c/1/2/codereview.settings#b42\n' +
2762 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002763 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002764 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002765 disapproval=False, approval=False, sender=u'owner@example.com'),
2766 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002767 message=(
2768 u'Patch Set 2: Code-Review+1\n' +
2769 u'\n' +
2770 u'/COMMIT_MSG\n' +
2771 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2772 u'c/1/2//COMMIT_MSG#\n' +
2773 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002774 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002775 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002776 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2777 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002778 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002779 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002780 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002781 self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
2782 self.assertEqual(
2783 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2784
2785 def test_git_cl_comments_robot_comments(self):
2786 # git cl comments also fetches robot comments (which are considered a type
2787 # of autogenerated comment), and unlike other types of comments, only robot
2788 # comments from the latest patchset are shown.
Edward Lemur79d4f992019-11-11 23:49:02 +00002789 self.mock(sys, 'stdout', StringIO())
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002790 self.calls = [
2791 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2792 ((['git', 'config', 'branch.foo.merge'],), ''),
2793 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2794 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2795 'origin/master'),
2796 ((['git', 'config', 'remote.origin.url'],),
2797 'https://chromium.googlesource.com/infra/infra'),
2798 (('GetChangeDetail', 'chromium-review.googlesource.com',
2799 'infra%2Finfra~1',
2800 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2801 'CURRENT_COMMIT']), {
2802 'owner': {'email': 'owner@example.com'},
2803 'current_revision': 'ba5eba11',
2804 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002805 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002806 '_number': 1,
2807 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002808 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002809 '_number': 2,
2810 },
2811 },
2812 'messages': [
2813 {
2814 u'_revision_number': 1,
2815 u'author': {
2816 u'_account_id': 1111084,
2817 u'email': u'commit-bot@chromium.org',
2818 u'name': u'Commit Bot'
2819 },
2820 u'date': u'2017-03-15 20:08:45.000000000',
2821 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2822 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2823 u'tag': u'autogenerated:cq:dry-run'
2824 },
2825 {
2826 u'_revision_number': 1,
2827 u'author': {
2828 u'_account_id': 123,
2829 u'email': u'tricium@serviceaccount.com',
2830 u'name': u'Tricium'
2831 },
2832 u'date': u'2017-03-16 20:00:41.000000000',
2833 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2834 u'message': u'(1 comment)',
2835 u'tag': u'autogenerated:tricium',
2836 },
2837 {
2838 u'_revision_number': 1,
2839 u'author': {
2840 u'_account_id': 123,
2841 u'email': u'tricium@serviceaccount.com',
2842 u'name': u'Tricium'
2843 },
2844 u'date': u'2017-03-16 20:00:41.000000000',
2845 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2846 u'message': u'(1 comment)',
2847 u'tag': u'autogenerated:tricium',
2848 },
2849 {
2850 u'_revision_number': 2,
2851 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002852 u'_account_id': 123,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002853 u'email': u'tricium@serviceaccount.com',
2854 u'name': u'reviewer'
2855 },
2856 u'date': u'2017-03-17 05:30:37.000000000',
2857 u'tag': u'autogenerated:tricium',
2858 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2859 u'message': u'(1 comment)',
2860 },
2861 ]
2862 }),
2863 (('GetChangeComments', 'chromium-review.googlesource.com',
2864 'infra%2Finfra~1'), {}),
2865 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2866 'infra%2Finfra~1'), {
2867 'codereview.settings': [
2868 {
2869 u'author': {u'email': u'tricium@serviceaccount.com'},
2870 u'updated': u'2017-03-17 05:30:37.000000000',
2871 u'robot_run_id': u'5565031076855808',
2872 u'robot_id': u'Linter/Category',
2873 u'tag': u'autogenerated:tricium',
2874 u'patch_set': 2,
2875 u'side': u'REVISION',
2876 u'message': u'Linter warning message text',
2877 u'line': 32,
2878 },
2879 ],
2880 }),
2881 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
2882 ]
2883 expected_comments_summary = [
2884 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2885 message=(
2886 u'(1 comment)\n\ncodereview.settings\n'
2887 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2888 u'c/1/2/codereview.settings#32\n'
2889 u' Linter warning message text\n'),
2890 sender=u'tricium@serviceaccount.com',
2891 autogenerated=True, approval=False, disapproval=False)
2892 ]
2893 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002894 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002895 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002896
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002897 def test_get_remote_url_with_mirror(self):
2898 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002899
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002900 def selective_os_path_isdir_mock(path):
2901 if path == '/cache/this-dir-exists':
2902 return self._mocked_call('os.path.isdir', path)
2903 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002904
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002905 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2906
2907 url = 'https://chromium.googlesource.com/my/repo'
2908 self.calls = [
2909 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2910 ((['git', 'config', 'branch.master.merge'],), 'master'),
2911 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2912 ((['git', 'config', 'remote.origin.url'],),
2913 '/cache/this-dir-exists'),
2914 (('os.path.isdir', '/cache/this-dir-exists'),
2915 True),
2916 # Runs in /cache/this-dir-exists.
2917 ((['git', 'config', 'remote.origin.url'],),
2918 url),
2919 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002920 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002921 self.assertEqual(cl.GetRemoteUrl(), url)
2922 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2923
Edward Lemur298f2cf2019-02-22 21:40:39 +00002924 def test_get_remote_url_non_existing_mirror(self):
2925 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002926
Edward Lemur298f2cf2019-02-22 21:40:39 +00002927 def selective_os_path_isdir_mock(path):
2928 if path == '/cache/this-dir-doesnt-exist':
2929 return self._mocked_call('os.path.isdir', path)
2930 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002931
Edward Lemur298f2cf2019-02-22 21:40:39 +00002932 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2933 self.mock(logging, 'error',
2934 lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
2935
2936 self.calls = [
2937 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2938 ((['git', 'config', 'branch.master.merge'],), 'master'),
2939 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2940 ((['git', 'config', 'remote.origin.url'],),
2941 '/cache/this-dir-doesnt-exist'),
2942 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2943 False),
2944 (('logging.error',
Daniel Bratell4a60db42019-09-16 17:02:52 +00002945 'Remote "origin" for branch "master" points to'
2946 ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002947 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002948 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002949 self.assertIsNone(cl.GetRemoteUrl())
2950
2951 def test_get_remote_url_misconfigured_mirror(self):
2952 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002953
Edward Lemur298f2cf2019-02-22 21:40:39 +00002954 def selective_os_path_isdir_mock(path):
2955 if path == '/cache/this-dir-exists':
2956 return self._mocked_call('os.path.isdir', path)
2957 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002958
Edward Lemur298f2cf2019-02-22 21:40:39 +00002959 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2960 self.mock(logging, 'error',
2961 lambda *a: self._mocked_call('logging.error', *a))
2962
2963 self.calls = [
2964 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2965 ((['git', 'config', 'branch.master.merge'],), 'master'),
2966 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2967 ((['git', 'config', 'remote.origin.url'],),
2968 '/cache/this-dir-exists'),
2969 (('os.path.isdir', '/cache/this-dir-exists'), True),
2970 # Runs in /cache/this-dir-exists.
2971 ((['git', 'config', 'remote.origin.url'],), ''),
2972 (('logging.error',
2973 'Remote "%(remote)s" for branch "%(branch)s" points to '
2974 '"%(cache_path)s", but it is misconfigured.\n'
2975 '"%(cache_path)s" must be a git repo and must have a remote named '
2976 '"%(remote)s" pointing to the git host.', {
2977 'remote': 'origin',
2978 'cache_path': '/cache/this-dir-exists',
2979 'branch': 'master'}
2980 ), None),
2981 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002982 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002983 self.assertIsNone(cl.GetRemoteUrl())
2984
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002985 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002986 self.calls = [
2987 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2988 ((['git', 'config', 'branch.master.merge'],), 'master'),
2989 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2990 ((['git', 'config', 'remote.origin.url'],),
2991 'https://chromium.googlesource.com/a/my/repo.git/'),
2992 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002993 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002994 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
2995
2996 def test_gerrit_change_identifier_without_project(self):
2997 self.calls = [
2998 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2999 ((['git', 'config', 'branch.master.merge'],), 'master'),
3000 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3001 ((['git', 'config', 'remote.origin.url'],), CERR1),
3002 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003003 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003004 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003005
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003006
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003007class CMDTestCaseBase(unittest.TestCase):
3008 _STATUSES = [
3009 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3010 'INFRA_FAILURE', 'CANCELED',
3011 ]
3012 _CHANGE_DETAIL = {
3013 'project': 'depot_tools',
3014 'status': 'OPEN',
3015 'owner': {'email': 'owner@e.mail'},
3016 'current_revision': 'beeeeeef',
3017 'revisions': {
3018 'deadbeaf': {'_number': 6},
3019 'beeeeeef': {
3020 '_number': 7,
3021 'fetch': {'http': {
3022 'url': 'https://chromium.googlesource.com/depot_tools',
3023 'ref': 'refs/changes/56/123456/7'
3024 }},
3025 },
3026 },
3027 }
3028 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003029 'builds': [{
3030 'id': str(100 + idx),
3031 'builder': {
3032 'project': 'chromium',
3033 'bucket': 'try',
3034 'builder': 'bot_' + status.lower(),
3035 },
3036 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3037 'tags': [],
3038 'status': status,
3039 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003040 }
3041
Edward Lemur4c707a22019-09-24 21:13:43 +00003042 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003043 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00003044 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003045 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3046 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003047 mock.patch('git_cl.Changelist.GetCodereviewServer',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003048 return_value='https://chromium-review.googlesource.com').start()
3049 mock.patch('git_cl.Changelist.GetMostRecentPatchset',
3050 return_value=7).start()
Edward Lemur5b929a42019-10-21 17:57:39 +00003051 mock.patch('git_cl.auth.Authenticator',
Edward Lemurb4a587d2019-10-09 23:56:38 +00003052 return_value=AuthenticatorMock()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003053 mock.patch('git_cl.Changelist._GetChangeDetail',
3054 return_value=self._CHANGE_DETAIL).start()
3055 mock.patch('git_cl._call_buildbucket',
3056 return_value = self._DEFAULT_RESPONSE).start()
3057 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003058 self.addCleanup(mock.patch.stopall)
3059
Edward Lemur4c707a22019-09-24 21:13:43 +00003060
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003061class CMDTryResultsTestCase(CMDTestCaseBase):
3062 _DEFAULT_REQUEST = {
3063 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003064 "gerritChanges": [{
3065 "project": "depot_tools",
3066 "host": "chromium-review.googlesource.com",
3067 "patchset": 7,
3068 "change": 123456,
3069 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003070 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003071 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3072 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003073 }
3074
3075 def testNoJobs(self):
3076 git_cl._call_buildbucket.return_value = {}
3077
3078 self.assertEqual(0, git_cl.main(['try-results']))
3079 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3080 git_cl._call_buildbucket.assert_called_once_with(
3081 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3082 self._DEFAULT_REQUEST)
3083
3084 def testPrintToStdout(self):
3085 self.assertEqual(0, git_cl.main(['try-results']))
3086 self.assertEqual([
3087 'Successes:',
3088 ' bot_success https://ci.chromium.org/b/103',
3089 'Infra Failures:',
3090 ' bot_infra_failure https://ci.chromium.org/b/105',
3091 'Failures:',
3092 ' bot_failure https://ci.chromium.org/b/104',
3093 'Canceled:',
3094 ' bot_canceled ',
3095 'Started:',
3096 ' bot_started https://ci.chromium.org/b/102',
3097 'Scheduled:',
3098 ' bot_scheduled id=101',
3099 'Other:',
3100 ' bot_status_unspecified id=100',
3101 'Total: 7 tryjobs',
3102 ], sys.stdout.getvalue().splitlines())
3103 git_cl._call_buildbucket.assert_called_once_with(
3104 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3105 self._DEFAULT_REQUEST)
3106
3107 def testPrintToStdoutWithMasters(self):
3108 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3109 self.assertEqual([
3110 'Successes:',
3111 ' try bot_success https://ci.chromium.org/b/103',
3112 'Infra Failures:',
3113 ' try bot_infra_failure https://ci.chromium.org/b/105',
3114 'Failures:',
3115 ' try bot_failure https://ci.chromium.org/b/104',
3116 'Canceled:',
3117 ' try bot_canceled ',
3118 'Started:',
3119 ' try bot_started https://ci.chromium.org/b/102',
3120 'Scheduled:',
3121 ' try bot_scheduled id=101',
3122 'Other:',
3123 ' try bot_status_unspecified id=100',
3124 'Total: 7 tryjobs',
3125 ], sys.stdout.getvalue().splitlines())
3126 git_cl._call_buildbucket.assert_called_once_with(
3127 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3128 self._DEFAULT_REQUEST)
3129
3130 @mock.patch('git_cl.write_json')
3131 def testWriteToJson(self, mockJsonDump):
3132 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3133 git_cl._call_buildbucket.assert_called_once_with(
3134 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3135 self._DEFAULT_REQUEST)
3136 mockJsonDump.assert_called_once_with(
3137 'file.json', self._DEFAULT_RESPONSE['builds'])
3138
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003139 def test_filter_failed_for_one_simple(self):
3140 self.assertEqual({}, git_cl._filter_failed_for_retry([]))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003141 self.assertEqual({
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003142 'chromium/try': {
3143 'bot_failure': [],
3144 'bot_infra_failure': []
3145 },
3146 }, git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
3147
3148 def test_filter_failed_for_retry_many_builds(self):
3149
3150 def _build(name, created_sec, status, experimental=False):
3151 assert 0 <= created_sec < 100, created_sec
3152 b = {
3153 'id': 112112,
3154 'builder': {
3155 'project': 'chromium',
3156 'bucket': 'try',
3157 'builder': name,
3158 },
3159 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3160 'status': status,
3161 'tags': [],
3162 }
3163 if experimental:
3164 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3165 return b
3166
3167 builds = [
3168 _build('flaky-last-green', 1, 'FAILURE'),
3169 _build('flaky-last-green', 2, 'SUCCESS'),
3170 _build('flaky', 1, 'SUCCESS'),
3171 _build('flaky', 2, 'FAILURE'),
3172 _build('running', 1, 'FAILED'),
3173 _build('running', 2, 'SCHEDULED'),
3174 _build('yep-still-running', 1, 'STARTED'),
3175 _build('yep-still-running', 2, 'FAILURE'),
3176 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3177 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3178
3179 # Simulate experimental in CQ builder, which developer decided
3180 # to retry manually which resulted in 2nd build non-experimental.
3181 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3182 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3183 ]
3184 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
3185 self.assertEqual({
3186 'chromium/try': {
3187 'flaky': [],
3188 'sometimes-experimental': []
3189 },
3190 }, git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003191
3192
3193class CMDTryTestCase(CMDTestCaseBase):
3194
3195 @mock.patch('git_cl.Changelist.SetCQState')
3196 @mock.patch('git_cl._get_bucket_map', return_value={})
3197 def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
3198 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003199 self.assertEqual(0, git_cl.main(['try']))
3200 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3201 self.assertEqual(
3202 sys.stdout.getvalue(),
3203 'Scheduling CQ dry run on: '
3204 'https://chromium-review.googlesource.com/123456\n')
3205
Edward Lemur4c707a22019-09-24 21:13:43 +00003206 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003207 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003208 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003209
3210 self.assertEqual(0, git_cl.main([
3211 'try', '-B', 'luci.chromium.try', '-b', 'win',
3212 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3213 self.assertIn(
3214 'Scheduling jobs on:\nBucket: luci.chromium.try',
3215 git_cl.sys.stdout.getvalue())
3216
3217 expected_request = {
3218 "requests": [{
3219 "scheduleBuild": {
3220 "requestId": "uuid4",
3221 "builder": {
3222 "project": "chromium",
3223 "builder": "win",
3224 "bucket": "try",
3225 },
3226 "gerritChanges": [{
3227 "project": "depot_tools",
3228 "host": "chromium-review.googlesource.com",
3229 "patchset": 7,
3230 "change": 123456,
3231 }],
3232 "properties": {
3233 "category": "git_cl_try",
3234 "json": [{"a": 1}, None],
3235 "key": "val",
3236 },
3237 "tags": [
3238 {"value": "win", "key": "builder"},
3239 {"value": "git_cl_try", "key": "user_agent"},
3240 ],
3241 },
3242 }],
3243 }
3244 mockCallBuildbucket.assert_called_with(
3245 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3246
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003247 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur4c707a22019-09-24 21:13:43 +00003248 self.assertEqual(0, git_cl.main([
3249 'try', '-B', 'not-a-bucket', '-b', 'win',
3250 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3251 self.assertIn(
3252 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3253 git_cl.sys.stdout.getvalue())
3254
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003255 @mock.patch('git_cl._call_buildbucket')
3256 @mock.patch('git_cl.fetch_try_jobs')
3257 def testScheduleOnBuildbucketRetryFailed(
3258 self, mockFetchTryJobs, mockCallBuildbucket):
3259
3260 git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
3261 7: [],
3262 6: [{
3263 'id': 112112,
3264 'builder': {
3265 'project': 'chromium',
3266 'bucket': 'try',
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003267 'builder': 'linux',},
3268 'createTime': '2019-10-09T08:00:01.854286Z',
3269 'tags': [],
3270 'status': 'FAILURE',}],}[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003271 mockCallBuildbucket.return_value = {}
3272
3273 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3274 self.assertIn(
3275 'Scheduling jobs on:\nBucket: chromium/try',
3276 git_cl.sys.stdout.getvalue())
3277
3278 expected_request = {
3279 "requests": [{
3280 "scheduleBuild": {
3281 "requestId": "uuid4",
3282 "builder": {
3283 "project": "chromium",
3284 "bucket": "try",
3285 "builder": "linux",
3286 },
3287 "gerritChanges": [{
3288 "project": "depot_tools",
3289 "host": "chromium-review.googlesource.com",
3290 "patchset": 7,
3291 "change": 123456,
3292 }],
3293 "properties": {
3294 "category": "git_cl_try",
3295 },
3296 "tags": [
3297 {"value": "linux", "key": "builder"},
3298 {"value": "git_cl_try", "key": "user_agent"},
3299 {"value": "1", "key": "retry_failed"},
3300 ],
3301 },
3302 }],
3303 }
3304 mockCallBuildbucket.assert_called_with(
3305 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3306
Edward Lemur4c707a22019-09-24 21:13:43 +00003307 def test_parse_bucket(self):
3308 test_cases = [
3309 {
3310 'bucket': 'chromium/try',
3311 'result': ('chromium', 'try'),
3312 },
3313 {
3314 'bucket': 'luci.chromium.try',
3315 'result': ('chromium', 'try'),
3316 'has_warning': True,
3317 },
3318 {
3319 'bucket': 'skia.primary',
3320 'result': ('skia', 'skia.primary'),
3321 'has_warning': True,
3322 },
3323 {
3324 'bucket': 'not-a-bucket',
3325 'result': (None, None),
3326 },
3327 ]
3328
3329 for test_case in test_cases:
3330 git_cl.sys.stdout.truncate(0)
3331 self.assertEqual(
3332 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3333 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003334 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3335 test_case['result'])
3336 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003337
3338
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003339class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003340 def setUp(self):
3341 super(CMDUploadTestCase, self).setUp()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003342 mock.patch('git_cl.fetch_try_jobs').start()
3343 mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
3344 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003345 self.addCleanup(mock.patch.stopall)
3346
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003347 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003348 # This test mocks out the actual upload part, and just asserts that after
3349 # upload, if --retry-failed is added, then the tool will fetch try jobs
3350 # from the previous patchset and trigger the right builders on the latest
3351 # patchset.
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003352 git_cl.fetch_try_jobs.side_effect = [
3353 # Latest patchset: No builds.
3354 [],
3355 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003356 [{
3357 'id': str(100 + idx),
3358 'builder': {
3359 'project': 'chromium',
3360 'bucket': 'try',
3361 'builder': 'bot_' + status.lower(),
3362 },
3363 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3364 'tags': [],
3365 'status': status,
3366 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003367 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003368
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003369 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003370 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003371 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3372 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003373 ], git_cl.fetch_try_jobs.mock_calls)
3374 expected_buckets = {
3375 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
3376 }
3377 git_cl._trigger_try_jobs.assert_called_once_with(
Edward Lemur5b929a42019-10-21 17:57:39 +00003378 mock.ANY, expected_buckets, mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003379
Brian Sheedy59b06a82019-10-14 17:03:29 +00003380
3381class CMDFormatTestCase(TestCase):
3382
3383 def setUp(self):
3384 super(CMDFormatTestCase, self).setUp()
3385 self._top_dir = tempfile.mkdtemp()
3386
3387 def tearDown(self):
3388 shutil.rmtree(self._top_dir)
3389 super(CMDFormatTestCase, self).tearDown()
3390
3391 def _make_yapfignore(self, contents):
3392 with open(os.path.join(self._top_dir, '.yapfignore'), 'w') as yapfignore:
3393 yapfignore.write('\n'.join(contents))
3394
3395 def _make_files(self, file_dict):
3396 for directory, files in file_dict.iteritems():
3397 subdir = os.path.join(self._top_dir, directory)
3398 if not os.path.exists(subdir):
3399 os.makedirs(subdir)
3400 for f in files:
3401 with open(os.path.join(subdir, f), 'w'):
3402 pass
3403
3404 def testYapfignoreBasic(self):
3405 self._make_yapfignore(['test.py', '*/bar.py'])
3406 self._make_files({
3407 '.': ['test.py', 'bar.py'],
3408 'foo': ['bar.py'],
3409 })
3410 self.assertEqual(
3411 set(['test.py', 'foo/bar.py']),
3412 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3413
3414 def testYapfignoreMissingYapfignore(self):
3415 self.assertEqual(set(), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3416
3417 def testYapfignoreMissingFile(self):
3418 self._make_yapfignore(['test.py', 'test2.py', 'test3.py'])
3419 self._make_files({
3420 '.': ['test.py', 'test3.py'],
3421 })
3422 self.assertEqual(
3423 set(['test.py', 'test3.py']),
3424 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3425
3426 def testYapfignoreComments(self):
3427 self._make_yapfignore(['test.py', '#test2.py'])
3428 self._make_files({
3429 '.': ['test.py', 'test2.py'],
3430 })
3431 self.assertEqual(
3432 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3433
3434 def testYapfignoreBlankLines(self):
3435 self._make_yapfignore(['test.py', '', '', 'test2.py'])
3436 self._make_files({'.': ['test.py', 'test2.py']})
3437 self.assertEqual(
3438 set(['test.py', 'test2.py']),
3439 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3440
3441 def testYapfignoreWhitespace(self):
3442 self._make_yapfignore([' test.py '])
3443 self._make_files({'.': ['test.py']})
3444 self.assertEqual(
3445 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3446
3447 def testYapfignoreMultiWildcard(self):
3448 self._make_yapfignore(['*es*.py'])
3449 self._make_files({
3450 '.': ['test.py', 'test2.py'],
3451 })
3452 self.assertEqual(
3453 set(['test.py', 'test2.py']),
3454 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3455
3456 def testYapfignoreRestoresDirectory(self):
3457 self._make_yapfignore(['test.py'])
3458 self._make_files({
3459 '.': ['test.py'],
3460 })
3461 old_cwd = os.getcwd()
3462 self.assertEqual(
3463 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3464 self.assertEqual(old_cwd, os.getcwd())
3465
3466
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003467if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003468 logging.basicConfig(
3469 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003470 unittest.main()