git_cl_test.py 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Unit tests for git_cl.py."""
  6. import datetime
  7. import json
  8. import logging
  9. import os
  10. import StringIO
  11. import sys
  12. import tempfile
  13. import unittest
  14. import urlparse
  15. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  16. from testing_support.auto_stub import TestCase
  17. from third_party import mock
  18. import metrics
  19. # We have to disable monitoring before importing git_cl.
  20. metrics.DISABLE_METRICS_COLLECTION = True
  21. import gerrit_util
  22. import git_cl
  23. import git_common
  24. import git_footers
  25. import subprocess2
  26. def callError(code=1, cmd='', cwd='', stdout='', stderr=''):
  27. return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
  28. def _constantFn(return_value):
  29. def f(*args, **kwargs):
  30. return return_value
  31. return f
  32. CERR1 = callError(1)
  33. def MakeNamedTemporaryFileMock(expected_content):
  34. class NamedTemporaryFileMock(object):
  35. def __init__(self, *args, **kwargs):
  36. self.name = '/tmp/named'
  37. self.expected_content = expected_content
  38. def __enter__(self):
  39. return self
  40. def __exit__(self, _type, _value, _tb):
  41. pass
  42. def write(self, content):
  43. if self.expected_content:
  44. assert content == self.expected_content
  45. def close(self):
  46. pass
  47. return NamedTemporaryFileMock
  48. class ChangelistMock(object):
  49. # A class variable so we can access it when we don't have access to the
  50. # instance that's being set.
  51. desc = ''
  52. def __init__(self, **kwargs):
  53. pass
  54. def GetIssue(self):
  55. return 1
  56. def GetDescription(self, force=False):
  57. return ChangelistMock.desc
  58. def UpdateDescription(self, desc, force=False):
  59. ChangelistMock.desc = desc
  60. class PresubmitMock(object):
  61. def __init__(self, *args, **kwargs):
  62. self.reviewers = []
  63. self.more_cc = ['chromium-reviews+test-more-cc@chromium.org']
  64. @staticmethod
  65. def should_continue():
  66. return True
  67. class WatchlistsMock(object):
  68. def __init__(self, _):
  69. pass
  70. @staticmethod
  71. def GetWatchersForPaths(_):
  72. return ['joe@example.com']
  73. class CodereviewSettingsFileMock(object):
  74. def __init__(self):
  75. pass
  76. # pylint: disable=no-self-use
  77. def read(self):
  78. return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
  79. 'GERRIT_HOST: True\n')
  80. class AuthenticatorMock(object):
  81. def __init__(self, *_args):
  82. pass
  83. def has_cached_credentials(self):
  84. return True
  85. def authorize(self, http):
  86. return http
  87. def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
  88. """Use to mock Gerrit/Git credentials from ~/.netrc or ~/.gitcookies.
  89. Usage:
  90. >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
  91. CookiesAuthenticatorMockFactory({'host': ('user', _, 'pass')})
  92. OR
  93. >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
  94. CookiesAuthenticatorMockFactory(
  95. same_auth=('user', '', 'pass'))
  96. """
  97. class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
  98. def __init__(self): # pylint: disable=super-init-not-called
  99. # Intentionally not calling super() because it reads actual cookie files.
  100. pass
  101. @classmethod
  102. def get_gitcookies_path(cls):
  103. return '~/.gitcookies'
  104. @classmethod
  105. def get_netrc_path(cls):
  106. return '~/.netrc'
  107. def _get_auth_for_host(self, host):
  108. if same_auth:
  109. return same_auth
  110. return (hosts_with_creds or {}).get(host)
  111. return CookiesAuthenticatorMock
  112. class MockChangelistWithBranchAndIssue():
  113. def __init__(self, branch, issue):
  114. self.branch = branch
  115. self.issue = issue
  116. def GetBranch(self):
  117. return self.branch
  118. def GetIssue(self):
  119. return self.issue
  120. class SystemExitMock(Exception):
  121. pass
  122. class TestGitClBasic(unittest.TestCase):
  123. def test_get_description(self):
  124. cl = git_cl.Changelist(issue=1, codereview_host='host')
  125. cl.description = 'x'
  126. cl.has_description = True
  127. cl.FetchDescription = lambda *a, **kw: 'y'
  128. self.assertEquals(cl.GetDescription(), 'x')
  129. self.assertEquals(cl.GetDescription(force=True), 'y')
  130. self.assertEquals(cl.GetDescription(), 'y')
  131. def test_description_footers(self):
  132. cl = git_cl.Changelist(issue=1, codereview_host='host')
  133. cl.description = '\n'.join([
  134. 'This is some message',
  135. '',
  136. 'It has some lines',
  137. 'and, also',
  138. '',
  139. 'Some: Really',
  140. 'Awesome: Footers',
  141. ])
  142. cl.has_description = True
  143. cl.UpdateDescriptionRemote = lambda *a, **kw: 'y'
  144. msg, footers = cl.GetDescriptionFooters()
  145. self.assertEquals(
  146. msg, ['This is some message', '', 'It has some lines', 'and, also'])
  147. self.assertEquals(footers, [('Some', 'Really'), ('Awesome', 'Footers')])
  148. msg.append('wut')
  149. footers.append(('gnarly-dude', 'beans'))
  150. cl.UpdateDescriptionFooters(msg, footers)
  151. self.assertEquals(cl.GetDescription().splitlines(), [
  152. 'This is some message',
  153. '',
  154. 'It has some lines',
  155. 'and, also',
  156. 'wut'
  157. '',
  158. 'Some: Really',
  159. 'Awesome: Footers',
  160. 'Gnarly-Dude: beans',
  161. ])
  162. def test_set_preserve_tryjobs(self):
  163. d = git_cl.ChangeDescription('Simple.')
  164. d.set_preserve_tryjobs()
  165. self.assertEqual(d.description.splitlines(), [
  166. 'Simple.',
  167. '',
  168. 'Cq-Do-Not-Cancel-Tryjobs: true',
  169. ])
  170. before = d.description
  171. d.set_preserve_tryjobs()
  172. self.assertEqual(before, d.description)
  173. d = git_cl.ChangeDescription('\n'.join([
  174. 'One is enough',
  175. '',
  176. 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
  177. 'Change-Id: Ideadbeef',
  178. ]))
  179. d.set_preserve_tryjobs()
  180. self.assertEqual(d.description.splitlines(), [
  181. 'One is enough',
  182. '',
  183. 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
  184. 'Change-Id: Ideadbeef',
  185. 'Cq-Do-Not-Cancel-Tryjobs: true',
  186. ])
  187. def test_get_bug_line_values(self):
  188. f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
  189. self.assertEqual(f('', ''), [])
  190. self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
  191. self.assertEqual(f('v8', '456'), ['v8:456'])
  192. self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
  193. # Not nice, but not worth carying.
  194. self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
  195. ['v8:456', 'chromium:123', 'v8:123'])
  196. def _test_git_number(self, parent_msg, dest_ref, child_msg,
  197. parent_hash='parenthash'):
  198. desc = git_cl.ChangeDescription(child_msg)
  199. desc.update_with_git_number_footers(parent_hash, parent_msg, dest_ref)
  200. return desc.description
  201. def assertEqualByLine(self, actual, expected):
  202. self.assertEqual(actual.splitlines(), expected.splitlines())
  203. def test_git_number_bad_parent(self):
  204. with self.assertRaises(ValueError):
  205. self._test_git_number('Parent', 'refs/heads/master', 'Child')
  206. def test_git_number_bad_parent_footer(self):
  207. with self.assertRaises(AssertionError):
  208. self._test_git_number(
  209. 'Parent\n'
  210. '\n'
  211. 'Cr-Commit-Position: wrong',
  212. 'refs/heads/master', 'Child')
  213. def test_git_number_bad_lineage_ignored(self):
  214. actual = self._test_git_number(
  215. 'Parent\n'
  216. '\n'
  217. 'Cr-Commit-Position: refs/heads/master@{#1}\n'
  218. 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}',
  219. 'refs/heads/master', 'Child')
  220. self.assertEqualByLine(
  221. actual,
  222. 'Child\n'
  223. '\n'
  224. 'Cr-Commit-Position: refs/heads/master@{#2}\n'
  225. 'Cr-Branched-From: mustBeReal40CharHash-branch@{#pos}')
  226. def test_git_number_same_branch(self):
  227. actual = self._test_git_number(
  228. 'Parent\n'
  229. '\n'
  230. 'Cr-Commit-Position: refs/heads/master@{#12}',
  231. dest_ref='refs/heads/master',
  232. child_msg='Child')
  233. self.assertEqualByLine(
  234. actual,
  235. 'Child\n'
  236. '\n'
  237. 'Cr-Commit-Position: refs/heads/master@{#13}')
  238. def test_git_number_same_branch_mixed_footers(self):
  239. actual = self._test_git_number(
  240. 'Parent\n'
  241. '\n'
  242. 'Cr-Commit-Position: refs/heads/master@{#12}',
  243. dest_ref='refs/heads/master',
  244. child_msg='Child\n'
  245. '\n'
  246. 'Broken-by: design\n'
  247. 'BUG=123')
  248. self.assertEqualByLine(
  249. actual,
  250. 'Child\n'
  251. '\n'
  252. 'Broken-by: design\n'
  253. 'BUG=123\n'
  254. 'Cr-Commit-Position: refs/heads/master@{#13}')
  255. def test_git_number_same_branch_with_originals(self):
  256. actual = self._test_git_number(
  257. 'Parent\n'
  258. '\n'
  259. 'Cr-Commit-Position: refs/heads/master@{#12}',
  260. dest_ref='refs/heads/master',
  261. child_msg='Child\n'
  262. '\n'
  263. 'Some users are smart and insert their own footers\n'
  264. '\n'
  265. 'Cr-Whatever: value\n'
  266. 'Cr-Commit-Position: refs/copy/paste@{#22}')
  267. self.assertEqualByLine(
  268. actual,
  269. 'Child\n'
  270. '\n'
  271. 'Some users are smart and insert their own footers\n'
  272. '\n'
  273. 'Cr-Original-Whatever: value\n'
  274. 'Cr-Original-Commit-Position: refs/copy/paste@{#22}\n'
  275. 'Cr-Commit-Position: refs/heads/master@{#13}')
  276. def test_git_number_new_branch(self):
  277. actual = self._test_git_number(
  278. 'Parent\n'
  279. '\n'
  280. 'Cr-Commit-Position: refs/heads/master@{#12}',
  281. dest_ref='refs/heads/branch',
  282. child_msg='Child')
  283. self.assertEqualByLine(
  284. actual,
  285. 'Child\n'
  286. '\n'
  287. 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
  288. 'Cr-Branched-From: parenthash-refs/heads/master@{#12}')
  289. def test_git_number_lineage(self):
  290. actual = self._test_git_number(
  291. 'Parent\n'
  292. '\n'
  293. 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
  294. 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
  295. dest_ref='refs/heads/branch',
  296. child_msg='Child')
  297. self.assertEqualByLine(
  298. actual,
  299. 'Child\n'
  300. '\n'
  301. 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
  302. 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
  303. def test_git_number_moooooooore_lineage(self):
  304. actual = self._test_git_number(
  305. 'Parent\n'
  306. '\n'
  307. 'Cr-Commit-Position: refs/heads/branch@{#5}\n'
  308. 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
  309. dest_ref='refs/heads/mooore',
  310. child_msg='Child')
  311. self.assertEqualByLine(
  312. actual,
  313. 'Child\n'
  314. '\n'
  315. 'Cr-Commit-Position: refs/heads/mooore@{#1}\n'
  316. 'Cr-Branched-From: parenthash-refs/heads/branch@{#5}\n'
  317. 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
  318. def test_git_number_ever_moooooooore_lineage(self):
  319. self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
  320. actual = self._test_git_number(
  321. 'CQ commit on fresh new branch + numbering.\n'
  322. '\n'
  323. 'NOTRY=True\n'
  324. 'NOPRESUBMIT=True\n'
  325. 'BUG=\n'
  326. '\n'
  327. 'Review-Url: https://codereview.chromium.org/2577703003\n'
  328. 'Cr-Commit-Position: refs/heads/gnumb-test/br@{#1}\n'
  329. 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
  330. 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}',
  331. dest_ref='refs/heads/gnumb-test/cl',
  332. child_msg='git cl on fresh new branch + numbering.\n'
  333. '\n'
  334. 'Review-Url: https://codereview.chromium.org/2575043003 .\n')
  335. self.assertEqualByLine(
  336. actual,
  337. 'git cl on fresh new branch + numbering.\n'
  338. '\n'
  339. 'Review-Url: https://codereview.chromium.org/2575043003 .\n'
  340. 'Cr-Commit-Position: refs/heads/gnumb-test/cl@{#1}\n'
  341. 'Cr-Branched-From: parenthash-refs/heads/gnumb-test/br@{#1}\n'
  342. 'Cr-Branched-From: 0749ff9edc-refs/heads/gnumb-test/cq@{#4}\n'
  343. 'Cr-Branched-From: 5c49df2da6-refs/heads/master@{#41618}')
  344. def test_git_number_cherry_pick(self):
  345. actual = self._test_git_number(
  346. 'Parent\n'
  347. '\n'
  348. 'Cr-Commit-Position: refs/heads/branch@{#1}\n'
  349. 'Cr-Branched-From: somehash-refs/heads/master@{#12}',
  350. dest_ref='refs/heads/branch',
  351. child_msg='Child, which is cherry-pick from master\n'
  352. '\n'
  353. 'Cr-Commit-Position: refs/heads/master@{#100}\n'
  354. '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)')
  355. self.assertEqualByLine(
  356. actual,
  357. 'Child, which is cherry-pick from master\n'
  358. '\n'
  359. '(cherry picked from commit deadbeef12345678deadbeef12345678deadbeef)\n'
  360. '\n'
  361. 'Cr-Original-Commit-Position: refs/heads/master@{#100}\n'
  362. 'Cr-Commit-Position: refs/heads/branch@{#2}\n'
  363. 'Cr-Branched-From: somehash-refs/heads/master@{#12}')
  364. def test_gerrit_mirror_hack(self):
  365. cr = 'chromium-review.googlesource.com'
  366. url0 = 'https://%s/a/changes/x?a=b' % cr
  367. origMirrors = git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES
  368. try:
  369. git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = ['us1', 'us2']
  370. url1 = git_cl.gerrit_util._UseGerritMirror(url0, cr)
  371. url2 = git_cl.gerrit_util._UseGerritMirror(url1, cr)
  372. url3 = git_cl.gerrit_util._UseGerritMirror(url2, cr)
  373. self.assertNotEqual(url1, url2)
  374. self.assertEqual(sorted((url1, url2)), [
  375. 'https://us1-mirror-chromium-review.googlesource.com/a/changes/x?a=b',
  376. 'https://us2-mirror-chromium-review.googlesource.com/a/changes/x?a=b'])
  377. self.assertEqual(url1, url3)
  378. finally:
  379. git_cl.gerrit_util._GERRIT_MIRROR_PREFIXES = origMirrors
  380. def test_valid_accounts(self):
  381. mock_per_account = {
  382. 'u1': None, # 404, doesn't exist.
  383. 'u2': {
  384. '_account_id': 123124,
  385. 'avatars': [],
  386. 'email': 'u2@example.com',
  387. 'name': 'User Number 2',
  388. 'status': 'OOO',
  389. },
  390. 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
  391. }
  392. def GetAccountDetailsMock(_, account):
  393. # Poor-man's mock library's side_effect.
  394. v = mock_per_account.pop(account)
  395. if isinstance(v, Exception):
  396. raise v
  397. return v
  398. original = git_cl.gerrit_util.GetAccountDetails
  399. try:
  400. git_cl.gerrit_util.GetAccountDetails = GetAccountDetailsMock
  401. actual = git_cl.gerrit_util.ValidAccounts(
  402. 'host', ['u1', 'u2', 'u3'], max_threads=1)
  403. finally:
  404. git_cl.gerrit_util.GetAccountDetails = original
  405. self.assertEqual(actual, {
  406. 'u2': {
  407. '_account_id': 123124,
  408. 'avatars': [],
  409. 'email': 'u2@example.com',
  410. 'name': 'User Number 2',
  411. 'status': 'OOO',
  412. },
  413. })
  414. class TestParseIssueURL(unittest.TestCase):
  415. def _validate(self, parsed, issue=None, patchset=None, hostname=None,
  416. fail=False):
  417. self.assertIsNotNone(parsed)
  418. if fail:
  419. self.assertFalse(parsed.valid)
  420. return
  421. self.assertTrue(parsed.valid)
  422. self.assertEqual(parsed.issue, issue)
  423. self.assertEqual(parsed.patchset, patchset)
  424. self.assertEqual(parsed.hostname, hostname)
  425. def test_ParseIssueNumberArgument(self):
  426. def test(arg, *args, **kwargs):
  427. self._validate(git_cl.ParseIssueNumberArgument(arg), *args, **kwargs)
  428. test('123', 123)
  429. test('', fail=True)
  430. test('abc', fail=True)
  431. test('123/1', fail=True)
  432. test('123a', fail=True)
  433. test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
  434. test('https://codereview.source.com/123',
  435. 123, None, 'codereview.source.com')
  436. test('http://chrome-review.source.com/c/123',
  437. 123, None, 'chrome-review.source.com')
  438. test('https://chrome-review.source.com/c/123/',
  439. 123, None, 'chrome-review.source.com')
  440. test('https://chrome-review.source.com/c/123/4',
  441. 123, 4, 'chrome-review.source.com')
  442. test('https://chrome-review.source.com/#/c/123/4',
  443. 123, 4, 'chrome-review.source.com')
  444. test('https://chrome-review.source.com/c/123/4',
  445. 123, 4, 'chrome-review.source.com')
  446. test('https://chrome-review.source.com/123',
  447. 123, None, 'chrome-review.source.com')
  448. test('https://chrome-review.source.com/123/4',
  449. 123, 4, 'chrome-review.source.com')
  450. test('https://chrome-review.source.com/bad/123/4', fail=True)
  451. test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
  452. test('https://chrome-review.source.com/c/abc/', fail=True)
  453. test('ssh://chrome-review.source.com/c/123/1/', fail=True)
  454. class GitCookiesCheckerTest(TestCase):
  455. def setUp(self):
  456. super(GitCookiesCheckerTest, self).setUp()
  457. self.c = git_cl._GitCookiesChecker()
  458. self.c._all_hosts = []
  459. def mock_hosts_creds(self, subhost_identity_pairs):
  460. def ensure_googlesource(h):
  461. if not h.endswith(self.c._GOOGLESOURCE):
  462. assert not h.endswith('.')
  463. return h + '.' + self.c._GOOGLESOURCE
  464. return h
  465. self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
  466. for h, i in subhost_identity_pairs]
  467. def test_identity_parsing(self):
  468. self.assertEqual(self.c._parse_identity('ldap.google.com'),
  469. ('ldap', 'google.com'))
  470. self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
  471. ('ldap', 'example.com'))
  472. # Specical case because we know there are no subdomains in chromium.org.
  473. self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
  474. ('note.period', 'chromium.org'))
  475. # Pathological: ".period." can be either username OR domain, more likely
  476. # domain.
  477. self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
  478. ('note', 'period.example.com'))
  479. def test_analysis_nothing(self):
  480. self.c._all_hosts = []
  481. self.assertFalse(self.c.has_generic_host())
  482. self.assertEqual(set(), self.c.get_conflicting_hosts())
  483. self.assertEqual(set(), self.c.get_duplicated_hosts())
  484. self.assertEqual(set(), self.c.get_partially_configured_hosts())
  485. self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
  486. def test_analysis(self):
  487. self.mock_hosts_creds([
  488. ('.googlesource.com', 'git-example.chromium.org'),
  489. ('chromium', 'git-example.google.com'),
  490. ('chromium-review', 'git-example.google.com'),
  491. ('chrome-internal', 'git-example.chromium.org'),
  492. ('chrome-internal-review', 'git-example.chromium.org'),
  493. ('conflict', 'git-example.google.com'),
  494. ('conflict-review', 'git-example.chromium.org'),
  495. ('dup', 'git-example.google.com'),
  496. ('dup', 'git-example.google.com'),
  497. ('dup-review', 'git-example.google.com'),
  498. ('partial', 'git-example.google.com'),
  499. ('gpartial-review', 'git-example.google.com'),
  500. ])
  501. self.assertTrue(self.c.has_generic_host())
  502. self.assertEqual(set(['conflict.googlesource.com']),
  503. self.c.get_conflicting_hosts())
  504. self.assertEqual(set(['dup.googlesource.com']),
  505. self.c.get_duplicated_hosts())
  506. self.assertEqual(set(['partial.googlesource.com',
  507. 'gpartial-review.googlesource.com']),
  508. self.c.get_partially_configured_hosts())
  509. self.assertEqual(set(['chromium.googlesource.com',
  510. 'chrome-internal.googlesource.com']),
  511. self.c.get_hosts_with_wrong_identities())
  512. def test_report_no_problems(self):
  513. self.test_analysis_nothing()
  514. self.mock(sys, 'stdout', StringIO.StringIO())
  515. self.assertFalse(self.c.find_and_report_problems())
  516. self.assertEqual(sys.stdout.getvalue(), '')
  517. def test_report(self):
  518. self.test_analysis()
  519. self.mock(sys, 'stdout', StringIO.StringIO())
  520. self.mock(git_cl.gerrit_util.CookiesAuthenticator, 'get_gitcookies_path',
  521. classmethod(lambda _: '~/.gitcookies'))
  522. self.assertTrue(self.c.find_and_report_problems())
  523. with open(os.path.join(os.path.dirname(__file__),
  524. 'git_cl_creds_check_report.txt')) as f:
  525. expected = f.read()
  526. def by_line(text):
  527. return [l.rstrip() for l in text.rstrip().splitlines()]
  528. self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
  529. self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
  530. class TestGitCl(TestCase):
  531. def setUp(self):
  532. super(TestGitCl, self).setUp()
  533. self.calls = []
  534. self._calls_done = []
  535. self.mock(git_cl, 'time_time',
  536. lambda: self._mocked_call('time.time'))
  537. self.mock(git_cl.metrics.collector, 'add_repeated',
  538. lambda *a: self._mocked_call('add_repeated', *a))
  539. self.mock(subprocess2, 'call', self._mocked_call)
  540. self.mock(subprocess2, 'check_call', self._mocked_call)
  541. self.mock(subprocess2, 'check_output', self._mocked_call)
  542. self.mock(subprocess2, 'communicate',
  543. lambda *a, **kw: ([self._mocked_call(*a, **kw), ''], 0))
  544. self.mock(git_cl.gclient_utils, 'CheckCallAndFilter', self._mocked_call)
  545. self.mock(git_common, 'is_dirty_git_tree', lambda x: False)
  546. self.mock(git_common, 'get_or_create_merge_base',
  547. lambda *a: (
  548. self._mocked_call(['get_or_create_merge_base'] + list(a))))
  549. self.mock(git_cl, 'BranchExists', lambda _: True)
  550. self.mock(git_cl, 'FindCodereviewSettingsFile', lambda: '')
  551. self.mock(git_cl, 'SaveDescriptionBackup', lambda _:
  552. self._mocked_call('SaveDescriptionBackup'))
  553. self.mock(git_cl, 'ask_for_data', lambda *a, **k: self._mocked_call(
  554. *(['ask_for_data'] + list(a)), **k))
  555. self.mock(git_cl, 'write_json', lambda path, contents:
  556. self._mocked_call('write_json', path, contents))
  557. self.mock(git_cl.presubmit_support, 'DoPresubmitChecks', PresubmitMock)
  558. self.mock(git_cl.watchlists, 'Watchlists', WatchlistsMock)
  559. self.mock(git_cl.auth, 'get_authenticator', AuthenticatorMock)
  560. self.mock(git_cl.gerrit_util, 'GetChangeDetail',
  561. lambda *args, **kwargs: self._mocked_call(
  562. 'GetChangeDetail', *args, **kwargs))
  563. self.mock(git_cl.gerrit_util, 'GetChangeComments',
  564. lambda *args, **kwargs: self._mocked_call(
  565. 'GetChangeComments', *args, **kwargs))
  566. self.mock(git_cl.gerrit_util, 'GetChangeRobotComments',
  567. lambda *args, **kwargs: self._mocked_call(
  568. 'GetChangeRobotComments', *args, **kwargs))
  569. self.mock(git_cl.gerrit_util, 'AddReviewers',
  570. lambda h, i, reviewers, ccs, notify: self._mocked_call(
  571. 'AddReviewers', h, i, reviewers, ccs, notify))
  572. self.mock(git_cl.gerrit_util, 'SetReview',
  573. lambda h, i, msg=None, labels=None, notify=None:
  574. self._mocked_call('SetReview', h, i, msg, labels, notify))
  575. self.mock(git_cl.gerrit_util.LuciContextAuthenticator, 'is_luci',
  576. staticmethod(lambda: False))
  577. self.mock(git_cl.gerrit_util.GceAuthenticator, 'is_gce',
  578. classmethod(lambda _: False))
  579. self.mock(git_cl.gerrit_util, 'ValidAccounts',
  580. lambda host, accounts:
  581. self._mocked_call('ValidAccounts', host, accounts))
  582. self.mock(git_cl, 'DieWithError',
  583. lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
  584. # It's important to reset settings to not have inter-tests interference.
  585. git_cl.settings = None
  586. def tearDown(self):
  587. try:
  588. self.assertEquals([], self.calls)
  589. except AssertionError:
  590. if not self.has_failed():
  591. raise
  592. # Sadly, has_failed() returns True if this OR any other tests before this
  593. # one have failed.
  594. git_cl.logging.error(
  595. '!!!!!! IF YOU SEE THIS, READ BELOW, IT WILL SAVE YOUR TIME !!!!!\n'
  596. 'There are un-consumed self.calls after this test has finished.\n'
  597. 'If you don\'t know which test this is, run:\n'
  598. ' tests/git_cl_tests.py -v\n'
  599. 'If you are already running only this test, then **first** fix the '
  600. 'problem whose exception is emitted below by unittest runner.\n'
  601. 'Else, to be sure what\'s going on, run this test **alone** with \n'
  602. ' tests/git_cl_tests.py TestGitCl.<name>\n'
  603. 'and follow instructions above.\n' +
  604. '=' * 80)
  605. finally:
  606. super(TestGitCl, self).tearDown()
  607. def _mocked_call(self, *args, **_kwargs):
  608. self.assertTrue(
  609. self.calls,
  610. '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
  611. top = self.calls.pop(0)
  612. expected_args, result = top
  613. # Also logs otherwise it could get caught in a try/finally and be hard to
  614. # diagnose.
  615. if expected_args != args:
  616. N = 5
  617. prior_calls = '\n '.join(
  618. '@%d: %r' % (len(self._calls_done) - N + i, c[0])
  619. for i, c in enumerate(self._calls_done[-N:]))
  620. following_calls = '\n '.join(
  621. '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
  622. for i, c in enumerate(self.calls[:N]))
  623. extended_msg = (
  624. 'A few prior calls:\n %s\n\n'
  625. 'This (expected):\n @%d: %r\n'
  626. 'This (actual):\n @%d: %r\n\n'
  627. 'A few following expected calls:\n %s' %
  628. (prior_calls, len(self._calls_done), expected_args,
  629. len(self._calls_done), args, following_calls))
  630. git_cl.logging.error(extended_msg)
  631. self.fail('@%d\n'
  632. ' Expected: %r\n'
  633. ' Actual: %r' % (
  634. len(self._calls_done), expected_args, args))
  635. self._calls_done.append(top)
  636. if isinstance(result, Exception):
  637. raise result
  638. return result
  639. def test_ask_for_explicit_yes_true(self):
  640. self.calls = [
  641. (('ask_for_data', 'prompt [Yes/No]: '), 'blah'),
  642. (('ask_for_data', 'Please, type yes or no: '), 'ye'),
  643. ]
  644. self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
  645. def test_LoadCodereviewSettingsFromFile_gerrit(self):
  646. codereview_file = StringIO.StringIO('GERRIT_HOST: true')
  647. self.calls = [
  648. ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
  649. ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
  650. ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
  651. ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
  652. ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
  653. ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
  654. CERR1),
  655. ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
  656. CERR1),
  657. ((['git', 'config', 'gerrit.host', 'true'],), ''),
  658. ]
  659. self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
  660. @classmethod
  661. def _is_gerrit_calls(cls, gerrit=False):
  662. return [((['git', 'config', 'rietveld.autoupdate'],), ''),
  663. ((['git', 'config', 'gerrit.host'],), 'True' if gerrit else '')]
  664. @classmethod
  665. def _git_post_upload_calls(cls):
  666. return [
  667. ((['git', 'rev-parse', 'HEAD'],), 'hash'),
  668. ((['git', 'symbolic-ref', 'HEAD'],), 'hash'),
  669. ((['git',
  670. 'config', 'branch.hash.last-upload-hash', 'hash'],), ''),
  671. ((['git', 'config', 'rietveld.run-post-upload-hook'],), ''),
  672. ]
  673. @staticmethod
  674. def _git_sanity_checks(diff_base, working_branch, get_remote_branch=True):
  675. fake_ancestor = 'fake_ancestor'
  676. fake_cl = 'fake_cl_for_patch'
  677. return [
  678. ((['git',
  679. 'rev-parse', '--verify', diff_base],), fake_ancestor),
  680. ((['git',
  681. 'merge-base', fake_ancestor, 'HEAD'],), fake_ancestor),
  682. ((['git',
  683. 'rev-list', '^' + fake_ancestor, 'HEAD'],), fake_cl),
  684. # Mock a config miss (error code 1)
  685. ((['git',
  686. 'config', 'gitcl.remotebranch'],), CERR1),
  687. ] + ([
  688. # Call to GetRemoteBranch()
  689. ((['git',
  690. 'config', 'branch.%s.merge' % working_branch],),
  691. 'refs/heads/master'),
  692. ((['git',
  693. 'config', 'branch.%s.remote' % working_branch],), 'origin'),
  694. ] if get_remote_branch else []) + [
  695. ((['git', 'rev-list', '^' + fake_ancestor,
  696. 'refs/remotes/origin/master'],), ''),
  697. ]
  698. @classmethod
  699. def _gerrit_ensure_auth_calls(
  700. cls, issue=None, skip_auth_check=False, short_hostname='chromium',
  701. custom_cl_base=None):
  702. cmd = ['git', 'config', '--bool', 'gerrit.skip-ensure-authenticated']
  703. if skip_auth_check:
  704. return [((cmd, ), 'true')]
  705. calls = [((cmd, ), CERR1)]
  706. if custom_cl_base:
  707. calls += [
  708. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  709. ]
  710. calls.extend([
  711. ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
  712. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  713. ((['git', 'config', 'remote.origin.url'],),
  714. 'https://%s.googlesource.com/my/repo' % short_hostname),
  715. ])
  716. calls += [
  717. ((['git', 'config', 'branch.master.gerritissue'],),
  718. CERR1 if issue is None else str(issue)),
  719. ]
  720. if issue:
  721. calls.extend([
  722. ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
  723. ])
  724. return calls
  725. @classmethod
  726. def _gerrit_base_calls(cls, issue=None, fetched_description=None,
  727. fetched_status=None, other_cl_owner=None,
  728. custom_cl_base=None, short_hostname='chromium',
  729. change_id=None):
  730. calls = cls._is_gerrit_calls(True)
  731. if not custom_cl_base:
  732. calls += [
  733. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  734. ]
  735. if custom_cl_base:
  736. ancestor_revision = custom_cl_base
  737. else:
  738. # Determine ancestor_revision to be merge base.
  739. ancestor_revision = 'fake_ancestor_sha'
  740. calls += [
  741. ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
  742. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  743. ((['get_or_create_merge_base', 'master',
  744. 'refs/remotes/origin/master'],), ancestor_revision),
  745. ]
  746. # Calls to verify branch point is ancestor
  747. calls += cls._gerrit_ensure_auth_calls(
  748. issue=issue, short_hostname=short_hostname,
  749. custom_cl_base=custom_cl_base)
  750. if issue:
  751. calls += [
  752. (('GetChangeDetail', '%s-review.googlesource.com' % short_hostname,
  753. 'my%2Frepo~123456',
  754. ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']
  755. ),
  756. {
  757. 'owner': {'email': (other_cl_owner or 'owner@example.com')},
  758. 'change_id': (change_id or '123456789'),
  759. 'current_revision': 'sha1_of_current_revision',
  760. 'revisions': {'sha1_of_current_revision': {
  761. 'commit': {'message': fetched_description},
  762. }},
  763. 'status': fetched_status or 'NEW',
  764. }),
  765. ]
  766. if fetched_status == 'ABANDONED':
  767. calls += [
  768. (('DieWithError', 'Change https://%s-review.googlesource.com/'
  769. '123456 has been abandoned, new uploads are not '
  770. 'allowed' % short_hostname), SystemExitMock()),
  771. ]
  772. return calls
  773. if other_cl_owner:
  774. calls += [
  775. (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
  776. ]
  777. calls += cls._git_sanity_checks(ancestor_revision, 'master',
  778. get_remote_branch=False)
  779. calls += [
  780. ((['git', 'rev-parse', '--show-cdup'],), ''),
  781. ((['git', 'rev-parse', 'HEAD'],), '12345'),
  782. ((['git', '-c', 'core.quotePath=false', 'diff', '--name-status',
  783. '--no-renames', '-r', ancestor_revision + '...', '.'],),
  784. 'M\t.gitignore\n'),
  785. ((['git', 'config', 'branch.master.gerritpatchset'],), CERR1),
  786. ]
  787. if not issue:
  788. calls += [
  789. ((['git', 'log', '--pretty=format:%s%n%n%b',
  790. ancestor_revision + '...'],),
  791. 'foo'),
  792. ]
  793. calls += [
  794. ((['git', 'config', 'user.email'],), 'me@example.com'),
  795. (('time.time',), 1000,),
  796. (('time.time',), 3000,),
  797. (('add_repeated', 'sub_commands', {
  798. 'execution_time': 2000,
  799. 'command': 'presubmit',
  800. 'exit_code': 0
  801. }), None,),
  802. ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
  803. ([custom_cl_base] if custom_cl_base else
  804. [ancestor_revision, 'HEAD']),),
  805. '+dat'),
  806. ]
  807. return calls
  808. @classmethod
  809. def _gerrit_upload_calls(cls, description, reviewers, squash,
  810. squash_mode='default',
  811. expected_upstream_ref='origin/refs/heads/master',
  812. title=None, notify=False,
  813. post_amend_description=None, issue=None, cc=None,
  814. custom_cl_base=None, tbr=None,
  815. short_hostname='chromium',
  816. labels=None, change_id=None, original_title=None,
  817. final_description=None, gitcookies_exists=True,
  818. force=False):
  819. if post_amend_description is None:
  820. post_amend_description = description
  821. cc = cc or []
  822. # Determined in `_gerrit_base_calls`.
  823. determined_ancestor_revision = custom_cl_base or 'fake_ancestor_sha'
  824. calls = []
  825. if squash_mode == 'default':
  826. calls.extend([
  827. ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],), ''),
  828. ((['git', 'config', '--bool', 'gerrit.squash-uploads'],), ''),
  829. ])
  830. elif squash_mode in ('override_squash', 'override_nosquash'):
  831. calls.extend([
  832. ((['git', 'config', '--bool', 'gerrit.override-squash-uploads'],),
  833. 'true' if squash_mode == 'override_squash' else 'false'),
  834. ])
  835. else:
  836. assert squash_mode in ('squash', 'nosquash')
  837. # If issue is given, then description is fetched from Gerrit instead.
  838. if issue is None:
  839. calls += [
  840. ((['git', 'log', '--pretty=format:%s\n\n%b',
  841. ((custom_cl_base + '..') if custom_cl_base else
  842. 'fake_ancestor_sha..HEAD')],),
  843. description),
  844. ]
  845. if squash:
  846. title = 'Initial_upload'
  847. else:
  848. if not title:
  849. calls += [
  850. ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
  851. (('ask_for_data', 'Title for patchset []: '), 'User input'),
  852. ]
  853. title = 'User_input'
  854. if not git_footers.get_footer_change_id(description) and not squash:
  855. calls += [
  856. (('DownloadGerritHook', False), ''),
  857. # Amending of commit message to get the Change-Id.
  858. ((['git', 'log', '--pretty=format:%s\n\n%b',
  859. determined_ancestor_revision + '..HEAD'],),
  860. description),
  861. ((['git', 'commit', '--amend', '-m', description],), ''),
  862. ((['git', 'log', '--pretty=format:%s\n\n%b',
  863. determined_ancestor_revision + '..HEAD'],),
  864. post_amend_description)
  865. ]
  866. if squash:
  867. if force or not issue:
  868. if issue:
  869. calls += [
  870. ((['git', 'config', 'rietveld.bug-prefix'],), ''),
  871. ]
  872. # Prompting to edit description on first upload.
  873. calls += [
  874. ((['git', 'config', 'rietveld.bug-prefix'],), ''),
  875. ]
  876. if not force:
  877. calls += [
  878. ((['git', 'config', 'core.editor'],), ''),
  879. ((['RunEditor'],), description),
  880. ]
  881. ref_to_push = 'abcdef0123456789'
  882. calls += [
  883. ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
  884. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  885. ]
  886. if custom_cl_base is None:
  887. calls += [
  888. ((['get_or_create_merge_base', 'master',
  889. 'refs/remotes/origin/master'],),
  890. 'origin/master'),
  891. ]
  892. parent = 'origin/master'
  893. else:
  894. calls += [
  895. ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
  896. 'refs/remotes/origin/master'],),
  897. callError(1)), # Means not ancenstor.
  898. (('ask_for_data',
  899. 'Do you take responsibility for cleaning up potential mess '
  900. 'resulting from proceeding with upload? Press Enter to upload, '
  901. 'or Ctrl+C to abort'), ''),
  902. ]
  903. parent = custom_cl_base
  904. calls += [
  905. ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
  906. '0123456789abcdef'),
  907. ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
  908. '-F', '/tmp/named'],),
  909. ref_to_push),
  910. ]
  911. else:
  912. ref_to_push = 'HEAD'
  913. calls += [
  914. (('SaveDescriptionBackup',), None),
  915. ((['git', 'rev-list',
  916. (custom_cl_base if custom_cl_base else expected_upstream_ref) + '..' +
  917. ref_to_push],),
  918. '1hashPerLine\n'),
  919. ]
  920. metrics_arguments = []
  921. if notify:
  922. ref_suffix = '%ready,notify=ALL'
  923. metrics_arguments += ['ready', 'notify=ALL']
  924. else:
  925. if not issue and squash:
  926. ref_suffix = '%wip'
  927. metrics_arguments.append('wip')
  928. else:
  929. ref_suffix = '%notify=NONE'
  930. metrics_arguments.append('notify=NONE')
  931. if title:
  932. ref_suffix += ',m=' + title
  933. metrics_arguments.append('m')
  934. if issue is None:
  935. calls += [
  936. ((['git', 'config', 'rietveld.cc'],), ''),
  937. ]
  938. if short_hostname == 'chromium':
  939. # All reviwers and ccs get into ref_suffix.
  940. for r in sorted(reviewers):
  941. ref_suffix += ',r=%s' % r
  942. metrics_arguments.append('r')
  943. if issue is None:
  944. cc += ['chromium-reviews+test-more-cc@chromium.org', 'joe@example.com']
  945. for c in sorted(cc):
  946. ref_suffix += ',cc=%s' % c
  947. metrics_arguments.append('cc')
  948. reviewers, cc = [], []
  949. else:
  950. # TODO(crbug/877717): remove this case.
  951. calls += [
  952. (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
  953. sorted(reviewers) + ['joe@example.com',
  954. 'chromium-reviews+test-more-cc@chromium.org'] + cc),
  955. {
  956. e: {'email': e}
  957. for e in (reviewers + ['joe@example.com'] + cc)
  958. })
  959. ]
  960. for r in sorted(reviewers):
  961. if r != 'bad-account-or-email':
  962. ref_suffix += ',r=%s' % r
  963. metrics_arguments.append('r')
  964. reviewers.remove(r)
  965. if issue is None:
  966. cc += ['joe@example.com']
  967. for c in sorted(cc):
  968. ref_suffix += ',cc=%s' % c
  969. metrics_arguments.append('cc')
  970. if c in cc:
  971. cc.remove(c)
  972. for k, v in sorted((labels or {}).items()):
  973. ref_suffix += ',l=%s+%d' % (k, v)
  974. metrics_arguments.append('l=%s+%d' % (k, v))
  975. if tbr:
  976. calls += [
  977. (('GetCodeReviewTbrScore',
  978. '%s-review.googlesource.com' % short_hostname,
  979. 'my/repo'),
  980. 2,),
  981. ]
  982. calls += [
  983. (('time.time',), 1000,),
  984. ((['git', 'push',
  985. 'https://%s.googlesource.com/my/repo' % short_hostname,
  986. ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
  987. (('remote:\n'
  988. 'remote: Processing changes: (\)\n'
  989. 'remote: Processing changes: (|)\n'
  990. 'remote: Processing changes: (/)\n'
  991. 'remote: Processing changes: (-)\n'
  992. 'remote: Processing changes: new: 1 (/)\n'
  993. 'remote: Processing changes: new: 1, done\n'
  994. 'remote:\n'
  995. 'remote: New Changes:\n'
  996. 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
  997. ' XXX\n'
  998. 'remote:\n'
  999. 'To https://%s.googlesource.com/my/repo\n'
  1000. ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
  1001. ) % (short_hostname, short_hostname)),),
  1002. (('time.time',), 2000,),
  1003. (('add_repeated',
  1004. 'sub_commands',
  1005. {
  1006. 'execution_time': 1000,
  1007. 'command': 'git push',
  1008. 'exit_code': 0,
  1009. 'arguments': sorted(metrics_arguments),
  1010. }),
  1011. None,),
  1012. ]
  1013. final_description = final_description or post_amend_description.strip()
  1014. original_title = original_title or title or '<untitled>'
  1015. # Trace-related calls
  1016. calls += [
  1017. # Write a description with context for the current trace.
  1018. ((['FileWrite', 'TRACES_DIR/20170316T200041.000000-README',
  1019. 'Thu Mar 16 20:00:41 2017\n'
  1020. '%(short_hostname)s-review.googlesource.com\n'
  1021. '%(change_id)s\n'
  1022. '%(title)s\n'
  1023. '%(description)s\n'
  1024. '1000\n'
  1025. '0\n'
  1026. '%(trace_name)s' % {
  1027. 'short_hostname': short_hostname,
  1028. 'change_id': change_id,
  1029. 'description': final_description,
  1030. 'title': original_title,
  1031. 'trace_name': 'TRACES_DIR/20170316T200041.000000',
  1032. }],),
  1033. None,
  1034. ),
  1035. # Read traces and shorten git hashes.
  1036. ((['os.path.isfile', 'TEMP_DIR/trace-packet'],),
  1037. True,
  1038. ),
  1039. ((['FileRead', 'TEMP_DIR/trace-packet'],),
  1040. ('git-hash: 0123456789012345678901234567890123456789\n'
  1041. 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
  1042. ),
  1043. ((['FileWrite', 'TEMP_DIR/trace-packet',
  1044. 'git-hash: 012345\n'
  1045. 'git-hash: abcdea\n'],),
  1046. None,
  1047. ),
  1048. # Make zip file for the git traces.
  1049. ((['make_archive', 'TRACES_DIR/20170316T200041.000000-traces', 'zip',
  1050. 'TEMP_DIR'],),
  1051. None,
  1052. ),
  1053. # Collect git config and gitcookies.
  1054. ((['git', 'config', '-l'],),
  1055. 'git-config-output',
  1056. ),
  1057. ((['FileWrite', 'TEMP_DIR/git-config', 'git-config-output'],),
  1058. None,
  1059. ),
  1060. ((['os.path.isfile', '~/.gitcookies'],),
  1061. gitcookies_exists,
  1062. ),
  1063. ]
  1064. if gitcookies_exists:
  1065. calls += [
  1066. ((['FileRead', '~/.gitcookies'],),
  1067. 'gitcookies 1/SECRET',
  1068. ),
  1069. ((['FileWrite', 'TEMP_DIR/gitcookies', 'gitcookies REDACTED'],),
  1070. None,
  1071. ),
  1072. ]
  1073. calls += [
  1074. # Make zip file for the git config and gitcookies.
  1075. ((['make_archive', 'TRACES_DIR/20170316T200041.000000-git-info', 'zip',
  1076. 'TEMP_DIR'],),
  1077. None,
  1078. ),
  1079. ]
  1080. if squash:
  1081. calls += [
  1082. ((['git', 'config', 'branch.master.gerritissue', '123456'],),
  1083. ''),
  1084. ((['git', 'config', 'branch.master.gerritserver',
  1085. 'https://chromium-review.googlesource.com'],), ''),
  1086. ((['git', 'config', 'branch.master.gerritsquashhash',
  1087. 'abcdef0123456789'],), ''),
  1088. ]
  1089. # TODO(crbug/877717): this should never be used.
  1090. if squash and short_hostname != 'chromium':
  1091. calls += [
  1092. (('AddReviewers',
  1093. 'chromium-review.googlesource.com', 'my%2Frepo~123456',
  1094. sorted(reviewers),
  1095. cc + ['chromium-reviews+test-more-cc@chromium.org'],
  1096. notify),
  1097. ''),
  1098. ]
  1099. calls += cls._git_post_upload_calls()
  1100. return calls
  1101. def _run_gerrit_upload_test(
  1102. self,
  1103. upload_args,
  1104. description,
  1105. reviewers=None,
  1106. squash=True,
  1107. squash_mode=None,
  1108. expected_upstream_ref='origin/refs/heads/master',
  1109. title=None,
  1110. notify=False,
  1111. post_amend_description=None,
  1112. issue=None,
  1113. cc=None,
  1114. fetched_status=None,
  1115. other_cl_owner=None,
  1116. custom_cl_base=None,
  1117. tbr=None,
  1118. short_hostname='chromium',
  1119. labels=None,
  1120. change_id=None,
  1121. original_title=None,
  1122. final_description=None,
  1123. gitcookies_exists=True,
  1124. force=False,
  1125. fetched_description=None):
  1126. """Generic gerrit upload test framework."""
  1127. if squash_mode is None:
  1128. if '--no-squash' in upload_args:
  1129. squash_mode = 'nosquash'
  1130. elif '--squash' in upload_args:
  1131. squash_mode = 'squash'
  1132. else:
  1133. squash_mode = 'default'
  1134. reviewers = reviewers or []
  1135. cc = cc or []
  1136. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1137. self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
  1138. CookiesAuthenticatorMockFactory(
  1139. same_auth=('git-owner.example.com', '', 'pass')))
  1140. self.mock(git_cl.Changelist, '_GerritCommitMsgHookCheck',
  1141. lambda _, offer_removal: None)
  1142. self.mock(git_cl.gclient_utils, 'RunEditor',
  1143. lambda *_, **__: self._mocked_call(['RunEditor']))
  1144. self.mock(git_cl, 'DownloadGerritHook', lambda force: self._mocked_call(
  1145. 'DownloadGerritHook', force))
  1146. self.mock(git_cl.gclient_utils, 'FileRead',
  1147. lambda path: self._mocked_call(['FileRead', path]))
  1148. self.mock(git_cl.gclient_utils, 'FileWrite',
  1149. lambda path, contents: self._mocked_call(
  1150. ['FileWrite', path, contents]))
  1151. self.mock(git_cl, 'datetime_now',
  1152. lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0))
  1153. self.mock(git_cl.tempfile, 'mkdtemp', lambda: 'TEMP_DIR')
  1154. self.mock(git_cl, 'TRACES_DIR', 'TRACES_DIR')
  1155. self.mock(git_cl, 'TRACES_README_FORMAT',
  1156. '%(now)s\n'
  1157. '%(gerrit_host)s\n'
  1158. '%(change_id)s\n'
  1159. '%(title)s\n'
  1160. '%(description)s\n'
  1161. '%(execution_time)s\n'
  1162. '%(exit_code)s\n'
  1163. '%(trace_name)s')
  1164. self.mock(git_cl.shutil, 'make_archive',
  1165. lambda *args: self._mocked_call(['make_archive'] + list(args)))
  1166. self.mock(os.path, 'isfile',
  1167. lambda path: self._mocked_call(['os.path.isfile', path]))
  1168. self.calls = self._gerrit_base_calls(
  1169. issue=issue,
  1170. fetched_description=fetched_description or description,
  1171. fetched_status=fetched_status,
  1172. other_cl_owner=other_cl_owner,
  1173. custom_cl_base=custom_cl_base,
  1174. short_hostname=short_hostname,
  1175. change_id=change_id)
  1176. if fetched_status != 'ABANDONED':
  1177. self.mock(tempfile, 'NamedTemporaryFile', MakeNamedTemporaryFileMock(
  1178. expected_content=description))
  1179. self.mock(os, 'remove', lambda _: True)
  1180. self.calls += self._gerrit_upload_calls(
  1181. description, reviewers, squash,
  1182. squash_mode=squash_mode,
  1183. expected_upstream_ref=expected_upstream_ref,
  1184. title=title, notify=notify,
  1185. post_amend_description=post_amend_description,
  1186. issue=issue, cc=cc,
  1187. custom_cl_base=custom_cl_base, tbr=tbr,
  1188. short_hostname=short_hostname,
  1189. labels=labels,
  1190. change_id=change_id,
  1191. original_title=original_title,
  1192. final_description=final_description,
  1193. gitcookies_exists=gitcookies_exists,
  1194. force=force)
  1195. # Uncomment when debugging.
  1196. # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
  1197. git_cl.main(['upload'] + upload_args)
  1198. def test_gerrit_upload_traces_no_gitcookies(self):
  1199. self._run_gerrit_upload_test(
  1200. ['--no-squash'],
  1201. 'desc\n\nBUG=\n',
  1202. [],
  1203. squash=False,
  1204. post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
  1205. change_id='Ixxx',
  1206. gitcookies_exists=False)
  1207. def test_gerrit_upload_without_change_id(self):
  1208. self._run_gerrit_upload_test(
  1209. ['--no-squash'],
  1210. 'desc\n\nBUG=\n',
  1211. [],
  1212. squash=False,
  1213. post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
  1214. change_id='Ixxx')
  1215. def test_gerrit_upload_without_change_id_override_nosquash(self):
  1216. self._run_gerrit_upload_test(
  1217. [],
  1218. 'desc\n\nBUG=\n',
  1219. [],
  1220. squash=False,
  1221. squash_mode='override_nosquash',
  1222. post_amend_description='desc\n\nBUG=\n\nChange-Id: Ixxx',
  1223. change_id='Ixxx')
  1224. def test_gerrit_no_reviewer(self):
  1225. self._run_gerrit_upload_test(
  1226. [],
  1227. 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
  1228. [],
  1229. squash=False,
  1230. squash_mode='override_nosquash',
  1231. change_id='I123456789')
  1232. def test_gerrit_no_reviewer_non_chromium_host(self):
  1233. # TODO(crbug/877717): remove this test case.
  1234. self._run_gerrit_upload_test(
  1235. [],
  1236. 'desc\n\nBUG=\n\nChange-Id: I123456789\n',
  1237. [],
  1238. squash=False,
  1239. squash_mode='override_nosquash',
  1240. short_hostname='other',
  1241. change_id='I123456789')
  1242. def test_gerrit_patchset_title_special_chars(self):
  1243. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1244. self._run_gerrit_upload_test(
  1245. ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
  1246. 'desc\n\nBUG=\n\nChange-Id: I123456789',
  1247. squash=False,
  1248. squash_mode='override_nosquash',
  1249. title='We%27ll_escape_%5E%5F_%5E_special_chars%2E%2E%2E%40%7Bu%7D',
  1250. change_id='I123456789',
  1251. original_title='We\'ll escape ^_ ^ special chars...@{u}')
  1252. def test_gerrit_reviewers_cmd_line(self):
  1253. self._run_gerrit_upload_test(
  1254. ['-r', 'foo@example.com', '--send-mail'],
  1255. 'desc\n\nBUG=\n\nChange-Id: I123456789',
  1256. ['foo@example.com'],
  1257. squash=False,
  1258. squash_mode='override_nosquash',
  1259. notify=True,
  1260. change_id='I123456789',
  1261. final_description=(
  1262. 'desc\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
  1263. def test_gerrit_upload_force_sets_bug(self):
  1264. self._run_gerrit_upload_test(
  1265. ['-b', '10000', '-f'],
  1266. u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
  1267. [],
  1268. force=True,
  1269. expected_upstream_ref='origin/master',
  1270. fetched_description='desc=\n\nChange-Id: Ixxx',
  1271. original_title='Initial upload',
  1272. change_id='Ixxx')
  1273. def test_gerrit_upload_force_sets_bug_if_wrong_changeid(self):
  1274. self._run_gerrit_upload_test(
  1275. ['-b', '10000', '-f', '-m', 'Title'],
  1276. u'desc=\n\nChange-Id: Ixxxx\n\nChange-Id: Izzzz\nBug: 10000',
  1277. [],
  1278. force=True,
  1279. issue='123456',
  1280. expected_upstream_ref='origin/master',
  1281. fetched_description='desc=\n\nChange-Id: Ixxxx',
  1282. original_title='Title',
  1283. title='Title',
  1284. change_id='Izzzz')
  1285. def test_gerrit_reviewer_multiple(self):
  1286. self.mock(git_cl.gerrit_util, 'GetCodeReviewTbrScore',
  1287. lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a))
  1288. self._run_gerrit_upload_test(
  1289. [],
  1290. 'desc\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
  1291. 'CC=more@example.com,people@example.com\n\n'
  1292. 'Change-Id: 123456789',
  1293. ['reviewer@example.com', 'another@example.com'],
  1294. expected_upstream_ref='origin/master',
  1295. cc=['more@example.com', 'people@example.com'],
  1296. tbr='reviewer@example.com',
  1297. labels={'Code-Review': 2},
  1298. change_id='123456789',
  1299. original_title='Initial upload')
  1300. def test_gerrit_upload_squash_first_is_default(self):
  1301. self._run_gerrit_upload_test(
  1302. [],
  1303. 'desc\nBUG=\n\nChange-Id: 123456789',
  1304. [],
  1305. expected_upstream_ref='origin/master',
  1306. change_id='123456789',
  1307. original_title='Initial upload')
  1308. def test_gerrit_upload_squash_first(self):
  1309. self._run_gerrit_upload_test(
  1310. ['--squash'],
  1311. 'desc\nBUG=\n\nChange-Id: 123456789',
  1312. [],
  1313. squash=True,
  1314. expected_upstream_ref='origin/master',
  1315. change_id='123456789',
  1316. original_title='Initial upload')
  1317. def test_gerrit_upload_squash_first_with_labels(self):
  1318. self._run_gerrit_upload_test(
  1319. ['--squash', '--cq-dry-run', '--enable-auto-submit'],
  1320. 'desc\nBUG=\n\nChange-Id: 123456789',
  1321. [],
  1322. squash=True,
  1323. expected_upstream_ref='origin/master',
  1324. labels={'Commit-Queue': 1, 'Auto-Submit': 1},
  1325. change_id='123456789',
  1326. original_title='Initial upload')
  1327. def test_gerrit_upload_squash_first_against_rev(self):
  1328. custom_cl_base = 'custom_cl_base_rev_or_branch'
  1329. self._run_gerrit_upload_test(
  1330. ['--squash', custom_cl_base],
  1331. 'desc\nBUG=\n\nChange-Id: 123456789',
  1332. [],
  1333. squash=True,
  1334. expected_upstream_ref='origin/master',
  1335. custom_cl_base=custom_cl_base,
  1336. change_id='123456789',
  1337. original_title='Initial upload')
  1338. self.assertIn(
  1339. 'If you proceed with upload, more than 1 CL may be created by Gerrit',
  1340. sys.stdout.getvalue())
  1341. def test_gerrit_upload_squash_reupload(self):
  1342. description = 'desc\nBUG=\n\nChange-Id: 123456789'
  1343. self._run_gerrit_upload_test(
  1344. ['--squash'],
  1345. description,
  1346. [],
  1347. squash=True,
  1348. expected_upstream_ref='origin/master',
  1349. issue=123456,
  1350. change_id='123456789',
  1351. original_title='User input')
  1352. def test_gerrit_upload_squash_reupload_to_abandoned(self):
  1353. self.mock(git_cl, 'DieWithError',
  1354. lambda msg, change=None: self._mocked_call('DieWithError', msg))
  1355. description = 'desc\nBUG=\n\nChange-Id: 123456789'
  1356. with self.assertRaises(SystemExitMock):
  1357. self._run_gerrit_upload_test(
  1358. ['--squash'],
  1359. description,
  1360. [],
  1361. squash=True,
  1362. expected_upstream_ref='origin/master',
  1363. issue=123456,
  1364. fetched_status='ABANDONED',
  1365. change_id='123456789')
  1366. def test_gerrit_upload_squash_reupload_to_not_owned(self):
  1367. self.mock(git_cl.gerrit_util, 'GetAccountDetails',
  1368. lambda *_, **__: {'email': 'yet-another@example.com'})
  1369. description = 'desc\nBUG=\n\nChange-Id: 123456789'
  1370. self._run_gerrit_upload_test(
  1371. ['--squash'],
  1372. description,
  1373. [],
  1374. squash=True,
  1375. expected_upstream_ref='origin/master',
  1376. issue=123456,
  1377. other_cl_owner='other@example.com',
  1378. change_id='123456789',
  1379. original_title='User input')
  1380. self.assertIn(
  1381. 'WARNING: Change 123456 is owned by other@example.com, but you '
  1382. 'authenticate to Gerrit as yet-another@example.com.\n'
  1383. 'Uploading may fail due to lack of permissions',
  1384. git_cl.sys.stdout.getvalue())
  1385. def test_upload_branch_deps(self):
  1386. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1387. def mock_run_git(*args, **_kwargs):
  1388. if args[0] == ['for-each-ref',
  1389. '--format=%(refname:short) %(upstream:short)',
  1390. 'refs/heads']:
  1391. # Create a local branch dependency tree that looks like this:
  1392. # test1 -> test2 -> test3 -> test4 -> test5
  1393. # -> test3.1
  1394. # test6 -> test0
  1395. branch_deps = [
  1396. 'test2 test1', # test1 -> test2
  1397. 'test3 test2', # test2 -> test3
  1398. 'test3.1 test2', # test2 -> test3.1
  1399. 'test4 test3', # test3 -> test4
  1400. 'test5 test4', # test4 -> test5
  1401. 'test6 test0', # test0 -> test6
  1402. 'test7', # test7
  1403. ]
  1404. return '\n'.join(branch_deps)
  1405. self.mock(git_cl, 'RunGit', mock_run_git)
  1406. class RecordCalls:
  1407. times_called = 0
  1408. record_calls = RecordCalls()
  1409. def mock_CMDupload(*args, **_kwargs):
  1410. record_calls.times_called += 1
  1411. return 0
  1412. self.mock(git_cl, 'CMDupload', mock_CMDupload)
  1413. self.calls = [
  1414. (('ask_for_data', 'This command will checkout all dependent branches '
  1415. 'and run "git cl upload". Press Enter to continue, '
  1416. 'or Ctrl+C to abort'), ''),
  1417. ]
  1418. class MockChangelist():
  1419. def __init__(self):
  1420. pass
  1421. def GetBranch(self):
  1422. return 'test1'
  1423. def GetIssue(self):
  1424. return '123'
  1425. def GetPatchset(self):
  1426. return '1001'
  1427. def IsGerrit(self):
  1428. return False
  1429. ret = git_cl.upload_branch_deps(MockChangelist(), [])
  1430. # CMDupload should have been called 5 times because of 5 dependent branches.
  1431. self.assertEquals(5, record_calls.times_called)
  1432. self.assertEquals(0, ret)
  1433. def test_gerrit_change_id(self):
  1434. self.calls = [
  1435. ((['git', 'write-tree'], ),
  1436. 'hashtree'),
  1437. ((['git', 'rev-parse', 'HEAD~0'], ),
  1438. 'branch-parent'),
  1439. ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
  1440. 'A B <a@b.org> 1456848326 +0100'),
  1441. ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
  1442. 'C D <c@d.org> 1456858326 +0100'),
  1443. ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
  1444. 'hashchange'),
  1445. ]
  1446. change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
  1447. self.assertEqual(change_id, 'Ihashchange')
  1448. def test_desecription_append_footer(self):
  1449. for init_desc, footer_line, expected_desc in [
  1450. # Use unique desc first lines for easy test failure identification.
  1451. ('foo', 'R=one', 'foo\n\nR=one'),
  1452. ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
  1453. ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
  1454. ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
  1455. ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
  1456. 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
  1457. ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
  1458. 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
  1459. ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
  1460. 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
  1461. ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
  1462. ]:
  1463. desc = git_cl.ChangeDescription(init_desc)
  1464. desc.append_footer(footer_line)
  1465. self.assertEqual(desc.description, expected_desc)
  1466. def test_update_reviewers(self):
  1467. data = [
  1468. ('foo', [], [],
  1469. 'foo'),
  1470. ('foo\nR=xx', [], [],
  1471. 'foo\nR=xx'),
  1472. ('foo\nTBR=xx', [], [],
  1473. 'foo\nTBR=xx'),
  1474. ('foo', ['a@c'], [],
  1475. 'foo\n\nR=a@c'),
  1476. ('foo\nR=xx', ['a@c'], [],
  1477. 'foo\n\nR=a@c, xx'),
  1478. ('foo\nTBR=xx', ['a@c'], [],
  1479. 'foo\n\nR=a@c\nTBR=xx'),
  1480. ('foo\nTBR=xx\nR=yy', ['a@c'], [],
  1481. 'foo\n\nR=a@c, yy\nTBR=xx'),
  1482. ('foo\nBUG=', ['a@c'], [],
  1483. 'foo\nBUG=\nR=a@c'),
  1484. ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
  1485. 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
  1486. ('foo', ['a@c', 'b@c'], [],
  1487. 'foo\n\nR=a@c, b@c'),
  1488. ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
  1489. 'foo\nBar\n\nR=c@c\nBUG='),
  1490. ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
  1491. 'foo\nBar\n\nR=c@c\nBUG='),
  1492. # Same as the line before, but full of whitespaces.
  1493. (
  1494. 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
  1495. 'foo\nBar\n\nR=c@c\n BUG =',
  1496. ),
  1497. # Whitespaces aren't interpreted as new lines.
  1498. ('foo BUG=allo R=joe ', ['c@c'], [],
  1499. 'foo BUG=allo R=joe\n\nR=c@c'),
  1500. # Redundant TBRs get promoted to Rs
  1501. ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
  1502. 'foo\n\nR=a@c, b@c\nTBR=t@c'),
  1503. ]
  1504. expected = [i[-1] for i in data]
  1505. actual = []
  1506. for orig, reviewers, tbrs, _expected in data:
  1507. obj = git_cl.ChangeDescription(orig)
  1508. obj.update_reviewers(reviewers, tbrs)
  1509. actual.append(obj.description)
  1510. self.assertEqual(expected, actual)
  1511. def test_get_hash_tags(self):
  1512. cases = [
  1513. ('', []),
  1514. ('a', []),
  1515. ('[a]', ['a']),
  1516. ('[aa]', ['aa']),
  1517. ('[a ]', ['a']),
  1518. ('[a- ]', ['a']),
  1519. ('[a- b]', ['a-b']),
  1520. ('[a--b]', ['a-b']),
  1521. ('[a', []),
  1522. ('[a]x', ['a']),
  1523. ('[aa]x', ['aa']),
  1524. ('[a b]', ['a-b']),
  1525. ('[a b]', ['a-b']),
  1526. ('[a__b]', ['a-b']),
  1527. ('[a] x', ['a']),
  1528. ('[a][b]', ['a', 'b']),
  1529. ('[a] [b]', ['a', 'b']),
  1530. ('[a][b]x', ['a', 'b']),
  1531. ('[a][b] x', ['a', 'b']),
  1532. ('[a]\n[b]', ['a']),
  1533. ('[a\nb]', []),
  1534. ('[a][', ['a']),
  1535. ('Revert "[a] feature"', ['a']),
  1536. ('Reland "[a] feature"', ['a']),
  1537. ('Revert: [a] feature', ['a']),
  1538. ('Reland: [a] feature', ['a']),
  1539. ('Revert "Reland: [a] feature"', ['a']),
  1540. ('Foo: feature', ['foo']),
  1541. ('Foo Bar: feature', ['foo-bar']),
  1542. ('Revert "Foo bar: feature"', ['foo-bar']),
  1543. ('Reland "Foo bar: feature"', ['foo-bar']),
  1544. ]
  1545. for desc, expected in cases:
  1546. change_desc = git_cl.ChangeDescription(desc)
  1547. actual = change_desc.get_hash_tags()
  1548. self.assertEqual(
  1549. actual,
  1550. expected,
  1551. 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
  1552. self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
  1553. self.assertEqual(None, git_cl.GetTargetRef(None,
  1554. 'refs/remotes/origin/master',
  1555. 'master'))
  1556. # Check default target refs for branches.
  1557. self.assertEqual('refs/heads/master',
  1558. git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
  1559. None))
  1560. self.assertEqual('refs/heads/master',
  1561. git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
  1562. None))
  1563. self.assertEqual('refs/heads/master',
  1564. git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
  1565. None))
  1566. self.assertEqual('refs/branch-heads/123',
  1567. git_cl.GetTargetRef('origin',
  1568. 'refs/remotes/branch-heads/123',
  1569. None))
  1570. self.assertEqual('refs/diff/test',
  1571. git_cl.GetTargetRef('origin',
  1572. 'refs/remotes/origin/refs/diff/test',
  1573. None))
  1574. self.assertEqual('refs/heads/chrome/m42',
  1575. git_cl.GetTargetRef('origin',
  1576. 'refs/remotes/origin/chrome/m42',
  1577. None))
  1578. # Check target refs for user-specified target branch.
  1579. for branch in ('branch-heads/123', 'remotes/branch-heads/123',
  1580. 'refs/remotes/branch-heads/123'):
  1581. self.assertEqual('refs/branch-heads/123',
  1582. git_cl.GetTargetRef('origin',
  1583. 'refs/remotes/origin/master',
  1584. branch))
  1585. for branch in ('origin/master', 'remotes/origin/master',
  1586. 'refs/remotes/origin/master'):
  1587. self.assertEqual('refs/heads/master',
  1588. git_cl.GetTargetRef('origin',
  1589. 'refs/remotes/branch-heads/123',
  1590. branch))
  1591. for branch in ('master', 'heads/master', 'refs/heads/master'):
  1592. self.assertEqual('refs/heads/master',
  1593. git_cl.GetTargetRef('origin',
  1594. 'refs/remotes/branch-heads/123',
  1595. branch))
  1596. def test_patch_when_dirty(self):
  1597. # Patch when local tree is dirty.
  1598. self.mock(git_common, 'is_dirty_git_tree', lambda x: True)
  1599. self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
  1600. @staticmethod
  1601. def _get_gerrit_codereview_server_calls(branch, value=None,
  1602. git_short_host='host',
  1603. detect_branch=True,
  1604. detect_server=True):
  1605. """Returns calls executed by Changelist.GetCodereviewServer.
  1606. If value is given, branch.<BRANCH>.gerritcodereview is already set.
  1607. """
  1608. calls = []
  1609. if detect_branch:
  1610. calls.append(((['git', 'symbolic-ref', 'HEAD'],), branch))
  1611. if detect_server:
  1612. calls.append(((['git', 'config', 'branch.' + branch + '.gerritserver'],),
  1613. CERR1 if value is None else value))
  1614. if value is None:
  1615. calls += [
  1616. ((['git', 'config', 'branch.' + branch + '.merge'],),
  1617. 'refs/heads' + branch),
  1618. ((['git', 'config', 'branch.' + branch + '.remote'],),
  1619. 'origin'),
  1620. ((['git', 'config', 'remote.origin.url'],),
  1621. 'https://%s.googlesource.com/my/repo' % git_short_host),
  1622. ]
  1623. return calls
  1624. def _patch_common(self, force_codereview=False,
  1625. new_branch=False, git_short_host='host',
  1626. detect_gerrit_server=False,
  1627. actual_codereview=None,
  1628. codereview_in_url=False):
  1629. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1630. self.mock(git_cl, 'IsGitVersionAtLeast', lambda *args: True)
  1631. if new_branch:
  1632. self.calls = [((['git', 'new-branch', 'master'],), '')]
  1633. if codereview_in_url and actual_codereview == 'rietveld':
  1634. self.calls += [
  1635. ((['git', 'rev-parse', '--show-cdup'],), ''),
  1636. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  1637. ]
  1638. if not force_codereview and not codereview_in_url:
  1639. # These calls detect codereview to use.
  1640. self.calls += [
  1641. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  1642. ]
  1643. if detect_gerrit_server:
  1644. self.calls += self._get_gerrit_codereview_server_calls(
  1645. 'master', git_short_host=git_short_host,
  1646. detect_branch=not new_branch and force_codereview)
  1647. actual_codereview = 'gerrit'
  1648. if actual_codereview == 'gerrit':
  1649. self.calls += [
  1650. (('GetChangeDetail', git_short_host + '-review.googlesource.com',
  1651. 'my%2Frepo~123456', ['ALL_REVISIONS', 'CURRENT_COMMIT']),
  1652. {
  1653. 'current_revision': '7777777777',
  1654. 'revisions': {
  1655. '1111111111': {
  1656. '_number': 1,
  1657. 'fetch': {'http': {
  1658. 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
  1659. 'ref': 'refs/changes/56/123456/1',
  1660. }},
  1661. },
  1662. '7777777777': {
  1663. '_number': 7,
  1664. 'fetch': {'http': {
  1665. 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
  1666. 'ref': 'refs/changes/56/123456/7',
  1667. }},
  1668. },
  1669. },
  1670. }),
  1671. ]
  1672. def test_patch_gerrit_default(self):
  1673. self._patch_common(git_short_host='chromium', detect_gerrit_server=True)
  1674. self.calls += [
  1675. ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  1676. 'refs/changes/56/123456/7'],), ''),
  1677. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1678. ((['git', 'config', 'branch.master.gerritissue', '123456'],),
  1679. ''),
  1680. ((['git', 'config', 'branch.master.gerritserver',
  1681. 'https://chromium-review.googlesource.com'],), ''),
  1682. ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
  1683. ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
  1684. ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
  1685. ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
  1686. ]
  1687. self.assertEqual(git_cl.main(['patch', '123456']), 0)
  1688. def test_patch_gerrit_new_branch(self):
  1689. self._patch_common(
  1690. git_short_host='chromium', detect_gerrit_server=True, new_branch=True)
  1691. self.calls += [
  1692. ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  1693. 'refs/changes/56/123456/7'],), ''),
  1694. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1695. ((['git', 'config', 'branch.master.gerritissue', '123456'],),
  1696. ''),
  1697. ((['git', 'config', 'branch.master.gerritserver',
  1698. 'https://chromium-review.googlesource.com'],), ''),
  1699. ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
  1700. ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
  1701. ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
  1702. ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
  1703. ]
  1704. self.assertEqual(git_cl.main(['patch', '-b', 'master', '123456']), 0)
  1705. def test_patch_gerrit_force(self):
  1706. self._patch_common(
  1707. force_codereview=True, git_short_host='host', detect_gerrit_server=True)
  1708. self.calls += [
  1709. ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
  1710. 'refs/changes/56/123456/7'],), ''),
  1711. ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
  1712. ((['git', 'config', 'branch.master.gerritissue', '123456'],),
  1713. ''),
  1714. ((['git', 'config', 'branch.master.gerritserver',
  1715. 'https://host-review.googlesource.com'],), ''),
  1716. ((['git', 'config', 'branch.master.gerritpatchset', '7'],), ''),
  1717. ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
  1718. ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
  1719. ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
  1720. ]
  1721. self.assertEqual(git_cl.main(['patch', '--gerrit', '123456', '--force']), 0)
  1722. def test_patch_gerrit_guess_by_url(self):
  1723. self.calls += self._get_gerrit_codereview_server_calls(
  1724. 'master', git_short_host='else', detect_server=False)
  1725. self._patch_common(
  1726. actual_codereview='gerrit', git_short_host='else',
  1727. codereview_in_url=True, detect_gerrit_server=False)
  1728. self.calls += [
  1729. ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
  1730. 'refs/changes/56/123456/1'],), ''),
  1731. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1732. ((['git', 'config', 'branch.master.gerritissue', '123456'],),
  1733. ''),
  1734. ((['git', 'config', 'branch.master.gerritserver',
  1735. 'https://else-review.googlesource.com'],), ''),
  1736. ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
  1737. ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
  1738. ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
  1739. ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
  1740. ]
  1741. self.assertEqual(git_cl.main(
  1742. ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
  1743. def test_patch_gerrit_guess_by_url_with_repo(self):
  1744. self.calls += self._get_gerrit_codereview_server_calls(
  1745. 'master', git_short_host='else', detect_server=False)
  1746. self._patch_common(
  1747. actual_codereview='gerrit', git_short_host='else',
  1748. codereview_in_url=True, detect_gerrit_server=False)
  1749. self.calls += [
  1750. ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
  1751. 'refs/changes/56/123456/1'],), ''),
  1752. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1753. ((['git', 'config', 'branch.master.gerritissue', '123456'],),
  1754. ''),
  1755. ((['git', 'config', 'branch.master.gerritserver',
  1756. 'https://else-review.googlesource.com'],), ''),
  1757. ((['git', 'config', 'branch.master.gerritpatchset', '1'],), ''),
  1758. ((['git', 'rev-parse', 'FETCH_HEAD'],), 'deadbeef'),
  1759. ((['git', 'config', 'branch.master.last-upload-hash', 'deadbeef'],), ''),
  1760. ((['git', 'config', 'branch.master.gerritsquashhash', 'deadbeef'],), ''),
  1761. ]
  1762. self.assertEqual(git_cl.main(
  1763. ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
  1764. 0)
  1765. def test_patch_gerrit_conflict(self):
  1766. self._patch_common(detect_gerrit_server=True, git_short_host='chromium')
  1767. self.calls += [
  1768. ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  1769. 'refs/changes/56/123456/7'],), ''),
  1770. ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
  1771. ((['DieWithError', 'Command "git cherry-pick FETCH_HEAD" failed.\n'],),
  1772. SystemExitMock()),
  1773. ]
  1774. with self.assertRaises(SystemExitMock):
  1775. git_cl.main(['patch', '123456'])
  1776. def test_patch_gerrit_not_exists(self):
  1777. def notExists(_issue, *_, **kwargs):
  1778. raise git_cl.gerrit_util.GerritError(404, '')
  1779. self.mock(git_cl.gerrit_util, 'GetChangeDetail', notExists)
  1780. self.calls = [
  1781. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  1782. ((['git', 'config', 'branch.master.gerritserver'],), CERR1),
  1783. ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
  1784. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  1785. ((['git', 'config', 'remote.origin.url'],),
  1786. 'https://chromium.googlesource.com/my/repo'),
  1787. ((['DieWithError',
  1788. 'change 123456 at https://chromium-review.googlesource.com does not '
  1789. 'exist or you have no access to it'],), SystemExitMock()),
  1790. ]
  1791. with self.assertRaises(SystemExitMock):
  1792. self.assertEqual(1, git_cl.main(['patch', '123456']))
  1793. def _checkout_calls(self):
  1794. return [
  1795. ((['git', 'config', '--local', '--get-regexp',
  1796. 'branch\\..*\\.gerritissue'], ),
  1797. ('branch.ger-branch.gerritissue 123456\n'
  1798. 'branch.gbranch654.gerritissue 654321\n')),
  1799. ]
  1800. def test_checkout_gerrit(self):
  1801. """Tests git cl checkout <issue>."""
  1802. self.calls = self._checkout_calls()
  1803. self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
  1804. self.assertEqual(0, git_cl.main(['checkout', '123456']))
  1805. def test_checkout_not_found(self):
  1806. """Tests git cl checkout <issue>."""
  1807. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1808. self.calls = self._checkout_calls()
  1809. self.assertEqual(1, git_cl.main(['checkout', '99999']))
  1810. def test_checkout_no_branch_issues(self):
  1811. """Tests git cl checkout <issue>."""
  1812. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1813. self.calls = [
  1814. ((['git', 'config', '--local', '--get-regexp',
  1815. 'branch\\..*\\.gerritissue'], ), CERR1),
  1816. ]
  1817. self.assertEqual(1, git_cl.main(['checkout', '99999']))
  1818. def _test_gerrit_ensure_authenticated_common(self, auth,
  1819. skip_auth_check=False):
  1820. self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
  1821. CookiesAuthenticatorMockFactory(hosts_with_creds=auth))
  1822. self.mock(git_cl, 'DieWithError',
  1823. lambda msg, change=None: self._mocked_call(['DieWithError', msg]))
  1824. self.calls = self._gerrit_ensure_auth_calls(skip_auth_check=skip_auth_check)
  1825. cl = git_cl.Changelist()
  1826. cl.branch = 'master'
  1827. cl.branchref = 'refs/heads/master'
  1828. return cl
  1829. def test_gerrit_ensure_authenticated_missing(self):
  1830. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1831. 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
  1832. })
  1833. self.calls.append(
  1834. ((['DieWithError',
  1835. 'Credentials for the following hosts are required:\n'
  1836. ' chromium-review.googlesource.com\n'
  1837. 'These are read from ~/.gitcookies (or legacy ~/.netrc)\n'
  1838. 'You can (re)generate your credentials by visiting '
  1839. 'https://chromium-review.googlesource.com/new-password'],), ''),)
  1840. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1841. def test_gerrit_ensure_authenticated_conflict(self):
  1842. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  1843. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1844. 'chromium.googlesource.com':
  1845. ('git-one.example.com', None, 'secret1'),
  1846. 'chromium-review.googlesource.com':
  1847. ('git-other.example.com', None, 'secret2'),
  1848. })
  1849. self.calls.append(
  1850. (('ask_for_data', 'If you know what you are doing '
  1851. 'press Enter to continue, or Ctrl+C to abort'), ''))
  1852. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1853. def test_gerrit_ensure_authenticated_ok(self):
  1854. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1855. 'chromium.googlesource.com':
  1856. ('git-same.example.com', None, 'secret'),
  1857. 'chromium-review.googlesource.com':
  1858. ('git-same.example.com', None, 'secret'),
  1859. })
  1860. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1861. def test_gerrit_ensure_authenticated_skipped(self):
  1862. cl = self._test_gerrit_ensure_authenticated_common(
  1863. auth={}, skip_auth_check=True)
  1864. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1865. def test_gerrit_ensure_authenticated_bearer_token(self):
  1866. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1867. 'chromium.googlesource.com':
  1868. ('', None, 'secret'),
  1869. 'chromium-review.googlesource.com':
  1870. ('', None, 'secret'),
  1871. })
  1872. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1873. header = gerrit_util.CookiesAuthenticator().get_auth_header(
  1874. 'chromium.googlesource.com')
  1875. self.assertTrue('Bearer' in header)
  1876. def test_gerrit_ensure_authenticated_non_https(self):
  1877. self.calls = [
  1878. ((['git', 'config', '--bool',
  1879. 'gerrit.skip-ensure-authenticated'],), CERR1),
  1880. ((['git', 'config', 'branch.master.merge'],), 'refs/heads/master'),
  1881. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  1882. ((['git', 'config', 'remote.origin.url'],), 'custom-scheme://repo'),
  1883. ]
  1884. self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
  1885. CookiesAuthenticatorMockFactory(hosts_with_creds={}))
  1886. cl = git_cl.Changelist()
  1887. cl.branch = 'master'
  1888. cl.branchref = 'refs/heads/master'
  1889. cl.lookedup_issue = True
  1890. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1891. def _cmd_set_commit_gerrit_common(self, vote, notify=None):
  1892. self.mock(git_cl.gerrit_util, 'SetReview',
  1893. lambda h, i, labels, notify=None:
  1894. self._mocked_call(['SetReview', h, i, labels, notify]))
  1895. self.calls = [
  1896. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  1897. ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
  1898. ((['git', 'config', 'branch.feature.gerritserver'],),
  1899. 'https://chromium-review.googlesource.com'),
  1900. ((['git', 'config', 'branch.feature.merge'],), 'refs/heads/master'),
  1901. ((['git', 'config', 'branch.feature.remote'],), 'origin'),
  1902. ((['git', 'config', 'remote.origin.url'],),
  1903. 'https://chromium.googlesource.com/infra/infra.git'),
  1904. ((['SetReview', 'chromium-review.googlesource.com',
  1905. 'infra%2Finfra~123',
  1906. {'Commit-Queue': vote}, notify],), ''),
  1907. ]
  1908. def test_cmd_set_commit_gerrit_clear(self):
  1909. self._cmd_set_commit_gerrit_common(0)
  1910. self.assertEqual(0, git_cl.main(['set-commit', '-c']))
  1911. def test_cmd_set_commit_gerrit_dry(self):
  1912. self._cmd_set_commit_gerrit_common(1, notify=False)
  1913. self.assertEqual(0, git_cl.main(['set-commit', '-d']))
  1914. def test_cmd_set_commit_gerrit(self):
  1915. self._cmd_set_commit_gerrit_common(2)
  1916. self.assertEqual(0, git_cl.main(['set-commit']))
  1917. def test_description_display(self):
  1918. out = StringIO.StringIO()
  1919. self.mock(git_cl.sys, 'stdout', out)
  1920. self.mock(git_cl, 'Changelist', ChangelistMock)
  1921. ChangelistMock.desc = 'foo\n'
  1922. self.assertEqual(0, git_cl.main(['description', '-d']))
  1923. self.assertEqual('foo\n', out.getvalue())
  1924. def test_StatusFieldOverrideIssueMissingArgs(self):
  1925. out = StringIO.StringIO()
  1926. self.mock(git_cl.sys, 'stderr', out)
  1927. try:
  1928. self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
  1929. except SystemExit as ex:
  1930. self.assertEqual(ex.code, 2)
  1931. self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
  1932. out = StringIO.StringIO()
  1933. self.mock(git_cl.sys, 'stderr', out)
  1934. try:
  1935. self.assertEqual(git_cl.main(['status', '--issue', '1', '--gerrit']), 0)
  1936. except SystemExit as ex:
  1937. self.assertEqual(ex.code, 2)
  1938. self.assertRegexpMatches(out.getvalue(), r'--field must be specified')
  1939. def test_StatusFieldOverrideIssue(self):
  1940. out = StringIO.StringIO()
  1941. self.mock(git_cl.sys, 'stdout', out)
  1942. def assertIssue(cl_self, *_args):
  1943. self.assertEquals(cl_self.issue, 1)
  1944. return 'foobar'
  1945. self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
  1946. self.assertEqual(
  1947. git_cl.main(['status', '--issue', '1', '--gerrit', '--field', 'desc']),
  1948. 0)
  1949. self.assertEqual(out.getvalue(), 'foobar\n')
  1950. def test_SetCloseOverrideIssue(self):
  1951. def assertIssue(cl_self, *_args):
  1952. self.assertEquals(cl_self.issue, 1)
  1953. return 'foobar'
  1954. self.mock(git_cl.Changelist, 'GetDescription', assertIssue)
  1955. self.mock(git_cl.Changelist, 'CloseIssue', lambda *_: None)
  1956. self.assertEqual(
  1957. git_cl.main(['set-close', '--issue', '1', '--gerrit']), 0)
  1958. def test_description(self):
  1959. out = StringIO.StringIO()
  1960. self.mock(git_cl.sys, 'stdout', out)
  1961. self.calls = [
  1962. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  1963. ((['git', 'config', 'branch.feature.merge'],), 'feature'),
  1964. ((['git', 'config', 'branch.feature.remote'],), 'origin'),
  1965. ((['git', 'config', 'remote.origin.url'],),
  1966. 'https://chromium.googlesource.com/my/repo'),
  1967. (('GetChangeDetail', 'chromium-review.googlesource.com',
  1968. 'my%2Frepo~123123', ['CURRENT_REVISION', 'CURRENT_COMMIT']),
  1969. {
  1970. 'current_revision': 'sha1',
  1971. 'revisions': {'sha1': {
  1972. 'commit': {'message': 'foobar'},
  1973. }},
  1974. }),
  1975. ]
  1976. self.assertEqual(0, git_cl.main([
  1977. 'description',
  1978. 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
  1979. '-d']))
  1980. self.assertEqual('foobar\n', out.getvalue())
  1981. def test_description_set_raw(self):
  1982. out = StringIO.StringIO()
  1983. self.mock(git_cl.sys, 'stdout', out)
  1984. self.mock(git_cl, 'Changelist', ChangelistMock)
  1985. self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hihi'))
  1986. self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
  1987. self.assertEqual('hihi', ChangelistMock.desc)
  1988. def test_description_appends_bug_line(self):
  1989. current_desc = 'Some.\n\nChange-Id: xxx'
  1990. def RunEditor(desc, _, **kwargs):
  1991. self.assertEquals(
  1992. '# Enter a description of the change.\n'
  1993. '# This will be displayed on the codereview site.\n'
  1994. '# The first line will also be used as the subject of the review.\n'
  1995. '#--------------------This line is 72 characters long'
  1996. '--------------------\n'
  1997. 'Some.\n\nChange-Id: xxx\nBug: ',
  1998. desc)
  1999. # Simulate user changing something.
  2000. return 'Some.\n\nChange-Id: xxx\nBug: 123'
  2001. def UpdateDescriptionRemote(_, desc, force=False):
  2002. self.assertEquals(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
  2003. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  2004. self.mock(git_cl.Changelist, 'GetDescription',
  2005. lambda *args: current_desc)
  2006. self.mock(git_cl.Changelist, 'UpdateDescriptionRemote',
  2007. UpdateDescriptionRemote)
  2008. self.mock(git_cl.gclient_utils, 'RunEditor', RunEditor)
  2009. self.calls = [
  2010. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  2011. ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
  2012. ((['git', 'config', 'rietveld.autoupdate'],), CERR1),
  2013. ((['git', 'config', 'rietveld.bug-prefix'],), CERR1),
  2014. ((['git', 'config', 'core.editor'],), 'vi'),
  2015. ]
  2016. self.assertEqual(0, git_cl.main(['description', '--gerrit']))
  2017. def test_description_set_stdin(self):
  2018. out = StringIO.StringIO()
  2019. self.mock(git_cl.sys, 'stdout', out)
  2020. self.mock(git_cl, 'Changelist', ChangelistMock)
  2021. self.mock(git_cl.sys, 'stdin', StringIO.StringIO('hi \r\n\t there\n\nman'))
  2022. self.assertEqual(0, git_cl.main(['description', '-n', '-']))
  2023. self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
  2024. def test_archive(self):
  2025. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  2026. self.calls = [
  2027. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  2028. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  2029. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2030. ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
  2031. ((['git', 'branch', '-D', 'foo'],), '')
  2032. ]
  2033. self.mock(git_cl, 'get_cl_statuses',
  2034. lambda branches, fine_grained, max_processes:
  2035. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  2036. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2037. (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
  2038. self.assertEqual(0, git_cl.main(['archive', '-f']))
  2039. def test_archive_current_branch_fails(self):
  2040. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  2041. self.calls = [
  2042. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  2043. 'refs/heads/master'),
  2044. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2045. ]
  2046. self.mock(git_cl, 'get_cl_statuses',
  2047. lambda branches, fine_grained, max_processes:
  2048. [(MockChangelistWithBranchAndIssue('master', 1), 'closed')])
  2049. self.assertEqual(1, git_cl.main(['archive', '-f']))
  2050. def test_archive_dry_run(self):
  2051. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  2052. self.calls = [
  2053. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  2054. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  2055. ((['git', 'symbolic-ref', 'HEAD'],), 'master')
  2056. ]
  2057. self.mock(git_cl, 'get_cl_statuses',
  2058. lambda branches, fine_grained, max_processes:
  2059. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  2060. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2061. (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
  2062. self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
  2063. def test_archive_no_tags(self):
  2064. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  2065. self.calls = [
  2066. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  2067. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  2068. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2069. ((['git', 'branch', '-D', 'foo'],), '')
  2070. ]
  2071. self.mock(git_cl, 'get_cl_statuses',
  2072. lambda branches, fine_grained, max_processes:
  2073. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  2074. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2075. (MockChangelistWithBranchAndIssue('bar', 789), 'open')])
  2076. self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
  2077. def test_cmd_issue_erase_existing(self):
  2078. out = StringIO.StringIO()
  2079. self.mock(git_cl.sys, 'stdout', out)
  2080. self.calls = [
  2081. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  2082. # Let this command raise exception (retcode=1) - it should be ignored.
  2083. ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
  2084. CERR1),
  2085. ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
  2086. ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
  2087. ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
  2088. ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
  2089. ''),
  2090. ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
  2091. ]
  2092. self.assertEqual(0, git_cl.main(['issue', '0']))
  2093. def test_cmd_issue_erase_existing_with_change_id(self):
  2094. out = StringIO.StringIO()
  2095. self.mock(git_cl.sys, 'stdout', out)
  2096. self.mock(git_cl.Changelist, 'GetDescription',
  2097. lambda _: 'This is a description\n\nChange-Id: Ideadbeef')
  2098. self.calls = [
  2099. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  2100. # Let this command raise exception (retcode=1) - it should be ignored.
  2101. ((['git', 'config', '--unset', 'branch.feature.last-upload-hash'],),
  2102. CERR1),
  2103. ((['git', 'config', '--unset', 'branch.feature.gerritissue'],), ''),
  2104. ((['git', 'config', '--unset', 'branch.feature.gerritpatchset'],), ''),
  2105. ((['git', 'config', '--unset', 'branch.feature.gerritserver'],), ''),
  2106. ((['git', 'config', '--unset', 'branch.feature.gerritsquashhash'],),
  2107. ''),
  2108. ((['git', 'log', '-1', '--format=%B'],),
  2109. 'This is a description\n\nChange-Id: Ideadbeef'),
  2110. ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
  2111. ]
  2112. self.assertEqual(0, git_cl.main(['issue', '0']))
  2113. def test_cmd_issue_json(self):
  2114. out = StringIO.StringIO()
  2115. self.mock(git_cl.sys, 'stdout', out)
  2116. self.calls = [
  2117. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  2118. ((['git', 'config', 'branch.feature.gerritissue'],), '123'),
  2119. ((['git', 'config', 'branch.feature.gerritserver'],),
  2120. 'https://chromium-review.googlesource.com'),
  2121. (('write_json', 'output.json',
  2122. {'issue': 123,
  2123. 'issue_url': 'https://chromium-review.googlesource.com/123'}),
  2124. ''),
  2125. ]
  2126. self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
  2127. def _common_GerritCommitMsgHookCheck(self):
  2128. self.mock(git_cl.sys, 'stdout', StringIO.StringIO())
  2129. self.mock(git_cl.os.path, 'abspath',
  2130. lambda path: self._mocked_call(['abspath', path]))
  2131. self.mock(git_cl.os.path, 'exists',
  2132. lambda path: self._mocked_call(['exists', path]))
  2133. self.mock(git_cl.gclient_utils, 'FileRead',
  2134. lambda path: self._mocked_call(['FileRead', path]))
  2135. self.mock(git_cl.gclient_utils, 'rm_file_or_tree',
  2136. lambda path: self._mocked_call(['rm_file_or_tree', path]))
  2137. self.calls = [
  2138. ((['git', 'rev-parse', '--show-cdup'],), '../'),
  2139. ((['abspath', '../'],), '/abs/git_repo_root'),
  2140. ]
  2141. return git_cl.Changelist(issue=123)
  2142. def test_GerritCommitMsgHookCheck_custom_hook(self):
  2143. cl = self._common_GerritCommitMsgHookCheck()
  2144. self.calls += [
  2145. ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
  2146. ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
  2147. '#!/bin/sh\necho "custom hook"')
  2148. ]
  2149. cl._GerritCommitMsgHookCheck(offer_removal=True)
  2150. def test_GerritCommitMsgHookCheck_not_exists(self):
  2151. cl = self._common_GerritCommitMsgHookCheck()
  2152. self.calls += [
  2153. ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), False),
  2154. ]
  2155. cl._GerritCommitMsgHookCheck(offer_removal=True)
  2156. def test_GerritCommitMsgHookCheck(self):
  2157. cl = self._common_GerritCommitMsgHookCheck()
  2158. self.calls += [
  2159. ((['exists', '/abs/git_repo_root/.git/hooks/commit-msg'],), True),
  2160. ((['FileRead', '/abs/git_repo_root/.git/hooks/commit-msg'],),
  2161. '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
  2162. (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
  2163. ((['rm_file_or_tree', '/abs/git_repo_root/.git/hooks/commit-msg'],),
  2164. ''),
  2165. ]
  2166. cl._GerritCommitMsgHookCheck(offer_removal=True)
  2167. def test_GerritCmdLand(self):
  2168. self.calls += [
  2169. ((['git', 'symbolic-ref', 'HEAD'],), 'feature'),
  2170. ((['git', 'config', 'branch.feature.gerritsquashhash'],),
  2171. 'deadbeaf'),
  2172. ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
  2173. ((['git', 'config', 'branch.feature.gerritserver'],),
  2174. 'chromium-review.googlesource.com'),
  2175. ]
  2176. cl = git_cl.Changelist(issue=123)
  2177. cl._GetChangeDetail = lambda *args, **kwargs: {
  2178. 'labels': {},
  2179. 'current_revision': 'deadbeaf',
  2180. }
  2181. cl._GetChangeCommit = lambda: {
  2182. 'commit': 'deadbeef',
  2183. 'web_links': [{'name': 'gitiles',
  2184. 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
  2185. }
  2186. cl.SubmitIssue = lambda wait_for_merge: None
  2187. out = StringIO.StringIO()
  2188. self.mock(sys, 'stdout', out)
  2189. self.assertEqual(0, cl.CMDLand(force=True,
  2190. bypass_hooks=True,
  2191. verbose=True,
  2192. parallel=False))
  2193. self.assertRegexpMatches(out.getvalue(), 'Issue.*123 has been submitted')
  2194. self.assertRegexpMatches(out.getvalue(), 'Landed as: .*deadbeef')
  2195. def _mock_gerrit_changes_for_detail_cache(self):
  2196. self.mock(git_cl.Changelist, '_GetGerritHost', lambda _: 'host')
  2197. def test_gerrit_change_detail_cache_simple(self):
  2198. self._mock_gerrit_changes_for_detail_cache()
  2199. self.calls = [
  2200. (('GetChangeDetail', 'host', 'my%2Frepo~1', []), 'a'),
  2201. (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b'),
  2202. (('GetChangeDetail', 'host', 'ab%2Frepo~2', []), 'b2'),
  2203. ]
  2204. cl1 = git_cl.Changelist(issue=1)
  2205. cl1._cached_remote_url = (
  2206. True, 'https://chromium.googlesource.com/a/my/repo.git/')
  2207. cl2 = git_cl.Changelist(issue=2)
  2208. cl2._cached_remote_url = (
  2209. True, 'https://chromium.googlesource.com/ab/repo')
  2210. self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
  2211. self.assertEqual(cl1._GetChangeDetail(), 'a')
  2212. self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
  2213. self.assertEqual(cl2._GetChangeDetail(no_cache=True), 'b2') # Miss.
  2214. self.assertEqual(cl1._GetChangeDetail(), 'a')
  2215. self.assertEqual(cl2._GetChangeDetail(), 'b2')
  2216. def test_gerrit_change_detail_cache_options(self):
  2217. self._mock_gerrit_changes_for_detail_cache()
  2218. self.calls = [
  2219. (('GetChangeDetail', 'host', 'repo~1', ['C', 'A', 'B']), 'cab'),
  2220. (('GetChangeDetail', 'host', 'repo~1', ['A', 'D']), 'ad'),
  2221. (('GetChangeDetail', 'host', 'repo~1', ['A']), 'a'), # no_cache=True
  2222. # no longer in cache.
  2223. (('GetChangeDetail', 'host', 'repo~1', ['B']), 'b'),
  2224. ]
  2225. cl = git_cl.Changelist(issue=1)
  2226. cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
  2227. self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
  2228. self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
  2229. self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
  2230. self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
  2231. self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
  2232. self.assertEqual(cl._GetChangeDetail(), 'cab')
  2233. self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
  2234. self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
  2235. self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
  2236. self.assertEqual(cl._GetChangeDetail(), 'cab')
  2237. # Finally, no_cache should invalidate all caches for given change.
  2238. self.assertEqual(cl._GetChangeDetail(options=['A'], no_cache=True), 'a')
  2239. self.assertEqual(cl._GetChangeDetail(options=['B']), 'b')
  2240. def test_gerrit_description_caching(self):
  2241. def gen_detail(rev, desc):
  2242. return {
  2243. 'current_revision': rev,
  2244. 'revisions': {rev: {'commit': {'message': desc}}}
  2245. }
  2246. self.calls = [
  2247. (('GetChangeDetail', 'host', 'my%2Frepo~1',
  2248. ['CURRENT_REVISION', 'CURRENT_COMMIT']),
  2249. gen_detail('rev1', 'desc1')),
  2250. (('GetChangeDetail', 'host', 'my%2Frepo~1',
  2251. ['CURRENT_REVISION', 'CURRENT_COMMIT']),
  2252. gen_detail('rev2', 'desc2')),
  2253. ]
  2254. self._mock_gerrit_changes_for_detail_cache()
  2255. cl = git_cl.Changelist(issue=1)
  2256. cl._cached_remote_url = (
  2257. True, 'https://chromium.googlesource.com/a/my/repo.git/')
  2258. self.assertEqual(cl.GetDescription(), 'desc1')
  2259. self.assertEqual(cl.GetDescription(), 'desc1') # cache hit.
  2260. self.assertEqual(cl.GetDescription(force=True), 'desc2')
  2261. def test_print_current_creds(self):
  2262. class CookiesAuthenticatorMock(object):
  2263. def __init__(self):
  2264. self.gitcookies = {
  2265. 'host.googlesource.com': ('user', 'pass'),
  2266. 'host-review.googlesource.com': ('user', 'pass'),
  2267. }
  2268. self.netrc = self
  2269. self.netrc.hosts = {
  2270. 'github.com': ('user2', None, 'pass2'),
  2271. 'host2.googlesource.com': ('user3', None, 'pass'),
  2272. }
  2273. self.mock(git_cl.gerrit_util, 'CookiesAuthenticator',
  2274. CookiesAuthenticatorMock)
  2275. self.mock(sys, 'stdout', StringIO.StringIO())
  2276. git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
  2277. self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
  2278. ' Host\t User\t Which file',
  2279. '============================\t=====\t===========',
  2280. 'host-review.googlesource.com\t user\t.gitcookies',
  2281. ' host.googlesource.com\t user\t.gitcookies',
  2282. ' host2.googlesource.com\tuser3\t .netrc',
  2283. ])
  2284. sys.stdout.buf = ''
  2285. git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
  2286. self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
  2287. ' Host\tUser\t Which file',
  2288. '============================\t====\t===========',
  2289. 'host-review.googlesource.com\tuser\t.gitcookies',
  2290. ' host.googlesource.com\tuser\t.gitcookies',
  2291. ])
  2292. def _common_creds_check_mocks(self):
  2293. def exists_mock(path):
  2294. dirname = os.path.dirname(path)
  2295. if dirname == os.path.expanduser('~'):
  2296. dirname = '~'
  2297. base = os.path.basename(path)
  2298. if base in ('.netrc', '.gitcookies'):
  2299. return self._mocked_call('os.path.exists', '%s/%s' % (dirname, base))
  2300. # git cl also checks for existence other files not relevant to this test.
  2301. return None
  2302. self.mock(os.path, 'exists', exists_mock)
  2303. self.mock(sys, 'stdout', StringIO.StringIO())
  2304. def test_creds_check_gitcookies_not_configured(self):
  2305. self._common_creds_check_mocks()
  2306. self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
  2307. lambda _, include_netrc=False: [])
  2308. self.calls = [
  2309. ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
  2310. ((['git', 'config', '--global', 'http.cookiefile'],), CERR1),
  2311. (('os.path.exists', '~/.netrc'), True),
  2312. (('ask_for_data', 'Press Enter to setup .gitcookies, '
  2313. 'or Ctrl+C to abort'), ''),
  2314. ((['git', 'config', '--global', 'http.cookiefile',
  2315. os.path.expanduser('~/.gitcookies')], ), ''),
  2316. ]
  2317. self.assertEqual(0, git_cl.main(['creds-check']))
  2318. self.assertRegexpMatches(
  2319. sys.stdout.getvalue(),
  2320. '^You seem to be using outdated .netrc for git credentials:')
  2321. self.assertRegexpMatches(
  2322. sys.stdout.getvalue(),
  2323. '\nConfigured git to use .gitcookies from')
  2324. def test_creds_check_gitcookies_configured_custom_broken(self):
  2325. self._common_creds_check_mocks()
  2326. self.mock(git_cl._GitCookiesChecker, 'get_hosts_with_creds',
  2327. lambda _, include_netrc=False: [])
  2328. self.calls = [
  2329. ((['git', 'config', '--path', 'http.cookiefile'],), CERR1),
  2330. ((['git', 'config', '--global', 'http.cookiefile'],),
  2331. '/custom/.gitcookies'),
  2332. (('os.path.exists', '/custom/.gitcookies'), False),
  2333. (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
  2334. 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
  2335. ((['git', 'config', '--global', 'http.cookiefile',
  2336. os.path.expanduser('~/.gitcookies')], ), ''),
  2337. ]
  2338. self.assertEqual(0, git_cl.main(['creds-check']))
  2339. self.assertRegexpMatches(
  2340. sys.stdout.getvalue(),
  2341. 'WARNING: You have configured custom path to .gitcookies: ')
  2342. self.assertRegexpMatches(
  2343. sys.stdout.getvalue(),
  2344. 'However, your configured .gitcookies file is missing.')
  2345. def test_git_cl_comment_add_gerrit(self):
  2346. self.mock(git_cl.gerrit_util, 'SetReview',
  2347. lambda host, change, msg, ready:
  2348. self._mocked_call('SetReview', host, change, msg, ready))
  2349. self.calls = [
  2350. ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
  2351. ((['git', 'symbolic-ref', 'HEAD'],), CERR1),
  2352. ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
  2353. ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
  2354. 'origin/master'),
  2355. ((['git', 'config', 'remote.origin.url'],),
  2356. 'https://chromium.googlesource.com/infra/infra'),
  2357. (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
  2358. 'msg', None),
  2359. None),
  2360. ]
  2361. self.assertEqual(0, git_cl.main(['comment', '--gerrit', '-i', '10',
  2362. '-a', 'msg']))
  2363. def test_git_cl_comments_fetch_gerrit(self):
  2364. self.mock(sys, 'stdout', StringIO.StringIO())
  2365. self.calls = [
  2366. ((['git', 'config', 'branch.foo.gerritserver'],), ''),
  2367. ((['git', 'config', 'branch.foo.merge'],), ''),
  2368. ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
  2369. ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
  2370. 'origin/master'),
  2371. ((['git', 'config', 'remote.origin.url'],),
  2372. 'https://chromium.googlesource.com/infra/infra'),
  2373. (('GetChangeDetail', 'chromium-review.googlesource.com',
  2374. 'infra%2Finfra~1',
  2375. ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
  2376. 'CURRENT_COMMIT']), {
  2377. 'owner': {'email': 'owner@example.com'},
  2378. 'current_revision': 'ba5eba11',
  2379. 'revisions': {
  2380. 'deadbeaf': {
  2381. '_number': 1,
  2382. },
  2383. 'ba5eba11': {
  2384. '_number': 2,
  2385. },
  2386. },
  2387. 'messages': [
  2388. {
  2389. u'_revision_number': 1,
  2390. u'author': {
  2391. u'_account_id': 1111084,
  2392. u'email': u'commit-bot@chromium.org',
  2393. u'name': u'Commit Bot'
  2394. },
  2395. u'date': u'2017-03-15 20:08:45.000000000',
  2396. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
  2397. u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
  2398. u'tag': u'autogenerated:cq:dry-run'
  2399. },
  2400. {
  2401. u'_revision_number': 2,
  2402. u'author': {
  2403. u'_account_id': 11151243,
  2404. u'email': u'owner@example.com',
  2405. u'name': u'owner'
  2406. },
  2407. u'date': u'2017-03-16 20:00:41.000000000',
  2408. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2409. u'message': u'PTAL',
  2410. },
  2411. {
  2412. u'_revision_number': 2,
  2413. u'author': {
  2414. u'_account_id': 148512,
  2415. u'email': u'reviewer@example.com',
  2416. u'name': u'reviewer'
  2417. },
  2418. u'date': u'2017-03-17 05:19:37.500000000',
  2419. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
  2420. u'message': u'Patch Set 2: Code-Review+1',
  2421. },
  2422. ]
  2423. }),
  2424. (('GetChangeComments', 'chromium-review.googlesource.com',
  2425. 'infra%2Finfra~1'), {
  2426. '/COMMIT_MSG': [
  2427. {
  2428. 'author': {'email': u'reviewer@example.com'},
  2429. 'updated': u'2017-03-17 05:19:37.500000000',
  2430. 'patch_set': 2,
  2431. 'side': 'REVISION',
  2432. 'message': 'Please include a bug link',
  2433. },
  2434. ],
  2435. 'codereview.settings': [
  2436. {
  2437. 'author': {'email': u'owner@example.com'},
  2438. 'updated': u'2017-03-16 20:00:41.000000000',
  2439. 'patch_set': 2,
  2440. 'side': 'PARENT',
  2441. 'line': 42,
  2442. 'message': 'I removed this because it is bad',
  2443. },
  2444. ]
  2445. }),
  2446. (('GetChangeRobotComments', 'chromium-review.googlesource.com',
  2447. 'infra%2Finfra~1'), {}),
  2448. ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
  2449. ] * 2 + [
  2450. (('write_json', 'output.json', [
  2451. {
  2452. u'date': u'2017-03-16 20:00:41.000000',
  2453. u'message': (
  2454. u'PTAL\n' +
  2455. u'\n' +
  2456. u'codereview.settings\n' +
  2457. u' Base, Line 42: https://chromium-review.googlesource.com/' +
  2458. u'c/1/2/codereview.settings#b42\n' +
  2459. u' I removed this because it is bad\n'),
  2460. u'autogenerated': False,
  2461. u'approval': False,
  2462. u'disapproval': False,
  2463. u'sender': u'owner@example.com'
  2464. }, {
  2465. u'date': u'2017-03-17 05:19:37.500000',
  2466. u'message': (
  2467. u'Patch Set 2: Code-Review+1\n' +
  2468. u'\n' +
  2469. u'/COMMIT_MSG\n' +
  2470. u' PS2, File comment: https://chromium-review.googlesource' +
  2471. u'.com/c/1/2//COMMIT_MSG#\n' +
  2472. u' Please include a bug link\n'),
  2473. u'autogenerated': False,
  2474. u'approval': False,
  2475. u'disapproval': False,
  2476. u'sender': u'reviewer@example.com'
  2477. }
  2478. ]), '')
  2479. ]
  2480. expected_comments_summary = [
  2481. git_cl._CommentSummary(
  2482. message=(
  2483. u'PTAL\n' +
  2484. u'\n' +
  2485. u'codereview.settings\n' +
  2486. u' Base, Line 42: https://chromium-review.googlesource.com/' +
  2487. u'c/1/2/codereview.settings#b42\n' +
  2488. u' I removed this because it is bad\n'),
  2489. date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
  2490. autogenerated=False,
  2491. disapproval=False, approval=False, sender=u'owner@example.com'),
  2492. git_cl._CommentSummary(
  2493. message=(
  2494. u'Patch Set 2: Code-Review+1\n' +
  2495. u'\n' +
  2496. u'/COMMIT_MSG\n' +
  2497. u' PS2, File comment: https://chromium-review.googlesource.com/' +
  2498. u'c/1/2//COMMIT_MSG#\n' +
  2499. u' Please include a bug link\n'),
  2500. date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
  2501. autogenerated=False,
  2502. disapproval=False, approval=False, sender=u'reviewer@example.com'),
  2503. ]
  2504. cl = git_cl.Changelist(
  2505. issue=1, branchref='refs/heads/foo')
  2506. self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
  2507. self.mock(git_cl.Changelist, 'GetBranch', lambda _: 'foo')
  2508. self.assertEqual(
  2509. 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
  2510. def test_git_cl_comments_robot_comments(self):
  2511. # git cl comments also fetches robot comments (which are considered a type
  2512. # of autogenerated comment), and unlike other types of comments, only robot
  2513. # comments from the latest patchset are shown.
  2514. self.mock(sys, 'stdout', StringIO.StringIO())
  2515. self.calls = [
  2516. ((['git', 'config', 'branch.foo.gerritserver'],), ''),
  2517. ((['git', 'config', 'branch.foo.merge'],), ''),
  2518. ((['git', 'config', 'rietveld.upstream-branch'],), CERR1),
  2519. ((['git', 'branch', '-r'],), 'origin/HEAD -> origin/master\n'
  2520. 'origin/master'),
  2521. ((['git', 'config', 'remote.origin.url'],),
  2522. 'https://chromium.googlesource.com/infra/infra'),
  2523. (('GetChangeDetail', 'chromium-review.googlesource.com',
  2524. 'infra%2Finfra~1',
  2525. ['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION',
  2526. 'CURRENT_COMMIT']), {
  2527. 'owner': {'email': 'owner@example.com'},
  2528. 'current_revision': 'ba5eba11',
  2529. 'revisions': {
  2530. 'deadbeaf': {
  2531. '_number': 1,
  2532. },
  2533. 'ba5eba11': {
  2534. '_number': 2,
  2535. },
  2536. },
  2537. 'messages': [
  2538. {
  2539. u'_revision_number': 1,
  2540. u'author': {
  2541. u'_account_id': 1111084,
  2542. u'email': u'commit-bot@chromium.org',
  2543. u'name': u'Commit Bot'
  2544. },
  2545. u'date': u'2017-03-15 20:08:45.000000000',
  2546. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
  2547. u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
  2548. u'tag': u'autogenerated:cq:dry-run'
  2549. },
  2550. {
  2551. u'_revision_number': 1,
  2552. u'author': {
  2553. u'_account_id': 123,
  2554. u'email': u'tricium@serviceaccount.com',
  2555. u'name': u'Tricium'
  2556. },
  2557. u'date': u'2017-03-16 20:00:41.000000000',
  2558. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2559. u'message': u'(1 comment)',
  2560. u'tag': u'autogenerated:tricium',
  2561. },
  2562. {
  2563. u'_revision_number': 1,
  2564. u'author': {
  2565. u'_account_id': 123,
  2566. u'email': u'tricium@serviceaccount.com',
  2567. u'name': u'Tricium'
  2568. },
  2569. u'date': u'2017-03-16 20:00:41.000000000',
  2570. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2571. u'message': u'(1 comment)',
  2572. u'tag': u'autogenerated:tricium',
  2573. },
  2574. {
  2575. u'_revision_number': 2,
  2576. u'author': {
  2577. u'_account_id': 123,
  2578. u'email': u'tricium@serviceaccount.com',
  2579. u'name': u'reviewer'
  2580. },
  2581. u'date': u'2017-03-17 05:30:37.000000000',
  2582. u'tag': u'autogenerated:tricium',
  2583. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
  2584. u'message': u'(1 comment)',
  2585. },
  2586. ]
  2587. }),
  2588. (('GetChangeComments', 'chromium-review.googlesource.com',
  2589. 'infra%2Finfra~1'), {}),
  2590. (('GetChangeRobotComments', 'chromium-review.googlesource.com',
  2591. 'infra%2Finfra~1'), {
  2592. 'codereview.settings': [
  2593. {
  2594. u'author': {u'email': u'tricium@serviceaccount.com'},
  2595. u'updated': u'2017-03-17 05:30:37.000000000',
  2596. u'robot_run_id': u'5565031076855808',
  2597. u'robot_id': u'Linter/Category',
  2598. u'tag': u'autogenerated:tricium',
  2599. u'patch_set': 2,
  2600. u'side': u'REVISION',
  2601. u'message': u'Linter warning message text',
  2602. u'line': 32,
  2603. },
  2604. ],
  2605. }),
  2606. ((['git', 'config', 'branch.foo.gerritpatchset', '2'],), ''),
  2607. ]
  2608. expected_comments_summary = [
  2609. git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
  2610. message=(
  2611. u'(1 comment)\n\ncodereview.settings\n'
  2612. u' PS2, Line 32: https://chromium-review.googlesource.com/'
  2613. u'c/1/2/codereview.settings#32\n'
  2614. u' Linter warning message text\n'),
  2615. sender=u'tricium@serviceaccount.com',
  2616. autogenerated=True, approval=False, disapproval=False)
  2617. ]
  2618. cl = git_cl.Changelist(
  2619. issue=1, branchref='refs/heads/foo')
  2620. self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
  2621. def test_get_remote_url_with_mirror(self):
  2622. original_os_path_isdir = os.path.isdir
  2623. def selective_os_path_isdir_mock(path):
  2624. if path == '/cache/this-dir-exists':
  2625. return self._mocked_call('os.path.isdir', path)
  2626. return original_os_path_isdir(path)
  2627. self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
  2628. url = 'https://chromium.googlesource.com/my/repo'
  2629. self.calls = [
  2630. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2631. ((['git', 'config', 'branch.master.merge'],), 'master'),
  2632. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  2633. ((['git', 'config', 'remote.origin.url'],),
  2634. '/cache/this-dir-exists'),
  2635. (('os.path.isdir', '/cache/this-dir-exists'),
  2636. True),
  2637. # Runs in /cache/this-dir-exists.
  2638. ((['git', 'config', 'remote.origin.url'],),
  2639. url),
  2640. ]
  2641. cl = git_cl.Changelist(issue=1)
  2642. self.assertEqual(cl.GetRemoteUrl(), url)
  2643. self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
  2644. def test_get_remote_url_non_existing_mirror(self):
  2645. original_os_path_isdir = os.path.isdir
  2646. def selective_os_path_isdir_mock(path):
  2647. if path == '/cache/this-dir-doesnt-exist':
  2648. return self._mocked_call('os.path.isdir', path)
  2649. return original_os_path_isdir(path)
  2650. self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
  2651. self.mock(logging, 'error',
  2652. lambda fmt, *a: self._mocked_call('logging.error', fmt % a))
  2653. self.calls = [
  2654. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2655. ((['git', 'config', 'branch.master.merge'],), 'master'),
  2656. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  2657. ((['git', 'config', 'remote.origin.url'],),
  2658. '/cache/this-dir-doesnt-exist'),
  2659. (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
  2660. False),
  2661. (('logging.error',
  2662. 'Remote "origin" for branch "master" points to'
  2663. ' "/cache/this-dir-doesnt-exist", but it doesn\'t exist.'), None),
  2664. ]
  2665. cl = git_cl.Changelist(issue=1)
  2666. self.assertIsNone(cl.GetRemoteUrl())
  2667. def test_get_remote_url_misconfigured_mirror(self):
  2668. original_os_path_isdir = os.path.isdir
  2669. def selective_os_path_isdir_mock(path):
  2670. if path == '/cache/this-dir-exists':
  2671. return self._mocked_call('os.path.isdir', path)
  2672. return original_os_path_isdir(path)
  2673. self.mock(os.path, 'isdir', selective_os_path_isdir_mock)
  2674. self.mock(logging, 'error',
  2675. lambda *a: self._mocked_call('logging.error', *a))
  2676. self.calls = [
  2677. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2678. ((['git', 'config', 'branch.master.merge'],), 'master'),
  2679. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  2680. ((['git', 'config', 'remote.origin.url'],),
  2681. '/cache/this-dir-exists'),
  2682. (('os.path.isdir', '/cache/this-dir-exists'), True),
  2683. # Runs in /cache/this-dir-exists.
  2684. ((['git', 'config', 'remote.origin.url'],), ''),
  2685. (('logging.error',
  2686. 'Remote "%(remote)s" for branch "%(branch)s" points to '
  2687. '"%(cache_path)s", but it is misconfigured.\n'
  2688. '"%(cache_path)s" must be a git repo and must have a remote named '
  2689. '"%(remote)s" pointing to the git host.', {
  2690. 'remote': 'origin',
  2691. 'cache_path': '/cache/this-dir-exists',
  2692. 'branch': 'master'}
  2693. ), None),
  2694. ]
  2695. cl = git_cl.Changelist(issue=1)
  2696. self.assertIsNone(cl.GetRemoteUrl())
  2697. def test_gerrit_change_identifier_with_project(self):
  2698. self.calls = [
  2699. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2700. ((['git', 'config', 'branch.master.merge'],), 'master'),
  2701. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  2702. ((['git', 'config', 'remote.origin.url'],),
  2703. 'https://chromium.googlesource.com/a/my/repo.git/'),
  2704. ]
  2705. cl = git_cl.Changelist(issue=123456)
  2706. self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
  2707. def test_gerrit_change_identifier_without_project(self):
  2708. self.calls = [
  2709. ((['git', 'symbolic-ref', 'HEAD'],), 'master'),
  2710. ((['git', 'config', 'branch.master.merge'],), 'master'),
  2711. ((['git', 'config', 'branch.master.remote'],), 'origin'),
  2712. ((['git', 'config', 'remote.origin.url'],), CERR1),
  2713. ]
  2714. cl = git_cl.Changelist(issue=123456)
  2715. self.assertEqual(cl._GerritChangeIdentifier(), '123456')
  2716. class CMDTestCaseBase(unittest.TestCase):
  2717. _STATUSES = [
  2718. 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
  2719. 'INFRA_FAILURE', 'CANCELED',
  2720. ]
  2721. _CHANGE_DETAIL = {
  2722. 'project': 'depot_tools',
  2723. 'status': 'OPEN',
  2724. 'owner': {'email': 'owner@e.mail'},
  2725. 'current_revision': 'beeeeeef',
  2726. 'revisions': {
  2727. 'deadbeaf': {'_number': 6},
  2728. 'beeeeeef': {
  2729. '_number': 7,
  2730. 'fetch': {'http': {
  2731. 'url': 'https://chromium.googlesource.com/depot_tools',
  2732. 'ref': 'refs/changes/56/123456/7'
  2733. }},
  2734. },
  2735. },
  2736. }
  2737. _DEFAULT_RESPONSE = {
  2738. 'builds': [
  2739. {
  2740. 'id': str(100 + idx),
  2741. 'builder': {
  2742. 'project': 'chromium',
  2743. 'bucket': 'try',
  2744. 'builder': 'bot_' + status.lower(),
  2745. },
  2746. 'status': status,
  2747. }
  2748. for idx, status in enumerate(_STATUSES)
  2749. ]
  2750. }
  2751. def setUp(self):
  2752. super(CMDTestCaseBase, self).setUp()
  2753. mock.patch('git_cl.sys.stdout', StringIO.StringIO()).start()
  2754. mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
  2755. mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
  2756. mock.patch('git_cl.Changelist.GetCodereviewServer',
  2757. return_value='https://chromium-review.googlesource.com').start()
  2758. mock.patch('git_cl.Changelist.GetMostRecentPatchset',
  2759. return_value=7).start()
  2760. mock.patch('git_cl.auth.get_authenticator',
  2761. return_value=AuthenticatorMock()).start()
  2762. mock.patch('git_cl.Changelist._GetChangeDetail',
  2763. return_value=self._CHANGE_DETAIL).start()
  2764. mock.patch('git_cl._call_buildbucket',
  2765. return_value = self._DEFAULT_RESPONSE).start()
  2766. mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
  2767. self.addCleanup(mock.patch.stopall)
  2768. class CMDTryResultsTestCase(CMDTestCaseBase):
  2769. _DEFAULT_REQUEST = {
  2770. 'predicate': {
  2771. "gerritChanges": [{
  2772. "project": "depot_tools",
  2773. "host": "chromium-review.googlesource.com",
  2774. "patchset": 7,
  2775. "change": 123456,
  2776. }],
  2777. },
  2778. 'fields': 'builds.*.id,builds.*.builder,builds.*.status',
  2779. }
  2780. def testNoJobs(self):
  2781. git_cl._call_buildbucket.return_value = {}
  2782. self.assertEqual(0, git_cl.main(['try-results']))
  2783. self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
  2784. git_cl._call_buildbucket.assert_called_once_with(
  2785. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2786. self._DEFAULT_REQUEST)
  2787. def testPrintToStdout(self):
  2788. self.assertEqual(0, git_cl.main(['try-results']))
  2789. self.assertEqual([
  2790. 'Successes:',
  2791. ' bot_success https://ci.chromium.org/b/103',
  2792. 'Infra Failures:',
  2793. ' bot_infra_failure https://ci.chromium.org/b/105',
  2794. 'Failures:',
  2795. ' bot_failure https://ci.chromium.org/b/104',
  2796. 'Canceled:',
  2797. ' bot_canceled ',
  2798. 'Started:',
  2799. ' bot_started https://ci.chromium.org/b/102',
  2800. 'Scheduled:',
  2801. ' bot_scheduled id=101',
  2802. 'Other:',
  2803. ' bot_status_unspecified id=100',
  2804. 'Total: 7 tryjobs',
  2805. ], sys.stdout.getvalue().splitlines())
  2806. git_cl._call_buildbucket.assert_called_once_with(
  2807. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2808. self._DEFAULT_REQUEST)
  2809. def testPrintToStdoutWithMasters(self):
  2810. self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
  2811. self.assertEqual([
  2812. 'Successes:',
  2813. ' try bot_success https://ci.chromium.org/b/103',
  2814. 'Infra Failures:',
  2815. ' try bot_infra_failure https://ci.chromium.org/b/105',
  2816. 'Failures:',
  2817. ' try bot_failure https://ci.chromium.org/b/104',
  2818. 'Canceled:',
  2819. ' try bot_canceled ',
  2820. 'Started:',
  2821. ' try bot_started https://ci.chromium.org/b/102',
  2822. 'Scheduled:',
  2823. ' try bot_scheduled id=101',
  2824. 'Other:',
  2825. ' try bot_status_unspecified id=100',
  2826. 'Total: 7 tryjobs',
  2827. ], sys.stdout.getvalue().splitlines())
  2828. git_cl._call_buildbucket.assert_called_once_with(
  2829. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2830. self._DEFAULT_REQUEST)
  2831. @mock.patch('git_cl.write_json')
  2832. def testWriteToJson(self, mockJsonDump):
  2833. self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
  2834. git_cl._call_buildbucket.assert_called_once_with(
  2835. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2836. self._DEFAULT_REQUEST)
  2837. mockJsonDump.assert_called_once_with(
  2838. 'file.json', self._DEFAULT_RESPONSE['builds'])
  2839. def test_filter_failed(self):
  2840. self.assertEqual({}, git_cl._filter_failed([]))
  2841. self.assertEqual({
  2842. 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
  2843. }, git_cl._filter_failed(self._DEFAULT_RESPONSE['builds']))
  2844. class CMDTryTestCase(CMDTestCaseBase):
  2845. @mock.patch('git_cl.Changelist.SetCQState')
  2846. @mock.patch('git_cl._get_bucket_map', return_value={})
  2847. def testSetCQDryRunByDefault(self, _mockGetBucketMap, mockSetCQState):
  2848. mockSetCQState.return_value = 0
  2849. self.assertEqual(0, git_cl.main(['try']))
  2850. git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
  2851. self.assertEqual(
  2852. sys.stdout.getvalue(),
  2853. 'Scheduling CQ dry run on: '
  2854. 'https://chromium-review.googlesource.com/123456\n')
  2855. @mock.patch('git_cl._call_buildbucket')
  2856. def testScheduleOnBuildbucket(self, mockCallBuildbucket):
  2857. mockCallBuildbucket.return_value = {}
  2858. self.assertEqual(0, git_cl.main([
  2859. 'try', '-B', 'luci.chromium.try', '-b', 'win',
  2860. '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
  2861. self.assertIn(
  2862. 'Scheduling jobs on:\nBucket: luci.chromium.try',
  2863. git_cl.sys.stdout.getvalue())
  2864. expected_request = {
  2865. "requests": [{
  2866. "scheduleBuild": {
  2867. "requestId": "uuid4",
  2868. "builder": {
  2869. "project": "chromium",
  2870. "builder": "win",
  2871. "bucket": "try",
  2872. },
  2873. "gerritChanges": [{
  2874. "project": "depot_tools",
  2875. "host": "chromium-review.googlesource.com",
  2876. "patchset": 7,
  2877. "change": 123456,
  2878. }],
  2879. "properties": {
  2880. "category": "git_cl_try",
  2881. "json": [{"a": 1}, None],
  2882. "key": "val",
  2883. },
  2884. "tags": [
  2885. {"value": "win", "key": "builder"},
  2886. {"value": "git_cl_try", "key": "user_agent"},
  2887. ],
  2888. },
  2889. }],
  2890. }
  2891. mockCallBuildbucket.assert_called_with(
  2892. mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
  2893. def testScheduleOnBuildbucket_WrongBucket(self):
  2894. self.assertEqual(0, git_cl.main([
  2895. 'try', '-B', 'not-a-bucket', '-b', 'win',
  2896. '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
  2897. self.assertIn(
  2898. 'WARNING Could not parse bucket "not-a-bucket". Skipping.',
  2899. git_cl.sys.stdout.getvalue())
  2900. @mock.patch('git_cl._call_buildbucket')
  2901. @mock.patch('git_cl.fetch_try_jobs')
  2902. def testScheduleOnBuildbucketRetryFailed(
  2903. self, mockFetchTryJobs, mockCallBuildbucket):
  2904. git_cl.fetch_try_jobs.side_effect = lambda *_, **kw: {
  2905. 7: [],
  2906. 6: [{
  2907. 'id': 112112,
  2908. 'builder': {
  2909. 'project': 'chromium',
  2910. 'bucket': 'try',
  2911. 'builder': 'linux',
  2912. },
  2913. 'status': 'FAILURE',
  2914. }],
  2915. }[kw['patchset']]
  2916. mockCallBuildbucket.return_value = {}
  2917. self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
  2918. self.assertIn(
  2919. 'Scheduling jobs on:\nBucket: chromium/try',
  2920. git_cl.sys.stdout.getvalue())
  2921. expected_request = {
  2922. "requests": [{
  2923. "scheduleBuild": {
  2924. "requestId": "uuid4",
  2925. "builder": {
  2926. "project": "chromium",
  2927. "bucket": "try",
  2928. "builder": "linux",
  2929. },
  2930. "gerritChanges": [{
  2931. "project": "depot_tools",
  2932. "host": "chromium-review.googlesource.com",
  2933. "patchset": 7,
  2934. "change": 123456,
  2935. }],
  2936. "properties": {
  2937. "category": "git_cl_try",
  2938. },
  2939. "tags": [
  2940. {"value": "linux", "key": "builder"},
  2941. {"value": "git_cl_try", "key": "user_agent"},
  2942. {"value": "1", "key": "retry_failed"},
  2943. ],
  2944. },
  2945. }],
  2946. }
  2947. mockCallBuildbucket.assert_called_with(
  2948. mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
  2949. def test_parse_bucket(self):
  2950. test_cases = [
  2951. {
  2952. 'bucket': 'chromium/try',
  2953. 'result': ('chromium', 'try'),
  2954. },
  2955. {
  2956. 'bucket': 'luci.chromium.try',
  2957. 'result': ('chromium', 'try'),
  2958. 'has_warning': True,
  2959. },
  2960. {
  2961. 'bucket': 'skia.primary',
  2962. 'result': ('skia', 'skia.primary'),
  2963. 'has_warning': True,
  2964. },
  2965. {
  2966. 'bucket': 'not-a-bucket',
  2967. 'result': (None, None),
  2968. },
  2969. ]
  2970. for test_case in test_cases:
  2971. git_cl.sys.stdout.truncate(0)
  2972. self.assertEqual(
  2973. test_case['result'], git_cl._parse_bucket(test_case['bucket']))
  2974. if test_case.get('has_warning'):
  2975. expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
  2976. test_case['result'])
  2977. self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
  2978. class CMDUploadTestCase(CMDTestCaseBase):
  2979. def setUp(self):
  2980. super(CMDUploadTestCase, self).setUp()
  2981. mock.patch('git_cl.fetch_try_jobs').start()
  2982. mock.patch('git_cl._trigger_try_jobs', return_value={}).start()
  2983. mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
  2984. self.addCleanup(mock.patch.stopall)
  2985. def testUploadRetryFailed(self):
  2986. # This test mocks out the actual upload part, and just asserts that after
  2987. # upload, if --retry-failed is added, then the tool will fetch try jobs
  2988. # from the previous patchset and trigger the right builders on the latest
  2989. # patchset.
  2990. git_cl.fetch_try_jobs.side_effect = [
  2991. # Latest patchset: No builds.
  2992. [],
  2993. # Patchset before latest: Some builds.
  2994. [
  2995. {
  2996. 'id': str(100 + idx),
  2997. 'builder': {
  2998. 'project': 'chromium',
  2999. 'bucket': 'try',
  3000. 'builder': 'bot_' + status.lower(),
  3001. },
  3002. 'status': status,
  3003. }
  3004. for idx, status in enumerate(self._STATUSES)
  3005. ],
  3006. ]
  3007. self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
  3008. self.assertEqual([
  3009. mock.call(mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
  3010. mock.call(mock.ANY, mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
  3011. ], git_cl.fetch_try_jobs.mock_calls)
  3012. expected_buckets = {
  3013. 'chromium/try': {'bot_failure': [], 'bot_infra_failure': []},
  3014. }
  3015. git_cl._trigger_try_jobs.assert_called_once_with(
  3016. mock.ANY, mock.ANY, expected_buckets, mock.ANY, 8)
  3017. if __name__ == '__main__':
  3018. logging.basicConfig(
  3019. level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
  3020. unittest.main()