git_cl_test.py 214 KB

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