git_cl_test.py 221 KB

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