git_cl_test.py 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472
  1. #!/usr/bin/env vpython3
  2. # coding=utf-8
  3. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """Unit tests for git_cl.py."""
  7. import codecs
  8. import datetime
  9. import json
  10. import logging
  11. import multiprocessing
  12. import optparse
  13. import os
  14. import io
  15. import shutil
  16. import sys
  17. import tempfile
  18. import unittest
  19. from unittest import mock
  20. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  21. import scm_mock
  22. import metrics
  23. import metrics_utils
  24. # We have to disable monitoring before importing git_cl.
  25. metrics_utils.COLLECT_METRICS = False
  26. import clang_format
  27. import contextlib
  28. import gclient_utils
  29. import gerrit_util
  30. import git_cl
  31. import git_common
  32. import git_footers
  33. import git_new_branch
  34. import owners_client
  35. import scm
  36. import subprocess2
  37. # TODO: Should fix these warnings.
  38. # pylint: disable=line-too-long
  39. def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
  40. return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
  41. CERR1 = callError(1)
  42. class TemporaryFileMock(object):
  43. def __init__(self):
  44. self.suffix = 0
  45. @contextlib.contextmanager
  46. def __call__(self):
  47. self.suffix += 1
  48. yield '/tmp/fake-temp' + str(self.suffix)
  49. class ChangelistMock(object):
  50. # A class variable so we can access it when we don't have access to the
  51. # instance that's being set.
  52. desc = ''
  53. def __init__(self, gerrit_change=None, use_python3=False, **kwargs):
  54. self._gerrit_change = gerrit_change
  55. self._use_python3 = use_python3
  56. def GetIssue(self):
  57. return 1
  58. def FetchDescription(self):
  59. return ChangelistMock.desc
  60. def UpdateDescription(self, desc, force=False):
  61. ChangelistMock.desc = desc
  62. def GetGerritChange(self, patchset=None, **kwargs):
  63. del patchset
  64. return self._gerrit_change
  65. def GetRemoteBranch(self):
  66. return ('origin', 'refs/remotes/origin/main')
  67. class WatchlistsMock(object):
  68. def __init__(self, _):
  69. pass
  70. @staticmethod
  71. def GetWatchersForPaths(_):
  72. return ['joe@example.com']
  73. class CodereviewSettingsFileMock(object):
  74. def __init__(self):
  75. pass
  76. # pylint: disable=no-self-use
  77. def read(self):
  78. return ('CODE_REVIEW_SERVER: gerrit.chromium.org\n' +
  79. 'GERRIT_HOST: True\n')
  80. class AuthenticatorMock(object):
  81. def __init__(self, *_args):
  82. pass
  83. def has_cached_credentials(self):
  84. return True
  85. def authorize(self, http):
  86. return http
  87. def CookiesAuthenticatorMockFactory(hosts_with_creds=None, same_auth=False):
  88. """Use to mock Gerrit/Git credentials from ~/.gitcookies.
  89. Usage:
  90. >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
  91. CookiesAuthenticatorMockFactory({'host': ('user', 'pass')})
  92. OR
  93. >>> self.mock(git_cl.gerrit_util, "CookiesAuthenticator",
  94. CookiesAuthenticatorMockFactory(
  95. same_auth=('user', 'pass'))
  96. """
  97. class CookiesAuthenticatorMock(git_cl.gerrit_util.CookiesAuthenticator):
  98. def __init__(self): # pylint: disable=super-init-not-called
  99. # Intentionally not calling super() because it reads actual cookie
  100. # files.
  101. pass
  102. @classmethod
  103. def get_gitcookies_path(cls):
  104. return os.path.join('~', '.gitcookies')
  105. def _get_auth_for_host(self, host):
  106. if same_auth:
  107. return same_auth
  108. return (hosts_with_creds or {}).get(host)
  109. return CookiesAuthenticatorMock
  110. class MockChangelistWithBranchAndIssue():
  111. def __init__(self, branch, issue):
  112. self.branch = branch
  113. self.issue = issue
  114. def GetBranch(self):
  115. return self.branch
  116. def GetIssue(self):
  117. return self.issue
  118. class SystemExitMock(Exception):
  119. pass
  120. class TestGitClBasic(unittest.TestCase):
  121. def setUp(self):
  122. mock.patch('sys.exit', side_effect=SystemExitMock).start()
  123. mock.patch('sys.stdout', io.StringIO()).start()
  124. mock.patch('sys.stderr', io.StringIO()).start()
  125. self.addCleanup(mock.patch.stopall)
  126. def test_die_with_error(self):
  127. with self.assertRaises(SystemExitMock):
  128. git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
  129. self.assertEqual(sys.stderr.getvalue(), 'foo\n')
  130. self.assertTrue('saving CL description' in sys.stdout.getvalue())
  131. self.assertTrue('Content of CL description' in sys.stdout.getvalue())
  132. self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
  133. sys.exit.assert_called_once_with(1)
  134. def test_die_with_error_no_desc(self):
  135. with self.assertRaises(SystemExitMock):
  136. git_cl.DieWithError('foo')
  137. self.assertEqual(sys.stderr.getvalue(), 'foo\n')
  138. self.assertEqual(sys.stdout.getvalue(), '')
  139. sys.exit.assert_called_once_with(1)
  140. def test_fetch_description(self):
  141. cl = git_cl.Changelist(issue=1, codereview_host='host')
  142. cl.description = 'x'
  143. self.assertEqual(cl.FetchDescription(), 'x')
  144. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  145. @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
  146. def test_get_cl_statuses(self, *_mocks):
  147. statuses = [
  148. 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting'
  149. ]
  150. changes = []
  151. for status in statuses:
  152. cl = git_cl.Changelist()
  153. cl.status = status
  154. changes.append(cl)
  155. actual = set(git_cl.get_cl_statuses(changes, True))
  156. self.assertEqual(set(zip(changes, statuses)), actual)
  157. def test_upload_to_non_default_branch_no_retry(self):
  158. m = mock.patch('git_cl.Changelist._CMDUploadChange',
  159. side_effect=[git_cl.GitPushError(), None]).start()
  160. mock.patch('git_cl.Changelist.GetRemoteBranch',
  161. return_value=('foo', 'bar')).start()
  162. mock.patch('git_cl.Changelist.GetGerritProject',
  163. return_value='foo').start()
  164. mock.patch('git_cl.gerrit_util.GetProjectHead',
  165. return_value='refs/heads/main').start()
  166. cl = git_cl.Changelist()
  167. options = optparse.Values()
  168. options.target_branch = 'refs/heads/bar'
  169. with self.assertRaises(SystemExitMock):
  170. cl.CMDUploadChange(options, [], 'foo',
  171. git_cl.ChangeDescription('bar'))
  172. # ensure upload is called once
  173. self.assertEqual(len(m.mock_calls), 1)
  174. sys.exit.assert_called_once_with(1)
  175. # option not set as retry didn't happen
  176. self.assertFalse(hasattr(options, 'force'))
  177. self.assertFalse(hasattr(options, 'edit_description'))
  178. def test_upload_to_meta_config_branch_no_retry(self):
  179. m = mock.patch('git_cl.Changelist._CMDUploadChange',
  180. side_effect=[git_cl.GitPushError(), None]).start()
  181. mock.patch('git_cl.Changelist.GetRemoteBranch',
  182. return_value=('foo', 'bar')).start()
  183. mock.patch('git_cl.Changelist.GetGerritProject',
  184. return_value='foo').start()
  185. mock.patch('git_cl.gerrit_util.GetProjectHead',
  186. return_value='refs/heads/main').start()
  187. cl = git_cl.Changelist()
  188. options = optparse.Values()
  189. options.target_branch = 'refs/meta/config'
  190. with self.assertRaises(SystemExitMock):
  191. cl.CMDUploadChange(options, [], 'foo',
  192. git_cl.ChangeDescription('bar'))
  193. # ensure upload is called once
  194. self.assertEqual(len(m.mock_calls), 1)
  195. sys.exit.assert_called_once_with(1)
  196. # option not set as retry didn't happen
  197. self.assertFalse(hasattr(options, 'force'))
  198. self.assertFalse(hasattr(options, 'edit_description'))
  199. def test_upload_to_old_default_still_active(self):
  200. m = mock.patch('git_cl.Changelist._CMDUploadChange',
  201. side_effect=[git_cl.GitPushError(), None]).start()
  202. mock.patch('git_cl.Changelist.GetRemoteBranch',
  203. return_value=('foo', git_cl.DEFAULT_OLD_BRANCH)).start()
  204. mock.patch('git_cl.Changelist.GetGerritProject',
  205. return_value='foo').start()
  206. mock.patch('git_cl.gerrit_util.GetProjectHead',
  207. return_value='refs/heads/main').start()
  208. cl = git_cl.Changelist()
  209. options = optparse.Values()
  210. options.target_branch = 'refs/heads/main'
  211. with self.assertRaises(SystemExitMock):
  212. cl.CMDUploadChange(options, [], 'foo',
  213. git_cl.ChangeDescription('bar'))
  214. # ensure upload is called once
  215. self.assertEqual(len(m.mock_calls), 1)
  216. sys.exit.assert_called_once_with(1)
  217. # option not set as retry didn't happen
  218. self.assertFalse(hasattr(options, 'force'))
  219. self.assertFalse(hasattr(options, 'edit_description'))
  220. def test_upload_with_message_file_no_editor(self):
  221. m = mock.patch('git_cl.ChangeDescription.prompt',
  222. return_value=None).start()
  223. mock.patch('git_cl.Changelist.GetRemoteBranch',
  224. return_value=('foo', git_cl.DEFAULT_NEW_BRANCH)).start()
  225. mock.patch('git_cl.GetTargetRef',
  226. return_value='refs/heads/main').start()
  227. mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  228. lambda offer_removal: None).start()
  229. mock.patch('git_cl.Changelist.GetIssue', return_value=None).start()
  230. mock.patch('git_cl.Changelist.GetBranch',
  231. side_effect=SystemExitMock).start()
  232. mock.patch('git_cl.GenerateGerritChangeId', return_value=None).start()
  233. mock.patch('git_cl.RunGit').start()
  234. cl = git_cl.Changelist()
  235. options = optparse.Values()
  236. options.target_branch = 'refs/heads/main'
  237. options.squash = True
  238. options.edit_description = False
  239. options.force = False
  240. options.preserve_tryjobs = False
  241. options.message_file = "message.txt"
  242. options.commit_description = None
  243. with self.assertRaises(SystemExitMock):
  244. cl.CMDUploadChange(options, [], 'foo',
  245. git_cl.ChangeDescription('bar'))
  246. self.assertEqual(len(m.mock_calls), 0)
  247. options.message_file = None
  248. with self.assertRaises(SystemExitMock):
  249. cl.CMDUploadChange(options, [], 'foo',
  250. git_cl.ChangeDescription('bar'))
  251. self.assertEqual(len(m.mock_calls), 1)
  252. def test_get_cl_statuses_no_changes(self):
  253. self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
  254. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  255. @mock.patch('multiprocessing.pool.ThreadPool')
  256. def test_get_cl_statuses_timeout(self, *_mocks):
  257. changes = [git_cl.Changelist() for _ in range(2)]
  258. pool = multiprocessing.pool.ThreadPool()
  259. it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
  260. it.return_value.next.side_effect = [
  261. (changes[0], 'lgtm'),
  262. multiprocessing.TimeoutError,
  263. ]
  264. actual = list(git_cl.get_cl_statuses(changes, True))
  265. self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
  266. @mock.patch('git_cl.Changelist.GetIssueURL')
  267. def test_get_cl_statuses_not_finegrained(self, _mock):
  268. changes = [git_cl.Changelist() for _ in range(2)]
  269. urls = ['some-url', None]
  270. git_cl.Changelist.GetIssueURL.side_effect = urls
  271. actual = set(git_cl.get_cl_statuses(changes, False))
  272. self.assertEqual(set([(changes[0], 'waiting'), (changes[1], 'error')]),
  273. actual)
  274. def test_get_issue_url(self):
  275. cl = git_cl.Changelist(issue=123)
  276. cl._gerrit_server = 'https://example.com'
  277. self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
  278. self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
  279. cl = git_cl.Changelist(issue=123)
  280. cl._gerrit_server = 'https://chromium-review.googlesource.com'
  281. self.assertEqual(cl.GetIssueURL(),
  282. 'https://chromium-review.googlesource.com/123')
  283. self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
  284. def test_set_preserve_tryjobs(self):
  285. d = git_cl.ChangeDescription('Simple.')
  286. d.set_preserve_tryjobs()
  287. self.assertEqual(d.description.splitlines(), [
  288. 'Simple.',
  289. '',
  290. 'Cq-Do-Not-Cancel-Tryjobs: true',
  291. ])
  292. before = d.description
  293. d.set_preserve_tryjobs()
  294. self.assertEqual(before, d.description)
  295. d = git_cl.ChangeDescription('\n'.join([
  296. 'One is enough',
  297. '',
  298. 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
  299. 'Change-Id: Ideadbeef',
  300. ]))
  301. d.set_preserve_tryjobs()
  302. self.assertEqual(d.description.splitlines(), [
  303. 'One is enough',
  304. '',
  305. 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
  306. 'Change-Id: Ideadbeef',
  307. 'Cq-Do-Not-Cancel-Tryjobs: true',
  308. ])
  309. def test_get_bug_line_values(self):
  310. f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
  311. self.assertEqual(f('', ''), [])
  312. self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
  313. # Prefix that ends with colon.
  314. self.assertEqual(f('v8:', '456'), ['v8:456'])
  315. self.assertEqual(f('v8:', 'chromium:123,456'),
  316. ['v8:456', 'chromium:123'])
  317. # Prefix that ends without colon.
  318. self.assertEqual(f('v8', '456'), ['v8:456'])
  319. self.assertEqual(f('v8', 'chromium:123,456'),
  320. ['v8:456', 'chromium:123'])
  321. # Not nice, but not worth carying.
  322. self.assertEqual(f('v8:', 'chromium:123,456,v8:123'),
  323. ['v8:456', 'chromium:123', 'v8:123'])
  324. self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
  325. ['v8:456', 'chromium:123', 'v8:123'])
  326. @mock.patch('gerrit_util.GetAccountDetails')
  327. def test_valid_accounts(self, mockGetAccountDetails):
  328. mock_per_account = {
  329. 'u1': None, # 404, doesn't exist.
  330. 'u2': {
  331. '_account_id': 123124,
  332. 'avatars': [],
  333. 'email': 'u2@example.com',
  334. 'name': 'User Number 2',
  335. 'status': 'OOO',
  336. },
  337. 'u3': git_cl.gerrit_util.GerritError(500,
  338. 'retries didn\'t help :('),
  339. }
  340. def GetAccountDetailsMock(_, account):
  341. # Poor-man's mock library's side_effect.
  342. v = mock_per_account.pop(account)
  343. if isinstance(v, Exception):
  344. raise v
  345. return v
  346. mockGetAccountDetails.side_effect = GetAccountDetailsMock
  347. actual = git_cl.gerrit_util.ValidAccounts('host', ['u1', 'u2', 'u3'],
  348. max_threads=1)
  349. self.assertEqual(
  350. actual, {
  351. 'u2': {
  352. '_account_id': 123124,
  353. 'avatars': [],
  354. 'email': 'u2@example.com',
  355. 'name': 'User Number 2',
  356. 'status': 'OOO',
  357. },
  358. })
  359. class TestParseIssueURL(unittest.TestCase):
  360. def _test(self, arg, issue=None, patchset=None, hostname=None, fail=False):
  361. parsed = git_cl.ParseIssueNumberArgument(arg)
  362. self.assertIsNotNone(parsed)
  363. if fail:
  364. self.assertFalse(parsed.valid)
  365. return
  366. self.assertTrue(parsed.valid)
  367. self.assertEqual(parsed.issue, issue)
  368. self.assertEqual(parsed.patchset, patchset)
  369. self.assertEqual(parsed.hostname, hostname)
  370. def test_basic(self):
  371. self._test('123', 123)
  372. self._test('', fail=True)
  373. self._test('abc', fail=True)
  374. self._test('123/1', fail=True)
  375. self._test('123a', fail=True)
  376. self._test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
  377. self._test('ssh://chrome-review.source.com/c/123/1/', fail=True)
  378. def test_gerrit_url(self):
  379. self._test('https://codereview.source.com/123', 123, None,
  380. 'codereview.source.com')
  381. self._test('http://chrome-review.source.com/c/123', 123, None,
  382. 'chrome-review.source.com')
  383. self._test('https://chrome-review.source.com/c/123/', 123, None,
  384. 'chrome-review.source.com')
  385. self._test('https://chrome-review.source.com/c/123/4', 123, 4,
  386. 'chrome-review.source.com')
  387. self._test('https://chrome-review.source.com/#/c/123/4', 123, 4,
  388. 'chrome-review.source.com')
  389. self._test('https://chrome-review.source.com/c/123/4', 123, 4,
  390. 'chrome-review.source.com')
  391. self._test('https://chrome-review.source.com/123', 123, None,
  392. 'chrome-review.source.com')
  393. self._test('https://chrome-review.source.com/123/4', 123, 4,
  394. 'chrome-review.source.com')
  395. self._test('https://chrome-review.source.com/bad/123/4', fail=True)
  396. self._test('https://chrome-review.source.com/c/123/1/whatisthis',
  397. fail=True)
  398. self._test('https://chrome-review.source.com/c/abc/', fail=True)
  399. def test_short_urls(self):
  400. self._test('https://crrev.com/c/2151934', 2151934, None,
  401. 'chromium-review.googlesource.com')
  402. def test_missing_scheme(self):
  403. self._test('codereview.source.com/123', 123, None,
  404. 'codereview.source.com')
  405. self._test('crrev.com/c/2151934', 2151934, None,
  406. 'chromium-review.googlesource.com')
  407. class GitCookiesCheckerTest(unittest.TestCase):
  408. def setUp(self):
  409. super(GitCookiesCheckerTest, self).setUp()
  410. self.c = git_cl._GitCookiesChecker()
  411. self.c._all_hosts = []
  412. mock.patch('sys.stdout', io.StringIO()).start()
  413. self.addCleanup(mock.patch.stopall)
  414. def mock_hosts_creds(self, subhost_identity_pairs):
  415. def ensure_googlesource(h):
  416. if not h.endswith(git_cl._GOOGLESOURCE):
  417. assert not h.endswith('.')
  418. return h + '.' + git_cl._GOOGLESOURCE
  419. return h
  420. self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
  421. for h, i in subhost_identity_pairs]
  422. def test_identity_parsing(self):
  423. self.assertEqual(self.c._parse_identity('ldap.google.com'),
  424. ('ldap', 'google.com'))
  425. self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
  426. ('ldap', 'example.com'))
  427. # Specical case because we know there are no subdomains in chromium.org.
  428. self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
  429. ('note.period', 'chromium.org'))
  430. # Pathological: ".period." can be either username OR domain, more likely
  431. # domain.
  432. self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
  433. ('note', 'period.example.com'))
  434. def test_analysis_nothing(self):
  435. self.c._all_hosts = []
  436. self.assertFalse(self.c.has_generic_host())
  437. self.assertEqual(set(), self.c.get_conflicting_hosts())
  438. self.assertEqual(set(), self.c.get_duplicated_hosts())
  439. self.assertEqual(set(), self.c.get_partially_configured_hosts())
  440. def test_analysis(self):
  441. self.mock_hosts_creds([
  442. ('.googlesource.com', 'git-example.chromium.org'),
  443. ('chromium', 'git-example.google.com'),
  444. ('chromium-review', 'git-example.google.com'),
  445. ('chrome-internal', 'git-example.chromium.org'),
  446. ('chrome-internal-review', 'git-example.chromium.org'),
  447. ('conflict', 'git-example.google.com'),
  448. ('conflict-review', 'git-example.chromium.org'),
  449. ('dup', 'git-example.google.com'),
  450. ('dup', 'git-example.google.com'),
  451. ('dup-review', 'git-example.google.com'),
  452. ('partial', 'git-example.google.com'),
  453. ('gpartial-review', 'git-example.google.com'),
  454. ])
  455. self.assertTrue(self.c.has_generic_host())
  456. self.assertEqual(set(['conflict.googlesource.com']),
  457. self.c.get_conflicting_hosts())
  458. self.assertEqual(set(['dup.googlesource.com']),
  459. self.c.get_duplicated_hosts())
  460. self.assertEqual(
  461. set([
  462. 'partial.googlesource.com', 'gpartial-review.googlesource.com'
  463. ]), self.c.get_partially_configured_hosts())
  464. def test_report_no_problems(self):
  465. self.test_analysis_nothing()
  466. self.assertFalse(self.c.find_and_report_problems())
  467. self.assertEqual(sys.stdout.getvalue(), '')
  468. @mock.patch('git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
  469. return_value=os.path.join('~', '.gitcookies'))
  470. def test_report(self, *_mocks):
  471. self.test_analysis()
  472. self.assertTrue(self.c.find_and_report_problems())
  473. with open(
  474. os.path.join(os.path.dirname(__file__),
  475. 'git_cl_creds_check_report.txt')) as f:
  476. expected = f.read() % {
  477. 'sep': os.sep,
  478. }
  479. def by_line(text):
  480. return [l.rstrip() for l in text.rstrip().splitlines()]
  481. self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
  482. self.assertEqual(by_line(sys.stdout.getvalue().strip()),
  483. by_line(expected))
  484. class TestGitCl(unittest.TestCase):
  485. def setUp(self):
  486. super(TestGitCl, self).setUp()
  487. self.calls = []
  488. self._calls_done = []
  489. oldEnv = dict(os.environ)
  490. def _resetEnv():
  491. os.environ = oldEnv
  492. self.addCleanup(_resetEnv)
  493. self.failed = False
  494. mock.patch('sys.stdout', io.StringIO()).start()
  495. mock.patch('git_cl.time_time',
  496. lambda: self._mocked_call('time.time')).start()
  497. mock.patch('git_cl.metrics.collector.add_repeated',
  498. lambda *a: self._mocked_call('add_repeated', *a)).start()
  499. mock.patch('subprocess2.call', self._mocked_call).start()
  500. mock.patch('subprocess2.check_call', self._mocked_call).start()
  501. mock.patch('subprocess2.check_output', self._mocked_call).start()
  502. mock.patch('subprocess2.communicate', lambda *a, **_k:
  503. ([self._mocked_call(*a), ''], 0)).start()
  504. mock.patch('git_cl.gclient_utils.CheckCallAndFilter',
  505. self._mocked_call).start()
  506. mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
  507. mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
  508. mock.patch(
  509. 'git_cl.SaveDescriptionBackup',
  510. lambda _: self._mocked_call('SaveDescriptionBackup')).start()
  511. mock.patch('git_cl.write_json',
  512. lambda *a: self._mocked_call('write_json', *a)).start()
  513. mock.patch('git_cl.Changelist.RunHook',
  514. return_value={
  515. 'more_cc': ['test-more-cc@chromium.org']
  516. }).start()
  517. mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
  518. mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
  519. mock.patch('gerrit_util.GetChangeDetail').start()
  520. mock.patch(
  521. 'git_cl.gerrit_util.GetChangeComments',
  522. lambda *a: self._mocked_call('GetChangeComments', *a)).start()
  523. mock.patch(
  524. 'git_cl.gerrit_util.GetChangeRobotComments',
  525. lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
  526. mock.patch('git_cl.gerrit_util.AddReviewers',
  527. lambda *a: self._mocked_call('AddReviewers', *a)).start()
  528. mock.patch('git_cl.gerrit_util.SetReview',
  529. lambda h, i, msg=None, labels=None, notify=None, ready=None:
  530. (self._mocked_call('SetReview', h, i, msg, labels, notify,
  531. ready))).start()
  532. mock.patch('git_cl.gerrit_util.LuciContextAuthenticator.is_applicable',
  533. return_value=False).start()
  534. mock.patch('git_cl.gerrit_util.GceAuthenticator.is_applicable',
  535. return_value=False).start()
  536. mock.patch('git_cl.gerrit_util.ValidAccounts',
  537. lambda *a: self._mocked_call('ValidAccounts', *a)).start()
  538. mock.patch('sys.exit', side_effect=SystemExitMock).start()
  539. mock.patch('git_cl.Settings.GetRoot', return_value='').start()
  540. scm_mock.GIT(self)
  541. mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
  542. mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
  543. mock.patch('scm.GIT.FetchUpstreamTuple',
  544. return_value=('origin', 'refs/heads/main')).start()
  545. mock.patch('scm.GIT.CaptureStatus',
  546. return_value=[('M', 'foo.txt')]).start()
  547. # It's important to reset settings to not have inter-tests interference.
  548. git_cl.settings = git_cl.Settings()
  549. self.addCleanup(mock.patch.stopall)
  550. gerrit_util._Authenticator._resolved = None
  551. def tearDown(self):
  552. try:
  553. if not self.failed:
  554. self.assertEqual([], self.calls)
  555. except AssertionError:
  556. calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
  557. if len(self.calls) > 5:
  558. calls += ' ...\n'
  559. self.fail(
  560. '\n'
  561. 'There are un-consumed calls after this test has finished:\n' +
  562. calls)
  563. finally:
  564. super(TestGitCl, self).tearDown()
  565. def _mocked_call(self, *args, **_kwargs):
  566. self.assertTrue(
  567. self.calls, '@%d Expected: <Missing> Actual: %r' %
  568. (len(self._calls_done), args))
  569. top = self.calls.pop(0)
  570. expected_args, result = top
  571. # Also logs otherwise it could get caught in a try/finally and be hard
  572. # to diagnose.
  573. if expected_args != args:
  574. N = 5
  575. prior_calls = '\n '.join(
  576. '@%d: %r' % (len(self._calls_done) - N + i, c[0])
  577. for i, c in enumerate(self._calls_done[-N:]))
  578. following_calls = '\n '.join('@%d: %r' %
  579. (len(self._calls_done) + i + 1, c[0])
  580. for i, c in enumerate(self.calls[:N]))
  581. extended_msg = ('A few prior calls:\n %s\n\n'
  582. 'This (expected):\n @%d: %r\n'
  583. 'This (actual):\n @%d: %r\n\n'
  584. 'A few following expected calls:\n %s' %
  585. (prior_calls, len(self._calls_done), expected_args,
  586. len(self._calls_done), args, following_calls))
  587. self.failed = True
  588. self.fail(
  589. '@%d\n'
  590. ' Expected: %r\n'
  591. ' Actual: %r\n'
  592. '\n'
  593. '%s' %
  594. (len(self._calls_done), expected_args, args, extended_msg))
  595. self._calls_done.append(top)
  596. if isinstance(result, Exception):
  597. raise result
  598. # stdout from git commands is supposed to be a bytestream. Convert it
  599. # here instead of converting all test output in this file to bytes.
  600. if args[0][0] == 'git' and not isinstance(result, bytes):
  601. result = result.encode('utf-8')
  602. return result
  603. @mock.patch('sys.stdin', io.StringIO('blah\nye\n'))
  604. @mock.patch('sys.stdout', io.StringIO())
  605. def test_ask_for_explicit_yes_true(self):
  606. self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
  607. self.assertEqual('prompt [Yes/No]: Please, type yes or no: ',
  608. sys.stdout.getvalue())
  609. def test_LoadCodereviewSettingsFromFile_gerrit(self):
  610. codereview_file = io.StringIO('GERRIT_HOST: true')
  611. self.calls = [
  612. ]
  613. self.assertIsNone(
  614. git_cl.LoadCodereviewSettingsFromFile(codereview_file))
  615. @classmethod
  616. def _gerrit_base_calls(cls,
  617. issue=None,
  618. fetched_description=None,
  619. fetched_status=None,
  620. other_cl_owner=None,
  621. custom_cl_base=None,
  622. short_hostname='chromium',
  623. change_id=None,
  624. default_branch='main',
  625. reset_issue=False):
  626. calls = [
  627. (
  628. (['os.path.isfile', '.gitmodules'], ),
  629. 'True',
  630. ),
  631. ]
  632. if custom_cl_base:
  633. ancestor_revision = custom_cl_base
  634. else:
  635. # Determine ancestor_revision to be merge base.
  636. ancestor_revision = 'origin/' + default_branch
  637. if issue:
  638. # TODO: if tests don't provide a `change_id` the default used here
  639. # will cause the TRACES_README_FORMAT mock (which uses the test
  640. # provided `change_id` to fail.
  641. gerrit_util.GetChangeDetail.return_value = {
  642. 'owner': {
  643. 'email': (other_cl_owner or 'owner@example.com')
  644. },
  645. 'change_id': (change_id or '123456789'),
  646. 'current_revision': 'sha1_of_current_revision',
  647. 'revisions': {
  648. 'sha1_of_current_revision': {
  649. 'commit': {
  650. 'message': fetched_description
  651. },
  652. }
  653. },
  654. 'status': fetched_status or 'NEW',
  655. }
  656. if fetched_status == 'ABANDONED':
  657. return calls
  658. if fetched_status == 'MERGED':
  659. calls.append(((
  660. 'ask_for_data',
  661. 'Change https://chromium-review.googlesource.com/%s has been '
  662. 'submitted, new uploads are not allowed. Would you like to start '
  663. 'a new change (Y/n)?' % issue),
  664. 'y' if reset_issue else 'n'))
  665. if not reset_issue:
  666. return calls
  667. # Part of SetIssue call.
  668. calls.append(((['git', 'log', '-1', '--format=%B'], ), ''))
  669. if other_cl_owner:
  670. calls += [
  671. (('ask_for_data',
  672. 'Press Enter to upload, or Ctrl+C to abort'), ''),
  673. ]
  674. calls += [
  675. ((['git', 'rev-list', '--count'] +
  676. ([f'{custom_cl_base}..HEAD']
  677. if custom_cl_base else [f'{ancestor_revision}..HEAD']), ), '3'),
  678. ]
  679. calls += [
  680. ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
  681. ([custom_cl_base]
  682. if custom_cl_base else [ancestor_revision, 'HEAD']), ), '+dat'),
  683. ]
  684. return calls
  685. def _gerrit_upload_calls(self,
  686. description,
  687. reviewers,
  688. squash,
  689. squash_mode='default',
  690. title=None,
  691. notify=False,
  692. post_amend_description=None,
  693. issue=None,
  694. cc=None,
  695. custom_cl_base=None,
  696. short_hostname='chromium',
  697. labels=None,
  698. change_id=None,
  699. final_description=None,
  700. gitcookies_exists=True,
  701. force=False,
  702. edit_description=None,
  703. default_branch='main',
  704. ref_to_push='abcdef0123456789',
  705. external_parent=None,
  706. push_opts=None):
  707. if post_amend_description is None:
  708. post_amend_description = description
  709. cc = cc or []
  710. calls = []
  711. if squash_mode in ('override_squash', 'override_nosquash'):
  712. scm.GIT.SetConfig(
  713. '', 'gerrit.override-squash-uploads',
  714. 'true' if squash_mode == 'override_squash' else 'false')
  715. if not git_footers.get_footer_change_id(description) and not squash:
  716. calls += [
  717. (('DownloadGerritHook', False), ''),
  718. ]
  719. if squash:
  720. if not issue and not force:
  721. calls += [
  722. ((['RunEditor'], ), description),
  723. ]
  724. # user wants to edit description
  725. if edit_description:
  726. calls += [
  727. ((['RunEditor'], ), edit_description),
  728. ]
  729. if external_parent:
  730. parent = external_parent
  731. else:
  732. if custom_cl_base is None:
  733. parent = 'origin/' + default_branch
  734. git_common.get_or_create_merge_base.return_value = parent
  735. else:
  736. calls += [
  737. (([
  738. 'git', 'merge-base', '--is-ancestor',
  739. custom_cl_base,
  740. 'refs/remotes/origin/' + default_branch
  741. ], ), callError(1)), # Means not ancenstor.
  742. (('ask_for_data',
  743. 'Do you take responsibility for cleaning up potential mess '
  744. 'resulting from proceeding with upload? Press Enter to upload, '
  745. 'or Ctrl+C to abort'), ''),
  746. ]
  747. parent = custom_cl_base
  748. calls += [
  749. (
  750. (['git', 'rev-parse',
  751. 'HEAD:'], ), # `HEAD:` means HEAD's tree hash.
  752. '0123456789abcdef'),
  753. ((['FileWrite', '/tmp/fake-temp1', description], ), None),
  754. (([
  755. 'git', 'commit-tree', '0123456789abcdef', '-p', parent,
  756. '-F', '/tmp/fake-temp1'
  757. ], ), ref_to_push),
  758. ]
  759. else:
  760. ref_to_push = 'HEAD'
  761. parent = 'origin/refs/heads/' + default_branch
  762. calls += [
  763. (('SaveDescriptionBackup', ), None),
  764. ((['git', 'rev-list',
  765. parent + '..' + ref_to_push], ), '1hashPerLine\n'),
  766. ]
  767. metrics_arguments = []
  768. ref_suffix_list = []
  769. if notify:
  770. ref_suffix_list.append('ready,notify=ALL')
  771. metrics_arguments += ['ready', 'notify=ALL']
  772. elif not issue and squash:
  773. ref_suffix_list.append('wip')
  774. metrics_arguments.append('wip')
  775. # If issue is given, then description is fetched from Gerrit instead.
  776. if not title and squash_mode != "override_nosquash":
  777. if issue is None:
  778. if squash:
  779. title = 'Initial upload'
  780. else:
  781. calls += [
  782. ((['git', 'show', '-s', '--format=%s', 'HEAD',
  783. '--'], ), ''),
  784. (('ask_for_data', 'Title for patchset []: '), 'User input'),
  785. ]
  786. title = 'User input'
  787. if title:
  788. ref_suffix_list.append('m=' +
  789. gerrit_util.PercentEncodeForGitRef(title))
  790. metrics_arguments.append('m')
  791. for k, v in sorted((labels or {}).items()):
  792. ref_suffix_list.append('l=%s+%d' % (k, v))
  793. metrics_arguments.append('l=%s+%d' % (k, v))
  794. if short_hostname == 'chromium':
  795. # All reviewers and ccs get into ref_suffix.
  796. for r in sorted(reviewers):
  797. ref_suffix_list.append('r=%s' % r)
  798. metrics_arguments.append('r')
  799. if issue is None:
  800. cc += ['test-more-cc@chromium.org', 'joe@example.com']
  801. for c in sorted(cc):
  802. ref_suffix_list.append('cc=%s' % c)
  803. metrics_arguments.append('cc')
  804. reviewers, cc = [], []
  805. else:
  806. # TODO(crbug/877717): remove this case.
  807. calls += [(('ValidAccounts',
  808. '%s-review.googlesource.com' % short_hostname,
  809. sorted(reviewers) +
  810. ['joe@example.com', 'test-more-cc@chromium.org'] + cc),
  811. {
  812. e: {
  813. 'email': e
  814. }
  815. for e in (reviewers + ['joe@example.com'] + cc)
  816. })]
  817. for r in sorted(reviewers):
  818. if r != 'bad-account-or-email':
  819. ref_suffix_list.append('r=%s' % r)
  820. metrics_arguments.append('r')
  821. reviewers.remove(r)
  822. if issue is None:
  823. cc += ['joe@example.com']
  824. for c in sorted(cc):
  825. ref_suffix_list.append('cc=%s' % c)
  826. metrics_arguments.append('cc')
  827. if c in cc:
  828. cc.remove(c)
  829. ref_suffix = ''
  830. if ref_suffix_list:
  831. ref_suffix = '%' + ','.join(ref_suffix_list)
  832. calls += [
  833. (
  834. ('time.time', ),
  835. 1000,
  836. ),
  837. (
  838. ([
  839. 'git', 'push',
  840. 'https://%s.googlesource.com/my/repo' % short_hostname,
  841. ref_to_push + ':refs/for/refs/heads/' + default_branch +
  842. ref_suffix
  843. ] + (push_opts if push_opts else []), ),
  844. (('remote:\n'
  845. 'remote: Processing changes: (\)\n'
  846. 'remote: Processing changes: (|)\n'
  847. 'remote: Processing changes: (/)\n'
  848. 'remote: Processing changes: (-)\n'
  849. 'remote: Processing changes: new: 1 (/)\n'
  850. 'remote: Processing changes: new: 1, done\n'
  851. 'remote:\n'
  852. 'remote: New Changes:\n'
  853. 'remote: '
  854. 'https://%s-review.googlesource.com/#/c/my/repo/+/123456'
  855. ' XXX\n'
  856. 'remote:\n'
  857. 'To https://%s.googlesource.com/my/repo\n'
  858. ' * [new branch] hhhh -> refs/for/refs/heads/%s\n') %
  859. (short_hostname, short_hostname, default_branch)),
  860. ),
  861. (
  862. ('time.time', ),
  863. 2000,
  864. ),
  865. (
  866. ('add_repeated', 'sub_commands', {
  867. 'execution_time': 1000,
  868. 'command': 'git push',
  869. 'exit_code': 0,
  870. 'arguments': sorted(metrics_arguments),
  871. }),
  872. None,
  873. ),
  874. ]
  875. final_description = final_description or post_amend_description.strip()
  876. trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
  877. # Trace-related calls
  878. calls += [
  879. # Write a description with context for the current trace.
  880. (
  881. ([
  882. 'FileWrite', trace_name + '-README',
  883. '%(date)s\n'
  884. '%(short_hostname)s-review.googlesource.com\n'
  885. '%(change_id)s\n'
  886. '%(title)s\n'
  887. '%(description)s\n'
  888. '1000\n'
  889. '0\n'
  890. '%(trace_name)s' % {
  891. 'date': '2017-03-16T20:00:41.000000',
  892. 'short_hostname': short_hostname,
  893. 'change_id': change_id,
  894. 'description': final_description,
  895. 'title': title or '<untitled>',
  896. 'trace_name': trace_name,
  897. }
  898. ], ),
  899. None,
  900. ),
  901. # Read traces and shorten git hashes.
  902. (
  903. (['os.path.isfile',
  904. os.path.join('TEMP_DIR', 'trace-packet')], ),
  905. True,
  906. ),
  907. (
  908. (['FileRead',
  909. os.path.join('TEMP_DIR', 'trace-packet')], ),
  910. ('git-hash: 0123456789012345678901234567890123456789\n'
  911. 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
  912. ),
  913. (
  914. ([
  915. 'FileWrite',
  916. os.path.join('TEMP_DIR', 'trace-packet'),
  917. 'git-hash: 012345\n'
  918. 'git-hash: abcdea\n'
  919. ], ),
  920. None,
  921. ),
  922. # Make zip file for the git traces.
  923. (
  924. (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
  925. None,
  926. ),
  927. # Collect git config and gitcookies.
  928. #
  929. # We accept ANY for the git-config file because it's just reflecting
  930. # our mocked git config in scm.GIT anyway.
  931. (
  932. ([
  933. 'FileWrite',
  934. os.path.join('TEMP_DIR', 'git-config'), mock.ANY,
  935. ], ),
  936. None,
  937. ),
  938. (
  939. (['os.path.isfile',
  940. os.path.join('~', '.gitcookies')], ),
  941. gitcookies_exists,
  942. ),
  943. ]
  944. if gitcookies_exists:
  945. calls += [
  946. (
  947. (['FileRead', os.path.join('~', '.gitcookies')], ),
  948. 'gitcookies 1/SECRET',
  949. ),
  950. (
  951. ([
  952. 'FileWrite',
  953. os.path.join(
  954. 'TEMP_DIR',
  955. 'CookiesAuthenticatorMock.debug_summary_state'),
  956. 'gitcookies REDACTED'
  957. ], ),
  958. None,
  959. ),
  960. ]
  961. else:
  962. calls += [
  963. (
  964. ([
  965. 'FileWrite',
  966. os.path.join(
  967. 'TEMP_DIR',
  968. 'CookiesAuthenticatorMock.debug_summary_state'), ''
  969. ], ),
  970. None,
  971. ),
  972. ]
  973. calls += [
  974. # Make zip file for the git config and gitcookies.
  975. (
  976. (['make_archive', trace_name + '-git-info', 'zip',
  977. 'TEMP_DIR'], ),
  978. None,
  979. ),
  980. ]
  981. # TODO(crbug/877717): this should never be used.
  982. if squash and short_hostname != 'chromium':
  983. calls += [
  984. (('AddReviewers', 'chromium-review.googlesource.com',
  985. 'my%2Frepo~123456', sorted(reviewers),
  986. cc + ['test-more-cc@chromium.org'], notify), ''),
  987. ]
  988. return calls
  989. def _run_gerrit_upload_test(self,
  990. upload_args,
  991. description,
  992. reviewers=None,
  993. squash=True,
  994. squash_mode=None,
  995. title=None,
  996. notify=False,
  997. post_amend_description=None,
  998. issue=None,
  999. patchset=None,
  1000. cc=None,
  1001. fetched_status=None,
  1002. other_cl_owner=None,
  1003. custom_cl_base=None,
  1004. short_hostname='chromium',
  1005. labels=None,
  1006. change_id=None,
  1007. final_description=None,
  1008. gitcookies_exists=True,
  1009. force=False,
  1010. log_description=None,
  1011. edit_description=None,
  1012. fetched_description=None,
  1013. default_branch='main',
  1014. ref_to_push='abcdef0123456789',
  1015. external_parent=None,
  1016. push_opts=None,
  1017. reset_issue=False):
  1018. """Generic gerrit upload test framework."""
  1019. if squash_mode is None:
  1020. if '--no-squash' in upload_args:
  1021. squash_mode = 'nosquash'
  1022. elif '--squash' in upload_args:
  1023. squash_mode = 'squash'
  1024. else:
  1025. squash_mode = 'default'
  1026. reviewers = reviewers or []
  1027. cc = cc or []
  1028. mock.patch(
  1029. 'git_cl.gerrit_util.CookiesAuthenticator',
  1030. CookiesAuthenticatorMockFactory(same_auth=('git-owner.example.com',
  1031. 'pass'))).start()
  1032. mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  1033. lambda offer_removal: None).start()
  1034. mock.patch('git_cl.Changelist.GetMostRecentPatchset',
  1035. lambda _, update: patchset).start()
  1036. mock.patch('git_cl.gclient_utils.RunEditor',
  1037. lambda *_, **__: self._mocked_call(['RunEditor'])).start()
  1038. mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
  1039. 'DownloadGerritHook', force)).start()
  1040. mock.patch('git_cl.gclient_utils.FileRead',
  1041. lambda path: self._mocked_call(['FileRead', path])).start()
  1042. mock.patch(
  1043. 'git_cl.gclient_utils.FileWrite', lambda path, contents: self.
  1044. _mocked_call(['FileWrite', path, contents])).start()
  1045. mock.patch(
  1046. 'git_cl.datetime_now',
  1047. lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
  1048. mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
  1049. mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
  1050. mock.patch(
  1051. 'git_cl.TRACES_README_FORMAT', '%(now)s\n'
  1052. '%(gerrit_host)s\n'
  1053. '%(change_id)s\n'
  1054. '%(title)s\n'
  1055. '%(description)s\n'
  1056. '%(execution_time)s\n'
  1057. '%(exit_code)s\n'
  1058. '%(trace_name)s').start()
  1059. mock.patch(
  1060. 'git_cl.shutil.make_archive', lambda *args: self._mocked_call(
  1061. ['make_archive'] + list(args))).start()
  1062. mock.patch(
  1063. 'os.path.isfile',
  1064. lambda path: self._mocked_call(['os.path.isfile', path])).start()
  1065. mock.patch('git_cl._create_description_from_log',
  1066. return_value=log_description or description).start()
  1067. mock.patch('git_cl.Changelist._AddChangeIdToCommitMessage',
  1068. return_value=post_amend_description or description).start()
  1069. mock.patch('git_cl.GenerateGerritChangeId',
  1070. return_value=change_id).start()
  1071. mock.patch('git_common.get_or_create_merge_base',
  1072. return_value='origin/' + default_branch).start()
  1073. mock.patch(
  1074. 'gclient_utils.AskForData',
  1075. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  1076. scm.GIT.SetConfig('', 'gerrit.host', 'true')
  1077. scm.GIT.SetConfig('', 'branch.main.gerritissue',
  1078. (str(issue) if issue else None))
  1079. scm.GIT.SetConfig('', 'remote.origin.url',
  1080. f'https://{short_hostname}.googlesource.com/my/repo')
  1081. scm.GIT.SetConfig('', 'user.email', 'owner@example.com')
  1082. if squash_mode == "override_nosquash":
  1083. if issue:
  1084. mock.patch('gerrit_util.GetChange',
  1085. return_value={
  1086. '_number': issue
  1087. }).start()
  1088. else:
  1089. mock.patch('gerrit_util.GetChange', return_value={}).start()
  1090. self.calls = self._gerrit_base_calls(
  1091. issue=issue,
  1092. fetched_description=fetched_description or description,
  1093. fetched_status=fetched_status,
  1094. other_cl_owner=other_cl_owner,
  1095. custom_cl_base=custom_cl_base,
  1096. short_hostname=short_hostname,
  1097. change_id=change_id,
  1098. default_branch=default_branch,
  1099. reset_issue=reset_issue)
  1100. if fetched_status == 'ABANDONED' or (fetched_status == 'MERGED'
  1101. and not reset_issue):
  1102. pass # readability
  1103. else:
  1104. if fetched_status == 'MERGED' and reset_issue:
  1105. fetched_status = 'NEW'
  1106. issue = None
  1107. mock.patch('gclient_utils.temporary_file',
  1108. TemporaryFileMock()).start()
  1109. mock.patch('os.remove', return_value=True).start()
  1110. self.calls += self._gerrit_upload_calls(
  1111. description,
  1112. reviewers,
  1113. squash,
  1114. squash_mode=squash_mode,
  1115. title=title,
  1116. notify=notify,
  1117. post_amend_description=post_amend_description,
  1118. issue=issue,
  1119. cc=cc,
  1120. custom_cl_base=custom_cl_base,
  1121. short_hostname=short_hostname,
  1122. labels=labels,
  1123. change_id=change_id,
  1124. final_description=final_description,
  1125. gitcookies_exists=gitcookies_exists,
  1126. force=force,
  1127. edit_description=edit_description,
  1128. default_branch=default_branch,
  1129. ref_to_push=ref_to_push,
  1130. external_parent=external_parent,
  1131. push_opts=push_opts)
  1132. # Uncomment when debugging.
  1133. # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
  1134. git_cl.main(['upload'] + upload_args)
  1135. if squash:
  1136. self.assertIssueAndPatchset(patchset=str((patchset or 0) + 1))
  1137. self.assertEqual(
  1138. ref_to_push,
  1139. scm.GIT.GetBranchConfig('', 'main',
  1140. git_cl.GERRIT_SQUASH_HASH_CONFIG_KEY))
  1141. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1142. 'not supported in non-git environment')
  1143. def test_gerrit_upload_traces_no_gitcookies(self):
  1144. self._run_gerrit_upload_test(
  1145. ['--no-squash'],
  1146. 'desc ✔\n\nBUG=\n', [],
  1147. squash=False,
  1148. post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  1149. change_id='Ixxx',
  1150. gitcookies_exists=False)
  1151. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1152. 'not supported in non-git environment')
  1153. def test_gerrit_upload_without_change_id_nosquash(self):
  1154. self._run_gerrit_upload_test(
  1155. ['--no-squash'],
  1156. 'desc ✔\n\nBUG=\n', [],
  1157. squash=False,
  1158. post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  1159. change_id='Ixxx')
  1160. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1161. 'not supported in non-git environment')
  1162. def test_gerrit_upload_without_change_id_override_nosquash(self):
  1163. self._run_gerrit_upload_test(
  1164. [],
  1165. 'desc ✔\n\nBUG=\n', [],
  1166. squash=False,
  1167. squash_mode='override_nosquash',
  1168. post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  1169. change_id='Ixxx')
  1170. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1171. 'not supported in non-git environment')
  1172. def test_gerrit_no_reviewer(self):
  1173. self._run_gerrit_upload_test(
  1174. [],
  1175. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n', [],
  1176. squash=False,
  1177. squash_mode='override_nosquash',
  1178. change_id='I123456789')
  1179. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1180. 'not supported in non-git environment')
  1181. def test_gerrit_push_opts(self):
  1182. self._run_gerrit_upload_test(
  1183. ['-o', 'wip'],
  1184. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n', [],
  1185. squash=False,
  1186. squash_mode='override_nosquash',
  1187. change_id='I123456789',
  1188. push_opts=['-o', 'wip'])
  1189. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1190. 'not supported in non-git environment')
  1191. def test_gerrit_no_reviewer_non_chromium_host(self):
  1192. # TODO(crbug/877717): remove this test case.
  1193. self._run_gerrit_upload_test(
  1194. [],
  1195. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n', [],
  1196. squash=False,
  1197. squash_mode='override_nosquash',
  1198. short_hostname='other',
  1199. change_id='I123456789')
  1200. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1201. 'not supported in non-git environment')
  1202. def test_gerrit_patchset_title_special_chars_nosquash(self):
  1203. self._run_gerrit_upload_test(
  1204. ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
  1205. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
  1206. squash=False,
  1207. squash_mode='override_nosquash',
  1208. change_id='I123456789',
  1209. title='We\'ll escape ^_ ^ special chars...@{u}')
  1210. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1211. 'not supported in non-git environment')
  1212. def test_gerrit_reviewers_cmd_line(self):
  1213. self._run_gerrit_upload_test(
  1214. ['-r', 'foo@example.com', '--send-mail'],
  1215. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
  1216. reviewers=['foo@example.com'],
  1217. squash=False,
  1218. squash_mode='override_nosquash',
  1219. notify=True,
  1220. change_id='I123456789',
  1221. final_description=(
  1222. 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
  1223. @unittest.skipIf(gclient_utils.IsEnvCog(),
  1224. 'not supported in non-git environment')
  1225. def test_gerrit_reviewers_cmd_line_send_email(self):
  1226. self._run_gerrit_upload_test(
  1227. ['-r', 'foo@example.com', '--send-email'],
  1228. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
  1229. reviewers=['foo@example.com'],
  1230. squash=False,
  1231. squash_mode='override_nosquash',
  1232. notify=True,
  1233. change_id='I123456789',
  1234. final_description=(
  1235. 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
  1236. @mock.patch('git_cl.Changelist.GetGerritHost',
  1237. return_value='chromium-review.googlesource.com')
  1238. @mock.patch('git_cl.Changelist.GetRemoteBranch',
  1239. return_value=('origin', 'refs/remotes/origin/main'))
  1240. @mock.patch('git_cl.Changelist.PostUploadUpdates')
  1241. @mock.patch('git_cl.Changelist._RunGitPushWithTraces')
  1242. @mock.patch('git_cl._UploadAllPrecheck')
  1243. @mock.patch('git_cl.Changelist.PrepareCherryPickSquashedCommit')
  1244. def test_upload_all_squashed_cherry_pick(self, mockCherryPickCommit,
  1245. mockUploadAllPrecheck,
  1246. mockRunGitPush,
  1247. mockPostUploadUpdates, *_mocks):
  1248. # Set up
  1249. cls = [
  1250. git_cl.Changelist(branchref='refs/heads/current-branch',
  1251. issue='12345'),
  1252. git_cl.Changelist(branchref='refs/heads/upstream-branch')
  1253. ]
  1254. mockUploadAllPrecheck.return_value = (cls, True)
  1255. upstream_gerrit_commit = 'upstream-commit'
  1256. scm.GIT.SetConfig('', 'branch.upstream-branch.gerritsquashhash',
  1257. upstream_gerrit_commit)
  1258. reviewers = []
  1259. ccs = []
  1260. commit_to_push = 'commit-to-push'
  1261. new_last_upload = 'new-last-upload'
  1262. change_desc = git_cl.ChangeDescription(
  1263. 'stonks/nChange-Id:ec15e81197380')
  1264. prev_patchset = 2
  1265. new_upload = git_cl._NewUpload(reviewers, ccs, commit_to_push,
  1266. new_last_upload, upstream_gerrit_commit,
  1267. change_desc, prev_patchset)
  1268. mockCherryPickCommit.return_value = new_upload
  1269. options = optparse.Values()
  1270. options.send_mail = options.private = False
  1271. options.squash = True
  1272. options.title = None
  1273. options.message = 'honk stonk'
  1274. options.topic = 'circus'
  1275. options.enable_auto_submit = False
  1276. options.set_bot_commit = False
  1277. options.cq_dry_run = False
  1278. options.use_commit_queue = False
  1279. options.hashtags = ['cow']
  1280. options.target_branch = None
  1281. options.push_options = ['uploadvalidator~skip']
  1282. orig_args = []
  1283. mockRunGitPush.return_value = (
  1284. 'remote: https://chromium-review.'
  1285. 'googlesource.com/c/chromium/circus/clown/+/1234 stonks')
  1286. # Call
  1287. git_cl.UploadAllSquashed(options, orig_args)
  1288. # Asserts
  1289. mockCherryPickCommit.assert_called_once_with(options,
  1290. upstream_gerrit_commit)
  1291. expected_refspec = ('commit-to-push:refs/for/refs/heads/main%'
  1292. 'm=honk_stonk,topic=circus,hashtag=cow')
  1293. expected_refspec_opts = ['m=honk_stonk', 'topic=circus', 'hashtag=cow']
  1294. mockRunGitPush.assert_called_once_with(expected_refspec,
  1295. expected_refspec_opts, mock.ANY,
  1296. options.push_options)
  1297. mockPostUploadUpdates.assert_called_once_with(options, new_upload,
  1298. '1234')
  1299. @mock.patch('git_cl.Changelist.GetGerritHost',
  1300. return_value='chromium-review.googlesource.com')
  1301. @mock.patch('git_cl.Changelist.GetRemoteBranch',
  1302. return_value=('origin', 'refs/remotes/origin/main'))
  1303. @mock.patch(
  1304. 'git_cl.Changelist.GetCommonAncestorWithUpstream',
  1305. side_effect=['current-upstream-ancestor', 'next-upstream-ancestor'])
  1306. @mock.patch('git_cl.Changelist.PostUploadUpdates')
  1307. @mock.patch('git_cl.Changelist._RunGitPushWithTraces')
  1308. @mock.patch('git_cl._UploadAllPrecheck')
  1309. @mock.patch('git_cl.Changelist.PrepareSquashedCommit')
  1310. def test_upload_all_squashed(self, mockSquashedCommit,
  1311. mockUploadAllPrecheck, mockRunGitPush,
  1312. mockPostUploadUpdates, *_mocks):
  1313. # Set up
  1314. cls = [
  1315. git_cl.Changelist(branchref='refs/heads/current-branch',
  1316. issue='12345'),
  1317. git_cl.Changelist(branchref='refs/heads/upstream-branch')
  1318. ]
  1319. mockUploadAllPrecheck.return_value = (cls, False)
  1320. reviewers = []
  1321. ccs = []
  1322. current_commit_to_push = 'commit-to-push'
  1323. current_new_last_upload = 'new-last-upload'
  1324. change_desc = git_cl.ChangeDescription(
  1325. 'stonks/nChange-Id:ec15e81197380')
  1326. prev_patchset = 2
  1327. new_upload_current = git_cl._NewUpload(reviewers, ccs,
  1328. current_commit_to_push,
  1329. current_new_last_upload,
  1330. 'next-upstream-ancestor',
  1331. change_desc, prev_patchset)
  1332. upstream_desc = git_cl.ChangeDescription('kwak')
  1333. upstream_parent = 'origin-commit'
  1334. upstream_new_last_upload = 'upstrea-last-upload'
  1335. upstream_commit_to_push = 'upstream_push_commit'
  1336. new_upload_upstream = git_cl._NewUpload(reviewers, ccs,
  1337. upstream_commit_to_push,
  1338. upstream_new_last_upload,
  1339. upstream_parent, upstream_desc,
  1340. prev_patchset)
  1341. mockSquashedCommit.side_effect = [
  1342. new_upload_upstream, new_upload_current
  1343. ]
  1344. options = optparse.Values()
  1345. options.send_mail = options.private = False
  1346. options.squash = True
  1347. options.title = None
  1348. options.message = 'honk stonk'
  1349. options.topic = 'circus'
  1350. options.enable_auto_submit = False
  1351. options.set_bot_commit = False
  1352. options.cq_dry_run = False
  1353. options.use_commit_queue = False
  1354. options.hashtags = ['cow']
  1355. options.target_branch = None
  1356. options.push_options = ['uploadvalidator~skip']
  1357. orig_args = []
  1358. mockRunGitPush.return_value = (
  1359. 'remote: https://chromium-review.'
  1360. 'googlesource.com/c/chromium/circus/clown/+/1233 kwak'
  1361. '\n'
  1362. 'remote: https://chromium-review.'
  1363. 'googlesource.com/c/chromium/circus/clown/+/1234 stonks')
  1364. # Call
  1365. git_cl.UploadAllSquashed(options, orig_args)
  1366. # Asserts
  1367. self.maxDiff = None
  1368. self.assertEqual(mockSquashedCommit.mock_calls, [
  1369. mock.call(options,
  1370. 'current-upstream-ancestor',
  1371. 'current-upstream-ancestor',
  1372. end_commit='next-upstream-ancestor'),
  1373. mock.call(options,
  1374. upstream_commit_to_push,
  1375. 'next-upstream-ancestor',
  1376. end_commit=None)
  1377. ])
  1378. expected_refspec = ('commit-to-push:refs/for/refs/heads/main%'
  1379. 'topic=circus,hashtag=cow')
  1380. expected_refspec_opts = ['topic=circus', 'hashtag=cow']
  1381. mockRunGitPush.assert_called_once_with(expected_refspec,
  1382. expected_refspec_opts, mock.ANY,
  1383. options.push_options)
  1384. self.assertEqual(mockPostUploadUpdates.mock_calls, [
  1385. mock.call(options, new_upload_upstream, '1233'),
  1386. mock.call(options, new_upload_current, '1234')
  1387. ])
  1388. @mock.patch('git_cl.Changelist.GetGerritHost',
  1389. return_value='chromium-review.googlesource.com')
  1390. @mock.patch('git_cl.Changelist.GetRemoteBranch',
  1391. return_value=('origin', 'refs/remotes/origin/main'))
  1392. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream',
  1393. return_value='current-upstream-ancestor')
  1394. @mock.patch('git_cl.Changelist._UpdateWithExternalChanges')
  1395. @mock.patch('git_cl.Changelist.PostUploadUpdates')
  1396. @mock.patch('git_cl.Changelist._RunGitPushWithTraces')
  1397. @mock.patch('git_cl._UploadAllPrecheck')
  1398. @mock.patch('git_cl.Changelist.PrepareSquashedCommit')
  1399. def test_upload_all_squashed_external_changes(self, mockSquashedCommit,
  1400. mockUploadAllPrecheck,
  1401. mockRunGitPush,
  1402. mockPostUploadUpdates,
  1403. mockExternalChanges, *_mocks):
  1404. options = optparse.Values()
  1405. options.send_mail = options.private = False
  1406. options.squash = True
  1407. options.title = None
  1408. options.topic = 'circus'
  1409. options.message = 'honk stonk'
  1410. options.enable_auto_submit = False
  1411. options.set_bot_commit = False
  1412. options.cq_dry_run = False
  1413. options.use_commit_queue = False
  1414. options.hashtags = ['cow']
  1415. options.target_branch = None
  1416. options.push_options = ['uploadvalidator~skip']
  1417. orig_args = []
  1418. cls = [
  1419. git_cl.Changelist(branchref='refs/heads/current-branch',
  1420. issue='12345')
  1421. ]
  1422. mockUploadAllPrecheck.return_value = (cls, False)
  1423. reviewers = []
  1424. ccs = []
  1425. # Test case: user wants to pull in external changes.
  1426. mockExternalChanges.reset_mock()
  1427. mockExternalChanges.return_value = None
  1428. current_commit_to_push = 'commit-to-push'
  1429. current_new_last_upload = 'new-last-upload'
  1430. change_desc = git_cl.ChangeDescription(
  1431. 'stonks/nChange-Id:ec15e81197380')
  1432. prev_patchset = 2
  1433. new_upload_current = git_cl._NewUpload(reviewers, ccs,
  1434. current_commit_to_push,
  1435. current_new_last_upload,
  1436. 'next-upstream-ancestor',
  1437. change_desc, prev_patchset)
  1438. mockSquashedCommit.return_value = new_upload_current
  1439. mockRunGitPush.return_value = (
  1440. 'remote: https://chromium-review.'
  1441. 'googlesource.com/c/chromium/circus/clown/+/1233 kwak')
  1442. # Test case: user wants to pull in external changes.
  1443. mockExternalChanges.reset_mock()
  1444. mockExternalChanges.return_value = 'external-commit'
  1445. # Call
  1446. git_cl.UploadAllSquashed(options, orig_args)
  1447. # Asserts
  1448. self.assertEqual(mockSquashedCommit.mock_calls, [
  1449. mock.call(
  1450. options, 'external-commit', 'external-commit', end_commit=None)
  1451. ])
  1452. expected_refspec = ('commit-to-push:refs/for/refs/heads/main%'
  1453. 'm=honk_stonk,topic=circus,hashtag=cow')
  1454. expected_refspec_opts = ['m=honk_stonk', 'topic=circus', 'hashtag=cow']
  1455. mockRunGitPush.assert_called_once_with(expected_refspec,
  1456. expected_refspec_opts, mock.ANY,
  1457. options.push_options)
  1458. self.assertEqual(mockPostUploadUpdates.mock_calls,
  1459. [mock.call(options, new_upload_current, '1233')])
  1460. # Test case: user does not want external changes or there are none.
  1461. mockSquashedCommit.reset_mock()
  1462. mockExternalChanges.return_value = None
  1463. # Call
  1464. git_cl.UploadAllSquashed(options, orig_args)
  1465. # Asserts
  1466. self.assertEqual(mockSquashedCommit.mock_calls, [
  1467. mock.call(options,
  1468. 'current-upstream-ancestor',
  1469. 'current-upstream-ancestor',
  1470. end_commit=None)
  1471. ])
  1472. @mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  1473. lambda offer_removal: None)
  1474. @mock.patch('git_cl.RunGit')
  1475. @mock.patch('git_cl.RunGitSilent')
  1476. @mock.patch('git_cl.Changelist._GitGetBranchConfigValue')
  1477. @mock.patch('git_cl.Changelist.FetchUpstreamTuple')
  1478. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  1479. @mock.patch('scm.GIT.GetBranchRef')
  1480. @mock.patch('git_cl.Changelist.GetRemoteBranch')
  1481. @mock.patch('scm.GIT.IsAncestor')
  1482. @mock.patch('gclient_utils.AskForData')
  1483. def test_upload_all_precheck_long_chain(
  1484. self, mockAskForData, mockIsAncestor, mockGetRemoteBranch,
  1485. mockGetBranchRef, mockGetCommonAncestorWithUpstream,
  1486. mockFetchUpstreamTuple, mockGitGetBranchConfigValue,
  1487. mockRunGitSilent, mockRunGit, *_mocks):
  1488. mockGetRemoteBranch.return_value = ('origin',
  1489. 'refs/remotes/origin/main')
  1490. branches = [
  1491. 'current', 'upstream3', 'blank3', 'blank2', 'upstream2', 'blank1',
  1492. 'upstream1', 'origin/main'
  1493. ]
  1494. mockGetBranchRef.side_effect = (
  1495. ['refs/heads/current'] + # detached HEAD check
  1496. ['refs/heads/%s' % b for b in branches])
  1497. mockGetCommonAncestorWithUpstream.side_effect = [
  1498. 'commit3.5',
  1499. 'commit3.5',
  1500. 'commit3.5',
  1501. 'commit2.5',
  1502. 'commit1.5',
  1503. 'commit1.5',
  1504. 'commit0.5',
  1505. ]
  1506. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1507. ('.', 'refs/heads/blank3'),
  1508. ('.', 'refs/heads/blank2'),
  1509. ('.', 'refs/heads/upstream2'),
  1510. ('.', 'refs/heads/blank1'),
  1511. ('.', 'refs/heads/upstream1'),
  1512. ('origin',
  1513. 'refs/heads/origin/main')]
  1514. # end commits
  1515. mockRunGit.side_effect = [
  1516. 'commit4', 'commit3.5', 'commit3.5', 'commit2', 'commit1.5',
  1517. 'commit1', 'commit0.5'
  1518. ]
  1519. mockRunGitSilent.side_effect = ['80', '81', '0', '0', '82', '0', '83']
  1520. # Get gerrit squash hash. We only check this for branches that have a
  1521. # diff. Set to None to trigger `must_upload_upstream`.
  1522. mockGitGetBranchConfigValue.return_value = None
  1523. options = optparse.Values()
  1524. options.force = False
  1525. options.cherry_pick_stacked = False
  1526. orig_args = ['--preserve-tryjobs', '--chicken']
  1527. # Case 2: upstream3 has never been uploaded.
  1528. # (so no LAST_UPLOAD_HASH_CONIFG_KEY)
  1529. # Case 4: upstream2's last_upload is behind upstream3's base_commit
  1530. key = f'branch.upstream2.{git_cl.LAST_UPLOAD_HASH_CONFIG_KEY}'
  1531. scm.GIT.SetConfig('', key, 'commit2.3')
  1532. mockIsAncestor.side_effect = [True]
  1533. # Case 3: upstream1's last_upload matches upstream2's base_commit
  1534. key = f'branch.upstream1.{git_cl.LAST_UPLOAD_HASH_CONFIG_KEY}'
  1535. scm.GIT.SetConfig('', key, 'commit1.5')
  1536. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1537. self.assertFalse(cherry_pick)
  1538. mockAskForData.assert_called_once_with(
  1539. "\noptions ['--preserve-tryjobs', '--chicken'] will be used for all "
  1540. "uploads.\nAt least one parent branch in `current, upstream3, "
  1541. "upstream2` has never been uploaded and must be uploaded before/with "
  1542. "`upstream3`.\nPress Enter to confirm, or Ctrl+C to abort")
  1543. self.assertEqual(len(cls), 3)
  1544. @mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  1545. lambda offer_removal: None)
  1546. @mock.patch('git_cl.RunGit')
  1547. @mock.patch('git_cl.RunGitSilent')
  1548. @mock.patch('git_cl.Changelist._GitGetBranchConfigValue')
  1549. @mock.patch('git_cl.Changelist.FetchUpstreamTuple')
  1550. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  1551. @mock.patch('scm.GIT.GetBranchRef')
  1552. @mock.patch('git_cl.Changelist.GetRemoteBranch')
  1553. @mock.patch('scm.GIT.IsAncestor')
  1554. @mock.patch('gclient_utils.AskForData')
  1555. def test_upload_all_precheck_options_must_upload(
  1556. self, mockAskForData, mockIsAncestor, mockGetRemoteBranch,
  1557. mockGetBranchRef, mockGetCommonAncestorWithUpstream,
  1558. mockFetchUpstreamTuple, mockGitGetBranchConfigValue,
  1559. mockRunGitSilent, mockRunGit, *_mocks):
  1560. mockGetRemoteBranch.return_value = ('origin',
  1561. 'refs/remotes/origin/main')
  1562. branches = ['current', 'upstream3', 'main']
  1563. mockGetBranchRef.side_effect = (
  1564. ['refs/heads/current'] + # detached HEAD check
  1565. ['refs/heads/%s' % b for b in branches])
  1566. mockGetCommonAncestorWithUpstream.side_effect = [
  1567. 'commit3.5', 'commit0.5'
  1568. ]
  1569. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1570. ('origin', 'refs/heads/main')]
  1571. mockIsAncestor.return_value = True
  1572. # end commits
  1573. mockRunGit.return_value = 'any-commit'
  1574. mockRunGitSilent.return_value = '42'
  1575. # Get gerrit squash hash. We only check this for branches that have a
  1576. # diff.
  1577. mockGitGetBranchConfigValue.return_value = None
  1578. # Test case: User wants to cherry pick, but all branches must be
  1579. # uploaded.
  1580. options = optparse.Values()
  1581. options.force = True
  1582. options.cherry_pick_stacked = True
  1583. orig_args = []
  1584. with self.assertRaises(SystemExitMock):
  1585. git_cl._UploadAllPrecheck(options, orig_args)
  1586. # Test case: User does not require cherry picking
  1587. options.cherry_pick_stacked = False
  1588. # reset side_effects
  1589. mockGetBranchRef.side_effect = (
  1590. ['refs/heads/current'] + # detached HEAD check
  1591. ['refs/heads/%s' % b for b in branches])
  1592. mockGetCommonAncestorWithUpstream.side_effect = [
  1593. 'commit3.5', 'commit0.5'
  1594. ]
  1595. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1596. ('origin', 'refs/heads/main')]
  1597. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1598. self.assertFalse(cherry_pick)
  1599. self.assertEqual(len(cls), 2)
  1600. mockAskForData.assert_not_called()
  1601. # Test case: User does not require cherry picking and not in force mode.
  1602. options.force = False
  1603. # reset side_effects
  1604. mockGetBranchRef.side_effect = (
  1605. ['refs/heads/current'] + # detached HEAD check
  1606. ['refs/heads/%s' % b for b in branches])
  1607. mockGetCommonAncestorWithUpstream.side_effect = [
  1608. 'commit3.5', 'commit0.5'
  1609. ]
  1610. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1611. ('origin', 'refs/heads/main')]
  1612. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1613. self.assertFalse(cherry_pick)
  1614. self.assertEqual(len(cls), 2)
  1615. mockAskForData.assert_called_once()
  1616. @mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  1617. lambda offer_removal: None)
  1618. @mock.patch('git_cl.RunGit')
  1619. @mock.patch('git_cl.RunGitSilent')
  1620. @mock.patch('git_cl.Changelist._GitGetBranchConfigValue')
  1621. @mock.patch('git_cl.Changelist.FetchUpstreamTuple')
  1622. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  1623. @mock.patch('scm.GIT.GetBranchRef')
  1624. @mock.patch('scm.GIT.IsAncestor')
  1625. @mock.patch('gclient_utils.AskForData')
  1626. def test_upload_all_precheck_must_rebase(
  1627. self, mockAskForData, mockIsAncestor, mockGetBranchRef,
  1628. mockGetCommonAncestorWithUpstream, mockFetchUpstreamTuple,
  1629. mockGitGetBranchConfigValue, mockRunGitSilent, mockRunGit, *_mocks):
  1630. branches = ['current', 'upstream3']
  1631. mockGetBranchRef.side_effect = ['refs/heads/%s' % b for b in branches]
  1632. mockGetCommonAncestorWithUpstream.return_value = 'commit3.5'
  1633. mockFetchUpstreamTuple.return_value = ('.', 'refs/heads/upstream3')
  1634. # end commits
  1635. mockRunGit.return_value = 'commit4'
  1636. mockRunGitSilent.return_value = '42'
  1637. # Get gerrit squash hash. We only check this for branches that have a
  1638. # diff. Set to None to trigger `must_upload_upstream`.
  1639. mockGitGetBranchConfigValue.return_value = None
  1640. # Case 5: current's base_commit is behind upstream3's last_upload.
  1641. key = f'branch.upstream3.{git_cl.LAST_UPLOAD_HASH_CONFIG_KEY}'
  1642. scm.GIT.SetConfig('', key, 'commit3.7')
  1643. mockIsAncestor.side_effect = [False, True]
  1644. with self.assertRaises(SystemExitMock):
  1645. options = optparse.Values()
  1646. options.force = False
  1647. options.cherry_pick_stacked = False
  1648. git_cl._UploadAllPrecheck(options, [])
  1649. @mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  1650. lambda offer_removal: None)
  1651. @mock.patch('git_cl.RunGit')
  1652. @mock.patch('git_cl.RunGitSilent')
  1653. @mock.patch('git_cl.Changelist._GitGetBranchConfigValue')
  1654. @mock.patch('git_cl.Changelist.FetchUpstreamTuple')
  1655. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  1656. @mock.patch('scm.GIT.GetBranchRef')
  1657. @mock.patch('git_cl.Changelist.GetRemoteBranch')
  1658. @mock.patch('scm.GIT.IsAncestor')
  1659. @mock.patch('gclient_utils.AskForData')
  1660. def test_upload_all_precheck_hit_main(
  1661. self, mockAskForData, mockIsAncestor, mockGetRemoteBranch,
  1662. mockGetBranchRef, mockGetCommonAncestorWithUpstream,
  1663. mockFetchUpstreamTuple, mockGitGetBranchConfigValue,
  1664. mockRunGitSilent, mockRunGit, *_mocks):
  1665. options = optparse.Values()
  1666. options.force = False
  1667. options.cherry_pick_stacked = False
  1668. orig_args = ['--preserve-tryjobs', '--chicken']
  1669. mockGetRemoteBranch.return_value = ('origin',
  1670. 'refs/remotes/origin/main')
  1671. branches = ['current', 'upstream3', 'main']
  1672. mockGetBranchRef.side_effect = (
  1673. ['refs/heads/current'] + # detached HEAD check
  1674. ['refs/heads/%s' % b for b in branches])
  1675. mockGetCommonAncestorWithUpstream.side_effect = [
  1676. 'commit3.5', 'commit0.5'
  1677. ]
  1678. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1679. ('origin', 'refs/heads/main')]
  1680. mockIsAncestor.return_value = True
  1681. # Give upstream3 a last upload hash
  1682. key = f'branch.upstream3.{git_cl.LAST_UPLOAD_HASH_CONFIG_KEY}'
  1683. scm.GIT.SetConfig('', key, 'commit3.4')
  1684. # end commits
  1685. mockRunGit.return_value = 'commit4'
  1686. mockRunGitSilent.return_value = '42'
  1687. # Get gerrit squash hash. We only check this for branches that have a
  1688. # diff.
  1689. mockGitGetBranchConfigValue.return_value = 'just needs to exist'
  1690. # Test case: user cherry picks with options
  1691. options.cherry_pick_stacked = True
  1692. # Reset side_effects
  1693. mockGetBranchRef.side_effect = (
  1694. ['refs/heads/current'] + # detached HEAD check
  1695. ['refs/heads/%s' % b for b in branches])
  1696. mockGetCommonAncestorWithUpstream.side_effect = [
  1697. 'commit3.5', 'commit0.5'
  1698. ]
  1699. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1700. ('origin', 'refs/heads/main')]
  1701. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1702. self.assertTrue(cherry_pick)
  1703. self.assertEqual(len(cls), 2)
  1704. mockAskForData.assert_not_called()
  1705. # Test case: user uses force, no cherry-pick.
  1706. options.cherry_pick_stacked = False
  1707. options.force = True
  1708. # Reset side_effects
  1709. mockGetBranchRef.side_effect = (
  1710. ['refs/heads/current'] + # detached HEAD check
  1711. ['refs/heads/%s' % b for b in branches])
  1712. mockGetCommonAncestorWithUpstream.side_effect = [
  1713. 'commit3.5', 'commit0.5'
  1714. ]
  1715. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1716. ('origin', 'refs/heads/main')]
  1717. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1718. self.assertFalse(cherry_pick)
  1719. self.assertEqual(len(cls), 2)
  1720. mockAskForData.assert_not_called()
  1721. # Test case: user wants to cherry pick after being asked.
  1722. mockAskForData.return_value = 'n'
  1723. options.cherry_pick_stacked = False
  1724. options.force = False
  1725. # Reset side_effects
  1726. mockGetBranchRef.side_effect = (
  1727. ['refs/heads/current'] + # detached HEAD check
  1728. ['refs/heads/%s' % b for b in branches])
  1729. mockGetCommonAncestorWithUpstream.side_effect = [
  1730. 'commit3.5', 'commit0.5'
  1731. ]
  1732. mockFetchUpstreamTuple.side_effect = [('.', 'refs/heads/upstream3'),
  1733. ('origin', 'refs/heads/main')]
  1734. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1735. self.assertTrue(cherry_pick)
  1736. self.assertEqual(len(cls), 2)
  1737. mockAskForData.assert_called_once_with(
  1738. "\noptions ['--preserve-tryjobs', '--chicken'] will be used for all "
  1739. "uploads.\n"
  1740. "Press enter to update branches current, upstream3.\n"
  1741. "Or type `n` to upload only `current` cherry-picked on upstream3's "
  1742. "last upload:")
  1743. @mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  1744. lambda offer_removal: None)
  1745. @mock.patch('git_cl.RunGit')
  1746. @mock.patch('git_cl.RunGitSilent')
  1747. @mock.patch('git_cl.Changelist._GitGetBranchConfigValue')
  1748. @mock.patch('git_cl.Changelist.FetchUpstreamTuple')
  1749. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  1750. @mock.patch('scm.GIT.GetBranchRef')
  1751. @mock.patch('git_cl.Changelist.GetRemoteBranch')
  1752. @mock.patch('scm.GIT.IsAncestor')
  1753. @mock.patch('gclient_utils.AskForData')
  1754. def test_upload_all_precheck_one_change(
  1755. self, mockAskForData, mockIsAncestor, mockGetRemoteBranch,
  1756. mockGetBranchRef, mockGetCommonAncestorWithUpstream,
  1757. mockFetchUpstreamTuple, mockGitGetBranchConfigValue,
  1758. mockRunGitSilent, mockRunGit, *_mocks):
  1759. options = optparse.Values()
  1760. options.force = False
  1761. options.cherry_pick_stacked = False
  1762. orig_args = ['--preserve-tryjobs', '--chicken']
  1763. mockGetRemoteBranch.return_value = ('origin',
  1764. 'refs/remotes/origin/main')
  1765. mockGetBranchRef.side_effect = [
  1766. 'refs/heads/current', # detached HEAD check
  1767. 'refs/heads/current', # call within while loop
  1768. 'refs/heads/main',
  1769. 'refs/heads/main'
  1770. ]
  1771. mockGetCommonAncestorWithUpstream.return_value = 'commit3.5'
  1772. mockFetchUpstreamTuple.return_value = ('', 'refs/heads/main')
  1773. mockIsAncestor.return_value = True
  1774. # end commits
  1775. mockRunGit.return_value = 'commit4'
  1776. mockRunGitSilent.return_value = '42'
  1777. # Get gerrit squash hash. We only check this for branches that have a
  1778. # diff. Set to None to trigger `must_upload_upstream`.
  1779. mockGitGetBranchConfigValue.return_value = 'does not matter'
  1780. # Case 1: We hit the main branch
  1781. cls, cherry_pick = git_cl._UploadAllPrecheck(options, orig_args)
  1782. self.assertFalse(cherry_pick)
  1783. self.assertEqual(len(cls), 1)
  1784. mockAskForData.assert_not_called()
  1785. # No diff for current change
  1786. mockRunGitSilent.return_value = '0'
  1787. with self.assertRaises(SystemExitMock):
  1788. git_cl._UploadAllPrecheck(options, orig_args)
  1789. @mock.patch('scm.GIT.GetBranchRef', return_value=None)
  1790. def test_upload_all_precheck_detached_HEAD(self, mockGetBranchRef):
  1791. with self.assertRaises(SystemExitMock):
  1792. git_cl._UploadAllPrecheck(optparse.Values(), [])
  1793. @mock.patch('git_cl.RunGit')
  1794. @mock.patch('git_cl.CMDupload')
  1795. @mock.patch('sys.stdin', io.StringIO('\n'))
  1796. @mock.patch('sys.stdout', io.StringIO())
  1797. def test_upload_branch_deps(self, *_mocks):
  1798. def mock_run_git(*args, **_kwargs):
  1799. if args[0] == [
  1800. 'for-each-ref',
  1801. '--format=%(refname:short) %(upstream:short)', 'refs/heads'
  1802. ]:
  1803. # Create a local branch dependency tree that looks like this:
  1804. # test1 -> test2 -> test3 -> test4 -> test5
  1805. # -> test3.1
  1806. # test6 -> test0
  1807. branch_deps = [
  1808. 'test2 test1', # test1 -> test2
  1809. 'test3 test2', # test2 -> test3
  1810. 'test3.1 test2', # test2 -> test3.1
  1811. 'test4 test3', # test3 -> test4
  1812. 'test5 test4', # test4 -> test5
  1813. 'test6 test0', # test0 -> test6
  1814. 'test7', # test7
  1815. ]
  1816. return '\n'.join(branch_deps)
  1817. git_cl.RunGit.side_effect = mock_run_git
  1818. git_cl.CMDupload.return_value = 0
  1819. class MockChangelist():
  1820. def __init__(self):
  1821. pass
  1822. def GetBranch(self):
  1823. return 'test1'
  1824. def GetIssue(self):
  1825. return '123'
  1826. def GetPatchset(self):
  1827. return '1001'
  1828. def IsGerrit(self):
  1829. return False
  1830. ret = git_cl.upload_branch_deps(MockChangelist(), [])
  1831. # CMDupload should have been called 5 times because of 5 dependent
  1832. # branches.
  1833. self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
  1834. self.assertEqual(0, ret)
  1835. def test_gerrit_change_id(self):
  1836. self.calls = [
  1837. ((['git', 'write-tree'], ), 'hashtree'),
  1838. ((['git', 'rev-parse', 'HEAD~0'], ), 'branch-parent'),
  1839. ((['git', 'var',
  1840. 'GIT_AUTHOR_IDENT'], ), 'A B <a@b.org> 1456848326 +0100'),
  1841. ((['git', 'var',
  1842. 'GIT_COMMITTER_IDENT'], ), 'C D <c@d.org> 1456858326 +0100'),
  1843. ((['git', 'hash-object', '-t', 'commit',
  1844. '--stdin'], ), 'hashchange'),
  1845. ]
  1846. change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
  1847. self.assertEqual(change_id, 'Ihashchange')
  1848. @mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost')
  1849. @mock.patch('git_cl.Settings.GetBugPrefix')
  1850. @mock.patch('git_cl.Changelist.FetchDescription')
  1851. @mock.patch('git_cl.Changelist.GetBranch')
  1852. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  1853. @mock.patch('git_cl.Changelist.GetGerritHost')
  1854. @mock.patch('git_cl.Changelist.GetGerritProject')
  1855. @mock.patch('git_cl.Changelist.GetRemoteBranch')
  1856. @mock.patch('owners_client.OwnersClient.BatchListOwners')
  1857. def getDescriptionForUploadTest(self,
  1858. mockBatchListOwners=None,
  1859. mockGetRemoteBranch=None,
  1860. mockGetGerritProject=None,
  1861. mockGetGerritHost=None,
  1862. mockGetCommonAncestorWithUpstream=None,
  1863. mockGetBranch=None,
  1864. mockFetchDescription=None,
  1865. mockGetBugPrefix=None,
  1866. mockIsCodeOwnersEnabledOnHost=None,
  1867. initial_description='desc',
  1868. commit_description=None,
  1869. bug=None,
  1870. fixed=None,
  1871. branch='branch',
  1872. reviewers=None,
  1873. add_owners_to=None,
  1874. expected_description='desc'):
  1875. reviewers = reviewers or []
  1876. owners_by_path = {
  1877. 'a': ['a@example.com'],
  1878. 'b': ['b@example.com'],
  1879. 'c': ['c@example.com'],
  1880. }
  1881. mockIsCodeOwnersEnabledOnHost.return_value = True
  1882. mockGetBranch.return_value = branch
  1883. mockGetBugPrefix.return_value = 'prefix'
  1884. mockGetCommonAncestorWithUpstream.return_value = 'upstream'
  1885. mockGetRemoteBranch.return_value = ('origin',
  1886. 'refs/remotes/origin/main')
  1887. mockFetchDescription.return_value = 'desc'
  1888. mockBatchListOwners.side_effect = lambda ps: {
  1889. p: owners_by_path.get(p)
  1890. for p in ps
  1891. }
  1892. cl = git_cl.Changelist(issue=1234)
  1893. actual = cl._GetDescriptionForUpload(options=mock.Mock(
  1894. bug=bug,
  1895. fixed=fixed,
  1896. reviewers=reviewers,
  1897. add_owners_to=add_owners_to,
  1898. message=initial_description,
  1899. commit_description=commit_description),
  1900. git_diff_args=None,
  1901. files=list(owners_by_path))
  1902. self.assertEqual(expected_description, actual.description)
  1903. def testGetDescriptionForUpload(self):
  1904. self.getDescriptionForUploadTest()
  1905. def testGetDescriptionForUpload_Bug(self):
  1906. self.getDescriptionForUploadTest(bug='1234',
  1907. expected_description='\n'.join([
  1908. 'desc',
  1909. '',
  1910. 'Bug: prefix:1234',
  1911. ]))
  1912. def testGetDescriptionForUpload_Fixed(self):
  1913. self.getDescriptionForUploadTest(fixed='1234',
  1914. expected_description='\n'.join([
  1915. 'desc',
  1916. '',
  1917. 'Fixed: prefix:1234',
  1918. ]))
  1919. @mock.patch('git_cl.Changelist.GetIssue')
  1920. def testGetDescriptionForUpload_BugFromBranch(self, mockGetIssue):
  1921. mockGetIssue.return_value = None
  1922. self.getDescriptionForUploadTest(branch='bug-1234',
  1923. expected_description='\n'.join([
  1924. 'desc',
  1925. '',
  1926. 'Bug: prefix:1234',
  1927. ]))
  1928. @mock.patch('git_cl.Changelist.GetIssue')
  1929. def testGetDescriptionForUpload_FixedFromBranch(self, mockGetIssue):
  1930. mockGetIssue.return_value = None
  1931. self.getDescriptionForUploadTest(branch='fix-1234',
  1932. expected_description='\n'.join([
  1933. 'desc',
  1934. '',
  1935. 'Fixed: prefix:1234',
  1936. ]))
  1937. def testGetDescriptionForUpload_SkipBugFromBranchIfAlreadyUploaded(self):
  1938. self.getDescriptionForUploadTest(
  1939. branch='bug-1234',
  1940. expected_description='desc',
  1941. )
  1942. def testGetDescriptionForUpload_AddOwnersToR(self):
  1943. self.getDescriptionForUploadTest(
  1944. reviewers=['a@example.com'],
  1945. add_owners_to='R',
  1946. expected_description='\n'.join([
  1947. 'desc',
  1948. '',
  1949. 'R=a@example.com, b@example.com, c@example.com',
  1950. ]))
  1951. def testGetDescriptionForUpload_AddOwnersToNoOwnersNeeded(self):
  1952. self.getDescriptionForUploadTest(
  1953. reviewers=['a@example.com', 'c@example.com'],
  1954. expected_description='\n'.join([
  1955. 'desc',
  1956. '',
  1957. 'R=a@example.com, c@example.com',
  1958. ]))
  1959. def testGetDescriptionForUpload_Reviewers(self):
  1960. self.getDescriptionForUploadTest(
  1961. reviewers=['a@example.com', 'b@example.com'],
  1962. expected_description='\n'.join([
  1963. 'desc',
  1964. '',
  1965. 'R=a@example.com, b@example.com',
  1966. ]))
  1967. def testGetDescriptionForUpload_NewDesc(self):
  1968. self.getDescriptionForUploadTest(
  1969. commit_description='this is a new desc',
  1970. expected_description='this is a new desc')
  1971. @mock.patch('sys.stdin', io.StringIO('this is a new desc'))
  1972. def testGetDescriptionForUpload_NewDescFromStdin(self):
  1973. self.getDescriptionForUploadTest(
  1974. commit_description='-', expected_description='this is a new desc')
  1975. def test_description_append_footer(self):
  1976. for init_desc, footer_line, expected_desc in [
  1977. # Use unique desc first lines for easy test failure
  1978. # identification.
  1979. ('foo', 'R=one', 'foo\n\nR=one'),
  1980. ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
  1981. ('foo\n\nR=one', 'Change-Id: Ixx',
  1982. 'foo\n\nR=one\n\nChange-Id: Ixx'),
  1983. ('foo\n\nChange-Id: Ixx', 'R=one',
  1984. 'foo\n\nR=one\n\nChange-Id: Ixx'),
  1985. ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
  1986. 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
  1987. ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
  1988. 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
  1989. ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
  1990. ]:
  1991. desc = git_cl.ChangeDescription(init_desc)
  1992. desc.append_footer(footer_line)
  1993. self.assertEqual(desc.description, expected_desc)
  1994. def test_update_reviewers(self):
  1995. data = [
  1996. ('foo', [], 'foo'),
  1997. ('foo\nR=xx', [], 'foo\nR=xx'),
  1998. ('foo', ['a@c'], 'foo\n\nR=a@c'),
  1999. ('foo\nR=xx', ['a@c'], 'foo\n\nR=a@c, xx'),
  2000. ('foo\nBUG=', ['a@c'], 'foo\nBUG=\nR=a@c'),
  2001. ('foo\nR=xx\nR=bar', ['a@c'], 'foo\n\nR=a@c, bar, xx'),
  2002. ('foo', ['a@c', 'b@c'], 'foo\n\nR=a@c, b@c'),
  2003. ('foo\nBar\n\nR=\nBUG=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
  2004. ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], 'foo\nBar\n\nR=c@c\nBUG='),
  2005. # Same as the line before, but full of whitespaces.
  2006. (
  2007. 'foo\nBar\n\n R = \n BUG = \n R = ',
  2008. ['c@c'],
  2009. 'foo\nBar\n\nR=c@c\n BUG =',
  2010. ),
  2011. # Whitespaces aren't interpreted as new lines.
  2012. ('foo BUG=allo R=joe ', ['c@c'], 'foo BUG=allo R=joe\n\nR=c@c'),
  2013. ]
  2014. expected = [i[-1] for i in data]
  2015. actual = []
  2016. for orig, reviewers, _expected in data:
  2017. obj = git_cl.ChangeDescription(orig)
  2018. obj.update_reviewers(reviewers)
  2019. actual.append(obj.description)
  2020. self.assertEqual(expected, actual)
  2021. def test_get_hash_tags(self):
  2022. cases = [
  2023. ('', []),
  2024. ('a', []),
  2025. ('[a]', ['a']),
  2026. ('[aa]', ['aa']),
  2027. ('[a ]', ['a']),
  2028. ('[a- ]', ['a']),
  2029. ('[a- b]', ['a-b']),
  2030. ('[a--b]', ['a-b']),
  2031. ('[a', []),
  2032. ('[a]x', ['a']),
  2033. ('[aa]x', ['aa']),
  2034. ('[a b]', ['a-b']),
  2035. ('[a b]', ['a-b']),
  2036. ('[a__b]', ['a-b']),
  2037. ('[a] x', ['a']),
  2038. ('[a][b]', ['a', 'b']),
  2039. ('[a] [b]', ['a', 'b']),
  2040. ('[a][b]x', ['a', 'b']),
  2041. ('[a][b] x', ['a', 'b']),
  2042. ('[a]\n[b]', ['a']),
  2043. ('[a\nb]', []),
  2044. ('[a][', ['a']),
  2045. ('Revert "[a] feature"', ['a']),
  2046. ('Reland "[a] feature"', ['a']),
  2047. ('Revert: [a] feature', ['a']),
  2048. ('Reland: [a] feature', ['a']),
  2049. ('Revert "Reland: [a] feature"', ['a']),
  2050. ('Foo: feature', ['foo']),
  2051. ('Foo Bar: feature', ['foo-bar']),
  2052. ('Change Foo::Bar', []),
  2053. ('Foo: Change Foo::Bar', ['foo']),
  2054. ('Revert "Foo bar: feature"', ['foo-bar']),
  2055. ('Reland "Foo bar: feature"', ['foo-bar']),
  2056. ]
  2057. for desc, expected in cases:
  2058. change_desc = git_cl.ChangeDescription(desc)
  2059. actual = change_desc.get_hash_tags()
  2060. self.assertEqual(
  2061. actual, expected,
  2062. 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
  2063. self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'main'))
  2064. self.assertEqual(
  2065. None, git_cl.GetTargetRef(None, 'refs/remotes/origin/main', 'main'))
  2066. # Check default target refs for branches.
  2067. self.assertEqual(
  2068. 'refs/heads/main',
  2069. git_cl.GetTargetRef('origin', 'refs/remotes/origin/main', None))
  2070. self.assertEqual(
  2071. 'refs/heads/main',
  2072. git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr', None))
  2073. self.assertEqual(
  2074. 'refs/heads/main',
  2075. git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr', None))
  2076. self.assertEqual(
  2077. 'refs/branch-heads/123',
  2078. git_cl.GetTargetRef('origin', 'refs/remotes/branch-heads/123',
  2079. None))
  2080. self.assertEqual(
  2081. 'refs/diff/test',
  2082. git_cl.GetTargetRef('origin', 'refs/remotes/origin/refs/diff/test',
  2083. None))
  2084. self.assertEqual(
  2085. 'refs/heads/chrome/m42',
  2086. git_cl.GetTargetRef('origin', 'refs/remotes/origin/chrome/m42',
  2087. None))
  2088. # Check target refs for user-specified target branch.
  2089. for branch in ('branch-heads/123', 'remotes/branch-heads/123',
  2090. 'refs/remotes/branch-heads/123'):
  2091. self.assertEqual(
  2092. 'refs/branch-heads/123',
  2093. git_cl.GetTargetRef('origin', 'refs/remotes/origin/main',
  2094. branch))
  2095. for branch in ('origin/main', 'remotes/origin/main',
  2096. 'refs/remotes/origin/main'):
  2097. self.assertEqual(
  2098. 'refs/heads/main',
  2099. git_cl.GetTargetRef('origin', 'refs/remotes/branch-heads/123',
  2100. branch))
  2101. for branch in ('main', 'heads/main', 'refs/heads/main'):
  2102. self.assertEqual(
  2103. 'refs/heads/main',
  2104. git_cl.GetTargetRef('origin', 'refs/remotes/branch-heads/123',
  2105. branch))
  2106. @mock.patch('git_common.is_dirty_git_tree', return_value=True)
  2107. def test_patch_when_dirty(self, *_mocks):
  2108. # Patch when local tree is dirty.
  2109. self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
  2110. def assertIssueAndPatchset(self,
  2111. branch='main',
  2112. issue='123456',
  2113. patchset='7',
  2114. git_short_host='chromium'):
  2115. self.assertEqual(issue,
  2116. scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
  2117. self.assertEqual(patchset,
  2118. scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
  2119. self.assertEqual('https://%s-review.googlesource.com' % git_short_host,
  2120. scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
  2121. def _patch_common(self, git_short_host='chromium'):
  2122. mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
  2123. scm.GIT.SetConfig('', 'remote.origin.url',
  2124. f'https://{git_short_host}.googlesource.com/my/repo')
  2125. gerrit_util.GetChangeDetail.return_value = {
  2126. 'current_revision': '7777777777',
  2127. 'revisions': {
  2128. '1111111111': {
  2129. '_number': 1,
  2130. 'fetch': {
  2131. 'http': {
  2132. 'url': 'https://%s.googlesource.com/my/repo' %
  2133. git_short_host,
  2134. 'ref': 'refs/changes/56/123456/1',
  2135. }
  2136. },
  2137. },
  2138. '7777777777': {
  2139. '_number': 7,
  2140. 'fetch': {
  2141. 'http': {
  2142. 'url': 'https://%s.googlesource.com/my/repo' %
  2143. git_short_host,
  2144. 'ref': 'refs/changes/56/123456/7',
  2145. }
  2146. },
  2147. },
  2148. },
  2149. }
  2150. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2151. 'not supported in non-git environment')
  2152. def test_patch_gerrit_default(self):
  2153. self._patch_common()
  2154. self.calls += [
  2155. (([
  2156. 'git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  2157. 'refs/changes/56/123456/7'
  2158. ], ), ''),
  2159. ((['git', 'cherry-pick', 'FETCH_HEAD'], ), ''),
  2160. ]
  2161. self.assertEqual(git_cl.main(['patch', '123456']), 0)
  2162. self.assertIssueAndPatchset()
  2163. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2164. 'not supported in non-git environment')
  2165. def test_patch_gerrit_new_branch(self):
  2166. self._patch_common()
  2167. self.calls += [
  2168. (([
  2169. 'git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  2170. 'refs/changes/56/123456/7'
  2171. ], ), ''),
  2172. ((['git', 'cherry-pick', 'FETCH_HEAD'], ), ''),
  2173. ]
  2174. self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
  2175. self.assertIssueAndPatchset(branch='feature')
  2176. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2177. 'not supported in non-git environment')
  2178. def test_patch_gerrit_force(self):
  2179. self._patch_common('host')
  2180. self.calls += [
  2181. (([
  2182. 'git', 'fetch', 'https://host.googlesource.com/my/repo',
  2183. 'refs/changes/56/123456/7'
  2184. ], ), ''),
  2185. ((['git', 'reset', '--hard', 'FETCH_HEAD'], ), ''),
  2186. ]
  2187. self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
  2188. self.assertIssueAndPatchset(git_short_host='host')
  2189. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2190. 'not supported in non-git environment')
  2191. def test_patch_gerrit_guess_by_url(self):
  2192. self._patch_common('else')
  2193. self.calls += [
  2194. (([
  2195. 'git', 'fetch', 'https://else.googlesource.com/my/repo',
  2196. 'refs/changes/56/123456/1'
  2197. ], ), ''),
  2198. ((['git', 'cherry-pick', 'FETCH_HEAD'], ), ''),
  2199. ]
  2200. self.assertEqual(
  2201. git_cl.main(
  2202. ['patch', 'https://else-review.googlesource.com/#/c/123456/1']),
  2203. 0)
  2204. self.assertIssueAndPatchset(patchset='1', git_short_host='else')
  2205. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2206. 'not supported in non-git environment')
  2207. def test_patch_gerrit_guess_by_url_with_repo(self):
  2208. self._patch_common('else')
  2209. self.calls += [
  2210. (([
  2211. 'git', 'fetch', 'https://else.googlesource.com/my/repo',
  2212. 'refs/changes/56/123456/1'
  2213. ], ), ''),
  2214. ((['git', 'cherry-pick', 'FETCH_HEAD'], ), ''),
  2215. ]
  2216. self.assertEqual(
  2217. git_cl.main([
  2218. 'patch',
  2219. 'https://else-review.googlesource.com/c/my/repo/+/123456/1'
  2220. ]), 0)
  2221. self.assertIssueAndPatchset(patchset='1', git_short_host='else')
  2222. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2223. 'not supported in non-git environment')
  2224. @mock.patch('sys.stderr', io.StringIO())
  2225. def test_patch_gerrit_conflict(self):
  2226. self._patch_common()
  2227. self.calls += [
  2228. (([
  2229. 'git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  2230. 'refs/changes/56/123456/7'
  2231. ], ), ''),
  2232. ((['git', 'cherry-pick', 'FETCH_HEAD'], ), CERR1),
  2233. ]
  2234. with self.assertRaises(SystemExitMock):
  2235. git_cl.main(['patch', '123456'])
  2236. self.assertEqual('Command "git cherry-pick FETCH_HEAD" failed.\n\n',
  2237. sys.stderr.getvalue())
  2238. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2239. 'not supported in non-git environment')
  2240. @mock.patch('gerrit_util.GetChangeDetail',
  2241. side_effect=gerrit_util.GerritError(404, ''))
  2242. @mock.patch('sys.stderr', io.StringIO())
  2243. def test_patch_gerrit_not_exists(self, *_mocks):
  2244. scm.GIT.SetConfig('', 'remote.origin.url',
  2245. 'https://chromium.googlesource.com/my/repo')
  2246. with self.assertRaises(SystemExitMock):
  2247. self.assertEqual(1, git_cl.main(['patch', '123456']))
  2248. self.assertEqual(
  2249. 'change 123456 at https://chromium-review.googlesource.com does not '
  2250. 'exist or you have no access to it\n', sys.stderr.getvalue())
  2251. def _checkout_config(self):
  2252. scm.GIT.SetConfig('', 'branch.ger-branch.gerritissue', '123456')
  2253. scm.GIT.SetConfig('', 'branch.gbranch654.gerritissue', '654321')
  2254. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2255. 'not supported in non-git environment')
  2256. def test_checkout_gerrit(self):
  2257. """Tests git cl checkout <issue>."""
  2258. self._checkout_config()
  2259. self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
  2260. self.assertEqual(0, git_cl.main(['checkout', '123456']))
  2261. def test_checkout_not_found(self):
  2262. """Tests git cl checkout <issue>."""
  2263. self._checkout_config()
  2264. self.assertEqual(1, git_cl.main(['checkout', '99999']))
  2265. def test_checkout_no_branch_issues(self):
  2266. """Tests git cl checkout <issue>."""
  2267. self.assertEqual(1, git_cl.main(['checkout', '99999']))
  2268. def _test_gerrit_ensure_authenticated_common(self, auth):
  2269. mock.patch(
  2270. 'gclient_utils.AskForData',
  2271. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  2272. mock.patch(
  2273. 'git_cl.gerrit_util.CookiesAuthenticator',
  2274. CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
  2275. scm.GIT.SetConfig('', 'remote.origin.url',
  2276. 'https://chromium.googlesource.com/my/repo')
  2277. cl = git_cl.Changelist()
  2278. cl.branch = 'main'
  2279. cl.branchref = 'refs/heads/main'
  2280. return cl
  2281. @mock.patch('sys.stderr', io.StringIO())
  2282. def test_gerrit_ensure_authenticated_missing(self):
  2283. cl = self._test_gerrit_ensure_authenticated_common(auth={
  2284. 'chromium.googlesource.com': ('git-is.ok', 'but gerrit is missing'),
  2285. })
  2286. with self.assertRaises(SystemExitMock):
  2287. cl.EnsureAuthenticated(force=False)
  2288. self.assertEqual(
  2289. 'Credentials for the following hosts are required:\n'
  2290. ' chromium-review.googlesource.com\n'
  2291. 'These are read from ~%(sep)s.gitcookies\n'
  2292. 'You can (re)generate your credentials by visiting '
  2293. 'https://chromium.googlesource.com/new-password\n' % {
  2294. 'sep': os.sep,
  2295. }, sys.stderr.getvalue())
  2296. def test_gerrit_ensure_authenticated_conflict(self):
  2297. cl = self._test_gerrit_ensure_authenticated_common(
  2298. auth={
  2299. 'chromium.googlesource.com': ('git-one.example.com', 'secret1'),
  2300. 'chromium-review.googlesource.com': ('git-other.example.com',
  2301. 'secret2'),
  2302. })
  2303. self.calls.append((('ask_for_data', 'If you know what you are doing '
  2304. 'press Enter to continue, or Ctrl+C to abort'), ''))
  2305. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2306. def test_gerrit_ensure_authenticated_ok(self):
  2307. cl = self._test_gerrit_ensure_authenticated_common(
  2308. auth={
  2309. 'chromium.googlesource.com': ('git-same.example.com', 'secret'),
  2310. 'chromium-review.googlesource.com': ('git-same.example.com',
  2311. 'secret'),
  2312. })
  2313. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2314. def test_gerrit_ensure_authenticated_skipped(self):
  2315. scm.GIT.SetConfig('', 'gerrit.skip-ensure-authenticated', 'true')
  2316. cl = self._test_gerrit_ensure_authenticated_common(auth={})
  2317. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2318. def test_gerrit_ensure_authenticated_sso(self):
  2319. scm.GIT.SetConfig('', 'remote.origin.url', 'sso://repo')
  2320. mock.patch(
  2321. 'git_cl.gerrit_util.CookiesAuthenticator',
  2322. CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
  2323. cl = git_cl.Changelist()
  2324. cl.branch = 'main'
  2325. cl.branchref = 'refs/heads/main'
  2326. cl.lookedup_issue = True
  2327. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2328. def test_gerrit_ensure_authenticated_bearer_token(self):
  2329. cl = self._test_gerrit_ensure_authenticated_common(
  2330. auth={
  2331. 'chromium.googlesource.com': ('', 'secret'),
  2332. 'chromium-review.googlesource.com': ('', 'secret'),
  2333. })
  2334. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2335. conn = gerrit_util.HttpConn(
  2336. req_uri='???',
  2337. req_method='GET',
  2338. req_host='chromium.googlesource.com',
  2339. req_headers={},
  2340. req_body=None,
  2341. )
  2342. gerrit_util.CookiesAuthenticator().authenticate(conn)
  2343. self.assertTrue('Bearer' in conn.req_headers['Authorization'])
  2344. def test_gerrit_ensure_authenticated_non_https_sso(self):
  2345. scm.GIT.SetConfig('', 'remote.origin.url', 'custom-scheme://repo')
  2346. self.calls = [
  2347. (('logging.warning',
  2348. 'Ignoring branch %(branch)s with non-https remote '
  2349. '%(remote)s', {
  2350. 'branch': 'main',
  2351. 'remote': 'custom-scheme://repo'
  2352. }), None),
  2353. ]
  2354. mock.patch(
  2355. 'git_cl.gerrit_util.CookiesAuthenticator',
  2356. CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
  2357. mock.patch('logging.warning',
  2358. lambda *a: self._mocked_call('logging.warning', *a)).start()
  2359. cl = git_cl.Changelist()
  2360. cl.branch = 'main'
  2361. cl.branchref = 'refs/heads/main'
  2362. cl.lookedup_issue = True
  2363. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2364. def test_gerrit_ensure_authenticated_non_url(self):
  2365. scm.GIT.SetConfig('', 'remote.origin.url',
  2366. 'git@somehost.example:foo/bar.git')
  2367. self.calls = [
  2368. (('logging.error',
  2369. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  2370. 'but it doesn\'t exist.', {
  2371. 'remote': 'origin',
  2372. 'branch': 'main',
  2373. 'url': 'git@somehost.example:foo/bar.git'
  2374. }), None),
  2375. ]
  2376. mock.patch(
  2377. 'git_cl.gerrit_util.CookiesAuthenticator',
  2378. CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
  2379. mock.patch('logging.error',
  2380. lambda *a: self._mocked_call('logging.error', *a)).start()
  2381. cl = git_cl.Changelist()
  2382. cl.branch = 'main'
  2383. cl.branchref = 'refs/heads/main'
  2384. cl.lookedup_issue = True
  2385. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  2386. def _cmd_set_commit_gerrit_common(self, vote, notify=None):
  2387. scm.GIT.SetConfig('', 'branch.main.gerritissue', '123')
  2388. scm.GIT.SetConfig('', 'branch.main.gerritserver',
  2389. 'https://chromium-review.googlesource.com')
  2390. scm.GIT.SetConfig('', 'remote.origin.url',
  2391. 'https://chromium.googlesource.com/infra/infra')
  2392. self.calls = [
  2393. (('SetReview', 'chromium-review.googlesource.com',
  2394. 'infra%2Finfra~123', None, {
  2395. 'Commit-Queue': vote
  2396. }, notify, None), ''),
  2397. ]
  2398. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2399. 'not supported in non-git environment')
  2400. def test_cmd_set_commit_gerrit_clear(self):
  2401. self._cmd_set_commit_gerrit_common(0)
  2402. self.assertEqual(0, git_cl.main(['set-commit', '-c']))
  2403. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2404. 'not supported in non-git environment')
  2405. def test_cmd_set_commit_gerrit_dry(self):
  2406. self._cmd_set_commit_gerrit_common(1, notify=False)
  2407. self.assertEqual(0, git_cl.main(['set-commit', '-d']))
  2408. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2409. 'not supported in non-git environment')
  2410. def test_cmd_set_commit_gerrit(self):
  2411. self._cmd_set_commit_gerrit_common(2)
  2412. self.assertEqual(0, git_cl.main(['set-commit']))
  2413. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2414. 'not supported in non-git environment')
  2415. def test_description_display(self):
  2416. mock.patch('git_cl.Changelist', ChangelistMock).start()
  2417. ChangelistMock.desc = 'foo\n'
  2418. self.assertEqual(0, git_cl.main(['description', '-d']))
  2419. self.assertEqual('foo\n', sys.stdout.getvalue())
  2420. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2421. 'not supported in non-git environment')
  2422. @mock.patch('sys.stderr', io.StringIO())
  2423. def test_StatusFieldOverrideIssueMissingArgs(self):
  2424. try:
  2425. self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
  2426. except SystemExitMock:
  2427. self.assertIn('--field must be given when --issue is set.',
  2428. sys.stderr.getvalue())
  2429. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2430. 'not supported in non-git environment')
  2431. def test_StatusFieldOverrideIssue(self):
  2432. def assertIssue(cl_self, *_args):
  2433. self.assertEqual(cl_self.issue, 1)
  2434. return 'foobar'
  2435. mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
  2436. self.assertEqual(
  2437. git_cl.main(['status', '--issue', '1', '--field', 'desc']), 0)
  2438. self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
  2439. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2440. 'not supported in non-git environment')
  2441. def test_SetCloseOverrideIssue(self):
  2442. def assertIssue(cl_self, *_args):
  2443. self.assertEqual(cl_self.issue, 1)
  2444. return 'foobar'
  2445. mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
  2446. mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
  2447. self.assertEqual(git_cl.main(['set-close', '--issue', '1']), 0)
  2448. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2449. 'not supported in non-git environment')
  2450. def test_description(self):
  2451. scm.GIT.SetConfig('', 'remote.origin.url',
  2452. 'https://chromium.googlesource.com/my/repo')
  2453. gerrit_util.GetChangeDetail.return_value = {
  2454. 'current_revision': 'sha1',
  2455. 'revisions': {
  2456. 'sha1': {
  2457. 'commit': {
  2458. 'message': 'foobar'
  2459. },
  2460. }
  2461. },
  2462. }
  2463. self.assertEqual(
  2464. 0,
  2465. git_cl.main([
  2466. 'description',
  2467. 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
  2468. '-d'
  2469. ]))
  2470. self.assertEqual('foobar\n', sys.stdout.getvalue())
  2471. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2472. 'not supported in non-git environment')
  2473. def test_description_set_raw(self):
  2474. mock.patch('git_cl.Changelist', ChangelistMock).start()
  2475. mock.patch('git_cl.sys.stdin', io.StringIO('hihi')).start()
  2476. self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
  2477. self.assertEqual('hihi', ChangelistMock.desc)
  2478. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2479. 'not supported in non-git environment')
  2480. def test_description_appends_bug_line(self):
  2481. current_desc = 'Some.\n\nChange-Id: xxx'
  2482. def RunEditor(desc, _, **kwargs):
  2483. self.assertEqual(
  2484. '# Enter a description of the change.\n'
  2485. '# This will be displayed on the codereview site.\n'
  2486. '# The first line will also be used as the subject of the review.\n'
  2487. '#--------------------This line is 72 characters long'
  2488. '--------------------\n'
  2489. 'Some.\n\nChange-Id: xxx\nBug: ', desc)
  2490. # Simulate user changing something.
  2491. return 'Some.\n\nChange-Id: xxx\nBug: 123'
  2492. def UpdateDescription(_, desc, force=False):
  2493. self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
  2494. mock.patch('git_cl.Changelist.FetchDescription',
  2495. lambda *args: current_desc).start()
  2496. mock.patch('git_cl.Changelist.UpdateDescription',
  2497. UpdateDescription).start()
  2498. mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
  2499. scm.GIT.SetConfig('', 'branch.main.gerritissue', '123')
  2500. self.assertEqual(0, git_cl.main(['description']))
  2501. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2502. 'not supported in non-git environment')
  2503. def test_description_does_not_append_bug_line_if_fixed_is_present(self):
  2504. current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
  2505. def RunEditor(desc, _, **kwargs):
  2506. self.assertEqual(
  2507. '# Enter a description of the change.\n'
  2508. '# This will be displayed on the codereview site.\n'
  2509. '# The first line will also be used as the subject of the review.\n'
  2510. '#--------------------This line is 72 characters long'
  2511. '--------------------\n'
  2512. 'Some.\n\nFixed: 123\nChange-Id: xxx', desc)
  2513. return desc
  2514. mock.patch('git_cl.Changelist.FetchDescription',
  2515. lambda *args: current_desc).start()
  2516. mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
  2517. scm.GIT.SetConfig('', 'branch.main.gerritissue', '123')
  2518. self.assertEqual(0, git_cl.main(['description']))
  2519. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2520. 'not supported in non-git environment')
  2521. def test_description_set_stdin(self):
  2522. mock.patch('git_cl.Changelist', ChangelistMock).start()
  2523. mock.patch('git_cl.sys.stdin',
  2524. io.StringIO('hi \r\n\t there\n\nman')).start()
  2525. self.assertEqual(0, git_cl.main(['description', '-n', '-']))
  2526. self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
  2527. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2528. 'not supported in non-git environment')
  2529. def test_archive(self):
  2530. self.calls = [
  2531. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  2532. 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
  2533. ((['git', 'for-each-ref', '--format=%(refname)',
  2534. 'refs/tags'], ), ''),
  2535. ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'], ), ''),
  2536. ((['git', 'branch', '-D', 'foo'], ), '')
  2537. ]
  2538. mock.patch(
  2539. 'git_cl.get_cl_statuses',
  2540. lambda branches, fine_grained, max_processes: [
  2541. (MockChangelistWithBranchAndIssue('main', 1), 'open'),
  2542. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2543. (MockChangelistWithBranchAndIssue('bar', 789), 'open')
  2544. ]).start()
  2545. self.assertEqual(0, git_cl.main(['archive', '-f']))
  2546. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2547. 'not supported in non-git environment')
  2548. def test_archive_tag_collision(self):
  2549. self.calls = [
  2550. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  2551. 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
  2552. ((['git', 'for-each-ref', '--format=%(refname)',
  2553. 'refs/tags'], ), 'refs/tags/git-cl-archived-456-foo'),
  2554. ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'], ), ''),
  2555. ((['git', 'branch', '-D', 'foo'], ), '')
  2556. ]
  2557. mock.patch(
  2558. 'git_cl.get_cl_statuses',
  2559. lambda branches, fine_grained, max_processes: [
  2560. (MockChangelistWithBranchAndIssue('main', 1), 'open'),
  2561. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2562. (MockChangelistWithBranchAndIssue('bar', 789), 'open')
  2563. ]).start()
  2564. self.assertEqual(0, git_cl.main(['archive', '-f']))
  2565. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2566. 'not supported in non-git environment')
  2567. def test_archive_current_branch_fails(self):
  2568. self.calls = [
  2569. ((['git', 'for-each-ref', '--format=%(refname)',
  2570. 'refs/heads'], ), 'refs/heads/main'),
  2571. ((['git', 'for-each-ref', '--format=%(refname)',
  2572. 'refs/tags'], ), ''),
  2573. ]
  2574. mock.patch(
  2575. 'git_cl.get_cl_statuses',
  2576. lambda branches, fine_grained, max_processes: [
  2577. (MockChangelistWithBranchAndIssue('main', 1), 'closed')
  2578. ]).start()
  2579. self.assertEqual(1, git_cl.main(['archive', '-f']))
  2580. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2581. 'not supported in non-git environment')
  2582. def test_archive_dry_run(self):
  2583. self.calls = [
  2584. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  2585. 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
  2586. ((['git', 'for-each-ref', '--format=%(refname)',
  2587. 'refs/tags'], ), ''),
  2588. ]
  2589. mock.patch(
  2590. 'git_cl.get_cl_statuses',
  2591. lambda branches, fine_grained, max_processes: [
  2592. (MockChangelistWithBranchAndIssue('main', 1), 'open'),
  2593. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2594. (MockChangelistWithBranchAndIssue('bar', 789), 'open')
  2595. ]).start()
  2596. self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
  2597. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2598. 'not supported in non-git environment')
  2599. def test_archive_no_tags(self):
  2600. self.calls = [
  2601. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  2602. 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
  2603. ((['git', 'for-each-ref', '--format=%(refname)',
  2604. 'refs/tags'], ), ''), ((['git', 'branch', '-D', 'foo'], ), '')
  2605. ]
  2606. mock.patch(
  2607. 'git_cl.get_cl_statuses',
  2608. lambda branches, fine_grained, max_processes: [
  2609. (MockChangelistWithBranchAndIssue('main', 1), 'open'),
  2610. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2611. (MockChangelistWithBranchAndIssue('bar', 789), 'open')
  2612. ]).start()
  2613. self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
  2614. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2615. 'not supported in non-git environment')
  2616. def test_archive_tag_cleanup_on_branch_deletion_error(self):
  2617. self.calls = [
  2618. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  2619. 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
  2620. ((['git', 'for-each-ref', '--format=%(refname)',
  2621. 'refs/tags'], ), ''),
  2622. ((['git', 'tag', 'git-cl-archived-456-foo',
  2623. 'foo'], ), 'refs/tags/git-cl-archived-456-foo'),
  2624. ((['git', 'branch', '-D', 'foo'], ), CERR1),
  2625. ((['git', 'tag', '-d', 'git-cl-archived-456-foo'], ),
  2626. 'refs/tags/git-cl-archived-456-foo'),
  2627. ]
  2628. mock.patch(
  2629. 'git_cl.get_cl_statuses',
  2630. lambda branches, fine_grained, max_processes: [
  2631. (MockChangelistWithBranchAndIssue('main', 1), 'open'),
  2632. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  2633. (MockChangelistWithBranchAndIssue('bar', 789), 'open')
  2634. ]).start()
  2635. self.assertEqual(0, git_cl.main(['archive', '-f']))
  2636. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2637. 'not supported in non-git environment')
  2638. def test_archive_with_format(self):
  2639. self.calls = [
  2640. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  2641. 'refs/heads/main\nrefs/heads/foo\nrefs/heads/bar'),
  2642. ((['git', 'for-each-ref', '--format=%(refname)',
  2643. 'refs/tags'], ), ''),
  2644. ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
  2645. ((['git', 'branch', '-D', 'foo'], ), ''),
  2646. ]
  2647. mock.patch(
  2648. 'git_cl.get_cl_statuses',
  2649. lambda branches, fine_grained, max_processes: [
  2650. (MockChangelistWithBranchAndIssue('foo', 12), 'closed')
  2651. ]).start()
  2652. self.assertEqual(
  2653. 0, git_cl.main(['archive', '-f', '-p',
  2654. 'archived/{issue}-{branch}']))
  2655. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2656. 'not supported in non-git environment')
  2657. def test_cmd_issue_erase_existing(self):
  2658. scm.GIT.SetConfig('', 'branch.main.gerritissue', '123')
  2659. scm.GIT.SetConfig('', 'branch.main.gerritserver',
  2660. 'https://chromium-review.googlesource.com')
  2661. self.calls = [
  2662. ((['git', 'log', '-1', '--format=%B'], ), 'This is a description'),
  2663. ]
  2664. self.assertEqual(0, git_cl.main(['issue', '0']))
  2665. self.assertIsNone(scm.GIT.GetConfig('root', 'branch.main.gerritissue'))
  2666. self.assertIsNone(scm.GIT.GetConfig('root', 'branch.main.gerritserver'))
  2667. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2668. 'not supported in non-git environment')
  2669. def test_cmd_issue_erase_existing_with_change_id(self):
  2670. scm.GIT.SetConfig('', 'branch.main.gerritissue', '123')
  2671. scm.GIT.SetConfig('', 'branch.main.gerritserver',
  2672. 'https://chromium-review.googlesource.com')
  2673. mock.patch(
  2674. 'git_cl.Changelist.FetchDescription',
  2675. lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
  2676. self.calls = [
  2677. ((['git', 'log', '-1', '--format=%B'], ),
  2678. 'This is a description\n\nChange-Id: Ideadbeef'),
  2679. ((['git', 'commit', '--amend', '-m',
  2680. 'This is a description\n'], ), ''),
  2681. ]
  2682. self.assertEqual(0, git_cl.main(['issue', '0']))
  2683. self.assertIsNone(scm.GIT.GetConfig('root', 'branch.main.gerritissue'))
  2684. self.assertIsNone(scm.GIT.GetConfig('root', 'branch.main.gerritserver'))
  2685. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2686. 'not supported in non-git environment')
  2687. def test_cmd_issue_json(self):
  2688. scm.GIT.SetConfig('', 'branch.main.gerritissue', '123')
  2689. scm.GIT.SetConfig('', 'branch.main.gerritserver',
  2690. 'https://chromium-review.googlesource.com')
  2691. scm.GIT.SetConfig('', 'remote.origin.url',
  2692. 'https://chromium.googlesource.com/chromium/src')
  2693. self.calls = [(
  2694. (
  2695. 'write_json',
  2696. 'output.json',
  2697. {
  2698. 'issue': 123,
  2699. 'issue_url': 'https://chromium-review.googlesource.com/123',
  2700. 'gerrit_host': 'chromium-review.googlesource.com',
  2701. 'gerrit_project': 'chromium/src',
  2702. },
  2703. ),
  2704. '',
  2705. )]
  2706. self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
  2707. def _common_GerritCommitMsgHookCheck(self):
  2708. mock.patch('git_cl.os.path.abspath',
  2709. lambda path: self._mocked_call(['abspath', path])).start()
  2710. mock.patch('git_cl.os.path.exists',
  2711. lambda path: self._mocked_call(['exists', path])).start()
  2712. mock.patch('git_cl.gclient_utils.FileRead',
  2713. lambda path: self._mocked_call(['FileRead', path])).start()
  2714. mock.patch(
  2715. 'git_cl.gclient_utils.rm_file_or_tree',
  2716. lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
  2717. mock.patch(
  2718. 'gclient_utils.AskForData',
  2719. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  2720. return git_cl.Changelist(issue=123)
  2721. def test_GerritCommitMsgHookCheck_custom_hook(self):
  2722. cl = self._common_GerritCommitMsgHookCheck()
  2723. self.calls += [
  2724. ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
  2725. ((['FileRead',
  2726. os.path.join('.git', 'hooks',
  2727. 'commit-msg')], ), '#!/bin/sh\necho "custom hook"')
  2728. ]
  2729. cl._GerritCommitMsgHookCheck(offer_removal=True)
  2730. def test_GerritCommitMsgHookCheck_not_exists(self):
  2731. cl = self._common_GerritCommitMsgHookCheck()
  2732. self.calls += [
  2733. ((['exists', os.path.join('.git', 'hooks',
  2734. 'commit-msg')], ), False),
  2735. ]
  2736. cl._GerritCommitMsgHookCheck(offer_removal=True)
  2737. def test_GerritCommitMsgHookCheck(self):
  2738. cl = self._common_GerritCommitMsgHookCheck()
  2739. self.calls += [
  2740. ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
  2741. ((['FileRead',
  2742. os.path.join('.git', 'hooks', 'commit-msg')], ),
  2743. '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
  2744. (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '),
  2745. 'Yes'),
  2746. ((['rm_file_or_tree',
  2747. os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
  2748. ]
  2749. cl._GerritCommitMsgHookCheck(offer_removal=True)
  2750. def test_GerritCmdLand(self):
  2751. scm.GIT.SetConfig('', 'branch.main.gerritsquashhash', 'deadbeaf')
  2752. scm.GIT.SetConfig('', 'branch.main.gerritserver',
  2753. 'chromium-review.googlesource.com')
  2754. self.calls += [
  2755. ((['git', 'diff', 'deadbeaf'], ), ''), # No diff.
  2756. ]
  2757. cl = git_cl.Changelist(issue=123)
  2758. cl._GetChangeDetail = lambda *args, **kwargs: {
  2759. 'labels': {},
  2760. 'current_revision': 'deadbeaf',
  2761. }
  2762. cl._GetChangeCommit = lambda: {
  2763. 'commit':
  2764. 'deadbeef',
  2765. 'web_links': [{
  2766. 'name': 'gitiles',
  2767. 'url': 'https://git.googlesource.com/test/+/deadbeef'
  2768. }],
  2769. }
  2770. cl.SubmitIssue = lambda: None
  2771. self.assertEqual(
  2772. 0,
  2773. cl.CMDLand(force=True,
  2774. bypass_hooks=True,
  2775. verbose=True,
  2776. parallel=False,
  2777. resultdb=False,
  2778. realm=None))
  2779. self.assertIn(
  2780. 'Issue chromium-review.googlesource.com/123 has been submitted',
  2781. sys.stdout.getvalue())
  2782. self.assertIn('Landed as: https://git.googlesource.com/test/+/deadbeef',
  2783. sys.stdout.getvalue())
  2784. def _mock_gerrit_changes_for_detail_cache(self):
  2785. mock.patch('git_cl.Changelist.GetGerritHost', lambda _: 'host').start()
  2786. def test_gerrit_change_detail_cache_simple(self):
  2787. self._mock_gerrit_changes_for_detail_cache()
  2788. gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
  2789. cl1 = git_cl.Changelist(issue=1)
  2790. cl1._cached_remote_url = (
  2791. True, 'https://chromium.googlesource.com/a/my/repo.git/')
  2792. cl2 = git_cl.Changelist(issue=2)
  2793. cl2._cached_remote_url = (True,
  2794. 'https://chromium.googlesource.com/ab/repo')
  2795. self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
  2796. self.assertEqual(cl1._GetChangeDetail(), 'a')
  2797. self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
  2798. def test_gerrit_change_detail_cache_options(self):
  2799. self._mock_gerrit_changes_for_detail_cache()
  2800. gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
  2801. cl = git_cl.Changelist(issue=1)
  2802. cl._cached_remote_url = (True,
  2803. 'https://chromium.googlesource.com/repo/')
  2804. self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
  2805. self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
  2806. self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
  2807. self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
  2808. self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
  2809. self.assertEqual(cl._GetChangeDetail(), 'cab')
  2810. self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
  2811. self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
  2812. self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
  2813. self.assertEqual(cl._GetChangeDetail(), 'cab')
  2814. def test_gerrit_description_caching(self):
  2815. gerrit_util.GetChangeDetail.return_value = {
  2816. 'current_revision': 'rev1',
  2817. 'revisions': {
  2818. 'rev1': {
  2819. 'commit': {
  2820. 'message': 'desc1'
  2821. }
  2822. },
  2823. },
  2824. }
  2825. self._mock_gerrit_changes_for_detail_cache()
  2826. cl = git_cl.Changelist(issue=1)
  2827. cl._cached_remote_url = (
  2828. True, 'https://chromium.googlesource.com/a/my/repo.git/')
  2829. self.assertEqual(cl.FetchDescription(), 'desc1')
  2830. self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
  2831. def test_print_current_creds(self):
  2832. class CookiesAuthenticatorMock(object):
  2833. def __init__(self):
  2834. self.gitcookies = {
  2835. 'host.googlesource.com': ('user', 'pass'),
  2836. 'host-review.googlesource.com': ('user', 'pass'),
  2837. }
  2838. mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
  2839. CookiesAuthenticatorMock).start()
  2840. git_cl._GitCookiesChecker().print_current_creds()
  2841. self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
  2842. 'Your .gitcookies have credentials for these hosts:',
  2843. ' Host\tUser\t Which file',
  2844. '============================\t====\t===========',
  2845. 'host-review.googlesource.com\tuser\t.gitcookies',
  2846. ' host.googlesource.com\tuser\t.gitcookies',
  2847. ])
  2848. sys.stdout.seek(0)
  2849. sys.stdout.truncate(0)
  2850. git_cl._GitCookiesChecker().print_current_creds()
  2851. self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
  2852. 'Your .gitcookies have credentials for these hosts:',
  2853. ' Host\tUser\t Which file',
  2854. '============================\t====\t===========',
  2855. 'host-review.googlesource.com\tuser\t.gitcookies',
  2856. ' host.googlesource.com\tuser\t.gitcookies',
  2857. ])
  2858. def _common_creds_check_mocks(self):
  2859. def exists_mock(path):
  2860. dirname = os.path.dirname(path)
  2861. if dirname == os.path.expanduser('~'):
  2862. dirname = '~'
  2863. base = os.path.basename(path)
  2864. if base == '.gitcookies':
  2865. return self._mocked_call('os.path.exists',
  2866. os.path.join(dirname, base))
  2867. # git cl also checks for existence other files not relevant to this
  2868. # test.
  2869. return None
  2870. mock.patch(
  2871. 'gclient_utils.AskForData',
  2872. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  2873. mock.patch('os.path.exists', exists_mock).start()
  2874. def test_creds_check_gitcookies_not_configured(self):
  2875. self._common_creds_check_mocks()
  2876. mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
  2877. lambda _: []).start()
  2878. self.calls = [
  2879. (('ask_for_data', 'Press Enter to setup .gitcookies, '
  2880. 'or Ctrl+C to abort'), ''),
  2881. ]
  2882. self.assertEqual(0, git_cl.main(['creds-check']))
  2883. self.assertIn('\nConfigured git to use .gitcookies from',
  2884. sys.stdout.getvalue())
  2885. def test_creds_check_gitcookies_configured_custom_broken(self):
  2886. self._common_creds_check_mocks()
  2887. custom_cookie_path = ('C:\\.gitcookies' if sys.platform == 'win32' else
  2888. '/custom/.gitcookies')
  2889. scm.GIT.SetConfig('', 'http.cookiefile', custom_cookie_path)
  2890. os.environ['GIT_COOKIES_PATH'] = '/official/.gitcookies'
  2891. mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
  2892. lambda _: []).start()
  2893. self.calls = [
  2894. (('os.path.exists', custom_cookie_path), False),
  2895. (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
  2896. 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
  2897. ]
  2898. self.assertEqual(0, git_cl.main(['creds-check']))
  2899. self.assertIn(
  2900. 'WARNING: You have configured custom path to .gitcookies: ',
  2901. sys.stdout.getvalue())
  2902. self.assertIn('However, your configured .gitcookies file is missing.',
  2903. sys.stdout.getvalue())
  2904. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2905. 'not supported in non-git environment')
  2906. def test_git_cl_comment_add_gerrit(self):
  2907. git_new_branch.create_new_branch(None) # hits mock from scm_mock.GIT.
  2908. scm.GIT.SetConfig('', 'remote.origin.url',
  2909. 'https://chromium.googlesource.com/infra/infra')
  2910. self.calls = [
  2911. (('SetReview', 'chromium-review.googlesource.com',
  2912. 'infra%2Finfra~10', 'msg', None, None, None), None),
  2913. ]
  2914. self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
  2915. @unittest.skipIf(gclient_utils.IsEnvCog(),
  2916. 'not supported in non-git environment')
  2917. @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
  2918. def test_git_cl_comments_fetch_gerrit(self, *_mocks):
  2919. scm.GIT.SetConfig('', 'remote.origin.url',
  2920. 'https://chromium.googlesource.com/infra/infra')
  2921. gerrit_util.GetChangeDetail.return_value = {
  2922. 'owner': {
  2923. 'email': 'owner@example.com'
  2924. },
  2925. 'current_revision':
  2926. 'ba5eba11',
  2927. 'revisions': {
  2928. 'deadbeaf': {
  2929. '_number': 1,
  2930. },
  2931. 'ba5eba11': {
  2932. '_number': 2,
  2933. },
  2934. },
  2935. 'messages': [
  2936. {
  2937. u'_revision_number': 1,
  2938. u'author': {
  2939. u'_account_id': 1111084,
  2940. u'email': u'could-be-anything@example.com',
  2941. u'name': u'LUCI CQ'
  2942. },
  2943. u'date': u'2017-03-15 20:08:45.000000000',
  2944. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
  2945. u'message':
  2946. u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
  2947. u'tag': u'autogenerated:cv:dry-run'
  2948. },
  2949. {
  2950. u'_revision_number': 2,
  2951. u'author': {
  2952. u'_account_id': 11151243,
  2953. u'email': u'owner@example.com',
  2954. u'name': u'owner'
  2955. },
  2956. u'date': u'2017-03-16 20:00:41.000000000',
  2957. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2958. u'message': u'PTAL',
  2959. },
  2960. {
  2961. u'_revision_number': 2,
  2962. u'author': {
  2963. u'_account_id': 148512,
  2964. u'email': u'reviewer@example.com',
  2965. u'name': u'reviewer'
  2966. },
  2967. u'date': u'2017-03-17 05:19:37.500000000',
  2968. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
  2969. u'message': u'Patch Set 2: Code-Review+1',
  2970. },
  2971. {
  2972. u'_revision_number': 2,
  2973. u'author': {
  2974. u'_account_id': 42,
  2975. u'name': u'reviewer'
  2976. },
  2977. u'date': u'2017-03-17 05:19:37.900000000',
  2978. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d0000',
  2979. u'message': u'A bot with no email set',
  2980. },
  2981. ]
  2982. }
  2983. self.calls = [
  2984. (('GetChangeComments', 'chromium-review.googlesource.com',
  2985. 'infra%2Finfra~1'), {
  2986. '/COMMIT_MSG': [
  2987. {
  2988. 'author': {
  2989. 'email': u'reviewer@example.com'
  2990. },
  2991. 'updated': u'2017-03-17 05:19:37.500000000',
  2992. 'patch_set': 2,
  2993. 'side': 'REVISION',
  2994. 'message': 'Please include a bug link',
  2995. },
  2996. ],
  2997. 'codereview.settings': [
  2998. {
  2999. 'author': {
  3000. 'email': u'owner@example.com'
  3001. },
  3002. 'updated': u'2017-03-16 20:00:41.000000000',
  3003. 'patch_set': 2,
  3004. 'side': 'PARENT',
  3005. 'line': 42,
  3006. 'message': 'I removed this because it is bad',
  3007. },
  3008. ]
  3009. }),
  3010. (('GetChangeRobotComments', 'chromium-review.googlesource.com',
  3011. 'infra%2Finfra~1'), {}),
  3012. ] * 2 + [(('write_json', 'output.json', [{
  3013. u'date':
  3014. u'2017-03-16 20:00:41.000000',
  3015. u'message': (u'PTAL\n' + u'\n' + u'codereview.settings\n' +
  3016. u' Base, Line 42: https://crrev.com/c/1/2/'
  3017. u'codereview.settings#b42\n' +
  3018. u' I removed this because it is bad\n'),
  3019. u'autogenerated':
  3020. False,
  3021. u'approval':
  3022. False,
  3023. u'disapproval':
  3024. False,
  3025. u'sender':
  3026. u'owner@example.com'
  3027. }, {
  3028. u'date':
  3029. u'2017-03-17 05:19:37.500000',
  3030. u'message':
  3031. (u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
  3032. u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
  3033. u' Please include a bug link\n'),
  3034. u'autogenerated':
  3035. False,
  3036. u'approval':
  3037. False,
  3038. u'disapproval':
  3039. False,
  3040. u'sender':
  3041. u'reviewer@example.com'
  3042. }]), '')]
  3043. expected_comments_summary = [
  3044. git_cl._CommentSummary(
  3045. message=(u'PTAL\n' + u'\n' + u'codereview.settings\n' +
  3046. u' Base, Line 42: https://crrev.com/c/1/2/' +
  3047. u'codereview.settings#b42\n' +
  3048. u' I removed this because it is bad\n'),
  3049. date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
  3050. autogenerated=False,
  3051. disapproval=False,
  3052. approval=False,
  3053. sender=u'owner@example.com'),
  3054. git_cl._CommentSummary(message=(
  3055. u'Patch Set 2: Code-Review+1\n' + u'\n' + u'/COMMIT_MSG\n' +
  3056. u' PS2, File comment: https://crrev.com/c/1/2//COMMIT_MSG#\n' +
  3057. u' Please include a bug link\n'),
  3058. date=datetime.datetime(
  3059. 2017, 3, 17, 5, 19, 37, 500000),
  3060. autogenerated=False,
  3061. disapproval=False,
  3062. approval=False,
  3063. sender=u'reviewer@example.com'),
  3064. ]
  3065. cl = git_cl.Changelist(issue=1, branchref='refs/heads/foo')
  3066. self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
  3067. self.assertEqual(
  3068. 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
  3069. @unittest.skipIf(gclient_utils.IsEnvCog(),
  3070. 'not supported in non-git environment')
  3071. def test_git_cl_comments_robot_comments(self):
  3072. # git cl comments also fetches robot comments (which are considered a
  3073. # type of autogenerated comment), and unlike other types of comments,
  3074. # only robot comments from the latest patchset are shown.
  3075. scm.GIT.SetConfig('', 'remote.origin.url',
  3076. 'https://x.googlesource.com/infra/infra')
  3077. gerrit_util.GetChangeDetail.return_value = {
  3078. 'owner': {
  3079. 'email': 'owner@example.com'
  3080. },
  3081. 'current_revision':
  3082. 'ba5eba11',
  3083. 'revisions': {
  3084. 'deadbeaf': {
  3085. '_number': 1,
  3086. },
  3087. 'ba5eba11': {
  3088. '_number': 2,
  3089. },
  3090. },
  3091. 'messages': [
  3092. {
  3093. u'_revision_number': 1,
  3094. u'author': {
  3095. u'_account_id': 1111084,
  3096. u'email': u'commit-bot@chromium.org',
  3097. u'name': u'Commit Bot'
  3098. },
  3099. u'date': u'2017-03-15 20:08:45.000000000',
  3100. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
  3101. u'message':
  3102. u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
  3103. u'tag': u'autogenerated:cq:dry-run'
  3104. },
  3105. {
  3106. u'_revision_number': 1,
  3107. u'author': {
  3108. u'_account_id': 123,
  3109. u'email': u'tricium@serviceaccount.com',
  3110. u'name': u'Tricium'
  3111. },
  3112. u'date': u'2017-03-16 20:00:41.000000000',
  3113. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  3114. u'message': u'(1 comment)',
  3115. u'tag': u'autogenerated:tricium',
  3116. },
  3117. {
  3118. u'_revision_number': 1,
  3119. u'author': {
  3120. u'_account_id': 123,
  3121. u'email': u'tricium@serviceaccount.com',
  3122. u'name': u'Tricium'
  3123. },
  3124. u'date': u'2017-03-16 20:00:41.000000000',
  3125. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  3126. u'message': u'(1 comment)',
  3127. u'tag': u'autogenerated:tricium',
  3128. },
  3129. {
  3130. u'_revision_number': 2,
  3131. u'author': {
  3132. u'_account_id': 123,
  3133. u'email': u'tricium@serviceaccount.com',
  3134. u'name': u'reviewer'
  3135. },
  3136. u'date': u'2017-03-17 05:30:37.000000000',
  3137. u'tag': u'autogenerated:tricium',
  3138. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
  3139. u'message': u'(1 comment)',
  3140. },
  3141. ]
  3142. }
  3143. self.calls = [
  3144. (('GetChangeComments', 'x-review.googlesource.com',
  3145. 'infra%2Finfra~1'), {}),
  3146. (('GetChangeRobotComments', 'x-review.googlesource.com',
  3147. 'infra%2Finfra~1'), {
  3148. 'codereview.settings': [
  3149. {
  3150. u'author': {
  3151. u'email': u'tricium@serviceaccount.com'
  3152. },
  3153. u'updated': u'2017-03-17 05:30:37.000000000',
  3154. u'robot_run_id': u'5565031076855808',
  3155. u'robot_id': u'Linter/Category',
  3156. u'tag': u'autogenerated:tricium',
  3157. u'patch_set': 2,
  3158. u'side': u'REVISION',
  3159. u'message': u'Linter warning message text',
  3160. u'line': 32,
  3161. },
  3162. ],
  3163. }),
  3164. ]
  3165. expected_comments_summary = [
  3166. git_cl._CommentSummary(
  3167. date=datetime.datetime(2017, 3, 17, 5, 30, 37),
  3168. message=(
  3169. u'(1 comment)\n\ncodereview.settings\n'
  3170. u' PS2, Line 32: https://x-review.googlesource.com/c/1/2/'
  3171. u'codereview.settings#32\n'
  3172. u' Linter warning message text\n'),
  3173. sender=u'tricium@serviceaccount.com',
  3174. autogenerated=True,
  3175. approval=False,
  3176. disapproval=False)
  3177. ]
  3178. cl = git_cl.Changelist(issue=1, branchref='refs/heads/foo')
  3179. self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
  3180. def test_get_remote_url_with_mirror(self):
  3181. original_os_path_isdir = os.path.isdir
  3182. def selective_os_path_isdir_mock(path):
  3183. if path == '/cache/this-dir-exists':
  3184. return self._mocked_call('os.path.isdir', path)
  3185. return original_os_path_isdir(path)
  3186. mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
  3187. url = 'https://chromium.googlesource.com/my/repo'
  3188. scm.GIT.SetConfig('', 'remote.origin.url', '/cache/this-dir-exists')
  3189. scm.GIT.SetConfig('/cache/this-dir-exists', 'remote.origin.url', url)
  3190. self.calls = [
  3191. (('os.path.isdir', '/cache/this-dir-exists'), True),
  3192. ]
  3193. cl = git_cl.Changelist(issue=1)
  3194. self.assertEqual(cl.GetRemoteUrl(), url)
  3195. self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
  3196. def test_get_remote_url_non_existing_mirror(self):
  3197. original_os_path_isdir = os.path.isdir
  3198. def selective_os_path_isdir_mock(path):
  3199. if path == '/cache/this-dir-doesnt-exist':
  3200. return self._mocked_call('os.path.isdir', path)
  3201. return original_os_path_isdir(path)
  3202. mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
  3203. mock.patch('logging.error',
  3204. lambda *a: self._mocked_call('logging.error', *a)).start()
  3205. scm.GIT.SetConfig('', 'remote.origin.url',
  3206. '/cache/this-dir-doesnt-exist')
  3207. self.calls = [
  3208. (('os.path.isdir', '/cache/this-dir-doesnt-exist'), False),
  3209. (('logging.error',
  3210. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  3211. 'but it doesn\'t exist.', {
  3212. 'remote': 'origin',
  3213. 'branch': 'main',
  3214. 'url': '/cache/this-dir-doesnt-exist'
  3215. }), None),
  3216. ]
  3217. cl = git_cl.Changelist(issue=1)
  3218. self.assertIsNone(cl.GetRemoteUrl())
  3219. def test_get_remote_url_misconfigured_mirror(self):
  3220. original_os_path_isdir = os.path.isdir
  3221. def selective_os_path_isdir_mock(path):
  3222. if path == '/cache/this-dir-exists':
  3223. return self._mocked_call('os.path.isdir', path)
  3224. return original_os_path_isdir(path)
  3225. mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
  3226. mock.patch('logging.error',
  3227. lambda *a: self._mocked_call('logging.error', *a)).start()
  3228. scm.GIT.SetConfig('', 'remote.origin.url', '/cache/this-dir-exists')
  3229. self.calls = [
  3230. (('os.path.isdir', '/cache/this-dir-exists'), True),
  3231. (('logging.error',
  3232. 'Remote "%(remote)s" for branch "%(branch)s" points to '
  3233. '"%(cache_path)s", but it is misconfigured.\n'
  3234. '"%(cache_path)s" must be a git repo and must have a remote named '
  3235. '"%(remote)s" pointing to the git host.', {
  3236. 'remote': 'origin',
  3237. 'cache_path': '/cache/this-dir-exists',
  3238. 'branch': 'main'
  3239. }), None),
  3240. ]
  3241. cl = git_cl.Changelist(issue=1)
  3242. self.assertIsNone(cl.GetRemoteUrl())
  3243. def test_gerrit_change_identifier_with_project(self):
  3244. scm.GIT.SetConfig('', 'remote.origin.url',
  3245. 'https://chromium.googlesource.com/a/my/repo.git/')
  3246. cl = git_cl.Changelist(issue=123456)
  3247. self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
  3248. def test_gerrit_change_identifier_without_project(self):
  3249. mock.patch('logging.error',
  3250. lambda *a: self._mocked_call('logging.error', *a)).start()
  3251. self.calls = [
  3252. (('logging.error',
  3253. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  3254. 'but it doesn\'t exist.', {
  3255. 'remote': 'origin',
  3256. 'branch': 'main',
  3257. 'url': ''
  3258. }), None),
  3259. ]
  3260. cl = git_cl.Changelist(issue=123456)
  3261. self.assertEqual(cl._GerritChangeIdentifier(), '123456')
  3262. @unittest.skipIf(gclient_utils.IsEnvCog(),
  3263. 'not supported in non-git environment')
  3264. def test_gerrit_new_default(self):
  3265. self._run_gerrit_upload_test(
  3266. [],
  3267. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n', [],
  3268. squash=False,
  3269. squash_mode='override_nosquash',
  3270. change_id='I123456789',
  3271. default_branch='main')
  3272. @unittest.skipIf(gclient_utils.IsEnvCog(),
  3273. 'not supported in non-git environment')
  3274. def test_gerrit_nosquash_with_issue(self):
  3275. self._run_gerrit_upload_test(
  3276. [],
  3277. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n', [],
  3278. squash=False,
  3279. squash_mode='override_nosquash',
  3280. issue=123456,
  3281. change_id='I123456789',
  3282. default_branch='main')
  3283. class ChangelistTest(unittest.TestCase):
  3284. LAST_COMMIT_SUBJECT = 'Fixes goat teleporter destination to be Australia'
  3285. def _mock_run_git(commands):
  3286. if commands == ['show', '-s', '--format=%s', 'HEAD', '--']:
  3287. return ChangelistTest.LAST_COMMIT_SUBJECT
  3288. def setUp(self):
  3289. super(ChangelistTest, self).setUp()
  3290. mock.patch('gclient_utils.FileRead').start()
  3291. mock.patch('gclient_utils.FileWrite').start()
  3292. mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
  3293. mock.patch(
  3294. 'git_cl.Changelist.GetCodereviewServer',
  3295. return_value='https://chromium-review.googlesource.com').start()
  3296. mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
  3297. mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
  3298. mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
  3299. mock.patch('git_cl.Changelist.GetRemoteBranch',
  3300. return_value=('origin', 'refs/remotes/origin/main')).start()
  3301. mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
  3302. mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
  3303. mock.patch('git_cl.Settings.GetIsGerrit', return_value=True).start()
  3304. mock.patch('git_cl.time_time').start()
  3305. mock.patch('metrics.collector').start()
  3306. mock.patch('subprocess2.Popen').start()
  3307. mock.patch('git_cl.Changelist.GetGerritProject',
  3308. return_value='project').start()
  3309. mock.patch('sys.exit', side_effect=SystemExitMock).start()
  3310. scm_mock.GIT(self)
  3311. self.addCleanup(mock.patch.stopall)
  3312. self.temp_count = 0
  3313. gerrit_util._Authenticator._resolved = None
  3314. def testRunHook(self):
  3315. expected_results = {
  3316. 'more_cc': ['cc@example.com', 'more@example.com'],
  3317. 'errors': [],
  3318. 'notifications': [],
  3319. 'warnings': [],
  3320. }
  3321. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  3322. git_cl.time_time.side_effect = [100, 200, 300, 400]
  3323. mockProcess = mock.Mock()
  3324. mockProcess.wait.return_value = 0
  3325. subprocess2.Popen.return_value = mockProcess
  3326. cl = git_cl.Changelist()
  3327. results = cl.RunHook(committing=True,
  3328. may_prompt=True,
  3329. verbose=2,
  3330. parallel=True,
  3331. upstream='upstream',
  3332. description='description',
  3333. all_files=True,
  3334. resultdb=False)
  3335. self.assertEqual(expected_results, results)
  3336. subprocess2.Popen.assert_any_call([
  3337. 'vpython3',
  3338. 'PRESUBMIT_SUPPORT',
  3339. '--root',
  3340. 'root',
  3341. '--upstream',
  3342. 'upstream',
  3343. '--verbose',
  3344. '--verbose',
  3345. '--gerrit_url',
  3346. 'https://chromium-review.googlesource.com',
  3347. '--gerrit_project',
  3348. 'project',
  3349. '--gerrit_branch',
  3350. 'refs/heads/main',
  3351. '--author',
  3352. 'author',
  3353. '--issue',
  3354. '123456',
  3355. '--patchset',
  3356. '7',
  3357. '--commit',
  3358. '--may_prompt',
  3359. '--parallel',
  3360. '--all_files',
  3361. '--no_diffs',
  3362. '--json_output',
  3363. '/tmp/fake-temp2',
  3364. '--description_file',
  3365. '/tmp/fake-temp1',
  3366. ])
  3367. gclient_utils.FileWrite.assert_any_call('/tmp/fake-temp1',
  3368. 'description')
  3369. metrics.collector.add_repeated('sub_commands', {
  3370. 'command': 'presubmit',
  3371. 'execution_time': 100,
  3372. 'exit_code': 0,
  3373. })
  3374. def testRunHook_FewerOptions(self):
  3375. expected_results = {
  3376. 'more_cc': ['cc@example.com', 'more@example.com'],
  3377. 'errors': [],
  3378. 'notifications': [],
  3379. 'warnings': [],
  3380. }
  3381. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  3382. git_cl.time_time.side_effect = [100, 200, 300, 400]
  3383. mockProcess = mock.Mock()
  3384. mockProcess.wait.return_value = 0
  3385. subprocess2.Popen.return_value = mockProcess
  3386. git_cl.Changelist.GetAuthor.return_value = None
  3387. git_cl.Changelist.GetIssue.return_value = None
  3388. git_cl.Changelist.GetPatchset.return_value = None
  3389. cl = git_cl.Changelist()
  3390. results = cl.RunHook(committing=False,
  3391. may_prompt=False,
  3392. verbose=0,
  3393. parallel=False,
  3394. upstream='upstream',
  3395. description='description',
  3396. all_files=False,
  3397. resultdb=False)
  3398. self.assertEqual(expected_results, results)
  3399. subprocess2.Popen.assert_any_call([
  3400. 'vpython3',
  3401. 'PRESUBMIT_SUPPORT',
  3402. '--root',
  3403. 'root',
  3404. '--upstream',
  3405. 'upstream',
  3406. '--gerrit_url',
  3407. 'https://chromium-review.googlesource.com',
  3408. '--gerrit_project',
  3409. 'project',
  3410. '--gerrit_branch',
  3411. 'refs/heads/main',
  3412. '--upload',
  3413. '--json_output',
  3414. '/tmp/fake-temp2',
  3415. '--description_file',
  3416. '/tmp/fake-temp1',
  3417. ])
  3418. gclient_utils.FileWrite.assert_any_call('/tmp/fake-temp1',
  3419. 'description')
  3420. metrics.collector.add_repeated('sub_commands', {
  3421. 'command': 'presubmit',
  3422. 'execution_time': 100,
  3423. 'exit_code': 0,
  3424. })
  3425. def testRunHook_FewerOptionsResultDB(self):
  3426. expected_results = {
  3427. 'more_cc': ['cc@example.com', 'more@example.com'],
  3428. 'errors': [],
  3429. 'notifications': [],
  3430. 'warnings': [],
  3431. }
  3432. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  3433. git_cl.time_time.side_effect = [100, 200, 300, 400]
  3434. mockProcess = mock.Mock()
  3435. mockProcess.wait.return_value = 0
  3436. subprocess2.Popen.return_value = mockProcess
  3437. git_cl.Changelist.GetAuthor.return_value = None
  3438. git_cl.Changelist.GetIssue.return_value = None
  3439. git_cl.Changelist.GetPatchset.return_value = None
  3440. cl = git_cl.Changelist()
  3441. results = cl.RunHook(committing=False,
  3442. may_prompt=False,
  3443. verbose=0,
  3444. parallel=False,
  3445. upstream='upstream',
  3446. description='description',
  3447. all_files=False,
  3448. resultdb=True,
  3449. realm='chromium:public')
  3450. self.assertEqual(expected_results, results)
  3451. subprocess2.Popen.assert_any_call([
  3452. 'rdb',
  3453. 'stream',
  3454. '-new',
  3455. '-realm',
  3456. 'chromium:public',
  3457. '--',
  3458. 'vpython3',
  3459. 'PRESUBMIT_SUPPORT',
  3460. '--root',
  3461. 'root',
  3462. '--upstream',
  3463. 'upstream',
  3464. '--gerrit_url',
  3465. 'https://chromium-review.googlesource.com',
  3466. '--gerrit_project',
  3467. 'project',
  3468. '--gerrit_branch',
  3469. 'refs/heads/main',
  3470. '--upload',
  3471. '--json_output',
  3472. '/tmp/fake-temp2',
  3473. '--description_file',
  3474. '/tmp/fake-temp1',
  3475. ])
  3476. def testRunHook_NoGerrit(self):
  3477. mock.patch('git_cl.Settings.GetIsGerrit', return_value=False).start()
  3478. expected_results = {
  3479. 'more_cc': ['cc@example.com', 'more@example.com'],
  3480. 'errors': [],
  3481. 'notifications': [],
  3482. 'warnings': [],
  3483. }
  3484. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  3485. git_cl.time_time.side_effect = [100, 200, 300, 400]
  3486. mockProcess = mock.Mock()
  3487. mockProcess.wait.return_value = 0
  3488. subprocess2.Popen.return_value = mockProcess
  3489. git_cl.Changelist.GetAuthor.return_value = None
  3490. git_cl.Changelist.GetIssue.return_value = None
  3491. git_cl.Changelist.GetPatchset.return_value = None
  3492. cl = git_cl.Changelist()
  3493. results = cl.RunHook(committing=False,
  3494. may_prompt=False,
  3495. verbose=0,
  3496. parallel=False,
  3497. upstream='upstream',
  3498. description='description',
  3499. all_files=False,
  3500. resultdb=False)
  3501. self.assertEqual(expected_results, results)
  3502. subprocess2.Popen.assert_any_call([
  3503. 'vpython3',
  3504. 'PRESUBMIT_SUPPORT',
  3505. '--root',
  3506. 'root',
  3507. '--upstream',
  3508. 'upstream',
  3509. '--upload',
  3510. '--json_output',
  3511. '/tmp/fake-temp2',
  3512. '--description_file',
  3513. '/tmp/fake-temp1',
  3514. ])
  3515. gclient_utils.FileWrite.assert_any_call('/tmp/fake-temp1',
  3516. 'description')
  3517. metrics.collector.add_repeated('sub_commands', {
  3518. 'command': 'presubmit',
  3519. 'execution_time': 100,
  3520. 'exit_code': 0,
  3521. })
  3522. @mock.patch('sys.exit', side_effect=SystemExitMock)
  3523. def testRunHook_Failure(self, _mock):
  3524. git_cl.time_time.side_effect = [100, 200]
  3525. mockProcess = mock.Mock()
  3526. mockProcess.wait.return_value = 2
  3527. subprocess2.Popen.return_value = mockProcess
  3528. cl = git_cl.Changelist()
  3529. with self.assertRaises(SystemExitMock):
  3530. cl.RunHook(committing=True,
  3531. may_prompt=True,
  3532. verbose=2,
  3533. parallel=True,
  3534. upstream='upstream',
  3535. description='description',
  3536. all_files=True,
  3537. resultdb=False)
  3538. sys.exit.assert_called_once_with(2)
  3539. def testRunPostUploadHook(self):
  3540. cl = git_cl.Changelist()
  3541. cl.RunPostUploadHook(2, 'upstream', 'description')
  3542. subprocess2.Popen.assert_called_with([
  3543. 'vpython3',
  3544. 'PRESUBMIT_SUPPORT',
  3545. '--root',
  3546. 'root',
  3547. '--upstream',
  3548. 'upstream',
  3549. '--verbose',
  3550. '--verbose',
  3551. '--gerrit_url',
  3552. 'https://chromium-review.googlesource.com',
  3553. '--gerrit_project',
  3554. 'project',
  3555. '--gerrit_branch',
  3556. 'refs/heads/main',
  3557. '--author',
  3558. 'author',
  3559. '--issue',
  3560. '123456',
  3561. '--patchset',
  3562. '7',
  3563. '--post_upload',
  3564. '--description_file',
  3565. '/tmp/fake-temp1',
  3566. ])
  3567. gclient_utils.FileWrite.assert_called_once_with('/tmp/fake-temp1',
  3568. 'description')
  3569. def testRunPostUploadHookPy3Only(self):
  3570. cl = git_cl.Changelist()
  3571. cl.RunPostUploadHook(2, 'upstream', 'description')
  3572. subprocess2.Popen.assert_called_once_with([
  3573. 'vpython3',
  3574. 'PRESUBMIT_SUPPORT',
  3575. '--root',
  3576. 'root',
  3577. '--upstream',
  3578. 'upstream',
  3579. '--verbose',
  3580. '--verbose',
  3581. '--gerrit_url',
  3582. 'https://chromium-review.googlesource.com',
  3583. '--gerrit_project',
  3584. 'project',
  3585. '--gerrit_branch',
  3586. 'refs/heads/main',
  3587. '--author',
  3588. 'author',
  3589. '--issue',
  3590. '123456',
  3591. '--patchset',
  3592. '7',
  3593. '--post_upload',
  3594. '--description_file',
  3595. '/tmp/fake-temp1',
  3596. ])
  3597. gclient_utils.FileWrite.assert_called_once_with('/tmp/fake-temp1',
  3598. 'description')
  3599. @mock.patch('git_cl.RunGit', _mock_run_git)
  3600. def testDefaultTitleEmptyMessage(self):
  3601. cl = git_cl.Changelist()
  3602. cl.issue = 100
  3603. options = optparse.Values({
  3604. 'squash': True,
  3605. 'title': None,
  3606. 'message': None,
  3607. 'force': None,
  3608. 'skip_title': None
  3609. })
  3610. mock.patch('gclient_utils.AskForData', lambda _: user_title).start()
  3611. for user_title in ['', 'y', 'Y']:
  3612. self.assertEqual(cl._GetTitleForUpload(options),
  3613. self.LAST_COMMIT_SUBJECT)
  3614. for user_title in ['not empty', 'yes', 'YES']:
  3615. self.assertEqual(cl._GetTitleForUpload(options), user_title)
  3616. @mock.patch('git_cl.Changelist.GetMostRecentPatchset', return_value=2)
  3617. @mock.patch('git_cl.RunGit')
  3618. @mock.patch('git_cl.Changelist._PrepareChange')
  3619. def testPrepareSquashedCommit(self, mockPrepareChange, mockRunGit, *_mocks):
  3620. change_desc = git_cl.ChangeDescription('BOO!')
  3621. reviewers = []
  3622. ccs = []
  3623. mockPrepareChange.return_value = (reviewers, ccs, change_desc)
  3624. parent_hash = 'upstream-gerrit-hash'
  3625. parent_orig_hash = 'upstream-last-upload-hash'
  3626. parent_hash_root = 'root-commit'
  3627. hash_to_push = 'new-squash-hash'
  3628. hash_to_push_root = 'new-squash-hash-root'
  3629. branchref = 'refs/heads/current-branch'
  3630. end_hash = 'end-hash'
  3631. tree_hash = 'tree-hash'
  3632. def mock_run_git(commands):
  3633. if {'commit-tree', tree_hash, '-p', parent_hash,
  3634. '-F'}.issubset(set(commands)):
  3635. return hash_to_push
  3636. if {'commit-tree', tree_hash, '-p', parent_hash_root,
  3637. '-F'}.issubset(set(commands)):
  3638. return hash_to_push_root
  3639. if commands == ['rev-parse', branchref]:
  3640. return end_hash
  3641. if commands == ['rev-parse', end_hash + ':']:
  3642. return tree_hash
  3643. mockRunGit.side_effect = mock_run_git
  3644. cl = git_cl.Changelist(branchref=branchref)
  3645. options = optparse.Values()
  3646. new_upload = cl.PrepareSquashedCommit(options, parent_hash,
  3647. parent_orig_hash)
  3648. self.assertEqual(new_upload.reviewers, reviewers)
  3649. self.assertEqual(new_upload.ccs, ccs)
  3650. self.assertEqual(new_upload.commit_to_push, hash_to_push)
  3651. self.assertEqual(new_upload.new_last_uploaded_commit, end_hash)
  3652. self.assertEqual(new_upload.change_desc, change_desc)
  3653. mockPrepareChange.assert_called_with(options, parent_orig_hash,
  3654. end_hash)
  3655. @mock.patch('git_cl.Settings.GetRoot', return_value='')
  3656. @mock.patch('git_cl.Changelist.GetMostRecentPatchset', return_value=2)
  3657. @mock.patch('git_cl.RunGitWithCode')
  3658. @mock.patch('git_cl.RunGit')
  3659. @mock.patch('git_cl.Changelist._PrepareChange')
  3660. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream')
  3661. def testPrepareCherryPickSquashedCommit(self,
  3662. mockGetCommonAncestorWithUpstream,
  3663. mockPrepareChange, mockRunGit,
  3664. mockRunGitWithCode, *_mocks):
  3665. cherry_pick_base_hash = '1a2bcherrypickbase'
  3666. mockGetCommonAncestorWithUpstream.return_value = cherry_pick_base_hash
  3667. change_desc = git_cl.ChangeDescription('BOO!')
  3668. ccs = ['cc@review.cl']
  3669. reviewers = ['reviewer@review.cl']
  3670. mockPrepareChange.return_value = (reviewers, ccs, change_desc)
  3671. branchref = 'refs/heads/current-branch'
  3672. cl = git_cl.Changelist(branchref=branchref)
  3673. options = optparse.Values()
  3674. upstream_gerrit_hash = 'upstream-gerrit-hash'
  3675. latest_tree_hash = 'tree-hash'
  3676. hash_to_cp = 'squashed-hash'
  3677. hash_to_push = 'hash-to-push'
  3678. hash_to_save_as_last_upload = 'last-upload'
  3679. def mock_run_git(commands):
  3680. if commands == ['rev-parse', branchref]:
  3681. return hash_to_save_as_last_upload
  3682. if commands == ['rev-parse', branchref + ':']:
  3683. return latest_tree_hash
  3684. if {
  3685. 'commit-tree', latest_tree_hash, '-p',
  3686. cherry_pick_base_hash, '-F'
  3687. }.issubset(set(commands)):
  3688. return hash_to_cp
  3689. if commands == ['rev-parse', 'HEAD']:
  3690. return hash_to_push
  3691. mockRunGit.side_effect = mock_run_git
  3692. def mock_run_git_with_code(commands):
  3693. if commands == ['cherry-pick', hash_to_cp]:
  3694. return 0, ''
  3695. mockRunGitWithCode.side_effect = mock_run_git_with_code
  3696. new_upload = cl.PrepareCherryPickSquashedCommit(options,
  3697. upstream_gerrit_hash)
  3698. self.assertEqual(new_upload.reviewers, reviewers)
  3699. self.assertEqual(new_upload.ccs, ccs)
  3700. self.assertEqual(new_upload.commit_to_push, hash_to_push)
  3701. self.assertEqual(new_upload.new_last_uploaded_commit,
  3702. hash_to_save_as_last_upload)
  3703. self.assertEqual(new_upload.change_desc, change_desc)
  3704. # Test failed cherry-pick
  3705. def mock_run_git_with_code(commands):
  3706. if commands == ['cherry-pick', hash_to_cp]:
  3707. return 1, ''
  3708. mockRunGitWithCode.side_effect = mock_run_git_with_code
  3709. with self.assertRaises(SystemExitMock):
  3710. cl.PrepareCherryPickSquashedCommit(options, cherry_pick_base_hash)
  3711. @mock.patch('git_cl.Settings.GetDefaultCCList', return_value=[])
  3712. @mock.patch('git_cl.Changelist.GetAffectedFiles', return_value=[])
  3713. @mock.patch('git_cl.GenerateGerritChangeId', return_value='1a2b3c')
  3714. @mock.patch('git_cl.Changelist.GetIssue', return_value=None)
  3715. @mock.patch('git_cl.ChangeDescription.prompt')
  3716. @mock.patch('git_cl.Changelist.RunHook')
  3717. @mock.patch('git_cl.Changelist._GetDescriptionForUpload')
  3718. @mock.patch('git_cl.Changelist.EnsureCanUploadPatchset')
  3719. def testPrepareChange_new(self, mockEnsureCanUploadPatchset,
  3720. mockGetDescriptionForupload, mockRunHook,
  3721. mockPrompt, *_mocks):
  3722. options = optparse.Values()
  3723. options.force = False
  3724. options.bypass_hooks = False
  3725. options.verbose = False
  3726. options.parallel = False
  3727. options.preserve_tryjobs = False
  3728. options.private = False
  3729. options.no_autocc = False
  3730. options.message_file = None
  3731. options.commit_description = None
  3732. options.cc = ['chicken@bok.farm']
  3733. parent = '420parent'
  3734. latest_tree = '420latest_tree'
  3735. mockRunHook.return_value = {'more_cc': ['cow@moo.farm']}
  3736. desc = 'AH!\nCC=cow2@moo.farm\nR=horse@apple.farm'
  3737. mockGetDescriptionForupload.return_value = git_cl.ChangeDescription(
  3738. desc)
  3739. cl = git_cl.Changelist()
  3740. reviewers, ccs, change_desc = cl._PrepareChange(options, parent,
  3741. latest_tree)
  3742. self.assertEqual(reviewers, ['horse@apple.farm'])
  3743. self.assertEqual(ccs,
  3744. ['cow@moo.farm', 'chicken@bok.farm', 'cow2@moo.farm'])
  3745. self.assertEqual(change_desc._description_lines, [
  3746. 'AH!', 'CC=cow2@moo.farm', 'R=horse@apple.farm', '',
  3747. 'Change-Id: 1a2b3c'
  3748. ])
  3749. mockPrompt.assert_called_once()
  3750. mockEnsureCanUploadPatchset.assert_called_once()
  3751. mockRunHook.assert_called_once_with(committing=False,
  3752. may_prompt=True,
  3753. verbose=False,
  3754. parallel=False,
  3755. upstream='420parent',
  3756. description=desc,
  3757. all_files=False)
  3758. @mock.patch('git_cl.Changelist.GetAffectedFiles', return_value=[])
  3759. @mock.patch('git_cl.Changelist.GetIssue', return_value='123')
  3760. @mock.patch('git_cl.ChangeDescription.prompt')
  3761. @mock.patch('gerrit_util.GetChangeDetail')
  3762. @mock.patch('git_cl.Changelist.RunHook')
  3763. @mock.patch('git_cl.Changelist._GetDescriptionForUpload')
  3764. @mock.patch('git_cl.Changelist.EnsureCanUploadPatchset')
  3765. def testPrepareChange_existing(self, mockEnsureCanUploadPatchset,
  3766. mockGetDescriptionForupload, mockRunHook,
  3767. mockGetChangeDetail, mockPrompt, *_mocks):
  3768. cl = git_cl.Changelist()
  3769. options = optparse.Values()
  3770. options.force = False
  3771. options.bypass_hooks = False
  3772. options.verbose = False
  3773. options.parallel = False
  3774. options.edit_description = False
  3775. options.preserve_tryjobs = False
  3776. options.private = False
  3777. options.no_autocc = False
  3778. options.cc = ['chicken@bok.farm']
  3779. parent = '420parent'
  3780. latest_tree = '420latest_tree'
  3781. mockRunHook.return_value = {'more_cc': ['cow@moo.farm']}
  3782. desc = 'AH!\nCC=cow2@moo.farm\nR=horse@apple.farm'
  3783. mockGetDescriptionForupload.return_value = git_cl.ChangeDescription(
  3784. desc)
  3785. # Existing change
  3786. gerrit_util.GetChangeDetail.return_value = {
  3787. 'change_id': ('123456789'),
  3788. 'current_revision': 'sha1_of_current_revision',
  3789. }
  3790. reviewers, ccs, change_desc = cl._PrepareChange(options, parent,
  3791. latest_tree)
  3792. self.assertEqual(reviewers, ['horse@apple.farm'])
  3793. self.assertEqual(ccs, ['chicken@bok.farm', 'cow2@moo.farm'])
  3794. self.assertEqual(change_desc._description_lines, [
  3795. 'AH!', 'CC=cow2@moo.farm', 'R=horse@apple.farm', '',
  3796. 'Change-Id: 123456789'
  3797. ])
  3798. mockRunHook.assert_called_once_with(committing=False,
  3799. may_prompt=True,
  3800. verbose=False,
  3801. parallel=False,
  3802. upstream='420parent',
  3803. description=desc,
  3804. all_files=False)
  3805. mockEnsureCanUploadPatchset.assert_called_once()
  3806. # Test preserve_tryjob
  3807. options.preserve_tryjobs = True
  3808. # Test edit_description
  3809. options.edit_description = True
  3810. # Test private
  3811. options.private = True
  3812. options.no_autocc = True
  3813. reviewers, ccs, change_desc = cl._PrepareChange(options, parent,
  3814. latest_tree)
  3815. self.assertEqual(ccs, ['chicken@bok.farm', 'cow2@moo.farm'])
  3816. mockPrompt.assert_called_once()
  3817. self.assertEqual(change_desc._description_lines, [
  3818. 'AH!', 'CC=cow2@moo.farm', 'R=horse@apple.farm', '',
  3819. 'Change-Id: 123456789', 'Cq-Do-Not-Cancel-Tryjobs: true'
  3820. ])
  3821. @mock.patch('git_cl.Changelist.GetGerritHost', return_value='chromium')
  3822. @mock.patch('git_cl.Settings.GetRunPostUploadHook', return_value=True)
  3823. @mock.patch('git_cl.Changelist.SetPatchset')
  3824. @mock.patch('git_cl.Changelist.RunPostUploadHook')
  3825. @mock.patch('git_cl.gerrit_util.AddReviewers')
  3826. def testPostUploadUpdates(self, mockAddReviewers, mockRunPostHook,
  3827. mockSetPatchset, *_mocks):
  3828. cl = git_cl.Changelist(branchref='refs/heads/current-branch')
  3829. options = optparse.Values()
  3830. options.verbose = True
  3831. options.no_python2_post_upload_hooks = True
  3832. options.send_mail = False
  3833. reviewers = ['monkey@vp.circus']
  3834. ccs = ['cow@rds.corp']
  3835. change_desc = git_cl.ChangeDescription('[stonks] honk honk')
  3836. new_upload = git_cl._NewUpload(reviewers, ccs, 'pushed-commit',
  3837. 'last-uploaded-commit', 'parent-commit',
  3838. change_desc, 2)
  3839. cl.PostUploadUpdates(options, new_upload, '12345')
  3840. mockSetPatchset.assert_called_once_with(3)
  3841. self.assertEqual(
  3842. scm.GIT.GetConfig('root', 'branch.current-branch.gerritsquashhash'),
  3843. new_upload.commit_to_push)
  3844. self.assertEqual(
  3845. scm.GIT.GetConfig('root', 'branch.current-branch.last-upload-hash'),
  3846. new_upload.new_last_uploaded_commit)
  3847. mockAddReviewers.assert_called_once_with('chromium',
  3848. 'project~123456',
  3849. reviewers=reviewers,
  3850. ccs=ccs,
  3851. notify=False)
  3852. mockRunPostHook.assert_called_once_with(True, 'parent-commit',
  3853. change_desc.description)
  3854. class CMDTestCaseBase(unittest.TestCase):
  3855. _STATUSES = [
  3856. 'STATUS_UNSPECIFIED',
  3857. 'SCHEDULED',
  3858. 'STARTED',
  3859. 'SUCCESS',
  3860. 'FAILURE',
  3861. 'INFRA_FAILURE',
  3862. 'CANCELED',
  3863. ]
  3864. _CHANGE_DETAIL = {
  3865. 'project': 'depot_tools',
  3866. 'status': 'OPEN',
  3867. 'owner': {
  3868. 'email': 'owner@e.mail'
  3869. },
  3870. 'current_revision': 'beeeeeef',
  3871. 'revisions': {
  3872. 'deadbeaf': {
  3873. '_number': 6,
  3874. 'kind': 'REWORK',
  3875. },
  3876. 'beeeeeef': {
  3877. '_number': 7,
  3878. 'kind': 'NO_CODE_CHANGE',
  3879. 'fetch': {
  3880. 'http': {
  3881. 'url': 'https://chromium.googlesource.com/depot_tools',
  3882. 'ref': 'refs/changes/56/123456/7'
  3883. }
  3884. },
  3885. },
  3886. },
  3887. }
  3888. _DEFAULT_RESPONSE = {
  3889. 'builds': [{
  3890. 'id': str(100 + idx),
  3891. 'builder': {
  3892. 'project': 'chromium',
  3893. 'bucket': 'try',
  3894. 'builder': 'bot_' + status.lower(),
  3895. },
  3896. 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
  3897. 'tags': [],
  3898. 'status': status,
  3899. } for idx, status in enumerate(_STATUSES)]
  3900. }
  3901. def setUp(self):
  3902. super(CMDTestCaseBase, self).setUp()
  3903. mock.patch('git_cl.sys.stdout', io.StringIO()).start()
  3904. mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
  3905. mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
  3906. mock.patch(
  3907. 'git_cl.Changelist.GetCodereviewServer',
  3908. return_value='https://chromium-review.googlesource.com').start()
  3909. mock.patch('git_cl.Changelist.GetGerritHost',
  3910. return_value='chromium-review.googlesource.com').start()
  3911. mock.patch('git_cl.Changelist.GetMostRecentPatchset',
  3912. return_value=7).start()
  3913. mock.patch('git_cl.Changelist.GetMostRecentDryRunPatchset',
  3914. return_value=6).start()
  3915. mock.patch('git_cl.Changelist.GetRemoteUrl',
  3916. return_value='https://chromium.googlesource.com/depot_tools'
  3917. ).start()
  3918. mock.patch('auth.Authenticator',
  3919. return_value=AuthenticatorMock()).start()
  3920. mock.patch('gerrit_util.GetChangeDetail',
  3921. return_value=self._CHANGE_DETAIL).start()
  3922. mock.patch('git_cl._call_buildbucket',
  3923. return_value=self._DEFAULT_RESPONSE).start()
  3924. mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
  3925. self.addCleanup(mock.patch.stopall)
  3926. @unittest.skipIf(gclient_utils.IsEnvCog(),
  3927. 'not supported in non-git environment')
  3928. class CMDPresubmitTestCase(CMDTestCaseBase):
  3929. _RUN_HOOK_RETURN = {
  3930. 'errors': [],
  3931. 'more_cc': [],
  3932. 'notifications': [],
  3933. 'warnings': []
  3934. }
  3935. def setUp(self):
  3936. super(CMDPresubmitTestCase, self).setUp()
  3937. mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream',
  3938. return_value='upstream').start()
  3939. mock.patch('git_cl.Changelist.FetchDescription',
  3940. return_value='fetch description').start()
  3941. mock.patch('git_cl._create_description_from_log',
  3942. return_value='get description').start()
  3943. mock.patch('git_cl.Changelist.RunHook',
  3944. return_value=self._RUN_HOOK_RETURN).start()
  3945. def testDefaultCase(self):
  3946. self.assertEqual(0, git_cl.main(['presubmit']))
  3947. git_cl.Changelist.RunHook.assert_called_once_with(
  3948. committing=True,
  3949. may_prompt=False,
  3950. verbose=0,
  3951. parallel=None,
  3952. upstream='upstream',
  3953. description='fetch description',
  3954. all_files=None,
  3955. files=None,
  3956. resultdb=None,
  3957. realm=None)
  3958. def testNoIssue(self):
  3959. git_cl.Changelist.GetIssue.return_value = None
  3960. self.assertEqual(0, git_cl.main(['presubmit']))
  3961. git_cl.Changelist.RunHook.assert_called_once_with(
  3962. committing=True,
  3963. may_prompt=False,
  3964. verbose=0,
  3965. parallel=None,
  3966. upstream='upstream',
  3967. description='get description',
  3968. all_files=None,
  3969. files=None,
  3970. resultdb=None,
  3971. realm=None)
  3972. def testCustomBranch(self):
  3973. self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
  3974. git_cl.Changelist.RunHook.assert_called_once_with(
  3975. committing=True,
  3976. may_prompt=False,
  3977. verbose=0,
  3978. parallel=None,
  3979. upstream='custom_branch',
  3980. description='fetch description',
  3981. all_files=None,
  3982. files=None,
  3983. resultdb=None,
  3984. realm=None)
  3985. def testOptions(self):
  3986. self.assertEqual(
  3987. 0,
  3988. git_cl.main([
  3989. 'presubmit', '-v', '-v', '--all', '--parallel', '-u',
  3990. '--resultdb', '--realm', 'chromium:public'
  3991. ]))
  3992. git_cl.Changelist.RunHook.assert_called_once_with(
  3993. committing=False,
  3994. may_prompt=False,
  3995. verbose=2,
  3996. parallel=True,
  3997. upstream='upstream',
  3998. description='fetch description',
  3999. all_files=True,
  4000. files=None,
  4001. resultdb=True,
  4002. realm='chromium:public')
  4003. @mock.patch('git_cl.write_json')
  4004. def testJson(self, mock_write_json):
  4005. self.assertEqual(0, git_cl.main(['presubmit', '--json', 'file.json']))
  4006. mock_write_json.assert_called_once_with('file.json',
  4007. self._RUN_HOOK_RETURN)
  4008. class CMDTryResultsTestCase(CMDTestCaseBase):
  4009. _DEFAULT_REQUEST = {
  4010. 'predicate': {
  4011. "gerritChanges": [{
  4012. "project": "depot_tools",
  4013. "host": "chromium-review.googlesource.com",
  4014. "patchset": 6,
  4015. "change": 123456,
  4016. }],
  4017. },
  4018. 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
  4019. ',builds.*.createTime,builds.*.tags'),
  4020. }
  4021. _TRIVIAL_REQUEST = {
  4022. 'predicate': {
  4023. "gerritChanges": [{
  4024. "project": "depot_tools",
  4025. "host": "chromium-review.googlesource.com",
  4026. "patchset": 7,
  4027. "change": 123456,
  4028. }],
  4029. },
  4030. 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
  4031. ',builds.*.createTime,builds.*.tags'),
  4032. }
  4033. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4034. 'not supported in non-git environment')
  4035. def testNoJobs(self):
  4036. git_cl._call_buildbucket.return_value = {}
  4037. self.assertEqual(0, git_cl.main(['try-results']))
  4038. self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
  4039. git_cl._call_buildbucket.assert_called_once_with(
  4040. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  4041. self._DEFAULT_REQUEST)
  4042. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4043. 'not supported in non-git environment')
  4044. def testTrivialCommits(self):
  4045. self.assertEqual(0, git_cl.main(['try-results']))
  4046. git_cl._call_buildbucket.assert_called_with(
  4047. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  4048. self._DEFAULT_REQUEST)
  4049. git_cl._call_buildbucket.return_value = {}
  4050. self.assertEqual(0, git_cl.main(['try-results', '--patchset', '7']))
  4051. git_cl._call_buildbucket.assert_called_with(
  4052. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  4053. self._TRIVIAL_REQUEST)
  4054. self.assertEqual([
  4055. 'Successes:',
  4056. ' bot_success https://ci.chromium.org/b/103',
  4057. 'Infra Failures:',
  4058. ' bot_infra_failure https://ci.chromium.org/b/105',
  4059. 'Failures:',
  4060. ' bot_failure https://ci.chromium.org/b/104',
  4061. 'Canceled:',
  4062. ' bot_canceled ',
  4063. 'Started:',
  4064. ' bot_started https://ci.chromium.org/b/102',
  4065. 'Scheduled:',
  4066. ' bot_scheduled id=101',
  4067. 'Other:',
  4068. ' bot_status_unspecified id=100',
  4069. 'Total: 7 tryjobs',
  4070. 'No tryjobs scheduled.',
  4071. ],
  4072. sys.stdout.getvalue().splitlines())
  4073. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4074. 'not supported in non-git environment')
  4075. def testPrintToStdout(self):
  4076. self.assertEqual(0, git_cl.main(['try-results']))
  4077. self.assertEqual([
  4078. 'Successes:',
  4079. ' bot_success https://ci.chromium.org/b/103',
  4080. 'Infra Failures:',
  4081. ' bot_infra_failure https://ci.chromium.org/b/105',
  4082. 'Failures:',
  4083. ' bot_failure https://ci.chromium.org/b/104',
  4084. 'Canceled:',
  4085. ' bot_canceled ',
  4086. 'Started:',
  4087. ' bot_started https://ci.chromium.org/b/102',
  4088. 'Scheduled:',
  4089. ' bot_scheduled id=101',
  4090. 'Other:',
  4091. ' bot_status_unspecified id=100',
  4092. 'Total: 7 tryjobs',
  4093. ],
  4094. sys.stdout.getvalue().splitlines())
  4095. git_cl._call_buildbucket.assert_called_once_with(
  4096. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  4097. self._DEFAULT_REQUEST)
  4098. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4099. 'not supported in non-git environment')
  4100. def testPrintToStdoutWithMasters(self):
  4101. self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
  4102. self.assertEqual([
  4103. 'Successes:',
  4104. ' try bot_success https://ci.chromium.org/b/103',
  4105. 'Infra Failures:',
  4106. ' try bot_infra_failure https://ci.chromium.org/b/105',
  4107. 'Failures:',
  4108. ' try bot_failure https://ci.chromium.org/b/104',
  4109. 'Canceled:',
  4110. ' try bot_canceled ',
  4111. 'Started:',
  4112. ' try bot_started https://ci.chromium.org/b/102',
  4113. 'Scheduled:',
  4114. ' try bot_scheduled id=101',
  4115. 'Other:',
  4116. ' try bot_status_unspecified id=100',
  4117. 'Total: 7 tryjobs',
  4118. ],
  4119. sys.stdout.getvalue().splitlines())
  4120. git_cl._call_buildbucket.assert_called_once_with(
  4121. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  4122. self._DEFAULT_REQUEST)
  4123. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4124. 'not supported in non-git environment')
  4125. @mock.patch('git_cl.write_json')
  4126. def testWriteToJson(self, mockJsonDump):
  4127. self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
  4128. git_cl._call_buildbucket.assert_called_once_with(
  4129. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  4130. self._DEFAULT_REQUEST)
  4131. mockJsonDump.assert_called_once_with('file.json',
  4132. self._DEFAULT_RESPONSE['builds'])
  4133. def test_filter_failed_for_one_simple(self):
  4134. self.assertEqual([], git_cl._filter_failed_for_retry([]))
  4135. self.assertEqual([
  4136. ('chromium', 'try', 'bot_failure'),
  4137. ('chromium', 'try', 'bot_infra_failure'),
  4138. ], git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
  4139. def test_filter_failed_for_retry_many_builds(self):
  4140. def _build(name, created_sec, status, experimental=False):
  4141. assert 0 <= created_sec < 100, created_sec
  4142. b = {
  4143. 'id': 112112,
  4144. 'builder': {
  4145. 'project': 'chromium',
  4146. 'bucket': 'try',
  4147. 'builder': name,
  4148. },
  4149. 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
  4150. 'status': status,
  4151. 'tags': [],
  4152. }
  4153. if experimental:
  4154. b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
  4155. return b
  4156. builds = [
  4157. _build('flaky-last-green', 1, 'FAILURE'),
  4158. _build('flaky-last-green', 2, 'SUCCESS'),
  4159. _build('flaky', 1, 'SUCCESS'),
  4160. _build('flaky', 2, 'FAILURE'),
  4161. _build('running', 1, 'FAILED'),
  4162. _build('running', 2, 'SCHEDULED'),
  4163. _build('yep-still-running', 1, 'STARTED'),
  4164. _build('yep-still-running', 2, 'FAILURE'),
  4165. _build('cq-experimental', 1, 'SUCCESS', experimental=True),
  4166. _build('cq-experimental', 2, 'FAILURE', experimental=True),
  4167. # Simulate experimental in CQ builder, which developer decided
  4168. # to retry manually which resulted in 2nd build non-experimental.
  4169. _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
  4170. _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
  4171. ]
  4172. builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
  4173. self.assertEqual([
  4174. ('chromium', 'try', 'flaky'),
  4175. ('chromium', 'try', 'sometimes-experimental'),
  4176. ], git_cl._filter_failed_for_retry(builds))
  4177. class CMDTryTestCase(CMDTestCaseBase):
  4178. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4179. 'not supported in non-git environment')
  4180. @mock.patch('git_cl.Changelist.SetCQState')
  4181. def testSetCQDryRunByDefault(self, mockSetCQState):
  4182. mockSetCQState.return_value = 0
  4183. self.assertEqual(0, git_cl.main(['try']))
  4184. git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
  4185. self.assertEqual(
  4186. sys.stdout.getvalue(), 'Scheduling CQ dry run on: '
  4187. 'https://chromium-review.googlesource.com/123456\n')
  4188. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4189. 'not supported in non-git environment')
  4190. @mock.patch('git_cl._call_buildbucket')
  4191. def testScheduleOnBuildbucket(self, mockCallBuildbucket):
  4192. mockCallBuildbucket.return_value = {}
  4193. self.assertEqual(
  4194. 0,
  4195. git_cl.main([
  4196. 'try', '-B', 'luci.chromium.try', '-b', 'win', '-p', 'key=val',
  4197. '-p', 'json=[{"a":1}, null]'
  4198. ]))
  4199. self.assertIn('Scheduling jobs on:\n'
  4200. ' chromium/try: win', git_cl.sys.stdout.getvalue())
  4201. expected_request = {
  4202. "requests": [{
  4203. "scheduleBuild": {
  4204. "requestId":
  4205. "uuid4",
  4206. "builder": {
  4207. "project": "chromium",
  4208. "builder": "win",
  4209. "bucket": "try",
  4210. },
  4211. "gerritChanges": [{
  4212. "project": "depot_tools",
  4213. "host": "chromium-review.googlesource.com",
  4214. "patchset": 7,
  4215. "change": 123456,
  4216. }],
  4217. "properties": {
  4218. "category": "git_cl_try",
  4219. "json": [{
  4220. "a": 1
  4221. }, None],
  4222. "key": "val",
  4223. },
  4224. "tags": [
  4225. {
  4226. "value": "win",
  4227. "key": "builder"
  4228. },
  4229. {
  4230. "value": "git_cl_try",
  4231. "key": "user_agent"
  4232. },
  4233. ],
  4234. },
  4235. }],
  4236. }
  4237. mockCallBuildbucket.assert_called_with(mock.ANY,
  4238. 'cr-buildbucket.appspot.com',
  4239. 'Batch', expected_request)
  4240. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4241. 'not supported in non-git environment')
  4242. @mock.patch('git_cl._call_buildbucket')
  4243. def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
  4244. mockCallBuildbucket.return_value = {}
  4245. mock.patch('git_cl.Changelist.GetRemoteBranch',
  4246. return_value=('origin', 'refs/remotes/origin/main')).start()
  4247. self.assertEqual(
  4248. 0,
  4249. git_cl.main([
  4250. 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
  4251. '-p', 'key=val', '-p', 'json=[{"a":1}, null]', '-r',
  4252. 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef'
  4253. ]))
  4254. self.assertIn(
  4255. 'Scheduling jobs on:\n'
  4256. ' chromium/try: linux\n'
  4257. ' chromium/try: win', git_cl.sys.stdout.getvalue())
  4258. expected_request = {
  4259. "requests": [{
  4260. "scheduleBuild": {
  4261. "requestId":
  4262. "uuid4",
  4263. "builder": {
  4264. "project": "chromium",
  4265. "builder": "linux",
  4266. "bucket": "try",
  4267. },
  4268. "gerritChanges": [{
  4269. "project": "depot_tools",
  4270. "host": "chromium-review.googlesource.com",
  4271. "patchset": 7,
  4272. "change": 123456,
  4273. }],
  4274. "properties": {
  4275. "category": "git_cl_try",
  4276. "json": [{
  4277. "a": 1
  4278. }, None],
  4279. "key": "val",
  4280. },
  4281. "tags": [
  4282. {
  4283. "value": "linux",
  4284. "key": "builder"
  4285. },
  4286. {
  4287. "value": "git_cl_try",
  4288. "key": "user_agent"
  4289. },
  4290. ],
  4291. "gitilesCommit": {
  4292. "host": "chromium.googlesource.com",
  4293. "project": "depot_tools",
  4294. "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
  4295. "ref": "refs/heads/main",
  4296. }
  4297. },
  4298. }, {
  4299. "scheduleBuild": {
  4300. "requestId":
  4301. "uuid4",
  4302. "builder": {
  4303. "project": "chromium",
  4304. "builder": "win",
  4305. "bucket": "try",
  4306. },
  4307. "gerritChanges": [{
  4308. "project": "depot_tools",
  4309. "host": "chromium-review.googlesource.com",
  4310. "patchset": 7,
  4311. "change": 123456,
  4312. }],
  4313. "properties": {
  4314. "category": "git_cl_try",
  4315. "json": [{
  4316. "a": 1
  4317. }, None],
  4318. "key": "val",
  4319. },
  4320. "tags": [
  4321. {
  4322. "value": "win",
  4323. "key": "builder"
  4324. },
  4325. {
  4326. "value": "git_cl_try",
  4327. "key": "user_agent"
  4328. },
  4329. ],
  4330. "gitilesCommit": {
  4331. "host": "chromium.googlesource.com",
  4332. "project": "depot_tools",
  4333. "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
  4334. "ref": "refs/heads/main",
  4335. }
  4336. },
  4337. }],
  4338. }
  4339. mockCallBuildbucket.assert_called_with(mock.ANY,
  4340. 'cr-buildbucket.appspot.com',
  4341. 'Batch', expected_request)
  4342. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4343. 'not supported in non-git environment')
  4344. @mock.patch('sys.stderr', io.StringIO())
  4345. def testScheduleOnBuildbucket_WrongBucket(self):
  4346. with self.assertRaises(SystemExit):
  4347. git_cl.main([
  4348. 'try', '-B', 'not-a-bucket', '-b', 'win', '-p', 'key=val', '-p',
  4349. 'json=[{"a":1}, null]'
  4350. ])
  4351. self.assertIn('Invalid bucket: not-a-bucket.', sys.stderr.getvalue())
  4352. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4353. 'not supported in non-git environment')
  4354. @mock.patch('git_cl._call_buildbucket')
  4355. @mock.patch('git_cl._fetch_tryjobs')
  4356. def testScheduleOnBuildbucketRetryFailed(self, mockFetchTryJobs,
  4357. mockCallBuildbucket):
  4358. git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
  4359. 7: [],
  4360. 6: [{
  4361. 'id': 112112,
  4362. 'builder': {
  4363. 'project': 'chromium',
  4364. 'bucket': 'try',
  4365. 'builder': 'linux',
  4366. },
  4367. 'createTime': '2019-10-09T08:00:01.854286Z',
  4368. 'tags': [],
  4369. 'status': 'FAILURE',
  4370. }],
  4371. }[kw['patchset']]
  4372. mockCallBuildbucket.return_value = {}
  4373. self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
  4374. self.assertIn('Scheduling jobs on:\n'
  4375. ' chromium/try: linux', git_cl.sys.stdout.getvalue())
  4376. expected_request = {
  4377. "requests": [{
  4378. "scheduleBuild": {
  4379. "requestId":
  4380. "uuid4",
  4381. "builder": {
  4382. "project": "chromium",
  4383. "bucket": "try",
  4384. "builder": "linux",
  4385. },
  4386. "gerritChanges": [{
  4387. "project": "depot_tools",
  4388. "host": "chromium-review.googlesource.com",
  4389. "patchset": 7,
  4390. "change": 123456,
  4391. }],
  4392. "properties": {
  4393. "category": "git_cl_try",
  4394. },
  4395. "tags": [
  4396. {
  4397. "value": "linux",
  4398. "key": "builder"
  4399. },
  4400. {
  4401. "value": "git_cl_try",
  4402. "key": "user_agent"
  4403. },
  4404. {
  4405. "value": "1",
  4406. "key": "retry_failed"
  4407. },
  4408. ],
  4409. },
  4410. }],
  4411. }
  4412. mockCallBuildbucket.assert_called_with(mock.ANY,
  4413. 'cr-buildbucket.appspot.com',
  4414. 'Batch', expected_request)
  4415. def test_parse_bucket(self):
  4416. test_cases = [
  4417. {
  4418. 'bucket': 'chromium/try',
  4419. 'result': ('chromium', 'try'),
  4420. },
  4421. {
  4422. 'bucket': 'luci.chromium.try',
  4423. 'result': ('chromium', 'try'),
  4424. 'has_warning': True,
  4425. },
  4426. {
  4427. 'bucket': 'skia.primary',
  4428. 'result': ('skia', 'skia.primary'),
  4429. 'has_warning': True,
  4430. },
  4431. {
  4432. 'bucket': 'not-a-bucket',
  4433. 'result': (None, None),
  4434. },
  4435. ]
  4436. for test_case in test_cases:
  4437. git_cl.sys.stdout.truncate(0)
  4438. self.assertEqual(test_case['result'],
  4439. git_cl._parse_bucket(test_case['bucket']))
  4440. if test_case.get('has_warning'):
  4441. expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
  4442. test_case['result'])
  4443. self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
  4444. class CMDUploadTestCase(CMDTestCaseBase):
  4445. def setUp(self):
  4446. super(CMDUploadTestCase, self).setUp()
  4447. mock.patch('git_cl._fetch_tryjobs').start()
  4448. mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
  4449. mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
  4450. mock.patch('git_cl.Settings.GetRoot', return_value='').start()
  4451. mock.patch('git_cl.Settings.GetSquashGerritUploads',
  4452. return_value=True).start()
  4453. self.addCleanup(mock.patch.stopall)
  4454. class MakeRequestsHelperTestCase(unittest.TestCase):
  4455. def exampleGerritChange(self):
  4456. return {
  4457. 'host': 'chromium-review.googlesource.com',
  4458. 'project': 'depot_tools',
  4459. 'change': 1,
  4460. 'patchset': 2,
  4461. }
  4462. def testMakeRequestsHelperNoOptions(self):
  4463. # Basic test for the helper function _make_tryjob_schedule_requests;
  4464. # it shouldn't throw AttributeError even when options doesn't have any
  4465. # of the expected values; it will use default option values.
  4466. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  4467. jobs = [('chromium', 'try', 'my-builder')]
  4468. options = optparse.Values()
  4469. requests = git_cl._make_tryjob_schedule_requests(changelist,
  4470. jobs,
  4471. options,
  4472. patchset=None)
  4473. # requestId is non-deterministic. Just assert that it's there and has
  4474. # a particular length.
  4475. self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
  4476. self.assertEqual(requests, [{
  4477. 'scheduleBuild': {
  4478. 'builder': {
  4479. 'bucket': 'try',
  4480. 'builder': 'my-builder',
  4481. 'project': 'chromium'
  4482. },
  4483. 'gerritChanges': [self.exampleGerritChange()],
  4484. 'properties': {
  4485. 'category': 'git_cl_try'
  4486. },
  4487. 'tags': [{
  4488. 'key': 'builder',
  4489. 'value': 'my-builder'
  4490. }, {
  4491. 'key': 'user_agent',
  4492. 'value': 'git_cl_try'
  4493. }]
  4494. }
  4495. }])
  4496. def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
  4497. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  4498. jobs = [('chromium', 'try', 'presubmit')]
  4499. options = optparse.Values()
  4500. requests = git_cl._make_tryjob_schedule_requests(changelist,
  4501. jobs,
  4502. options,
  4503. patchset=None)
  4504. self.assertEqual(requests[0]['scheduleBuild']['properties'], {
  4505. 'category': 'git_cl_try',
  4506. 'dry_run': 'true'
  4507. })
  4508. def testMakeRequestsHelperRevisionSet(self):
  4509. # Gitiles commit is specified when revision is in options.
  4510. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  4511. jobs = [('chromium', 'try', 'my-builder')]
  4512. options = optparse.Values({'revision': 'ba5eba11'})
  4513. requests = git_cl._make_tryjob_schedule_requests(changelist,
  4514. jobs,
  4515. options,
  4516. patchset=None)
  4517. self.assertEqual(
  4518. requests[0]['scheduleBuild']['gitilesCommit'], {
  4519. 'host': 'chromium.googlesource.com',
  4520. 'id': 'ba5eba11',
  4521. 'project': 'depot_tools',
  4522. 'ref': 'refs/heads/main',
  4523. })
  4524. def testMakeRequestsHelperRetryFailedSet(self):
  4525. # An extra tag is added when retry_failed is in options.
  4526. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  4527. jobs = [('chromium', 'try', 'my-builder')]
  4528. options = optparse.Values({'retry_failed': 'true'})
  4529. requests = git_cl._make_tryjob_schedule_requests(changelist,
  4530. jobs,
  4531. options,
  4532. patchset=None)
  4533. self.assertEqual(requests[0]['scheduleBuild']['tags'],
  4534. [{
  4535. 'key': 'builder',
  4536. 'value': 'my-builder'
  4537. }, {
  4538. 'key': 'user_agent',
  4539. 'value': 'git_cl_try'
  4540. }, {
  4541. 'key': 'retry_failed',
  4542. 'value': '1'
  4543. }])
  4544. def testMakeRequestsHelperCategorySet(self):
  4545. # The category property can be overridden with options.
  4546. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  4547. jobs = [('chromium', 'try', 'my-builder')]
  4548. options = optparse.Values({'category': 'my-special-category'})
  4549. requests = git_cl._make_tryjob_schedule_requests(changelist,
  4550. jobs,
  4551. options,
  4552. patchset=None)
  4553. self.assertEqual(requests[0]['scheduleBuild']['properties'],
  4554. {'category': 'my-special-category'})
  4555. class CMDFormatTestCase(unittest.TestCase):
  4556. def setUp(self):
  4557. super(CMDFormatTestCase, self).setUp()
  4558. mock.patch('git_cl.RunCommand').start()
  4559. mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
  4560. mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
  4561. mock.patch('git_cl.settings').start()
  4562. self._top_dir = tempfile.mkdtemp()
  4563. self.addCleanup(mock.patch.stopall)
  4564. def tearDown(self):
  4565. shutil.rmtree(self._top_dir)
  4566. super(CMDFormatTestCase, self).tearDown()
  4567. def _make_temp_file(self, fname, contents):
  4568. gclient_utils.FileWrite(os.path.join(self._top_dir, fname),
  4569. ('\n'.join(contents)))
  4570. def _make_yapfignore(self, contents):
  4571. self._make_temp_file('.yapfignore', contents)
  4572. def _check_yapf_filtering(self, files, expected):
  4573. self.assertEqual(
  4574. expected,
  4575. git_cl._FilterYapfIgnoredFiles(
  4576. files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
  4577. def _run_command_mock(self, return_value):
  4578. def f(*args, **kwargs):
  4579. if 'stdin' in kwargs:
  4580. self.assertIsInstance(kwargs['stdin'], bytes)
  4581. return return_value
  4582. return f
  4583. def testClangFormatDiffFull(self):
  4584. self._make_temp_file('test.cc', ['// test'])
  4585. git_cl.settings.GetFormatFullByDefault.return_value = False
  4586. diff_file = [os.path.join(self._top_dir, 'test.cc')]
  4587. mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
  4588. # Diff
  4589. git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
  4590. return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
  4591. self._top_dir, 'HEAD')
  4592. self.assertEqual(2, return_value)
  4593. # No diff
  4594. git_cl.RunCommand.side_effect = self._run_command_mock('// test')
  4595. return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
  4596. self._top_dir, 'HEAD')
  4597. self.assertEqual(0, return_value)
  4598. def testClangFormatDiff(self):
  4599. git_cl.settings.GetFormatFullByDefault.return_value = False
  4600. # A valid file is required, so use this test.
  4601. clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
  4602. mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
  4603. # Diff
  4604. git_cl.RunCommand.side_effect = self._run_command_mock('error')
  4605. return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'],
  4606. self._top_dir, 'HEAD')
  4607. self.assertEqual(2, return_value)
  4608. # No diff
  4609. git_cl.RunCommand.side_effect = self._run_command_mock('')
  4610. return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'],
  4611. self._top_dir, 'HEAD')
  4612. self.assertEqual(0, return_value)
  4613. def testYapfignoreExplicit(self):
  4614. self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
  4615. files = [
  4616. 'bar.py',
  4617. 'foo/bar.py',
  4618. 'foo/baz.py',
  4619. 'foo/bar/baz.py',
  4620. 'foo/bar/foobar.py',
  4621. ]
  4622. expected = [
  4623. 'bar.py',
  4624. 'foo/baz.py',
  4625. 'foo/bar/foobar.py',
  4626. ]
  4627. self._check_yapf_filtering(files, expected)
  4628. def testYapfignoreSingleWildcards(self):
  4629. self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
  4630. files = [
  4631. 'bar.py', # Matched by *bar.py.
  4632. 'bar.txt',
  4633. 'foobar.py', # Matched by *bar.py, foo*.
  4634. 'foobar.txt', # Matched by foo*.
  4635. 'bazbar.py', # Matched by *bar.py, baz*.py.
  4636. 'bazbar.txt',
  4637. 'foo/baz.txt', # Matched by foo*.
  4638. 'bar/bar.py', # Matched by *bar.py.
  4639. 'baz/foo.py', # Matched by baz*.py, foo*.
  4640. 'baz/foo.txt',
  4641. ]
  4642. expected = [
  4643. 'bar.txt',
  4644. 'bazbar.txt',
  4645. 'baz/foo.txt',
  4646. ]
  4647. self._check_yapf_filtering(files, expected)
  4648. def testYapfignoreMultiplewildcards(self):
  4649. self._make_yapfignore(['*bar*', '*foo*baz.txt'])
  4650. files = [
  4651. 'bar.py', # Matched by *bar*.
  4652. 'bar.txt', # Matched by *bar*.
  4653. 'abar.py', # Matched by *bar*.
  4654. 'foobaz.txt', # Matched by *foo*baz.txt.
  4655. 'foobaz.py',
  4656. 'afoobaz.txt', # Matched by *foo*baz.txt.
  4657. ]
  4658. expected = [
  4659. 'foobaz.py',
  4660. ]
  4661. self._check_yapf_filtering(files, expected)
  4662. def testYapfignoreComments(self):
  4663. self._make_yapfignore(['test.py', '#test2.py'])
  4664. files = [
  4665. 'test.py',
  4666. 'test2.py',
  4667. ]
  4668. expected = [
  4669. 'test2.py',
  4670. ]
  4671. self._check_yapf_filtering(files, expected)
  4672. def testYapfHandleUtf8(self):
  4673. self._make_yapfignore(['test.py', 'test_🌐.py'])
  4674. files = [
  4675. 'test.py',
  4676. 'test_🌐.py',
  4677. 'test2.py',
  4678. ]
  4679. expected = [
  4680. 'test2.py',
  4681. ]
  4682. self._check_yapf_filtering(files, expected)
  4683. def testYapfignoreBlankLines(self):
  4684. self._make_yapfignore(['test.py', '', '', 'test2.py'])
  4685. files = [
  4686. 'test.py',
  4687. 'test2.py',
  4688. 'test3.py',
  4689. ]
  4690. expected = [
  4691. 'test3.py',
  4692. ]
  4693. self._check_yapf_filtering(files, expected)
  4694. def testYapfignoreWhitespace(self):
  4695. self._make_yapfignore([' test.py '])
  4696. files = [
  4697. 'test.py',
  4698. 'test2.py',
  4699. ]
  4700. expected = [
  4701. 'test2.py',
  4702. ]
  4703. self._check_yapf_filtering(files, expected)
  4704. def testYapfignoreNoFiles(self):
  4705. self._make_yapfignore(['test.py'])
  4706. self._check_yapf_filtering([], [])
  4707. def testYapfignoreMissingYapfignore(self):
  4708. files = [
  4709. 'test.py',
  4710. ]
  4711. expected = [
  4712. 'test.py',
  4713. ]
  4714. self._check_yapf_filtering(files, expected)
  4715. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4716. 'not supported in non-git environment')
  4717. class CMDStatusTestCase(CMDTestCaseBase):
  4718. # Return branch names a,..,f with comitterdates in increasing order, i.e.
  4719. # 'f' is the most-recently changed branch.
  4720. def _mock_run_git(commands):
  4721. if commands == [
  4722. 'for-each-ref', '--format=%(refname) %(committerdate:unix)',
  4723. 'refs/heads'
  4724. ]:
  4725. branches_and_committerdates = [
  4726. 'refs/heads/a 1',
  4727. 'refs/heads/b 2',
  4728. 'refs/heads/c 3',
  4729. 'refs/heads/d 4',
  4730. 'refs/heads/e 5',
  4731. 'refs/heads/f 6',
  4732. ]
  4733. return '\n'.join(branches_and_committerdates)
  4734. # Mock the status in such a way that the issue number gives us an
  4735. # indication of the commit date (simplifies manual debugging).
  4736. def _mock_get_cl_statuses(branches, fine_grained, max_processes):
  4737. for c in branches:
  4738. c.issue = (100 + int(c.GetCommitDate()))
  4739. yield (c, 'open')
  4740. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  4741. @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
  4742. @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
  4743. @mock.patch('git_cl.RunGit', _mock_run_git)
  4744. @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
  4745. @mock.patch('git_cl.Settings.GetRoot', return_value='')
  4746. @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
  4747. @mock.patch('scm.GIT.GetBranch', return_value='a')
  4748. def testStatus(self, *_mocks):
  4749. self.assertEqual(0, git_cl.main(['status', '--no-branch-color']))
  4750. self.maxDiff = None
  4751. self.assertEqual(
  4752. sys.stdout.getvalue(), 'Branches associated with reviews:\n'
  4753. ' * a : https://crrev.com/c/101 (open)\n'
  4754. ' b : https://crrev.com/c/102 (open)\n'
  4755. ' c : https://crrev.com/c/103 (open)\n'
  4756. ' d : https://crrev.com/c/104 (open)\n'
  4757. ' e : https://crrev.com/c/105 (open)\n'
  4758. ' f : https://crrev.com/c/106 (open)\n\n'
  4759. 'Current branch: a\n'
  4760. 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
  4761. 'Issue description:\n'
  4762. 'x\n')
  4763. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  4764. @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
  4765. @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
  4766. @mock.patch('git_cl.RunGit', _mock_run_git)
  4767. @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
  4768. @mock.patch('git_cl.Settings.GetRoot', return_value='')
  4769. @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=False)
  4770. @mock.patch('scm.GIT.GetBranch', return_value='a')
  4771. def testStatusByDate(self, *_mocks):
  4772. self.assertEqual(
  4773. 0, git_cl.main(['status', '--no-branch-color', '--date-order']))
  4774. self.maxDiff = None
  4775. self.assertEqual(
  4776. sys.stdout.getvalue(), 'Branches associated with reviews:\n'
  4777. ' f : https://crrev.com/c/106 (open)\n'
  4778. ' e : https://crrev.com/c/105 (open)\n'
  4779. ' d : https://crrev.com/c/104 (open)\n'
  4780. ' c : https://crrev.com/c/103 (open)\n'
  4781. ' b : https://crrev.com/c/102 (open)\n'
  4782. ' * a : https://crrev.com/c/101 (open)\n\n'
  4783. 'Current branch: a\n'
  4784. 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
  4785. 'Issue description:\n'
  4786. 'x\n')
  4787. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  4788. @mock.patch('git_cl.Changelist.FetchDescription', lambda cl, pretty: 'x')
  4789. @mock.patch('git_cl.Changelist.GetIssue', lambda cl: cl.issue)
  4790. @mock.patch('git_cl.RunGit', _mock_run_git)
  4791. @mock.patch('git_cl.get_cl_statuses', _mock_get_cl_statuses)
  4792. @mock.patch('git_cl.Settings.GetRoot', return_value='')
  4793. @mock.patch('git_cl.Settings.IsStatusCommitOrderByDate', return_value=True)
  4794. @mock.patch('scm.GIT.GetBranch', return_value='a')
  4795. def testStatusByDate(self, *_mocks):
  4796. self.assertEqual(0, git_cl.main(['status', '--no-branch-color']))
  4797. self.maxDiff = None
  4798. self.assertEqual(
  4799. sys.stdout.getvalue(), 'Branches associated with reviews:\n'
  4800. ' f : https://crrev.com/c/106 (open)\n'
  4801. ' e : https://crrev.com/c/105 (open)\n'
  4802. ' d : https://crrev.com/c/104 (open)\n'
  4803. ' c : https://crrev.com/c/103 (open)\n'
  4804. ' b : https://crrev.com/c/102 (open)\n'
  4805. ' * a : https://crrev.com/c/101 (open)\n\n'
  4806. 'Current branch: a\n'
  4807. 'Issue number: 101 (https://chromium-review.googlesource.com/101)\n'
  4808. 'Issue description:\n'
  4809. 'x\n')
  4810. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4811. 'not supported in non-git environment')
  4812. class CMDOwnersTestCase(CMDTestCaseBase):
  4813. def setUp(self):
  4814. super(CMDOwnersTestCase, self).setUp()
  4815. self.owners_by_path = {
  4816. 'foo': ['a@example.com'],
  4817. 'bar': ['b@example.com', 'c@example.com'],
  4818. }
  4819. mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
  4820. mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
  4821. mock.patch('git_cl.Changelist.GetAffectedFiles',
  4822. return_value=list(self.owners_by_path)).start()
  4823. mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream',
  4824. return_value='upstream').start()
  4825. mock.patch('git_cl.Changelist.GetGerritHost',
  4826. return_value='host').start()
  4827. mock.patch('git_cl.Changelist.GetGerritProject',
  4828. return_value='project').start()
  4829. mock.patch('git_cl.Changelist.GetRemoteBranch',
  4830. return_value=('origin', 'refs/remotes/origin/main')).start()
  4831. mock.patch('owners_client.OwnersClient.BatchListOwners',
  4832. return_value=self.owners_by_path).start()
  4833. mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost',
  4834. return_value=True).start()
  4835. self.addCleanup(mock.patch.stopall)
  4836. def testShowAllNoArgs(self):
  4837. self.assertEqual(0, git_cl.main(['owners', '--show-all']))
  4838. self.assertEqual('No files specified for --show-all. Nothing to do.\n',
  4839. git_cl.sys.stdout.getvalue())
  4840. def testShowAll(self):
  4841. self.assertEqual(
  4842. 0, git_cl.main(['owners', '--show-all', 'foo', 'bar', 'baz']))
  4843. owners_client.OwnersClient.BatchListOwners.assert_called_once_with(
  4844. ['foo', 'bar', 'baz'])
  4845. self.assertEqual(
  4846. '\n'.join([
  4847. 'Owners for foo:',
  4848. ' - a@example.com',
  4849. 'Owners for bar:',
  4850. ' - b@example.com',
  4851. ' - c@example.com',
  4852. 'Owners for baz:',
  4853. ' - No owners found',
  4854. '',
  4855. ]), sys.stdout.getvalue())
  4856. def testBatch(self):
  4857. self.assertEqual(0, git_cl.main(['owners', '--batch']))
  4858. self.assertIn('a@example.com', sys.stdout.getvalue())
  4859. self.assertIn('b@example.com', sys.stdout.getvalue())
  4860. class CMDLintTestCase(CMDTestCaseBase):
  4861. bad_indent = '\n'.join([
  4862. '// Copyright 1999 <a@example.com>',
  4863. 'namespace foo {',
  4864. ' class a;',
  4865. '}',
  4866. '',
  4867. ])
  4868. filesInCL = ['foo', 'bar']
  4869. def setUp(self):
  4870. super(CMDLintTestCase, self).setUp()
  4871. mock.patch('git_cl.sys.stderr', io.StringIO()).start()
  4872. mock.patch('codecs.open', mock.mock_open()).start()
  4873. mock.patch('os.path.isfile', return_value=True).start()
  4874. def testLintSingleFile(self, *_mock):
  4875. codecs.open().read.return_value = self.bad_indent
  4876. self.assertEqual(1, git_cl.main(['lint', 'pdf.h']))
  4877. self.assertIn('pdf.h:3: (cpplint) Do not indent within a namespace',
  4878. git_cl.sys.stderr.getvalue())
  4879. def testLintMultiFiles(self, *_mock):
  4880. codecs.open().read.return_value = self.bad_indent
  4881. self.assertEqual(1, git_cl.main(['lint', 'pdf.h', 'pdf.cc']))
  4882. self.assertIn('pdf.h:3: (cpplint) Do not indent within a namespace',
  4883. git_cl.sys.stderr.getvalue())
  4884. self.assertIn('pdf.cc:3: (cpplint) Do not indent within a namespace',
  4885. git_cl.sys.stderr.getvalue())
  4886. @unittest.skipIf(gclient_utils.IsEnvCog(),
  4887. 'not supported in non-git environment')
  4888. @mock.patch('git_cl.Changelist.GetAffectedFiles',
  4889. return_value=['chg-1.h', 'chg-2.cc'])
  4890. @mock.patch('git_cl.Changelist.GetCommonAncestorWithUpstream',
  4891. return_value='upstream')
  4892. @mock.patch('git_cl.Settings.GetRoot', return_value='.')
  4893. @mock.patch('git_cl.FindCodereviewSettingsFile', return_value=None)
  4894. def testLintChangelist(self, *_mock):
  4895. codecs.open().read.return_value = self.bad_indent
  4896. self.assertEqual(1, git_cl.main(['lint']))
  4897. self.assertIn('chg-1.h:3: (cpplint) Do not indent within a namespace',
  4898. git_cl.sys.stderr.getvalue())
  4899. self.assertIn('chg-2.cc:3: (cpplint) Do not indent within a namespace',
  4900. git_cl.sys.stderr.getvalue())
  4901. class CMDCherryPickTestCase(CMDTestCaseBase):
  4902. def setUp(self):
  4903. super(CMDTestCaseBase, self).setUp()
  4904. def testCreateCommitMessage(self):
  4905. orig_message = """Foo the bar
  4906. This change foo's the bar.
  4907. Bug: 123456
  4908. Change-Id: I25699146b24c7ad8776f17775f489b9d41499595
  4909. """
  4910. expected_message = """Cherry pick "Foo the bar"
  4911. Original change's description:
  4912. > Foo the bar
  4913. >
  4914. > This change foo's the bar.
  4915. >
  4916. > Bug: 123456
  4917. > Change-Id: I25699146b24c7ad8776f17775f489b9d41499595
  4918. """
  4919. self.assertEqual(git_cl._create_commit_message(orig_message),
  4920. expected_message)
  4921. def testCreateCommitMessageWithBug(self):
  4922. bug = "987654"
  4923. orig_message = """Foo the bar
  4924. This change foo's the bar.
  4925. Bug: 123456
  4926. Change-Id: I25699146b24c7ad8776f17775f489b9d41499595
  4927. """
  4928. expected_message = f"""Cherry pick "Foo the bar"
  4929. Original change's description:
  4930. > Foo the bar
  4931. >
  4932. > This change foo's the bar.
  4933. >
  4934. > Bug: 123456
  4935. > Change-Id: I25699146b24c7ad8776f17775f489b9d41499595
  4936. Bug: {bug}
  4937. """
  4938. self.assertEqual(git_cl._create_commit_message(orig_message, bug),
  4939. expected_message)
  4940. if __name__ == '__main__':
  4941. logging.basicConfig(
  4942. level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
  4943. unittest.main()