git_cl_test.py 221 KB

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