blob: f11ea1fa36e36c76c51a1bb64974a283fd2a53e5 [file] [log] [blame]
Edward Lemur0db01f02019-11-12 22:01:51 +00001#!/usr/bin/env vpython3
2# coding=utf-8
maruel@chromium.orgeb5edbc2012-01-16 17:03:28 +00003# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgddd59412011-11-30 14:20:38 +00004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Unit tests for git_cl.py."""
8
Edward Lemur0db01f02019-11-12 22:01:51 +00009from __future__ import unicode_literals
10
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +010011import datetime
tandriide281ae2016-10-12 06:02:30 -070012import json
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +010013import logging
maruel@chromium.orgddd59412011-11-30 14:20:38 +000014import os
Brian Sheedy59b06a82019-10-14 17:03:29 +000015import shutil
maruel@chromium.orgddd59412011-11-30 14:20:38 +000016import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070017import tempfile
maruel@chromium.orgddd59412011-11-30 14:20:38 +000018import unittest
19
20sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
21
22from testing_support.auto_stub import TestCase
Edward Lemur4c707a22019-09-24 21:13:43 +000023from third_party import mock
maruel@chromium.orgddd59412011-11-30 14:20:38 +000024
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000025import metrics
26# We have to disable monitoring before importing git_cl.
27metrics.DISABLE_METRICS_COLLECTION = True
28
Eric Boren2fb63102018-10-05 13:05:03 +000029import gerrit_util
maruel@chromium.orgddd59412011-11-30 14:20:38 +000030import git_cl
iannucci@chromium.org9e849272014-04-04 00:31:55 +000031import git_common
tandrii@chromium.org57d86542016-03-04 16:11:32 +000032import git_footers
maruel@chromium.orgddd59412011-11-30 14:20:38 +000033import subprocess2
maruel@chromium.orgddd59412011-11-30 14:20:38 +000034
Edward Lemur79d4f992019-11-11 23:49:02 +000035if sys.version_info.major == 2:
36 from StringIO import StringIO
37else:
38 from io import StringIO
39
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000040
Edward Lemur0db01f02019-11-12 22:01:51 +000041def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
tandrii5d48c322016-08-18 16:19:37 -070042 return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
43
44
Edward Lemur4c707a22019-09-24 21:13:43 +000045def _constantFn(return_value):
46 def f(*args, **kwargs):
47 return return_value
48 return f
49
50
tandrii5d48c322016-08-18 16:19:37 -070051CERR1 = callError(1)
52
53
Edward Lemur0db01f02019-11-12 22:01:51 +000054def MakeNamedTemporaryFileMock(test, expected_content):
Aaron Gable9a03ae02017-11-03 11:31:07 -070055 class NamedTemporaryFileMock(object):
56 def __init__(self, *args, **kwargs):
57 self.name = '/tmp/named'
Edward Lemur0db01f02019-11-12 22:01:51 +000058 self.expected_content = expected_content.encode('utf-8', 'replace')
Aaron Gable9a03ae02017-11-03 11:31:07 -070059
60 def __enter__(self):
61 return self
62
63 def __exit__(self, _type, _value, _tb):
64 pass
65
66 def write(self, content):
67 if self.expected_content:
Edward Lemur0db01f02019-11-12 22:01:51 +000068 test.assertEqual(self.expected_content, content)
Aaron Gable9a03ae02017-11-03 11:31:07 -070069
70 def close(self):
71 pass
72
73 return NamedTemporaryFileMock
74
75
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000076class ChangelistMock(object):
77 # A class variable so we can access it when we don't have access to the
78 # instance that's being set.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000079 desc = ''
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000080 def __init__(self, **kwargs):
81 pass
82 def GetIssue(self):
83 return 1
Kenneth Russell61e2ed42017-02-15 11:47:13 -080084 def GetDescription(self, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000085 return ChangelistMock.desc
dsansomee2d6fd92016-09-08 00:10:47 -070086 def UpdateDescription(self, desc, force=False):
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +000087 ChangelistMock.desc = desc
88
tandrii5d48c322016-08-18 16:19:37 -070089
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000090class PresubmitMock(object):
91 def __init__(self, *args, **kwargs):
92 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -080093 self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
94
maruel@chromium.org2e72bb12012-01-17 15:18:35 +000095 @staticmethod
96 def should_continue():
97 return True
98
99
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000100class WatchlistsMock(object):
101 def __init__(self, _):
102 pass
103 @staticmethod
104 def GetWatchersForPaths(_):
105 return ['joe@example.com']
106
107
Edward Lemur4c707a22019-09-24 21:13:43 +0000108class CodereviewSettingsFileMock(object):
109 def __init__(self):
110 pass
111 # pylint: disable=no-self-use
112 def read(self):
113 return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
114 'GERRIT_HOST: True\n')
115
116
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000117class AuthenticatorMock(object):
118 def __init__(self, *_args):
119 pass
120 def has_cached_credentials(self):
121 return True
tandrii221ab252016-10-06 08:12:04 -0700122 def authorize(self, http):
123 return http
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +0000124
125
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100126def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000127 """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
128
129 Usage:
130 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100131 CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000132
133 OR
134 >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100135 CookiesAuthenticatorMockFactory(
136 same_auth=('user', '', 'pass'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000137 """
138 class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800139 def __init__(self): # pylint: disable=super-init-not-called
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000140 # Intentionally not calling super() because it reads actual cookie files.
141 pass
142 @classmethod
143 def get_gitcookies_path(cls):
144 return '~/.gitcookies'
145 @classmethod
146 def get_netrc_path(cls):
147 return '~/.netrc'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100148 def _get_auth_for_host(self, host):
149 if same_auth:
150 return same_auth
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000151 return (hosts_with_creds or {}).get(host)
152 return CookiesAuthenticatorMock
153
Aaron Gable9a03ae02017-11-03 11:31:07 -0700154
kmarshall9249e012016-08-23 12:02:16 -0700155class MockChangelistWithBranchAndIssue():
156 def __init__(self, branch, issue):
157 self.branch = branch
158 self.issue = issue
159 def GetBranch(self):
160 return self.branch
161 def GetIssue(self):
162 return self.issue
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000163
tandriic2405f52016-10-10 08:13:15 -0700164
165class SystemExitMock(Exception):
166 pass
167
168
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000169class TestGitClBasic(unittest.TestCase):
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100170 def test_get_description(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000171 cl = git_cl.Changelist(issue=1, codereview_host='host')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100172 cl.description = 'x'
173 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000174 cl.FetchDescription = lambda *a, **kw: 'y'
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000175 self.assertEqual(cl.GetDescription(), 'x')
176 self.assertEqual(cl.GetDescription(force=True), 'y')
177 self.assertEqual(cl.GetDescription(), 'y')
Andrii Shyshkalov31863012017-02-08 11:35:12 +0100178
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700179 def test_description_footers(self):
Edward Lemurf38bc172019-09-03 21:02:13 +0000180 cl = git_cl.Changelist(issue=1, codereview_host='host')
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700181 cl.description = '\n'.join([
182 'This is some message',
183 '',
184 'It has some lines',
185 'and, also',
186 '',
187 'Some: Really',
188 'Awesome: Footers',
189 ])
190 cl.has_description = True
Edward Lemur125d60a2019-09-13 18:25:41 +0000191 cl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700192 msg, footers = cl.GetDescriptionFooters()
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000193 self.assertEqual(
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700194 msg, ['This is some message', '', 'It has some lines', 'and, also'])
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000195 self.assertEqual(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700196
197 msg.append('wut')
198 footers.append(('gnarly-dude', 'beans'))
199 cl.UpdateDescriptionFooters(msg, footers)
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000200 self.assertEqual(cl.GetDescription().splitlines(), [
Robert Iannucci09f1f3d2017-03-28 16:54:32 -0700201 'This is some message',
202 '',
203 'It has some lines',
204 'and, also',
205 'wut'
206 '',
207 'Some: Really',
208 'Awesome: Footers',
209 'Gnarly-Dude: beans',
210 ])
211
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +0000212 def test_set_preserve_tryjobs(self):
213 d = git_cl.ChangeDescription('Simple.')
214 d.set_preserve_tryjobs()
215 self.assertEqual(d.description.splitlines(), [
216 'Simple.',
217 '',
218 'Cq-Do-Not-Cancel-Tryjobs: true',
219 ])
220 before = d.description
221 d.set_preserve_tryjobs()
222 self.assertEqual(before, d.description)
223
224 d = git_cl.ChangeDescription('\n'.join([
225 'One is enough',
226 '',
227 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
228 'Change-Id: Ideadbeef',
229 ]))
230 d.set_preserve_tryjobs()
231 self.assertEqual(d.description.splitlines(), [
232 'One is enough',
233 '',
234 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
235 'Change-Id: Ideadbeef',
236 'Cq-Do-Not-Cancel-Tryjobs: true',
237 ])
238
tandriif9aefb72016-07-01 09:06:51 -0700239 def test_get_bug_line_values(self):
240 f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
241 self.assertEqual(f('', ''), [])
242 self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
243 self.assertEqual(f('v8', '456'), ['v8:456'])
244 self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
245 # Not nice, but not worth carying.
246 self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
247 ['v8:456', 'chromium:123', 'v8:123'])
248
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100249 def _test_git_number(self, parent_msg, dest_ref, child_msg,
250 parent_hash='parenthash'):
251 desc = git_cl.ChangeDescription(child_msg)
252 desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
253 return desc.description
254
255 def assertEqualByLine(self, actual, expected):
256 self.assertEqual(actual.splitlines(), expected.splitlines())
257
258 def test_git_number_bad_parent(self):
259 with self.assertRaises(ValueError):
260 self._test_git_number('Parent', 'refs/heads/master', 'Child')
261
262 def test_git_number_bad_parent_footer(self):
263 with self.assertRaises(AssertionError):
264 self._test_git_number(
265 'Parent\n'
266 '\n'
267 'Cr-Commit-Position: wrong',
268 'refs/heads/master', 'Child')
269
270 def test_git_number_bad_lineage_ignored(self):
271 actual = self._test_git_number(
272 'Parent\n'
273 '\n'
274 'Cr-Commit-Position: refs/heads/master@{#1}\n'
275 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
276 'refs/heads/master', 'Child')
277 self.assertEqualByLine(
278 actual,
279 'Child\n'
280 '\n'
281 'Cr-Commit-Position: refs/heads/master@{#2}\n'
282 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
283
284 def test_git_number_same_branch(self):
285 actual = self._test_git_number(
286 'Parent\n'
287 '\n'
288 'Cr-Commit-Position: refs/heads/master@{#12}',
289 dest_ref='refs/heads/master',
290 child_msg='Child')
291 self.assertEqualByLine(
292 actual,
293 'Child\n'
294 '\n'
295 'Cr-Commit-Position: refs/heads/master@{#13}')
296
Andrii Shyshkalovde37c012017-07-06 21:06:50 +0200297 def test_git_number_same_branch_mixed_footers(self):
298 actual = self._test_git_number(
299 'Parent\n'
300 '\n'
301 'Cr-Commit-Position: refs/heads/master@{#12}',
302 dest_ref='refs/heads/master',
303 child_msg='Child\n'
304 '\n'
305 'Broken-by: design\n'
306 'BUG=123')
307 self.assertEqualByLine(
308 actual,
309 'Child\n'
310 '\n'
311 'Broken-by: design\n'
312 'BUG=123\n'
313 'Cr-Commit-Position: refs/heads/master@{#13}')
314
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100315 def test_git_number_same_branch_with_originals(self):
316 actual = self._test_git_number(
317 'Parent\n'
318 '\n'
319 'Cr-Commit-Position: refs/heads/master@{#12}',
320 dest_ref='refs/heads/master',
321 child_msg='Child\n'
322 '\n'
323 'Some users are smart and insert their own footers\n'
324 '\n'
325 'Cr-Whatever: value\n'
326 'Cr-Commit-Position: refs/copy/paste@{#22}')
327 self.assertEqualByLine(
328 actual,
329 'Child\n'
330 '\n'
331 'Some users are smart and insert their own footers\n'
332 '\n'
333 'Cr-Original-Whatever: value\n'
334 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
335 'Cr-Commit-Position: refs/heads/master@{#13}')
336
337 def test_git_number_new_branch(self):
338 actual = self._test_git_number(
339 'Parent\n'
340 '\n'
341 'Cr-Commit-Position: refs/heads/master@{#12}',
342 dest_ref='refs/heads/branch',
343 child_msg='Child')
344 self.assertEqualByLine(
345 actual,
346 'Child\n'
347 '\n'
348 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
349 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
350
351 def test_git_number_lineage(self):
352 actual = self._test_git_number(
353 'Parent\n'
354 '\n'
355 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
356 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
357 dest_ref='refs/heads/branch',
358 child_msg='Child')
359 self.assertEqualByLine(
360 actual,
361 'Child\n'
362 '\n'
363 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
364 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
365
366 def test_git_number_moooooooore_lineage(self):
367 actual = self._test_git_number(
368 'Parent\n'
369 '\n'
370 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
371 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
372 dest_ref='refs/heads/mooore',
373 child_msg='Child')
374 self.assertEqualByLine(
375 actual,
376 'Child\n'
377 '\n'
378 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
379 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
380 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
381
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100382 def test_git_number_ever_moooooooore_lineage(self):
Robert Iannucci456b0d62018-03-13 19:15:50 -0700383 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalovb5effa12016-12-14 19:35:12 +0100384 actual = self._test_git_number(
385 'CQ commit on fresh new branch + numbering.\n'
386 '\n'
387 'NOTRY=True\n'
388 'NOPRESUBMIT=True\n'
389 'BUG=\n'
390 '\n'
391 'Review-Url: https://codereview.chromium.org/2577703003\n'
392 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
393 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
394 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
395 dest_ref='refs/heads/gnumb-test/cl',
396 child_msg='git cl on fresh new branch + numbering.\n'
397 '\n'
398 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
399 self.assertEqualByLine(
400 actual,
401 'git cl on fresh new branch + numbering.\n'
402 '\n'
403 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
404 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
405 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
406 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
407 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +0100408
409 def test_git_number_cherry_pick(self):
410 actual = self._test_git_number(
411 'Parent\n'
412 '\n'
413 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
414 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
415 dest_ref='refs/heads/branch',
416 child_msg='Child, which is cherry-pick from master\n'
417 '\n'
418 'Cr-Commit-Position: refs/heads/master@{#100}\n'
419 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
420 self.assertEqualByLine(
421 actual,
422 'Child, which is cherry-pick from master\n'
423 '\n'
424 '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
425 '\n'
426 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
427 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
428 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
429
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000430 def test_valid_accounts(self):
431 mock_per_account = {
432 'u1': None, # 404, doesn't exist.
433 'u2': {
434 '_account_id': 123124,
435 'avatars': [],
436 'email': 'u2@example.com',
437 'name': 'User Number 2',
438 'status': 'OOO',
439 },
440 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
441 }
442 def GetAccountDetailsMock(_, account):
443 # Poor-man's mock library's side_effect.
444 v = mock_per_account.pop(account)
445 if isinstance(v, Exception):
446 raise v
447 return v
448
449 original = git_cl.gerrit_util.GetAccountDetails
450 try:
451 git_cl.gerrit_util.GetAccountDetails = GetAccountDetailsMock
452 actual = git_cl.gerrit_util.ValidAccounts(
453 'host', ['u1', 'u2', 'u3'], max_threads=1)
454 finally:
455 git_cl.gerrit_util.GetAccountDetails = original
456 self.assertEqual(actual, {
457 'u2': {
458 '_account_id': 123124,
459 'avatars': [],
460 'email': 'u2@example.com',
461 'name': 'User Number 2',
462 'status': 'OOO',
463 },
464 })
465
466
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200467class TestParseIssueURL(unittest.TestCase):
468 def _validate(self, parsed, issue=None, patchset=None, hostname=None,
Edward Lemurf38bc172019-09-03 21:02:13 +0000469 fail=False):
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200470 self.assertIsNotNone(parsed)
471 if fail:
472 self.assertFalse(parsed.valid)
473 return
474 self.assertTrue(parsed.valid)
475 self.assertEqual(parsed.issue, issue)
476 self.assertEqual(parsed.patchset, patchset)
477 self.assertEqual(parsed.hostname, hostname)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200478
Edward Lemur678a6842019-10-03 22:25:05 +0000479 def test_ParseIssueNumberArgument(self):
480 def test(arg, *args, **kwargs):
481 self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200482
Edward Lemur678a6842019-10-03 22:25:05 +0000483 test('123', 123)
484 test('', fail=True)
485 test('abc', fail=True)
486 test('123/1', fail=True)
487 test('123a', fail=True)
488 test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200489
Edward Lemur678a6842019-10-03 22:25:05 +0000490 test('https://codereview.source.com/123',
491 123, None, 'codereview.source.com')
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200492 test('http://chrome-review.source.com/c/123',
493 123, None, 'chrome-review.source.com')
494 test('https://chrome-review.source.com/c/123/',
495 123, None, 'chrome-review.source.com')
496 test('https://chrome-review.source.com/c/123/4',
497 123, 4, 'chrome-review.source.com')
498 test('https://chrome-review.source.com/#/c/123/4',
499 123, 4, 'chrome-review.source.com')
500 test('https://chrome-review.source.com/c/123/4',
501 123, 4, 'chrome-review.source.com')
502 test('https://chrome-review.source.com/123',
503 123, None, 'chrome-review.source.com')
504 test('https://chrome-review.source.com/123/4',
505 123, 4, 'chrome-review.source.com')
506
Edward Lemur678a6842019-10-03 22:25:05 +0000507 test('https://chrome-review.source.com/bad/123/4', fail=True)
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200508 test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
509 test('https://chrome-review.source.com/c/abc/', fail=True)
510 test('ssh://chrome-review.source.com/c/123/1/', fail=True)
511
Andrii Shyshkalov90f31922017-04-10 16:10:21 +0200512
513
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100514class GitCookiesCheckerTest(TestCase):
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100515 def setUp(self):
516 super(GitCookiesCheckerTest, self).setUp()
517 self.c = git_cl._GitCookiesChecker()
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100518 self.c._all_hosts = []
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100519
520 def mock_hosts_creds(self, subhost_identity_pairs):
521 def ensure_googlesource(h):
522 if not h.endswith(self.c._GOOGLESOURCE):
523 assert not h.endswith('.')
524 return h + '.' + self.c._GOOGLESOURCE
525 return h
526 self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
527 for h, i in subhost_identity_pairs]
528
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200529 def test_identity_parsing(self):
530 self.assertEqual(self.c._parse_identity('ldap.google.com'),
531 ('ldap', 'google.com'))
532 self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
533 ('ldap', 'example.com'))
534 # Specical case because we know there are no subdomains in chromium.org.
535 self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
536 ('note.period', 'chromium.org'))
Lei Zhangd3f769a2017-12-15 15:16:14 -0800537 # Pathological: ".period." can be either username OR domain, more likely
538 # domain.
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +0200539 self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
540 ('note', 'period.example.com'))
541
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100542 def test_analysis_nothing(self):
543 self.c._all_hosts = []
544 self.assertFalse(self.c.has_generic_host())
545 self.assertEqual(set(), self.c.get_conflicting_hosts())
546 self.assertEqual(set(), self.c.get_duplicated_hosts())
547 self.assertEqual(set(), self.c.get_partially_configured_hosts())
548 self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
549
550 def test_analysis(self):
551 self.mock_hosts_creds([
552 ('.googlesource.com', 'git-example.chromium.org'),
553
554 ('chromium', 'git-example.google.com'),
555 ('chromium-review', 'git-example.google.com'),
556 ('chrome-internal', 'git-example.chromium.org'),
557 ('chrome-internal-review', 'git-example.chromium.org'),
558 ('conflict', 'git-example.google.com'),
559 ('conflict-review', 'git-example.chromium.org'),
560 ('dup', 'git-example.google.com'),
561 ('dup', 'git-example.google.com'),
562 ('dup-review', 'git-example.google.com'),
563 ('partial', 'git-example.google.com'),
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200564 ('gpartial-review', 'git-example.google.com'),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100565 ])
566 self.assertTrue(self.c.has_generic_host())
567 self.assertEqual(set(['conflict.googlesource.com']),
568 self.c.get_conflicting_hosts())
569 self.assertEqual(set(['dup.googlesource.com']),
570 self.c.get_duplicated_hosts())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200571 self.assertEqual(set(['partial.googlesource.com',
572 'gpartial-review.googlesource.com']),
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100573 self.c.get_partially_configured_hosts())
574 self.assertEqual(set(['chromium.googlesource.com',
575 'chrome-internal.googlesource.com']),
576 self.c.get_hosts_with_wrong_identities())
577
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100578 def test_report_no_problems(self):
579 self.test_analysis_nothing()
Edward Lemur79d4f992019-11-11 23:49:02 +0000580 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100581 self.assertFalse(self.c.find_and_report_problems())
582 self.assertEqual(sys.stdout.getvalue(), '')
583
584 def test_report(self):
585 self.test_analysis()
Edward Lemur79d4f992019-11-11 23:49:02 +0000586 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200587 self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
588 classmethod(lambda _: '~/.gitcookies'))
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100589 self.assertTrue(self.c.find_and_report_problems())
590 with open(os.path.join(os.path.dirname(__file__),
591 'git_cl_creds_check_report.txt')) as f:
592 expected = f.read()
593 def by_line(text):
594 return [l.rstrip() for l in text.rstrip().splitlines()]
Robert Iannucci456b0d62018-03-13 19:15:50 -0700595 self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
Andrii Shyshkalov4812e612017-03-27 17:22:57 +0200596 self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
Andrii Shyshkalov97800502017-03-16 16:04:32 +0100597
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -0800598
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000599class TestGitCl(TestCase):
600 def setUp(self):
601 super(TestGitCl, self).setUp()
602 self.calls = []
tandrii9d206752016-06-20 11:32:47 -0700603 self._calls_done = []
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000604 self.mock(git_cl, 'time_time',
605 lambda: self._mocked_call('time.time'))
606 self.mock(git_cl.metrics.collector, 'add_repeated',
607 lambda *a: self._mocked_call('add_repeated', *a))
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000608 self.mock(subprocess2, 'call', self._mocked_call)
609 self.mock(subprocess2, 'check_call', self._mocked_call)
610 self.mock(subprocess2, 'check_output', self._mocked_call)
tandrii5d48c322016-08-18 16:19:37 -0700611 self.mock(subprocess2, 'communicate',
612 lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
tandrii@chromium.orga342c922016-03-16 07:08:25 +0000613 self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000614 self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000615 self.mock(git_common, 'get_or_create_merge_base',
616 lambda *a: (
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000617 self._mocked_call(['get_or_create_merge_base'] + list(a))))
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +0000618 self.mock(git_cl, 'BranchExists', lambda _: True)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000619 self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000620 self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
621 self._mocked_call('SaveDescriptionBackup'))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100622 self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000623 *(['ask_for_data'] + list(a)), **k))
phajdan.jre328cf92016-08-22 04:12:17 -0700624 self.mock(git_cl, 'write_json', lambda path, contents:
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000625 self._mocked_call('write_json', path, contents))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000626 self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000627 self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
Edward Lemur5b929a42019-10-21 17:57:39 +0000628 self.mock(git_cl.auth, 'Authenticator', AuthenticatorMock)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100629 self.mock(git_cl.gerrit_util, 'GetChangeDetail',
630 lambda *args, **kwargs: self._mocked_call(
631 'GetChangeDetail', *args, **kwargs))
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700632 self.mock(git_cl.gerrit_util, 'GetChangeComments',
633 lambda *args, **kwargs: self._mocked_call(
634 'GetChangeComments', *args, **kwargs))
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000635 self.mock(git_cl.gerrit_util, 'GetChangeRobotComments',
636 lambda *args, **kwargs: self._mocked_call(
637 'GetChangeRobotComments', *args, **kwargs))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +0100638 self.mock(git_cl.gerrit_util, 'AddReviewers',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700639 lambda h, i, reviewers, ccs, notify: self._mocked_call(
640 'AddReviewers', h, i, reviewers, ccs, notify))
Aaron Gablefd238082017-06-07 13:42:34 -0700641 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gablefc62f762017-07-17 11:12:07 -0700642 lambda h, i, msg=None, labels=None, notify=None:
643 self._mocked_call('SetReview', h, i, msg, labels, notify))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700644 self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
645 staticmethod(lambda: False))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000646 self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
647 classmethod(lambda _: False))
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000648 self.mock(git_cl.gerrit_util, 'ValidAccounts',
649 lambda host, accounts:
650 self._mocked_call('ValidAccounts', host, accounts))
tandriic2405f52016-10-10 08:13:15 -0700651 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +1100652 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000653 # It's important to reset settings to not have inter-tests interference.
654 git_cl.settings = None
655
656 def tearDown(self):
wychen@chromium.org445c8962015-04-28 23:30:05 +0000657 try:
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +0000658 self.assertEqual([], self.calls)
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100659 except AssertionError:
wychen@chromium.org445c8962015-04-28 23:30:05 +0000660 if not self.has_failed():
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100661 raise
662 # Sadly, has_failed() returns True if this OR any other tests before this
663 # one have failed.
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200664 git_cl.logging.error(
665 '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100666 'There are un-consumed self.calls after this test has finished.\n'
667 'If you don\'t know which test this is, run:\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700668 ' tests/git_cl_tests.py -v\n'
Andrii Shyshkalove05d4882017-04-12 14:34:49 +0200669 'If you are already running only this test, then **first** fix the '
670 'problem whose exception is emitted below by unittest runner.\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100671 'Else, to be sure what\'s going on, run this test **alone** with \n'
Aaron Gable3a16ed12017-03-23 10:51:55 -0700672 ' tests/git_cl_tests.py TestGitCl.<name>\n'
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +0100673 'and follow instructions above.\n' +
674 '=' * 80)
wychen@chromium.org445c8962015-04-28 23:30:05 +0000675 finally:
676 super(TestGitCl, self).tearDown()
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000677
iannucci@chromium.org9e849272014-04-04 00:31:55 +0000678 def _mocked_call(self, *args, **_kwargs):
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000679 self.assertTrue(
680 self.calls,
tandrii9d206752016-06-20 11:32:47 -0700681 '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
wychen@chromium.orga872e752015-04-28 23:42:18 +0000682 top = self.calls.pop(0)
wychen@chromium.orga872e752015-04-28 23:42:18 +0000683 expected_args, result = top
684
maruel@chromium.orge52678e2013-04-26 18:34:44 +0000685 # Also logs otherwise it could get caught in a try/finally and be hard to
686 # diagnose.
687 if expected_args != args:
tandrii9d206752016-06-20 11:32:47 -0700688 N = 5
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000689 prior_calls = '\n '.join(
tandrii9d206752016-06-20 11:32:47 -0700690 '@%d: %r' % (len(self._calls_done) - N + i, c[0])
691 for i, c in enumerate(self._calls_done[-N:]))
692 following_calls = '\n '.join(
693 '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
694 for i, c in enumerate(self.calls[:N]))
695 extended_msg = (
696 'A few prior calls:\n %s\n\n'
697 'This (expected):\n @%d: %r\n'
698 'This (actual):\n @%d: %r\n\n'
699 'A few following expected calls:\n %s' %
700 (prior_calls, len(self._calls_done), expected_args,
701 len(self._calls_done), args, following_calls))
702 git_cl.logging.error(extended_msg)
703
tandrii99a72f22016-08-17 14:33:24 -0700704 self.fail('@%d\n'
705 ' Expected: %r\n'
706 ' Actual: %r' % (
tandrii9d206752016-06-20 11:32:47 -0700707 len(self._calls_done), expected_args, args))
708
709 self._calls_done.append(top)
tandrii5d48c322016-08-18 16:19:37 -0700710 if isinstance(result, Exception):
711 raise result
Edward Lemur0db01f02019-11-12 22:01:51 +0000712 # stdout from git commands is supposed to be a bytestream. Convert it here
713 # instead of converting all test output in this file to bytes.
714 if args[0][0] == 'git' and not isinstance(result, bytes):
715 result = result.encode('utf-8')
maruel@chromium.org2e72bb12012-01-17 15:18:35 +0000716 return result
717
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100718 def test_ask_for_explicit_yes_true(self):
719 self.calls = [
720 (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
721 (('ask_for_data', 'Please, type yes or no: '), 'ye'),
722 ]
723 self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
724
tandrii48df5812016-10-17 03:55:37 -0700725 def test_LoadCodereviewSettingsFromFile_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +0000726 codereview_file = StringIO('GERRIT_HOST: true')
tandrii48df5812016-10-17 03:55:37 -0700727 self.calls = [
728 ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700729 ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
730 ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
731 ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
732 ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
tandrii48df5812016-10-17 03:55:37 -0700733 ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
734 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700735 ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
736 CERR1),
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000737 ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
738 CERR1),
tandrii48df5812016-10-17 03:55:37 -0700739 ((['git', 'config', 'gerrit.host', 'true'],), ''),
740 ]
741 self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
742
maruel@chromium.orga3353652011-11-30 14:26:57 +0000743 @classmethod
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000744 def _is_gerrit_calls(cls, gerrit=False):
745 return [((['git', 'config', 'rietveld.autoupdate'],), ''),
746 ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
747
748 @classmethod
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000749 def _git_post_upload_calls(cls):
750 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000751 ((['git', 'rev-parse', 'HEAD'],), 'hash'),
752 ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
753 ((['git',
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000754 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
rmistry@google.com5626a922015-02-26 14:03:30 +0000755 ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000756 ]
757
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000758 @staticmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000759 def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000760 fake_ancestor = 'fake_ancestor'
761 fake_cl = 'fake_cl_for_patch'
762 return [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000763 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000764 'rev-parse', '--verify', diff_base],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000765 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000766 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000767 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000768 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000769 # Mock a config miss (error code 1)
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000770 ((['git',
tandrii5d48c322016-08-18 16:19:37 -0700771 'config', 'gitcl.remotebranch'],), CERR1),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000772 ] + ([
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000773 # Call to GetRemoteBranch()
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000774 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000775 'config', 'branch.%s.merge' % working_branch],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000776 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000777 ((['git',
bratell@opera.comf267b0e2013-05-02 09:11:43 +0000778 'config', 'branch.%s.remote' % working_branch],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000779 ] if get_remote_branch else []) + [
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000780 ((['git', 'rev-list', '^' + fake_ancestor,
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000781 'refs/remotes/origin/master'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000782 ]
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000783
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000784 @classmethod
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000785 def _gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000786 cls, issue=None, skip_auth_check=False, short_hostname='chromium',
787 custom_cl_base=None):
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +0000788 cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
tandrii@chromium.org28253532016-04-14 13:46:56 +0000789 if skip_auth_check:
790 return [((cmd, ), 'true')]
791
tandrii5d48c322016-08-18 16:19:37 -0700792 calls = [((cmd, ), CERR1)]
Edward Lemurf38bc172019-09-03 21:02:13 +0000793
794 if custom_cl_base:
795 calls += [
796 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
797 ]
798
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000799 calls.extend([
800 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
801 ((['git', 'config', 'branch.master.remote'],), 'origin'),
802 ((['git', 'config', 'remote.origin.url'],),
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000803 'https://%s.googlesource.com/my/repo' % short_hostname),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000804 ])
Edward Lemurf38bc172019-09-03 21:02:13 +0000805
806 calls += [
807 ((['git', 'config', 'branch.master.gerritissue'],),
808 CERR1 if issue is None else str(issue)),
809 ]
810
Daniel Chengcf6269b2019-05-18 01:02:12 +0000811 if issue:
812 calls.extend([
813 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
814 ])
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000815 return calls
816
817 @classmethod
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100818 def _gerrit_base_calls(cls, issue=None, fetched_description=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200819 fetched_status=None, other_cl_owner=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000820 custom_cl_base=None, short_hostname='chromium',
821 change_id=None):
Aaron Gable13101a62018-02-09 13:20:41 -0800822 calls = cls._is_gerrit_calls(True)
Edward Lemurf38bc172019-09-03 21:02:13 +0000823 if not custom_cl_base:
824 calls += [
825 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
826 ]
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200827
828 if custom_cl_base:
829 ancestor_revision = custom_cl_base
830 else:
831 # Determine ancestor_revision to be merge base.
832 ancestor_revision = 'fake_ancestor_sha'
833 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000834 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000835 ((['git', 'config', 'branch.master.remote'],), 'origin'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000836 ((['get_or_create_merge_base', 'master',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200837 'refs/remotes/origin/master'],), ancestor_revision),
838 ]
839
840 # Calls to verify branch point is ancestor
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000841 calls += cls._gerrit_ensure_auth_calls(
Edward Lemurf38bc172019-09-03 21:02:13 +0000842 issue=issue, short_hostname=short_hostname,
843 custom_cl_base=custom_cl_base)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100844
845 if issue:
846 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000847 (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +0000848 'my%2Frepo~123456',
Andrii Shyshkalovc4a73562018-09-25 18:40:17 +0000849 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
850 ),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100851 {
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100852 'owner': {'email': (other_cl_owner or 'owner@example.com')},
Anthony Polito8b955342019-09-24 19:01:36 +0000853 'change_id': (change_id or '123456789'),
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100854 'current_revision': 'sha1_of_current_revision',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000855 'revisions': {'sha1_of_current_revision': {
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100856 'commit': {'message': fetched_description},
857 }},
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100858 'status': fetched_status or 'NEW',
Andrii Shyshkalov3e631422017-02-16 17:46:44 +0100859 }),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100860 ]
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100861 if fetched_status == 'ABANDONED':
862 calls += [
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000863 (('DieWithError', 'Change https://%s-review.googlesource.com/'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100864 '123456 has been abandoned, new uploads are not '
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000865 'allowed' % short_hostname), SystemExitMock()),
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +0100866 ]
867 return calls
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100868 if other_cl_owner:
869 calls += [
870 (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
871 ]
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100872
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200873 calls += cls._git_sanity_checks(ancestor_revision, 'master',
874 get_remote_branch=False)
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100875 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200876 ((['git', 'rev-parse', '--show-cdup'],), ''),
877 ((['git', 'rev-parse', 'HEAD'],), '12345'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000878
Aaron Gable7817f022017-12-12 09:43:17 -0800879 ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
880 '--no-renames', '-r', ancestor_revision + '...', '.'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200881 'M\t.gitignore\n'),
882 ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100883 ]
884
885 if not issue:
886 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200887 ((['git', 'log', '--pretty=format:%s%n%n%b',
888 ancestor_revision + '...'],),
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +0000889 'foo'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100890 ]
891
892 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200893 ((['git', 'config', 'user.email'],), 'me@example.com'),
Edward Lemur2c48f242019-06-04 16:14:09 +0000894 (('time.time',), 1000,),
895 (('time.time',), 3000,),
896 (('add_repeated', 'sub_commands', {
897 'execution_time': 2000,
898 'command': 'presubmit',
899 'exit_code': 0
900 }), None,),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200901 ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
902 ([custom_cl_base] if custom_cl_base else
903 [ancestor_revision, 'HEAD']),),
904 '+dat'),
Andrii Shyshkalov02939562017-02-16 17:47:17 +0100905 ]
906 return calls
ukai@chromium.orge8077812012-02-03 03:41:46 +0000907
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +0000908 @classmethod
909 def _gerrit_upload_calls(cls, description, reviewers, squash,
tandriia60502f2016-06-20 02:01:53 -0700910 squash_mode='default',
tandrii@chromium.org10625002016-03-04 20:03:47 +0000911 expected_upstream_ref='origin/refs/heads/master',
Aaron Gablefd238082017-06-07 13:42:34 -0700912 title=None, notify=False,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +0100913 post_amend_description=None, issue=None, cc=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +0000914 custom_cl_base=None, tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +0000915 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +0000916 labels=None, change_id=None, original_title=None,
Anthony Polito8b955342019-09-24 19:01:36 +0000917 final_description=None, gitcookies_exists=True,
918 force=False):
tandrii@chromium.org10625002016-03-04 20:03:47 +0000919 if post_amend_description is None:
920 post_amend_description = description
bradnelsond975b302016-10-23 12:20:23 -0700921 cc = cc or []
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200922 # Determined in `_gerrit_base_calls`.
923 determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
924
925 calls = []
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000926
tandriia60502f2016-06-20 02:01:53 -0700927 if squash_mode == 'default':
928 calls.extend([
929 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
930 ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
931 ])
932 elif squash_mode in ('override_squash', 'override_nosquash'):
933 calls.extend([
934 ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
935 'true' if squash_mode == 'override_squash' else 'false'),
936 ])
937 else:
938 assert squash_mode in ('squash', 'nosquash')
939
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000940 # If issue is given, then description is fetched from Gerrit instead.
941 if issue is None:
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000942 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200943 ((['git', 'log', '--pretty=format:%s\n\n%b',
944 ((custom_cl_base + '..') if custom_cl_base else
945 'fake_ancestor_sha..HEAD')],),
946 description),
947 ]
Aaron Gableb56ad332017-01-06 15:24:31 -0800948 if squash:
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000949 title = 'Initial_upload'
Aaron Gableb56ad332017-01-06 15:24:31 -0800950 else:
951 if not title:
952 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200953 ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
954 (('ask_for_data', 'Title for patchset []: '), 'User input'),
Aaron Gableb56ad332017-01-06 15:24:31 -0800955 ]
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +0000956 title = 'User_input'
tandrii@chromium.org57d86542016-03-04 16:11:32 +0000957 if not git_footers.get_footer_change_id(description) and not squash:
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +0000958 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200959 (('DownloadGerritHook', False), ''),
960 # Amending of commit message to get the Change-Id.
961 ((['git', 'log', '--pretty=format:%s\n\n%b',
962 determined_ancestor_revision + '..HEAD'],),
963 description),
964 ((['git', 'commit', '--amend', '-m', description],), ''),
965 ((['git', 'log', '--pretty=format:%s\n\n%b',
966 determined_ancestor_revision + '..HEAD'],),
967 post_amend_description)
968 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000969 if squash:
Anthony Polito8b955342019-09-24 19:01:36 +0000970 if force or not issue:
971 if issue:
972 calls += [
973 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
974 ]
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000975 # Prompting to edit description on first upload.
976 calls += [
Jonas Termansend0f79112019-03-22 15:28:26 +0000977 ((['git', 'config', 'rietveld.bug-prefix'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +0000978 ]
Anthony Polito8b955342019-09-24 19:01:36 +0000979 if not force:
980 calls += [
981 ((['git', 'config', 'core.editor'],), ''),
982 ((['RunEditor'],), description),
983 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000984 ref_to_push = 'abcdef0123456789'
985 calls += [
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200986 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
987 ((['git', 'config', 'branch.master.remote'],), 'origin'),
988 ]
989
990 if custom_cl_base is None:
991 calls += [
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000992 ((['get_or_create_merge_base', 'master',
993 'refs/remotes/origin/master'],),
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000994 'origin/master'),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +0200995 ]
996 parent = 'origin/master'
997 else:
998 calls += [
999 ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
1000 'refs/remotes/origin/master'],),
1001 callError(1)), # Means not ancenstor.
1002 (('ask_for_data',
1003 'Do you take responsibility for cleaning up potential mess '
1004 'resulting from proceeding with upload? Press Enter to upload, '
1005 'or Ctrl+C to abort'), ''),
1006 ]
1007 parent = custom_cl_base
1008
1009 calls += [
1010 ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
1011 '0123456789abcdef'),
1012 ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
Aaron Gable9a03ae02017-11-03 11:31:07 -07001013 '-F', '/tmp/named'],),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001014 ref_to_push),
1015 ]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001016 else:
1017 ref_to_push = 'HEAD'
1018
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001019 calls += [
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00001020 (('SaveDescriptionBackup',), None),
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001021 ((['git', 'rev-list',
1022 (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
1023 ref_to_push],),
1024 '1hashPerLine\n'),
1025 ]
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001026
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001027 metrics_arguments = []
1028
Aaron Gableafd52772017-06-27 16:40:10 -07001029 if notify:
Aaron Gable844cf292017-06-28 11:32:59 -07001030 ref_suffix = '%ready,notify=ALL'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001031 metrics_arguments += ['ready', 'notify=ALL']
Aaron Gable844cf292017-06-28 11:32:59 -07001032 else:
Jamie Madill276da0b2018-04-27 14:41:20 -04001033 if not issue and squash:
Aaron Gable844cf292017-06-28 11:32:59 -07001034 ref_suffix = '%wip'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001035 metrics_arguments.append('wip')
Aaron Gable844cf292017-06-28 11:32:59 -07001036 else:
1037 ref_suffix = '%notify=NONE'
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001038 metrics_arguments.append('notify=NONE')
Aaron Gable9b713dd2016-12-14 16:04:21 -08001039
Aaron Gable70f4e242017-06-26 10:45:59 -07001040 if title:
Aaron Gableafd52772017-06-27 16:40:10 -07001041 ref_suffix += ',m=' + title
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001042 metrics_arguments.append('m')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001043
Edward Lemur4508b422019-10-03 21:56:35 +00001044 if issue is None:
1045 calls += [
1046 ((['git', 'config', 'rietveld.cc'],), ''),
1047 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001048 if short_hostname == 'chromium':
1049 # All reviwers and ccs get into ref_suffix.
1050 for r in sorted(reviewers):
1051 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001052 metrics_arguments.append('r')
Edward Lemur4508b422019-10-03 21:56:35 +00001053 if issue is None:
1054 cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
1055 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001056 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001057 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001058 reviewers, cc = [], []
1059 else:
1060 # TODO(crbug/877717): remove this case.
1061 calls += [
1062 (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
1063 sorted(reviewers) + ['joe@example.com',
1064 'chromium-reviews+test-more-cc@chromium.org'] + cc),
1065 {
1066 e: {'email': e}
1067 for e in (reviewers + ['joe@example.com'] + cc)
1068 })
1069 ]
1070 for r in sorted(reviewers):
1071 if r != 'bad-account-or-email':
1072 ref_suffix += ',r=%s' % r
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001073 metrics_arguments.append('r')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001074 reviewers.remove(r)
Edward Lemur4508b422019-10-03 21:56:35 +00001075 if issue is None:
1076 cc += ['joe@example.com']
1077 for c in sorted(cc):
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001078 ref_suffix += ',cc=%s' % c
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001079 metrics_arguments.append('cc')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001080 if c in cc:
1081 cc.remove(c)
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00001082
Edward Lemur687ca902018-12-05 02:30:30 +00001083 for k, v in sorted((labels or {}).items()):
1084 ref_suffix += ',l=%s+%d' % (k, v)
1085 metrics_arguments.append('l=%s+%d' % (k, v))
1086
1087 if tbr:
1088 calls += [
1089 (('GetCodeReviewTbrScore',
1090 '%s-review.googlesource.com' % short_hostname,
1091 'my/repo'),
1092 2,),
1093 ]
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001094
Edward Lemur01f4a4f2018-11-03 00:40:38 +00001095 calls += [
1096 (('time.time',), 1000,),
1097 ((['git', 'push',
1098 'https://%s.googlesource.com/my/repo' % short_hostname,
1099 ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
1100 (('remote:\n'
1101 'remote: Processing changes: (\)\n'
1102 'remote: Processing changes: (|)\n'
1103 'remote: Processing changes: (/)\n'
1104 'remote: Processing changes: (-)\n'
1105 'remote: Processing changes: new: 1 (/)\n'
1106 'remote: Processing changes: new: 1, done\n'
1107 'remote:\n'
1108 'remote: New Changes:\n'
1109 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
1110 ' XXX\n'
1111 'remote:\n'
1112 'To https://%s.googlesource.com/my/repo\n'
1113 ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
1114 ) % (short_hostname, short_hostname)),),
1115 (('time.time',), 2000,),
1116 (('add_repeated',
1117 'sub_commands',
1118 {
1119 'execution_time': 1000,
1120 'command': 'git push',
1121 'exit_code': 0,
1122 'arguments': sorted(metrics_arguments),
1123 }),
1124 None,),
1125 ]
1126
Edward Lemur1b52d872019-05-09 21:12:12 +00001127 final_description = final_description or post_amend_description.strip()
1128 original_title = original_title or title or '<untitled>'
1129 # Trace-related calls
1130 calls += [
1131 # Write a description with context for the current trace.
1132 ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
Edward Lemur75391d42019-05-14 23:35:56 +00001133 'Thu Mar 16 20:00:41 2017\n'
1134 '%(short_hostname)s-review.googlesource.com\n'
1135 '%(change_id)s\n'
1136 '%(title)s\n'
1137 '%(description)s\n'
1138 '1000\n'
1139 '0\n'
1140 '%(trace_name)s' % {
Edward Lemur1b52d872019-05-09 21:12:12 +00001141 'short_hostname': short_hostname,
1142 'change_id': change_id,
1143 'description': final_description,
1144 'title': original_title,
Edward Lemur75391d42019-05-14 23:35:56 +00001145 'trace_name': 'TRACES_DIR/20170316T200041.000000',
Edward Lemur1b52d872019-05-09 21:12:12 +00001146 }],),
1147 None,
1148 ),
1149 # Read traces and shorten git hashes.
1150 ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
1151 True,
1152 ),
1153 ((['FileRead', 'TEMP_DIR/trace-packet'],),
1154 ('git-hash: 0123456789012345678901234567890123456789\n'
1155 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
1156 ),
1157 ((['FileWrite', 'TEMP_DIR/trace-packet',
1158 'git-hash: 012345\n'
1159 'git-hash: abcdea\n'],),
1160 None,
1161 ),
1162 # Make zip file for the git traces.
1163 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
1164 'TEMP_DIR'],),
1165 None,
1166 ),
1167 # Collect git config and gitcookies.
1168 ((['git', 'config', '-l'],),
1169 'git-config-output',
1170 ),
1171 ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
1172 None,
1173 ),
1174 ((['os.path.isfile', '~/.gitcookies'],),
1175 gitcookies_exists,
1176 ),
1177 ]
1178 if gitcookies_exists:
1179 calls += [
1180 ((['FileRead', '~/.gitcookies'],),
1181 'gitcookies 1/SECRET',
1182 ),
1183 ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
1184 None,
1185 ),
1186 ]
1187 calls += [
1188 # Make zip file for the git config and gitcookies.
1189 ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
1190 'TEMP_DIR'],),
1191 None,
1192 ),
1193 ]
1194
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001195 if squash:
1196 calls += [
tandrii33a46ff2016-08-23 05:53:40 -07001197 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001198 ''),
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001199 ((['git', 'config', 'branch.master.gerritserver',
tandrii5d48c322016-08-18 16:19:37 -07001200 'https://chromium-review.googlesource.com'],), ''),
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001201 ((['git', 'config', 'branch.master.gerritsquashhash',
1202 'abcdef0123456789'],), ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001203 ]
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001204 # TODO(crbug/877717): this should never be used.
1205 if squash and short_hostname != 'chromium':
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001206 calls += [
1207 (('AddReviewers',
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001208 'chromium-review.googlesource.com', 'my%2Frepo~123456',
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001209 sorted(reviewers),
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00001210 cc + ['chromium-reviews+test-more-cc@chromium.org'],
1211 notify),
1212 ''),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001213 ]
tandrii@chromium.org1e67bb72016-02-11 12:15:49 +00001214 calls += cls._git_post_upload_calls()
ukai@chromium.orge8077812012-02-03 03:41:46 +00001215 return calls
1216
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001217 def _run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001218 self,
1219 upload_args,
1220 description,
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001221 reviewers=None,
tandriia60502f2016-06-20 02:01:53 -07001222 squash=True,
1223 squash_mode=None,
tandrii@chromium.org10625002016-03-04 20:03:47 +00001224 expected_upstream_ref='origin/refs/heads/master',
Aaron Gable9b713dd2016-12-14 16:04:21 -08001225 title=None,
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001226 notify=False,
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001227 post_amend_description=None,
bradnelsond975b302016-10-23 12:20:23 -07001228 issue=None,
Andrii Shyshkalove9c78ff2017-02-06 15:53:13 +01001229 cc=None,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001230 fetched_status=None,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001231 other_cl_owner=None,
Aaron Gablefd238082017-06-07 13:42:34 -07001232 custom_cl_base=None,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001233 tbr=None,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001234 short_hostname='chromium',
Edward Lemur1b52d872019-05-09 21:12:12 +00001235 labels=None,
1236 change_id=None,
1237 original_title=None,
1238 final_description=None,
Anthony Polito8b955342019-09-24 19:01:36 +00001239 gitcookies_exists=True,
1240 force=False,
1241 fetched_description=None):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001242 """Generic gerrit upload test framework."""
tandriia60502f2016-06-20 02:01:53 -07001243 if squash_mode is None:
1244 if '--no-squash' in upload_args:
1245 squash_mode = 'nosquash'
1246 elif '--squash' in upload_args:
1247 squash_mode = 'squash'
1248 else:
1249 squash_mode = 'default'
1250
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00001251 reviewers = reviewers or []
bradnelsond975b302016-10-23 12:20:23 -07001252 cc = cc or []
Edward Lemur79d4f992019-11-11 23:49:02 +00001253 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07001254 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001255 CookiesAuthenticatorMockFactory(
1256 same_auth=('git-owner.example.com', '', 'pass')))
Edward Lemur125d60a2019-09-13 18:25:41 +00001257 self.mock(git_cl.Changelist, '_GerritCommitMsgHookCheck',
tandrii16e0b4e2016-06-07 10:34:28 -07001258 lambda _, offer_removal: None)
tandriia60502f2016-06-20 02:01:53 -07001259 self.mock(git_cl.gclient_utils, 'RunEditor',
1260 lambda *_, **__: self._mocked_call(['RunEditor']))
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001261 self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
1262 'DownloadGerritHook', force))
Edward Lemur1b52d872019-05-09 21:12:12 +00001263 self.mock(git_cl.gclient_utils, 'FileRead',
1264 lambda path: self._mocked_call(['FileRead', path]))
1265 self.mock(git_cl.gclient_utils, 'FileWrite',
1266 lambda path, contents: self._mocked_call(
1267 ['FileWrite', path, contents]))
1268 self.mock(git_cl, 'datetime_now',
1269 lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0))
1270 self.mock(git_cl.tempfile, 'mkdtemp', lambda: 'TEMP_DIR')
1271 self.mock(git_cl, 'TRACES_DIR', 'TRACES_DIR')
Edward Lemur75391d42019-05-14 23:35:56 +00001272 self.mock(git_cl, 'TRACES_README_FORMAT',
1273 '%(now)s\n'
1274 '%(gerrit_host)s\n'
1275 '%(change_id)s\n'
1276 '%(title)s\n'
1277 '%(description)s\n'
1278 '%(execution_time)s\n'
1279 '%(exit_code)s\n'
1280 '%(trace_name)s')
Edward Lemur1b52d872019-05-09 21:12:12 +00001281 self.mock(git_cl.shutil, 'make_archive',
1282 lambda *args: self._mocked_call(['make_archive'] + list(args)))
1283 self.mock(os.path, 'isfile',
1284 lambda path: self._mocked_call(['os.path.isfile', path]))
tandriia60502f2016-06-20 02:01:53 -07001285
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001286 self.calls = self._gerrit_base_calls(
1287 issue=issue,
Anthony Polito8b955342019-09-24 19:01:36 +00001288 fetched_description=fetched_description or description,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001289 fetched_status=fetched_status,
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001290 other_cl_owner=other_cl_owner,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001291 custom_cl_base=custom_cl_base,
Anthony Polito8b955342019-09-24 19:01:36 +00001292 short_hostname=short_hostname,
1293 change_id=change_id)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001294 if fetched_status != 'ABANDONED':
Aaron Gable9a03ae02017-11-03 11:31:07 -07001295 self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
Edward Lemur0db01f02019-11-12 22:01:51 +00001296 self, expected_content=description))
Aaron Gable9a03ae02017-11-03 11:31:07 -07001297 self.mock(os, 'remove', lambda _: True)
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001298 self.calls += self._gerrit_upload_calls(
1299 description, reviewers, squash,
1300 squash_mode=squash_mode,
1301 expected_upstream_ref=expected_upstream_ref,
Aaron Gablefd238082017-06-07 13:42:34 -07001302 title=title, notify=notify,
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001303 post_amend_description=post_amend_description,
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001304 issue=issue, cc=cc,
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001305 custom_cl_base=custom_cl_base, tbr=tbr,
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001306 short_hostname=short_hostname,
Edward Lemur1b52d872019-05-09 21:12:12 +00001307 labels=labels,
1308 change_id=change_id,
1309 original_title=original_title,
1310 final_description=final_description,
Anthony Polito8b955342019-09-24 19:01:36 +00001311 gitcookies_exists=gitcookies_exists,
1312 force=force)
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +00001313 # Uncomment when debugging.
Raul Tambre80ee78e2019-05-06 22:41:05 +00001314 # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001315 git_cl.main(['upload'] + upload_args)
1316
Edward Lemur1b52d872019-05-09 21:12:12 +00001317 def test_gerrit_upload_traces_no_gitcookies(self):
1318 self._run_gerrit_upload_test(
1319 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001320 'desc ✔\n\nBUG=\n',
Edward Lemur1b52d872019-05-09 21:12:12 +00001321 [],
1322 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001323 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001324 change_id='Ixxx',
1325 gitcookies_exists=False)
1326
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001327 def test_gerrit_upload_without_change_id(self):
tandriia60502f2016-06-20 02:01:53 -07001328 self._run_gerrit_upload_test(
1329 ['--no-squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001330 'desc ✔\n\nBUG=\n',
tandriia60502f2016-06-20 02:01:53 -07001331 [],
1332 squash=False,
Edward Lemur0db01f02019-11-12 22:01:51 +00001333 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001334 change_id='Ixxx')
tandriia60502f2016-06-20 02:01:53 -07001335
1336 def test_gerrit_upload_without_change_id_override_nosquash(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001337 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001338 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001339 'desc ✔\n\nBUG=\n',
tandrii@chromium.org10625002016-03-04 20:03:47 +00001340 [],
tandriia60502f2016-06-20 02:01:53 -07001341 squash=False,
1342 squash_mode='override_nosquash',
Edward Lemur0db01f02019-11-12 22:01:51 +00001343 post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
Edward Lemur1b52d872019-05-09 21:12:12 +00001344 change_id='Ixxx')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001345
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001346 def test_gerrit_no_reviewer(self):
1347 self._run_gerrit_upload_test(
1348 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001349 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
tandriia60502f2016-06-20 02:01:53 -07001350 [],
1351 squash=False,
Edward Lemur1b52d872019-05-09 21:12:12 +00001352 squash_mode='override_nosquash',
1353 change_id='I123456789')
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001354
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001355 def test_gerrit_no_reviewer_non_chromium_host(self):
1356 # TODO(crbug/877717): remove this test case.
1357 self._run_gerrit_upload_test(
1358 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001359 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001360 [],
1361 squash=False,
1362 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001363 short_hostname='other',
1364 change_id='I123456789')
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00001365
Nick Carter8692b182017-11-06 16:30:38 -08001366 def test_gerrit_patchset_title_special_chars(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00001367 self.mock(git_cl.sys, 'stdout', StringIO())
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001368 self._run_gerrit_upload_test(
Nick Carter8692b182017-11-06 16:30:38 -08001369 ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001370 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001371 squash=False,
1372 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001373 title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
1374 change_id='I123456789',
1375 original_title='We\'ll escape ^_ ^ special chars...@{u}')
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00001376
ukai@chromium.orge8077812012-02-03 03:41:46 +00001377 def test_gerrit_reviewers_cmd_line(self):
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001378 self._run_gerrit_upload_test(
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001379 ['-r', 'foo@example.com', '--send-mail'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001380 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
tandrii@chromium.org8da45402016-05-24 23:11:03 +00001381 ['foo@example.com'],
tandriia60502f2016-06-20 02:01:53 -07001382 squash=False,
1383 squash_mode='override_nosquash',
Edward Lemur1b52d872019-05-09 21:12:12 +00001384 notify=True,
1385 change_id='I123456789',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001386 final_description=(
Edward Lemur0db01f02019-11-12 22:01:51 +00001387 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
ukai@chromium.orge8077812012-02-03 03:41:46 +00001388
Anthony Polito8b955342019-09-24 19:01:36 +00001389 def test_gerrit_upload_force_sets_bug(self):
1390 self._run_gerrit_upload_test(
1391 ['-b', '10000', '-f'],
1392 u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
1393 [],
1394 force=True,
1395 expected_upstream_ref='origin/master',
1396 fetched_description='desc=\n\nChange-Id: Ixxx',
1397 original_title='Initial upload',
1398 change_id='Ixxx')
1399
1400 def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
1401 self._run_gerrit_upload_test(
1402 ['-b', '10000', '-f', '-m', 'Title'],
1403 u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
1404 [],
1405 force=True,
1406 issue='123456',
1407 expected_upstream_ref='origin/master',
1408 fetched_description='desc=\n\nChange-Id: Ixxxx',
1409 original_title='Title',
1410 title='Title',
1411 change_id='Izzzz')
1412
Dan Beamd8b04ca2019-10-10 21:23:26 +00001413 def test_gerrit_upload_force_sets_fixed(self):
1414 self._run_gerrit_upload_test(
1415 ['-x', '10000', '-f'],
1416 u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
1417 [],
1418 force=True,
1419 expected_upstream_ref='origin/master',
1420 fetched_description='desc=\n\nChange-Id: Ixxx',
1421 original_title='Initial upload',
1422 change_id='Ixxx')
1423
ukai@chromium.orge8077812012-02-03 03:41:46 +00001424 def test_gerrit_reviewer_multiple(self):
Edward Lemur687ca902018-12-05 02:30:30 +00001425 self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
1426 lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
sivachandra@chromium.orgaebe87f2012-10-22 20:34:21 +00001427 self._run_gerrit_upload_test(
ukai@chromium.orge8077812012-02-03 03:41:46 +00001428 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001429 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
bradnelsond975b302016-10-23 12:20:23 -07001430 'CC=more@example.com,people@example.com\n\n'
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001431 'Change-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001432 ['reviewer@example.com', 'another@example.com'],
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +09001433 expected_upstream_ref='origin/master',
Aaron Gablefd238082017-06-07 13:42:34 -07001434 cc=['more@example.com', 'people@example.com'],
Edward Lemur687ca902018-12-05 02:30:30 +00001435 tbr='reviewer@example.com',
Edward Lemur1b52d872019-05-09 21:12:12 +00001436 labels={'Code-Review': 2},
1437 change_id='123456789',
1438 original_title='Initial upload')
tandriia60502f2016-06-20 02:01:53 -07001439
1440 def test_gerrit_upload_squash_first_is_default(self):
tandriia60502f2016-06-20 02:01:53 -07001441 self._run_gerrit_upload_test(
1442 [],
Edward Lemur0db01f02019-11-12 22:01:51 +00001443 'desc ✔\nBUG=\n\nChange-Id: 123456789',
tandriia60502f2016-06-20 02:01:53 -07001444 [],
Edward Lemur1b52d872019-05-09 21:12:12 +00001445 expected_upstream_ref='origin/master',
1446 change_id='123456789',
1447 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001448
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001449 def test_gerrit_upload_squash_first(self):
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001450 self._run_gerrit_upload_test(
1451 ['--squash'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001452 'desc ✔\nBUG=\n\nChange-Id: 123456789',
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001453 [],
luqui@chromium.org609f3952015-05-04 22:47:04 +00001454 squash=True,
Edward Lemur1b52d872019-05-09 21:12:12 +00001455 expected_upstream_ref='origin/master',
1456 change_id='123456789',
1457 original_title='Initial upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00001458
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001459 def test_gerrit_upload_squash_first_with_labels(self):
1460 self._run_gerrit_upload_test(
1461 ['--squash', '--cq-dry-run', '--enable-auto-submit'],
Edward Lemur0db01f02019-11-12 22:01:51 +00001462 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001463 [],
1464 squash=True,
1465 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001466 labels={'Commit-Queue': 1, 'Auto-Submit': 1},
1467 change_id='123456789',
1468 original_title='Initial upload')
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00001469
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001470 def test_gerrit_upload_squash_first_against_rev(self):
1471 custom_cl_base = 'custom_cl_base_rev_or_branch'
1472 self._run_gerrit_upload_test(
1473 ['--squash', custom_cl_base],
Edward Lemur0db01f02019-11-12 22:01:51 +00001474 'desc ✔\nBUG=\n\nChange-Id: 123456789',
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001475 [],
1476 squash=True,
1477 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001478 custom_cl_base=custom_cl_base,
1479 change_id='123456789',
1480 original_title='Initial upload')
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001481 self.assertIn(
1482 'If you proceed with upload, more than 1 CL may be created by Gerrit',
1483 sys.stdout.getvalue())
1484
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001485 def test_gerrit_upload_squash_reupload(self):
Edward Lemur0db01f02019-11-12 22:01:51 +00001486 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001487 self._run_gerrit_upload_test(
1488 ['--squash'],
1489 description,
1490 [],
1491 squash=True,
1492 expected_upstream_ref='origin/master',
Edward Lemur1b52d872019-05-09 21:12:12 +00001493 issue=123456,
1494 change_id='123456789',
1495 original_title='User input')
tandrii@chromium.org512d79c2016-03-31 12:55:28 +00001496
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001497 def test_gerrit_upload_squash_reupload_to_abandoned(self):
1498 self.mock(git_cl, 'DieWithError',
1499 lambda msg, change=None: self._mocked_call('DieWithError', msg))
Edward Lemur0db01f02019-11-12 22:01:51 +00001500 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001501 with self.assertRaises(SystemExitMock):
1502 self._run_gerrit_upload_test(
1503 ['--squash'],
1504 description,
1505 [],
1506 squash=True,
1507 expected_upstream_ref='origin/master',
1508 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001509 fetched_status='ABANDONED',
1510 change_id='123456789')
Andrii Shyshkalov5c3d0b32017-02-16 17:47:31 +01001511
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001512 def test_gerrit_upload_squash_reupload_to_not_owned(self):
1513 self.mock(git_cl.gerrit_util, 'GetAccountDetails',
1514 lambda *_, **__: {'email': 'yet-another@example.com'})
Edward Lemur0db01f02019-11-12 22:01:51 +00001515 description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001516 self._run_gerrit_upload_test(
1517 ['--squash'],
1518 description,
1519 [],
1520 squash=True,
1521 expected_upstream_ref='origin/master',
1522 issue=123456,
Edward Lemur1b52d872019-05-09 21:12:12 +00001523 other_cl_owner='other@example.com',
1524 change_id='123456789',
1525 original_title='User input')
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001526 self.assertIn(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001527 'WARNING: Change 123456 is owned by other@example.com, but you '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001528 'authenticate to Gerrit as yet-another@example.com.\n'
1529 'Uploading may fail due to lack of permissions',
1530 git_cl.sys.stdout.getvalue())
1531
rmistry@google.com2dd99862015-06-22 12:22:18 +00001532 def test_upload_branch_deps(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00001533 self.mock(git_cl.sys, 'stdout', StringIO())
rmistry@google.com2dd99862015-06-22 12:22:18 +00001534 def mock_run_git(*args, **_kwargs):
1535 if args[0] == ['for-each-ref',
1536 '--format=%(refname:short) %(upstream:short)',
1537 'refs/heads']:
1538 # Create a local branch dependency tree that looks like this:
1539 # test1 -> test2 -> test3 -> test4 -> test5
1540 # -> test3.1
1541 # test6 -> test0
1542 branch_deps = [
1543 'test2 test1', # test1 -> test2
1544 'test3 test2', # test2 -> test3
1545 'test3.1 test2', # test2 -> test3.1
1546 'test4 test3', # test3 -> test4
1547 'test5 test4', # test4 -> test5
1548 'test6 test0', # test0 -> test6
1549 'test7', # test7
1550 ]
1551 return '\n'.join(branch_deps)
1552 self.mock(git_cl, 'RunGit', mock_run_git)
1553
1554 class RecordCalls:
1555 times_called = 0
1556 record_calls = RecordCalls()
1557 def mock_CMDupload(*args, **_kwargs):
1558 record_calls.times_called += 1
1559 return 0
1560 self.mock(git_cl, 'CMDupload', mock_CMDupload)
1561
1562 self.calls = [
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001563 (('ask_for_data', 'This command will checkout all dependent branches '
1564 'and run "git cl upload". Press Enter to continue, '
1565 'or Ctrl+C to abort'), ''),
1566 ]
rmistry@google.com2dd99862015-06-22 12:22:18 +00001567
1568 class MockChangelist():
1569 def __init__(self):
1570 pass
1571 def GetBranch(self):
1572 return 'test1'
1573 def GetIssue(self):
1574 return '123'
1575 def GetPatchset(self):
1576 return '1001'
tandrii@chromium.org4c72b082016-03-31 22:26:35 +00001577 def IsGerrit(self):
1578 return False
rmistry@google.com2dd99862015-06-22 12:22:18 +00001579
1580 ret = git_cl.upload_branch_deps(MockChangelist(), [])
1581 # CMDupload should have been called 5 times because of 5 dependent branches.
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00001582 self.assertEqual(5, record_calls.times_called)
1583 self.assertEqual(0, ret)
rmistry@google.com2dd99862015-06-22 12:22:18 +00001584
tandrii@chromium.org65874e12016-03-04 12:03:02 +00001585 def test_gerrit_change_id(self):
1586 self.calls = [
1587 ((['git', 'write-tree'], ),
1588 'hashtree'),
1589 ((['git', 'rev-parse', 'HEAD~0'], ),
1590 'branch-parent'),
1591 ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
1592 'A B <a@b.org> 1456848326 +0100'),
1593 ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
1594 'C D <c@d.org> 1456858326 +0100'),
1595 ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
1596 'hashchange'),
1597 ]
1598 change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
1599 self.assertEqual(change_id, 'Ihashchange')
1600
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00001601 def test_desecription_append_footer(self):
1602 for init_desc, footer_line, expected_desc in [
1603 # Use unique desc first lines for easy test failure identification.
1604 ('foo', 'R=one', 'foo\n\nR=one'),
1605 ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
1606 ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1607 ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
1608 ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
1609 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
1610 ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
1611 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
1612 ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
1613 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
1614 ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
1615 ]:
1616 desc = git_cl.ChangeDescription(init_desc)
1617 desc.append_footer(footer_line)
1618 self.assertEqual(desc.description, expected_desc)
1619
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001620 def test_update_reviewers(self):
1621 data = [
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001622 ('foo', [], [],
1623 'foo'),
1624 ('foo\nR=xx', [], [],
1625 'foo\nR=xx'),
1626 ('foo\nTBR=xx', [], [],
1627 'foo\nTBR=xx'),
1628 ('foo', ['a@c'], [],
1629 'foo\n\nR=a@c'),
1630 ('foo\nR=xx', ['a@c'], [],
1631 'foo\n\nR=a@c, xx'),
1632 ('foo\nTBR=xx', ['a@c'], [],
1633 'foo\n\nR=a@c\nTBR=xx'),
1634 ('foo\nTBR=xx\nR=yy', ['a@c'], [],
1635 'foo\n\nR=a@c, yy\nTBR=xx'),
1636 ('foo\nBUG=', ['a@c'], [],
1637 'foo\nBUG=\nR=a@c'),
1638 ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
1639 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
1640 ('foo', ['a@c', 'b@c'], [],
1641 'foo\n\nR=a@c, b@c'),
1642 ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
1643 'foo\nBar\n\nR=c@c\nBUG='),
1644 ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
1645 'foo\nBar\n\nR=c@c\nBUG='),
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001646 # Same as the line before, but full of whitespaces.
1647 (
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001648 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001649 'foo\nBar\n\nR=c@c\n BUG =',
1650 ),
1651 # Whitespaces aren't interpreted as new lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001652 ('foo BUG=allo R=joe ', ['c@c'], [],
1653 'foo BUG=allo R=joe\n\nR=c@c'),
1654 # Redundant TBRs get promoted to Rs
1655 ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
1656 'foo\n\nR=a@c, b@c\nTBR=t@c'),
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001657 ]
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001658 expected = [i[-1] for i in data]
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001659 actual = []
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001660 for orig, reviewers, tbrs, _expected in data:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001661 obj = git_cl.ChangeDescription(orig)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07001662 obj.update_reviewers(reviewers, tbrs)
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001663 actual.append(obj.description)
1664 self.assertEqual(expected, actual)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00001665
Nodir Turakulov23b82142017-11-16 11:04:25 -08001666 def test_get_hash_tags(self):
1667 cases = [
1668 ('', []),
1669 ('a', []),
1670 ('[a]', ['a']),
1671 ('[aa]', ['aa']),
1672 ('[a ]', ['a']),
1673 ('[a- ]', ['a']),
1674 ('[a- b]', ['a-b']),
1675 ('[a--b]', ['a-b']),
1676 ('[a', []),
1677 ('[a]x', ['a']),
1678 ('[aa]x', ['aa']),
1679 ('[a b]', ['a-b']),
1680 ('[a b]', ['a-b']),
1681 ('[a__b]', ['a-b']),
1682 ('[a] x', ['a']),
1683 ('[a][b]', ['a', 'b']),
1684 ('[a] [b]', ['a', 'b']),
1685 ('[a][b]x', ['a', 'b']),
1686 ('[a][b] x', ['a', 'b']),
1687 ('[a]\n[b]', ['a']),
1688 ('[a\nb]', []),
1689 ('[a][', ['a']),
1690 ('Revert "[a] feature"', ['a']),
1691 ('Reland "[a] feature"', ['a']),
1692 ('Revert: [a] feature', ['a']),
1693 ('Reland: [a] feature', ['a']),
1694 ('Revert "Reland: [a] feature"', ['a']),
1695 ('Foo: feature', ['foo']),
1696 ('Foo Bar: feature', ['foo-bar']),
1697 ('Revert "Foo bar: feature"', ['foo-bar']),
1698 ('Reland "Foo bar: feature"', ['foo-bar']),
1699 ]
1700 for desc, expected in cases:
1701 change_desc = git_cl.ChangeDescription(desc)
1702 actual = change_desc.get_hash_tags()
1703 self.assertEqual(
1704 actual,
1705 expected,
1706 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
1707
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001708 self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001709 self.assertEqual(None, git_cl.GetTargetRef(None,
1710 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001711 'master'))
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00001712
wittman@chromium.org455dc922015-01-26 20:15:50 +00001713 # Check default target refs for branches.
1714 self.assertEqual('refs/heads/master',
1715 git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001716 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001717 self.assertEqual('refs/heads/master',
1718 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001719 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001720 self.assertEqual('refs/heads/master',
1721 git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001722 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001723 self.assertEqual('refs/branch-heads/123',
1724 git_cl.GetTargetRef('origin',
1725 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001726 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001727 self.assertEqual('refs/diff/test',
1728 git_cl.GetTargetRef('origin',
1729 'refs/remotes/origin/refs/diff/test',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001730 None))
rmistry@google.comc68112d2015-03-03 12:48:06 +00001731 self.assertEqual('refs/heads/chrome/m42',
1732 git_cl.GetTargetRef('origin',
1733 'refs/remotes/origin/chrome/m42',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001734 None))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001735
1736 # Check target refs for user-specified target branch.
1737 for branch in ('branch-heads/123', 'remotes/branch-heads/123',
1738 'refs/remotes/branch-heads/123'):
1739 self.assertEqual('refs/branch-heads/123',
1740 git_cl.GetTargetRef('origin',
1741 'refs/remotes/origin/master',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001742 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001743 for branch in ('origin/master', 'remotes/origin/master',
1744 'refs/remotes/origin/master'):
1745 self.assertEqual('refs/heads/master',
1746 git_cl.GetTargetRef('origin',
1747 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001748 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001749 for branch in ('master', 'heads/master', 'refs/heads/master'):
1750 self.assertEqual('refs/heads/master',
1751 git_cl.GetTargetRef('origin',
1752 'refs/remotes/branch-heads/123',
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01001753 branch))
wittman@chromium.org455dc922015-01-26 20:15:50 +00001754
wychen@chromium.orga872e752015-04-28 23:42:18 +00001755 def test_patch_when_dirty(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001756 # Patch when local tree is dirty.
wychen@chromium.orga872e752015-04-28 23:42:18 +00001757 self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
1758 self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
1759
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001760 @staticmethod
1761 def _get_gerrit_codereview_server_calls(branch, value=None,
1762 git_short_host='host',
Aaron Gable697a91b2018-01-19 15:20:15 -08001763 detect_branch=True,
1764 detect_server=True):
Edward Lemur125d60a2019-09-13 18:25:41 +00001765 """Returns calls executed by Changelist.GetCodereviewServer.
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001766
1767 If value is given, branch.<BRANCH>.gerritcodereview is already set.
1768 """
1769 calls = []
1770 if detect_branch:
1771 calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
Aaron Gable697a91b2018-01-19 15:20:15 -08001772 if detect_server:
1773 calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
1774 CERR1 if value is None else value))
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001775 if value is None:
1776 calls += [
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001777 ((['git', 'config', 'branch.' + branch + '.merge'],),
1778 'refs/heads' + branch),
1779 ((['git', 'config', 'branch.' + branch + '.remote'],),
1780 'origin'),
1781 ((['git', 'config', 'remote.origin.url'],),
1782 'https://%s.googlesource.com/my/repo' % git_short_host),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001783 ]
1784 return calls
1785
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001786 def _patch_common(self, force_codereview=False,
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001787 new_branch=False, git_short_host='host',
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001788 detect_gerrit_server=False,
1789 actual_codereview=None,
1790 codereview_in_url=False):
Edward Lemur79d4f992019-11-11 23:49:02 +00001791 self.mock(git_cl.sys, 'stdout', StringIO())
wychen@chromium.orga872e752015-04-28 23:42:18 +00001792 self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
1793
tandriidf09a462016-08-18 16:23:55 -07001794 if new_branch:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001795 self.calls = [((['git', 'new-branch', 'master'],), '')]
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001796
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001797 if codereview_in_url and actual_codereview == 'rietveld':
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001798 self.calls += [
1799 ((['git', 'rev-parse', '--show-cdup'],), ''),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001800 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001801 ]
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001802
1803 if not force_codereview and not codereview_in_url:
1804 # These calls detect codereview to use.
1805 self.calls += [
1806 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001807 ]
1808 if detect_gerrit_server:
1809 self.calls += self._get_gerrit_codereview_server_calls(
1810 'master', git_short_host=git_short_host,
1811 detect_branch=not new_branch and force_codereview)
1812 actual_codereview = 'gerrit'
1813
1814 if actual_codereview == 'gerrit':
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001815 self.calls += [
1816 (('GetChangeDetail', git_short_host + '-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001817 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001818 {
1819 'current_revision': '7777777777',
1820 'revisions': {
1821 '1111111111': {
1822 '_number': 1,
1823 'fetch': {'http': {
1824 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1825 'ref': 'refs/changes/56/123456/1',
1826 }},
1827 },
1828 '7777777777': {
1829 '_number': 7,
1830 'fetch': {'http': {
1831 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
1832 'ref': 'refs/changes/56/123456/7',
1833 }},
1834 },
1835 },
1836 }),
1837 ]
wychen@chromium.orga872e752015-04-28 23:42:18 +00001838
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001839 def test_patch_gerrit_default(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001840 self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001841 self.calls += [
1842 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1843 'refs/changes/56/123456/7'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001844 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001845 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
Aaron Gable697a91b2018-01-19 15:20:15 -08001846 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001847 ((['git', 'config', 'branch.master.gerritserver',
1848 'https://chromium-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001849 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001850 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1851 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1852 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001853 ]
1854 self.assertEqual(git_cl.main(['patch', '123456']), 0)
1855
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001856 def test_patch_gerrit_new_branch(self):
1857 self._patch_common(
1858 git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
1859 self.calls += [
1860 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
1861 'refs/changes/56/123456/7'],), ''),
1862 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1863 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1864 ''),
1865 ((['git', 'config', 'branch.master.gerritserver',
1866 'https://chromium-review.googlesource.com'],), ''),
1867 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
1868 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1869 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1870 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1871 ]
1872 self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
1873
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001874 def test_patch_gerrit_force(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001875 self._patch_common(
1876 force_codereview=True, git_short_host='host', detect_gerrit_server=True)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001877 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001878 ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001879 'refs/changes/56/123456/7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001880 ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001881 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001882 ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001883 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001884 'https://host-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001885 ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001886 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1887 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1888 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001889 ]
Aaron Gable62619a32017-06-16 08:22:09 -07001890 self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
tandrii@chromium.orgdde64622016-04-13 17:11:21 +00001891
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001892 def test_patch_gerrit_guess_by_url(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001893 self.calls += self._get_gerrit_codereview_server_calls(
1894 'master', git_short_host='else', detect_server=False)
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001895 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001896 actual_codereview='gerrit', git_short_host='else',
1897 codereview_in_url=True, detect_gerrit_server=False)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001898 self.calls += [
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001899 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001900 'refs/changes/56/123456/1'],), ''),
Aaron Gable62619a32017-06-16 08:22:09 -07001901 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001902 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
tandrii5d48c322016-08-18 16:19:37 -07001903 ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001904 ((['git', 'config', 'branch.master.gerritserver',
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001905 'https://else-review.googlesource.com'],), ''),
tandrii33a46ff2016-08-23 05:53:40 -07001906 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
Aaron Gable9387b4f2017-06-08 10:50:03 -07001907 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1908 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1909 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001910 ]
1911 self.assertEqual(git_cl.main(
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01001912 ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001913
Aaron Gable697a91b2018-01-19 15:20:15 -08001914 def test_patch_gerrit_guess_by_url_with_repo(self):
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001915 self.calls += self._get_gerrit_codereview_server_calls(
1916 'master', git_short_host='else', detect_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001917 self._patch_common(
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001918 actual_codereview='gerrit', git_short_host='else',
1919 codereview_in_url=True, detect_gerrit_server=False)
Aaron Gable697a91b2018-01-19 15:20:15 -08001920 self.calls += [
1921 ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
1922 'refs/changes/56/123456/1'],), ''),
1923 ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
1924 ((['git', 'config', 'branch.master.gerritissue', '123456'],),
1925 ''),
1926 ((['git', 'config', 'branch.master.gerritserver',
1927 'https://else-review.googlesource.com'],), ''),
1928 ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
1929 ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
1930 ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
1931 ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
1932 ]
1933 self.assertEqual(git_cl.main(
1934 ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
1935 0)
1936
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001937 def test_patch_gerrit_conflict(self):
Andrii Shyshkalovf57841b2018-08-28 00:48:53 +00001938 self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001939 self.calls += [
1940 ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001941 'refs/changes/56/123456/7'],), ''),
tandrii5d48c322016-08-18 16:19:37 -07001942 ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
1943 ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
1944 SystemExitMock()),
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001945 ]
1946 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001947 git_cl.main(['patch', '123456'])
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00001948
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001949 def test_patch_gerrit_not_exists(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001950
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001951 def notExists(_issue, *_, **kwargs):
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001952 raise git_cl.gerrit_util.GerritError(404, '')
1953 self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
1954
tandriic2405f52016-10-10 08:13:15 -07001955 self.calls = [
1956 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001957 ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
1958 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
1959 ((['git', 'config', 'branch.master.remote'],), 'origin'),
1960 ((['git', 'config', 'remote.origin.url'],),
1961 'https://chromium.googlesource.com/my/repo'),
1962 ((['DieWithError',
1963 'change 123456 at https://chromium-review.googlesource.com does not '
1964 'exist or you have no access to it'],), SystemExitMock()),
tandriic2405f52016-10-10 08:13:15 -07001965 ]
1966 with self.assertRaises(SystemExitMock):
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02001967 self.assertEqual(1, git_cl.main(['patch', '123456']))
tandriic2405f52016-10-10 08:13:15 -07001968
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001969 def _checkout_calls(self):
1970 return [
1971 ((['git', 'config', '--local', '--get-regexp',
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001972 'branch\\..*\\.gerritissue'], ),
1973 ('branch.ger-branch.gerritissue 123456\n'
1974 'branch.gbranch654.gerritissue 654321\n')),
1975 ]
1976
1977 def test_checkout_gerrit(self):
1978 """Tests git cl checkout <issue>."""
1979 self.calls = self._checkout_calls()
1980 self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
1981 self.assertEqual(0, git_cl.main(['checkout', '123456']))
1982
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001983 def test_checkout_not_found(self):
1984 """Tests git cl checkout <issue>."""
Edward Lemur79d4f992019-11-11 23:49:02 +00001985 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00001986 self.calls = self._checkout_calls()
1987 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1988
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001989 def test_checkout_no_branch_issues(self):
1990 """Tests git cl checkout <issue>."""
Edward Lemur79d4f992019-11-11 23:49:02 +00001991 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001992 self.calls = [
1993 ((['git', 'config', '--local', '--get-regexp',
tandrii5d48c322016-08-18 16:19:37 -07001994 'branch\\..*\\.gerritissue'], ), CERR1),
tandrii@chromium.org26c8fd22016-04-11 21:33:21 +00001995 ]
1996 self.assertEqual(1, git_cl.main(['checkout', '99999']))
1997
tandrii@chromium.org28253532016-04-14 13:46:56 +00001998 def _test_gerrit_ensure_authenticated_common(self, auth,
1999 skip_auth_check=False):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002000 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2001 CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
2002 self.mock(git_cl, 'DieWithError',
Christopher Lamf732cd52017-01-24 12:40:11 +11002003 lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
tandrii@chromium.org28253532016-04-14 13:46:56 +00002004 self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
Edward Lemurf38bc172019-09-03 21:02:13 +00002005 cl = git_cl.Changelist()
tandrii@chromium.org28253532016-04-14 13:46:56 +00002006 cl.branch = 'master'
2007 cl.branchref = 'refs/heads/master'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002008 return cl
2009
2010 def test_gerrit_ensure_authenticated_missing(self):
2011 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002012 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002013 })
2014 self.calls.append(
2015 ((['DieWithError',
2016 'Credentials for the following hosts are required:\n'
2017 ' chromium-review.googlesource.com\n'
2018 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002019 'You can (re)generate your credentials by visiting '
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002020 'https://chromium-review.googlesource.com/new-password'],), ''),)
2021 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2022
2023 def test_gerrit_ensure_authenticated_conflict(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002024 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002025 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002026 'chromium.googlesource.com':
2027 ('git-one.example.com', None, 'secret1'),
2028 'chromium-review.googlesource.com':
2029 ('git-other.example.com', None, 'secret2'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002030 })
2031 self.calls.append(
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002032 (('ask_for_data', 'If you know what you are doing '
2033 'press Enter to continue, or Ctrl+C to abort'), ''))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002034 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2035
2036 def test_gerrit_ensure_authenticated_ok(self):
2037 cl = self._test_gerrit_ensure_authenticated_common(auth={
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01002038 'chromium.googlesource.com':
2039 ('git-same.example.com', None, 'secret'),
2040 'chromium-review.googlesource.com':
2041 ('git-same.example.com', None, 'secret'),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00002042 })
2043 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2044
tandrii@chromium.org28253532016-04-14 13:46:56 +00002045 def test_gerrit_ensure_authenticated_skipped(self):
2046 cl = self._test_gerrit_ensure_authenticated_common(
2047 auth={}, skip_auth_check=True)
2048 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2049
Eric Boren2fb63102018-10-05 13:05:03 +00002050 def test_gerrit_ensure_authenticated_bearer_token(self):
2051 cl = self._test_gerrit_ensure_authenticated_common(auth={
2052 'chromium.googlesource.com':
2053 ('', None, 'secret'),
2054 'chromium-review.googlesource.com':
2055 ('', None, 'secret'),
2056 })
2057 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2058 header = gerrit_util.CookiesAuthenticator().get_auth_header(
2059 'chromium.googlesource.com')
2060 self.assertTrue('Bearer' in header)
2061
Daniel Chengcf6269b2019-05-18 01:02:12 +00002062 def test_gerrit_ensure_authenticated_non_https(self):
2063 self.calls = [
2064 ((['git', 'config', '--bool',
2065 'gerrit.skip-ensure-authenticated'],), CERR1),
2066 ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
2067 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2068 ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
2069 ]
2070 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2071 CookiesAuthenticatorMockFactory(hosts_with_creds={}))
Edward Lemurf38bc172019-09-03 21:02:13 +00002072 cl = git_cl.Changelist()
Daniel Chengcf6269b2019-05-18 01:02:12 +00002073 cl.branch = 'master'
2074 cl.branchref = 'refs/heads/master'
2075 cl.lookedup_issue = True
2076 self.assertIsNone(cl.EnsureAuthenticated(force=False))
2077
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002078 def _cmd_set_commit_gerrit_common(self, vote, notify=None):
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002079 self.mock(git_cl.gerrit_util, 'SetReview',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002080 lambda h, i, labels, notify=None:
2081 self._mocked_call(['SetReview', h, i, labels, notify]))
2082
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002083 self.calls = [
2084 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002085 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002086 ((['git', 'config', 'branch.feature.gerritserver'],),
2087 'https://chromium-review.googlesource.com'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002088 ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
2089 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2090 ((['git', 'config', 'remote.origin.url'],),
2091 'https://chromium.googlesource.com/infra/infra.git'),
2092 ((['SetReview', 'chromium-review.googlesource.com',
2093 'infra%2Finfra~123',
Andrii Shyshkalov828701b2016-12-09 10:46:47 +01002094 {'Commit-Queue': vote}, notify],), ''),
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002095 ]
tandriid9e5ce52016-07-13 02:32:59 -07002096
2097 def test_cmd_set_commit_gerrit_clear(self):
2098 self._cmd_set_commit_gerrit_common(0)
2099 self.assertEqual(0, git_cl.main(['set-commit', '-c']))
2100
2101 def test_cmd_set_commit_gerrit_dry(self):
Aaron Gable75e78722017-06-09 10:40:16 -07002102 self._cmd_set_commit_gerrit_common(1, notify=False)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00002103 self.assertEqual(0, git_cl.main(['set-commit', '-d']))
2104
tandriid9e5ce52016-07-13 02:32:59 -07002105 def test_cmd_set_commit_gerrit(self):
2106 self._cmd_set_commit_gerrit_common(2)
2107 self.assertEqual(0, git_cl.main(['set-commit']))
2108
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002109 def test_description_display(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002110 out = StringIO()
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002111 self.mock(git_cl.sys, 'stdout', out)
2112
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002113 self.mock(git_cl, 'Changelist', ChangelistMock)
2114 ChangelistMock.desc = 'foo\n'
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002115
2116 self.assertEqual(0, git_cl.main(['description', '-d']))
2117 self.assertEqual('foo\n', out.getvalue())
2118
iannucci3c972b92016-08-17 13:24:10 -07002119 def test_StatusFieldOverrideIssueMissingArgs(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002120 out = StringIO()
iannucci3c972b92016-08-17 13:24:10 -07002121 self.mock(git_cl.sys, 'stderr', out)
2122
2123 try:
2124 self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
2125 except SystemExit as ex:
2126 self.assertEqual(ex.code, 2)
Edward Lemurf38bc172019-09-03 21:02:13 +00002127 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002128
Edward Lemur79d4f992019-11-11 23:49:02 +00002129 out = StringIO()
iannucci3c972b92016-08-17 13:24:10 -07002130 self.mock(git_cl.sys, 'stderr', out)
2131
2132 try:
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002133 self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
iannucci3c972b92016-08-17 13:24:10 -07002134 except SystemExit as ex:
2135 self.assertEqual(ex.code, 2)
iannuccie53c9352016-08-17 14:40:40 -07002136 self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
iannucci3c972b92016-08-17 13:24:10 -07002137
2138 def test_StatusFieldOverrideIssue(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002139 out = StringIO()
iannucci3c972b92016-08-17 13:24:10 -07002140 self.mock(git_cl.sys, 'stdout', out)
2141
2142 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002143 self.assertEqual(cl_self.issue, 1)
iannucci3c972b92016-08-17 13:24:10 -07002144 return 'foobar'
2145
2146 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
iannuccie53c9352016-08-17 14:40:40 -07002147 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002148 git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
iannuccie53c9352016-08-17 14:40:40 -07002149 0)
iannucci3c972b92016-08-17 13:24:10 -07002150 self.assertEqual(out.getvalue(), 'foobar\n')
2151
iannuccie53c9352016-08-17 14:40:40 -07002152 def test_SetCloseOverrideIssue(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002153
iannuccie53c9352016-08-17 14:40:40 -07002154 def assertIssue(cl_self, *_args):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002155 self.assertEqual(cl_self.issue, 1)
iannuccie53c9352016-08-17 14:40:40 -07002156 return 'foobar'
2157
2158 self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
2159 self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
iannuccie53c9352016-08-17 14:40:40 -07002160 self.assertEqual(
Andrii Shyshkalovfeec80e2018-10-16 01:00:47 +00002161 git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
iannuccie53c9352016-08-17 14:40:40 -07002162
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002163 def test_description(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002164 out = StringIO()
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002165 self.mock(git_cl.sys, 'stdout', out)
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002166 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002167 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2168 ((['git', 'config', 'branch.feature.merge'],), 'feature'),
2169 ((['git', 'config', 'branch.feature.remote'],), 'origin'),
2170 ((['git', 'config', 'remote.origin.url'],),
2171 'https://chromium.googlesource.com/my/repo'),
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002172 (('GetChangeDetail', 'chromium-review.googlesource.com',
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002173 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
Andrii Shyshkalov8fc0c1d2017-01-26 09:38:10 +01002174 {
2175 'current_revision': 'sha1',
2176 'revisions': {'sha1': {
2177 'commit': {'message': 'foobar'},
2178 }},
2179 }),
2180 ]
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002181 self.assertEqual(0, git_cl.main([
Andrii Shyshkalovdd672fb2018-10-16 06:09:51 +00002182 'description',
2183 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
2184 '-d']))
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00002185 self.assertEqual('foobar\n', out.getvalue())
2186
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002187 def test_description_set_raw(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002188 out = StringIO()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002189 self.mock(git_cl.sys, 'stdout', out)
2190
2191 self.mock(git_cl, 'Changelist', ChangelistMock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002192 self.mock(git_cl.sys, 'stdin', StringIO('hihi'))
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002193
2194 self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
2195 self.assertEqual('hihi', ChangelistMock.desc)
2196
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002197 def test_description_appends_bug_line(self):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002198 current_desc = 'Some.\n\nChange-Id: xxx'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002199
2200 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002201 self.assertEqual(
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002202 '# Enter a description of the change.\n'
2203 '# This will be displayed on the codereview site.\n'
2204 '# The first line will also be used as the subject of the review.\n'
2205 '#--------------------This line is 72 characters long'
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002206 '--------------------\n'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002207 'Some.\n\nChange-Id: xxx\nBug: ',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002208 desc)
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002209 # Simulate user changing something.
Aaron Gable3a16ed12017-03-23 10:51:55 -07002210 return 'Some.\n\nChange-Id: xxx\nBug: 123'
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002211
dsansomee2d6fd92016-09-08 00:10:47 -07002212 def UpdateDescriptionRemote(_, desc, force=False):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002213 self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002214
Edward Lemur79d4f992019-11-11 23:49:02 +00002215 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002216 self.mock(git_cl.Changelist, 'GetDescription',
2217 lambda *args: current_desc)
Edward Lemur125d60a2019-09-13 18:25:41 +00002218 self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002219 UpdateDescriptionRemote)
2220 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2221
2222 self.calls = [
2223 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii33a46ff2016-08-23 05:53:40 -07002224 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
tandrii5d48c322016-08-18 16:19:37 -07002225 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2226 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
tandrii@chromium.orgd605a512016-06-03 09:55:00 +00002227 ((['git', 'config', 'core.editor'],), 'vi'),
2228 ]
2229 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2230
Dan Beamd8b04ca2019-10-10 21:23:26 +00002231 def test_description_does_not_append_bug_line_if_fixed_is_present(self):
2232 current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
2233
2234 def RunEditor(desc, _, **kwargs):
Raphael Kubo da Costae9342a72019-10-14 17:49:39 +00002235 self.assertEqual(
Dan Beamd8b04ca2019-10-10 21:23:26 +00002236 '# Enter a description of the change.\n'
2237 '# This will be displayed on the codereview site.\n'
2238 '# The first line will also be used as the subject of the review.\n'
2239 '#--------------------This line is 72 characters long'
2240 '--------------------\n'
2241 'Some.\n\nFixed: 123\nChange-Id: xxx',
2242 desc)
2243 return desc
2244
Edward Lemur79d4f992019-11-11 23:49:02 +00002245 self.mock(git_cl.sys, 'stdout', StringIO())
Dan Beamd8b04ca2019-10-10 21:23:26 +00002246 self.mock(git_cl.Changelist, 'GetDescription',
2247 lambda *args: current_desc)
2248 self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
2249
2250 self.calls = [
2251 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2252 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2253 ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
2254 ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
2255 ((['git', 'config', 'core.editor'],), 'vi'),
2256 ]
2257 self.assertEqual(0, git_cl.main(['description', '--gerrit']))
2258
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002259 def test_description_set_stdin(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002260 out = StringIO()
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002261 self.mock(git_cl.sys, 'stdout', out)
2262
2263 self.mock(git_cl, 'Changelist', ChangelistMock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002264 self.mock(git_cl.sys, 'stdin', StringIO('hi \r\n\t there\n\nman'))
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00002265
2266 self.assertEqual(0, git_cl.main(['description', '-n', '-']))
2267 self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
2268
kmarshall3bff56b2016-06-06 18:31:47 -07002269 def test_archive(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002270 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii1c67da62016-06-10 07:35:53 -07002271
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002272 self.calls = [
2273 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
Edward Lemurf38bc172019-09-03 21:02:13 +00002274 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002275 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2276 ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
Edward Lemurf38bc172019-09-03 21:02:13 +00002277 ((['git', 'branch', '-D', 'foo'],), '')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002278 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002279
kmarshall3bff56b2016-06-06 18:31:47 -07002280 self.mock(git_cl, 'get_cl_statuses',
2281 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002282 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2283 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2284 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002285
2286 self.assertEqual(0, git_cl.main(['archive', '-f']))
2287
2288 def test_archive_current_branch_fails(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002289 self.mock(git_cl.sys, 'stdout', StringIO())
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002290 self.calls = [
2291 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2292 'refs/heads/master'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002293 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2294 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002295
kmarshall9249e012016-08-23 12:02:16 -07002296 self.mock(git_cl, 'get_cl_statuses',
2297 lambda branches, fine_grained, max_processes:
2298 [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
2299
2300 self.assertEqual(1, git_cl.main(['archive', '-f']))
2301
2302 def test_archive_dry_run(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002303 self.mock(git_cl.sys, 'stdout', StringIO())
kmarshall9249e012016-08-23 12:02:16 -07002304
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002305 self.calls = [
2306 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2307 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002308 ((['git', 'symbolic-ref', 'HEAD'],), 'master')
2309 ]
kmarshall3bff56b2016-06-06 18:31:47 -07002310
2311 self.mock(git_cl, 'get_cl_statuses',
2312 lambda branches, fine_grained, max_processes:
kmarshall9249e012016-08-23 12:02:16 -07002313 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2314 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2315 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
kmarshall3bff56b2016-06-06 18:31:47 -07002316
kmarshall9249e012016-08-23 12:02:16 -07002317 self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
2318
2319 def test_archive_no_tags(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002320 self.mock(git_cl.sys, 'stdout', StringIO())
kmarshall9249e012016-08-23 12:02:16 -07002321
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002322 self.calls = [
2323 ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
2324 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002325 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2326 ((['git', 'branch', '-D', 'foo'],), '')
2327 ]
kmarshall9249e012016-08-23 12:02:16 -07002328
2329 self.mock(git_cl, 'get_cl_statuses',
2330 lambda branches, fine_grained, max_processes:
2331 [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
2332 (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
2333 (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
2334
2335 self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
kmarshall3bff56b2016-06-06 18:31:47 -07002336
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002337 def test_cmd_issue_erase_existing(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002338 out = StringIO()
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002339 self.mock(git_cl.sys, 'stdout', out)
2340 self.calls = [
2341 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002342 # Let this command raise exception (retcode=1) - it should be ignored.
2343 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
tandrii5d48c322016-08-18 16:19:37 -07002344 CERR1),
2345 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2346 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002347 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2348 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2349 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002350 ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00002351 ]
2352 self.assertEqual(0, git_cl.main(['issue', '0']))
2353
Aaron Gable400e9892017-07-12 15:31:21 -07002354 def test_cmd_issue_erase_existing_with_change_id(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002355 out = StringIO()
Aaron Gable400e9892017-07-12 15:31:21 -07002356 self.mock(git_cl.sys, 'stdout', out)
2357 self.mock(git_cl.Changelist, 'GetDescription',
2358 lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
2359 self.calls = [
2360 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Aaron Gable400e9892017-07-12 15:31:21 -07002361 # Let this command raise exception (retcode=1) - it should be ignored.
2362 ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
2363 CERR1),
2364 ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
2365 ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
2366 ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
2367 ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
2368 ''),
Aaron Gableca01e2c2017-07-19 11:16:02 -07002369 ((['git', 'log', '-1', '--format=%B'],),
2370 'This is a description\n\nChange-Id: Ideadbeef'),
2371 ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
Aaron Gable400e9892017-07-12 15:31:21 -07002372 ]
2373 self.assertEqual(0, git_cl.main(['issue', '0']))
2374
phajdan.jre328cf92016-08-22 04:12:17 -07002375 def test_cmd_issue_json(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002376 out = StringIO()
phajdan.jre328cf92016-08-22 04:12:17 -07002377 self.mock(git_cl.sys, 'stdout', out)
2378 self.calls = [
2379 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002380 ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
2381 ((['git', 'config', 'branch.feature.gerritserver'],),
2382 'https://chromium-review.googlesource.com'),
phajdan.jre328cf92016-08-22 04:12:17 -07002383 (('write_json', 'output.json',
Andrii Shyshkalova185e2e2018-11-21 00:42:55 +00002384 {'issue': 123,
2385 'issue_url': 'https://chromium-review.googlesource.com/123'}),
phajdan.jre328cf92016-08-22 04:12:17 -07002386 ''),
2387 ]
2388 self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
2389
tandrii16e0b4e2016-06-07 10:34:28 -07002390 def _common_GerritCommitMsgHookCheck(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002391 self.mock(git_cl.sys, 'stdout', StringIO())
tandrii16e0b4e2016-06-07 10:34:28 -07002392 self.mock(git_cl.os.path, 'abspath',
2393 lambda path: self._mocked_call(['abspath', path]))
2394 self.mock(git_cl.os.path, 'exists',
2395 lambda path: self._mocked_call(['exists', path]))
2396 self.mock(git_cl.gclient_utils, 'FileRead',
2397 lambda path: self._mocked_call(['FileRead', path]))
2398 self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
2399 lambda path: self._mocked_call(['rm_file_or_tree', path]))
2400 self.calls = [
2401 ((['git', 'rev-parse', '--show-cdup'],), '../'),
2402 ((['abspath', '../'],), '/abs/git_repo_root'),
2403 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002404 return git_cl.Changelist(issue=123)
tandrii16e0b4e2016-06-07 10:34:28 -07002405
2406 def test_GerritCommitMsgHookCheck_custom_hook(self):
2407 cl = self._common_GerritCommitMsgHookCheck()
2408 self.calls += [
2409 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2410 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2411 '#!/bin/sh\necho "custom hook"')
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_not_exists(self):
2416 cl = self._common_GerritCommitMsgHookCheck()
2417 self.calls += [
2418 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
2419 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002420 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002421
2422 def test_GerritCommitMsgHookCheck(self):
2423 cl = self._common_GerritCommitMsgHookCheck()
2424 self.calls += [
2425 ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
2426 ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2427 '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002428 (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
tandrii16e0b4e2016-06-07 10:34:28 -07002429 ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
2430 ''),
2431 ]
Edward Lemur125d60a2019-09-13 18:25:41 +00002432 cl._GerritCommitMsgHookCheck(offer_removal=True)
tandrii16e0b4e2016-06-07 10:34:28 -07002433
tandriic4344b52016-08-29 06:04:54 -07002434 def test_GerritCmdLand(self):
2435 self.calls += [
2436 ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
2437 ((['git', 'config', 'branch.feature.gerritsquashhash'],),
2438 'deadbeaf'),
2439 ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
2440 ((['git', 'config', 'branch.feature.gerritserver'],),
2441 'chromium-review.googlesource.com'),
2442 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002443 cl = git_cl.Changelist(issue=123)
Edward Lemur125d60a2019-09-13 18:25:41 +00002444 cl._GetChangeDetail = lambda *args, **kwargs: {
tandriic4344b52016-08-29 06:04:54 -07002445 'labels': {},
2446 'current_revision': 'deadbeaf',
2447 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002448 cl._GetChangeCommit = lambda: {
agable32978d92016-11-01 12:55:02 -07002449 'commit': 'deadbeef',
Aaron Gable02cdbb42016-12-13 16:24:25 -08002450 'web_links': [{'name': 'gitiles',
agable32978d92016-11-01 12:55:02 -07002451 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
2452 }
Edward Lemur125d60a2019-09-13 18:25:41 +00002453 cl.SubmitIssue = lambda wait_for_merge: None
Edward Lemur79d4f992019-11-11 23:49:02 +00002454 out = StringIO()
tandrii8da412c2016-09-07 16:01:07 -07002455 self.mock(sys, 'stdout', out)
Olivier Robin75ee7252018-04-13 10:02:56 +02002456 self.assertEqual(0, cl.CMDLand(force=True,
2457 bypass_hooks=True,
2458 verbose=True,
2459 parallel=False))
tandrii8da412c2016-09-07 16:01:07 -07002460 self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002461 self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
tandriic4344b52016-08-29 06:04:54 -07002462
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002463 def _mock_gerrit_changes_for_detail_cache(self):
Edward Lemur125d60a2019-09-13 18:25:41 +00002464 self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002465
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002466 def test_gerrit_change_detail_cache_simple(self):
2467 self._mock_gerrit_changes_for_detail_cache()
2468 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002469 (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
2470 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
2471 (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002472 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002473 cl1 = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002474 cl1._cached_remote_url = (
2475 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Edward Lemurf38bc172019-09-03 21:02:13 +00002476 cl2 = git_cl.Changelist(issue=2)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002477 cl2._cached_remote_url = (
2478 True, 'https://chromium.googlesource.com/ab/repo')
Andrii Shyshkalovb7214602018-08-22 23:20:26 +00002479 self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
2480 self.assertEqual(cl1._GetChangeDetail(), 'a')
2481 self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
2482 self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
2483 self.assertEqual(cl1._GetChangeDetail(), 'a')
2484 self.assertEqual(cl2._GetChangeDetail(), 'b2')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002485
2486 def test_gerrit_change_detail_cache_options(self):
2487 self._mock_gerrit_changes_for_detail_cache()
2488 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002489 (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
2490 (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
2491 (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
2492 # no longer in cache.
2493 (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002494 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002495 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002496 cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01002497 self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
2498 self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
2499 self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
2500 self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
2501 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2502 self.assertEqual(cl._GetChangeDetail(), 'cab')
2503
2504 self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
2505 self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
2506 self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
2507 self.assertEqual(cl._GetChangeDetail(), 'cab')
2508
2509 # Finally, no_cache should invalidate all caches for given change.
2510 self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
2511 self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
2512
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002513 def test_gerrit_description_caching(self):
2514 def gen_detail(rev, desc):
2515 return {
2516 'current_revision': rev,
2517 'revisions': {rev: {'commit': {'message': desc}}}
2518 }
2519 self.calls = [
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002520 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002521 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2522 gen_detail('rev1', 'desc1')),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002523 (('GetChangeDetail', 'host', 'my%2Frepo~1',
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002524 ['CURRENT_REVISION', 'CURRENT_COMMIT']),
2525 gen_detail('rev2', 'desc2')),
2526 ]
2527
2528 self._mock_gerrit_changes_for_detail_cache()
Edward Lemurf38bc172019-09-03 21:02:13 +00002529 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002530 cl._cached_remote_url = (
2531 True, 'https://chromium.googlesource.com/a/my/repo.git/')
Andrii Shyshkalov21fb8242017-02-15 21:09:27 +01002532 self.assertEqual(cl.GetDescription(), 'desc1')
2533 self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
2534 self.assertEqual(cl.GetDescription(force=True), 'desc2')
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002535
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002536 def test_print_current_creds(self):
2537 class CookiesAuthenticatorMock(object):
2538 def __init__(self):
2539 self.gitcookies = {
2540 'host.googlesource.com': ('user', 'pass'),
2541 'host-review.googlesource.com': ('user', 'pass'),
2542 }
2543 self.netrc = self
2544 self.netrc.hosts = {
2545 'github.com': ('user2', None, 'pass2'),
2546 'host2.googlesource.com': ('user3', None, 'pass'),
2547 }
2548 self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
2549 CookiesAuthenticatorMock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002550 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002551 git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
2552 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2553 ' Host\t User\t Which file',
2554 '============================\t=====\t===========',
2555 'host-review.googlesource.com\t user\t.gitcookies',
2556 ' host.googlesource.com\t user\t.gitcookies',
2557 ' host2.googlesource.com\tuser3\t .netrc',
2558 ])
Edward Lemur79d4f992019-11-11 23:49:02 +00002559 sys.stdout.seek(0)
2560 sys.stdout.truncate(0)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002561 git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
2562 self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
2563 ' Host\tUser\t Which file',
2564 '============================\t====\t===========',
2565 'host-review.googlesource.com\tuser\t.gitcookies',
2566 ' host.googlesource.com\tuser\t.gitcookies',
2567 ])
2568
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002569 def _common_creds_check_mocks(self):
2570 def exists_mock(path):
2571 dirname = os.path.dirname(path)
2572 if dirname == os.path.expanduser('~'):
2573 dirname = '~'
2574 base = os.path.basename(path)
2575 if base in ('.netrc', '.gitcookies'):
2576 return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
2577 # git cl also checks for existence other files not relevant to this test.
2578 return None
2579 self.mock(os.path, 'exists', exists_mock)
Edward Lemur79d4f992019-11-11 23:49:02 +00002580 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002581
2582 def test_creds_check_gitcookies_not_configured(self):
2583 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002584 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002585 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002586 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002587 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002588 ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
2589 (('os.path.exists', '~/.netrc'), True),
2590 (('ask_for_data', 'Press Enter to setup .gitcookies, '
2591 'or Ctrl+C to abort'), ''),
2592 ((['git', 'config', '--global', 'http.cookiefile',
2593 os.path.expanduser('~/.gitcookies')], ), ''),
2594 ]
2595 self.assertEqual(0, git_cl.main(['creds-check']))
2596 self.assertRegexpMatches(
2597 sys.stdout.getvalue(),
2598 '^You seem to be using outdated .netrc for git credentials:')
2599 self.assertRegexpMatches(
2600 sys.stdout.getvalue(),
2601 '\nConfigured git to use .gitcookies from')
2602
2603 def test_creds_check_gitcookies_configured_custom_broken(self):
2604 self._common_creds_check_mocks()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002605 self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01002606 lambda _, include_netrc=False: [])
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002607 self.calls = [
Aaron Gable8797cab2018-03-06 13:55:00 -08002608 ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002609 ((['git', 'config', '--global', 'http.cookiefile'],),
2610 '/custom/.gitcookies'),
2611 (('os.path.exists', '/custom/.gitcookies'), False),
2612 (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
2613 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
2614 ((['git', 'config', '--global', 'http.cookiefile',
2615 os.path.expanduser('~/.gitcookies')], ), ''),
2616 ]
2617 self.assertEqual(0, git_cl.main(['creds-check']))
2618 self.assertRegexpMatches(
2619 sys.stdout.getvalue(),
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002620 'WARNING: You have configured custom path to .gitcookies: ')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01002621 self.assertRegexpMatches(
2622 sys.stdout.getvalue(),
2623 'However, your configured .gitcookies file is missing.')
2624
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002625 def test_git_cl_comment_add_gerrit(self):
2626 self.mock(git_cl.gerrit_util, 'SetReview',
Aaron Gable636b13f2017-07-14 10:42:48 -07002627 lambda host, change, msg, ready:
2628 self._mocked_call('SetReview', host, change, msg, ready))
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002629 self.calls = [
2630 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2631 ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
2632 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2633 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2634 'origin/master'),
2635 ((['git', 'config', 'remote.origin.url'],),
2636 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002637 (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
2638 'msg', None),
Aaron Gable636b13f2017-07-14 10:42:48 -07002639 None),
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01002640 ]
2641 self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
2642 '-a', 'msg']))
2643
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002644 def test_git_cl_comments_fetch_gerrit(self):
Edward Lemur79d4f992019-11-11 23:49:02 +00002645 self.mock(sys, 'stdout', StringIO())
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002646 self.calls = [
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002647 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2648 ((['git', 'config', 'branch.foo.merge'],), ''),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002649 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2650 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2651 'origin/master'),
2652 ((['git', 'config', 'remote.origin.url'],),
2653 'https://chromium.googlesource.com/infra/infra'),
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00002654 (('GetChangeDetail', 'chromium-review.googlesource.com',
2655 'infra%2Finfra~1',
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002656 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2657 'CURRENT_COMMIT']), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002658 'owner': {'email': 'owner@example.com'},
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002659 'current_revision': 'ba5eba11',
2660 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002661 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002662 '_number': 1,
2663 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002664 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002665 '_number': 2,
2666 },
2667 },
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002668 'messages': [
2669 {
2670 u'_revision_number': 1,
2671 u'author': {
2672 u'_account_id': 1111084,
2673 u'email': u'commit-bot@chromium.org',
2674 u'name': u'Commit Bot'
2675 },
2676 u'date': u'2017-03-15 20:08:45.000000000',
2677 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
Dirk Prankef6a58802017-10-17 12:49:42 -07002678 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002679 u'tag': u'autogenerated:cq:dry-run'
2680 },
2681 {
2682 u'_revision_number': 2,
2683 u'author': {
2684 u'_account_id': 11151243,
2685 u'email': u'owner@example.com',
2686 u'name': u'owner'
2687 },
2688 u'date': u'2017-03-16 20:00:41.000000000',
2689 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2690 u'message': u'PTAL',
2691 },
2692 {
2693 u'_revision_number': 2,
2694 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002695 u'_account_id': 148512,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002696 u'email': u'reviewer@example.com',
2697 u'name': u'reviewer'
2698 },
2699 u'date': u'2017-03-17 05:19:37.500000000',
2700 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2701 u'message': u'Patch Set 2: Code-Review+1',
2702 },
2703 ]
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002704 }),
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00002705 (('GetChangeComments', 'chromium-review.googlesource.com',
2706 'infra%2Finfra~1'), {
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002707 '/COMMIT_MSG': [
2708 {
2709 'author': {'email': u'reviewer@example.com'},
2710 'updated': u'2017-03-17 05:19:37.500000000',
2711 'patch_set': 2,
2712 'side': 'REVISION',
2713 'message': 'Please include a bug link',
2714 },
2715 ],
2716 'codereview.settings': [
2717 {
2718 'author': {'email': u'owner@example.com'},
2719 'updated': u'2017-03-16 20:00:41.000000000',
2720 'patch_set': 2,
2721 'side': 'PARENT',
2722 'line': 42,
2723 'message': 'I removed this because it is bad',
2724 },
2725 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002726 }),
2727 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2728 'infra%2Finfra~1'), {}),
2729 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
Leszek Swirski45b20c42018-09-17 17:05:26 +00002730 ] * 2 + [
2731 (('write_json', 'output.json', [
2732 {
2733 u'date': u'2017-03-16 20:00:41.000000',
2734 u'message': (
2735 u'PTAL\n' +
2736 u'\n' +
2737 u'codereview.settings\n' +
2738 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2739 u'c/1/2/codereview.settings#b42\n' +
2740 u' I removed this because it is bad\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002741 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002742 u'approval': False,
2743 u'disapproval': False,
2744 u'sender': u'owner@example.com'
2745 }, {
2746 u'date': u'2017-03-17 05:19:37.500000',
2747 u'message': (
2748 u'Patch Set 2: Code-Review+1\n' +
2749 u'\n' +
2750 u'/COMMIT_MSG\n' +
2751 u' PS2, File comment: https://chromium-review.googlesource' +
2752 u'.com/c/1/2//COMMIT_MSG#\n' +
2753 u' Please include a bug link\n'),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002754 u'autogenerated': False,
Leszek Swirski45b20c42018-09-17 17:05:26 +00002755 u'approval': False,
2756 u'disapproval': False,
2757 u'sender': u'reviewer@example.com'
2758 }
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002759 ]), '')
Leszek Swirski45b20c42018-09-17 17:05:26 +00002760 ]
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002761 expected_comments_summary = [
2762 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002763 message=(
2764 u'PTAL\n' +
2765 u'\n' +
2766 u'codereview.settings\n' +
2767 u' Base, Line 42: https://chromium-review.googlesource.com/' +
2768 u'c/1/2/codereview.settings#b42\n' +
2769 u' I removed this because it is bad\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002770 date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002771 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002772 disapproval=False, approval=False, sender=u'owner@example.com'),
2773 git_cl._CommentSummary(
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07002774 message=(
2775 u'Patch Set 2: Code-Review+1\n' +
2776 u'\n' +
2777 u'/COMMIT_MSG\n' +
2778 u' PS2, File comment: https://chromium-review.googlesource.com/' +
2779 u'c/1/2//COMMIT_MSG#\n' +
2780 u' Please include a bug link\n'),
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002781 date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002782 autogenerated=False,
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002783 disapproval=False, approval=False, sender=u'reviewer@example.com'),
2784 ]
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002785 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002786 issue=1, branchref='refs/heads/foo')
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01002787 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002788 self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
2789 self.assertEqual(
2790 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
2791
2792 def test_git_cl_comments_robot_comments(self):
2793 # git cl comments also fetches robot comments (which are considered a type
2794 # of autogenerated comment), and unlike other types of comments, only robot
2795 # comments from the latest patchset are shown.
Edward Lemur79d4f992019-11-11 23:49:02 +00002796 self.mock(sys, 'stdout', StringIO())
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002797 self.calls = [
2798 ((['git', 'config', 'branch.foo.gerritserver'],), ''),
2799 ((['git', 'config', 'branch.foo.merge'],), ''),
2800 ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
2801 ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
2802 'origin/master'),
2803 ((['git', 'config', 'remote.origin.url'],),
2804 'https://chromium.googlesource.com/infra/infra'),
2805 (('GetChangeDetail', 'chromium-review.googlesource.com',
2806 'infra%2Finfra~1',
2807 ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
2808 'CURRENT_COMMIT']), {
2809 'owner': {'email': 'owner@example.com'},
2810 'current_revision': 'ba5eba11',
2811 'revisions': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002812 'deadbeaf': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002813 '_number': 1,
2814 },
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002815 'ba5eba11': {
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002816 '_number': 2,
2817 },
2818 },
2819 'messages': [
2820 {
2821 u'_revision_number': 1,
2822 u'author': {
2823 u'_account_id': 1111084,
2824 u'email': u'commit-bot@chromium.org',
2825 u'name': u'Commit Bot'
2826 },
2827 u'date': u'2017-03-15 20:08:45.000000000',
2828 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
2829 u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
2830 u'tag': u'autogenerated:cq:dry-run'
2831 },
2832 {
2833 u'_revision_number': 1,
2834 u'author': {
2835 u'_account_id': 123,
2836 u'email': u'tricium@serviceaccount.com',
2837 u'name': u'Tricium'
2838 },
2839 u'date': u'2017-03-16 20:00:41.000000000',
2840 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2841 u'message': u'(1 comment)',
2842 u'tag': u'autogenerated:tricium',
2843 },
2844 {
2845 u'_revision_number': 1,
2846 u'author': {
2847 u'_account_id': 123,
2848 u'email': u'tricium@serviceaccount.com',
2849 u'name': u'Tricium'
2850 },
2851 u'date': u'2017-03-16 20:00:41.000000000',
2852 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
2853 u'message': u'(1 comment)',
2854 u'tag': u'autogenerated:tricium',
2855 },
2856 {
2857 u'_revision_number': 2,
2858 u'author': {
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002859 u'_account_id': 123,
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002860 u'email': u'tricium@serviceaccount.com',
2861 u'name': u'reviewer'
2862 },
2863 u'date': u'2017-03-17 05:30:37.000000000',
2864 u'tag': u'autogenerated:tricium',
2865 u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
2866 u'message': u'(1 comment)',
2867 },
2868 ]
2869 }),
2870 (('GetChangeComments', 'chromium-review.googlesource.com',
2871 'infra%2Finfra~1'), {}),
2872 (('GetChangeRobotComments', 'chromium-review.googlesource.com',
2873 'infra%2Finfra~1'), {
2874 'codereview.settings': [
2875 {
2876 u'author': {u'email': u'tricium@serviceaccount.com'},
2877 u'updated': u'2017-03-17 05:30:37.000000000',
2878 u'robot_run_id': u'5565031076855808',
2879 u'robot_id': u'Linter/Category',
2880 u'tag': u'autogenerated:tricium',
2881 u'patch_set': 2,
2882 u'side': u'REVISION',
2883 u'message': u'Linter warning message text',
2884 u'line': 32,
2885 },
2886 ],
2887 }),
2888 ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
2889 ]
2890 expected_comments_summary = [
2891 git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
2892 message=(
2893 u'(1 comment)\n\ncodereview.settings\n'
2894 u' PS2, Line 32: https://chromium-review.googlesource.com/'
2895 u'c/1/2/codereview.settings#32\n'
2896 u' Linter warning message text\n'),
2897 sender=u'tricium@serviceaccount.com',
2898 autogenerated=True, approval=False, disapproval=False)
2899 ]
2900 cl = git_cl.Changelist(
Edward Lemurf38bc172019-09-03 21:02:13 +00002901 issue=1, branchref='refs/heads/foo')
Quinten Yearsley0e617c02019-02-20 00:37:03 +00002902 self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01002903
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002904 def test_get_remote_url_with_mirror(self):
2905 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002906
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002907 def selective_os_path_isdir_mock(path):
2908 if path == '/cache/this-dir-exists':
2909 return self._mocked_call('os.path.isdir', path)
2910 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002911
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002912 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2913
2914 url = 'https://chromium.googlesource.com/my/repo'
2915 self.calls = [
2916 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2917 ((['git', 'config', 'branch.master.merge'],), 'master'),
2918 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2919 ((['git', 'config', 'remote.origin.url'],),
2920 '/cache/this-dir-exists'),
2921 (('os.path.isdir', '/cache/this-dir-exists'),
2922 True),
2923 # Runs in /cache/this-dir-exists.
2924 ((['git', 'config', 'remote.origin.url'],),
2925 url),
2926 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002927 cl = git_cl.Changelist(issue=1)
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00002928 self.assertEqual(cl.GetRemoteUrl(), url)
2929 self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
2930
Edward Lemur298f2cf2019-02-22 21:40:39 +00002931 def test_get_remote_url_non_existing_mirror(self):
2932 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002933
Edward Lemur298f2cf2019-02-22 21:40:39 +00002934 def selective_os_path_isdir_mock(path):
2935 if path == '/cache/this-dir-doesnt-exist':
2936 return self._mocked_call('os.path.isdir', path)
2937 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002938
Edward Lemur298f2cf2019-02-22 21:40:39 +00002939 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2940 self.mock(logging, 'error',
2941 lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
2942
2943 self.calls = [
2944 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2945 ((['git', 'config', 'branch.master.merge'],), 'master'),
2946 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2947 ((['git', 'config', 'remote.origin.url'],),
2948 '/cache/this-dir-doesnt-exist'),
2949 (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
2950 False),
2951 (('logging.error',
Daniel Bratell4a60db42019-09-16 17:02:52 +00002952 'Remote "origin" for branch "master" points to'
2953 ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
Edward Lemur298f2cf2019-02-22 21:40:39 +00002954 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002955 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002956 self.assertIsNone(cl.GetRemoteUrl())
2957
2958 def test_get_remote_url_misconfigured_mirror(self):
2959 original_os_path_isdir = os.path.isdir
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002960
Edward Lemur298f2cf2019-02-22 21:40:39 +00002961 def selective_os_path_isdir_mock(path):
2962 if path == '/cache/this-dir-exists':
2963 return self._mocked_call('os.path.isdir', path)
2964 return original_os_path_isdir(path)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002965
Edward Lemur298f2cf2019-02-22 21:40:39 +00002966 self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
2967 self.mock(logging, 'error',
2968 lambda *a: self._mocked_call('logging.error', *a))
2969
2970 self.calls = [
2971 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2972 ((['git', 'config', 'branch.master.merge'],), 'master'),
2973 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2974 ((['git', 'config', 'remote.origin.url'],),
2975 '/cache/this-dir-exists'),
2976 (('os.path.isdir', '/cache/this-dir-exists'), True),
2977 # Runs in /cache/this-dir-exists.
2978 ((['git', 'config', 'remote.origin.url'],), ''),
2979 (('logging.error',
2980 'Remote "%(remote)s" for branch "%(branch)s" points to '
2981 '"%(cache_path)s", but it is misconfigured.\n'
2982 '"%(cache_path)s" must be a git repo and must have a remote named '
2983 '"%(remote)s" pointing to the git host.', {
2984 'remote': 'origin',
2985 'cache_path': '/cache/this-dir-exists',
2986 'branch': 'master'}
2987 ), None),
2988 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00002989 cl = git_cl.Changelist(issue=1)
Edward Lemur298f2cf2019-02-22 21:40:39 +00002990 self.assertIsNone(cl.GetRemoteUrl())
2991
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00002992 def test_gerrit_change_identifier_with_project(self):
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00002993 self.calls = [
2994 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
2995 ((['git', 'config', 'branch.master.merge'],), 'master'),
2996 ((['git', 'config', 'branch.master.remote'],), 'origin'),
2997 ((['git', 'config', 'remote.origin.url'],),
2998 'https://chromium.googlesource.com/a/my/repo.git/'),
2999 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003000 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003001 self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
3002
3003 def test_gerrit_change_identifier_without_project(self):
3004 self.calls = [
3005 ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
3006 ((['git', 'config', 'branch.master.merge'],), 'master'),
3007 ((['git', 'config', 'branch.master.remote'],), 'origin'),
3008 ((['git', 'config', 'remote.origin.url'],), CERR1),
3009 ]
Edward Lemurf38bc172019-09-03 21:02:13 +00003010 cl = git_cl.Changelist(issue=123456)
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00003011 self.assertEqual(cl._GerritChangeIdentifier(), '123456')
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00003012
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003013
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003014class CMDTestCaseBase(unittest.TestCase):
3015 _STATUSES = [
3016 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
3017 'INFRA_FAILURE', 'CANCELED',
3018 ]
3019 _CHANGE_DETAIL = {
3020 'project': 'depot_tools',
3021 'status': 'OPEN',
3022 'owner': {'email': 'owner@e.mail'},
3023 'current_revision': 'beeeeeef',
3024 'revisions': {
3025 'deadbeaf': {'_number': 6},
3026 'beeeeeef': {
3027 '_number': 7,
3028 'fetch': {'http': {
3029 'url': 'https://chromium.googlesource.com/depot_tools',
3030 'ref': 'refs/changes/56/123456/7'
3031 }},
3032 },
3033 },
3034 }
3035 _DEFAULT_RESPONSE = {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003036 'builds': [{
3037 'id': str(100 + idx),
3038 'builder': {
3039 'project': 'chromium',
3040 'bucket': 'try',
3041 'builder': 'bot_' + status.lower(),
3042 },
3043 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3044 'tags': [],
3045 'status': status,
3046 } for idx, status in enumerate(_STATUSES)]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003047 }
3048
Edward Lemur4c707a22019-09-24 21:13:43 +00003049 def setUp(self):
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003050 super(CMDTestCaseBase, self).setUp()
Edward Lemur79d4f992019-11-11 23:49:02 +00003051 mock.patch('git_cl.sys.stdout', StringIO()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003052 mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
3053 mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003054 mock.patch('git_cl.Changelist.GetCodereviewServer',
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003055 return_value='https://chromium-review.googlesource.com').start()
3056 mock.patch('git_cl.Changelist.GetMostRecentPatchset',
3057 return_value=7).start()
Edward Lemur5b929a42019-10-21 17:57:39 +00003058 mock.patch('git_cl.auth.Authenticator',
Edward Lemurb4a587d2019-10-09 23:56:38 +00003059 return_value=AuthenticatorMock()).start()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003060 mock.patch('git_cl.Changelist._GetChangeDetail',
3061 return_value=self._CHANGE_DETAIL).start()
3062 mock.patch('git_cl._call_buildbucket',
3063 return_value = self._DEFAULT_RESPONSE).start()
3064 mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
Edward Lemur4c707a22019-09-24 21:13:43 +00003065 self.addCleanup(mock.patch.stopall)
3066
Edward Lemur4c707a22019-09-24 21:13:43 +00003067
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003068class CMDTryResultsTestCase(CMDTestCaseBase):
3069 _DEFAULT_REQUEST = {
3070 'predicate': {
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003071 "gerritChanges": [{
3072 "project": "depot_tools",
3073 "host": "chromium-review.googlesource.com",
3074 "patchset": 7,
3075 "change": 123456,
3076 }],
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003077 },
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003078 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
3079 ',builds.*.createTime,builds.*.tags'),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003080 }
3081
3082 def testNoJobs(self):
3083 git_cl._call_buildbucket.return_value = {}
3084
3085 self.assertEqual(0, git_cl.main(['try-results']))
3086 self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
3087 git_cl._call_buildbucket.assert_called_once_with(
3088 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3089 self._DEFAULT_REQUEST)
3090
3091 def testPrintToStdout(self):
3092 self.assertEqual(0, git_cl.main(['try-results']))
3093 self.assertEqual([
3094 'Successes:',
3095 ' bot_success https://ci.chromium.org/b/103',
3096 'Infra Failures:',
3097 ' bot_infra_failure https://ci.chromium.org/b/105',
3098 'Failures:',
3099 ' bot_failure https://ci.chromium.org/b/104',
3100 'Canceled:',
3101 ' bot_canceled ',
3102 'Started:',
3103 ' bot_started https://ci.chromium.org/b/102',
3104 'Scheduled:',
3105 ' bot_scheduled id=101',
3106 'Other:',
3107 ' bot_status_unspecified id=100',
3108 'Total: 7 tryjobs',
3109 ], sys.stdout.getvalue().splitlines())
3110 git_cl._call_buildbucket.assert_called_once_with(
3111 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3112 self._DEFAULT_REQUEST)
3113
3114 def testPrintToStdoutWithMasters(self):
3115 self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
3116 self.assertEqual([
3117 'Successes:',
3118 ' try bot_success https://ci.chromium.org/b/103',
3119 'Infra Failures:',
3120 ' try bot_infra_failure https://ci.chromium.org/b/105',
3121 'Failures:',
3122 ' try bot_failure https://ci.chromium.org/b/104',
3123 'Canceled:',
3124 ' try bot_canceled ',
3125 'Started:',
3126 ' try bot_started https://ci.chromium.org/b/102',
3127 'Scheduled:',
3128 ' try bot_scheduled id=101',
3129 'Other:',
3130 ' try bot_status_unspecified id=100',
3131 'Total: 7 tryjobs',
3132 ], sys.stdout.getvalue().splitlines())
3133 git_cl._call_buildbucket.assert_called_once_with(
3134 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3135 self._DEFAULT_REQUEST)
3136
3137 @mock.patch('git_cl.write_json')
3138 def testWriteToJson(self, mockJsonDump):
3139 self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
3140 git_cl._call_buildbucket.assert_called_once_with(
3141 mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
3142 self._DEFAULT_REQUEST)
3143 mockJsonDump.assert_called_once_with(
3144 'file.json', self._DEFAULT_RESPONSE['builds'])
3145
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003146 def test_filter_failed_for_one_simple(self):
3147 self.assertEqual({}, git_cl._filter_failed_for_retry([]))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003148 self.assertEqual({
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003149 'chromium/try': {
3150 'bot_failure': [],
3151 'bot_infra_failure': []
3152 },
3153 }, git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
3154
3155 def test_filter_failed_for_retry_many_builds(self):
3156
3157 def _build(name, created_sec, status, experimental=False):
3158 assert 0 <= created_sec < 100, created_sec
3159 b = {
3160 'id': 112112,
3161 'builder': {
3162 'project': 'chromium',
3163 'bucket': 'try',
3164 'builder': name,
3165 },
3166 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
3167 'status': status,
3168 'tags': [],
3169 }
3170 if experimental:
3171 b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
3172 return b
3173
3174 builds = [
3175 _build('flaky-last-green', 1, 'FAILURE'),
3176 _build('flaky-last-green', 2, 'SUCCESS'),
3177 _build('flaky', 1, 'SUCCESS'),
3178 _build('flaky', 2, 'FAILURE'),
3179 _build('running', 1, 'FAILED'),
3180 _build('running', 2, 'SCHEDULED'),
3181 _build('yep-still-running', 1, 'STARTED'),
3182 _build('yep-still-running', 2, 'FAILURE'),
3183 _build('cq-experimental', 1, 'SUCCESS', experimental=True),
3184 _build('cq-experimental', 2, 'FAILURE', experimental=True),
3185
3186 # Simulate experimental in CQ builder, which developer decided
3187 # to retry manually which resulted in 2nd build non-experimental.
3188 _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
3189 _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
3190 ]
3191 builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
3192 self.assertEqual({
3193 'chromium/try': {
3194 'flaky': [],
3195 'sometimes-experimental': []
3196 },
3197 }, git_cl._filter_failed_for_retry(builds))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003198
3199
3200class CMDTryTestCase(CMDTestCaseBase):
3201
3202 @mock.patch('git_cl.Changelist.SetCQState')
3203 @mock.patch('git_cl._get_bucket_map', return_value={})
3204 def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
3205 mockSetCQState.return_value = 0
Edward Lemur4c707a22019-09-24 21:13:43 +00003206 self.assertEqual(0, git_cl.main(['try']))
3207 git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
3208 self.assertEqual(
3209 sys.stdout.getvalue(),
3210 'Scheduling CQ dry run on: '
3211 'https://chromium-review.googlesource.com/123456\n')
3212
Edward Lemur4c707a22019-09-24 21:13:43 +00003213 @mock.patch('git_cl._call_buildbucket')
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003214 def testScheduleOnBuildbucket(self, mockCallBuildbucket):
Edward Lemur4c707a22019-09-24 21:13:43 +00003215 mockCallBuildbucket.return_value = {}
Edward Lemur4c707a22019-09-24 21:13:43 +00003216
3217 self.assertEqual(0, git_cl.main([
3218 'try', '-B', 'luci.chromium.try', '-b', 'win',
3219 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3220 self.assertIn(
3221 'Scheduling jobs on:\nBucket: luci.chromium.try',
3222 git_cl.sys.stdout.getvalue())
3223
3224 expected_request = {
3225 "requests": [{
3226 "scheduleBuild": {
3227 "requestId": "uuid4",
3228 "builder": {
3229 "project": "chromium",
3230 "builder": "win",
3231 "bucket": "try",
3232 },
3233 "gerritChanges": [{
3234 "project": "depot_tools",
3235 "host": "chromium-review.googlesource.com",
3236 "patchset": 7,
3237 "change": 123456,
3238 }],
3239 "properties": {
3240 "category": "git_cl_try",
3241 "json": [{"a": 1}, None],
3242 "key": "val",
3243 },
3244 "tags": [
3245 {"value": "win", "key": "builder"},
3246 {"value": "git_cl_try", "key": "user_agent"},
3247 ],
3248 },
3249 }],
3250 }
3251 mockCallBuildbucket.assert_called_with(
3252 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3253
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003254 def testScheduleOnBuildbucket_WrongBucket(self):
Edward Lemur4c707a22019-09-24 21:13:43 +00003255 self.assertEqual(0, git_cl.main([
3256 'try', '-B', 'not-a-bucket', '-b', 'win',
3257 '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
3258 self.assertIn(
3259 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
3260 git_cl.sys.stdout.getvalue())
3261
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003262 @mock.patch('git_cl._call_buildbucket')
3263 @mock.patch('git_cl.fetch_try_jobs')
3264 def testScheduleOnBuildbucketRetryFailed(
3265 self, mockFetchTryJobs, mockCallBuildbucket):
3266
3267 git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
3268 7: [],
3269 6: [{
3270 'id': 112112,
3271 'builder': {
3272 'project': 'chromium',
3273 'bucket': 'try',
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003274 'builder': 'linux',},
3275 'createTime': '2019-10-09T08:00:01.854286Z',
3276 'tags': [],
3277 'status': 'FAILURE',}],}[kw['patchset']]
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00003278 mockCallBuildbucket.return_value = {}
3279
3280 self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
3281 self.assertIn(
3282 'Scheduling jobs on:\nBucket: chromium/try',
3283 git_cl.sys.stdout.getvalue())
3284
3285 expected_request = {
3286 "requests": [{
3287 "scheduleBuild": {
3288 "requestId": "uuid4",
3289 "builder": {
3290 "project": "chromium",
3291 "bucket": "try",
3292 "builder": "linux",
3293 },
3294 "gerritChanges": [{
3295 "project": "depot_tools",
3296 "host": "chromium-review.googlesource.com",
3297 "patchset": 7,
3298 "change": 123456,
3299 }],
3300 "properties": {
3301 "category": "git_cl_try",
3302 },
3303 "tags": [
3304 {"value": "linux", "key": "builder"},
3305 {"value": "git_cl_try", "key": "user_agent"},
3306 {"value": "1", "key": "retry_failed"},
3307 ],
3308 },
3309 }],
3310 }
3311 mockCallBuildbucket.assert_called_with(
3312 mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
3313
Edward Lemur4c707a22019-09-24 21:13:43 +00003314 def test_parse_bucket(self):
3315 test_cases = [
3316 {
3317 'bucket': 'chromium/try',
3318 'result': ('chromium', 'try'),
3319 },
3320 {
3321 'bucket': 'luci.chromium.try',
3322 'result': ('chromium', 'try'),
3323 'has_warning': True,
3324 },
3325 {
3326 'bucket': 'skia.primary',
3327 'result': ('skia', 'skia.primary'),
3328 'has_warning': True,
3329 },
3330 {
3331 'bucket': 'not-a-bucket',
3332 'result': (None, None),
3333 },
3334 ]
3335
3336 for test_case in test_cases:
3337 git_cl.sys.stdout.truncate(0)
3338 self.assertEqual(
3339 test_case['result'], git_cl._parse_bucket(test_case['bucket']))
3340 if test_case.get('has_warning'):
Edward Lemur6215c792019-10-03 21:59:05 +00003341 expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
3342 test_case['result'])
3343 self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
Edward Lemur4c707a22019-09-24 21:13:43 +00003344
3345
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003346class CMDUploadTestCase(CMDTestCaseBase):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003347 def setUp(self):
3348 super(CMDUploadTestCase, self).setUp()
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003349 mock.patch('git_cl.fetch_try_jobs').start()
3350 mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
3351 mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
Anthony Polito46689b02019-11-15 20:56:41 +00003352 mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003353 self.addCleanup(mock.patch.stopall)
3354
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003355 def testUploadRetryFailed(self):
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003356 # This test mocks out the actual upload part, and just asserts that after
3357 # upload, if --retry-failed is added, then the tool will fetch try jobs
3358 # from the previous patchset and trigger the right builders on the latest
3359 # patchset.
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003360 git_cl.fetch_try_jobs.side_effect = [
3361 # Latest patchset: No builds.
3362 [],
3363 # Patchset before latest: Some builds.
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +00003364 [{
3365 'id': str(100 + idx),
3366 'builder': {
3367 'project': 'chromium',
3368 'bucket': 'try',
3369 'builder': 'bot_' + status.lower(),
3370 },
3371 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
3372 'tags': [],
3373 'status': status,
3374 } for idx, status in enumerate(self._STATUSES)],
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00003375 ]
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003376
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003377 self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003378 self.assertEqual([
Edward Lemur5b929a42019-10-21 17:57:39 +00003379 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
3380 mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
Edward Lemurbaaf6be2019-10-09 18:00:44 +00003381 ], git_cl.fetch_try_jobs.mock_calls)
3382 expected_buckets = {
3383 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
3384 }
3385 git_cl._trigger_try_jobs.assert_called_once_with(
Edward Lemur5b929a42019-10-21 17:57:39 +00003386 mock.ANY, expected_buckets, mock.ANY, 8)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00003387
Brian Sheedy59b06a82019-10-14 17:03:29 +00003388
3389class CMDFormatTestCase(TestCase):
3390
3391 def setUp(self):
3392 super(CMDFormatTestCase, self).setUp()
3393 self._top_dir = tempfile.mkdtemp()
3394
3395 def tearDown(self):
3396 shutil.rmtree(self._top_dir)
3397 super(CMDFormatTestCase, self).tearDown()
3398
3399 def _make_yapfignore(self, contents):
3400 with open(os.path.join(self._top_dir, '.yapfignore'), 'w') as yapfignore:
3401 yapfignore.write('\n'.join(contents))
3402
3403 def _make_files(self, file_dict):
Edward Lemur0db01f02019-11-12 22:01:51 +00003404 for directory, files in file_dict.items():
Brian Sheedy59b06a82019-10-14 17:03:29 +00003405 subdir = os.path.join(self._top_dir, directory)
3406 if not os.path.exists(subdir):
3407 os.makedirs(subdir)
3408 for f in files:
3409 with open(os.path.join(subdir, f), 'w'):
3410 pass
3411
3412 def testYapfignoreBasic(self):
3413 self._make_yapfignore(['test.py', '*/bar.py'])
3414 self._make_files({
3415 '.': ['test.py', 'bar.py'],
3416 'foo': ['bar.py'],
3417 })
3418 self.assertEqual(
3419 set(['test.py', 'foo/bar.py']),
3420 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3421
3422 def testYapfignoreMissingYapfignore(self):
3423 self.assertEqual(set(), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3424
3425 def testYapfignoreMissingFile(self):
3426 self._make_yapfignore(['test.py', 'test2.py', 'test3.py'])
3427 self._make_files({
3428 '.': ['test.py', 'test3.py'],
3429 })
3430 self.assertEqual(
3431 set(['test.py', 'test3.py']),
3432 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3433
3434 def testYapfignoreComments(self):
3435 self._make_yapfignore(['test.py', '#test2.py'])
3436 self._make_files({
3437 '.': ['test.py', 'test2.py'],
3438 })
3439 self.assertEqual(
3440 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3441
3442 def testYapfignoreBlankLines(self):
3443 self._make_yapfignore(['test.py', '', '', 'test2.py'])
3444 self._make_files({'.': ['test.py', 'test2.py']})
3445 self.assertEqual(
3446 set(['test.py', 'test2.py']),
3447 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3448
3449 def testYapfignoreWhitespace(self):
3450 self._make_yapfignore([' test.py '])
3451 self._make_files({'.': ['test.py']})
3452 self.assertEqual(
3453 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3454
3455 def testYapfignoreMultiWildcard(self):
3456 self._make_yapfignore(['*es*.py'])
3457 self._make_files({
3458 '.': ['test.py', 'test2.py'],
3459 })
3460 self.assertEqual(
3461 set(['test.py', 'test2.py']),
3462 git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3463
3464 def testYapfignoreRestoresDirectory(self):
3465 self._make_yapfignore(['test.py'])
3466 self._make_files({
3467 '.': ['test.py'],
3468 })
3469 old_cwd = os.getcwd()
3470 self.assertEqual(
3471 set(['test.py']), git_cl._GetYapfIgnoreFilepaths(self._top_dir))
3472 self.assertEqual(old_cwd, os.getcwd())
3473
3474
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003475if __name__ == '__main__':
Andrii Shyshkalov18df0cd2017-01-25 15:22:20 +01003476 logging.basicConfig(
3477 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
maruel@chromium.orgddd59412011-11-30 14:20:38 +00003478 unittest.main()