git_cl_test.py 125 KB

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