git_cl_test.py 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683
  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. from __future__ import print_function
  8. from __future__ import unicode_literals
  9. import datetime
  10. import json
  11. import logging
  12. import multiprocessing
  13. import optparse
  14. import os
  15. import pprint
  16. import shutil
  17. import sys
  18. import tempfile
  19. import unittest
  20. if sys.version_info.major == 2:
  21. from StringIO import StringIO
  22. import mock
  23. else:
  24. from io import StringIO
  25. from unittest import mock
  26. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  27. import metrics
  28. # We have to disable monitoring before importing git_cl.
  29. metrics.DISABLE_METRICS_COLLECTION = True
  30. import clang_format
  31. import contextlib
  32. import gclient_utils
  33. import gerrit_util
  34. import git_cl
  35. import git_common
  36. import git_footers
  37. import git_new_branch
  38. import scm
  39. import subprocess2
  40. NETRC_FILENAME = '_netrc' if sys.platform == 'win32' else '.netrc'
  41. def callError(code=1, cmd='', cwd='', stdout=b'', stderr=b''):
  42. return subprocess2.CalledProcessError(code, cmd, cwd, stdout, stderr)
  43. CERR1 = callError(1)
  44. class TemporaryFileMock(object):
  45. def __init__(self):
  46. self.suffix = 0
  47. @contextlib.contextmanager
  48. def __call__(self):
  49. self.suffix += 1
  50. yield '/tmp/fake-temp' + str(self.suffix)
  51. class ChangelistMock(object):
  52. # A class variable so we can access it when we don't have access to the
  53. # instance that's being set.
  54. desc = ''
  55. def __init__(self, gerrit_change=None, **kwargs):
  56. self._gerrit_change = gerrit_change
  57. def GetIssue(self):
  58. return 1
  59. def FetchDescription(self):
  60. return ChangelistMock.desc
  61. def UpdateDescription(self, desc, force=False):
  62. ChangelistMock.desc = desc
  63. def GetGerritChange(self, patchset=None, **kwargs):
  64. del patchset
  65. return self._gerrit_change
  66. class GitMocks(object):
  67. def __init__(self, config=None, branchref=None):
  68. self.branchref = branchref or 'refs/heads/master'
  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 files.
  120. pass
  121. @classmethod
  122. def get_gitcookies_path(cls):
  123. return os.path.join('~', '.gitcookies')
  124. @classmethod
  125. def get_netrc_path(cls):
  126. return os.path.join('~', NETRC_FILENAME)
  127. def _get_auth_for_host(self, host):
  128. if same_auth:
  129. return same_auth
  130. return (hosts_with_creds or {}).get(host)
  131. return CookiesAuthenticatorMock
  132. class MockChangelistWithBranchAndIssue():
  133. def __init__(self, branch, issue):
  134. self.branch = branch
  135. self.issue = issue
  136. def GetBranch(self):
  137. return self.branch
  138. def GetIssue(self):
  139. return self.issue
  140. class SystemExitMock(Exception):
  141. pass
  142. class TestGitClBasic(unittest.TestCase):
  143. def setUp(self):
  144. mock.patch('sys.exit', side_effect=SystemExitMock).start()
  145. mock.patch('sys.stdout', StringIO()).start()
  146. mock.patch('sys.stderr', StringIO()).start()
  147. self.addCleanup(mock.patch.stopall)
  148. def test_die_with_error(self):
  149. with self.assertRaises(SystemExitMock):
  150. git_cl.DieWithError('foo', git_cl.ChangeDescription('lorem ipsum'))
  151. self.assertEqual(sys.stderr.getvalue(), 'foo\n')
  152. self.assertTrue('saving CL description' in sys.stdout.getvalue())
  153. self.assertTrue('Content of CL description' in sys.stdout.getvalue())
  154. self.assertTrue('lorem ipsum' in sys.stdout.getvalue())
  155. sys.exit.assert_called_once_with(1)
  156. def test_die_with_error_no_desc(self):
  157. with self.assertRaises(SystemExitMock):
  158. git_cl.DieWithError('foo')
  159. self.assertEqual(sys.stderr.getvalue(), 'foo\n')
  160. self.assertEqual(sys.stdout.getvalue(), '')
  161. sys.exit.assert_called_once_with(1)
  162. def test_fetch_description(self):
  163. cl = git_cl.Changelist(issue=1, codereview_host='host')
  164. cl.description = 'x'
  165. self.assertEqual(cl.FetchDescription(), 'x')
  166. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  167. @mock.patch('git_cl.Changelist.GetStatus', lambda cl: cl.status)
  168. def test_get_cl_statuses(self, *_mocks):
  169. statuses = [
  170. 'closed', 'commit', 'dry-run', 'lgtm', 'reply', 'unsent', 'waiting']
  171. changes = []
  172. for status in statuses:
  173. cl = git_cl.Changelist()
  174. cl.status = status
  175. changes.append(cl)
  176. actual = set(git_cl.get_cl_statuses(changes, True))
  177. self.assertEqual(set(zip(changes, statuses)), actual)
  178. def test_get_cl_statuses_no_changes(self):
  179. self.assertEqual([], list(git_cl.get_cl_statuses([], True)))
  180. @mock.patch('git_cl.Changelist.EnsureAuthenticated')
  181. @mock.patch('multiprocessing.pool.ThreadPool')
  182. def test_get_cl_statuses_timeout(self, *_mocks):
  183. changes = [git_cl.Changelist() for _ in range(2)]
  184. pool = multiprocessing.pool.ThreadPool()
  185. it = pool.imap_unordered.return_value.__iter__ = mock.Mock()
  186. it.return_value.next.side_effect = [
  187. (changes[0], 'lgtm'),
  188. multiprocessing.TimeoutError,
  189. ]
  190. actual = list(git_cl.get_cl_statuses(changes, True))
  191. self.assertEqual([(changes[0], 'lgtm'), (changes[1], 'error')], actual)
  192. @mock.patch('git_cl.Changelist.GetIssueURL')
  193. def test_get_cl_statuses_not_finegrained(self, _mock):
  194. changes = [git_cl.Changelist() for _ in range(2)]
  195. urls = ['some-url', None]
  196. git_cl.Changelist.GetIssueURL.side_effect = urls
  197. actual = set(git_cl.get_cl_statuses(changes, False))
  198. self.assertEqual(
  199. set([(changes[0], 'waiting'), (changes[1], 'error')]), actual)
  200. def test_get_issue_url(self):
  201. cl = git_cl.Changelist(issue=123)
  202. cl._gerrit_server = 'https://example.com'
  203. self.assertEqual(cl.GetIssueURL(), 'https://example.com/123')
  204. self.assertEqual(cl.GetIssueURL(short=True), 'https://example.com/123')
  205. cl = git_cl.Changelist(issue=123)
  206. cl._gerrit_server = 'https://chromium-review.googlesource.com'
  207. self.assertEqual(cl.GetIssueURL(),
  208. 'https://chromium-review.googlesource.com/123')
  209. self.assertEqual(cl.GetIssueURL(short=True), 'https://crrev.com/c/123')
  210. def test_set_preserve_tryjobs(self):
  211. d = git_cl.ChangeDescription('Simple.')
  212. d.set_preserve_tryjobs()
  213. self.assertEqual(d.description.splitlines(), [
  214. 'Simple.',
  215. '',
  216. 'Cq-Do-Not-Cancel-Tryjobs: true',
  217. ])
  218. before = d.description
  219. d.set_preserve_tryjobs()
  220. self.assertEqual(before, d.description)
  221. d = git_cl.ChangeDescription('\n'.join([
  222. 'One is enough',
  223. '',
  224. 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
  225. 'Change-Id: Ideadbeef',
  226. ]))
  227. d.set_preserve_tryjobs()
  228. self.assertEqual(d.description.splitlines(), [
  229. 'One is enough',
  230. '',
  231. 'Cq-Do-Not-Cancel-Tryjobs: dups not encouraged, but don\'t hurt',
  232. 'Change-Id: Ideadbeef',
  233. 'Cq-Do-Not-Cancel-Tryjobs: true',
  234. ])
  235. def test_get_bug_line_values(self):
  236. f = lambda p, bugs: list(git_cl._get_bug_line_values(p, bugs))
  237. self.assertEqual(f('', ''), [])
  238. self.assertEqual(f('', '123,v8:456'), ['123', 'v8:456'])
  239. # Prefix that ends with colon.
  240. self.assertEqual(f('v8:', '456'), ['v8:456'])
  241. self.assertEqual(f('v8:', 'chromium:123,456'), ['v8:456', 'chromium:123'])
  242. # Prefix that ends without colon.
  243. self.assertEqual(f('v8', '456'), ['v8:456'])
  244. self.assertEqual(f('v8', 'chromium:123,456'), ['v8:456', 'chromium:123'])
  245. # Not nice, but not worth carying.
  246. self.assertEqual(f('v8:', 'chromium:123,456,v8:123'),
  247. ['v8:456', 'chromium:123', 'v8:123'])
  248. self.assertEqual(f('v8', 'chromium:123,456,v8:123'),
  249. ['v8:456', 'chromium:123', 'v8:123'])
  250. @mock.patch('gerrit_util.GetAccountDetails')
  251. def test_valid_accounts(self, mockGetAccountDetails):
  252. mock_per_account = {
  253. 'u1': None, # 404, doesn't exist.
  254. 'u2': {
  255. '_account_id': 123124,
  256. 'avatars': [],
  257. 'email': 'u2@example.com',
  258. 'name': 'User Number 2',
  259. 'status': 'OOO',
  260. },
  261. 'u3': git_cl.gerrit_util.GerritError(500, 'retries didn\'t help :('),
  262. }
  263. def GetAccountDetailsMock(_, account):
  264. # Poor-man's mock library's side_effect.
  265. v = mock_per_account.pop(account)
  266. if isinstance(v, Exception):
  267. raise v
  268. return v
  269. mockGetAccountDetails.side_effect = GetAccountDetailsMock
  270. actual = git_cl.gerrit_util.ValidAccounts(
  271. 'host', ['u1', 'u2', 'u3'], max_threads=1)
  272. self.assertEqual(actual, {
  273. 'u2': {
  274. '_account_id': 123124,
  275. 'avatars': [],
  276. 'email': 'u2@example.com',
  277. 'name': 'User Number 2',
  278. 'status': 'OOO',
  279. },
  280. })
  281. class TestParseIssueURL(unittest.TestCase):
  282. def _test(self, arg, issue=None, patchset=None, hostname=None, fail=False):
  283. parsed = git_cl.ParseIssueNumberArgument(arg)
  284. self.assertIsNotNone(parsed)
  285. if fail:
  286. self.assertFalse(parsed.valid)
  287. return
  288. self.assertTrue(parsed.valid)
  289. self.assertEqual(parsed.issue, issue)
  290. self.assertEqual(parsed.patchset, patchset)
  291. self.assertEqual(parsed.hostname, hostname)
  292. def test_basic(self):
  293. self._test('123', 123)
  294. self._test('', fail=True)
  295. self._test('abc', fail=True)
  296. self._test('123/1', fail=True)
  297. self._test('123a', fail=True)
  298. self._test('ssh://chrome-review.source.com/#/c/123/4/', fail=True)
  299. self._test('ssh://chrome-review.source.com/c/123/1/', fail=True)
  300. def test_gerrit_url(self):
  301. self._test('https://codereview.source.com/123', 123, None,
  302. 'codereview.source.com')
  303. self._test('http://chrome-review.source.com/c/123', 123, None,
  304. 'chrome-review.source.com')
  305. self._test('https://chrome-review.source.com/c/123/', 123, None,
  306. 'chrome-review.source.com')
  307. self._test('https://chrome-review.source.com/c/123/4', 123, 4,
  308. 'chrome-review.source.com')
  309. self._test('https://chrome-review.source.com/#/c/123/4', 123, 4,
  310. 'chrome-review.source.com')
  311. self._test('https://chrome-review.source.com/c/123/4', 123, 4,
  312. 'chrome-review.source.com')
  313. self._test('https://chrome-review.source.com/123', 123, None,
  314. 'chrome-review.source.com')
  315. self._test('https://chrome-review.source.com/123/4', 123, 4,
  316. 'chrome-review.source.com')
  317. self._test('https://chrome-review.source.com/bad/123/4', fail=True)
  318. self._test('https://chrome-review.source.com/c/123/1/whatisthis', fail=True)
  319. self._test('https://chrome-review.source.com/c/abc/', fail=True)
  320. def test_short_urls(self):
  321. self._test('https://crrev.com/c/2151934', 2151934, None,
  322. 'chromium-review.googlesource.com')
  323. class GitCookiesCheckerTest(unittest.TestCase):
  324. def setUp(self):
  325. super(GitCookiesCheckerTest, self).setUp()
  326. self.c = git_cl._GitCookiesChecker()
  327. self.c._all_hosts = []
  328. mock.patch('sys.stdout', StringIO()).start()
  329. self.addCleanup(mock.patch.stopall)
  330. def mock_hosts_creds(self, subhost_identity_pairs):
  331. def ensure_googlesource(h):
  332. if not h.endswith(self.c._GOOGLESOURCE):
  333. assert not h.endswith('.')
  334. return h + '.' + self.c._GOOGLESOURCE
  335. return h
  336. self.c._all_hosts = [(ensure_googlesource(h), i, '.gitcookies')
  337. for h, i in subhost_identity_pairs]
  338. def test_identity_parsing(self):
  339. self.assertEqual(self.c._parse_identity('ldap.google.com'),
  340. ('ldap', 'google.com'))
  341. self.assertEqual(self.c._parse_identity('git-ldap.example.com'),
  342. ('ldap', 'example.com'))
  343. # Specical case because we know there are no subdomains in chromium.org.
  344. self.assertEqual(self.c._parse_identity('git-note.period.chromium.org'),
  345. ('note.period', 'chromium.org'))
  346. # Pathological: ".period." can be either username OR domain, more likely
  347. # domain.
  348. self.assertEqual(self.c._parse_identity('git-note.period.example.com'),
  349. ('note', 'period.example.com'))
  350. def test_analysis_nothing(self):
  351. self.c._all_hosts = []
  352. self.assertFalse(self.c.has_generic_host())
  353. self.assertEqual(set(), self.c.get_conflicting_hosts())
  354. self.assertEqual(set(), self.c.get_duplicated_hosts())
  355. self.assertEqual(set(), self.c.get_partially_configured_hosts())
  356. self.assertEqual(set(), self.c.get_hosts_with_wrong_identities())
  357. def test_analysis(self):
  358. self.mock_hosts_creds([
  359. ('.googlesource.com', 'git-example.chromium.org'),
  360. ('chromium', 'git-example.google.com'),
  361. ('chromium-review', 'git-example.google.com'),
  362. ('chrome-internal', 'git-example.chromium.org'),
  363. ('chrome-internal-review', 'git-example.chromium.org'),
  364. ('conflict', 'git-example.google.com'),
  365. ('conflict-review', 'git-example.chromium.org'),
  366. ('dup', 'git-example.google.com'),
  367. ('dup', 'git-example.google.com'),
  368. ('dup-review', 'git-example.google.com'),
  369. ('partial', 'git-example.google.com'),
  370. ('gpartial-review', 'git-example.google.com'),
  371. ])
  372. self.assertTrue(self.c.has_generic_host())
  373. self.assertEqual(set(['conflict.googlesource.com']),
  374. self.c.get_conflicting_hosts())
  375. self.assertEqual(set(['dup.googlesource.com']),
  376. self.c.get_duplicated_hosts())
  377. self.assertEqual(set(['partial.googlesource.com',
  378. 'gpartial-review.googlesource.com']),
  379. self.c.get_partially_configured_hosts())
  380. self.assertEqual(set(['chromium.googlesource.com',
  381. 'chrome-internal.googlesource.com']),
  382. self.c.get_hosts_with_wrong_identities())
  383. def test_report_no_problems(self):
  384. self.test_analysis_nothing()
  385. self.assertFalse(self.c.find_and_report_problems())
  386. self.assertEqual(sys.stdout.getvalue(), '')
  387. @mock.patch(
  388. 'git_cl.gerrit_util.CookiesAuthenticator.get_gitcookies_path',
  389. return_value=os.path.join('~', '.gitcookies'))
  390. def test_report(self, *_mocks):
  391. self.test_analysis()
  392. self.assertTrue(self.c.find_and_report_problems())
  393. with open(os.path.join(os.path.dirname(__file__),
  394. 'git_cl_creds_check_report.txt')) as f:
  395. expected = f.read() % {
  396. 'sep': os.sep,
  397. }
  398. def by_line(text):
  399. return [l.rstrip() for l in text.rstrip().splitlines()]
  400. self.maxDiff = 10000 # pylint: disable=attribute-defined-outside-init
  401. self.assertEqual(by_line(sys.stdout.getvalue().strip()), by_line(expected))
  402. class TestGitCl(unittest.TestCase):
  403. def setUp(self):
  404. super(TestGitCl, self).setUp()
  405. self.calls = []
  406. self._calls_done = []
  407. self.failed = False
  408. mock.patch('sys.stdout', StringIO()).start()
  409. mock.patch(
  410. 'git_cl.time_time',
  411. lambda: self._mocked_call('time.time')).start()
  412. mock.patch(
  413. 'git_cl.metrics.collector.add_repeated',
  414. lambda *a: self._mocked_call('add_repeated', *a)).start()
  415. mock.patch('subprocess2.call', self._mocked_call).start()
  416. mock.patch('subprocess2.check_call', self._mocked_call).start()
  417. mock.patch('subprocess2.check_output', self._mocked_call).start()
  418. mock.patch(
  419. 'subprocess2.communicate',
  420. lambda *a, **_k: ([self._mocked_call(*a), ''], 0)).start()
  421. mock.patch(
  422. 'git_cl.gclient_utils.CheckCallAndFilter',
  423. self._mocked_call).start()
  424. mock.patch('git_common.is_dirty_git_tree', lambda x: False).start()
  425. mock.patch(
  426. 'git_common.get_or_create_merge_base',
  427. lambda *a: self._mocked_call('get_or_create_merge_base', *a)).start()
  428. mock.patch('git_cl.FindCodereviewSettingsFile', return_value='').start()
  429. mock.patch(
  430. 'git_cl.SaveDescriptionBackup',
  431. lambda _: self._mocked_call('SaveDescriptionBackup')).start()
  432. mock.patch(
  433. 'git_cl.write_json',
  434. lambda *a: self._mocked_call('write_json', *a)).start()
  435. mock.patch(
  436. 'git_cl.Changelist.RunHook',
  437. return_value={'more_cc': ['test-more-cc@chromium.org']}).start()
  438. mock.patch('git_cl.watchlists.Watchlists', WatchlistsMock).start()
  439. mock.patch('git_cl.auth.Authenticator', AuthenticatorMock).start()
  440. mock.patch('gerrit_util.GetChangeDetail').start()
  441. mock.patch(
  442. 'git_cl.gerrit_util.GetChangeComments',
  443. lambda *a: self._mocked_call('GetChangeComments', *a)).start()
  444. mock.patch(
  445. 'git_cl.gerrit_util.GetChangeRobotComments',
  446. lambda *a: self._mocked_call('GetChangeRobotComments', *a)).start()
  447. mock.patch(
  448. 'git_cl.gerrit_util.AddReviewers',
  449. lambda *a: self._mocked_call('AddReviewers', *a)).start()
  450. mock.patch(
  451. 'git_cl.gerrit_util.SetReview',
  452. lambda h, i, msg=None, labels=None, notify=None, ready=None: (
  453. self._mocked_call(
  454. 'SetReview', h, i, msg, labels, notify, ready))).start()
  455. mock.patch(
  456. 'git_cl.gerrit_util.LuciContextAuthenticator.is_luci',
  457. return_value=False).start()
  458. mock.patch(
  459. 'git_cl.gerrit_util.GceAuthenticator.is_gce',
  460. return_value=False).start()
  461. mock.patch(
  462. 'git_cl.gerrit_util.ValidAccounts',
  463. lambda *a: self._mocked_call('ValidAccounts', *a)).start()
  464. mock.patch('sys.exit', side_effect=SystemExitMock).start()
  465. mock.patch('git_cl.Settings.GetRoot', return_value='').start()
  466. self.mockGit = GitMocks()
  467. mock.patch('scm.GIT.GetBranchRef', self.mockGit.GetBranchRef).start()
  468. mock.patch('scm.GIT.GetConfig', self.mockGit.GetConfig).start()
  469. mock.patch('scm.GIT.ResolveCommit', return_value='hash').start()
  470. mock.patch('scm.GIT.IsValidRevision', return_value=True).start()
  471. mock.patch('scm.GIT.SetConfig', self.mockGit.SetConfig).start()
  472. mock.patch(
  473. 'git_new_branch.create_new_branch', self.mockGit.NewBranch).start()
  474. mock.patch(
  475. 'scm.GIT.FetchUpstreamTuple',
  476. return_value=('origin', 'refs/heads/master')).start()
  477. mock.patch(
  478. 'scm.GIT.CaptureStatus', return_value=[('M', 'foo.txt')]).start()
  479. # It's important to reset settings to not have inter-tests interference.
  480. git_cl.settings = None
  481. self.addCleanup(mock.patch.stopall)
  482. def tearDown(self):
  483. try:
  484. if not self.failed:
  485. self.assertEqual([], self.calls)
  486. except AssertionError:
  487. calls = ''.join(' %s\n' % str(call) for call in self.calls[:5])
  488. if len(self.calls) > 5:
  489. calls += ' ...\n'
  490. self.fail(
  491. '\n'
  492. 'There are un-consumed calls after this test has finished:\n' +
  493. calls)
  494. finally:
  495. super(TestGitCl, self).tearDown()
  496. def _mocked_call(self, *args, **_kwargs):
  497. self.assertTrue(
  498. self.calls,
  499. '@%d Expected: <Missing> Actual: %r' % (len(self._calls_done), args))
  500. top = self.calls.pop(0)
  501. expected_args, result = top
  502. # Also logs otherwise it could get caught in a try/finally and be hard to
  503. # diagnose.
  504. if expected_args != args:
  505. N = 5
  506. prior_calls = '\n '.join(
  507. '@%d: %r' % (len(self._calls_done) - N + i, c[0])
  508. for i, c in enumerate(self._calls_done[-N:]))
  509. following_calls = '\n '.join(
  510. '@%d: %r' % (len(self._calls_done) + i + 1, c[0])
  511. for i, c in enumerate(self.calls[:N]))
  512. extended_msg = (
  513. 'A few prior calls:\n %s\n\n'
  514. 'This (expected):\n @%d: %r\n'
  515. 'This (actual):\n @%d: %r\n\n'
  516. 'A few following expected calls:\n %s' %
  517. (prior_calls, len(self._calls_done), expected_args,
  518. len(self._calls_done), args, following_calls))
  519. self.failed = True
  520. self.fail('@%d\n'
  521. ' Expected: %r\n'
  522. ' Actual: %r\n'
  523. '\n'
  524. '%s' % (
  525. len(self._calls_done), expected_args, args, extended_msg))
  526. self._calls_done.append(top)
  527. if isinstance(result, Exception):
  528. raise result
  529. # stdout from git commands is supposed to be a bytestream. Convert it here
  530. # instead of converting all test output in this file to bytes.
  531. if args[0][0] == 'git' and not isinstance(result, bytes):
  532. result = result.encode('utf-8')
  533. return result
  534. @mock.patch('sys.stdin', StringIO('blah\nye\n'))
  535. @mock.patch('sys.stdout', StringIO())
  536. def test_ask_for_explicit_yes_true(self):
  537. self.assertTrue(git_cl.ask_for_explicit_yes('prompt'))
  538. self.assertEqual(
  539. 'prompt [Yes/No]: Please, type yes or no: ',
  540. sys.stdout.getvalue())
  541. def test_LoadCodereviewSettingsFromFile_gerrit(self):
  542. codereview_file = StringIO('GERRIT_HOST: true')
  543. self.calls = [
  544. ((['git', 'config', '--unset-all', 'rietveld.cc'],), CERR1),
  545. ((['git', 'config', '--unset-all', 'rietveld.tree-status-url'],), CERR1),
  546. ((['git', 'config', '--unset-all', 'rietveld.viewvc-url'],), CERR1),
  547. ((['git', 'config', '--unset-all', 'rietveld.bug-prefix'],), CERR1),
  548. ((['git', 'config', '--unset-all', 'rietveld.cpplint-regex'],), CERR1),
  549. ((['git', 'config', '--unset-all', 'rietveld.cpplint-ignore-regex'],),
  550. CERR1),
  551. ((['git', 'config', '--unset-all', 'rietveld.run-post-upload-hook'],),
  552. CERR1),
  553. ((['git', 'config', '--unset-all', 'rietveld.format-full-by-default'],),
  554. CERR1),
  555. ((['git', 'config', 'gerrit.host', 'true'],), ''),
  556. ]
  557. self.assertIsNone(git_cl.LoadCodereviewSettingsFromFile(codereview_file))
  558. @classmethod
  559. def _gerrit_base_calls(cls, issue=None, fetched_description=None,
  560. fetched_status=None, other_cl_owner=None,
  561. custom_cl_base=None, short_hostname='chromium',
  562. change_id=None):
  563. calls = []
  564. if custom_cl_base:
  565. ancestor_revision = custom_cl_base
  566. else:
  567. # Determine ancestor_revision to be merge base.
  568. ancestor_revision = 'fake_ancestor_sha'
  569. calls += [
  570. (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
  571. ancestor_revision),
  572. ]
  573. if issue:
  574. gerrit_util.GetChangeDetail.return_value = {
  575. 'owner': {'email': (other_cl_owner or 'owner@example.com')},
  576. 'change_id': (change_id or '123456789'),
  577. 'current_revision': 'sha1_of_current_revision',
  578. 'revisions': {'sha1_of_current_revision': {
  579. 'commit': {'message': fetched_description},
  580. }},
  581. 'status': fetched_status or 'NEW',
  582. }
  583. if fetched_status == 'ABANDONED':
  584. return calls
  585. if other_cl_owner:
  586. calls += [
  587. (('ask_for_data', 'Press Enter to upload, or Ctrl+C to abort'), ''),
  588. ]
  589. calls += [
  590. ((['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] +
  591. ([custom_cl_base] if custom_cl_base else
  592. [ancestor_revision, 'HEAD']),),
  593. '+dat'),
  594. ]
  595. return calls
  596. def _gerrit_upload_calls(self, description, reviewers, squash,
  597. squash_mode='default',
  598. title=None, notify=False,
  599. post_amend_description=None, issue=None, cc=None,
  600. custom_cl_base=None, tbr=None,
  601. short_hostname='chromium',
  602. labels=None, change_id=None,
  603. final_description=None, gitcookies_exists=True,
  604. force=False, edit_description=None):
  605. if post_amend_description is None:
  606. post_amend_description = description
  607. cc = cc or []
  608. calls = []
  609. if squash_mode in ('override_squash', 'override_nosquash'):
  610. self.mockGit.config['gerrit.override-squash-uploads'] = (
  611. 'true' if squash_mode == 'override_squash' else 'false')
  612. if not git_footers.get_footer_change_id(description) and not squash:
  613. calls += [
  614. (('DownloadGerritHook', False), ''),
  615. ]
  616. if squash:
  617. if not issue and not force:
  618. calls += [
  619. ((['RunEditor'],), description),
  620. ]
  621. # user wants to edit description
  622. if edit_description:
  623. calls += [
  624. ((['RunEditor'],), edit_description),
  625. ]
  626. ref_to_push = 'abcdef0123456789'
  627. if custom_cl_base is None:
  628. calls += [
  629. (('get_or_create_merge_base', 'master', 'refs/remotes/origin/master'),
  630. 'origin/master'),
  631. ]
  632. parent = 'origin/master'
  633. else:
  634. calls += [
  635. ((['git', 'merge-base', '--is-ancestor', custom_cl_base,
  636. 'refs/remotes/origin/master'],),
  637. callError(1)), # Means not ancenstor.
  638. (('ask_for_data',
  639. 'Do you take responsibility for cleaning up potential mess '
  640. 'resulting from proceeding with upload? Press Enter to upload, '
  641. 'or Ctrl+C to abort'), ''),
  642. ]
  643. parent = custom_cl_base
  644. calls += [
  645. ((['git', 'rev-parse', 'HEAD:'],), # `HEAD:` means HEAD's tree hash.
  646. '0123456789abcdef'),
  647. ((['FileWrite', '/tmp/fake-temp1', description],), None),
  648. ((['git', 'commit-tree', '0123456789abcdef', '-p', parent,
  649. '-F', '/tmp/fake-temp1'],),
  650. ref_to_push),
  651. ]
  652. else:
  653. ref_to_push = 'HEAD'
  654. parent = 'origin/refs/heads/master'
  655. calls += [
  656. (('SaveDescriptionBackup',), None),
  657. ((['git', 'rev-list', parent + '..' + ref_to_push],),'1hashPerLine\n'),
  658. ]
  659. metrics_arguments = []
  660. if notify:
  661. ref_suffix = '%ready,notify=ALL'
  662. metrics_arguments += ['ready', 'notify=ALL']
  663. else:
  664. if not issue and squash:
  665. ref_suffix = '%wip'
  666. metrics_arguments.append('wip')
  667. else:
  668. ref_suffix = '%notify=NONE'
  669. metrics_arguments.append('notify=NONE')
  670. # If issue is given, then description is fetched from Gerrit instead.
  671. if issue is None:
  672. if squash:
  673. title = 'Initial upload'
  674. else:
  675. if not title:
  676. calls += [
  677. ((['git', 'show', '-s', '--format=%s', 'HEAD'],), ''),
  678. (('ask_for_data', 'Title for patchset []: '), 'User input'),
  679. ]
  680. title = 'User input'
  681. if title:
  682. ref_suffix += ',m=' + gerrit_util.PercentEncodeForGitRef(title)
  683. metrics_arguments.append('m')
  684. if short_hostname == 'chromium':
  685. # All reviewers and ccs get into ref_suffix.
  686. for r in sorted(reviewers):
  687. ref_suffix += ',r=%s' % r
  688. metrics_arguments.append('r')
  689. if issue is None:
  690. cc += ['test-more-cc@chromium.org', 'joe@example.com']
  691. for c in sorted(cc):
  692. ref_suffix += ',cc=%s' % c
  693. metrics_arguments.append('cc')
  694. reviewers, cc = [], []
  695. else:
  696. # TODO(crbug/877717): remove this case.
  697. calls += [
  698. (('ValidAccounts', '%s-review.googlesource.com' % short_hostname,
  699. sorted(reviewers) + ['joe@example.com',
  700. 'test-more-cc@chromium.org'] + cc),
  701. {
  702. e: {'email': e}
  703. for e in (reviewers + ['joe@example.com'] + cc)
  704. })
  705. ]
  706. for r in sorted(reviewers):
  707. if r != 'bad-account-or-email':
  708. ref_suffix += ',r=%s' % r
  709. metrics_arguments.append('r')
  710. reviewers.remove(r)
  711. if issue is None:
  712. cc += ['joe@example.com']
  713. for c in sorted(cc):
  714. ref_suffix += ',cc=%s' % c
  715. metrics_arguments.append('cc')
  716. if c in cc:
  717. cc.remove(c)
  718. for k, v in sorted((labels or {}).items()):
  719. ref_suffix += ',l=%s+%d' % (k, v)
  720. metrics_arguments.append('l=%s+%d' % (k, v))
  721. if tbr:
  722. calls += [
  723. (('GetCodeReviewTbrScore',
  724. '%s-review.googlesource.com' % short_hostname,
  725. 'my/repo'),
  726. 2,),
  727. ]
  728. calls += [
  729. (('time.time',), 1000,),
  730. ((['git', 'push',
  731. 'https://%s.googlesource.com/my/repo' % short_hostname,
  732. ref_to_push + ':refs/for/refs/heads/master' + ref_suffix],),
  733. (('remote:\n'
  734. 'remote: Processing changes: (\)\n'
  735. 'remote: Processing changes: (|)\n'
  736. 'remote: Processing changes: (/)\n'
  737. 'remote: Processing changes: (-)\n'
  738. 'remote: Processing changes: new: 1 (/)\n'
  739. 'remote: Processing changes: new: 1, done\n'
  740. 'remote:\n'
  741. 'remote: New Changes:\n'
  742. 'remote: https://%s-review.googlesource.com/#/c/my/repo/+/123456'
  743. ' XXX\n'
  744. 'remote:\n'
  745. 'To https://%s.googlesource.com/my/repo\n'
  746. ' * [new branch] hhhh -> refs/for/refs/heads/master\n'
  747. ) % (short_hostname, short_hostname)),),
  748. (('time.time',), 2000,),
  749. (('add_repeated',
  750. 'sub_commands',
  751. {
  752. 'execution_time': 1000,
  753. 'command': 'git push',
  754. 'exit_code': 0,
  755. 'arguments': sorted(metrics_arguments),
  756. }),
  757. None,),
  758. ]
  759. final_description = final_description or post_amend_description.strip()
  760. trace_name = os.path.join('TRACES_DIR', '20170316T200041.000000')
  761. # Trace-related calls
  762. calls += [
  763. # Write a description with context for the current trace.
  764. (
  765. ([
  766. 'FileWrite', trace_name + '-README',
  767. '%(date)s\n'
  768. '%(short_hostname)s-review.googlesource.com\n'
  769. '%(change_id)s\n'
  770. '%(title)s\n'
  771. '%(description)s\n'
  772. '1000\n'
  773. '0\n'
  774. '%(trace_name)s' % {
  775. 'date': '2017-03-16T20:00:41.000000',
  776. 'short_hostname': short_hostname,
  777. 'change_id': change_id,
  778. 'description': final_description,
  779. 'title': title or '<untitled>',
  780. 'trace_name': trace_name,
  781. }
  782. ], ),
  783. None,
  784. ),
  785. # Read traces and shorten git hashes.
  786. (
  787. (['os.path.isfile',
  788. os.path.join('TEMP_DIR', 'trace-packet')], ),
  789. True,
  790. ),
  791. (
  792. (['FileRead', os.path.join('TEMP_DIR', 'trace-packet')], ),
  793. ('git-hash: 0123456789012345678901234567890123456789\n'
  794. 'git-hash: abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n'),
  795. ),
  796. (
  797. ([
  798. 'FileWrite',
  799. os.path.join('TEMP_DIR', 'trace-packet'), 'git-hash: 012345\n'
  800. 'git-hash: abcdea\n'
  801. ], ),
  802. None,
  803. ),
  804. # Make zip file for the git traces.
  805. (
  806. (['make_archive', trace_name + '-traces', 'zip', 'TEMP_DIR'], ),
  807. None,
  808. ),
  809. # Collect git config and gitcookies.
  810. (
  811. (['git', 'config', '-l'], ),
  812. 'git-config-output',
  813. ),
  814. (
  815. ([
  816. 'FileWrite',
  817. os.path.join('TEMP_DIR', 'git-config'), 'git-config-output'
  818. ], ),
  819. None,
  820. ),
  821. (
  822. (['os.path.isfile',
  823. os.path.join('~', '.gitcookies')], ),
  824. gitcookies_exists,
  825. ),
  826. ]
  827. if gitcookies_exists:
  828. calls += [
  829. (
  830. (['FileRead', os.path.join('~', '.gitcookies')], ),
  831. 'gitcookies 1/SECRET',
  832. ),
  833. (
  834. ([
  835. 'FileWrite',
  836. os.path.join('TEMP_DIR', 'gitcookies'), 'gitcookies REDACTED'
  837. ], ),
  838. None,
  839. ),
  840. ]
  841. calls += [
  842. # Make zip file for the git config and gitcookies.
  843. (
  844. (['make_archive', trace_name + '-git-info', 'zip', 'TEMP_DIR'], ),
  845. None,
  846. ),
  847. ]
  848. # TODO(crbug/877717): this should never be used.
  849. if squash and short_hostname != 'chromium':
  850. calls += [
  851. (('AddReviewers',
  852. 'chromium-review.googlesource.com', 'my%2Frepo~123456',
  853. sorted(reviewers),
  854. cc + ['test-more-cc@chromium.org'],
  855. notify),
  856. ''),
  857. ]
  858. return calls
  859. def _run_gerrit_upload_test(
  860. self,
  861. upload_args,
  862. description,
  863. reviewers=None,
  864. squash=True,
  865. squash_mode=None,
  866. title=None,
  867. notify=False,
  868. post_amend_description=None,
  869. issue=None,
  870. cc=None,
  871. fetched_status=None,
  872. other_cl_owner=None,
  873. custom_cl_base=None,
  874. tbr=None,
  875. short_hostname='chromium',
  876. labels=None,
  877. change_id=None,
  878. final_description=None,
  879. gitcookies_exists=True,
  880. force=False,
  881. log_description=None,
  882. edit_description=None,
  883. fetched_description=None):
  884. """Generic gerrit upload test framework."""
  885. if squash_mode is None:
  886. if '--no-squash' in upload_args:
  887. squash_mode = 'nosquash'
  888. elif '--squash' in upload_args:
  889. squash_mode = 'squash'
  890. else:
  891. squash_mode = 'default'
  892. reviewers = reviewers or []
  893. cc = cc or []
  894. mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
  895. CookiesAuthenticatorMockFactory(
  896. same_auth=('git-owner.example.com', '', 'pass'))).start()
  897. mock.patch('git_cl.Changelist._GerritCommitMsgHookCheck',
  898. lambda _, offer_removal: None).start()
  899. mock.patch('git_cl.gclient_utils.RunEditor',
  900. lambda *_, **__: self._mocked_call(['RunEditor'])).start()
  901. mock.patch('git_cl.DownloadGerritHook', lambda force: self._mocked_call(
  902. 'DownloadGerritHook', force)).start()
  903. mock.patch('git_cl.gclient_utils.FileRead',
  904. lambda path: self._mocked_call(['FileRead', path])).start()
  905. mock.patch('git_cl.gclient_utils.FileWrite',
  906. lambda path, contents: self._mocked_call(
  907. ['FileWrite', path, contents])).start()
  908. mock.patch('git_cl.datetime_now',
  909. lambda: datetime.datetime(2017, 3, 16, 20, 0, 41, 0)).start()
  910. mock.patch('git_cl.tempfile.mkdtemp', lambda: 'TEMP_DIR').start()
  911. mock.patch('git_cl.TRACES_DIR', 'TRACES_DIR').start()
  912. mock.patch('git_cl.TRACES_README_FORMAT',
  913. '%(now)s\n'
  914. '%(gerrit_host)s\n'
  915. '%(change_id)s\n'
  916. '%(title)s\n'
  917. '%(description)s\n'
  918. '%(execution_time)s\n'
  919. '%(exit_code)s\n'
  920. '%(trace_name)s').start()
  921. mock.patch('git_cl.shutil.make_archive',
  922. lambda *args: self._mocked_call(['make_archive'] +
  923. list(args))).start()
  924. mock.patch('os.path.isfile',
  925. lambda path: self._mocked_call(['os.path.isfile', path])).start()
  926. mock.patch(
  927. 'git_cl._create_description_from_log',
  928. return_value=log_description or description).start()
  929. mock.patch(
  930. 'git_cl.Changelist._AddChangeIdToCommitMessage',
  931. return_value=post_amend_description or description).start()
  932. mock.patch(
  933. 'git_cl.GenerateGerritChangeId', return_value=change_id).start()
  934. mock.patch(
  935. 'gclient_utils.AskForData',
  936. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  937. self.mockGit.config['gerrit.host'] = 'true'
  938. self.mockGit.config['branch.master.gerritissue'] = (
  939. str(issue) if issue else None)
  940. self.mockGit.config['remote.origin.url'] = (
  941. 'https://%s.googlesource.com/my/repo' % short_hostname)
  942. self.mockGit.config['user.email'] = 'me@example.com'
  943. self.calls = self._gerrit_base_calls(
  944. issue=issue,
  945. fetched_description=fetched_description or description,
  946. fetched_status=fetched_status,
  947. other_cl_owner=other_cl_owner,
  948. custom_cl_base=custom_cl_base,
  949. short_hostname=short_hostname,
  950. change_id=change_id)
  951. if fetched_status != 'ABANDONED':
  952. mock.patch(
  953. 'gclient_utils.temporary_file', TemporaryFileMock()).start()
  954. mock.patch('os.remove', return_value=True).start()
  955. self.calls += self._gerrit_upload_calls(
  956. description, reviewers, squash,
  957. squash_mode=squash_mode,
  958. title=title, notify=notify,
  959. post_amend_description=post_amend_description,
  960. issue=issue, cc=cc,
  961. custom_cl_base=custom_cl_base, tbr=tbr,
  962. short_hostname=short_hostname,
  963. labels=labels,
  964. change_id=change_id,
  965. final_description=final_description,
  966. gitcookies_exists=gitcookies_exists,
  967. force=force,
  968. edit_description=edit_description)
  969. # Uncomment when debugging.
  970. # print('\n'.join(map(lambda x: '%2i: %s' % x, enumerate(self.calls))))
  971. git_cl.main(['upload'] + upload_args)
  972. if squash:
  973. self.assertIssueAndPatchset(patchset=None)
  974. self.assertEqual(
  975. 'abcdef0123456789',
  976. scm.GIT.GetBranchConfig('', 'master', 'gerritsquashhash'))
  977. def test_gerrit_upload_traces_no_gitcookies(self):
  978. self._run_gerrit_upload_test(
  979. ['--no-squash'],
  980. 'desc ✔\n\nBUG=\n',
  981. [],
  982. squash=False,
  983. post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  984. change_id='Ixxx',
  985. gitcookies_exists=False)
  986. def test_gerrit_upload_without_change_id(self):
  987. self._run_gerrit_upload_test(
  988. [],
  989. 'desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  990. [],
  991. change_id='Ixxx')
  992. def test_gerrit_upload_without_change_id_nosquash(self):
  993. self._run_gerrit_upload_test(
  994. ['--no-squash'],
  995. 'desc ✔\n\nBUG=\n',
  996. [],
  997. squash=False,
  998. post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  999. change_id='Ixxx')
  1000. def test_gerrit_upload_without_change_id_override_nosquash(self):
  1001. self._run_gerrit_upload_test(
  1002. [],
  1003. 'desc ✔\n\nBUG=\n',
  1004. [],
  1005. squash=False,
  1006. squash_mode='override_nosquash',
  1007. post_amend_description='desc ✔\n\nBUG=\n\nChange-Id: Ixxx',
  1008. change_id='Ixxx')
  1009. def test_gerrit_no_reviewer(self):
  1010. self._run_gerrit_upload_test(
  1011. [],
  1012. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
  1013. [],
  1014. squash=False,
  1015. squash_mode='override_nosquash',
  1016. change_id='I123456789')
  1017. def test_gerrit_no_reviewer_non_chromium_host(self):
  1018. # TODO(crbug/877717): remove this test case.
  1019. self._run_gerrit_upload_test(
  1020. [],
  1021. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789\n',
  1022. [],
  1023. squash=False,
  1024. squash_mode='override_nosquash',
  1025. short_hostname='other',
  1026. change_id='I123456789')
  1027. def test_gerrit_patchset_title_special_chars_nosquash(self):
  1028. self._run_gerrit_upload_test(
  1029. ['-f', '-t', 'We\'ll escape ^_ ^ special chars...@{u}'],
  1030. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
  1031. squash=False,
  1032. squash_mode='override_nosquash',
  1033. change_id='I123456789',
  1034. title='We\'ll escape ^_ ^ special chars...@{u}')
  1035. def test_gerrit_reviewers_cmd_line(self):
  1036. self._run_gerrit_upload_test(
  1037. ['-r', 'foo@example.com', '--send-mail'],
  1038. 'desc ✔\n\nBUG=\n\nChange-Id: I123456789',
  1039. reviewers=['foo@example.com'],
  1040. squash=False,
  1041. squash_mode='override_nosquash',
  1042. notify=True,
  1043. change_id='I123456789',
  1044. final_description=(
  1045. 'desc ✔\n\nBUG=\nR=foo@example.com\n\nChange-Id: I123456789'))
  1046. def test_gerrit_upload_force_sets_bug(self):
  1047. self._run_gerrit_upload_test(
  1048. ['-b', '10000', '-f'],
  1049. u'desc=\n\nBug: 10000\nChange-Id: Ixxx',
  1050. [],
  1051. force=True,
  1052. fetched_description='desc=\n\nChange-Id: Ixxx',
  1053. change_id='Ixxx')
  1054. def test_gerrit_upload_corrects_wrong_change_id(self):
  1055. self._run_gerrit_upload_test(
  1056. ['-b', '10000', '-m', 'Title', '--edit-description'],
  1057. u'desc=\n\nBug: 10000\nChange-Id: Ixxxx',
  1058. [],
  1059. issue='123456',
  1060. edit_description='desc=\n\nBug: 10000\nChange-Id: Izzzz',
  1061. fetched_description='desc=\n\nChange-Id: Ixxxx',
  1062. title='Title',
  1063. change_id='Ixxxx')
  1064. def test_gerrit_upload_force_sets_fixed(self):
  1065. self._run_gerrit_upload_test(
  1066. ['-x', '10000', '-f'],
  1067. u'desc=\n\nFixed: 10000\nChange-Id: Ixxx',
  1068. [],
  1069. force=True,
  1070. fetched_description='desc=\n\nChange-Id: Ixxx',
  1071. change_id='Ixxx')
  1072. def test_gerrit_reviewer_multiple(self):
  1073. mock.patch('git_cl.gerrit_util.GetCodeReviewTbrScore',
  1074. lambda *a: self._mocked_call('GetCodeReviewTbrScore', *a)).start()
  1075. self._run_gerrit_upload_test(
  1076. [],
  1077. 'desc ✔\nTBR=reviewer@example.com\nBUG=\nR=another@example.com\n'
  1078. 'CC=more@example.com,people@example.com\n\n'
  1079. 'Change-Id: 123456789',
  1080. ['reviewer@example.com', 'another@example.com'],
  1081. cc=['more@example.com', 'people@example.com'],
  1082. tbr='reviewer@example.com',
  1083. labels={'Code-Review': 2},
  1084. change_id='123456789')
  1085. def test_gerrit_upload_squash_first_is_default(self):
  1086. self._run_gerrit_upload_test(
  1087. [],
  1088. 'desc ✔\nBUG=\n\nChange-Id: 123456789',
  1089. [],
  1090. change_id='123456789')
  1091. def test_gerrit_upload_squash_first(self):
  1092. self._run_gerrit_upload_test(
  1093. ['--squash'],
  1094. 'desc ✔\nBUG=\n\nChange-Id: 123456789',
  1095. [],
  1096. squash=True,
  1097. change_id='123456789')
  1098. def test_gerrit_upload_squash_first_title(self):
  1099. self._run_gerrit_upload_test(
  1100. ['-f', '-t', 'title'],
  1101. 'title\n\ndesc\n\nChange-Id: 123456789',
  1102. [],
  1103. force=True,
  1104. squash=True,
  1105. log_description='desc',
  1106. change_id='123456789')
  1107. def test_gerrit_upload_squash_first_with_labels(self):
  1108. self._run_gerrit_upload_test(
  1109. ['--squash', '--cq-dry-run', '--enable-auto-submit'],
  1110. 'desc ✔\nBUG=\n\nChange-Id: 123456789',
  1111. [],
  1112. squash=True,
  1113. labels={'Commit-Queue': 1, 'Auto-Submit': 1},
  1114. change_id='123456789')
  1115. def test_gerrit_upload_squash_first_against_rev(self):
  1116. custom_cl_base = 'custom_cl_base_rev_or_branch'
  1117. self._run_gerrit_upload_test(
  1118. ['--squash', custom_cl_base],
  1119. 'desc ✔\nBUG=\n\nChange-Id: 123456789',
  1120. [],
  1121. squash=True,
  1122. custom_cl_base=custom_cl_base,
  1123. change_id='123456789')
  1124. self.assertIn(
  1125. 'If you proceed with upload, more than 1 CL may be created by Gerrit',
  1126. sys.stdout.getvalue())
  1127. def test_gerrit_upload_squash_reupload(self):
  1128. description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
  1129. self._run_gerrit_upload_test(
  1130. ['--squash'],
  1131. description,
  1132. [],
  1133. squash=True,
  1134. issue=123456,
  1135. change_id='123456789')
  1136. @mock.patch('sys.stderr', StringIO())
  1137. def test_gerrit_upload_squash_reupload_to_abandoned(self):
  1138. description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
  1139. with self.assertRaises(SystemExitMock):
  1140. self._run_gerrit_upload_test(
  1141. ['--squash'],
  1142. description,
  1143. [],
  1144. squash=True,
  1145. issue=123456,
  1146. fetched_status='ABANDONED',
  1147. change_id='123456789')
  1148. self.assertEqual(
  1149. 'Change https://chromium-review.googlesource.com/123456 has been '
  1150. 'abandoned, new uploads are not allowed\n',
  1151. sys.stderr.getvalue())
  1152. @mock.patch(
  1153. 'gerrit_util.GetAccountDetails',
  1154. return_value={'email': 'yet-another@example.com'})
  1155. def test_gerrit_upload_squash_reupload_to_not_owned(self, _mock):
  1156. description = 'desc ✔\nBUG=\n\nChange-Id: 123456789'
  1157. self._run_gerrit_upload_test(
  1158. ['--squash'],
  1159. description,
  1160. [],
  1161. squash=True,
  1162. issue=123456,
  1163. other_cl_owner='other@example.com',
  1164. change_id='123456789')
  1165. self.assertIn(
  1166. 'WARNING: Change 123456 is owned by other@example.com, but you '
  1167. 'authenticate to Gerrit as yet-another@example.com.\n'
  1168. 'Uploading may fail due to lack of permissions',
  1169. sys.stdout.getvalue())
  1170. def test_upload_change_description_editor(self):
  1171. fetched_description = 'foo\n\nChange-Id: 123456789'
  1172. description = 'bar\n\nChange-Id: 123456789'
  1173. self._run_gerrit_upload_test(
  1174. ['--squash', '--edit-description'],
  1175. description,
  1176. [],
  1177. fetched_description=fetched_description,
  1178. squash=True,
  1179. issue=123456,
  1180. change_id='123456789',
  1181. edit_description=description)
  1182. @mock.patch('git_cl.RunGit')
  1183. @mock.patch('git_cl.CMDupload')
  1184. @mock.patch('sys.stdin', StringIO('\n'))
  1185. @mock.patch('sys.stdout', StringIO())
  1186. def test_upload_branch_deps(self, *_mocks):
  1187. def mock_run_git(*args, **_kwargs):
  1188. if args[0] == ['for-each-ref',
  1189. '--format=%(refname:short) %(upstream:short)',
  1190. 'refs/heads']:
  1191. # Create a local branch dependency tree that looks like this:
  1192. # test1 -> test2 -> test3 -> test4 -> test5
  1193. # -> test3.1
  1194. # test6 -> test0
  1195. branch_deps = [
  1196. 'test2 test1', # test1 -> test2
  1197. 'test3 test2', # test2 -> test3
  1198. 'test3.1 test2', # test2 -> test3.1
  1199. 'test4 test3', # test3 -> test4
  1200. 'test5 test4', # test4 -> test5
  1201. 'test6 test0', # test0 -> test6
  1202. 'test7', # test7
  1203. ]
  1204. return '\n'.join(branch_deps)
  1205. git_cl.RunGit.side_effect = mock_run_git
  1206. git_cl.CMDupload.return_value = 0
  1207. class MockChangelist():
  1208. def __init__(self):
  1209. pass
  1210. def GetBranch(self):
  1211. return 'test1'
  1212. def GetIssue(self):
  1213. return '123'
  1214. def GetPatchset(self):
  1215. return '1001'
  1216. def IsGerrit(self):
  1217. return False
  1218. ret = git_cl.upload_branch_deps(MockChangelist(), [])
  1219. # CMDupload should have been called 5 times because of 5 dependent branches.
  1220. self.assertEqual(5, len(git_cl.CMDupload.mock_calls))
  1221. self.assertIn(
  1222. 'This command will checkout all dependent branches '
  1223. 'and run "git cl upload". Press Enter to continue, '
  1224. 'or Ctrl+C to abort',
  1225. sys.stdout.getvalue())
  1226. self.assertEqual(0, ret)
  1227. def test_gerrit_change_id(self):
  1228. self.calls = [
  1229. ((['git', 'write-tree'], ),
  1230. 'hashtree'),
  1231. ((['git', 'rev-parse', 'HEAD~0'], ),
  1232. 'branch-parent'),
  1233. ((['git', 'var', 'GIT_AUTHOR_IDENT'], ),
  1234. 'A B <a@b.org> 1456848326 +0100'),
  1235. ((['git', 'var', 'GIT_COMMITTER_IDENT'], ),
  1236. 'C D <c@d.org> 1456858326 +0100'),
  1237. ((['git', 'hash-object', '-t', 'commit', '--stdin'], ),
  1238. 'hashchange'),
  1239. ]
  1240. change_id = git_cl.GenerateGerritChangeId('line1\nline2\n')
  1241. self.assertEqual(change_id, 'Ihashchange')
  1242. def test_desecription_append_footer(self):
  1243. for init_desc, footer_line, expected_desc in [
  1244. # Use unique desc first lines for easy test failure identification.
  1245. ('foo', 'R=one', 'foo\n\nR=one'),
  1246. ('foo\n\nR=one', 'BUG=', 'foo\n\nR=one\nBUG='),
  1247. ('foo\n\nR=one', 'Change-Id: Ixx', 'foo\n\nR=one\n\nChange-Id: Ixx'),
  1248. ('foo\n\nChange-Id: Ixx', 'R=one', 'foo\n\nR=one\n\nChange-Id: Ixx'),
  1249. ('foo\n\nR=one\n\nChange-Id: Ixx', 'TBR=two',
  1250. 'foo\n\nR=one\nTBR=two\n\nChange-Id: Ixx'),
  1251. ('foo\n\nR=one\n\nChange-Id: Ixx', 'Foo-Bar: baz',
  1252. 'foo\n\nR=one\n\nChange-Id: Ixx\nFoo-Bar: baz'),
  1253. ('foo\n\nChange-Id: Ixx', 'Foo-Bak: baz',
  1254. 'foo\n\nChange-Id: Ixx\nFoo-Bak: baz'),
  1255. ('foo', 'Change-Id: Ixx', 'foo\n\nChange-Id: Ixx'),
  1256. ]:
  1257. desc = git_cl.ChangeDescription(init_desc)
  1258. desc.append_footer(footer_line)
  1259. self.assertEqual(desc.description, expected_desc)
  1260. def test_update_reviewers(self):
  1261. data = [
  1262. ('foo', [], [],
  1263. 'foo'),
  1264. ('foo\nR=xx', [], [],
  1265. 'foo\nR=xx'),
  1266. ('foo\nTBR=xx', [], [],
  1267. 'foo\nTBR=xx'),
  1268. ('foo', ['a@c'], [],
  1269. 'foo\n\nR=a@c'),
  1270. ('foo\nR=xx', ['a@c'], [],
  1271. 'foo\n\nR=a@c, xx'),
  1272. ('foo\nTBR=xx', ['a@c'], [],
  1273. 'foo\n\nR=a@c\nTBR=xx'),
  1274. ('foo\nTBR=xx\nR=yy', ['a@c'], [],
  1275. 'foo\n\nR=a@c, yy\nTBR=xx'),
  1276. ('foo\nBUG=', ['a@c'], [],
  1277. 'foo\nBUG=\nR=a@c'),
  1278. ('foo\nR=xx\nTBR=yy\nR=bar', ['a@c'], [],
  1279. 'foo\n\nR=a@c, bar, xx\nTBR=yy'),
  1280. ('foo', ['a@c', 'b@c'], [],
  1281. 'foo\n\nR=a@c, b@c'),
  1282. ('foo\nBar\n\nR=\nBUG=', ['c@c'], [],
  1283. 'foo\nBar\n\nR=c@c\nBUG='),
  1284. ('foo\nBar\n\nR=\nBUG=\nR=', ['c@c'], [],
  1285. 'foo\nBar\n\nR=c@c\nBUG='),
  1286. # Same as the line before, but full of whitespaces.
  1287. (
  1288. 'foo\nBar\n\n R = \n BUG = \n R = ', ['c@c'], [],
  1289. 'foo\nBar\n\nR=c@c\n BUG =',
  1290. ),
  1291. # Whitespaces aren't interpreted as new lines.
  1292. ('foo BUG=allo R=joe ', ['c@c'], [],
  1293. 'foo BUG=allo R=joe\n\nR=c@c'),
  1294. # Redundant TBRs get promoted to Rs
  1295. ('foo\n\nR=a@c\nTBR=t@c', ['b@c', 'a@c'], ['a@c', 't@c'],
  1296. 'foo\n\nR=a@c, b@c\nTBR=t@c'),
  1297. ]
  1298. expected = [i[-1] for i in data]
  1299. actual = []
  1300. for orig, reviewers, tbrs, _expected in data:
  1301. obj = git_cl.ChangeDescription(orig)
  1302. obj.update_reviewers(reviewers, tbrs, None, None, None)
  1303. actual.append(obj.description)
  1304. self.assertEqual(expected, actual)
  1305. def test_get_hash_tags(self):
  1306. cases = [
  1307. ('', []),
  1308. ('a', []),
  1309. ('[a]', ['a']),
  1310. ('[aa]', ['aa']),
  1311. ('[a ]', ['a']),
  1312. ('[a- ]', ['a']),
  1313. ('[a- b]', ['a-b']),
  1314. ('[a--b]', ['a-b']),
  1315. ('[a', []),
  1316. ('[a]x', ['a']),
  1317. ('[aa]x', ['aa']),
  1318. ('[a b]', ['a-b']),
  1319. ('[a b]', ['a-b']),
  1320. ('[a__b]', ['a-b']),
  1321. ('[a] x', ['a']),
  1322. ('[a][b]', ['a', 'b']),
  1323. ('[a] [b]', ['a', 'b']),
  1324. ('[a][b]x', ['a', 'b']),
  1325. ('[a][b] x', ['a', 'b']),
  1326. ('[a]\n[b]', ['a']),
  1327. ('[a\nb]', []),
  1328. ('[a][', ['a']),
  1329. ('Revert "[a] feature"', ['a']),
  1330. ('Reland "[a] feature"', ['a']),
  1331. ('Revert: [a] feature', ['a']),
  1332. ('Reland: [a] feature', ['a']),
  1333. ('Revert "Reland: [a] feature"', ['a']),
  1334. ('Foo: feature', ['foo']),
  1335. ('Foo Bar: feature', ['foo-bar']),
  1336. ('Change Foo::Bar', []),
  1337. ('Foo: Change Foo::Bar', ['foo']),
  1338. ('Revert "Foo bar: feature"', ['foo-bar']),
  1339. ('Reland "Foo bar: feature"', ['foo-bar']),
  1340. ]
  1341. for desc, expected in cases:
  1342. change_desc = git_cl.ChangeDescription(desc)
  1343. actual = change_desc.get_hash_tags()
  1344. self.assertEqual(
  1345. actual,
  1346. expected,
  1347. 'GetHashTags(%r) == %r, expected %r' % (desc, actual, expected))
  1348. self.assertEqual(None, git_cl.GetTargetRef('origin', None, 'master'))
  1349. self.assertEqual(None, git_cl.GetTargetRef(None,
  1350. 'refs/remotes/origin/master',
  1351. 'master'))
  1352. # Check default target refs for branches.
  1353. self.assertEqual('refs/heads/master',
  1354. git_cl.GetTargetRef('origin', 'refs/remotes/origin/master',
  1355. None))
  1356. self.assertEqual('refs/heads/master',
  1357. git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkgr',
  1358. None))
  1359. self.assertEqual('refs/heads/master',
  1360. git_cl.GetTargetRef('origin', 'refs/remotes/origin/lkcr',
  1361. None))
  1362. self.assertEqual('refs/branch-heads/123',
  1363. git_cl.GetTargetRef('origin',
  1364. 'refs/remotes/branch-heads/123',
  1365. None))
  1366. self.assertEqual('refs/diff/test',
  1367. git_cl.GetTargetRef('origin',
  1368. 'refs/remotes/origin/refs/diff/test',
  1369. None))
  1370. self.assertEqual('refs/heads/chrome/m42',
  1371. git_cl.GetTargetRef('origin',
  1372. 'refs/remotes/origin/chrome/m42',
  1373. None))
  1374. # Check target refs for user-specified target branch.
  1375. for branch in ('branch-heads/123', 'remotes/branch-heads/123',
  1376. 'refs/remotes/branch-heads/123'):
  1377. self.assertEqual('refs/branch-heads/123',
  1378. git_cl.GetTargetRef('origin',
  1379. 'refs/remotes/origin/master',
  1380. branch))
  1381. for branch in ('origin/master', 'remotes/origin/master',
  1382. 'refs/remotes/origin/master'):
  1383. self.assertEqual('refs/heads/master',
  1384. git_cl.GetTargetRef('origin',
  1385. 'refs/remotes/branch-heads/123',
  1386. branch))
  1387. for branch in ('master', 'heads/master', 'refs/heads/master'):
  1388. self.assertEqual('refs/heads/master',
  1389. git_cl.GetTargetRef('origin',
  1390. 'refs/remotes/branch-heads/123',
  1391. branch))
  1392. @mock.patch('git_common.is_dirty_git_tree', return_value=True)
  1393. def test_patch_when_dirty(self, *_mocks):
  1394. # Patch when local tree is dirty.
  1395. self.assertNotEqual(git_cl.main(['patch', '123456']), 0)
  1396. def assertIssueAndPatchset(
  1397. self, branch='master', issue='123456', patchset='7',
  1398. git_short_host='chromium'):
  1399. self.assertEqual(
  1400. issue, scm.GIT.GetBranchConfig('', branch, 'gerritissue'))
  1401. self.assertEqual(
  1402. patchset, scm.GIT.GetBranchConfig('', branch, 'gerritpatchset'))
  1403. self.assertEqual(
  1404. 'https://%s-review.googlesource.com' % git_short_host,
  1405. scm.GIT.GetBranchConfig('', branch, 'gerritserver'))
  1406. def _patch_common(self, git_short_host='chromium'):
  1407. mock.patch('scm.GIT.ResolveCommit', return_value='deadbeef').start()
  1408. self.mockGit.config['remote.origin.url'] = (
  1409. 'https://%s.googlesource.com/my/repo' % git_short_host)
  1410. gerrit_util.GetChangeDetail.return_value = {
  1411. 'current_revision': '7777777777',
  1412. 'revisions': {
  1413. '1111111111': {
  1414. '_number': 1,
  1415. 'fetch': {'http': {
  1416. 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
  1417. 'ref': 'refs/changes/56/123456/1',
  1418. }},
  1419. },
  1420. '7777777777': {
  1421. '_number': 7,
  1422. 'fetch': {'http': {
  1423. 'url': 'https://%s.googlesource.com/my/repo' % git_short_host,
  1424. 'ref': 'refs/changes/56/123456/7',
  1425. }},
  1426. },
  1427. },
  1428. }
  1429. def test_patch_gerrit_default(self):
  1430. self._patch_common()
  1431. self.calls += [
  1432. ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  1433. 'refs/changes/56/123456/7'],), ''),
  1434. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1435. ]
  1436. self.assertEqual(git_cl.main(['patch', '123456']), 0)
  1437. self.assertIssueAndPatchset()
  1438. def test_patch_gerrit_new_branch(self):
  1439. self._patch_common()
  1440. self.calls += [
  1441. ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  1442. 'refs/changes/56/123456/7'],), ''),
  1443. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1444. ]
  1445. self.assertEqual(git_cl.main(['patch', '-b', 'feature', '123456']), 0)
  1446. self.assertIssueAndPatchset(branch='feature')
  1447. def test_patch_gerrit_force(self):
  1448. self._patch_common('host')
  1449. self.calls += [
  1450. ((['git', 'fetch', 'https://host.googlesource.com/my/repo',
  1451. 'refs/changes/56/123456/7'],), ''),
  1452. ((['git', 'reset', '--hard', 'FETCH_HEAD'],), ''),
  1453. ]
  1454. self.assertEqual(git_cl.main(['patch', '123456', '--force']), 0)
  1455. self.assertIssueAndPatchset(git_short_host='host')
  1456. def test_patch_gerrit_guess_by_url(self):
  1457. self._patch_common('else')
  1458. self.calls += [
  1459. ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
  1460. 'refs/changes/56/123456/1'],), ''),
  1461. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1462. ]
  1463. self.assertEqual(git_cl.main(
  1464. ['patch', 'https://else-review.googlesource.com/#/c/123456/1']), 0)
  1465. self.assertIssueAndPatchset(patchset='1', git_short_host='else')
  1466. def test_patch_gerrit_guess_by_url_with_repo(self):
  1467. self._patch_common('else')
  1468. self.calls += [
  1469. ((['git', 'fetch', 'https://else.googlesource.com/my/repo',
  1470. 'refs/changes/56/123456/1'],), ''),
  1471. ((['git', 'cherry-pick', 'FETCH_HEAD'],), ''),
  1472. ]
  1473. self.assertEqual(git_cl.main(
  1474. ['patch', 'https://else-review.googlesource.com/c/my/repo/+/123456/1']),
  1475. 0)
  1476. self.assertIssueAndPatchset(patchset='1', git_short_host='else')
  1477. @mock.patch('sys.stderr', StringIO())
  1478. def test_patch_gerrit_conflict(self):
  1479. self._patch_common()
  1480. self.calls += [
  1481. ((['git', 'fetch', 'https://chromium.googlesource.com/my/repo',
  1482. 'refs/changes/56/123456/7'],), ''),
  1483. ((['git', 'cherry-pick', 'FETCH_HEAD'],), CERR1),
  1484. ]
  1485. with self.assertRaises(SystemExitMock):
  1486. git_cl.main(['patch', '123456'])
  1487. self.assertEqual(
  1488. 'Command "git cherry-pick FETCH_HEAD" failed.\n\n',
  1489. sys.stderr.getvalue())
  1490. @mock.patch(
  1491. 'gerrit_util.GetChangeDetail',
  1492. side_effect=gerrit_util.GerritError(404, ''))
  1493. @mock.patch('sys.stderr', StringIO())
  1494. def test_patch_gerrit_not_exists(self, *_mocks):
  1495. self.mockGit.config['remote.origin.url'] = (
  1496. 'https://chromium.googlesource.com/my/repo')
  1497. with self.assertRaises(SystemExitMock):
  1498. self.assertEqual(1, git_cl.main(['patch', '123456']))
  1499. self.assertEqual(
  1500. 'change 123456 at https://chromium-review.googlesource.com does not '
  1501. 'exist or you have no access to it\n',
  1502. sys.stderr.getvalue())
  1503. def _checkout_calls(self):
  1504. return [
  1505. ((['git', 'config', '--local', '--get-regexp',
  1506. 'branch\\..*\\.gerritissue'], ),
  1507. ('branch.ger-branch.gerritissue 123456\n'
  1508. 'branch.gbranch654.gerritissue 654321\n')),
  1509. ]
  1510. def test_checkout_gerrit(self):
  1511. """Tests git cl checkout <issue>."""
  1512. self.calls = self._checkout_calls()
  1513. self.calls += [((['git', 'checkout', 'ger-branch'], ), '')]
  1514. self.assertEqual(0, git_cl.main(['checkout', '123456']))
  1515. def test_checkout_not_found(self):
  1516. """Tests git cl checkout <issue>."""
  1517. self.calls = self._checkout_calls()
  1518. self.assertEqual(1, git_cl.main(['checkout', '99999']))
  1519. def test_checkout_no_branch_issues(self):
  1520. """Tests git cl checkout <issue>."""
  1521. self.calls = [
  1522. ((['git', 'config', '--local', '--get-regexp',
  1523. 'branch\\..*\\.gerritissue'], ), CERR1),
  1524. ]
  1525. self.assertEqual(1, git_cl.main(['checkout', '99999']))
  1526. def _test_gerrit_ensure_authenticated_common(self, auth):
  1527. mock.patch(
  1528. 'gclient_utils.AskForData',
  1529. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  1530. mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
  1531. CookiesAuthenticatorMockFactory(hosts_with_creds=auth)).start()
  1532. self.mockGit.config['remote.origin.url'] = (
  1533. 'https://chromium.googlesource.com/my/repo')
  1534. cl = git_cl.Changelist()
  1535. cl.branch = 'master'
  1536. cl.branchref = 'refs/heads/master'
  1537. return cl
  1538. @mock.patch('sys.stderr', StringIO())
  1539. def test_gerrit_ensure_authenticated_missing(self):
  1540. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1541. 'chromium.googlesource.com': ('git-is.ok', '', 'but gerrit is missing'),
  1542. })
  1543. with self.assertRaises(SystemExitMock):
  1544. cl.EnsureAuthenticated(force=False)
  1545. self.assertEqual(
  1546. 'Credentials for the following hosts are required:\n'
  1547. ' chromium-review.googlesource.com\n'
  1548. 'These are read from ~%(sep)s.gitcookies '
  1549. '(or legacy ~%(sep)s%(netrc)s)\n'
  1550. 'You can (re)generate your credentials by visiting '
  1551. 'https://chromium-review.googlesource.com/new-password\n' % {
  1552. 'sep': os.sep,
  1553. 'netrc': NETRC_FILENAME,
  1554. }, sys.stderr.getvalue())
  1555. def test_gerrit_ensure_authenticated_conflict(self):
  1556. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1557. 'chromium.googlesource.com':
  1558. ('git-one.example.com', None, 'secret1'),
  1559. 'chromium-review.googlesource.com':
  1560. ('git-other.example.com', None, 'secret2'),
  1561. })
  1562. self.calls.append(
  1563. (('ask_for_data', 'If you know what you are doing '
  1564. 'press Enter to continue, or Ctrl+C to abort'), ''))
  1565. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1566. def test_gerrit_ensure_authenticated_ok(self):
  1567. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1568. 'chromium.googlesource.com':
  1569. ('git-same.example.com', None, 'secret'),
  1570. 'chromium-review.googlesource.com':
  1571. ('git-same.example.com', None, 'secret'),
  1572. })
  1573. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1574. def test_gerrit_ensure_authenticated_skipped(self):
  1575. self.mockGit.config['gerrit.skip-ensure-authenticated'] = 'true'
  1576. cl = self._test_gerrit_ensure_authenticated_common(auth={})
  1577. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1578. def test_gerrit_ensure_authenticated_bearer_token(self):
  1579. cl = self._test_gerrit_ensure_authenticated_common(auth={
  1580. 'chromium.googlesource.com':
  1581. ('', None, 'secret'),
  1582. 'chromium-review.googlesource.com':
  1583. ('', None, 'secret'),
  1584. })
  1585. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1586. header = gerrit_util.CookiesAuthenticator().get_auth_header(
  1587. 'chromium.googlesource.com')
  1588. self.assertTrue('Bearer' in header)
  1589. def test_gerrit_ensure_authenticated_non_https(self):
  1590. self.mockGit.config['remote.origin.url'] = 'custom-scheme://repo'
  1591. self.calls = [
  1592. (('logging.warning',
  1593. 'Ignoring branch %(branch)s with non-https remote '
  1594. '%(remote)s', {
  1595. 'branch': 'master',
  1596. 'remote': 'custom-scheme://repo'}
  1597. ), None),
  1598. ]
  1599. mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
  1600. CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
  1601. mock.patch('logging.warning',
  1602. lambda *a: self._mocked_call('logging.warning', *a)).start()
  1603. cl = git_cl.Changelist()
  1604. cl.branch = 'master'
  1605. cl.branchref = 'refs/heads/master'
  1606. cl.lookedup_issue = True
  1607. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1608. def test_gerrit_ensure_authenticated_non_url(self):
  1609. self.mockGit.config['remote.origin.url'] = (
  1610. 'git@somehost.example:foo/bar.git')
  1611. self.calls = [
  1612. (('logging.error',
  1613. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  1614. 'but it doesn\'t exist.', {
  1615. 'remote': 'origin',
  1616. 'branch': 'master',
  1617. 'url': 'git@somehost.example:foo/bar.git'}
  1618. ), None),
  1619. ]
  1620. mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
  1621. CookiesAuthenticatorMockFactory(hosts_with_creds={})).start()
  1622. mock.patch('logging.error',
  1623. lambda *a: self._mocked_call('logging.error', *a)).start()
  1624. cl = git_cl.Changelist()
  1625. cl.branch = 'master'
  1626. cl.branchref = 'refs/heads/master'
  1627. cl.lookedup_issue = True
  1628. self.assertIsNone(cl.EnsureAuthenticated(force=False))
  1629. def _cmd_set_commit_gerrit_common(self, vote, notify=None):
  1630. self.mockGit.config['branch.master.gerritissue'] = '123'
  1631. self.mockGit.config['branch.master.gerritserver'] = (
  1632. 'https://chromium-review.googlesource.com')
  1633. self.mockGit.config['remote.origin.url'] = (
  1634. 'https://chromium.googlesource.com/infra/infra')
  1635. self.calls = [
  1636. (('SetReview', 'chromium-review.googlesource.com',
  1637. 'infra%2Finfra~123', None,
  1638. {'Commit-Queue': vote}, notify, None), ''),
  1639. ]
  1640. def test_cmd_set_commit_gerrit_clear(self):
  1641. self._cmd_set_commit_gerrit_common(0)
  1642. self.assertEqual(0, git_cl.main(['set-commit', '-c']))
  1643. def test_cmd_set_commit_gerrit_dry(self):
  1644. self._cmd_set_commit_gerrit_common(1, notify=False)
  1645. self.assertEqual(0, git_cl.main(['set-commit', '-d']))
  1646. def test_cmd_set_commit_gerrit(self):
  1647. self._cmd_set_commit_gerrit_common(2)
  1648. self.assertEqual(0, git_cl.main(['set-commit']))
  1649. def test_description_display(self):
  1650. mock.patch('git_cl.Changelist', ChangelistMock).start()
  1651. ChangelistMock.desc = 'foo\n'
  1652. self.assertEqual(0, git_cl.main(['description', '-d']))
  1653. self.assertEqual('foo\n', sys.stdout.getvalue())
  1654. @mock.patch('sys.stderr', StringIO())
  1655. def test_StatusFieldOverrideIssueMissingArgs(self):
  1656. try:
  1657. self.assertEqual(git_cl.main(['status', '--issue', '1']), 0)
  1658. except SystemExitMock:
  1659. self.assertIn(
  1660. '--field must be given when --issue is set.', sys.stderr.getvalue())
  1661. def test_StatusFieldOverrideIssue(self):
  1662. def assertIssue(cl_self, *_args):
  1663. self.assertEqual(cl_self.issue, 1)
  1664. return 'foobar'
  1665. mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
  1666. self.assertEqual(
  1667. git_cl.main(['status', '--issue', '1', '--field', 'desc']),
  1668. 0)
  1669. self.assertEqual(sys.stdout.getvalue(), 'foobar\n')
  1670. def test_SetCloseOverrideIssue(self):
  1671. def assertIssue(cl_self, *_args):
  1672. self.assertEqual(cl_self.issue, 1)
  1673. return 'foobar'
  1674. mock.patch('git_cl.Changelist.FetchDescription', assertIssue).start()
  1675. mock.patch('git_cl.Changelist.CloseIssue', lambda *_: None).start()
  1676. self.assertEqual(
  1677. git_cl.main(['set-close', '--issue', '1']), 0)
  1678. def test_description(self):
  1679. self.mockGit.config['remote.origin.url'] = (
  1680. 'https://chromium.googlesource.com/my/repo')
  1681. gerrit_util.GetChangeDetail.return_value = {
  1682. 'current_revision': 'sha1',
  1683. 'revisions': {'sha1': {
  1684. 'commit': {'message': 'foobar'},
  1685. }},
  1686. }
  1687. self.assertEqual(0, git_cl.main([
  1688. 'description',
  1689. 'https://chromium-review.googlesource.com/c/my/repo/+/123123',
  1690. '-d']))
  1691. self.assertEqual('foobar\n', sys.stdout.getvalue())
  1692. def test_description_set_raw(self):
  1693. mock.patch('git_cl.Changelist', ChangelistMock).start()
  1694. mock.patch('git_cl.sys.stdin', StringIO('hihi')).start()
  1695. self.assertEqual(0, git_cl.main(['description', '-n', 'hihi']))
  1696. self.assertEqual('hihi', ChangelistMock.desc)
  1697. def test_description_appends_bug_line(self):
  1698. current_desc = 'Some.\n\nChange-Id: xxx'
  1699. def RunEditor(desc, _, **kwargs):
  1700. self.assertEqual(
  1701. '# Enter a description of the change.\n'
  1702. '# This will be displayed on the codereview site.\n'
  1703. '# The first line will also be used as the subject of the review.\n'
  1704. '#--------------------This line is 72 characters long'
  1705. '--------------------\n'
  1706. 'Some.\n\nChange-Id: xxx\nBug: ',
  1707. desc)
  1708. # Simulate user changing something.
  1709. return 'Some.\n\nChange-Id: xxx\nBug: 123'
  1710. def UpdateDescription(_, desc, force=False):
  1711. self.assertEqual(desc, 'Some.\n\nChange-Id: xxx\nBug: 123')
  1712. mock.patch('git_cl.Changelist.FetchDescription',
  1713. lambda *args: current_desc).start()
  1714. mock.patch('git_cl.Changelist.UpdateDescription',
  1715. UpdateDescription).start()
  1716. mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
  1717. self.mockGit.config['branch.master.gerritissue'] = '123'
  1718. self.assertEqual(0, git_cl.main(['description']))
  1719. def test_description_does_not_append_bug_line_if_fixed_is_present(self):
  1720. current_desc = 'Some.\n\nFixed: 123\nChange-Id: xxx'
  1721. def RunEditor(desc, _, **kwargs):
  1722. self.assertEqual(
  1723. '# Enter a description of the change.\n'
  1724. '# This will be displayed on the codereview site.\n'
  1725. '# The first line will also be used as the subject of the review.\n'
  1726. '#--------------------This line is 72 characters long'
  1727. '--------------------\n'
  1728. 'Some.\n\nFixed: 123\nChange-Id: xxx',
  1729. desc)
  1730. return desc
  1731. mock.patch('git_cl.Changelist.FetchDescription',
  1732. lambda *args: current_desc).start()
  1733. mock.patch('git_cl.gclient_utils.RunEditor', RunEditor).start()
  1734. self.mockGit.config['branch.master.gerritissue'] = '123'
  1735. self.assertEqual(0, git_cl.main(['description']))
  1736. def test_description_set_stdin(self):
  1737. mock.patch('git_cl.Changelist', ChangelistMock).start()
  1738. mock.patch('git_cl.sys.stdin', StringIO('hi \r\n\t there\n\nman')).start()
  1739. self.assertEqual(0, git_cl.main(['description', '-n', '-']))
  1740. self.assertEqual('hi\n\t there\n\nman', ChangelistMock.desc)
  1741. def test_archive(self):
  1742. self.calls = [
  1743. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  1744. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  1745. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
  1746. ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],), ''),
  1747. ((['git', 'branch', '-D', 'foo'],), '')
  1748. ]
  1749. mock.patch('git_cl.get_cl_statuses',
  1750. lambda branches, fine_grained, max_processes:
  1751. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  1752. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  1753. (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
  1754. self.assertEqual(0, git_cl.main(['archive', '-f']))
  1755. def test_archive_tag_collision(self):
  1756. self.calls = [
  1757. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  1758. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  1759. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],),
  1760. 'refs/tags/git-cl-archived-456-foo'),
  1761. ((['git', 'tag', 'git-cl-archived-456-foo-2', 'foo'],), ''),
  1762. ((['git', 'branch', '-D', 'foo'],), '')
  1763. ]
  1764. mock.patch('git_cl.get_cl_statuses',
  1765. lambda branches, fine_grained, max_processes:
  1766. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  1767. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  1768. (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
  1769. self.assertEqual(0, git_cl.main(['archive', '-f']))
  1770. def test_archive_current_branch_fails(self):
  1771. self.calls = [
  1772. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  1773. 'refs/heads/master'),
  1774. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
  1775. ]
  1776. mock.patch('git_cl.get_cl_statuses',
  1777. lambda branches, fine_grained, max_processes:
  1778. [(MockChangelistWithBranchAndIssue('master', 1),
  1779. 'closed')]).start()
  1780. self.assertEqual(1, git_cl.main(['archive', '-f']))
  1781. def test_archive_dry_run(self):
  1782. self.calls = [
  1783. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  1784. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  1785. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
  1786. ]
  1787. mock.patch('git_cl.get_cl_statuses',
  1788. lambda branches, fine_grained, max_processes:
  1789. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  1790. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  1791. (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
  1792. self.assertEqual(0, git_cl.main(['archive', '-f', '--dry-run']))
  1793. def test_archive_no_tags(self):
  1794. self.calls = [
  1795. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  1796. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  1797. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
  1798. ((['git', 'branch', '-D', 'foo'],), '')
  1799. ]
  1800. mock.patch('git_cl.get_cl_statuses',
  1801. lambda branches, fine_grained, max_processes:
  1802. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  1803. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  1804. (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
  1805. self.assertEqual(0, git_cl.main(['archive', '-f', '--notags']))
  1806. def test_archive_tag_cleanup_on_branch_deletion_error(self):
  1807. self.calls = [
  1808. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'],),
  1809. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  1810. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'],), ''),
  1811. ((['git', 'tag', 'git-cl-archived-456-foo', 'foo'],),
  1812. 'refs/tags/git-cl-archived-456-foo'),
  1813. ((['git', 'branch', '-D', 'foo'],), CERR1),
  1814. ((['git', 'tag', '-d', 'git-cl-archived-456-foo'],),
  1815. 'refs/tags/git-cl-archived-456-foo'),
  1816. ]
  1817. mock.patch('git_cl.get_cl_statuses',
  1818. lambda branches, fine_grained, max_processes:
  1819. [(MockChangelistWithBranchAndIssue('master', 1), 'open'),
  1820. (MockChangelistWithBranchAndIssue('foo', 456), 'closed'),
  1821. (MockChangelistWithBranchAndIssue('bar', 789), 'open')]).start()
  1822. self.assertEqual(0, git_cl.main(['archive', '-f']))
  1823. def test_archive_with_format(self):
  1824. self.calls = [
  1825. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/heads'], ),
  1826. 'refs/heads/master\nrefs/heads/foo\nrefs/heads/bar'),
  1827. ((['git', 'for-each-ref', '--format=%(refname)', 'refs/tags'], ), ''),
  1828. ((['git', 'tag', 'archived/12-foo', 'foo'], ), ''),
  1829. ((['git', 'branch', '-D', 'foo'], ), ''),
  1830. ]
  1831. mock.patch('git_cl.get_cl_statuses',
  1832. lambda branches, fine_grained, max_processes:
  1833. [(MockChangelistWithBranchAndIssue('foo', 12), 'closed')]).start()
  1834. self.assertEqual(
  1835. 0, git_cl.main(['archive', '-f', '-p', 'archived/{issue}-{branch}']))
  1836. def test_cmd_issue_erase_existing(self):
  1837. self.mockGit.config['branch.master.gerritissue'] = '123'
  1838. self.mockGit.config['branch.master.gerritserver'] = (
  1839. 'https://chromium-review.googlesource.com')
  1840. self.calls = [
  1841. ((['git', 'log', '-1', '--format=%B'],), 'This is a description'),
  1842. ]
  1843. self.assertEqual(0, git_cl.main(['issue', '0']))
  1844. self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
  1845. self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
  1846. def test_cmd_issue_erase_existing_with_change_id(self):
  1847. self.mockGit.config['branch.master.gerritissue'] = '123'
  1848. self.mockGit.config['branch.master.gerritserver'] = (
  1849. 'https://chromium-review.googlesource.com')
  1850. mock.patch('git_cl.Changelist.FetchDescription',
  1851. lambda _: 'This is a description\n\nChange-Id: Ideadbeef').start()
  1852. self.calls = [
  1853. ((['git', 'log', '-1', '--format=%B'],),
  1854. 'This is a description\n\nChange-Id: Ideadbeef'),
  1855. ((['git', 'commit', '--amend', '-m', 'This is a description\n'],), ''),
  1856. ]
  1857. self.assertEqual(0, git_cl.main(['issue', '0']))
  1858. self.assertNotIn('branch.master.gerritissue', self.mockGit.config)
  1859. self.assertNotIn('branch.master.gerritserver', self.mockGit.config)
  1860. def test_cmd_issue_json(self):
  1861. self.mockGit.config['branch.master.gerritissue'] = '123'
  1862. self.mockGit.config['branch.master.gerritserver'] = (
  1863. 'https://chromium-review.googlesource.com')
  1864. self.calls = [
  1865. (('write_json', 'output.json',
  1866. {'issue': 123,
  1867. 'issue_url': 'https://chromium-review.googlesource.com/123'}),
  1868. ''),
  1869. ]
  1870. self.assertEqual(0, git_cl.main(['issue', '--json', 'output.json']))
  1871. def _common_GerritCommitMsgHookCheck(self):
  1872. mock.patch(
  1873. 'git_cl.os.path.abspath',
  1874. lambda path: self._mocked_call(['abspath', path])).start()
  1875. mock.patch(
  1876. 'git_cl.os.path.exists',
  1877. lambda path: self._mocked_call(['exists', path])).start()
  1878. mock.patch(
  1879. 'git_cl.gclient_utils.FileRead',
  1880. lambda path: self._mocked_call(['FileRead', path])).start()
  1881. mock.patch(
  1882. 'git_cl.gclient_utils.rm_file_or_tree',
  1883. lambda path: self._mocked_call(['rm_file_or_tree', path])).start()
  1884. mock.patch(
  1885. 'gclient_utils.AskForData',
  1886. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  1887. return git_cl.Changelist(issue=123)
  1888. def test_GerritCommitMsgHookCheck_custom_hook(self):
  1889. cl = self._common_GerritCommitMsgHookCheck()
  1890. self.calls += [((['exists',
  1891. os.path.join('.git', 'hooks', 'commit-msg')], ), True),
  1892. ((['FileRead',
  1893. os.path.join('.git', 'hooks', 'commit-msg')], ),
  1894. '#!/bin/sh\necho "custom hook"')]
  1895. cl._GerritCommitMsgHookCheck(offer_removal=True)
  1896. def test_GerritCommitMsgHookCheck_not_exists(self):
  1897. cl = self._common_GerritCommitMsgHookCheck()
  1898. self.calls += [
  1899. ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), False),
  1900. ]
  1901. cl._GerritCommitMsgHookCheck(offer_removal=True)
  1902. def test_GerritCommitMsgHookCheck(self):
  1903. cl = self._common_GerritCommitMsgHookCheck()
  1904. self.calls += [
  1905. ((['exists', os.path.join('.git', 'hooks', 'commit-msg')], ), True),
  1906. ((['FileRead', os.path.join('.git', 'hooks', 'commit-msg')], ),
  1907. '...\n# From Gerrit Code Review\n...\nadd_ChangeId()\n'),
  1908. (('ask_for_data', 'Do you want to remove it now? [Yes/No]: '), 'Yes'),
  1909. ((['rm_file_or_tree',
  1910. os.path.join('.git', 'hooks', 'commit-msg')], ), ''),
  1911. ]
  1912. cl._GerritCommitMsgHookCheck(offer_removal=True)
  1913. def test_GerritCmdLand(self):
  1914. self.mockGit.config['branch.master.gerritsquashhash'] = 'deadbeaf'
  1915. self.mockGit.config['branch.master.gerritserver'] = (
  1916. 'chromium-review.googlesource.com')
  1917. self.calls += [
  1918. ((['git', 'diff', 'deadbeaf'],), ''), # No diff.
  1919. ]
  1920. cl = git_cl.Changelist(issue=123)
  1921. cl._GetChangeDetail = lambda *args, **kwargs: {
  1922. 'labels': {},
  1923. 'current_revision': 'deadbeaf',
  1924. }
  1925. cl._GetChangeCommit = lambda: {
  1926. 'commit': 'deadbeef',
  1927. 'web_links': [{'name': 'gitiles',
  1928. 'url': 'https://git.googlesource.com/test/+/deadbeef'}],
  1929. }
  1930. cl.SubmitIssue = lambda wait_for_merge: None
  1931. self.assertEqual(0, cl.CMDLand(force=True,
  1932. bypass_hooks=True,
  1933. verbose=True,
  1934. parallel=False,
  1935. resultdb=False,
  1936. realm=None))
  1937. self.assertIn(
  1938. 'Issue chromium-review.googlesource.com/123 has been submitted',
  1939. sys.stdout.getvalue())
  1940. self.assertIn(
  1941. 'Landed as: https://git.googlesource.com/test/+/deadbeef',
  1942. sys.stdout.getvalue())
  1943. def _mock_gerrit_changes_for_detail_cache(self):
  1944. mock.patch('git_cl.Changelist._GetGerritHost', lambda _: 'host').start()
  1945. def test_gerrit_change_detail_cache_simple(self):
  1946. self._mock_gerrit_changes_for_detail_cache()
  1947. gerrit_util.GetChangeDetail.side_effect = ['a', 'b']
  1948. cl1 = git_cl.Changelist(issue=1)
  1949. cl1._cached_remote_url = (
  1950. True, 'https://chromium.googlesource.com/a/my/repo.git/')
  1951. cl2 = git_cl.Changelist(issue=2)
  1952. cl2._cached_remote_url = (
  1953. True, 'https://chromium.googlesource.com/ab/repo')
  1954. self.assertEqual(cl1._GetChangeDetail(), 'a') # Miss.
  1955. self.assertEqual(cl1._GetChangeDetail(), 'a')
  1956. self.assertEqual(cl2._GetChangeDetail(), 'b') # Miss.
  1957. def test_gerrit_change_detail_cache_options(self):
  1958. self._mock_gerrit_changes_for_detail_cache()
  1959. gerrit_util.GetChangeDetail.side_effect = ['cab', 'ad']
  1960. cl = git_cl.Changelist(issue=1)
  1961. cl._cached_remote_url = (True, 'https://chromium.googlesource.com/repo/')
  1962. self.assertEqual(cl._GetChangeDetail(options=['C', 'A', 'B']), 'cab')
  1963. self.assertEqual(cl._GetChangeDetail(options=['A', 'B', 'C']), 'cab')
  1964. self.assertEqual(cl._GetChangeDetail(options=['B', 'A']), 'cab')
  1965. self.assertEqual(cl._GetChangeDetail(options=['C']), 'cab')
  1966. self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
  1967. self.assertEqual(cl._GetChangeDetail(), 'cab')
  1968. self.assertEqual(cl._GetChangeDetail(options=['A', 'D']), 'ad')
  1969. self.assertEqual(cl._GetChangeDetail(options=['A']), 'cab')
  1970. self.assertEqual(cl._GetChangeDetail(options=['D']), 'ad')
  1971. self.assertEqual(cl._GetChangeDetail(), 'cab')
  1972. def test_gerrit_description_caching(self):
  1973. gerrit_util.GetChangeDetail.return_value = {
  1974. 'current_revision': 'rev1',
  1975. 'revisions': {
  1976. 'rev1': {'commit': {'message': 'desc1'}},
  1977. },
  1978. }
  1979. self._mock_gerrit_changes_for_detail_cache()
  1980. cl = git_cl.Changelist(issue=1)
  1981. cl._cached_remote_url = (
  1982. True, 'https://chromium.googlesource.com/a/my/repo.git/')
  1983. self.assertEqual(cl.FetchDescription(), 'desc1')
  1984. self.assertEqual(cl.FetchDescription(), 'desc1') # cache hit.
  1985. def test_print_current_creds(self):
  1986. class CookiesAuthenticatorMock(object):
  1987. def __init__(self):
  1988. self.gitcookies = {
  1989. 'host.googlesource.com': ('user', 'pass'),
  1990. 'host-review.googlesource.com': ('user', 'pass'),
  1991. }
  1992. self.netrc = self
  1993. self.netrc.hosts = {
  1994. 'github.com': ('user2', None, 'pass2'),
  1995. 'host2.googlesource.com': ('user3', None, 'pass'),
  1996. }
  1997. mock.patch('git_cl.gerrit_util.CookiesAuthenticator',
  1998. CookiesAuthenticatorMock).start()
  1999. git_cl._GitCookiesChecker().print_current_creds(include_netrc=True)
  2000. self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
  2001. ' Host\t User\t Which file',
  2002. '============================\t=====\t===========',
  2003. 'host-review.googlesource.com\t user\t.gitcookies',
  2004. ' host.googlesource.com\t user\t.gitcookies',
  2005. ' host2.googlesource.com\tuser3\t .netrc',
  2006. ])
  2007. sys.stdout.seek(0)
  2008. sys.stdout.truncate(0)
  2009. git_cl._GitCookiesChecker().print_current_creds(include_netrc=False)
  2010. self.assertEqual(list(sys.stdout.getvalue().splitlines()), [
  2011. ' Host\tUser\t Which file',
  2012. '============================\t====\t===========',
  2013. 'host-review.googlesource.com\tuser\t.gitcookies',
  2014. ' host.googlesource.com\tuser\t.gitcookies',
  2015. ])
  2016. def _common_creds_check_mocks(self):
  2017. def exists_mock(path):
  2018. dirname = os.path.dirname(path)
  2019. if dirname == os.path.expanduser('~'):
  2020. dirname = '~'
  2021. base = os.path.basename(path)
  2022. if base in (NETRC_FILENAME, '.gitcookies'):
  2023. return self._mocked_call('os.path.exists', os.path.join(dirname, base))
  2024. # git cl also checks for existence other files not relevant to this test.
  2025. return None
  2026. mock.patch(
  2027. 'gclient_utils.AskForData',
  2028. lambda prompt: self._mocked_call('ask_for_data', prompt)).start()
  2029. mock.patch('os.path.exists', exists_mock).start()
  2030. def test_creds_check_gitcookies_not_configured(self):
  2031. self._common_creds_check_mocks()
  2032. mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
  2033. lambda _, include_netrc=False: []).start()
  2034. self.calls = [
  2035. ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
  2036. ((['git', 'config', '--global', 'http.cookiefile'], ), CERR1),
  2037. (('os.path.exists', os.path.join('~', NETRC_FILENAME)), True),
  2038. (('ask_for_data', 'Press Enter to setup .gitcookies, '
  2039. 'or Ctrl+C to abort'), ''),
  2040. (([
  2041. 'git', 'config', '--global', 'http.cookiefile',
  2042. os.path.expanduser(os.path.join('~', '.gitcookies'))
  2043. ], ), ''),
  2044. ]
  2045. self.assertEqual(0, git_cl.main(['creds-check']))
  2046. self.assertTrue(
  2047. sys.stdout.getvalue().startswith(
  2048. 'You seem to be using outdated .netrc for git credentials:'))
  2049. self.assertIn(
  2050. '\nConfigured git to use .gitcookies from',
  2051. sys.stdout.getvalue())
  2052. def test_creds_check_gitcookies_configured_custom_broken(self):
  2053. self._common_creds_check_mocks()
  2054. mock.patch('git_cl._GitCookiesChecker.get_hosts_with_creds',
  2055. lambda _, include_netrc=False: []).start()
  2056. custom_cookie_path = ('C:\\.gitcookies'
  2057. if sys.platform == 'win32' else '/custom/.gitcookies')
  2058. self.calls = [
  2059. ((['git', 'config', '--path', 'http.cookiefile'], ), CERR1),
  2060. ((['git', 'config', '--global', 'http.cookiefile'], ),
  2061. custom_cookie_path),
  2062. (('os.path.exists', custom_cookie_path), False),
  2063. (('ask_for_data', 'Reconfigure git to use default .gitcookies? '
  2064. 'Press Enter to reconfigure, or Ctrl+C to abort'), ''),
  2065. (([
  2066. 'git', 'config', '--global', 'http.cookiefile',
  2067. os.path.expanduser(os.path.join('~', '.gitcookies'))
  2068. ], ), ''),
  2069. ]
  2070. self.assertEqual(0, git_cl.main(['creds-check']))
  2071. self.assertIn(
  2072. 'WARNING: You have configured custom path to .gitcookies: ',
  2073. sys.stdout.getvalue())
  2074. self.assertIn(
  2075. 'However, your configured .gitcookies file is missing.',
  2076. sys.stdout.getvalue())
  2077. def test_git_cl_comment_add_gerrit(self):
  2078. self.mockGit.branchref = None
  2079. self.mockGit.config['remote.origin.url'] = (
  2080. 'https://chromium.googlesource.com/infra/infra')
  2081. self.calls = [
  2082. (('SetReview', 'chromium-review.googlesource.com', 'infra%2Finfra~10',
  2083. 'msg', None, None, None),
  2084. None),
  2085. ]
  2086. self.assertEqual(0, git_cl.main(['comment', '-i', '10', '-a', 'msg']))
  2087. @mock.patch('git_cl.Changelist.GetBranch', return_value='foo')
  2088. def test_git_cl_comments_fetch_gerrit(self, *_mocks):
  2089. self.mockGit.config['remote.origin.url'] = (
  2090. 'https://chromium.googlesource.com/infra/infra')
  2091. gerrit_util.GetChangeDetail.return_value = {
  2092. 'owner': {'email': 'owner@example.com'},
  2093. 'current_revision': 'ba5eba11',
  2094. 'revisions': {
  2095. 'deadbeaf': {
  2096. '_number': 1,
  2097. },
  2098. 'ba5eba11': {
  2099. '_number': 2,
  2100. },
  2101. },
  2102. 'messages': [
  2103. {
  2104. u'_revision_number': 1,
  2105. u'author': {
  2106. u'_account_id': 1111084,
  2107. u'email': u'could-be-anything@example.com',
  2108. u'name': u'LUCI CQ'
  2109. },
  2110. u'date': u'2017-03-15 20:08:45.000000000',
  2111. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
  2112. u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
  2113. u'tag': u'autogenerated:cq:dry-run'
  2114. },
  2115. {
  2116. u'_revision_number': 2,
  2117. u'author': {
  2118. u'_account_id': 11151243,
  2119. u'email': u'owner@example.com',
  2120. u'name': u'owner'
  2121. },
  2122. u'date': u'2017-03-16 20:00:41.000000000',
  2123. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2124. u'message': u'PTAL',
  2125. },
  2126. {
  2127. u'_revision_number': 2,
  2128. u'author': {
  2129. u'_account_id': 148512,
  2130. u'email': u'reviewer@example.com',
  2131. u'name': u'reviewer'
  2132. },
  2133. u'date': u'2017-03-17 05:19:37.500000000',
  2134. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
  2135. u'message': u'Patch Set 2: Code-Review+1',
  2136. },
  2137. ]
  2138. }
  2139. self.calls = [
  2140. (('GetChangeComments', 'chromium-review.googlesource.com',
  2141. 'infra%2Finfra~1'), {
  2142. '/COMMIT_MSG': [
  2143. {
  2144. 'author': {'email': u'reviewer@example.com'},
  2145. 'updated': u'2017-03-17 05:19:37.500000000',
  2146. 'patch_set': 2,
  2147. 'side': 'REVISION',
  2148. 'message': 'Please include a bug link',
  2149. },
  2150. ],
  2151. 'codereview.settings': [
  2152. {
  2153. 'author': {'email': u'owner@example.com'},
  2154. 'updated': u'2017-03-16 20:00:41.000000000',
  2155. 'patch_set': 2,
  2156. 'side': 'PARENT',
  2157. 'line': 42,
  2158. 'message': 'I removed this because it is bad',
  2159. },
  2160. ]
  2161. }),
  2162. (('GetChangeRobotComments', 'chromium-review.googlesource.com',
  2163. 'infra%2Finfra~1'), {}),
  2164. ] * 2 + [
  2165. (('write_json', 'output.json', [
  2166. {
  2167. u'date': u'2017-03-16 20:00:41.000000',
  2168. u'message': (
  2169. u'PTAL\n' +
  2170. u'\n' +
  2171. u'codereview.settings\n' +
  2172. u' Base, Line 42: https://chromium-review.googlesource.com/' +
  2173. u'c/1/2/codereview.settings#b42\n' +
  2174. u' I removed this because it is bad\n'),
  2175. u'autogenerated': False,
  2176. u'approval': False,
  2177. u'disapproval': False,
  2178. u'sender': u'owner@example.com'
  2179. }, {
  2180. u'date': u'2017-03-17 05:19:37.500000',
  2181. u'message': (
  2182. u'Patch Set 2: Code-Review+1\n' +
  2183. u'\n' +
  2184. u'/COMMIT_MSG\n' +
  2185. u' PS2, File comment: https://chromium-review.googlesource' +
  2186. u'.com/c/1/2//COMMIT_MSG#\n' +
  2187. u' Please include a bug link\n'),
  2188. u'autogenerated': False,
  2189. u'approval': False,
  2190. u'disapproval': False,
  2191. u'sender': u'reviewer@example.com'
  2192. }
  2193. ]), '')
  2194. ]
  2195. expected_comments_summary = [
  2196. git_cl._CommentSummary(
  2197. message=(
  2198. u'PTAL\n' +
  2199. u'\n' +
  2200. u'codereview.settings\n' +
  2201. u' Base, Line 42: https://chromium-review.googlesource.com/' +
  2202. u'c/1/2/codereview.settings#b42\n' +
  2203. u' I removed this because it is bad\n'),
  2204. date=datetime.datetime(2017, 3, 16, 20, 0, 41, 0),
  2205. autogenerated=False,
  2206. disapproval=False, approval=False, sender=u'owner@example.com'),
  2207. git_cl._CommentSummary(
  2208. message=(
  2209. u'Patch Set 2: Code-Review+1\n' +
  2210. u'\n' +
  2211. u'/COMMIT_MSG\n' +
  2212. u' PS2, File comment: https://chromium-review.googlesource.com/' +
  2213. u'c/1/2//COMMIT_MSG#\n' +
  2214. u' Please include a bug link\n'),
  2215. date=datetime.datetime(2017, 3, 17, 5, 19, 37, 500000),
  2216. autogenerated=False,
  2217. disapproval=False, approval=False, sender=u'reviewer@example.com'),
  2218. ]
  2219. cl = git_cl.Changelist(
  2220. issue=1, branchref='refs/heads/foo')
  2221. self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
  2222. self.assertEqual(
  2223. 0, git_cl.main(['comments', '-i', '1', '-j', 'output.json']))
  2224. def test_git_cl_comments_robot_comments(self):
  2225. # git cl comments also fetches robot comments (which are considered a type
  2226. # of autogenerated comment), and unlike other types of comments, only robot
  2227. # comments from the latest patchset are shown.
  2228. self.mockGit.config['remote.origin.url'] = (
  2229. 'https://chromium.googlesource.com/infra/infra')
  2230. gerrit_util.GetChangeDetail.return_value = {
  2231. 'owner': {'email': 'owner@example.com'},
  2232. 'current_revision': 'ba5eba11',
  2233. 'revisions': {
  2234. 'deadbeaf': {
  2235. '_number': 1,
  2236. },
  2237. 'ba5eba11': {
  2238. '_number': 2,
  2239. },
  2240. },
  2241. 'messages': [
  2242. {
  2243. u'_revision_number': 1,
  2244. u'author': {
  2245. u'_account_id': 1111084,
  2246. u'email': u'commit-bot@chromium.org',
  2247. u'name': u'Commit Bot'
  2248. },
  2249. u'date': u'2017-03-15 20:08:45.000000000',
  2250. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046dc50b',
  2251. u'message': u'Patch Set 1:\n\nDry run: CQ is trying the patch...',
  2252. u'tag': u'autogenerated:cq:dry-run'
  2253. },
  2254. {
  2255. u'_revision_number': 1,
  2256. u'author': {
  2257. u'_account_id': 123,
  2258. u'email': u'tricium@serviceaccount.com',
  2259. u'name': u'Tricium'
  2260. },
  2261. u'date': u'2017-03-16 20:00:41.000000000',
  2262. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2263. u'message': u'(1 comment)',
  2264. u'tag': u'autogenerated:tricium',
  2265. },
  2266. {
  2267. u'_revision_number': 1,
  2268. u'author': {
  2269. u'_account_id': 123,
  2270. u'email': u'tricium@serviceaccount.com',
  2271. u'name': u'Tricium'
  2272. },
  2273. u'date': u'2017-03-16 20:00:41.000000000',
  2274. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d1234',
  2275. u'message': u'(1 comment)',
  2276. u'tag': u'autogenerated:tricium',
  2277. },
  2278. {
  2279. u'_revision_number': 2,
  2280. u'author': {
  2281. u'_account_id': 123,
  2282. u'email': u'tricium@serviceaccount.com',
  2283. u'name': u'reviewer'
  2284. },
  2285. u'date': u'2017-03-17 05:30:37.000000000',
  2286. u'tag': u'autogenerated:tricium',
  2287. u'id': u'f5a6c25ecbd3b3b54a43ae418ed97eff046d4568',
  2288. u'message': u'(1 comment)',
  2289. },
  2290. ]
  2291. }
  2292. self.calls = [
  2293. (('GetChangeComments', 'chromium-review.googlesource.com',
  2294. 'infra%2Finfra~1'), {}),
  2295. (('GetChangeRobotComments', 'chromium-review.googlesource.com',
  2296. 'infra%2Finfra~1'), {
  2297. 'codereview.settings': [
  2298. {
  2299. u'author': {u'email': u'tricium@serviceaccount.com'},
  2300. u'updated': u'2017-03-17 05:30:37.000000000',
  2301. u'robot_run_id': u'5565031076855808',
  2302. u'robot_id': u'Linter/Category',
  2303. u'tag': u'autogenerated:tricium',
  2304. u'patch_set': 2,
  2305. u'side': u'REVISION',
  2306. u'message': u'Linter warning message text',
  2307. u'line': 32,
  2308. },
  2309. ],
  2310. }),
  2311. ]
  2312. expected_comments_summary = [
  2313. git_cl._CommentSummary(date=datetime.datetime(2017, 3, 17, 5, 30, 37),
  2314. message=(
  2315. u'(1 comment)\n\ncodereview.settings\n'
  2316. u' PS2, Line 32: https://chromium-review.googlesource.com/'
  2317. u'c/1/2/codereview.settings#32\n'
  2318. u' Linter warning message text\n'),
  2319. sender=u'tricium@serviceaccount.com',
  2320. autogenerated=True, approval=False, disapproval=False)
  2321. ]
  2322. cl = git_cl.Changelist(
  2323. issue=1, branchref='refs/heads/foo')
  2324. self.assertEqual(cl.GetCommentsSummary(), expected_comments_summary)
  2325. def test_get_remote_url_with_mirror(self):
  2326. original_os_path_isdir = os.path.isdir
  2327. def selective_os_path_isdir_mock(path):
  2328. if path == '/cache/this-dir-exists':
  2329. return self._mocked_call('os.path.isdir', path)
  2330. return original_os_path_isdir(path)
  2331. mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
  2332. url = 'https://chromium.googlesource.com/my/repo'
  2333. self.mockGit.config['remote.origin.url'] = (
  2334. '/cache/this-dir-exists')
  2335. self.mockGit.config['/cache/this-dir-exists:remote.origin.url'] = (
  2336. url)
  2337. self.calls = [
  2338. (('os.path.isdir', '/cache/this-dir-exists'),
  2339. True),
  2340. ]
  2341. cl = git_cl.Changelist(issue=1)
  2342. self.assertEqual(cl.GetRemoteUrl(), url)
  2343. self.assertEqual(cl.GetRemoteUrl(), url) # Must be cached.
  2344. def test_get_remote_url_non_existing_mirror(self):
  2345. original_os_path_isdir = os.path.isdir
  2346. def selective_os_path_isdir_mock(path):
  2347. if path == '/cache/this-dir-doesnt-exist':
  2348. return self._mocked_call('os.path.isdir', path)
  2349. return original_os_path_isdir(path)
  2350. mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
  2351. mock.patch('logging.error',
  2352. lambda *a: self._mocked_call('logging.error', *a)).start()
  2353. self.mockGit.config['remote.origin.url'] = (
  2354. '/cache/this-dir-doesnt-exist')
  2355. self.calls = [
  2356. (('os.path.isdir', '/cache/this-dir-doesnt-exist'),
  2357. False),
  2358. (('logging.error',
  2359. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  2360. 'but it doesn\'t exist.', {
  2361. 'remote': 'origin',
  2362. 'branch': 'master',
  2363. 'url': '/cache/this-dir-doesnt-exist'}
  2364. ), None),
  2365. ]
  2366. cl = git_cl.Changelist(issue=1)
  2367. self.assertIsNone(cl.GetRemoteUrl())
  2368. def test_get_remote_url_misconfigured_mirror(self):
  2369. original_os_path_isdir = os.path.isdir
  2370. def selective_os_path_isdir_mock(path):
  2371. if path == '/cache/this-dir-exists':
  2372. return self._mocked_call('os.path.isdir', path)
  2373. return original_os_path_isdir(path)
  2374. mock.patch('os.path.isdir', selective_os_path_isdir_mock).start()
  2375. mock.patch('logging.error',
  2376. lambda *a: self._mocked_call('logging.error', *a)).start()
  2377. self.mockGit.config['remote.origin.url'] = (
  2378. '/cache/this-dir-exists')
  2379. self.calls = [
  2380. (('os.path.isdir', '/cache/this-dir-exists'), True),
  2381. (('logging.error',
  2382. 'Remote "%(remote)s" for branch "%(branch)s" points to '
  2383. '"%(cache_path)s", but it is misconfigured.\n'
  2384. '"%(cache_path)s" must be a git repo and must have a remote named '
  2385. '"%(remote)s" pointing to the git host.', {
  2386. 'remote': 'origin',
  2387. 'cache_path': '/cache/this-dir-exists',
  2388. 'branch': 'master'}
  2389. ), None),
  2390. ]
  2391. cl = git_cl.Changelist(issue=1)
  2392. self.assertIsNone(cl.GetRemoteUrl())
  2393. def test_gerrit_change_identifier_with_project(self):
  2394. self.mockGit.config['remote.origin.url'] = (
  2395. 'https://chromium.googlesource.com/a/my/repo.git/')
  2396. cl = git_cl.Changelist(issue=123456)
  2397. self.assertEqual(cl._GerritChangeIdentifier(), 'my%2Frepo~123456')
  2398. def test_gerrit_change_identifier_without_project(self):
  2399. mock.patch('logging.error',
  2400. lambda *a: self._mocked_call('logging.error', *a)).start()
  2401. self.calls = [
  2402. (('logging.error',
  2403. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  2404. 'but it doesn\'t exist.', {
  2405. 'remote': 'origin',
  2406. 'branch': 'master',
  2407. 'url': ''}
  2408. ), None),
  2409. ]
  2410. cl = git_cl.Changelist(issue=123456)
  2411. self.assertEqual(cl._GerritChangeIdentifier(), '123456')
  2412. class ChangelistTest(unittest.TestCase):
  2413. def setUp(self):
  2414. super(ChangelistTest, self).setUp()
  2415. mock.patch('gclient_utils.FileRead').start()
  2416. mock.patch('gclient_utils.FileWrite').start()
  2417. mock.patch('gclient_utils.temporary_file', TemporaryFileMock()).start()
  2418. mock.patch(
  2419. 'git_cl.Changelist.GetCodereviewServer',
  2420. return_value='https://chromium-review.googlesource.com').start()
  2421. mock.patch('git_cl.Changelist.GetAuthor', return_value='author').start()
  2422. mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
  2423. mock.patch('git_cl.Changelist.GetPatchset', return_value=7).start()
  2424. mock.patch('git_cl.PRESUBMIT_SUPPORT', 'PRESUBMIT_SUPPORT').start()
  2425. mock.patch('git_cl.Settings.GetRoot', return_value='root').start()
  2426. mock.patch('git_cl.time_time').start()
  2427. mock.patch('metrics.collector').start()
  2428. mock.patch('subprocess2.Popen').start()
  2429. mock.patch('git_cl.Changelist._GetGerritProject',
  2430. return_value='https://chromium-review.googlesource.com').start()
  2431. self.addCleanup(mock.patch.stopall)
  2432. self.temp_count = 0
  2433. def testRunHook(self):
  2434. expected_results = {
  2435. 'more_cc': ['more@example.com', 'cc@example.com'],
  2436. 'should_continue': True,
  2437. }
  2438. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  2439. git_cl.time_time.side_effect = [100, 200]
  2440. mockProcess = mock.Mock()
  2441. mockProcess.wait.return_value = 0
  2442. subprocess2.Popen.return_value = mockProcess
  2443. cl = git_cl.Changelist()
  2444. results = cl.RunHook(
  2445. committing=True,
  2446. may_prompt=True,
  2447. verbose=2,
  2448. parallel=True,
  2449. upstream='upstream',
  2450. description='description',
  2451. all_files=True,
  2452. resultdb=False)
  2453. self.assertEqual(expected_results, results)
  2454. subprocess2.Popen.assert_called_once_with([
  2455. 'vpython', 'PRESUBMIT_SUPPORT',
  2456. '--root', 'root',
  2457. '--upstream', 'upstream',
  2458. '--verbose', '--verbose',
  2459. '--author', 'author',
  2460. '--gerrit_url', 'https://chromium-review.googlesource.com',
  2461. '--issue', '123456',
  2462. '--patchset', '7',
  2463. '--commit',
  2464. '--may_prompt',
  2465. '--parallel',
  2466. '--all_files',
  2467. '--json_output', '/tmp/fake-temp2',
  2468. '--description_file', '/tmp/fake-temp1',
  2469. '--gerrit_project', 'https://chromium-review.googlesource.com',
  2470. ])
  2471. gclient_utils.FileWrite.assert_called_once_with(
  2472. '/tmp/fake-temp1', 'description')
  2473. metrics.collector.add_repeated('sub_commands', {
  2474. 'command': 'presubmit',
  2475. 'execution_time': 100,
  2476. 'exit_code': 0,
  2477. })
  2478. def testRunHook_FewerOptions(self):
  2479. expected_results = {
  2480. 'more_cc': ['more@example.com', 'cc@example.com'],
  2481. 'should_continue': True,
  2482. }
  2483. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  2484. git_cl.time_time.side_effect = [100, 200]
  2485. mockProcess = mock.Mock()
  2486. mockProcess.wait.return_value = 0
  2487. subprocess2.Popen.return_value = mockProcess
  2488. git_cl.Changelist.GetAuthor.return_value = None
  2489. git_cl.Changelist.GetIssue.return_value = None
  2490. git_cl.Changelist.GetPatchset.return_value = None
  2491. git_cl.Changelist.GetCodereviewServer.return_value = None
  2492. cl = git_cl.Changelist()
  2493. results = cl.RunHook(
  2494. committing=False,
  2495. may_prompt=False,
  2496. verbose=0,
  2497. parallel=False,
  2498. upstream='upstream',
  2499. description='description',
  2500. all_files=False,
  2501. resultdb=False)
  2502. self.assertEqual(expected_results, results)
  2503. subprocess2.Popen.assert_called_once_with([
  2504. 'vpython', 'PRESUBMIT_SUPPORT',
  2505. '--root', 'root',
  2506. '--upstream', 'upstream',
  2507. '--upload',
  2508. '--json_output', '/tmp/fake-temp2',
  2509. '--description_file', '/tmp/fake-temp1',
  2510. '--gerrit_project', 'https://chromium-review.googlesource.com',
  2511. ])
  2512. gclient_utils.FileWrite.assert_called_once_with(
  2513. '/tmp/fake-temp1', 'description')
  2514. metrics.collector.add_repeated('sub_commands', {
  2515. 'command': 'presubmit',
  2516. 'execution_time': 100,
  2517. 'exit_code': 0,
  2518. })
  2519. def testRunHook_FewerOptionsResultDB(self):
  2520. expected_results = {
  2521. 'more_cc': ['more@example.com', 'cc@example.com'],
  2522. 'should_continue': True,
  2523. }
  2524. gclient_utils.FileRead.return_value = json.dumps(expected_results)
  2525. git_cl.time_time.side_effect = [100, 200]
  2526. mockProcess = mock.Mock()
  2527. mockProcess.wait.return_value = 0
  2528. subprocess2.Popen.return_value = mockProcess
  2529. git_cl.Changelist.GetAuthor.return_value = None
  2530. git_cl.Changelist.GetIssue.return_value = None
  2531. git_cl.Changelist.GetPatchset.return_value = None
  2532. git_cl.Changelist.GetCodereviewServer.return_value = None
  2533. cl = git_cl.Changelist()
  2534. results = cl.RunHook(
  2535. committing=False,
  2536. may_prompt=False,
  2537. verbose=0,
  2538. parallel=False,
  2539. upstream='upstream',
  2540. description='description',
  2541. all_files=False,
  2542. resultdb=True,
  2543. realm='chromium:public')
  2544. self.assertEqual(expected_results, results)
  2545. subprocess2.Popen.assert_called_once_with([
  2546. 'rdb', 'stream', '-new', '-realm', 'chromium:public', '--',
  2547. 'vpython', 'PRESUBMIT_SUPPORT',
  2548. '--root', 'root',
  2549. '--upstream', 'upstream',
  2550. '--upload',
  2551. '--json_output', '/tmp/fake-temp2',
  2552. '--description_file', '/tmp/fake-temp1',
  2553. '--gerrit_project', 'https://chromium-review.googlesource.com',
  2554. ])
  2555. @mock.patch('sys.exit', side_effect=SystemExitMock)
  2556. def testRunHook_Failure(self, _mock):
  2557. git_cl.time_time.side_effect = [100, 200]
  2558. mockProcess = mock.Mock()
  2559. mockProcess.wait.return_value = 2
  2560. subprocess2.Popen.return_value = mockProcess
  2561. cl = git_cl.Changelist()
  2562. with self.assertRaises(SystemExitMock):
  2563. cl.RunHook(
  2564. committing=True,
  2565. may_prompt=True,
  2566. verbose=2,
  2567. parallel=True,
  2568. upstream='upstream',
  2569. description='description',
  2570. all_files=True,
  2571. resultdb=False)
  2572. sys.exit.assert_called_once_with(2)
  2573. def testRunPostUploadHook(self):
  2574. cl = git_cl.Changelist()
  2575. cl.RunPostUploadHook(2, 'upstream', 'description')
  2576. subprocess2.Popen.assert_called_once_with([
  2577. 'vpython', 'PRESUBMIT_SUPPORT',
  2578. '--root', 'root',
  2579. '--upstream', 'upstream',
  2580. '--verbose', '--verbose',
  2581. '--author', 'author',
  2582. '--gerrit_url', 'https://chromium-review.googlesource.com',
  2583. '--issue', '123456',
  2584. '--patchset', '7',
  2585. '--post_upload',
  2586. '--description_file', '/tmp/fake-temp1',
  2587. ])
  2588. gclient_utils.FileWrite.assert_called_once_with(
  2589. '/tmp/fake-temp1', 'description')
  2590. class CMDTestCaseBase(unittest.TestCase):
  2591. _STATUSES = [
  2592. 'STATUS_UNSPECIFIED', 'SCHEDULED', 'STARTED', 'SUCCESS', 'FAILURE',
  2593. 'INFRA_FAILURE', 'CANCELED',
  2594. ]
  2595. _CHANGE_DETAIL = {
  2596. 'project': 'depot_tools',
  2597. 'status': 'OPEN',
  2598. 'owner': {'email': 'owner@e.mail'},
  2599. 'current_revision': 'beeeeeef',
  2600. 'revisions': {
  2601. 'deadbeaf': {'_number': 6},
  2602. 'beeeeeef': {
  2603. '_number': 7,
  2604. 'fetch': {'http': {
  2605. 'url': 'https://chromium.googlesource.com/depot_tools',
  2606. 'ref': 'refs/changes/56/123456/7'
  2607. }},
  2608. },
  2609. },
  2610. }
  2611. _DEFAULT_RESPONSE = {
  2612. 'builds': [{
  2613. 'id': str(100 + idx),
  2614. 'builder': {
  2615. 'project': 'chromium',
  2616. 'bucket': 'try',
  2617. 'builder': 'bot_' + status.lower(),
  2618. },
  2619. 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
  2620. 'tags': [],
  2621. 'status': status,
  2622. } for idx, status in enumerate(_STATUSES)]
  2623. }
  2624. def setUp(self):
  2625. super(CMDTestCaseBase, self).setUp()
  2626. mock.patch('git_cl.sys.stdout', StringIO()).start()
  2627. mock.patch('git_cl.uuid.uuid4', return_value='uuid4').start()
  2628. mock.patch('git_cl.Changelist.GetIssue', return_value=123456).start()
  2629. mock.patch(
  2630. 'git_cl.Changelist.GetCodereviewServer',
  2631. return_value='https://chromium-review.googlesource.com').start()
  2632. mock.patch(
  2633. 'git_cl.Changelist._GetGerritHost',
  2634. return_value='chromium-review.googlesource.com').start()
  2635. mock.patch(
  2636. 'git_cl.Changelist.GetMostRecentPatchset',
  2637. return_value=7).start()
  2638. mock.patch(
  2639. 'git_cl.Changelist.GetRemoteUrl',
  2640. return_value='https://chromium.googlesource.com/depot_tools').start()
  2641. mock.patch(
  2642. 'auth.Authenticator',
  2643. return_value=AuthenticatorMock()).start()
  2644. mock.patch(
  2645. 'gerrit_util.GetChangeDetail',
  2646. return_value=self._CHANGE_DETAIL).start()
  2647. mock.patch(
  2648. 'git_cl._call_buildbucket',
  2649. return_value = self._DEFAULT_RESPONSE).start()
  2650. mock.patch('git_common.is_dirty_git_tree', return_value=False).start()
  2651. self.addCleanup(mock.patch.stopall)
  2652. class CMDPresubmitTestCase(CMDTestCaseBase):
  2653. def setUp(self):
  2654. super(CMDPresubmitTestCase, self).setUp()
  2655. mock.patch(
  2656. 'git_cl.Changelist.GetCommonAncestorWithUpstream',
  2657. return_value='upstream').start()
  2658. mock.patch(
  2659. 'git_cl.Changelist.FetchDescription',
  2660. return_value='fetch description').start()
  2661. mock.patch(
  2662. 'git_cl._create_description_from_log',
  2663. return_value='get description').start()
  2664. mock.patch('git_cl.Changelist.RunHook').start()
  2665. def testDefaultCase(self):
  2666. self.assertEqual(0, git_cl.main(['presubmit']))
  2667. git_cl.Changelist.RunHook.assert_called_once_with(
  2668. committing=True,
  2669. may_prompt=False,
  2670. verbose=0,
  2671. parallel=None,
  2672. upstream='upstream',
  2673. description='fetch description',
  2674. all_files=None,
  2675. resultdb=None,
  2676. realm=None)
  2677. def testNoIssue(self):
  2678. git_cl.Changelist.GetIssue.return_value = None
  2679. self.assertEqual(0, git_cl.main(['presubmit']))
  2680. git_cl.Changelist.RunHook.assert_called_once_with(
  2681. committing=True,
  2682. may_prompt=False,
  2683. verbose=0,
  2684. parallel=None,
  2685. upstream='upstream',
  2686. description='get description',
  2687. all_files=None,
  2688. resultdb=None,
  2689. realm=None)
  2690. def testCustomBranch(self):
  2691. self.assertEqual(0, git_cl.main(['presubmit', 'custom_branch']))
  2692. git_cl.Changelist.RunHook.assert_called_once_with(
  2693. committing=True,
  2694. may_prompt=False,
  2695. verbose=0,
  2696. parallel=None,
  2697. upstream='custom_branch',
  2698. description='fetch description',
  2699. all_files=None,
  2700. resultdb=None,
  2701. realm=None)
  2702. def testOptions(self):
  2703. self.assertEqual(
  2704. 0, git_cl.main(['presubmit', '-v', '-v', '--all', '--parallel', '-u',
  2705. '--resultdb', '--realm', 'chromium:public']))
  2706. git_cl.Changelist.RunHook.assert_called_once_with(
  2707. committing=False,
  2708. may_prompt=False,
  2709. verbose=2,
  2710. parallel=True,
  2711. upstream='upstream',
  2712. description='fetch description',
  2713. all_files=True,
  2714. resultdb=True,
  2715. realm='chromium:public')
  2716. class CMDTryResultsTestCase(CMDTestCaseBase):
  2717. _DEFAULT_REQUEST = {
  2718. 'predicate': {
  2719. "gerritChanges": [{
  2720. "project": "depot_tools",
  2721. "host": "chromium-review.googlesource.com",
  2722. "patchset": 7,
  2723. "change": 123456,
  2724. }],
  2725. },
  2726. 'fields': ('builds.*.id,builds.*.builder,builds.*.status' +
  2727. ',builds.*.createTime,builds.*.tags'),
  2728. }
  2729. def testNoJobs(self):
  2730. git_cl._call_buildbucket.return_value = {}
  2731. self.assertEqual(0, git_cl.main(['try-results']))
  2732. self.assertEqual('No tryjobs scheduled.\n', sys.stdout.getvalue())
  2733. git_cl._call_buildbucket.assert_called_once_with(
  2734. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2735. self._DEFAULT_REQUEST)
  2736. def testPrintToStdout(self):
  2737. self.assertEqual(0, git_cl.main(['try-results']))
  2738. self.assertEqual([
  2739. 'Successes:',
  2740. ' bot_success https://ci.chromium.org/b/103',
  2741. 'Infra Failures:',
  2742. ' bot_infra_failure https://ci.chromium.org/b/105',
  2743. 'Failures:',
  2744. ' bot_failure https://ci.chromium.org/b/104',
  2745. 'Canceled:',
  2746. ' bot_canceled ',
  2747. 'Started:',
  2748. ' bot_started https://ci.chromium.org/b/102',
  2749. 'Scheduled:',
  2750. ' bot_scheduled id=101',
  2751. 'Other:',
  2752. ' bot_status_unspecified id=100',
  2753. 'Total: 7 tryjobs',
  2754. ], sys.stdout.getvalue().splitlines())
  2755. git_cl._call_buildbucket.assert_called_once_with(
  2756. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2757. self._DEFAULT_REQUEST)
  2758. def testPrintToStdoutWithMasters(self):
  2759. self.assertEqual(0, git_cl.main(['try-results', '--print-master']))
  2760. self.assertEqual([
  2761. 'Successes:',
  2762. ' try bot_success https://ci.chromium.org/b/103',
  2763. 'Infra Failures:',
  2764. ' try bot_infra_failure https://ci.chromium.org/b/105',
  2765. 'Failures:',
  2766. ' try bot_failure https://ci.chromium.org/b/104',
  2767. 'Canceled:',
  2768. ' try bot_canceled ',
  2769. 'Started:',
  2770. ' try bot_started https://ci.chromium.org/b/102',
  2771. 'Scheduled:',
  2772. ' try bot_scheduled id=101',
  2773. 'Other:',
  2774. ' try bot_status_unspecified id=100',
  2775. 'Total: 7 tryjobs',
  2776. ], sys.stdout.getvalue().splitlines())
  2777. git_cl._call_buildbucket.assert_called_once_with(
  2778. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2779. self._DEFAULT_REQUEST)
  2780. @mock.patch('git_cl.write_json')
  2781. def testWriteToJson(self, mockJsonDump):
  2782. self.assertEqual(0, git_cl.main(['try-results', '--json', 'file.json']))
  2783. git_cl._call_buildbucket.assert_called_once_with(
  2784. mock.ANY, 'cr-buildbucket.appspot.com', 'SearchBuilds',
  2785. self._DEFAULT_REQUEST)
  2786. mockJsonDump.assert_called_once_with(
  2787. 'file.json', self._DEFAULT_RESPONSE['builds'])
  2788. def test_filter_failed_for_one_simple(self):
  2789. self.assertEqual([], git_cl._filter_failed_for_retry([]))
  2790. self.assertEqual(
  2791. [
  2792. ('chromium', 'try', 'bot_failure'),
  2793. ('chromium', 'try', 'bot_infra_failure'),
  2794. ],
  2795. git_cl._filter_failed_for_retry(self._DEFAULT_RESPONSE['builds']))
  2796. def test_filter_failed_for_retry_many_builds(self):
  2797. def _build(name, created_sec, status, experimental=False):
  2798. assert 0 <= created_sec < 100, created_sec
  2799. b = {
  2800. 'id': 112112,
  2801. 'builder': {
  2802. 'project': 'chromium',
  2803. 'bucket': 'try',
  2804. 'builder': name,
  2805. },
  2806. 'createTime': '2019-10-09T08:00:%02d.854286Z' % created_sec,
  2807. 'status': status,
  2808. 'tags': [],
  2809. }
  2810. if experimental:
  2811. b['tags'].append({'key': 'cq_experimental', 'value': 'true'})
  2812. return b
  2813. builds = [
  2814. _build('flaky-last-green', 1, 'FAILURE'),
  2815. _build('flaky-last-green', 2, 'SUCCESS'),
  2816. _build('flaky', 1, 'SUCCESS'),
  2817. _build('flaky', 2, 'FAILURE'),
  2818. _build('running', 1, 'FAILED'),
  2819. _build('running', 2, 'SCHEDULED'),
  2820. _build('yep-still-running', 1, 'STARTED'),
  2821. _build('yep-still-running', 2, 'FAILURE'),
  2822. _build('cq-experimental', 1, 'SUCCESS', experimental=True),
  2823. _build('cq-experimental', 2, 'FAILURE', experimental=True),
  2824. # Simulate experimental in CQ builder, which developer decided
  2825. # to retry manually which resulted in 2nd build non-experimental.
  2826. _build('sometimes-experimental', 1, 'FAILURE', experimental=True),
  2827. _build('sometimes-experimental', 2, 'FAILURE', experimental=False),
  2828. ]
  2829. builds.sort(key=lambda b: b['status']) # ~deterministic shuffle.
  2830. self.assertEqual(
  2831. [
  2832. ('chromium', 'try', 'flaky'),
  2833. ('chromium', 'try', 'sometimes-experimental'),
  2834. ],
  2835. git_cl._filter_failed_for_retry(builds))
  2836. class CMDTryTestCase(CMDTestCaseBase):
  2837. @mock.patch('git_cl.Changelist.SetCQState')
  2838. def testSetCQDryRunByDefault(self, mockSetCQState):
  2839. mockSetCQState.return_value = 0
  2840. self.assertEqual(0, git_cl.main(['try']))
  2841. git_cl.Changelist.SetCQState.assert_called_with(git_cl._CQState.DRY_RUN)
  2842. self.assertEqual(
  2843. sys.stdout.getvalue(),
  2844. 'Scheduling CQ dry run on: '
  2845. 'https://chromium-review.googlesource.com/123456\n')
  2846. @mock.patch('git_cl._call_buildbucket')
  2847. def testScheduleOnBuildbucket(self, mockCallBuildbucket):
  2848. mockCallBuildbucket.return_value = {}
  2849. self.assertEqual(0, git_cl.main([
  2850. 'try', '-B', 'luci.chromium.try', '-b', 'win',
  2851. '-p', 'key=val', '-p', 'json=[{"a":1}, null]']))
  2852. self.assertIn(
  2853. 'Scheduling jobs on:\n'
  2854. ' chromium/try: win',
  2855. git_cl.sys.stdout.getvalue())
  2856. expected_request = {
  2857. "requests": [{
  2858. "scheduleBuild": {
  2859. "requestId": "uuid4",
  2860. "builder": {
  2861. "project": "chromium",
  2862. "builder": "win",
  2863. "bucket": "try",
  2864. },
  2865. "gerritChanges": [{
  2866. "project": "depot_tools",
  2867. "host": "chromium-review.googlesource.com",
  2868. "patchset": 7,
  2869. "change": 123456,
  2870. }],
  2871. "properties": {
  2872. "category": "git_cl_try",
  2873. "json": [{"a": 1}, None],
  2874. "key": "val",
  2875. },
  2876. "tags": [
  2877. {"value": "win", "key": "builder"},
  2878. {"value": "git_cl_try", "key": "user_agent"},
  2879. ],
  2880. },
  2881. }],
  2882. }
  2883. mockCallBuildbucket.assert_called_with(
  2884. mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
  2885. @mock.patch('git_cl._call_buildbucket')
  2886. def testScheduleOnBuildbucketWithRevision(self, mockCallBuildbucket):
  2887. mockCallBuildbucket.return_value = {}
  2888. self.assertEqual(0, git_cl.main([
  2889. 'try', '-B', 'luci.chromium.try', '-b', 'win', '-b', 'linux',
  2890. '-p', 'key=val', '-p', 'json=[{"a":1}, null]',
  2891. '-r', 'beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef']))
  2892. self.assertIn(
  2893. 'Scheduling jobs on:\n'
  2894. ' chromium/try: linux\n'
  2895. ' chromium/try: win',
  2896. git_cl.sys.stdout.getvalue())
  2897. expected_request = {
  2898. "requests": [{
  2899. "scheduleBuild": {
  2900. "requestId": "uuid4",
  2901. "builder": {
  2902. "project": "chromium",
  2903. "builder": "linux",
  2904. "bucket": "try",
  2905. },
  2906. "gerritChanges": [{
  2907. "project": "depot_tools",
  2908. "host": "chromium-review.googlesource.com",
  2909. "patchset": 7,
  2910. "change": 123456,
  2911. }],
  2912. "properties": {
  2913. "category": "git_cl_try",
  2914. "json": [{"a": 1}, None],
  2915. "key": "val",
  2916. },
  2917. "tags": [
  2918. {"value": "linux", "key": "builder"},
  2919. {"value": "git_cl_try", "key": "user_agent"},
  2920. ],
  2921. "gitilesCommit": {
  2922. "host": "chromium-review.googlesource.com",
  2923. "project": "depot_tools",
  2924. "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
  2925. }
  2926. },
  2927. },
  2928. {
  2929. "scheduleBuild": {
  2930. "requestId": "uuid4",
  2931. "builder": {
  2932. "project": "chromium",
  2933. "builder": "win",
  2934. "bucket": "try",
  2935. },
  2936. "gerritChanges": [{
  2937. "project": "depot_tools",
  2938. "host": "chromium-review.googlesource.com",
  2939. "patchset": 7,
  2940. "change": 123456,
  2941. }],
  2942. "properties": {
  2943. "category": "git_cl_try",
  2944. "json": [{"a": 1}, None],
  2945. "key": "val",
  2946. },
  2947. "tags": [
  2948. {"value": "win", "key": "builder"},
  2949. {"value": "git_cl_try", "key": "user_agent"},
  2950. ],
  2951. "gitilesCommit": {
  2952. "host": "chromium-review.googlesource.com",
  2953. "project": "depot_tools",
  2954. "id": "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
  2955. }
  2956. },
  2957. }],
  2958. }
  2959. mockCallBuildbucket.assert_called_with(
  2960. mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
  2961. @mock.patch('sys.stderr', StringIO())
  2962. def testScheduleOnBuildbucket_WrongBucket(self):
  2963. with self.assertRaises(SystemExit):
  2964. git_cl.main([
  2965. 'try', '-B', 'not-a-bucket', '-b', 'win',
  2966. '-p', 'key=val', '-p', 'json=[{"a":1}, null]'])
  2967. self.assertIn(
  2968. 'Invalid bucket: not-a-bucket.',
  2969. sys.stderr.getvalue())
  2970. @mock.patch('git_cl._call_buildbucket')
  2971. @mock.patch('git_cl._fetch_tryjobs')
  2972. def testScheduleOnBuildbucketRetryFailed(
  2973. self, mockFetchTryJobs, mockCallBuildbucket):
  2974. git_cl._fetch_tryjobs.side_effect = lambda *_, **kw: {
  2975. 7: [],
  2976. 6: [{
  2977. 'id': 112112,
  2978. 'builder': {
  2979. 'project': 'chromium',
  2980. 'bucket': 'try',
  2981. 'builder': 'linux', },
  2982. 'createTime': '2019-10-09T08:00:01.854286Z',
  2983. 'tags': [],
  2984. 'status': 'FAILURE', }], }[kw['patchset']]
  2985. mockCallBuildbucket.return_value = {}
  2986. self.assertEqual(0, git_cl.main(['try', '--retry-failed']))
  2987. self.assertIn(
  2988. 'Scheduling jobs on:\n'
  2989. ' chromium/try: linux',
  2990. git_cl.sys.stdout.getvalue())
  2991. expected_request = {
  2992. "requests": [{
  2993. "scheduleBuild": {
  2994. "requestId": "uuid4",
  2995. "builder": {
  2996. "project": "chromium",
  2997. "bucket": "try",
  2998. "builder": "linux",
  2999. },
  3000. "gerritChanges": [{
  3001. "project": "depot_tools",
  3002. "host": "chromium-review.googlesource.com",
  3003. "patchset": 7,
  3004. "change": 123456,
  3005. }],
  3006. "properties": {
  3007. "category": "git_cl_try",
  3008. },
  3009. "tags": [
  3010. {"value": "linux", "key": "builder"},
  3011. {"value": "git_cl_try", "key": "user_agent"},
  3012. {"value": "1", "key": "retry_failed"},
  3013. ],
  3014. },
  3015. }],
  3016. }
  3017. mockCallBuildbucket.assert_called_with(
  3018. mock.ANY, 'cr-buildbucket.appspot.com', 'Batch', expected_request)
  3019. def test_parse_bucket(self):
  3020. test_cases = [
  3021. {
  3022. 'bucket': 'chromium/try',
  3023. 'result': ('chromium', 'try'),
  3024. },
  3025. {
  3026. 'bucket': 'luci.chromium.try',
  3027. 'result': ('chromium', 'try'),
  3028. 'has_warning': True,
  3029. },
  3030. {
  3031. 'bucket': 'skia.primary',
  3032. 'result': ('skia', 'skia.primary'),
  3033. 'has_warning': True,
  3034. },
  3035. {
  3036. 'bucket': 'not-a-bucket',
  3037. 'result': (None, None),
  3038. },
  3039. ]
  3040. for test_case in test_cases:
  3041. git_cl.sys.stdout.truncate(0)
  3042. self.assertEqual(
  3043. test_case['result'], git_cl._parse_bucket(test_case['bucket']))
  3044. if test_case.get('has_warning'):
  3045. expected_warning = 'WARNING Please use %s/%s to specify the bucket' % (
  3046. test_case['result'])
  3047. self.assertIn(expected_warning, git_cl.sys.stdout.getvalue())
  3048. class CMDUploadTestCase(CMDTestCaseBase):
  3049. def setUp(self):
  3050. super(CMDUploadTestCase, self).setUp()
  3051. mock.patch('git_cl._fetch_tryjobs').start()
  3052. mock.patch('git_cl._trigger_tryjobs', return_value={}).start()
  3053. mock.patch('git_cl.Changelist.CMDUpload', return_value=0).start()
  3054. mock.patch('git_cl.Settings.GetRoot', return_value='').start()
  3055. mock.patch(
  3056. 'git_cl.Settings.GetSquashGerritUploads',
  3057. return_value=True).start()
  3058. self.addCleanup(mock.patch.stopall)
  3059. def testWarmUpChangeDetailCache(self):
  3060. self.assertEqual(0, git_cl.main(['upload']))
  3061. gerrit_util.GetChangeDetail.assert_called_once_with(
  3062. 'chromium-review.googlesource.com', 'depot_tools~123456',
  3063. frozenset([
  3064. 'LABELS', 'CURRENT_REVISION', 'DETAILED_ACCOUNTS',
  3065. 'CURRENT_COMMIT']))
  3066. def testUploadRetryFailed(self):
  3067. # This test mocks out the actual upload part, and just asserts that after
  3068. # upload, if --retry-failed is added, then the tool will fetch try jobs
  3069. # from the previous patchset and trigger the right builders on the latest
  3070. # patchset.
  3071. git_cl._fetch_tryjobs.side_effect = [
  3072. # Latest patchset: No builds.
  3073. [],
  3074. # Patchset before latest: Some builds.
  3075. [{
  3076. 'id': str(100 + idx),
  3077. 'builder': {
  3078. 'project': 'chromium',
  3079. 'bucket': 'try',
  3080. 'builder': 'bot_' + status.lower(),
  3081. },
  3082. 'createTime': '2019-10-09T08:00:0%d.854286Z' % (idx % 10),
  3083. 'tags': [],
  3084. 'status': status,
  3085. } for idx, status in enumerate(self._STATUSES)],
  3086. ]
  3087. self.assertEqual(0, git_cl.main(['upload', '--retry-failed']))
  3088. self.assertEqual([
  3089. mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=7),
  3090. mock.call(mock.ANY, 'cr-buildbucket.appspot.com', patchset=6),
  3091. ], git_cl._fetch_tryjobs.mock_calls)
  3092. expected_buckets = [
  3093. ('chromium', 'try', 'bot_failure'),
  3094. ('chromium', 'try', 'bot_infra_failure'),
  3095. ]
  3096. git_cl._trigger_tryjobs.assert_called_once_with(mock.ANY, expected_buckets,
  3097. mock.ANY, 8)
  3098. class MakeRequestsHelperTestCase(unittest.TestCase):
  3099. def exampleGerritChange(self):
  3100. return {
  3101. 'host': 'chromium-review.googlesource.com',
  3102. 'project': 'depot_tools',
  3103. 'change': 1,
  3104. 'patchset': 2,
  3105. }
  3106. def testMakeRequestsHelperNoOptions(self):
  3107. # Basic test for the helper function _make_tryjob_schedule_requests;
  3108. # it shouldn't throw AttributeError even when options doesn't have any
  3109. # of the expected values; it will use default option values.
  3110. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  3111. jobs = [('chromium', 'try', 'my-builder')]
  3112. options = optparse.Values()
  3113. requests = git_cl._make_tryjob_schedule_requests(
  3114. changelist, jobs, options, patchset=None)
  3115. # requestId is non-deterministic. Just assert that it's there and has
  3116. # a particular length.
  3117. self.assertEqual(len(requests[0]['scheduleBuild'].pop('requestId')), 36)
  3118. self.assertEqual(requests, [{
  3119. 'scheduleBuild': {
  3120. 'builder': {
  3121. 'bucket': 'try',
  3122. 'builder': 'my-builder',
  3123. 'project': 'chromium'
  3124. },
  3125. 'gerritChanges': [self.exampleGerritChange()],
  3126. 'properties': {
  3127. 'category': 'git_cl_try'
  3128. },
  3129. 'tags': [{
  3130. 'key': 'builder',
  3131. 'value': 'my-builder'
  3132. }, {
  3133. 'key': 'user_agent',
  3134. 'value': 'git_cl_try'
  3135. }]
  3136. }
  3137. }])
  3138. def testMakeRequestsHelperPresubmitSetsDryRunProperty(self):
  3139. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  3140. jobs = [('chromium', 'try', 'presubmit')]
  3141. options = optparse.Values()
  3142. requests = git_cl._make_tryjob_schedule_requests(
  3143. changelist, jobs, options, patchset=None)
  3144. self.assertEqual(requests[0]['scheduleBuild']['properties'], {
  3145. 'category': 'git_cl_try',
  3146. 'dry_run': 'true'
  3147. })
  3148. def testMakeRequestsHelperRevisionSet(self):
  3149. # Gitiles commit is specified when revision is in options.
  3150. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  3151. jobs = [('chromium', 'try', 'my-builder')]
  3152. options = optparse.Values({'revision': 'ba5eba11'})
  3153. requests = git_cl._make_tryjob_schedule_requests(
  3154. changelist, jobs, options, patchset=None)
  3155. self.assertEqual(
  3156. requests[0]['scheduleBuild']['gitilesCommit'], {
  3157. 'host': 'chromium-review.googlesource.com',
  3158. 'id': 'ba5eba11',
  3159. 'project': 'depot_tools'
  3160. })
  3161. def testMakeRequestsHelperRetryFailedSet(self):
  3162. # An extra tag is added when retry_failed is in options.
  3163. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  3164. jobs = [('chromium', 'try', 'my-builder')]
  3165. options = optparse.Values({'retry_failed': 'true'})
  3166. requests = git_cl._make_tryjob_schedule_requests(
  3167. changelist, jobs, options, patchset=None)
  3168. self.assertEqual(
  3169. requests[0]['scheduleBuild']['tags'], [
  3170. {
  3171. 'key': 'builder',
  3172. 'value': 'my-builder'
  3173. },
  3174. {
  3175. 'key': 'user_agent',
  3176. 'value': 'git_cl_try'
  3177. },
  3178. {
  3179. 'key': 'retry_failed',
  3180. 'value': '1'
  3181. }
  3182. ])
  3183. def testMakeRequestsHelperCategorySet(self):
  3184. # The category property can be overridden with options.
  3185. changelist = ChangelistMock(gerrit_change=self.exampleGerritChange())
  3186. jobs = [('chromium', 'try', 'my-builder')]
  3187. options = optparse.Values({'category': 'my-special-category'})
  3188. requests = git_cl._make_tryjob_schedule_requests(
  3189. changelist, jobs, options, patchset=None)
  3190. self.assertEqual(requests[0]['scheduleBuild']['properties'],
  3191. {'category': 'my-special-category'})
  3192. class CMDFormatTestCase(unittest.TestCase):
  3193. def setUp(self):
  3194. super(CMDFormatTestCase, self).setUp()
  3195. mock.patch('git_cl.RunCommand').start()
  3196. mock.patch('clang_format.FindClangFormatToolInChromiumTree').start()
  3197. mock.patch('clang_format.FindClangFormatScriptInChromiumTree').start()
  3198. mock.patch('git_cl.settings').start()
  3199. self._top_dir = tempfile.mkdtemp()
  3200. self.addCleanup(mock.patch.stopall)
  3201. def tearDown(self):
  3202. shutil.rmtree(self._top_dir)
  3203. super(CMDFormatTestCase, self).tearDown()
  3204. def _make_temp_file(self, fname, contents):
  3205. with open(os.path.join(self._top_dir, fname), 'w') as tf:
  3206. tf.write('\n'.join(contents))
  3207. def _make_yapfignore(self, contents):
  3208. self._make_temp_file('.yapfignore', contents)
  3209. def _check_yapf_filtering(self, files, expected):
  3210. self.assertEqual(expected, git_cl._FilterYapfIgnoredFiles(
  3211. files, git_cl._GetYapfIgnorePatterns(self._top_dir)))
  3212. def _run_command_mock(self, return_value):
  3213. def f(*args, **kwargs):
  3214. if 'stdin' in kwargs:
  3215. self.assertIsInstance(kwargs['stdin'], bytes)
  3216. return return_value
  3217. return f
  3218. def testClangFormatDiffFull(self):
  3219. self._make_temp_file('test.cc', ['// test'])
  3220. git_cl.settings.GetFormatFullByDefault.return_value = False
  3221. diff_file = [os.path.join(self._top_dir, 'test.cc')]
  3222. mock_opts = mock.Mock(full=True, dry_run=True, diff=False)
  3223. # Diff
  3224. git_cl.RunCommand.side_effect = self._run_command_mock(' // test')
  3225. return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
  3226. self._top_dir, 'HEAD')
  3227. self.assertEqual(2, return_value)
  3228. # No diff
  3229. git_cl.RunCommand.side_effect = self._run_command_mock('// test')
  3230. return_value = git_cl._RunClangFormatDiff(mock_opts, diff_file,
  3231. self._top_dir, 'HEAD')
  3232. self.assertEqual(0, return_value)
  3233. def testClangFormatDiff(self):
  3234. git_cl.settings.GetFormatFullByDefault.return_value = False
  3235. # A valid file is required, so use this test.
  3236. clang_format.FindClangFormatToolInChromiumTree.return_value = __file__
  3237. mock_opts = mock.Mock(full=False, dry_run=True, diff=False)
  3238. # Diff
  3239. git_cl.RunCommand.side_effect = self._run_command_mock('error')
  3240. return_value = git_cl._RunClangFormatDiff(
  3241. mock_opts, ['.'], self._top_dir, 'HEAD')
  3242. self.assertEqual(2, return_value)
  3243. # No diff
  3244. git_cl.RunCommand.side_effect = self._run_command_mock('')
  3245. return_value = git_cl._RunClangFormatDiff(mock_opts, ['.'], self._top_dir,
  3246. 'HEAD')
  3247. self.assertEqual(0, return_value)
  3248. def testYapfignoreExplicit(self):
  3249. self._make_yapfignore(['foo/bar.py', 'foo/bar/baz.py'])
  3250. files = [
  3251. 'bar.py',
  3252. 'foo/bar.py',
  3253. 'foo/baz.py',
  3254. 'foo/bar/baz.py',
  3255. 'foo/bar/foobar.py',
  3256. ]
  3257. expected = [
  3258. 'bar.py',
  3259. 'foo/baz.py',
  3260. 'foo/bar/foobar.py',
  3261. ]
  3262. self._check_yapf_filtering(files, expected)
  3263. def testYapfignoreSingleWildcards(self):
  3264. self._make_yapfignore(['*bar.py', 'foo*', 'baz*.py'])
  3265. files = [
  3266. 'bar.py', # Matched by *bar.py.
  3267. 'bar.txt',
  3268. 'foobar.py', # Matched by *bar.py, foo*.
  3269. 'foobar.txt', # Matched by foo*.
  3270. 'bazbar.py', # Matched by *bar.py, baz*.py.
  3271. 'bazbar.txt',
  3272. 'foo/baz.txt', # Matched by foo*.
  3273. 'bar/bar.py', # Matched by *bar.py.
  3274. 'baz/foo.py', # Matched by baz*.py, foo*.
  3275. 'baz/foo.txt',
  3276. ]
  3277. expected = [
  3278. 'bar.txt',
  3279. 'bazbar.txt',
  3280. 'baz/foo.txt',
  3281. ]
  3282. self._check_yapf_filtering(files, expected)
  3283. def testYapfignoreMultiplewildcards(self):
  3284. self._make_yapfignore(['*bar*', '*foo*baz.txt'])
  3285. files = [
  3286. 'bar.py', # Matched by *bar*.
  3287. 'bar.txt', # Matched by *bar*.
  3288. 'abar.py', # Matched by *bar*.
  3289. 'foobaz.txt', # Matched by *foo*baz.txt.
  3290. 'foobaz.py',
  3291. 'afoobaz.txt', # Matched by *foo*baz.txt.
  3292. ]
  3293. expected = [
  3294. 'foobaz.py',
  3295. ]
  3296. self._check_yapf_filtering(files, expected)
  3297. def testYapfignoreComments(self):
  3298. self._make_yapfignore(['test.py', '#test2.py'])
  3299. files = [
  3300. 'test.py',
  3301. 'test2.py',
  3302. ]
  3303. expected = [
  3304. 'test2.py',
  3305. ]
  3306. self._check_yapf_filtering(files, expected)
  3307. def testYapfignoreBlankLines(self):
  3308. self._make_yapfignore(['test.py', '', '', 'test2.py'])
  3309. files = [
  3310. 'test.py',
  3311. 'test2.py',
  3312. 'test3.py',
  3313. ]
  3314. expected = [
  3315. 'test3.py',
  3316. ]
  3317. self._check_yapf_filtering(files, expected)
  3318. def testYapfignoreWhitespace(self):
  3319. self._make_yapfignore([' test.py '])
  3320. files = [
  3321. 'test.py',
  3322. 'test2.py',
  3323. ]
  3324. expected = [
  3325. 'test2.py',
  3326. ]
  3327. self._check_yapf_filtering(files, expected)
  3328. def testYapfignoreNoFiles(self):
  3329. self._make_yapfignore(['test.py'])
  3330. self._check_yapf_filtering([], [])
  3331. def testYapfignoreMissingYapfignore(self):
  3332. files = [
  3333. 'test.py',
  3334. ]
  3335. expected = [
  3336. 'test.py',
  3337. ]
  3338. self._check_yapf_filtering(files, expected)
  3339. if __name__ == '__main__':
  3340. logging.basicConfig(
  3341. level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
  3342. unittest.main()