presubmit_unittest.py 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Unit tests for presubmit_support.py and presubmit_canned_checks.py."""
  6. # pylint: disable=no-member,E1103
  7. import functools
  8. import io
  9. import itertools
  10. import logging
  11. import multiprocessing
  12. import os
  13. import random
  14. import re
  15. import sys
  16. import tempfile
  17. import threading
  18. import time
  19. import unittest
  20. from io import StringIO
  21. from unittest import mock
  22. import urllib.request as urllib_request
  23. _ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  24. sys.path.insert(0, _ROOT)
  25. from testing_support.test_case_utils import TestCaseUtils
  26. import auth
  27. import gclient_utils
  28. import git_cl
  29. import git_common as git
  30. import json
  31. import owners_client
  32. import presubmit_support as presubmit
  33. import rdb_wrapper
  34. import scm
  35. import subprocess2 as subprocess
  36. # Shortcut.
  37. presubmit_canned_checks = presubmit.presubmit_canned_checks
  38. RUNNING_PY_CHECKS_TEXT = ('Running presubmit upload checks ...\n')
  39. # Access to a protected member XXX of a client class
  40. # pylint: disable=protected-access
  41. # TODO: Should fix these warnings.
  42. # pylint: disable=line-too-long
  43. class MockTemporaryFile(object):
  44. """Simple mock for files returned by tempfile.NamedTemporaryFile()."""
  45. def __init__(self, name):
  46. self.name = name
  47. def __enter__(self):
  48. return self
  49. def __exit__(self, *args):
  50. pass
  51. def close(self):
  52. pass
  53. class PresubmitTestsBase(TestCaseUtils, unittest.TestCase):
  54. """Sets up and tears down the mocks but doesn't test anything as-is."""
  55. presubmit_text = """
  56. def CheckChangeOnUpload(input_api, output_api):
  57. if input_api.change.tags.get('ERROR'):
  58. return [output_api.PresubmitError("!!")]
  59. if input_api.change.tags.get('PROMPT_WARNING'):
  60. return [output_api.PresubmitPromptWarning("??")]
  61. else:
  62. return ()
  63. def PostUploadHook(gerrit, change, output_api):
  64. if change.tags.get('ERROR'):
  65. return [output_api.PresubmitError("!!")]
  66. if change.tags.get('PROMPT_WARNING'):
  67. return [output_api.PresubmitPromptWarning("??")]
  68. else:
  69. return ()
  70. """
  71. presubmit_trymaster = """
  72. def GetPreferredTryMasters(project, change):
  73. return %s
  74. """
  75. presubmit_diffs = """
  76. diff --git %(filename)s %(filename)s
  77. index fe3de7b..54ae6e1 100755
  78. --- %(filename)s 2011-02-09 10:38:16.517224845 -0800
  79. +++ %(filename)s 2011-02-09 10:38:53.177226516 -0800
  80. @@ -1,6 +1,5 @@
  81. this is line number 0
  82. this is line number 1
  83. -this is line number 2 to be deleted
  84. this is line number 3
  85. this is line number 4
  86. this is line number 5
  87. @@ -8,7 +7,7 @@
  88. this is line number 7
  89. this is line number 8
  90. this is line number 9
  91. -this is line number 10 to be modified
  92. +this is line number 10
  93. this is line number 11
  94. this is line number 12
  95. this is line number 13
  96. @@ -21,9 +20,8 @@
  97. this is line number 20
  98. this is line number 21
  99. this is line number 22
  100. -this is line number 23
  101. -this is line number 24
  102. -this is line number 25
  103. +this is line number 23.1
  104. +this is line number 25.1
  105. this is line number 26
  106. this is line number 27
  107. this is line number 28
  108. @@ -31,6 +29,7 @@
  109. this is line number 30
  110. this is line number 31
  111. this is line number 32
  112. +this is line number 32.1
  113. this is line number 33
  114. this is line number 34
  115. this is line number 35
  116. @@ -38,14 +37,14 @@
  117. this is line number 37
  118. this is line number 38
  119. this is line number 39
  120. -
  121. this is line number 40
  122. -this is line number 41
  123. +this is line number 41.1
  124. this is line number 42
  125. this is line number 43
  126. this is line number 44
  127. this is line number 45
  128. +
  129. this is line number 46
  130. this is line number 47
  131. -this is line number 48
  132. +this is line number 48.1
  133. this is line number 49
  134. """
  135. def setUp(self):
  136. super(PresubmitTestsBase, self).setUp()
  137. # Disable string diff max. It's hard to parse assertion error if there's
  138. # limit set.
  139. self.maxDiff = None
  140. class FakeChange(object):
  141. def __init__(self, obj):
  142. self._root = obj.fake_root_dir
  143. self.issue = 0
  144. def RepositoryRoot(self):
  145. return self._root
  146. def UpstreamBranch(self):
  147. return 'upstream'
  148. presubmit._ASKED_FOR_FEEDBACK = False
  149. self.fake_root_dir = self.RootDir()
  150. self.fake_change = FakeChange(self)
  151. self.rdb_client = mock.MagicMock()
  152. mock.patch('gclient_utils.FileRead').start()
  153. mock.patch('gclient_utils.FileWrite').start()
  154. mock.patch('json.load').start()
  155. mock.patch('multiprocessing.cpu_count', lambda: 2)
  156. mock.patch('gerrit_util.IsCodeOwnersEnabledOnHost').start()
  157. mock.patch('os.chdir').start()
  158. mock.patch('os.getcwd', self.RootDir)
  159. mock.patch('os.listdir').start()
  160. mock.patch('os.path.abspath', lambda f: f).start()
  161. mock.patch('os.path.isfile').start()
  162. mock.patch('os.remove').start()
  163. mock.patch('presubmit_support._parse_files').start()
  164. mock.patch('presubmit_support.rdb_wrapper.client',
  165. return_value=self.rdb_client).start()
  166. mock.patch('presubmit_support.sigint_handler').start()
  167. mock.patch('presubmit_support.time_time', return_value=0).start()
  168. mock.patch('presubmit_support.warn').start()
  169. mock.patch('random.randint').start()
  170. mock.patch('scm.GIT.GenerateDiff').start()
  171. mock.patch('scm.determine_scm').start()
  172. mock.patch('subprocess2.Popen').start()
  173. mock.patch('sys.stderr', StringIO()).start()
  174. mock.patch('sys.stdout', StringIO()).start()
  175. mock.patch('tempfile.NamedTemporaryFile').start()
  176. mock.patch('threading.Timer').start()
  177. mock.patch('urllib.request.urlopen').start()
  178. self.addCleanup(mock.patch.stopall)
  179. def checkstdout(self, value):
  180. self.assertEqual(sys.stdout.getvalue(), value)
  181. class PresubmitUnittest(PresubmitTestsBase):
  182. """General presubmit_support.py tests (excluding InputApi and OutputApi)."""
  183. _INHERIT_SETTINGS = 'inherit-review-settings-ok'
  184. fake_root_dir = '/foo/bar'
  185. def testCannedCheckFilter(self):
  186. canned = presubmit.presubmit_canned_checks
  187. orig = canned.CheckOwners
  188. with presubmit.canned_check_filter(['CheckOwners']):
  189. self.assertNotEqual(canned.CheckOwners, orig)
  190. self.assertEqual(canned.CheckOwners(None, None), [])
  191. self.assertEqual(canned.CheckOwners, orig)
  192. def testListRelevantPresubmitFiles(self):
  193. files = [
  194. 'blat.cc',
  195. os.path.join('foo', 'haspresubmit', 'yodle', 'smart.h'),
  196. os.path.join('moo', 'mat', 'gat', 'yo.h'),
  197. os.path.join('foo', 'luck.h'),
  198. ]
  199. known_files = [
  200. os.path.join(self.fake_root_dir, 'PRESUBMIT.py'),
  201. os.path.join(self.fake_root_dir, 'foo', 'haspresubmit',
  202. 'PRESUBMIT.py'),
  203. os.path.join(self.fake_root_dir, 'foo', 'haspresubmit', 'yodle',
  204. 'PRESUBMIT.py'),
  205. ]
  206. os.path.isfile.side_effect = lambda f: f in known_files
  207. dirs_with_presubmit = [
  208. self.fake_root_dir,
  209. os.path.join(self.fake_root_dir, 'foo', 'haspresubmit'),
  210. os.path.join(self.fake_root_dir, 'foo', 'haspresubmit', 'yodle'),
  211. ]
  212. os.listdir.side_effect = (lambda d: ['PRESUBMIT.py']
  213. if d in dirs_with_presubmit else [])
  214. presubmit_files = presubmit.ListRelevantPresubmitFiles(
  215. files, self.fake_root_dir)
  216. self.assertEqual(presubmit_files, known_files)
  217. def testListUserPresubmitFiles(self):
  218. files = [
  219. 'blat.cc',
  220. ]
  221. os.path.isfile.side_effect = lambda f: 'PRESUBMIT' in f
  222. os.listdir.return_value = [
  223. 'PRESUBMIT.py', 'PRESUBMIT_test.py', 'PRESUBMIT-user.py'
  224. ]
  225. presubmit_files = presubmit.ListRelevantPresubmitFiles(
  226. files, self.fake_root_dir)
  227. self.assertEqual(presubmit_files, [
  228. os.path.join(self.fake_root_dir, 'PRESUBMIT.py'),
  229. os.path.join(self.fake_root_dir, 'PRESUBMIT-user.py'),
  230. ])
  231. def testListRelevantPresubmitFilesInheritSettings(self):
  232. sys_root_dir = self._OS_SEP
  233. root_dir = os.path.join(sys_root_dir, 'foo', 'bar')
  234. inherit_path = os.path.join(root_dir, self._INHERIT_SETTINGS)
  235. files = [
  236. 'test.cc',
  237. os.path.join('moo', 'test2.cc'),
  238. os.path.join('zoo', 'test3.cc')
  239. ]
  240. known_files = [
  241. inherit_path,
  242. os.path.join(sys_root_dir, 'foo', 'PRESUBMIT.py'),
  243. os.path.join(sys_root_dir, 'foo', 'bar', 'moo', 'PRESUBMIT.py'),
  244. ]
  245. os.path.isfile.side_effect = lambda f: f in known_files
  246. dirs_with_presubmit = [
  247. os.path.join(sys_root_dir, 'foo'),
  248. os.path.join(sys_root_dir, 'foo', 'bar', 'moo'),
  249. ]
  250. os.listdir.side_effect = (lambda d: ['PRESUBMIT.py']
  251. if d in dirs_with_presubmit else [])
  252. presubmit_files = presubmit.ListRelevantPresubmitFiles(files, root_dir)
  253. self.assertEqual(presubmit_files, [
  254. os.path.join(sys_root_dir, 'foo', 'PRESUBMIT.py'),
  255. os.path.join(sys_root_dir, 'foo', 'bar', 'moo', 'PRESUBMIT.py')
  256. ])
  257. def testTagLineRe(self):
  258. m = presubmit.Change.TAG_LINE_RE.match(' BUG =1223, 1445 \t')
  259. self.assertIsNotNone(m)
  260. self.assertEqual(m.group('key'), 'BUG')
  261. self.assertEqual(m.group('value'), '1223, 1445')
  262. def testGitChange(self):
  263. description_lines = ('Hello there', 'this is a change', 'BUG=123',
  264. 'and some more regular text \t')
  265. unified_diff = [
  266. 'diff --git binary_a.png binary_a.png', 'new file mode 100644',
  267. 'index 0000000..6fbdd6d',
  268. 'Binary files /dev/null and binary_a.png differ',
  269. 'diff --git binary_d.png binary_d.png', 'deleted file mode 100644',
  270. 'index 6fbdd6d..0000000',
  271. 'Binary files binary_d.png and /dev/null differ',
  272. 'diff --git binary_md.png binary_md.png',
  273. 'index 6fbdd6..be3d5d8 100644', 'GIT binary patch', 'delta 109',
  274. 'zcmeyihjs5>)(Opwi4&WXB~yyi6N|G`(i5|?i<2_a@)OH5N{Um`D-<SM@g!_^W9;SR',
  275. 'zO9b*W5{pxTM0slZ=F42indK9U^MTyVQlJ2s%1BMmEKMv1Q^gtS&9nHn&*Ede;|~CU',
  276. 'CMJxLN', '', 'delta 34',
  277. 'scmV+-0Nww+y#@BX1(1W0gkzIp3}CZh0gVZ>`wGVcgW(Rh;SK@ZPa9GXlK=n!', '',
  278. 'diff --git binary_m.png binary_m.png',
  279. 'index 6fbdd6d..be3d5d8 100644',
  280. 'Binary files binary_m.png and binary_m.png differ',
  281. 'diff --git boo/blat.cc boo/blat.cc', 'new file mode 100644',
  282. 'index 0000000..37d18ad', '--- boo/blat.cc', '+++ boo/blat.cc',
  283. '@@ -0,0 +1,5 @@', '+This is some text',
  284. '+which lacks a copyright warning',
  285. '+but it is nonetheless interesting',
  286. '+and worthy of your attention.',
  287. '+Its freshness factor is through the roof.',
  288. 'diff --git floo/delburt.cc floo/delburt.cc',
  289. 'deleted file mode 100644', 'index e06377a..0000000',
  290. '--- floo/delburt.cc', '+++ /dev/null', '@@ -1,14 +0,0 @@',
  291. '-This text used to be here', '-but someone, probably you,',
  292. '-having consumed the text', '- (absorbed its meaning)',
  293. '-decided that it should be made to not exist',
  294. '-that others would not read it.', '- (What happened here?',
  295. '-was the author incompetent?',
  296. '-or is the world today so different from the world',
  297. '- the author foresaw', '-and past imaginination',
  298. '- amounts to rubble, insignificant,',
  299. '-something to be tripped over', '-and frustrated by)',
  300. 'diff --git foo/TestExpectations foo/TestExpectations',
  301. 'index c6e12ab..d1c5f23 100644', '--- foo/TestExpectations',
  302. '+++ foo/TestExpectations', '@@ -1,12 +1,24 @@',
  303. '-Stranger, behold:', '+Strange to behold:', ' This is a text',
  304. ' Its contents existed before.', '', '-It is written:',
  305. '+Weasel words suggest:', ' its contents shall exist after',
  306. ' and its contents', ' with the progress of time',
  307. ' will evolve,', '- snaillike,', '+ erratically,',
  308. ' into still different texts', '-from this.',
  309. '\ No newline at end of file', '+from this.', '+',
  310. '+For the most part,', '+I really think unified diffs',
  311. '+are elegant: the way you can type',
  312. '+diff --git inside/a/text inside/a/text',
  313. '+or something silly like', '+@@ -278,6 +278,10 @@',
  314. '+and have this not be interpreted', '+as the start of a new file',
  315. '+or anything messed up like that,',
  316. '+because you parsed the header', '+correctly.',
  317. '\ No newline at end of file', ''
  318. ]
  319. files = [
  320. ('A ', 'binary_a.png'),
  321. ('D ', 'binary_d.png'),
  322. ('M ', 'binary_m.png'),
  323. ('M ', 'binary_md.png'), # Binary w/ diff
  324. ('A ', 'boo/blat.cc'),
  325. ('D ', 'floo/delburt.cc'),
  326. ('M ', 'foo/TestExpectations')
  327. ]
  328. known_files = [
  329. os.path.join(self.fake_root_dir, *path.split('/'))
  330. for op, path in files if not op.startswith('D')
  331. ]
  332. os.path.isfile.side_effect = lambda f: f in known_files
  333. scm.GIT.GenerateDiff.return_value = '\n'.join(unified_diff)
  334. change = presubmit.GitChange('mychange',
  335. '\n'.join(description_lines),
  336. self.fake_root_dir,
  337. files,
  338. 0,
  339. 0,
  340. None,
  341. upstream='upstream',
  342. end_commit='end_commit')
  343. self.assertIsNotNone(change.Name() == 'mychange')
  344. self.assertIsNotNone(change.DescriptionText(
  345. ) == 'Hello there\nthis is a change\nand some more regular text')
  346. self.assertIsNotNone(
  347. change.FullDescriptionText() == '\n'.join(description_lines))
  348. self.assertIsNotNone(change.BugsFromDescription() == ['123'])
  349. self.assertIsNotNone(len(change.AffectedFiles()) == 7)
  350. self.assertIsNotNone(len(change.AffectedFiles()) == 7)
  351. self.assertIsNotNone(
  352. len(change.AffectedFiles(include_deletes=False)) == 5)
  353. self.assertIsNotNone(
  354. len(change.AffectedFiles(include_deletes=False)) == 5)
  355. # Note that on git, there's no distinction between binary files and text
  356. # files; everything that's not a delete is a text file.
  357. affected_text_files = change.AffectedTestableFiles()
  358. self.assertIsNotNone(len(affected_text_files) == 5)
  359. local_paths = change.LocalPaths()
  360. expected_paths = [os.path.normpath(f) for op, f in files]
  361. self.assertEqual(local_paths, expected_paths)
  362. actual_rhs_lines = []
  363. for f, linenum, line in change.RightHandSideLines():
  364. actual_rhs_lines.append((f.LocalPath(), linenum, line))
  365. scm.GIT.GenerateDiff.assert_called_once_with(self.fake_root_dir,
  366. files=[],
  367. full_move=True,
  368. branch='upstream',
  369. branch_head='end_commit')
  370. f_blat = os.path.normpath('boo/blat.cc')
  371. f_test_expectations = os.path.normpath('foo/TestExpectations')
  372. expected_rhs_lines = [
  373. (f_blat, 1, 'This is some text'),
  374. (f_blat, 2, 'which lacks a copyright warning'),
  375. (f_blat, 3, 'but it is nonetheless interesting'),
  376. (f_blat, 4, 'and worthy of your attention.'),
  377. (f_blat, 5, 'Its freshness factor is through the roof.'),
  378. (f_test_expectations, 1, 'Strange to behold:'),
  379. (f_test_expectations, 5, 'Weasel words suggest:'),
  380. (f_test_expectations, 10, ' erratically,'),
  381. (f_test_expectations, 13, 'from this.'),
  382. (f_test_expectations, 14, ''),
  383. (f_test_expectations, 15, 'For the most part,'),
  384. (f_test_expectations, 16, 'I really think unified diffs'),
  385. (f_test_expectations, 17, 'are elegant: the way you can type'),
  386. (f_test_expectations, 18, 'diff --git inside/a/text inside/a/text'),
  387. (f_test_expectations, 19, 'or something silly like'),
  388. (f_test_expectations, 20, '@@ -278,6 +278,10 @@'),
  389. (f_test_expectations, 21, 'and have this not be interpreted'),
  390. (f_test_expectations, 22, 'as the start of a new file'),
  391. (f_test_expectations, 23, 'or anything messed up like that,'),
  392. (f_test_expectations, 24, 'because you parsed the header'),
  393. (f_test_expectations, 25, 'correctly.')
  394. ]
  395. self.assertEqual(expected_rhs_lines, actual_rhs_lines)
  396. def testInvalidChange(self):
  397. with self.assertRaises(AssertionError):
  398. presubmit.GitChange('mychange',
  399. 'description',
  400. self.fake_root_dir, ['foo/blat.cc', 'bar'],
  401. 0,
  402. 0,
  403. None,
  404. upstream='upstream',
  405. end_commit='HEAD')
  406. def testExecPresubmitScript(self):
  407. description_lines = ('Hello there', 'this is a change', 'BUG=123')
  408. files = [
  409. ['A', 'foo\\blat.cc'],
  410. ]
  411. fake_presubmit = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  412. change = presubmit.Change('mychange', '\n'.join(description_lines),
  413. self.fake_root_dir, files, 0, 0, None)
  414. executer = presubmit.PresubmitExecuter(change, False, None,
  415. presubmit.GerritAccessor())
  416. self.assertFalse(executer.ExecPresubmitScript('', fake_presubmit))
  417. # No error if no on-upload entry point
  418. self.assertFalse(
  419. executer.ExecPresubmitScript(
  420. ('def CheckChangeOnCommit(input_api, output_api):\n'
  421. ' return (output_api.PresubmitError("!!"))\n'),
  422. fake_presubmit))
  423. executer = presubmit.PresubmitExecuter(change, True, None,
  424. presubmit.GerritAccessor())
  425. # No error if no on-commit entry point
  426. self.assertFalse(
  427. executer.ExecPresubmitScript(
  428. ('def CheckChangeOnUpload(input_api, output_api):\n'
  429. ' return (output_api.PresubmitError("!!"))\n'),
  430. fake_presubmit))
  431. self.assertFalse(
  432. executer.ExecPresubmitScript(
  433. ('def CheckChangeOnUpload(input_api, output_api):\n'
  434. ' if not input_api.change.BugsFromDescription():\n'
  435. ' return (output_api.PresubmitError("!!"))\n'
  436. ' else:\n'
  437. ' return ()'), fake_presubmit))
  438. self.assertFalse(
  439. executer.ExecPresubmitScript(
  440. 'def CheckChangeOnCommit(input_api, output_api):\n'
  441. ' results = []\n'
  442. ' results.extend(input_api.canned_checks.CheckChangeHasBugField(\n'
  443. ' input_api, output_api))\n'
  444. ' results.extend(input_api.canned_checks.'
  445. 'CheckChangeHasNoUnwantedTags(\n'
  446. ' input_api, output_api))\n'
  447. ' results.extend(input_api.canned_checks.'
  448. 'CheckChangeHasDescription(\n'
  449. ' input_api, output_api))\n'
  450. ' return results\n', fake_presubmit))
  451. def testExecPresubmitScriptWithResultDB(self):
  452. description_lines = ('Hello there', 'this is a change', 'BUG=123')
  453. files = [['A', 'foo\\blat.cc']]
  454. fake_presubmit = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  455. change = presubmit.Change('mychange', '\n'.join(description_lines),
  456. self.fake_root_dir, files, 0, 0, None)
  457. executer = presubmit.PresubmitExecuter(change, True, None,
  458. presubmit.GerritAccessor())
  459. sink = self.rdb_client.__enter__.return_value = mock.MagicMock()
  460. # STATUS_PASS on success
  461. executer.ExecPresubmitScript(
  462. 'def CheckChangeOnCommit(input_api, output_api):\n'
  463. ' return [output_api.PresubmitResult("test")]\n', fake_presubmit)
  464. sink.report.assert_called_with('CheckChangeOnCommit',
  465. rdb_wrapper.STATUS_PASS, 0, None)
  466. # STATUS_FAIL on fatal error
  467. sink.reset_mock()
  468. executer.ExecPresubmitScript(
  469. 'def CheckChangeOnCommit(input_api, output_api):\n'
  470. ' return [output_api.PresubmitError("error")]\n', fake_presubmit)
  471. sink.report.assert_called_with('CheckChangeOnCommit',
  472. rdb_wrapper.STATUS_FAIL, 0, "error\n")
  473. def testExecPresubmitScriptTemporaryFilesRemoval(self):
  474. tempfile.NamedTemporaryFile.side_effect = [
  475. MockTemporaryFile('baz'),
  476. MockTemporaryFile('quux'),
  477. ]
  478. fake_presubmit = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  479. executer = presubmit.PresubmitExecuter(self.fake_change, False, None,
  480. presubmit.GerritAccessor())
  481. self.assertEqual(
  482. [],
  483. executer.ExecPresubmitScript(
  484. ('def CheckChangeOnUpload(input_api, output_api):\n'
  485. ' if len(input_api._named_temporary_files):\n'
  486. ' return (output_api.PresubmitError("!!"),)\n'
  487. ' return ()\n'), fake_presubmit))
  488. result = executer.ExecPresubmitScript(
  489. ('def CheckChangeOnUpload(input_api, output_api):\n'
  490. ' with input_api.CreateTemporaryFile():\n'
  491. ' pass\n'
  492. ' with input_api.CreateTemporaryFile():\n'
  493. ' pass\n'
  494. ' return [output_api.PresubmitResult(\'\', f)\n'
  495. ' for f in input_api._named_temporary_files]\n'),
  496. fake_presubmit)
  497. self.assertEqual(['baz', 'quux'], [r._items for r in result])
  498. self.assertEqual(os.remove.mock_calls,
  499. [mock.call('baz'), mock.call('quux')])
  500. def testExecPresubmitScriptInSourceDirectory(self):
  501. """Tests that the presubmits are executed with the current working
  502. directory (CWD) set to the directory of the source presubmit script.
  503. """
  504. orig_dir = os.getcwd()
  505. fake_presubmit_dir = os.path.join(self.fake_root_dir, 'fake_dir')
  506. fake_presubmit = os.path.join(fake_presubmit_dir, 'PRESUBMIT.py')
  507. change = self.ExampleChange()
  508. executer = presubmit.PresubmitExecuter(change, False, None,
  509. presubmit.GerritAccessor())
  510. executer.ExecPresubmitScript('', fake_presubmit)
  511. # Check that the executer switched to the directory of the script and
  512. # back.
  513. self.assertEqual(os.chdir.call_args_list, [
  514. mock.call(fake_presubmit_dir),
  515. mock.call(orig_dir),
  516. ])
  517. def testExecPostUploadHookSourceDirectory(self):
  518. """Tests that the post upload hooks are executed with the current working
  519. directory (CWD) set to the directory of the source presubmit script.
  520. s"""
  521. orig_dir = os.getcwd()
  522. fake_presubmit_dir = os.path.join(self.fake_root_dir, 'fake_dir')
  523. fake_presubmit = os.path.join(fake_presubmit_dir, 'PRESUBMIT.py')
  524. change = self.ExampleChange()
  525. executer = presubmit.GetPostUploadExecuter(change,
  526. presubmit.GerritAccessor())
  527. executer.ExecPresubmitScript(self.presubmit_text, fake_presubmit)
  528. # Check that the executer switched to the directory of the script and
  529. # back.
  530. self.assertEqual(os.chdir.call_args_list, [
  531. mock.call(fake_presubmit_dir),
  532. mock.call(orig_dir),
  533. ])
  534. def testDoPostUploadExecuter(self):
  535. os.path.isfile.side_effect = lambda f: 'PRESUBMIT.py' in f
  536. os.listdir.return_value = ['PRESUBMIT.py']
  537. gclient_utils.FileRead.return_value = self.presubmit_text
  538. change = self.ExampleChange()
  539. self.assertEqual(
  540. 0,
  541. presubmit.DoPostUploadExecuter(change=change,
  542. gerrit_obj=None,
  543. verbose=False))
  544. expected = (r'Running post upload checks \.\.\.\n')
  545. self.assertRegexpMatches(sys.stdout.getvalue(), expected)
  546. def testDoPostUploadExecuterWarning(self):
  547. path = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  548. os.path.isfile.side_effect = lambda f: f == path
  549. os.listdir.return_value = ['PRESUBMIT.py']
  550. gclient_utils.FileRead.return_value = self.presubmit_text
  551. change = self.ExampleChange(extra_lines=['PROMPT_WARNING=yes'])
  552. self.assertEqual(
  553. 0,
  554. presubmit.DoPostUploadExecuter(change=change,
  555. gerrit_obj=None,
  556. verbose=False))
  557. self.assertEqual(
  558. 'Running post upload checks ...\n'
  559. '\n'
  560. '** Post Upload Hook Messages **\n'
  561. '??\n'
  562. '\n', sys.stdout.getvalue())
  563. def testDoPostUploadExecuterWarning(self):
  564. path = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  565. os.path.isfile.side_effect = lambda f: f == path
  566. os.listdir.return_value = ['PRESUBMIT.py']
  567. gclient_utils.FileRead.return_value = self.presubmit_text
  568. change = self.ExampleChange(extra_lines=['ERROR=yes'])
  569. self.assertEqual(
  570. 1,
  571. presubmit.DoPostUploadExecuter(change=change,
  572. gerrit_obj=None,
  573. verbose=False))
  574. expected = ('Running post upload checks \.\.\.\n'
  575. '\n'
  576. '\*\* Post Upload Hook Messages \*\*\n'
  577. '!!\n'
  578. '\n')
  579. self.assertRegexpMatches(sys.stdout.getvalue(), expected)
  580. def testDoPresubmitChecksNoWarningsOrErrors(self):
  581. haspresubmit_path = os.path.join(self.fake_root_dir, 'haspresubmit',
  582. 'PRESUBMIT.py')
  583. root_path = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  584. os.path.isfile.side_effect = lambda f: f in [
  585. root_path, haspresubmit_path
  586. ]
  587. os.listdir.return_value = ['PRESUBMIT.py']
  588. gclient_utils.FileRead.return_value = self.presubmit_text
  589. # Make a change which will have no warnings.
  590. change = self.ExampleChange(extra_lines=['STORY=http://tracker/123'])
  591. self.assertEqual(
  592. 0,
  593. presubmit.DoPresubmitChecks(change=change,
  594. committing=False,
  595. verbose=True,
  596. default_presubmit=None,
  597. may_prompt=False,
  598. gerrit_obj=None,
  599. json_output=None))
  600. self.assertEqual(sys.stdout.getvalue().count('!!'), 0)
  601. self.assertEqual(sys.stdout.getvalue().count('??'), 0)
  602. self.assertEqual(sys.stdout.getvalue().count(RUNNING_PY_CHECKS_TEXT), 1)
  603. def testDoPresubmitChecksJsonOutput(self):
  604. fake_error = 'Missing LGTM'
  605. fake_error_items = '["!", "!!", "!!!"]'
  606. fake_error_long_text = "Error long text..."
  607. fake_error2 = 'This failed was found in file fake.py'
  608. fake_error2_items = '["!!!", "!!", "!"]'
  609. fake_error2_long_text = " Error long text" * 3
  610. fake_warning = 'Line 88 is more than 80 characters.'
  611. fake_warning_items = '["W", "w"]'
  612. fake_warning_long_text = 'Warning long text...'
  613. fake_notify = 'This is a dry run'
  614. fake_notify_items = '["N"]'
  615. fake_notify_long_text = 'Notification long text...'
  616. always_fail_presubmit_script = ("""\n
  617. def CheckChangeOnUpload(input_api, output_api):
  618. output_api.more_cc = ['me@example.com']
  619. return [
  620. output_api.PresubmitError("%s",%s, "%s"),
  621. output_api.PresubmitError("%s",%s, "%s"),
  622. output_api.PresubmitPromptWarning("%s",%s, "%s"),
  623. output_api.PresubmitNotifyResult("%s",%s, "%s")
  624. ]
  625. def CheckChangeOnCommit(input_api, output_api):
  626. raise Exception("Test error")
  627. """ % (fake_error, fake_error_items, fake_error_long_text, fake_error2,
  628. fake_error2_items, fake_error2_long_text, fake_warning,
  629. fake_warning_items, fake_warning_long_text, fake_notify,
  630. fake_notify_items, fake_notify_long_text))
  631. os.path.isfile.return_value = False
  632. os.listdir.side_effect = [[], ['PRESUBMIT.py']]
  633. random.randint.return_value = 0
  634. change = self.ExampleChange(extra_lines=['ERROR=yes'])
  635. temp_path = 'temp.json'
  636. fake_result = {
  637. 'notifications': [{
  638. 'message': fake_notify,
  639. 'items': json.loads(fake_notify_items),
  640. 'fatal': False,
  641. 'long_text': fake_notify_long_text
  642. }],
  643. 'errors': [{
  644. 'message': fake_error,
  645. 'items': json.loads(fake_error_items),
  646. 'fatal': True,
  647. 'long_text': fake_error_long_text
  648. }, {
  649. 'message': fake_error2,
  650. 'items': json.loads(fake_error2_items),
  651. 'fatal': True,
  652. 'long_text': fake_error2_long_text
  653. }],
  654. 'warnings': [{
  655. 'message': fake_warning,
  656. 'items': json.loads(fake_warning_items),
  657. 'fatal': False,
  658. 'long_text': fake_warning_long_text
  659. }],
  660. 'more_cc': ['me@example.com'],
  661. }
  662. fake_result_json = json.dumps(fake_result, sort_keys=True)
  663. self.assertEqual(
  664. 1,
  665. presubmit.DoPresubmitChecks(
  666. change=change,
  667. committing=False,
  668. verbose=True,
  669. default_presubmit=always_fail_presubmit_script,
  670. may_prompt=False,
  671. gerrit_obj=None,
  672. json_output=temp_path))
  673. gclient_utils.FileWrite.assert_called_with(temp_path, fake_result_json)
  674. def testDoPresubmitChecksPromptsAfterWarnings(self):
  675. presubmit_path = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  676. haspresubmit_path = os.path.join(self.fake_root_dir, 'haspresubmit',
  677. 'PRESUBMIT.py')
  678. os.path.isfile.side_effect = (
  679. lambda f: f in [presubmit_path, haspresubmit_path])
  680. os.listdir.return_value = ['PRESUBMIT.py']
  681. random.randint.return_value = 1
  682. gclient_utils.FileRead.return_value = self.presubmit_text
  683. # Make a change with a single warning.
  684. change = self.ExampleChange(extra_lines=['PROMPT_WARNING=yes'])
  685. # say no to the warning
  686. with mock.patch('sys.stdin', StringIO('n\n')):
  687. self.assertEqual(
  688. 1,
  689. presubmit.DoPresubmitChecks(change=change,
  690. committing=False,
  691. verbose=True,
  692. default_presubmit=None,
  693. may_prompt=True,
  694. gerrit_obj=None,
  695. json_output=None))
  696. self.assertEqual(sys.stdout.getvalue().count('??'), 2)
  697. sys.stdout.truncate(0)
  698. # say yes to the warning
  699. with mock.patch('sys.stdin', StringIO('y\n')):
  700. self.assertEqual(
  701. 0,
  702. presubmit.DoPresubmitChecks(change=change,
  703. committing=False,
  704. verbose=True,
  705. default_presubmit=None,
  706. may_prompt=True,
  707. gerrit_obj=None,
  708. json_output=None))
  709. self.assertEqual(sys.stdout.getvalue().count('??'), 2)
  710. self.assertEqual(sys.stdout.getvalue().count(RUNNING_PY_CHECKS_TEXT), 1)
  711. def testDoPresubmitChecksWithWarningsAndNoPrompt(self):
  712. presubmit_path = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  713. haspresubmit_path = os.path.join(self.fake_root_dir, 'haspresubmit',
  714. 'PRESUBMIT.py')
  715. os.path.isfile.side_effect = (
  716. lambda f: f in [presubmit_path, haspresubmit_path])
  717. os.listdir.return_value = ['PRESUBMIT.py']
  718. gclient_utils.FileRead.return_value = self.presubmit_text
  719. random.randint.return_value = 1
  720. change = self.ExampleChange(extra_lines=['PROMPT_WARNING=yes'])
  721. # There is no input buffer and may_prompt is set to False.
  722. self.assertEqual(
  723. 0,
  724. presubmit.DoPresubmitChecks(change=change,
  725. committing=False,
  726. verbose=True,
  727. default_presubmit=None,
  728. may_prompt=False,
  729. gerrit_obj=None,
  730. json_output=None))
  731. # A warning is printed, and should_continue is True.
  732. self.assertEqual(sys.stdout.getvalue().count('??'), 2)
  733. self.assertEqual(sys.stdout.getvalue().count('(y/N)'), 0)
  734. self.assertEqual(sys.stdout.getvalue().count(RUNNING_PY_CHECKS_TEXT), 1)
  735. def testDoPresubmitChecksNoWarningPromptIfErrors(self):
  736. presubmit_path = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  737. haspresubmit_path = os.path.join(self.fake_root_dir, 'haspresubmit',
  738. 'PRESUBMIT.py')
  739. os.path.isfile.side_effect = (
  740. lambda f: f in [presubmit_path, haspresubmit_path])
  741. os.listdir.return_value = ['PRESUBMIT.py']
  742. gclient_utils.FileRead.return_value = self.presubmit_text
  743. random.randint.return_value = 1
  744. change = self.ExampleChange(extra_lines=['ERROR=yes'])
  745. self.assertEqual(
  746. 1,
  747. presubmit.DoPresubmitChecks(change=change,
  748. committing=False,
  749. verbose=True,
  750. default_presubmit=None,
  751. may_prompt=True,
  752. gerrit_obj=None,
  753. json_output=None))
  754. self.assertEqual(sys.stdout.getvalue().count('??'), 0)
  755. self.assertEqual(sys.stdout.getvalue().count('!!'), 2)
  756. self.assertEqual(sys.stdout.getvalue().count('(y/N)'), 0)
  757. self.assertEqual(sys.stdout.getvalue().count(RUNNING_PY_CHECKS_TEXT), 1)
  758. def testDoDefaultPresubmitChecksAndFeedback(self):
  759. always_fail_presubmit_script = ("""\n
  760. def CheckChangeOnUpload(input_api, output_api):
  761. return [output_api.PresubmitError("!!")]
  762. def CheckChangeOnCommit(input_api, output_api):
  763. raise Exception("Test error")
  764. """)
  765. os.path.isfile.return_value = False
  766. os.listdir.side_effect = (
  767. lambda d: [] if d == self.fake_root_dir else ['PRESUBMIT.py'])
  768. random.randint.return_value = 0
  769. change = self.ExampleChange(extra_lines=['STORY=http://tracker/123'])
  770. with mock.patch('sys.stdin', StringIO('y\n')):
  771. self.assertEqual(
  772. 1,
  773. presubmit.DoPresubmitChecks(
  774. change=change,
  775. committing=False,
  776. verbose=True,
  777. default_presubmit=always_fail_presubmit_script,
  778. may_prompt=False,
  779. gerrit_obj=None,
  780. json_output=None))
  781. text = (
  782. RUNNING_PY_CHECKS_TEXT + 'Warning, no PRESUBMIT.py found.\n'
  783. 'Running default presubmit script.\n'
  784. '** Presubmit ERRORS: 1 **\n!!\n\n'
  785. 'There were presubmit errors.\n'
  786. 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
  787. 'to figure out which PRESUBMIT.py was run, then run "git blame"\n'
  788. 'on the file to figure out who to ask for help.\n')
  789. self.assertEqual(sys.stdout.getvalue(), text)
  790. def ExampleChange(self, extra_lines=None):
  791. """Returns an example Change instance for tests."""
  792. description_lines = [
  793. 'Hello there',
  794. 'This is a change',
  795. ] + (extra_lines or [])
  796. files = [
  797. ['A', os.path.join('haspresubmit', 'blat.cc')],
  798. ]
  799. return presubmit.Change(name='mychange',
  800. description='\n'.join(description_lines),
  801. local_root=self.fake_root_dir,
  802. files=files,
  803. issue=0,
  804. patchset=0,
  805. author=None)
  806. def testMainPostUpload(self):
  807. os.path.isfile.side_effect = lambda f: 'PRESUBMIT.py' in f
  808. os.listdir.return_value = ['PRESUBMIT.py']
  809. gclient_utils.FileRead.return_value = (
  810. 'def PostUploadHook(gerrit, change, output_api):\n'
  811. ' return ()\n')
  812. scm.determine_scm.return_value = None
  813. presubmit._parse_files.return_value = [('M', 'random_file.txt')]
  814. self.assertEqual(
  815. 0,
  816. presubmit.main([
  817. '--root', self.fake_root_dir, 'random_file.txt', '--post_upload'
  818. ]))
  819. @mock.patch('presubmit_support.ListRelevantPresubmitFiles')
  820. def testMainUnversioned(self, *_mocks):
  821. gclient_utils.FileRead.return_value = ''
  822. scm.determine_scm.return_value = None
  823. presubmit.ListRelevantPresubmitFiles.return_value = [
  824. os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  825. ]
  826. self.assertEqual(
  827. 0, presubmit.main(['--root', self.fake_root_dir,
  828. 'random_file.txt']))
  829. @mock.patch('presubmit_support.ListRelevantPresubmitFiles')
  830. def testMainUnversionedChecksFail(self, *_mocks):
  831. gclient_utils.FileRead.return_value = (
  832. 'def CheckChangeOnUpload(input_api, output_api):\n'
  833. ' return [output_api.PresubmitError("!!")]\n')
  834. scm.determine_scm.return_value = None
  835. presubmit.ListRelevantPresubmitFiles.return_value = [
  836. os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  837. ]
  838. self.assertEqual(
  839. 1, presubmit.main(['--root', self.fake_root_dir,
  840. 'random_file.txt']))
  841. def testMainUnversionedFail(self):
  842. scm.determine_scm.return_value = 'diff'
  843. with self.assertRaises(SystemExit) as e:
  844. presubmit.main(['--root', self.fake_root_dir])
  845. self.assertEqual(2, e.exception.code)
  846. self.assertEqual(
  847. sys.stderr.getvalue(),
  848. 'usage: presubmit_unittest.py [options] <files...>\n'
  849. 'presubmit_unittest.py: error: unversioned directories must '
  850. 'specify <files>, <all_files>, or <diff_file>.\n')
  851. @mock.patch('presubmit_support.Change', mock.Mock())
  852. def testParseChange_Files(self):
  853. presubmit._parse_files.return_value = [('M', 'random_file.txt')]
  854. scm.determine_scm.return_value = None
  855. options = mock.Mock(all_files=False,
  856. generate_diff=False,
  857. source_controlled_only=False)
  858. change = presubmit._parse_change(None, options)
  859. self.assertEqual(presubmit.Change.return_value, change)
  860. presubmit.Change.assert_called_once_with(
  861. options.name, options.description, options.root,
  862. [('M', 'random_file.txt')], options.issue, options.patchset,
  863. options.author)
  864. presubmit._parse_files.assert_called_once_with(options.files,
  865. options.recursive)
  866. def testParseChange_NoFilesAndDiff(self):
  867. presubmit._parse_files.return_value = []
  868. scm.determine_scm.return_value = 'diff'
  869. parser = mock.Mock()
  870. parser.error.side_effect = [SystemExit]
  871. options = mock.Mock(files=[], diff_file='', all_files=False)
  872. with self.assertRaises(SystemExit):
  873. presubmit._parse_change(parser, options)
  874. parser.error.assert_called_once_with(
  875. 'unversioned directories must specify '
  876. '<files>, <all_files>, or <diff_file>.')
  877. def testParseChange_FilesAndAllFiles(self):
  878. parser = mock.Mock()
  879. parser.error.side_effect = [SystemExit]
  880. options = mock.Mock(files=['foo'], all_files=True)
  881. with self.assertRaises(SystemExit):
  882. presubmit._parse_change(parser, options)
  883. parser.error.assert_called_once_with(
  884. '<files> cannot be specified when --all-files is set.')
  885. def testParseChange_DiffAndAllFiles(self):
  886. parser = mock.Mock()
  887. parser.error.side_effect = [SystemExit]
  888. options = mock.Mock(files=[], all_files=True, diff_file='foo.diff')
  889. with self.assertRaises(SystemExit):
  890. presubmit._parse_change(parser, options)
  891. parser.error.assert_called_once_with(
  892. '<diff_file> cannot be specified when --all-files is set.')
  893. def testParseChange_DiffAndGenerateDiff(self):
  894. parser = mock.Mock()
  895. parser.error.side_effect = [SystemExit]
  896. options = mock.Mock(all_files=False,
  897. files=[],
  898. generate_diff=True,
  899. diff_file='foo.diff')
  900. with self.assertRaises(SystemExit):
  901. presubmit._parse_change(parser, options)
  902. parser.error.assert_called_once_with(
  903. '<diff_file> cannot be specified when <generate_diff> is set.')
  904. @mock.patch('presubmit_support.GitChange', mock.Mock())
  905. def testParseChange_FilesAndGit(self):
  906. scm.determine_scm.return_value = 'git'
  907. presubmit._parse_files.return_value = [('M', 'random_file.txt')]
  908. options = mock.Mock(all_files=False,
  909. generate_diff=False,
  910. source_controlled_only=False)
  911. change = presubmit._parse_change(None, options)
  912. self.assertEqual(presubmit.GitChange.return_value, change)
  913. presubmit.GitChange.assert_called_once_with(
  914. options.name,
  915. options.description,
  916. options.root, [('M', 'random_file.txt')],
  917. options.issue,
  918. options.patchset,
  919. options.author,
  920. upstream=options.upstream,
  921. end_commit=options.end_commit)
  922. presubmit._parse_files.assert_called_once_with(options.files,
  923. options.recursive)
  924. @mock.patch('presubmit_support.GitChange', mock.Mock())
  925. @mock.patch('scm.GIT.CaptureStatus', mock.Mock())
  926. def testParseChange_NoFilesAndGit(self):
  927. scm.determine_scm.return_value = 'git'
  928. scm.GIT.CaptureStatus.return_value = [('A', 'added.txt')]
  929. options = mock.Mock(all_files=False, files=[], diff_file='')
  930. change = presubmit._parse_change(None, options)
  931. self.assertEqual(presubmit.GitChange.return_value, change)
  932. presubmit.GitChange.assert_called_once_with(
  933. options.name,
  934. options.description,
  935. options.root, [('A', 'added.txt')],
  936. options.issue,
  937. options.patchset,
  938. options.author,
  939. upstream=options.upstream,
  940. end_commit=options.end_commit)
  941. scm.GIT.CaptureStatus.assert_called_once_with(options.root,
  942. options.upstream,
  943. ignore_submodules=False)
  944. @mock.patch('presubmit_support.GitChange', mock.Mock())
  945. @mock.patch('scm.GIT.GetAllFiles', mock.Mock())
  946. def testParseChange_AllFilesAndGit(self):
  947. scm.determine_scm.return_value = 'git'
  948. scm.GIT.GetAllFiles.return_value = ['foo.txt', 'bar.txt']
  949. options = mock.Mock(all_files=True, files=[], diff_file='')
  950. change = presubmit._parse_change(None, options)
  951. self.assertEqual(presubmit.GitChange.return_value, change)
  952. presubmit.GitChange.assert_called_once_with(
  953. options.name,
  954. options.description,
  955. options.root, [('M', 'foo.txt'), ('M', 'bar.txt')],
  956. options.issue,
  957. options.patchset,
  958. options.author,
  959. upstream=options.upstream,
  960. end_commit=options.end_commit)
  961. scm.GIT.GetAllFiles.assert_called_once_with(options.root)
  962. @mock.patch('presubmit_support.ProvidedDiffChange', mock.Mock())
  963. def testParseChange_ProvidedDiffFile(self):
  964. diff = """
  965. diff --git a/foo b/foo
  966. new file mode 100644
  967. index 0000000..9daeafb
  968. --- /dev/null
  969. +++ b/foo
  970. @@ -0,0 +1 @@
  971. +test
  972. diff --git a/bar b/bar
  973. deleted file mode 100644
  974. index f675c2a..0000000
  975. --- a/bar
  976. +++ /dev/null
  977. @@ -1,1 +0,0 @@
  978. -bar
  979. diff --git a/baz b/baz
  980. index d7ba659f..b7957f3 100644
  981. --- a/baz
  982. +++ b/baz
  983. @@ -1,1 +1,1 @@
  984. -baz
  985. +bat"""
  986. gclient_utils.FileRead.return_value = diff
  987. options = mock.Mock(all_files=False,
  988. files=[],
  989. generate_diff=False,
  990. diff_file='foo.diff')
  991. change = presubmit._parse_change(None, options)
  992. self.assertEqual(presubmit.ProvidedDiffChange.return_value, change)
  993. presubmit.ProvidedDiffChange.assert_called_once_with(
  994. options.name,
  995. options.description,
  996. options.root, [('A', 'foo'), ('D', 'bar'), ('M', 'baz')],
  997. options.issue,
  998. options.patchset,
  999. options.author,
  1000. diff=diff)
  1001. def testParseGerritOptions_NoGerritUrl(self):
  1002. options = mock.Mock(gerrit_url=None,
  1003. gerrit_fetch=False,
  1004. author='author',
  1005. description='description')
  1006. gerrit_obj = presubmit._parse_gerrit_options(None, options)
  1007. self.assertIsNone(gerrit_obj)
  1008. self.assertEqual('author', options.author)
  1009. self.assertEqual('description', options.description)
  1010. def testParseGerritOptions_NoGerritFetch(self):
  1011. options = mock.Mock(
  1012. gerrit_url='https://foo-review.googlesource.com/bar',
  1013. gerrit_project='project',
  1014. gerrit_branch='refs/heads/main',
  1015. gerrit_fetch=False,
  1016. author='author',
  1017. description='description')
  1018. gerrit_obj = presubmit._parse_gerrit_options(None, options)
  1019. self.assertEqual('foo-review.googlesource.com', gerrit_obj.host)
  1020. self.assertEqual('project', gerrit_obj.project)
  1021. self.assertEqual('refs/heads/main', gerrit_obj.branch)
  1022. self.assertEqual('author', options.author)
  1023. self.assertEqual('description', options.description)
  1024. @mock.patch('presubmit_support.GerritAccessor.GetChangeOwner')
  1025. @mock.patch('presubmit_support.GerritAccessor.GetChangeDescription')
  1026. def testParseGerritOptions_GerritFetch(self, mockDescription, mockOwner):
  1027. mockDescription.return_value = 'new description'
  1028. mockOwner.return_value = 'new owner'
  1029. options = mock.Mock(
  1030. gerrit_url='https://foo-review.googlesource.com/bar',
  1031. gerrit_project='project',
  1032. gerrit_branch='refs/heads/main',
  1033. gerrit_fetch=True,
  1034. issue=123,
  1035. patchset=4)
  1036. gerrit_obj = presubmit._parse_gerrit_options(None, options)
  1037. self.assertEqual('foo-review.googlesource.com', gerrit_obj.host)
  1038. self.assertEqual('project', gerrit_obj.project)
  1039. self.assertEqual('refs/heads/main', gerrit_obj.branch)
  1040. self.assertEqual('new owner', options.author)
  1041. self.assertEqual('new description', options.description)
  1042. def testParseGerritOptions_GerritFetchNoUrl(self):
  1043. parser = mock.Mock()
  1044. parser.error.side_effect = [SystemExit]
  1045. options = mock.Mock(gerrit_url=None,
  1046. gerrit_fetch=True,
  1047. issue=123,
  1048. patchset=4)
  1049. with self.assertRaises(SystemExit):
  1050. presubmit._parse_gerrit_options(parser, options)
  1051. parser.error.assert_called_once_with(
  1052. '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
  1053. def testParseGerritOptions_GerritFetchNoIssue(self):
  1054. parser = mock.Mock()
  1055. parser.error.side_effect = [SystemExit]
  1056. options = mock.Mock(gerrit_url='https://example.com',
  1057. gerrit_fetch=True,
  1058. issue=None,
  1059. patchset=4)
  1060. with self.assertRaises(SystemExit):
  1061. presubmit._parse_gerrit_options(parser, options)
  1062. parser.error.assert_called_once_with(
  1063. '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
  1064. def testParseGerritOptions_GerritFetchNoPatchset(self):
  1065. parser = mock.Mock()
  1066. parser.error.side_effect = [SystemExit]
  1067. options = mock.Mock(gerrit_url='https://example.com',
  1068. gerrit_fetch=True,
  1069. issue=123,
  1070. patchset=None)
  1071. with self.assertRaises(SystemExit):
  1072. presubmit._parse_gerrit_options(parser, options)
  1073. parser.error.assert_called_once_with(
  1074. '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
  1075. class InputApiUnittest(PresubmitTestsBase):
  1076. """Tests presubmit.InputApi."""
  1077. def testInputApiConstruction(self):
  1078. api = presubmit.InputApi(self.fake_change,
  1079. presubmit_path='foo/path/PRESUBMIT.py',
  1080. is_committing=False,
  1081. gerrit_obj=None,
  1082. verbose=False)
  1083. self.assertEqual(api.PresubmitLocalPath(), 'foo/path')
  1084. self.assertEqual(api.change, self.fake_change)
  1085. def testInputApiPresubmitScriptFiltering(self):
  1086. description_lines = ('Hello there', 'this is a change', 'BUG=123',
  1087. ' STORY =http://foo/ \t',
  1088. 'and some more regular text')
  1089. files = [
  1090. ['A', os.path.join('foo', 'blat.cc'), True],
  1091. ['M', os.path.join('foo', 'blat', 'READ_ME2'), True],
  1092. ['M', os.path.join('foo', 'blat', 'binary.dll'), True],
  1093. ['M', os.path.join('foo', 'blat', 'weird.xyz'), True],
  1094. ['M', os.path.join('foo', 'blat', 'another.h'), True],
  1095. ['M', os.path.join('foo', 'third_party', 'third.cc'), True],
  1096. ['D', os.path.join('foo', 'mat', 'beingdeleted.txt'), False],
  1097. ['M', os.path.join('flop', 'notfound.txt'), False],
  1098. ['A', os.path.join('boo', 'flap.h'), True],
  1099. ]
  1100. diffs = []
  1101. known_files = []
  1102. for _, f, exists in files:
  1103. full_file = os.path.join(self.fake_root_dir, f)
  1104. if exists and f.startswith('foo'):
  1105. known_files.append(full_file)
  1106. diffs.append(self.presubmit_diffs % {'filename': f})
  1107. os.path.isfile.side_effect = lambda f: f in known_files
  1108. presubmit.scm.GIT.GenerateDiff.return_value = '\n'.join(diffs)
  1109. change = presubmit.GitChange('mychange',
  1110. '\n'.join(description_lines),
  1111. self.fake_root_dir,
  1112. [[f[0], f[1]] for f in files],
  1113. 0,
  1114. 0,
  1115. None,
  1116. upstream='upstream',
  1117. end_commit='HEAD')
  1118. input_api = presubmit.InputApi(
  1119. change, os.path.join(self.fake_root_dir, 'foo', 'PRESUBMIT.py'),
  1120. False, None, False)
  1121. # Doesn't filter much
  1122. got_files = input_api.AffectedFiles()
  1123. self.assertEqual(len(got_files), 7)
  1124. self.assertEqual(got_files[0].LocalPath(),
  1125. presubmit.normpath(files[0][1]))
  1126. self.assertEqual(got_files[1].LocalPath(),
  1127. presubmit.normpath(files[1][1]))
  1128. self.assertEqual(got_files[2].LocalPath(),
  1129. presubmit.normpath(files[2][1]))
  1130. self.assertEqual(got_files[3].LocalPath(),
  1131. presubmit.normpath(files[3][1]))
  1132. self.assertEqual(got_files[4].LocalPath(),
  1133. presubmit.normpath(files[4][1]))
  1134. self.assertEqual(got_files[5].LocalPath(),
  1135. presubmit.normpath(files[5][1]))
  1136. self.assertEqual(got_files[6].LocalPath(),
  1137. presubmit.normpath(files[6][1]))
  1138. # Ignores weird because of check_list, third_party because of skip_list,
  1139. # binary isn't a text file and being deleted doesn't exist. The rest is
  1140. # outside foo/.
  1141. rhs_lines = list(input_api.RightHandSideLines(None))
  1142. self.assertEqual(len(rhs_lines), 14)
  1143. self.assertEqual(rhs_lines[0][0].LocalPath(),
  1144. presubmit.normpath(files[0][1]))
  1145. self.assertEqual(rhs_lines[3][0].LocalPath(),
  1146. presubmit.normpath(files[0][1]))
  1147. self.assertEqual(rhs_lines[7][0].LocalPath(),
  1148. presubmit.normpath(files[4][1]))
  1149. self.assertEqual(rhs_lines[13][0].LocalPath(),
  1150. presubmit.normpath(files[4][1]))
  1151. def testInputApiFilterSourceFile(self):
  1152. files = [
  1153. ['A', os.path.join('foo', 'blat.cc')],
  1154. ['M', os.path.join('foo', 'blat', 'READ_ME2')],
  1155. ['M', os.path.join('foo', 'blat', 'binary.dll')],
  1156. ['M', os.path.join('foo', 'blat', 'weird.xyz')],
  1157. ['M', os.path.join('foo', 'blat', 'another.h')],
  1158. ['M',
  1159. os.path.join('foo', 'third_party', 'WebKit', 'WebKit.cpp')],
  1160. ['M',
  1161. os.path.join('foo', 'third_party', 'WebKit2', 'WebKit2.cpp')],
  1162. ['M', os.path.join('foo', 'third_party', 'blink', 'blink.cc')],
  1163. ['M',
  1164. os.path.join('foo', 'third_party', 'blink1', 'blink1.cc')],
  1165. ['M', os.path.join('foo', 'third_party', 'third', 'third.cc')],
  1166. ]
  1167. known_files = [os.path.join(self.fake_root_dir, f) for _, f in files]
  1168. os.path.isfile.side_effect = lambda f: f in known_files
  1169. change = presubmit.GitChange('mychange',
  1170. 'description\nlines\n',
  1171. self.fake_root_dir,
  1172. [[f[0], f[1]] for f in files],
  1173. 0,
  1174. 0,
  1175. None,
  1176. upstream='upstream',
  1177. end_commit='HEAD')
  1178. input_api = presubmit.InputApi(
  1179. change, os.path.join(self.fake_root_dir, 'foo', 'PRESUBMIT.py'),
  1180. False, None, False)
  1181. # We'd like to test FilterSourceFile, which is used by
  1182. # AffectedSourceFiles(None).
  1183. got_files = input_api.AffectedSourceFiles(None)
  1184. self.assertEqual(len(got_files), 4)
  1185. # blat.cc, another.h, WebKit.cpp, and blink.cc remain.
  1186. self.assertEqual(got_files[0].LocalPath(),
  1187. presubmit.normpath(files[0][1]))
  1188. self.assertEqual(got_files[1].LocalPath(),
  1189. presubmit.normpath(files[4][1]))
  1190. self.assertEqual(got_files[2].LocalPath(),
  1191. presubmit.normpath(files[5][1]))
  1192. self.assertEqual(got_files[3].LocalPath(),
  1193. presubmit.normpath(files[7][1]))
  1194. def testDefaultFilesToCheckFilesToSkipFilters(self):
  1195. def f(x):
  1196. return presubmit.AffectedFile(x, 'M', self.fake_root_dir, None)
  1197. files = [
  1198. (
  1199. [
  1200. # To be tested.
  1201. f('testing_support/google_appengine/b'),
  1202. f('testing_support/not_google_appengine/foo.cc'),
  1203. ],
  1204. [
  1205. # Expected.
  1206. 'testing_support/not_google_appengine/foo.cc',
  1207. ],
  1208. ),
  1209. (
  1210. [
  1211. # To be tested.
  1212. f('a/experimental/b'),
  1213. f('experimental/b'),
  1214. f('a/experimental'),
  1215. f('a/experimental.cc'),
  1216. f('a/experimental.S'),
  1217. ],
  1218. [
  1219. # Expected.
  1220. 'a/experimental.cc',
  1221. 'a/experimental.S',
  1222. ],
  1223. ),
  1224. (
  1225. [
  1226. # To be tested.
  1227. f('a/third_party/b'),
  1228. f('third_party/b'),
  1229. f('a/third_party'),
  1230. f('a/third_party.cc'),
  1231. ],
  1232. [
  1233. # Expected.
  1234. 'a/third_party.cc',
  1235. ],
  1236. ),
  1237. (
  1238. [
  1239. # To be tested.
  1240. f('a/LOL_FILE/b'),
  1241. f('b.c/LOL_FILE'),
  1242. f('a/PRESUBMIT.py'),
  1243. f('a/FOO.json'),
  1244. f('a/FOO.java'),
  1245. f('a/FOO.mojom'),
  1246. ],
  1247. [
  1248. # Expected.
  1249. 'a/PRESUBMIT.py',
  1250. 'a/FOO.java',
  1251. 'a/FOO.mojom',
  1252. ],
  1253. ),
  1254. (
  1255. [
  1256. # To be tested.
  1257. f('a/.git'),
  1258. f('b.c/.git'),
  1259. f('a/.git/bleh.py'),
  1260. f('.git/bleh.py'),
  1261. f('bleh.diff'),
  1262. f('foo/bleh.patch'),
  1263. ],
  1264. [
  1265. # Expected.
  1266. ],
  1267. ),
  1268. ]
  1269. input_api = presubmit.InputApi(self.fake_change, './PRESUBMIT.py',
  1270. False, None, False)
  1271. for item in files:
  1272. results = list(filter(input_api.FilterSourceFile, item[0]))
  1273. for i in range(len(results)):
  1274. self.assertEqual(results[i].LocalPath(),
  1275. presubmit.normpath(item[1][i]))
  1276. # Same number of expected results.
  1277. self.assertEqual(
  1278. sorted([f.LocalPath().replace(os.sep, '/') for f in results]),
  1279. sorted(item[1]))
  1280. def testDefaultOverrides(self):
  1281. input_api = presubmit.InputApi(self.fake_change, './PRESUBMIT.py',
  1282. False, None, False)
  1283. self.assertEqual(len(input_api.DEFAULT_FILES_TO_CHECK), 26)
  1284. self.assertEqual(len(input_api.DEFAULT_FILES_TO_SKIP), 12)
  1285. input_api.DEFAULT_FILES_TO_CHECK = (r'.+\.c$', )
  1286. input_api.DEFAULT_FILES_TO_SKIP = (r'.+\.patch$', r'.+\.diff')
  1287. self.assertEqual(len(input_api.DEFAULT_FILES_TO_CHECK), 1)
  1288. self.assertEqual(len(input_api.DEFAULT_FILES_TO_SKIP), 2)
  1289. def testCustomFilter(self):
  1290. def FilterSourceFile(affected_file):
  1291. return 'a' in affected_file.LocalPath()
  1292. files = [('A', 'eeaee'), ('M', 'eeabee'), ('M', 'eebcee')]
  1293. known_files = [
  1294. os.path.join(self.fake_root_dir, item) for _, item in files
  1295. ]
  1296. os.path.isfile.side_effect = lambda f: f in known_files
  1297. change = presubmit.GitChange('mychange',
  1298. '',
  1299. self.fake_root_dir,
  1300. files,
  1301. 0,
  1302. 0,
  1303. None,
  1304. upstream='upstream',
  1305. end_commit='HEAD')
  1306. input_api = presubmit.InputApi(
  1307. change, os.path.join(self.fake_root_dir, 'PRESUBMIT.py'), False,
  1308. None, False)
  1309. got_files = input_api.AffectedSourceFiles(FilterSourceFile)
  1310. self.assertEqual(len(got_files), 2)
  1311. self.assertEqual(got_files[0].LocalPath(), 'eeaee')
  1312. self.assertEqual(got_files[1].LocalPath(), 'eeabee')
  1313. def testLambdaFilter(self):
  1314. files_to_check = presubmit.InputApi.DEFAULT_FILES_TO_SKIP + (
  1315. r".*?a.*?", )
  1316. files_to_skip = [r".*?b.*?"]
  1317. files = [('A', 'eeaee'), ('M', 'eeabee'), ('M', 'eebcee'),
  1318. ('M', 'eecaee')]
  1319. known_files = [
  1320. os.path.join(self.fake_root_dir, item) for _, item in files
  1321. ]
  1322. os.path.isfile.side_effect = lambda f: f in known_files
  1323. change = presubmit.GitChange('mychange',
  1324. '',
  1325. self.fake_root_dir,
  1326. files,
  1327. 0,
  1328. 0,
  1329. None,
  1330. upstream='upstream',
  1331. end_commit='HEAD')
  1332. input_api = presubmit.InputApi(
  1333. change, os.path.join(self.fake_root_dir, 'PRESUBMIT.py'), False,
  1334. None, False)
  1335. # Sample usage of overriding the default white and black lists.
  1336. got_files = input_api.AffectedSourceFiles(
  1337. lambda x: input_api.FilterSourceFile(x, files_to_check,
  1338. files_to_skip))
  1339. self.assertEqual(len(got_files), 2)
  1340. self.assertEqual(got_files[0].LocalPath(), 'eeaee')
  1341. self.assertEqual(got_files[1].LocalPath(), 'eecaee')
  1342. def testGetAbsoluteLocalPath(self):
  1343. normpath = presubmit.normpath
  1344. # Regression test for bug of presubmit stuff that relies on invoking
  1345. # SVN (e.g. to get mime type of file) not working unless gcl invoked
  1346. # from the client root (e.g. if you were at 'src' and did 'cd base'
  1347. # before invoking 'gcl upload' it would fail because svn wouldn't find
  1348. # the files the presubmit script was asking about).
  1349. files = [
  1350. ['A', 'isdir'],
  1351. ['A', os.path.join('isdir', 'blat.cc')],
  1352. ['M', os.path.join('elsewhere', 'ouf.cc')],
  1353. ]
  1354. change = presubmit.Change('mychange', '', self.fake_root_dir, files, 0,
  1355. 0, None)
  1356. affected_files = change.AffectedFiles()
  1357. # Validate that normpath strips trailing path separators.
  1358. self.assertEqual('isdir', normpath('isdir/'))
  1359. # Local paths should remain the same
  1360. self.assertEqual(affected_files[0].LocalPath(), normpath('isdir'))
  1361. self.assertEqual(affected_files[1].LocalPath(),
  1362. normpath('isdir/blat.cc'))
  1363. # Absolute paths should be prefixed
  1364. self.assertEqual(
  1365. affected_files[0].AbsoluteLocalPath(),
  1366. presubmit.normpath(os.path.join(self.fake_root_dir, 'isdir')))
  1367. self.assertEqual(
  1368. affected_files[1].AbsoluteLocalPath(),
  1369. presubmit.normpath(os.path.join(self.fake_root_dir,
  1370. 'isdir/blat.cc')))
  1371. # New helper functions need to work
  1372. paths_from_change = change.AbsoluteLocalPaths()
  1373. self.assertEqual(len(paths_from_change), 3)
  1374. presubmit_path = os.path.join(self.fake_root_dir, 'isdir',
  1375. 'PRESUBMIT.py')
  1376. api = presubmit.InputApi(change=change,
  1377. presubmit_path=presubmit_path,
  1378. is_committing=True,
  1379. gerrit_obj=None,
  1380. verbose=False)
  1381. paths_from_api = api.AbsoluteLocalPaths()
  1382. self.assertEqual(len(paths_from_api), 1)
  1383. self.assertEqual(
  1384. paths_from_change[0],
  1385. presubmit.normpath(os.path.join(self.fake_root_dir, 'isdir')))
  1386. self.assertEqual(
  1387. paths_from_change[1],
  1388. presubmit.normpath(
  1389. os.path.join(self.fake_root_dir, 'isdir', 'blat.cc')))
  1390. self.assertEqual(
  1391. paths_from_api[0],
  1392. presubmit.normpath(
  1393. os.path.join(self.fake_root_dir, 'isdir', 'blat.cc')))
  1394. def testDeprecated(self):
  1395. change = presubmit.Change('mychange', '', self.fake_root_dir, [], 0, 0,
  1396. None)
  1397. api = presubmit.InputApi(
  1398. change, os.path.join(self.fake_root_dir, 'foo', 'PRESUBMIT.py'),
  1399. True, None, False)
  1400. api.AffectedTestableFiles(include_deletes=False)
  1401. def testReadFileStringDenied(self):
  1402. change = presubmit.Change('foo', 'foo', self.fake_root_dir,
  1403. [('M', 'AA')], 0, 0, None)
  1404. input_api = presubmit.InputApi(change,
  1405. os.path.join(self.fake_root_dir, '/p'),
  1406. False, None, False)
  1407. self.assertRaises(IOError, input_api.ReadFile, 'boo', 'x')
  1408. def testReadFileStringAccepted(self):
  1409. path = os.path.join(self.fake_root_dir, 'AA/boo')
  1410. presubmit.gclient_utils.FileRead.return_code = None
  1411. change = presubmit.Change('foo', 'foo', self.fake_root_dir,
  1412. [('M', 'AA')], 0, 0, None)
  1413. input_api = presubmit.InputApi(change,
  1414. os.path.join(self.fake_root_dir, '/p'),
  1415. False, None, False)
  1416. input_api.ReadFile(path, 'x')
  1417. def testReadFileAffectedFileDenied(self):
  1418. fileobj = presubmit.AffectedFile('boo',
  1419. 'M',
  1420. 'Unrelated',
  1421. diff_cache=mock.Mock())
  1422. change = presubmit.Change('foo', 'foo', self.fake_root_dir,
  1423. [('M', 'AA')], 0, 0, None)
  1424. input_api = presubmit.InputApi(change,
  1425. os.path.join(self.fake_root_dir, '/p'),
  1426. False, None, False)
  1427. self.assertRaises(IOError, input_api.ReadFile, fileobj, 'x')
  1428. def testReadFileAffectedFileAccepted(self):
  1429. fileobj = presubmit.AffectedFile('AA/boo',
  1430. 'M',
  1431. self.fake_root_dir,
  1432. diff_cache=mock.Mock())
  1433. presubmit.gclient_utils.FileRead.return_code = None
  1434. change = presubmit.Change('foo', 'foo', self.fake_root_dir,
  1435. [('M', 'AA')], 0, 0, None)
  1436. input_api = presubmit.InputApi(change,
  1437. os.path.join(self.fake_root_dir, '/p'),
  1438. False, None, False)
  1439. input_api.ReadFile(fileobj, 'x')
  1440. def testCreateTemporaryFile(self):
  1441. input_api = presubmit.InputApi(self.fake_change,
  1442. presubmit_path='foo/path/PRESUBMIT.py',
  1443. is_committing=False,
  1444. gerrit_obj=None,
  1445. verbose=False)
  1446. tempfile.NamedTemporaryFile.side_effect = [
  1447. MockTemporaryFile('foo'),
  1448. MockTemporaryFile('bar')
  1449. ]
  1450. self.assertEqual(0, len(input_api._named_temporary_files))
  1451. with input_api.CreateTemporaryFile():
  1452. self.assertEqual(1, len(input_api._named_temporary_files))
  1453. self.assertEqual(['foo'], input_api._named_temporary_files)
  1454. with input_api.CreateTemporaryFile():
  1455. self.assertEqual(2, len(input_api._named_temporary_files))
  1456. self.assertEqual(2, len(input_api._named_temporary_files))
  1457. self.assertEqual(['foo', 'bar'], input_api._named_temporary_files)
  1458. self.assertRaises(TypeError, input_api.CreateTemporaryFile, delete=True)
  1459. self.assertRaises(TypeError,
  1460. input_api.CreateTemporaryFile,
  1461. delete=False)
  1462. self.assertEqual(['foo', 'bar'], input_api._named_temporary_files)
  1463. class OutputApiUnittest(PresubmitTestsBase):
  1464. """Tests presubmit.OutputApi."""
  1465. def testOutputApiBasics(self):
  1466. self.assertIsNotNone(presubmit.OutputApi.PresubmitError('').fatal)
  1467. self.assertFalse(presubmit.OutputApi.PresubmitError('').should_prompt)
  1468. self.assertFalse(presubmit.OutputApi.PresubmitPromptWarning('').fatal)
  1469. self.assertIsNotNone(
  1470. presubmit.OutputApi.PresubmitPromptWarning('').should_prompt)
  1471. self.assertFalse(presubmit.OutputApi.PresubmitNotifyResult('').fatal)
  1472. self.assertFalse(
  1473. presubmit.OutputApi.PresubmitNotifyResult('').should_prompt)
  1474. # TODO(joi) Test MailTextResult once implemented.
  1475. def testAppendCC(self):
  1476. output_api = presubmit.OutputApi(False)
  1477. output_api.AppendCC('chromium-reviews@chromium.org')
  1478. self.assertEqual(['chromium-reviews@chromium.org'], output_api.more_cc)
  1479. def testAppendCCAndMultipleChecks(self):
  1480. description_lines = ('Hello there', 'this is a change', 'BUG=123')
  1481. files = [
  1482. ['A', 'foo\\blat.cc'],
  1483. ]
  1484. fake_presubmit = os.path.join(self.fake_root_dir, 'PRESUBMIT.py')
  1485. change = presubmit.Change('mychange', '\n'.join(description_lines),
  1486. self.fake_root_dir, files, 0, 0, None)
  1487. # Base case: AppendCC from multiple different checks should be reflected
  1488. # in the final result.
  1489. executer = presubmit.PresubmitExecuter(change, True, None,
  1490. presubmit.GerritAccessor())
  1491. self.assertFalse(
  1492. executer.ExecPresubmitScript(
  1493. "PRESUBMIT_VERSION = '2.0.0'\n"
  1494. 'def CheckChangeAddCC1(input_api, output_api):\n'
  1495. " output_api.AppendCC('chromium-reviews@chromium.org')\n"
  1496. ' return []\n'
  1497. '\n'
  1498. 'def CheckChangeAppendCC2(input_api, output_api):\n'
  1499. " output_api.AppendCC('ipc-security-reviews@chromium.org')\n"
  1500. ' return []\n', fake_presubmit))
  1501. self.assertEqual([
  1502. 'chromium-reviews@chromium.org', 'ipc-security-reviews@chromium.org'
  1503. ], executer.more_cc)
  1504. # Check that if one presubmit check appends a CC, it does not get
  1505. # duplicated into the more CC list by subsequent checks.
  1506. executer = presubmit.PresubmitExecuter(change, True, None,
  1507. presubmit.GerritAccessor())
  1508. self.assertFalse(
  1509. executer.ExecPresubmitScript(
  1510. "PRESUBMIT_VERSION = '2.0.0'\n"
  1511. 'def CheckChangeAddCC(input_api, output_api):\n'
  1512. " output_api.AppendCC('chromium-reviews@chromium.org')\n"
  1513. ' return []\n'
  1514. '\n'
  1515. 'def CheckChangeDoNothing(input_api, output_api):\n'
  1516. ' return []\n', fake_presubmit))
  1517. self.assertEqual(['chromium-reviews@chromium.org'], executer.more_cc)
  1518. # Check that if multiple presubmit checks append the same CC, it gets
  1519. # deduplicated.
  1520. executer = presubmit.PresubmitExecuter(change, True, None,
  1521. presubmit.GerritAccessor())
  1522. self.assertFalse(
  1523. executer.ExecPresubmitScript(
  1524. "PRESUBMIT_VERSION = '2.0.0'\n"
  1525. 'def CheckChangeAddCC1(input_api, output_api):\n'
  1526. " output_api.AppendCC('chromium-reviews@chromium.org')\n"
  1527. ' return []\n'
  1528. '\n'
  1529. 'def CheckChangeAppendCC2(input_api, output_api):\n'
  1530. " output_api.AppendCC('chromium-reviews@chromium.org')\n"
  1531. ' return []\n', fake_presubmit))
  1532. self.assertEqual(['chromium-reviews@chromium.org'], executer.more_cc)
  1533. def testOutputApiHandling(self):
  1534. presubmit.OutputApi.PresubmitError('!!!').handle()
  1535. self.assertIsNotNone(sys.stdout.getvalue().count('!!!'))
  1536. sys.stdout.truncate(0)
  1537. presubmit.OutputApi.PresubmitNotifyResult('?see?').handle()
  1538. self.assertIsNotNone(sys.stdout.getvalue().count('?see?'))
  1539. sys.stdout.truncate(0)
  1540. presubmit.OutputApi.PresubmitPromptWarning('???').handle()
  1541. self.assertIsNotNone(sys.stdout.getvalue().count('???'))
  1542. sys.stdout.truncate(0)
  1543. output_api = presubmit.OutputApi(True)
  1544. output_api.PresubmitPromptOrNotify('???').handle()
  1545. self.assertIsNotNone(sys.stdout.getvalue().count('???'))
  1546. sys.stdout.truncate(0)
  1547. output_api = presubmit.OutputApi(False)
  1548. output_api.PresubmitPromptOrNotify('???').handle()
  1549. self.assertIsNotNone(sys.stdout.getvalue().count('???'))
  1550. class AffectedFileUnittest(PresubmitTestsBase):
  1551. def testAffectedFile(self):
  1552. gclient_utils.FileRead.return_value = 'whatever\ncookie'
  1553. af = presubmit.GitAffectedFile('foo/blat.cc', 'M', self.fake_root_dir,
  1554. None)
  1555. self.assertEqual(presubmit.normpath('foo/blat.cc'), af.LocalPath())
  1556. self.assertEqual('M', af.Action())
  1557. self.assertEqual(['whatever', 'cookie'], af.NewContents())
  1558. def testAffectedFileNotExists(self):
  1559. notfound = 'notfound.cc'
  1560. gclient_utils.FileRead.side_effect = IOError
  1561. af = presubmit.AffectedFile(notfound, 'A', self.fake_root_dir, None)
  1562. self.assertEqual([], af.NewContents())
  1563. def testIsTestableFile(self):
  1564. files = [
  1565. presubmit.GitAffectedFile('foo/blat.txt', 'M', self.fake_root_dir,
  1566. None),
  1567. presubmit.GitAffectedFile('foo/binary.blob', 'M',
  1568. self.fake_root_dir, None),
  1569. presubmit.GitAffectedFile('blat/flop.txt', 'D', self.fake_root_dir,
  1570. None)
  1571. ]
  1572. blat = os.path.join('foo', 'blat.txt')
  1573. blob = os.path.join('foo', 'binary.blob')
  1574. f_blat = os.path.join(self.fake_root_dir, blat)
  1575. f_blob = os.path.join(self.fake_root_dir, blob)
  1576. os.path.isfile.side_effect = lambda f: f in [f_blat, f_blob]
  1577. output = list(filter(lambda x: x.IsTestableFile(), files))
  1578. self.assertEqual(2, len(output))
  1579. self.assertEqual(files[:2], output[:2])
  1580. class ChangeUnittest(PresubmitTestsBase):
  1581. def testAffectedFiles(self):
  1582. change = presubmit.Change('', '', self.fake_root_dir, [('Y', 'AA'),
  1583. ('A', 'BB')], 3,
  1584. 5, '')
  1585. self.assertEqual(2, len(change.AffectedFiles()))
  1586. self.assertEqual('Y', change.AffectedFiles()[0].Action())
  1587. @mock.patch('scm.GIT.ListSubmodules', return_value=['BB'])
  1588. def testAffectedSubmodules(self, mockListSubmodules):
  1589. change = presubmit.GitChange('',
  1590. '',
  1591. self.fake_root_dir, [('Y', 'AA'),
  1592. ('A', 'BB')],
  1593. 3,
  1594. 5,
  1595. '',
  1596. upstream='upstream',
  1597. end_commit='HEAD')
  1598. self.assertEqual(1, len(change.AffectedSubmodules()))
  1599. self.assertEqual('A', change.AffectedSubmodules()[0].Action())
  1600. @mock.patch('scm.GIT.ListSubmodules', return_value=['BB'])
  1601. def testAffectedSubmodulesCachesSubmodules(self, mockListSubmodules):
  1602. change = presubmit.GitChange('',
  1603. '',
  1604. self.fake_root_dir, [('Y', 'AA'),
  1605. ('A', 'BB')],
  1606. 3,
  1607. 5,
  1608. '',
  1609. upstream='upstream',
  1610. end_commit='HEAD')
  1611. change.AffectedSubmodules()
  1612. mockListSubmodules.assert_called_once()
  1613. change.AffectedSubmodules()
  1614. mockListSubmodules.assert_called_once()
  1615. def testSetDescriptionText(self):
  1616. change = presubmit.Change('', 'foo\nDRU=ro', self.fake_root_dir, [], 3,
  1617. 5, '')
  1618. self.assertEqual('foo', change.DescriptionText())
  1619. self.assertEqual('foo\nDRU=ro', change.FullDescriptionText())
  1620. self.assertEqual({'DRU': 'ro'}, change.tags)
  1621. change.SetDescriptionText('WHIZ=bang\nbar\nFOO=baz')
  1622. self.assertEqual('bar', change.DescriptionText())
  1623. self.assertEqual('WHIZ=bang\nbar\nFOO=baz',
  1624. change.FullDescriptionText())
  1625. self.assertEqual({'WHIZ': 'bang', 'FOO': 'baz'}, change.tags)
  1626. def testAddDescriptionFooter(self):
  1627. change = presubmit.Change('', 'foo\nDRU=ro\n\nChange-Id: asdf',
  1628. self.fake_root_dir, [], 3, 5, '')
  1629. change.AddDescriptionFooter('my-footer', 'my-value')
  1630. self.assertEqual('foo\nDRU=ro\n\nChange-Id: asdf\nMy-Footer: my-value',
  1631. change.FullDescriptionText())
  1632. def testAddDescriptionFooter_NoPreviousFooters(self):
  1633. change = presubmit.Change('', 'foo\nDRU=ro', self.fake_root_dir, [], 3,
  1634. 5, '')
  1635. change.AddDescriptionFooter('my-footer', 'my-value')
  1636. self.assertEqual('foo\nDRU=ro\n\nMy-Footer: my-value',
  1637. change.FullDescriptionText())
  1638. def testAddDescriptionFooter_InvalidFooter(self):
  1639. change = presubmit.Change('', 'foo\nDRU=ro', self.fake_root_dir, [], 3,
  1640. 5, '')
  1641. with self.assertRaises(ValueError):
  1642. change.AddDescriptionFooter('invalid.characters in:the',
  1643. 'footer key')
  1644. def testGitFootersFromDescription(self):
  1645. change = presubmit.Change(
  1646. '', 'foo\n\nChange-Id: asdf\nBug: 1\nBug: 2\nNo-Try: True',
  1647. self.fake_root_dir, [], 0, 0, '')
  1648. self.assertEqual(
  1649. {
  1650. 'Change-Id': ['asdf'],
  1651. 'Bug': ['2', '1'],
  1652. 'No-Try': ['True'],
  1653. }, change.GitFootersFromDescription())
  1654. def testGitFootersFromDescription_NoFooters(self):
  1655. change = presubmit.Change('', 'foo', self.fake_root_dir, [], 0, 0, '')
  1656. self.assertEqual({}, change.GitFootersFromDescription())
  1657. def testBugFromDescription_FixedAndBugGetDeduped(self):
  1658. change = presubmit.Change(
  1659. '', 'foo\n\nChange-Id: asdf\nBug: 1, 2\nFixed:2, 1 ',
  1660. self.fake_root_dir, [], 0, 0, '')
  1661. self.assertEqual(['1', '2'], change.BugsFromDescription())
  1662. self.assertEqual('1,2', change.BUG)
  1663. def testBugsFromDescription_MixedTagsAndFooters(self):
  1664. change = presubmit.Change('',
  1665. 'foo\nBUG=2,1\n\nChange-Id: asdf\nBug: 3, 6',
  1666. self.fake_root_dir, [], 0, 0, '')
  1667. self.assertEqual(['1', '2', '3', '6'], change.BugsFromDescription())
  1668. self.assertEqual('1,2,3,6', change.BUG)
  1669. def testBugsFromDescription_MultipleFooters(self):
  1670. change = presubmit.Change(
  1671. '', 'foo\n\nChange-Id: asdf\nBug: 1\nBug:4, 6\nFixed: 7',
  1672. self.fake_root_dir, [], 0, 0, '')
  1673. self.assertEqual(['1', '4', '6', '7'], change.BugsFromDescription())
  1674. self.assertEqual('1,4,6,7', change.BUG)
  1675. def testBugFromDescription_OnlyFixed(self):
  1676. change = presubmit.Change('', 'foo\n\nChange-Id: asdf\nFixed:1, 2',
  1677. self.fake_root_dir, [], 0, 0, '')
  1678. self.assertEqual(['1', '2'], change.BugsFromDescription())
  1679. self.assertEqual('1,2', change.BUG)
  1680. def testReviewersFromDescription(self):
  1681. change = presubmit.Change('',
  1682. 'foo\nR=foo,bar\n\nChange-Id: asdf\nR: baz',
  1683. self.fake_root_dir, [], 0, 0, '')
  1684. self.assertEqual(['bar', 'foo'], change.ReviewersFromDescription())
  1685. self.assertEqual('bar,foo', change.R)
  1686. def testTBRsFromDescription(self):
  1687. change = presubmit.Change(
  1688. '', 'foo\nTBR=foo,bar\n\nChange-Id: asdf\nTBR: baz',
  1689. self.fake_root_dir, [], 0, 0, '')
  1690. self.assertEqual(['bar', 'baz', 'foo'], change.TBRsFromDescription())
  1691. self.assertEqual('bar,baz,foo', change.TBR)
  1692. class CannedChecksUnittest(PresubmitTestsBase):
  1693. """Tests presubmit_canned_checks.py."""
  1694. def MockInputApi(self, change, committing, gerrit=None):
  1695. # pylint: disable=no-self-use
  1696. input_api = mock.MagicMock(presubmit.InputApi)
  1697. input_api.thread_pool = presubmit.ThreadPool()
  1698. input_api.parallel = False
  1699. input_api.json = presubmit.json
  1700. input_api.logging = logging
  1701. input_api.os_listdir = mock.Mock()
  1702. input_api.os_walk = mock.Mock()
  1703. input_api.os_path = os.path
  1704. input_api.re = presubmit.re
  1705. input_api.gerrit = gerrit
  1706. input_api.urllib_request = mock.MagicMock(presubmit.urllib_request)
  1707. input_api.urllib_error = mock.MagicMock(presubmit.urllib_error)
  1708. input_api.unittest = unittest
  1709. input_api.subprocess = subprocess
  1710. input_api.sys = sys
  1711. class fake_CalledProcessError(Exception):
  1712. def __str__(self):
  1713. return 'foo'
  1714. input_api.subprocess.CalledProcessError = fake_CalledProcessError
  1715. input_api.verbose = False
  1716. input_api.is_windows = False
  1717. input_api.no_diffs = False
  1718. input_api.change = change
  1719. input_api.is_committing = committing
  1720. input_api.tbr = False
  1721. input_api.dry_run = None
  1722. input_api.python_executable = 'pyyyyython'
  1723. input_api.python3_executable = 'pyyyyython3'
  1724. input_api.platform = sys.platform
  1725. input_api.cpu_count = 2
  1726. input_api.time = time
  1727. input_api.canned_checks = presubmit_canned_checks
  1728. input_api.Command = presubmit.CommandData
  1729. input_api.RunTests = functools.partial(presubmit.InputApi.RunTests,
  1730. input_api)
  1731. return input_api
  1732. def DescriptionTest(self, check, description1, description2, error_type,
  1733. committing):
  1734. change1 = presubmit.Change('foo1', description1, self.fake_root_dir,
  1735. None, 0, 0, None)
  1736. input_api1 = self.MockInputApi(change1, committing)
  1737. change2 = presubmit.Change('foo2', description2, self.fake_root_dir,
  1738. None, 0, 0, None)
  1739. input_api2 = self.MockInputApi(change2, committing)
  1740. results1 = check(input_api1, presubmit.OutputApi)
  1741. self.assertEqual(results1, [])
  1742. results2 = check(input_api2, presubmit.OutputApi)
  1743. self.assertEqual(len(results2), 1)
  1744. self.assertTrue(isinstance(results2[0], error_type))
  1745. def ContentTest(self, check, content1, content1_path, content2,
  1746. content2_path, error_type):
  1747. """Runs a test of a content-checking rule.
  1748. Args:
  1749. check: the check to run.
  1750. content1: content which is expected to pass the check.
  1751. content1_path: file path for content1.
  1752. content2: content which is expected to fail the check.
  1753. content2_path: file path for content2.
  1754. error_type: the type of the error expected for content2.
  1755. """
  1756. change1 = presubmit.Change('foo1', 'foo1\n', self.fake_root_dir, None,
  1757. 0, 0, None)
  1758. input_api1 = self.MockInputApi(change1, False)
  1759. affected_file1 = mock.MagicMock(presubmit.GitAffectedFile)
  1760. input_api1.AffectedFiles.return_value = [affected_file1]
  1761. affected_file1.LocalPath.return_value = content1_path
  1762. affected_file1.NewContents.return_value = [
  1763. 'afoo', content1, 'bfoo', 'cfoo', 'dfoo'
  1764. ]
  1765. # It falls back to ChangedContents when there is a failure. This is an
  1766. # optimization since NewContents() is much faster to execute than
  1767. # ChangedContents().
  1768. affected_file1.ChangedContents.return_value = [(42, content1),
  1769. (43, 'hfoo'),
  1770. (23, 'ifoo')]
  1771. change2 = presubmit.Change('foo2', 'foo2\n', self.fake_root_dir, None,
  1772. 0, 0, None)
  1773. input_api2 = self.MockInputApi(change2, False)
  1774. affected_file2 = mock.MagicMock(presubmit.GitAffectedFile)
  1775. input_api2.AffectedFiles.return_value = [affected_file2]
  1776. affected_file2.LocalPath.return_value = content2_path
  1777. affected_file2.NewContents.return_value = [
  1778. 'dfoo', content2, 'efoo', 'ffoo', 'gfoo'
  1779. ]
  1780. affected_file2.ChangedContents.return_value = [(42, content2),
  1781. (43, 'hfoo'),
  1782. (23, 'ifoo')]
  1783. results1 = check(input_api1, presubmit.OutputApi, None)
  1784. self.assertEqual(results1, [])
  1785. results2 = check(input_api2, presubmit.OutputApi, None)
  1786. self.assertEqual(len(results2), 1)
  1787. self.assertEqual(results2[0].__class__, error_type)
  1788. def PythonLongLineTest(self, maxlen, content, should_pass):
  1789. """Runs a test of Python long-line checking rule.
  1790. Because ContentTest() cannot be used here due to the different code path
  1791. that the implementation of CheckLongLines() uses for Python files.
  1792. Args:
  1793. maxlen: Maximum line length for content.
  1794. content: Python source which is expected to pass or fail the test.
  1795. should_pass: True iff the test should pass, False otherwise.
  1796. """
  1797. change = presubmit.Change('foo1', 'foo1\n', self.fake_root_dir, None, 0,
  1798. 0, None)
  1799. input_api = self.MockInputApi(change, False)
  1800. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  1801. input_api.AffectedFiles.return_value = [affected_file]
  1802. affected_file.LocalPath.return_value = 'foo.py'
  1803. affected_file.NewContents.return_value = content.splitlines()
  1804. results = presubmit_canned_checks.CheckLongLines(
  1805. input_api, presubmit.OutputApi, maxlen)
  1806. if should_pass:
  1807. self.assertEqual(results, [])
  1808. else:
  1809. self.assertEqual(len(results), 1)
  1810. self.assertEqual(results[0].__class__,
  1811. presubmit.OutputApi.PresubmitPromptWarning)
  1812. def ReadFileTest(self, check, content1, content2, error_type):
  1813. change1 = presubmit.Change('foo1', 'foo1\n', self.fake_root_dir, None,
  1814. 0, 0, None)
  1815. input_api1 = self.MockInputApi(change1, False)
  1816. affected_file1 = mock.MagicMock(presubmit.GitAffectedFile)
  1817. input_api1.AffectedSourceFiles.return_value = [affected_file1]
  1818. input_api1.ReadFile.return_value = content1
  1819. change2 = presubmit.Change('foo2', 'foo2\n', self.fake_root_dir, None,
  1820. 0, 0, None)
  1821. input_api2 = self.MockInputApi(change2, False)
  1822. affected_file2 = mock.MagicMock(presubmit.GitAffectedFile)
  1823. input_api2.AffectedSourceFiles.return_value = [affected_file2]
  1824. input_api2.ReadFile.return_value = content2
  1825. affected_file2.LocalPath.return_value = 'bar.cc'
  1826. results = check(input_api1, presubmit.OutputApi)
  1827. self.assertEqual(results, [])
  1828. results2 = check(input_api2, presubmit.OutputApi)
  1829. self.assertEqual(len(results2), 1)
  1830. self.assertEqual(results2[0].__class__, error_type)
  1831. def testCannedCheckChangeHasBugField(self):
  1832. self.DescriptionTest(presubmit_canned_checks.CheckChangeHasBugField,
  1833. 'Foo\nBUG=b:1234', 'Foo\n',
  1834. presubmit.OutputApi.PresubmitNotifyResult, False)
  1835. def testCannedCheckChangeHasBugFieldWithBuganizerSlash(self):
  1836. self.DescriptionTest(presubmit_canned_checks.CheckChangeHasBugField,
  1837. 'Foo\nBUG=b:1234', 'Foo\nBUG=b/1234',
  1838. presubmit.OutputApi.PresubmitNotifyResult, False)
  1839. def testCannedCheckChangeHasNoUnwantedTags(self):
  1840. self.DescriptionTest(
  1841. presubmit_canned_checks.CheckChangeHasNoUnwantedTags, 'Foo\n',
  1842. 'Foo\nFIXED=1234', presubmit.OutputApi.PresubmitError, False)
  1843. def testCheckChangeHasDescription(self):
  1844. self.DescriptionTest(presubmit_canned_checks.CheckChangeHasDescription,
  1845. 'Bleh', '',
  1846. presubmit.OutputApi.PresubmitNotifyResult, False)
  1847. self.DescriptionTest(presubmit_canned_checks.CheckChangeHasDescription,
  1848. 'Bleh', '', presubmit.OutputApi.PresubmitError,
  1849. True)
  1850. def testCannedCheckDoNotSubmitInDescription(self):
  1851. self.DescriptionTest(
  1852. presubmit_canned_checks.CheckDoNotSubmitInDescription,
  1853. 'Foo\nDO NOTSUBMIT', 'Foo\nDO NOT ' + 'SUBMIT',
  1854. presubmit.OutputApi.PresubmitError, False)
  1855. def testCannedCheckDoNotSubmitInFiles(self):
  1856. self.ContentTest(
  1857. lambda x, y, z: presubmit_canned_checks.CheckDoNotSubmitInFiles(
  1858. x, y), 'DO NOTSUBMIT', None, 'DO NOT ' + 'SUBMIT', None,
  1859. presubmit.OutputApi.PresubmitError)
  1860. def testCannedCheckCorpLinksInDescription(self):
  1861. self.DescriptionTest(
  1862. presubmit_canned_checks.CheckCorpLinksInDescription,
  1863. 'chromium.googlesource.com', 'chromium.git.corp.google.com',
  1864. presubmit.OutputApi.PresubmitPromptWarning, False)
  1865. def testCannedCheckCorpLinksInFiles(self):
  1866. self.ContentTest(presubmit_canned_checks.CheckCorpLinksInFiles,
  1867. 'chromium.googlesource.com', None,
  1868. 'chromium.git.corp.google.com', None,
  1869. presubmit.OutputApi.PresubmitPromptWarning)
  1870. def testCannedCheckLargeScaleChange(self):
  1871. input_api = self.MockInputApi(
  1872. presubmit.Change('foo', 'foo1', self.fake_root_dir, None, 0, 0,
  1873. None), False)
  1874. affected_files = []
  1875. for i in range(100):
  1876. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  1877. affected_file.LocalPath.return_value = f'foo{i}.cc'
  1878. affected_files.append(affected_file)
  1879. input_api.AffectedFiles = lambda **_: affected_files
  1880. # Don't warn if less than or equal to 100 files.
  1881. results = presubmit_canned_checks.CheckLargeScaleChange(
  1882. input_api, presubmit.OutputApi)
  1883. self.assertEqual(len(results), 0)
  1884. # Warn if greater than 100 files.
  1885. affected_files.append('bar.cc')
  1886. results = presubmit_canned_checks.CheckLargeScaleChange(
  1887. input_api, presubmit.OutputApi)
  1888. self.assertEqual(len(results), 1)
  1889. result = results[0]
  1890. self.assertEqual(result.__class__,
  1891. presubmit.OutputApi.PresubmitPromptWarning)
  1892. self.assertIn("large scale change", result.json_format()['message'])
  1893. def testCheckChangeHasNoStrayWhitespace(self):
  1894. self.ContentTest(
  1895. lambda x, y, z: presubmit_canned_checks.
  1896. CheckChangeHasNoStrayWhitespace(x, y), 'Foo', None, 'Foo ', None,
  1897. presubmit.OutputApi.PresubmitPromptWarning)
  1898. def testCheckChangeHasOnlyOneEol(self):
  1899. self.ReadFileTest(presubmit_canned_checks.CheckChangeHasOnlyOneEol,
  1900. "Hey!\nHo!\n", "Hey!\nHo!\n\n",
  1901. presubmit.OutputApi.PresubmitPromptWarning)
  1902. def testCheckChangeHasNoCR(self):
  1903. self.ReadFileTest(presubmit_canned_checks.CheckChangeHasNoCR,
  1904. "Hey!\nHo!\n", "Hey!\r\nHo!\r\n",
  1905. presubmit.OutputApi.PresubmitPromptWarning)
  1906. def testCheckChangeHasNoCrAndHasOnlyOneEol(self):
  1907. self.ReadFileTest(
  1908. presubmit_canned_checks.CheckChangeHasNoCrAndHasOnlyOneEol,
  1909. "Hey!\nHo!\n", "Hey!\nHo!\n\n",
  1910. presubmit.OutputApi.PresubmitPromptWarning)
  1911. self.ReadFileTest(
  1912. presubmit_canned_checks.CheckChangeHasNoCrAndHasOnlyOneEol,
  1913. "Hey!\nHo!\n", "Hey!\r\nHo!\r\n",
  1914. presubmit.OutputApi.PresubmitPromptWarning)
  1915. def testCheckChangeTodoHasOwner(self):
  1916. self.ContentTest(presubmit_canned_checks.CheckChangeTodoHasOwner,
  1917. "TODO: foo - bar", None, "TODO: bar", None,
  1918. presubmit.OutputApi.PresubmitPromptWarning)
  1919. self.ContentTest(presubmit_canned_checks.CheckChangeTodoHasOwner,
  1920. "TODO(foo): bar", None, "TODO: bar", None,
  1921. presubmit.OutputApi.PresubmitPromptWarning)
  1922. @mock.patch('git_cl.Changelist')
  1923. @mock.patch('auth.Authenticator')
  1924. def testCannedCheckChangedLUCIConfigsRoot(self, mockGetAuth, mockCl):
  1925. affected_file1 = mock.MagicMock(presubmit.GitAffectedFile)
  1926. affected_file1.LocalPath.return_value = 'foo.cfg'
  1927. affected_file2 = mock.MagicMock(presubmit.GitAffectedFile)
  1928. affected_file2.LocalPath.return_value = 'sub/bar.cfg'
  1929. mockGetAuth().get_id_token().token = 123
  1930. host = 'https://host.com'
  1931. branch = 'branch'
  1932. http_resp = b")]}'\n" + json.dumps({
  1933. 'configSets': [{
  1934. 'name': 'project/deadbeef',
  1935. 'url': '%s/+/%s' % (host, branch)
  1936. }]
  1937. }).encode("utf-8")
  1938. mockCl().GetRemoteBranch.return_value = ('remote', branch)
  1939. mockCl().GetRemoteUrl.return_value = host
  1940. change1 = presubmit.Change('foo', 'foo1', self.fake_root_dir, None, 0,
  1941. 0, None)
  1942. input_api = self.MockInputApi(change1, False)
  1943. input_api.urllib_request.urlopen().read.return_value = http_resp
  1944. affected_files = (affected_file1, affected_file2)
  1945. input_api.AffectedFiles = lambda **_: affected_files
  1946. proc = mock.Mock()
  1947. proc.communicate.return_value = ('This is STDOUT', 'This is STDERR')
  1948. proc.returncode = 0
  1949. subprocess.Popen.return_value = proc
  1950. input_api.CreateTemporaryFile.return_value = MockTemporaryFile(
  1951. 'tmp_file')
  1952. validation_result = {
  1953. 'result': {
  1954. 'validation': [{
  1955. 'messages': [{
  1956. 'path': 'foo.cfg',
  1957. 'severity': 'ERROR',
  1958. 'text': 'deadbeef',
  1959. }, {
  1960. 'path': 'sub/bar.cfg',
  1961. 'severity': 'WARNING',
  1962. 'text': 'cafecafe',
  1963. }]
  1964. }]
  1965. }
  1966. }
  1967. json.load.return_value = validation_result
  1968. results = presubmit_canned_checks.CheckChangedLUCIConfigs(
  1969. input_api, presubmit.OutputApi)
  1970. self.assertEqual(len(results), 2)
  1971. self.assertEqual(results[0].json_format()['message'],
  1972. "Config validation for file(foo.cfg): deadbeef")
  1973. self.assertEqual(results[1].json_format()['message'],
  1974. "Config validation for file(sub/bar.cfg): cafecafe")
  1975. subprocess.Popen.assert_called_once_with([
  1976. 'lucicfg' + ('.bat' if input_api.is_windows else ''), 'validate',
  1977. '.', '-config-set', 'project/deadbeef', '-log-level',
  1978. 'debug' if input_api.verbose else 'warning', '-json-output',
  1979. 'tmp_file'
  1980. ],
  1981. cwd=self.fake_root_dir,
  1982. stderr=subprocess.PIPE,
  1983. shell=input_api.is_windows)
  1984. @mock.patch('git_cl.Changelist')
  1985. @mock.patch('auth.Authenticator')
  1986. def testCannedCheckChangedLUCIConfigsNoFile(self, mockGetAuth, mockCl):
  1987. affected_file1 = mock.MagicMock(presubmit.GitAffectedFile)
  1988. affected_file1.LocalPath.return_value = 'foo.cfg'
  1989. affected_file2 = mock.MagicMock(presubmit.GitAffectedFile)
  1990. affected_file2.LocalPath.return_value = 'bar.cfg'
  1991. mockGetAuth().get_id_token().token = 123
  1992. host = 'https://host.com'
  1993. branch = 'branch'
  1994. http_resp = b")]}'\n" + json.dumps({
  1995. 'configSets': [{
  1996. 'name': 'project/deadbeef',
  1997. 'url': '%s/+/%s/generated' % (host, branch)
  1998. # no affected file in generated folder
  1999. }]
  2000. }).encode("utf-8")
  2001. mockCl().GetRemoteBranch.return_value = ('remote', branch)
  2002. mockCl().GetRemoteUrl.return_value = host
  2003. change1 = presubmit.Change('foo', 'foo1', self.fake_root_dir, None, 0,
  2004. 0, None)
  2005. input_api = self.MockInputApi(change1, False)
  2006. input_api.urllib_request.urlopen().read.return_value = http_resp
  2007. affected_files = (affected_file1, affected_file2)
  2008. input_api.AffectedFiles = lambda **_: affected_files
  2009. results = presubmit_canned_checks.CheckChangedLUCIConfigs(
  2010. input_api, presubmit.OutputApi)
  2011. self.assertEqual(len(results), 0)
  2012. @mock.patch('git_cl.Changelist')
  2013. @mock.patch('auth.Authenticator')
  2014. def testCannedCheckChangedLUCIConfigsNonRoot(self, mockGetAuth, mockCl):
  2015. affected_file1 = mock.MagicMock(presubmit.GitAffectedFile)
  2016. affected_file1.LocalPath.return_value = 'generated/foo.cfg'
  2017. affected_file2 = mock.MagicMock(presubmit.GitAffectedFile)
  2018. affected_file2.LocalPath.return_value = 'generated/bar.cfg'
  2019. mockGetAuth().get_access_token().token = 123
  2020. host = 'https://host.com'
  2021. branch = 'branch'
  2022. http_resp = b")]}'\n" + json.dumps({
  2023. 'configSets': [{
  2024. 'name': 'project/deadbeef',
  2025. 'url': '%s/+/%s/generated' % (host, branch)
  2026. }]
  2027. }).encode("utf-8")
  2028. mockCl().GetRemoteBranch.return_value = ('remote', branch)
  2029. mockCl().GetRemoteUrl.return_value = host
  2030. change1 = presubmit.Change('foo', 'foo1', self.fake_root_dir, None, 0,
  2031. 0, None)
  2032. input_api = self.MockInputApi(change1, False)
  2033. input_api.urllib_request.urlopen().read.return_value = http_resp
  2034. affected_files = (affected_file1, affected_file2)
  2035. input_api.AffectedFiles = lambda **_: affected_files
  2036. proc = mock.Mock()
  2037. proc.communicate.return_value = ('This is STDOUT', 'This is STDERR')
  2038. proc.returncode = 0
  2039. subprocess.Popen.return_value = proc
  2040. input_api.CreateTemporaryFile.return_value = MockTemporaryFile(
  2041. 'tmp_file')
  2042. validation_result = {
  2043. 'result': {
  2044. 'validation': [{
  2045. 'messages': [
  2046. {
  2047. 'path': 'bar.cfg',
  2048. 'severity': 'ERROR',
  2049. 'text': 'deadbeef',
  2050. },
  2051. {
  2052. 'path': 'sub/baz.cfg', # not an affected file
  2053. 'severity': 'ERROR',
  2054. 'text': 'cafecafe',
  2055. }
  2056. ]
  2057. }]
  2058. }
  2059. }
  2060. json.load.return_value = validation_result
  2061. results = presubmit_canned_checks.CheckChangedLUCIConfigs(
  2062. input_api, presubmit.OutputApi)
  2063. self.assertEqual(len(results), 2)
  2064. self.assertEqual(results[0].json_format()['message'],
  2065. "Config validation for file(bar.cfg): deadbeef")
  2066. self.assertEqual(
  2067. results[1].json_format()['message'],
  2068. "Found 1 additional errors/warnings in files that are not modified,"
  2069. " run `lucicfg validate %s%sgenerated -config-set "
  2070. "project/deadbeef` to reveal them" %
  2071. (self.fake_root_dir, self._OS_SEP))
  2072. subprocess.Popen.assert_called_once_with([
  2073. 'lucicfg' + ('.bat' if input_api.is_windows else ''),
  2074. 'validate',
  2075. 'generated',
  2076. '-config-set',
  2077. 'project/deadbeef',
  2078. '-log-level',
  2079. 'debug' if input_api.verbose else 'warning',
  2080. '-json-output',
  2081. 'tmp_file',
  2082. ],
  2083. cwd=self.fake_root_dir,
  2084. stderr=subprocess.PIPE,
  2085. shell=input_api.is_windows)
  2086. @mock.patch('git_cl.Changelist')
  2087. @mock.patch('auth.Authenticator')
  2088. def testCannedCheckChangedLUCIConfigsGerritInfo(self, mockGetAuth, mockCl):
  2089. affected_file = mock.MagicMock(presubmit.ProvidedDiffAffectedFile)
  2090. affected_file.LocalPath.return_value = 'foo.cfg'
  2091. mockGetAuth().get_id_token().token = 123
  2092. host = 'host.googlesource.com'
  2093. project = 'project/deadbeef'
  2094. branch = 'branch'
  2095. http_resp = b")]}'\n" + json.dumps({
  2096. 'configSets':
  2097. [{
  2098. 'name': 'project/deadbeef',
  2099. 'url': f'https://{host}/{project}/+/{branch}/generated'
  2100. # no affected file in generated folder
  2101. }]
  2102. }).encode("utf-8")
  2103. gerrit_mock = mock.MagicMock(presubmit.GerritAccessor)
  2104. gerrit_mock.host = host
  2105. gerrit_mock.project = project
  2106. gerrit_mock.branch = branch
  2107. change1 = presubmit.Change('foo', 'foo1', self.fake_root_dir, None, 0,
  2108. 0, None)
  2109. input_api = self.MockInputApi(change1, False, gerrit_mock)
  2110. input_api.urllib_request.urlopen().read.return_value = http_resp
  2111. input_api.AffectedFiles = lambda **_: (affected_file, )
  2112. results = presubmit_canned_checks.CheckChangedLUCIConfigs(
  2113. input_api, presubmit.OutputApi)
  2114. self.assertEqual(len(results), 0)
  2115. def testCannedCheckChangeHasNoTabs(self):
  2116. self.ContentTest(presubmit_canned_checks.CheckChangeHasNoTabs,
  2117. 'blah blah', None, 'blah\tblah', None,
  2118. presubmit.OutputApi.PresubmitPromptWarning)
  2119. # Make sure makefiles are ignored.
  2120. change1 = presubmit.Change('foo1', 'foo1\n', self.fake_root_dir, None,
  2121. 0, 0, None)
  2122. input_api1 = self.MockInputApi(change1, False)
  2123. affected_file1 = mock.MagicMock(presubmit.GitAffectedFile)
  2124. affected_file1.LocalPath.return_value = 'foo.cc'
  2125. affected_file2 = mock.MagicMock(presubmit.GitAffectedFile)
  2126. affected_file2.LocalPath.return_value = 'foo/Makefile'
  2127. affected_file3 = mock.MagicMock(presubmit.GitAffectedFile)
  2128. affected_file3.LocalPath.return_value = 'makefile'
  2129. # Only this one will trigger.
  2130. affected_file4 = mock.MagicMock(presubmit.GitAffectedFile)
  2131. affected_file1.LocalPath.return_value = 'foo.cc'
  2132. affected_file1.NewContents.return_value = ['yo, ']
  2133. affected_file4.LocalPath.return_value = 'makefile.foo'
  2134. affected_file4.LocalPath.return_value = 'makefile.foo'
  2135. affected_file4.NewContents.return_value = ['ye\t']
  2136. affected_file4.ChangedContents.return_value = [(46, 'ye\t')]
  2137. affected_file4.LocalPath.return_value = 'makefile.foo'
  2138. affected_files = (affected_file1, affected_file2, affected_file3,
  2139. affected_file4)
  2140. def test(include_deletes=True, file_filter=None):
  2141. self.assertFalse(include_deletes)
  2142. for x in affected_files:
  2143. if file_filter(x):
  2144. yield x
  2145. # Override the mock of these functions.
  2146. input_api1.FilterSourceFile = lambda x: x
  2147. input_api1.AffectedFiles = test
  2148. results1 = presubmit_canned_checks.CheckChangeHasNoTabs(
  2149. input_api1, presubmit.OutputApi, None)
  2150. self.assertEqual(len(results1), 1)
  2151. self.assertEqual(results1[0].__class__,
  2152. presubmit.OutputApi.PresubmitPromptWarning)
  2153. self.assertEqual(results1[0]._long_text, 'makefile.foo:46')
  2154. def testCannedCheckLongLines(self):
  2155. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2156. x, y, 10, z)
  2157. self.ContentTest(check, '0123456789', None, '01234567890', None,
  2158. presubmit.OutputApi.PresubmitPromptWarning)
  2159. def testCannedCheckJavaLongLines(self):
  2160. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 80)
  2161. self.ContentTest(check, 'A ' * 50, 'foo.java', 'A ' * 50 + 'B',
  2162. 'foo.java', presubmit.OutputApi.PresubmitPromptWarning)
  2163. def testCannedCheckSpecialJavaLongLines(self):
  2164. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 80)
  2165. self.ContentTest(check, 'import ' + 'A ' * 150, 'foo.java',
  2166. 'importSomething ' + 'A ' * 50, 'foo.java',
  2167. presubmit.OutputApi.PresubmitPromptWarning)
  2168. def testCannedCheckPythonLongLines(self):
  2169. # NOTE: Cannot use ContentTest() here because of the different code path
  2170. # used for Python checks in CheckLongLines().
  2171. passing_cases = [
  2172. r"""
  2173. 01234568901234589012345689012345689
  2174. A short line
  2175. """,
  2176. r"""
  2177. 01234568901234589012345689012345689
  2178. This line is too long but should pass # pylint: disable=line-too-long
  2179. """,
  2180. r"""
  2181. 01234568901234589012345689012345689
  2182. # pylint: disable=line-too-long
  2183. This line is too long but should pass due to global disable
  2184. """,
  2185. r"""
  2186. 01234568901234589012345689012345689
  2187. #pylint: disable=line-too-long
  2188. This line is too long but should pass due to global disable.
  2189. """,
  2190. r"""
  2191. 01234568901234589012345689012345689
  2192. # pylint: disable=line-too-long
  2193. This line is too long but should pass due to global disable.
  2194. """,
  2195. r"""
  2196. 01234568901234589012345689012345689
  2197. # import is a valid exception
  2198. import some.really.long.package.name.that.should.pass
  2199. """,
  2200. r"""
  2201. 01234568901234589012345689012345689
  2202. # from is a valid exception
  2203. from some.really.long.package.name import passing.line
  2204. """,
  2205. r"""
  2206. 01234568901234589012345689012345689
  2207. import some.package
  2208. """,
  2209. r"""
  2210. 01234568901234589012345689012345689
  2211. from some.package import stuff
  2212. """,
  2213. ]
  2214. for content in passing_cases:
  2215. self.PythonLongLineTest(40, content, should_pass=True)
  2216. failing_cases = [
  2217. r"""
  2218. 01234568901234589012345689012345689
  2219. This line is definitely too long and should fail.
  2220. """,
  2221. r"""
  2222. 01234568901234589012345689012345689
  2223. # pylint: disable=line-too-long
  2224. This line is too long and should pass due to global disable
  2225. # pylint: enable=line-too-long
  2226. But this line is too long and should still fail now
  2227. """,
  2228. r"""
  2229. 01234568901234589012345689012345689
  2230. # pylint: disable=line-too-long
  2231. This line is too long and should pass due to global disable
  2232. But this line is too long # pylint: enable=line-too-long
  2233. """,
  2234. r"""
  2235. 01234568901234589012345689012345689
  2236. This should fail because the global
  2237. check is enabled on the next line.
  2238. # pylint: enable=line-too-long
  2239. """,
  2240. r"""
  2241. 01234568901234589012345689012345689
  2242. # pylint: disable=line-too-long
  2243. # pylint: enable-foo-bar should pass
  2244. The following line should fail
  2245. since global directives apply to
  2246. the current line as well!
  2247. # pylint: enable-line-too-long should fail
  2248. """,
  2249. ]
  2250. for content in failing_cases[0:0]:
  2251. self.PythonLongLineTest(40, content, should_pass=False)
  2252. def testCannedCheckJSLongLines(self):
  2253. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 10)
  2254. self.ContentTest(check, 'GEN(\'#include "c/b/ui/webui/fixture.h"\');',
  2255. 'foo.js', "// GEN('something');", 'foo.js',
  2256. presubmit.OutputApi.PresubmitPromptWarning)
  2257. def testCannedCheckJSLongImports(self):
  2258. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 10)
  2259. self.ContentTest(check,
  2260. "import {Name, otherName} from './dir/file.js';",
  2261. 'foo.js', "// We should import something long, eh?",
  2262. 'foo.js', presubmit.OutputApi.PresubmitPromptWarning)
  2263. def testCannedCheckTSLongImports(self):
  2264. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 10)
  2265. self.ContentTest(check, "import {Name, otherName} from './dir/file';",
  2266. 'foo.ts', "// We should import something long, eh?",
  2267. 'foo.ts', presubmit.OutputApi.PresubmitPromptWarning)
  2268. def testCannedCheckObjCExceptionLongLines(self):
  2269. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 80)
  2270. self.ContentTest(check, '#import ' + 'A ' * 150, 'foo.mm',
  2271. 'import' + 'A ' * 150, 'foo.mm',
  2272. presubmit.OutputApi.PresubmitPromptWarning)
  2273. def testCannedCheckMakefileLongLines(self):
  2274. check = lambda x, y, _: presubmit_canned_checks.CheckLongLines(x, y, 80)
  2275. self.ContentTest(check, 'A ' * 100, 'foo.mk', 'A ' * 100 + 'B',
  2276. 'foo.mk', presubmit.OutputApi.PresubmitPromptWarning)
  2277. def testCannedCheckLongLinesLF(self):
  2278. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2279. x, y, 10, z)
  2280. self.ContentTest(check, '012345678\n', None, '0123456789\n', None,
  2281. presubmit.OutputApi.PresubmitPromptWarning)
  2282. def testCannedCheckCppExceptionLongLines(self):
  2283. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2284. x, y, 10, z)
  2285. self.ContentTest(check, '#if 56 89 12 45 9191919191919', 'foo.cc',
  2286. '#nif 56 89 12 45 9191919191919', 'foo.cc',
  2287. presubmit.OutputApi.PresubmitPromptWarning)
  2288. def testCannedCheckLongLinesHttp(self):
  2289. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2290. x, y, 10, z)
  2291. self.ContentTest(check, ' http:// 0 23 56', None, ' foob:// 0 23 56',
  2292. None, presubmit.OutputApi.PresubmitPromptWarning)
  2293. def testCannedCheckLongLinesFile(self):
  2294. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2295. x, y, 10, z)
  2296. self.ContentTest(check, ' file:// 0 23 56', None, ' foob:// 0 23 56',
  2297. None, presubmit.OutputApi.PresubmitPromptWarning)
  2298. def testCannedCheckLongLinesCssUrl(self):
  2299. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2300. x, y, 10, z)
  2301. self.ContentTest(check, ' url(some.png)', 'foo.css', ' url(some.png)',
  2302. 'foo.cc', presubmit.OutputApi.PresubmitPromptWarning)
  2303. def testCannedCheckLongLinesLongSymbol(self):
  2304. check = lambda x, y, z: presubmit_canned_checks.CheckLongLines(
  2305. x, y, 10, z)
  2306. self.ContentTest(check, ' TUP5D_LoNG_SY ', None, ' TUP5D_LoNG_SY5 ',
  2307. None, presubmit.OutputApi.PresubmitPromptWarning)
  2308. def _LicenseCheck(self,
  2309. text,
  2310. license_text,
  2311. committing,
  2312. expected_result,
  2313. new_file=False,
  2314. **kwargs):
  2315. change = mock.MagicMock(presubmit.GitChange)
  2316. change.scm = 'svn'
  2317. input_api = self.MockInputApi(change, committing)
  2318. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  2319. if new_file:
  2320. affected_file.Action.return_value = 'A'
  2321. input_api.AffectedSourceFiles.return_value = [affected_file]
  2322. input_api.ReadFile.return_value = text
  2323. if expected_result:
  2324. affected_file.LocalPath.return_value = 'bleh'
  2325. result = presubmit_canned_checks.CheckLicense(input_api,
  2326. presubmit.OutputApi,
  2327. license_text,
  2328. source_file_filter=42,
  2329. **kwargs)
  2330. if expected_result:
  2331. self.assertEqual(len(result), 1)
  2332. self.assertEqual(result[0].__class__, expected_result)
  2333. else:
  2334. self.assertEqual(result, [])
  2335. def testCheckLicenseSuccess(self):
  2336. text = ("#!/bin/python\n"
  2337. "# Copyright (c) 2037 Nobody.\n"
  2338. "# All Rights Reserved.\n"
  2339. "print('foo')\n")
  2340. license_text = (r".*? Copyright \(c\) 2037 Nobody.\n"
  2341. r".*? All Rights Reserved\.\n")
  2342. self._LicenseCheck(text, license_text, True, None)
  2343. def testCheckLicenseSuccessNew(self):
  2344. # Make sure the license check works on new files with custom licenses.
  2345. text = ("#!/bin/python\n"
  2346. "# Copyright (c) 2037 Nobody.\n"
  2347. "# All Rights Reserved.\n"
  2348. "print('foo')\n")
  2349. license_text = (r".*? Copyright \(c\) 2037 Nobody.\n"
  2350. r".*? All Rights Reserved\.\n")
  2351. self._LicenseCheck(text, license_text, True, None, new_file=True)
  2352. def testCheckLicenseFailCommit(self):
  2353. text = ("#!/bin/python\n"
  2354. "# Copyright (c) 2037 Nobody.\n"
  2355. "# All Rights Reserved.\n"
  2356. "print('foo')\n")
  2357. license_text = (r".*? Copyright \(c\) 0007 Nobody.\n"
  2358. r".*? All Rights Reserved\.\n")
  2359. self._LicenseCheck(text, license_text, True,
  2360. presubmit.OutputApi.PresubmitPromptWarning)
  2361. def testCheckLicenseFailUpload(self):
  2362. text = ("#!/bin/python\n"
  2363. "# Copyright (c) 2037 Nobody.\n"
  2364. "# All Rights Reserved.\n"
  2365. "print('foo')\n")
  2366. license_text = (r".*? Copyright \(c\) 0007 Nobody.\n"
  2367. r".*? All Rights Reserved\.\n")
  2368. self._LicenseCheck(text, license_text, False,
  2369. presubmit.OutputApi.PresubmitPromptWarning)
  2370. def testCheckLicenseEmptySuccess(self):
  2371. text = ''
  2372. license_text = (r".*? Copyright \(c\) 2037 Nobody.\n"
  2373. r".*? All Rights Reserved\.\n")
  2374. self._LicenseCheck(text,
  2375. license_text,
  2376. True,
  2377. None,
  2378. accept_empty_files=True)
  2379. def testCheckLicenseNewFilePass(self):
  2380. text = self._GetLicenseText(int(time.strftime('%Y')))
  2381. license_text = None
  2382. self._LicenseCheck(text, license_text, False, None, new_file=True)
  2383. def testCheckLicenseNewFileFail(self):
  2384. # Check that we fail on new files with the (c) symbol.
  2385. current_year = int(time.strftime('%Y'))
  2386. text = (
  2387. "#!/bin/python\n"
  2388. "# Copyright (c) %d The Chromium Authors\n"
  2389. "# Use of this source code is governed by a BSD-style license that can "
  2390. "be\n"
  2391. "# found in the LICENSE file.\n"
  2392. "print('foo')\n" % current_year)
  2393. license_text = None
  2394. self._LicenseCheck(text,
  2395. license_text,
  2396. False,
  2397. presubmit.OutputApi.PresubmitPromptWarning,
  2398. new_file=True)
  2399. def _GetLicenseText(self, current_year):
  2400. return (
  2401. "#!/bin/python\n"
  2402. "# Copyright %d The Chromium Authors\n"
  2403. "# Use of this source code is governed by a BSD-style license that can "
  2404. "be\n"
  2405. "# found in the LICENSE file.\n"
  2406. "print('foo')\n" % current_year)
  2407. def testCheckLicenseNewFileWarn(self):
  2408. # Check that we warn on new files with wrong year. Test with first
  2409. # allowed year.
  2410. text = self._GetLicenseText(2006)
  2411. license_text = None
  2412. self._LicenseCheck(text,
  2413. license_text,
  2414. False,
  2415. presubmit.OutputApi.PresubmitPromptWarning,
  2416. new_file=True)
  2417. def testCheckLicenseNewCSSFilePass(self):
  2418. # Check that CSS-style comments in license text are supported.
  2419. current_year = int(time.strftime('%Y'))
  2420. text = (
  2421. "/* Copyright %d The Chromium Authors\n"
  2422. " * Use of this source code is governed by a BSD-style license that "
  2423. "can be\n"
  2424. "* found in the LICENSE file. */\n"
  2425. "\n"
  2426. "h1 {}\n" % current_year)
  2427. license_text = None
  2428. self._LicenseCheck(text, license_text, False, None, new_file=True)
  2429. def testCannedCheckTreeIsOpenOpen(self):
  2430. input_api = self.MockInputApi(None, True)
  2431. input_api.urllib_request.urlopen(
  2432. ).read.return_value = 'The tree is open'
  2433. results = presubmit_canned_checks.CheckTreeIsOpen(input_api,
  2434. presubmit.OutputApi,
  2435. url='url_to_open',
  2436. closed='.*closed.*')
  2437. self.assertEqual(results, [])
  2438. def testCannedCheckTreeIsOpenClosed(self):
  2439. input_api = self.MockInputApi(None, True)
  2440. input_api.urllib_request.urlopen().read.return_value = (
  2441. 'Tree is closed for maintenance')
  2442. results = presubmit_canned_checks.CheckTreeIsOpen(input_api,
  2443. presubmit.OutputApi,
  2444. url='url_to_closed',
  2445. closed='.*closed.*')
  2446. self.assertEqual(len(results), 1)
  2447. self.assertEqual(results[0].__class__,
  2448. presubmit.OutputApi.PresubmitError)
  2449. def testCannedCheckJsonTreeIsOpenOpen(self):
  2450. input_api = self.MockInputApi(None, True)
  2451. status = {
  2452. 'can_commit_freely': True,
  2453. 'general_state': 'open',
  2454. 'message': 'The tree is open'
  2455. }
  2456. input_api.urllib_request.urlopen().read.return_value = json.dumps(
  2457. status)
  2458. results = presubmit_canned_checks.CheckTreeIsOpen(
  2459. input_api, presubmit.OutputApi, json_url='url_to_open')
  2460. self.assertEqual(results, [])
  2461. def testCannedCheckJsonTreeIsOpenClosed(self):
  2462. input_api = self.MockInputApi(None, True)
  2463. status = {
  2464. 'can_commit_freely': False,
  2465. 'general_state': 'closed',
  2466. 'message': 'The tree is close',
  2467. }
  2468. input_api.urllib_request.urlopen().read.return_value = json.dumps(
  2469. status)
  2470. results = presubmit_canned_checks.CheckTreeIsOpen(
  2471. input_api, presubmit.OutputApi, json_url='url_to_closed')
  2472. self.assertEqual(len(results), 1)
  2473. self.assertEqual(results[0].__class__,
  2474. presubmit.OutputApi.PresubmitError)
  2475. def testRunPythonUnitTestsNoTest(self):
  2476. input_api = self.MockInputApi(None, False)
  2477. presubmit_canned_checks.RunPythonUnitTests(input_api,
  2478. presubmit.OutputApi, [])
  2479. results = input_api.thread_pool.RunAsync()
  2480. self.assertEqual(results, [])
  2481. def testRunPythonUnitTestsNonExistentUpload(self):
  2482. input_api = self.MockInputApi(None, False)
  2483. subprocess.Popen().returncode = 1 # pylint: disable=no-value-for-parameter
  2484. presubmit.sigint_handler.wait.return_value = (b'foo', None)
  2485. results = presubmit_canned_checks.RunPythonUnitTests(
  2486. input_api, presubmit.OutputApi, ['_non_existent_module'])
  2487. self.assertEqual(len(results), 1)
  2488. self.assertEqual(results[0].__class__,
  2489. presubmit.OutputApi.PresubmitNotifyResult)
  2490. def testRunPythonUnitTestsNonExistentCommitting(self):
  2491. input_api = self.MockInputApi(None, True)
  2492. subprocess.Popen().returncode = 1 # pylint: disable=no-value-for-parameter
  2493. presubmit.sigint_handler.wait.return_value = (b'foo', None)
  2494. results = presubmit_canned_checks.RunPythonUnitTests(
  2495. input_api, presubmit.OutputApi, ['_non_existent_module'])
  2496. self.assertEqual(len(results), 1)
  2497. self.assertEqual(results[0].__class__,
  2498. presubmit.OutputApi.PresubmitError)
  2499. def testRunPythonUnitTestsFailureUpload(self):
  2500. input_api = self.MockInputApi(None, False)
  2501. input_api.unittest = mock.MagicMock(unittest)
  2502. subprocess.Popen().returncode = 1 # pylint: disable=no-value-for-parameter
  2503. presubmit.sigint_handler.wait.return_value = (b'foo', None)
  2504. results = presubmit_canned_checks.RunPythonUnitTests(
  2505. input_api, presubmit.OutputApi, ['test_module'])
  2506. self.assertEqual(len(results), 1)
  2507. self.assertEqual(results[0].__class__,
  2508. presubmit.OutputApi.PresubmitNotifyResult)
  2509. self.assertEqual(
  2510. 'test_module\npyyyyython3 -m test_module (0.00s) failed\nfoo',
  2511. results[0]._message)
  2512. def testRunPythonUnitTestsFailureCommitting(self):
  2513. input_api = self.MockInputApi(None, True)
  2514. subprocess.Popen().returncode = 1 # pylint: disable=no-value-for-parameter
  2515. presubmit.sigint_handler.wait.return_value = (b'foo', None)
  2516. results = presubmit_canned_checks.RunPythonUnitTests(
  2517. input_api, presubmit.OutputApi, ['test_module'])
  2518. self.assertEqual(len(results), 1)
  2519. self.assertEqual(results[0].__class__,
  2520. presubmit.OutputApi.PresubmitError)
  2521. self.assertEqual(
  2522. 'test_module\npyyyyython3 -m test_module (0.00s) failed\nfoo',
  2523. results[0]._message)
  2524. def testRunPythonUnitTestsSuccess(self):
  2525. input_api = self.MockInputApi(None, False)
  2526. input_api.unittest = mock.MagicMock(unittest)
  2527. subprocess.Popen().returncode = 0 # pylint: disable=no-value-for-parameter
  2528. presubmit.sigint_handler.wait.return_value = (b'', None)
  2529. presubmit_canned_checks.RunPythonUnitTests(input_api,
  2530. presubmit.OutputApi,
  2531. ['test_module'])
  2532. results = input_api.thread_pool.RunAsync()
  2533. self.assertEqual(results, [])
  2534. def testCannedRunPylint(self):
  2535. change = mock.Mock()
  2536. change.RepositoryRoot.return_value = 'CWD'
  2537. input_api = self.MockInputApi(change, True)
  2538. input_api.environ = mock.MagicMock(os.environ)
  2539. input_api.environ.copy.return_value = {}
  2540. input_api.AffectedSourceFiles.return_value = True
  2541. input_api.PresubmitLocalPath.return_value = 'CWD'
  2542. input_api.os_walk.return_value = [('CWD', [], ['file1.py'])]
  2543. process = mock.Mock()
  2544. process.returncode = 0
  2545. subprocess.Popen.return_value = process
  2546. presubmit.sigint_handler.wait.return_value = (b'', None)
  2547. pylint = os.path.join(_ROOT, 'pylint-2.7')
  2548. pylintrc = os.path.join(_ROOT, 'pylintrc-2.7')
  2549. env = {str('PYTHONPATH'): str('')}
  2550. if sys.platform == 'win32':
  2551. pylint += '.bat'
  2552. results = presubmit_canned_checks.RunPylint(input_api,
  2553. presubmit.OutputApi,
  2554. version='2.7')
  2555. self.assertEqual([], results)
  2556. self.assertEqual(subprocess.Popen.mock_calls, [
  2557. mock.call([pylint, '--args-on-stdin'],
  2558. env=env,
  2559. cwd='CWD',
  2560. stderr=subprocess.STDOUT,
  2561. stdout=subprocess.PIPE,
  2562. stdin=subprocess.PIPE),
  2563. ])
  2564. self.assertEqual(presubmit.sigint_handler.wait.mock_calls, [
  2565. mock.call(process,
  2566. ('--rcfile=%s\nfile1.py' % pylintrc).encode('utf-8')),
  2567. ])
  2568. self.checkstdout('')
  2569. def GetInputApiWithFiles(self, files):
  2570. change = mock.MagicMock(presubmit.Change)
  2571. change.AffectedFiles = lambda *a, **kw: (presubmit.Change.AffectedFiles(
  2572. change, *a, **kw))
  2573. change._affected_files = []
  2574. for path, (action, contents) in files.items():
  2575. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  2576. affected_file.AbsoluteLocalPath.return_value = path
  2577. affected_file.LocalPath.return_value = path
  2578. affected_file.Action.return_value = action
  2579. affected_file.ChangedContents.return_value = [
  2580. (1, contents or ''),
  2581. ]
  2582. change._affected_files.append(affected_file)
  2583. input_api = self.MockInputApi(None, False)
  2584. input_api.change = change
  2585. input_api.ReadFile = lambda path: files[path][1]
  2586. input_api.basename = os.path.basename
  2587. input_api.is_windows = sys.platform.startswith('win')
  2588. os.path.exists = lambda path: path in files and files[path][0] != 'D'
  2589. os.path.isfile = os.path.exists
  2590. return input_api
  2591. def testCheckDirMetadataFormat(self):
  2592. input_api = self.GetInputApiWithFiles({
  2593. 'DIR_METADATA': ('M', ''),
  2594. 'a/DIR_METADATA': ('M', ''),
  2595. 'a/b/OWNERS': ('M', ''),
  2596. 'c/DIR_METADATA': ('D', ''),
  2597. 'd/unrelated': ('M', ''),
  2598. })
  2599. dirmd_bin = 'dirmd.bat' if input_api.is_windows else 'dirmd'
  2600. expected_cmd = [
  2601. dirmd_bin, 'validate', 'DIR_METADATA', 'a/DIR_METADATA',
  2602. 'a/b/OWNERS'
  2603. ]
  2604. commands = presubmit_canned_checks.CheckDirMetadataFormat(
  2605. input_api, presubmit.OutputApi)
  2606. self.assertEqual(1, len(commands))
  2607. self.assertEqual(expected_cmd, commands[0].cmd)
  2608. def testCheckNoNewMetadataInOwners(self):
  2609. input_api = self.GetInputApiWithFiles({
  2610. 'no-new-metadata/OWNERS': ('M', '# WARNING: Blah'),
  2611. 'added-no-new-metadata/OWNERS': ('A', '# WARNING: Bleh'),
  2612. 'deleted/OWNERS': ('D', None),
  2613. })
  2614. self.assertEqual([],
  2615. presubmit_canned_checks.CheckNoNewMetadataInOwners(
  2616. input_api, presubmit.OutputApi))
  2617. def testCheckNoNewMetadataInOwnersFails(self):
  2618. input_api = self.GetInputApiWithFiles({
  2619. 'new-metadata/OWNERS': ('M', '# CoMpOnEnT: Monorail>Component'),
  2620. })
  2621. results = presubmit_canned_checks.CheckNoNewMetadataInOwners(
  2622. input_api, presubmit.OutputApi)
  2623. self.assertEqual(1, len(results))
  2624. self.assertIsInstance(results[0], presubmit.OutputApi.PresubmitError)
  2625. def testCheckOwnersDirMetadataExclusiveWorks(self):
  2626. input_api = self.GetInputApiWithFiles({
  2627. 'only-owners/OWNERS': ('M', '# COMPONENT: Monorail>Component'),
  2628. 'only-dir-metadata/DIR_METADATA': ('M', ''),
  2629. 'owners-has-no-metadata/DIR_METADATA': ('M', ''),
  2630. 'owners-has-no-metadata/OWNERS': ('M', 'no-metadata'),
  2631. 'deleted-owners/OWNERS': ('D', None),
  2632. 'deleted-owners/DIR_METADATA': ('M', ''),
  2633. 'deleted-dir-metadata/OWNERS':
  2634. ('M', '# COMPONENT: Monorail>Component'),
  2635. 'deleted-dir-metadata/DIR_METADATA': ('D', None),
  2636. 'non-metadata-comment/OWNERS': ('M', '# WARNING: something.'),
  2637. 'non-metadata-comment/DIR_METADATA': ('M', ''),
  2638. })
  2639. self.assertEqual(
  2640. [],
  2641. presubmit_canned_checks.CheckOwnersDirMetadataExclusive(
  2642. input_api, presubmit.OutputApi))
  2643. def testCheckOwnersDirMetadataExclusiveFails(self):
  2644. input_api = self.GetInputApiWithFiles({
  2645. 'DIR_METADATA': ('M', ''),
  2646. 'OWNERS': ('M', '# COMPONENT: Monorail>Component'),
  2647. })
  2648. results = presubmit_canned_checks.CheckOwnersDirMetadataExclusive(
  2649. input_api, presubmit.OutputApi)
  2650. self.assertEqual(1, len(results))
  2651. self.assertIsInstance(results[0], presubmit.OutputApi.PresubmitError)
  2652. def GetInputApiWithOWNERS(self, owners_content):
  2653. input_api = self.GetInputApiWithFiles({'OWNERS': ('M', owners_content)})
  2654. gerrit_mock = mock.MagicMock(presubmit.GerritAccessor)
  2655. gerrit_mock.IsCodeOwnersEnabledOnRepo = lambda: True
  2656. input_api.gerrit = gerrit_mock
  2657. return input_api
  2658. def testCheckOwnersFormatWorks_CodeOwners(self):
  2659. # If code owners is enabled, we rely on it to check owners format
  2660. # instead of depot tools.
  2661. input_api = self.GetInputApiWithOWNERS('any content')
  2662. self.assertEqual([],
  2663. presubmit_canned_checks.CheckOwnersFormat(
  2664. input_api, presubmit.OutputApi))
  2665. def AssertOwnersWorks(self,
  2666. tbr=False,
  2667. issue='1',
  2668. approvers=None,
  2669. modified_files=None,
  2670. owners_by_path=None,
  2671. is_committing=True,
  2672. response=None,
  2673. expected_output='',
  2674. manually_specified_reviewers=None,
  2675. dry_run=None):
  2676. # The set of people who lgtm'ed a change.
  2677. approvers = approvers or set()
  2678. manually_specified_reviewers = manually_specified_reviewers or []
  2679. modified_files = modified_files or ['foo/xyz.cc']
  2680. owners_by_path = owners_by_path or {'foo/xyz.cc': ['john@example.com']}
  2681. response = response or {
  2682. "owner": {
  2683. "email": 'john@example.com'
  2684. },
  2685. "labels": {
  2686. "Code-Review": {
  2687. u'all': [{
  2688. u'email': a,
  2689. u'value': +1
  2690. } for a in approvers],
  2691. u'default_value': 0,
  2692. u'values': {
  2693. u' 0': u'No score',
  2694. u'+1': u'Looks good to me',
  2695. u'-1': u"I would prefer that you didn't submit this"
  2696. }
  2697. }
  2698. },
  2699. "reviewers": {"REVIEWER": [{
  2700. u'email': a
  2701. }]
  2702. for a in approvers},
  2703. }
  2704. change = mock.MagicMock(presubmit.Change)
  2705. change.OriginalOwnersFiles.return_value = {}
  2706. change.RepositoryRoot.return_value = None
  2707. change.ReviewersFromDescription.return_value = manually_specified_reviewers
  2708. change.TBRsFromDescription.return_value = []
  2709. change.author_email = 'john@example.com'
  2710. change.issue = issue
  2711. affected_files = []
  2712. for f in modified_files:
  2713. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  2714. affected_file.LocalPath.return_value = f
  2715. affected_files.append(affected_file)
  2716. change.AffectedFiles.return_value = affected_files
  2717. input_api = self.MockInputApi(change, False)
  2718. input_api.gerrit = presubmit.GerritAccessor('host')
  2719. input_api.is_committing = is_committing
  2720. input_api.tbr = tbr
  2721. input_api.dry_run = dry_run
  2722. input_api.gerrit._FetchChangeDetail = lambda _: response
  2723. input_api.gerrit.IsCodeOwnersEnabledOnRepo = lambda: True
  2724. input_api.owners_client = owners_client.OwnersClient()
  2725. with mock.patch('owners_client.OwnersClient.ListOwners',
  2726. side_effect=lambda f: owners_by_path.get(f, [])):
  2727. results = presubmit_canned_checks.CheckOwners(
  2728. input_api, presubmit.OutputApi)
  2729. for result in results:
  2730. result.handle()
  2731. if expected_output:
  2732. self.assertRegexpMatches(sys.stdout.getvalue(), expected_output)
  2733. else:
  2734. self.assertEqual(sys.stdout.getvalue(), expected_output)
  2735. sys.stdout.truncate(0)
  2736. def testCannedCheckOwners_TBRIgnored(self):
  2737. self.AssertOwnersWorks(tbr=True, expected_output='')
  2738. self.AssertOwnersWorks(tbr=True,
  2739. is_committing=False,
  2740. expected_output='')
  2741. @mock.patch('io.open', mock.mock_open())
  2742. def testCannedRunUnitTests(self):
  2743. io.open().readline.return_value = ''
  2744. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2745. None, 0, 0, None)
  2746. input_api = self.MockInputApi(change, False)
  2747. input_api.verbose = True
  2748. input_api.PresubmitLocalPath.return_value = self.fake_root_dir
  2749. presubmit.sigint_handler.wait.return_value = (b'', None)
  2750. process1 = mock.Mock()
  2751. process1.returncode = 1
  2752. process2 = mock.Mock()
  2753. process2.returncode = 0
  2754. subprocess.Popen.side_effect = [process1, process2]
  2755. unit_tests = ['allo', 'bar.py']
  2756. results = presubmit_canned_checks.RunUnitTests(input_api,
  2757. presubmit.OutputApi,
  2758. unit_tests)
  2759. self.assertEqual(2, len(results))
  2760. self.assertEqual(presubmit.OutputApi.PresubmitNotifyResult,
  2761. results[1].__class__)
  2762. self.assertEqual(presubmit.OutputApi.PresubmitPromptWarning,
  2763. results[0].__class__)
  2764. cmd = ['bar.py', '--verbose']
  2765. if input_api.platform == 'win32':
  2766. cmd.insert(0, 'vpython3.bat')
  2767. else:
  2768. cmd.insert(0, 'vpython3')
  2769. self.assertEqual(subprocess.Popen.mock_calls, [
  2770. mock.call(cmd,
  2771. cwd=self.fake_root_dir,
  2772. stdout=subprocess.PIPE,
  2773. stderr=subprocess.STDOUT,
  2774. stdin=subprocess.PIPE),
  2775. mock.call(['allo', '--verbose'],
  2776. cwd=self.fake_root_dir,
  2777. stdout=subprocess.PIPE,
  2778. stderr=subprocess.STDOUT,
  2779. stdin=subprocess.PIPE),
  2780. ])
  2781. threading.Timer.assert_not_called()
  2782. self.checkstdout('')
  2783. @mock.patch('io.open', mock.mock_open())
  2784. def testCannedRunUnitTestsWithTimer(self):
  2785. io.open().readline.return_value = ''
  2786. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2787. None, 0, 0, None)
  2788. input_api = self.MockInputApi(change, False)
  2789. input_api.verbose = True
  2790. input_api.thread_pool.timeout = 100
  2791. input_api.PresubmitLocalPath.return_value = self.fake_root_dir
  2792. presubmit.sigint_handler.wait.return_value = (b'', None)
  2793. subprocess.Popen.return_value = mock.Mock(returncode=0)
  2794. results = presubmit_canned_checks.RunUnitTests(input_api,
  2795. presubmit.OutputApi,
  2796. ['bar.py'])
  2797. self.assertEqual(presubmit.OutputApi.PresubmitNotifyResult,
  2798. results[0].__class__)
  2799. threading.Timer.assert_called_once_with(input_api.thread_pool.timeout,
  2800. mock.ANY)
  2801. threading.Timer().start.assert_called_once_with()
  2802. threading.Timer().cancel.assert_called_once_with()
  2803. self.checkstdout('')
  2804. @mock.patch('io.open', mock.mock_open())
  2805. def testCannedRunUnitTestsWithTimerTimesOut(self):
  2806. io.open().readline.return_value = ''
  2807. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2808. None, 0, 0, None)
  2809. input_api = self.MockInputApi(change, False)
  2810. input_api.verbose = True
  2811. input_api.thread_pool.timeout = 100
  2812. input_api.PresubmitLocalPath.return_value = self.fake_root_dir
  2813. presubmit.sigint_handler.wait.return_value = (b'', None)
  2814. subprocess.Popen.return_value = mock.Mock(returncode=1)
  2815. timer_instance = mock.Mock()
  2816. def mockTimer(_, fn):
  2817. fn()
  2818. return timer_instance
  2819. threading.Timer.side_effect = mockTimer
  2820. results = presubmit_canned_checks.RunUnitTests(input_api,
  2821. presubmit.OutputApi,
  2822. ['bar.py'])
  2823. self.assertEqual(presubmit.OutputApi.PresubmitPromptWarning,
  2824. results[0].__class__)
  2825. results[0].handle()
  2826. self.assertIn(
  2827. 'bar.py --verbose (0.00s) failed\nProcess timed out after 100s',
  2828. sys.stdout.getvalue())
  2829. threading.Timer.assert_called_once_with(input_api.thread_pool.timeout,
  2830. mock.ANY)
  2831. timer_instance.start.assert_called_once_with()
  2832. @mock.patch('io.open', mock.mock_open())
  2833. def testCannedRunUnitTestsPython3(self):
  2834. io.open().readline.return_value = '#!/usr/bin/env python3'
  2835. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2836. None, 0, 0, None)
  2837. input_api = self.MockInputApi(change, False)
  2838. input_api.verbose = True
  2839. input_api.PresubmitLocalPath.return_value = self.fake_root_dir
  2840. presubmit.sigint_handler.wait.return_value = (b'', None)
  2841. subprocesses = [
  2842. mock.Mock(returncode=1),
  2843. mock.Mock(returncode=0),
  2844. mock.Mock(returncode=0),
  2845. ]
  2846. subprocess.Popen.side_effect = subprocesses
  2847. unit_tests = ['allo', 'bar.py']
  2848. results = presubmit_canned_checks.RunUnitTests(input_api,
  2849. presubmit.OutputApi,
  2850. unit_tests)
  2851. self.assertEqual([result.__class__ for result in results], [
  2852. presubmit.OutputApi.PresubmitPromptWarning,
  2853. presubmit.OutputApi.PresubmitNotifyResult,
  2854. ])
  2855. cmd = ['bar.py', '--verbose']
  2856. vpython3 = 'vpython3'
  2857. if input_api.platform == 'win32':
  2858. vpython3 += '.bat'
  2859. self.assertEqual(subprocess.Popen.mock_calls, [
  2860. mock.call([vpython3] + cmd,
  2861. cwd=self.fake_root_dir,
  2862. stdout=subprocess.PIPE,
  2863. stderr=subprocess.STDOUT,
  2864. stdin=subprocess.PIPE),
  2865. mock.call(['allo', '--verbose'],
  2866. cwd=self.fake_root_dir,
  2867. stdout=subprocess.PIPE,
  2868. stderr=subprocess.STDOUT,
  2869. stdin=subprocess.PIPE),
  2870. ])
  2871. self.assertEqual(presubmit.sigint_handler.wait.mock_calls, [
  2872. mock.call(subprocesses[0], None),
  2873. mock.call(subprocesses[1], None),
  2874. ])
  2875. self.checkstdout('')
  2876. @mock.patch('io.open', mock.mock_open())
  2877. def testCannedRunUnitTestsDontRunOnPython2(self):
  2878. io.open().readline.return_value = '#!/usr/bin/env python3'
  2879. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2880. None, 0, 0, None)
  2881. input_api = self.MockInputApi(change, False)
  2882. input_api.verbose = True
  2883. input_api.PresubmitLocalPath.return_value = self.fake_root_dir
  2884. presubmit.sigint_handler.wait.return_value = (b'', None)
  2885. subprocess.Popen.side_effect = [
  2886. mock.Mock(returncode=1),
  2887. mock.Mock(returncode=0),
  2888. mock.Mock(returncode=0),
  2889. ]
  2890. unit_tests = ['allo', 'bar.py']
  2891. results = presubmit_canned_checks.RunUnitTests(input_api,
  2892. presubmit.OutputApi,
  2893. unit_tests,
  2894. run_on_python2=False)
  2895. self.assertEqual([result.__class__ for result in results], [
  2896. presubmit.OutputApi.PresubmitPromptWarning,
  2897. presubmit.OutputApi.PresubmitNotifyResult,
  2898. ])
  2899. cmd = ['bar.py', '--verbose']
  2900. vpython3 = 'vpython3'
  2901. if input_api.platform == 'win32':
  2902. vpython3 += '.bat'
  2903. self.assertEqual(subprocess.Popen.mock_calls, [
  2904. mock.call([vpython3] + cmd,
  2905. cwd=self.fake_root_dir,
  2906. stdout=subprocess.PIPE,
  2907. stderr=subprocess.STDOUT,
  2908. stdin=subprocess.PIPE),
  2909. mock.call(['allo', '--verbose'],
  2910. cwd=self.fake_root_dir,
  2911. stdout=subprocess.PIPE,
  2912. stderr=subprocess.STDOUT,
  2913. stdin=subprocess.PIPE),
  2914. ])
  2915. self.checkstdout('')
  2916. def testCannedRunUnitTestsInDirectory(self):
  2917. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2918. None, 0, 0, None)
  2919. input_api = self.MockInputApi(change, False)
  2920. input_api.verbose = True
  2921. input_api.logging = mock.MagicMock(logging)
  2922. input_api.PresubmitLocalPath.return_value = self.fake_root_dir
  2923. input_api.os_listdir.return_value = ['.', '..', 'a', 'b', 'c']
  2924. input_api.os_path.isfile = lambda x: not x.endswith('.')
  2925. process = mock.Mock()
  2926. process.returncode = 0
  2927. subprocess.Popen.return_value = process
  2928. presubmit.sigint_handler.wait.return_value = (b'', None)
  2929. results = presubmit_canned_checks.RunUnitTestsInDirectory(
  2930. input_api,
  2931. presubmit.OutputApi,
  2932. 'random_directory',
  2933. files_to_check=['^a$', '^b$'],
  2934. files_to_skip=['a'])
  2935. self.assertEqual(1, len(results))
  2936. self.assertEqual(presubmit.OutputApi.PresubmitNotifyResult,
  2937. results[0].__class__)
  2938. self.assertEqual(subprocess.Popen.mock_calls, [
  2939. mock.call([os.path.join('random_directory', 'b'), '--verbose'],
  2940. cwd=self.fake_root_dir,
  2941. stdout=subprocess.PIPE,
  2942. stderr=subprocess.STDOUT,
  2943. stdin=subprocess.PIPE),
  2944. ])
  2945. self.checkstdout('')
  2946. def testPanProjectChecks(self):
  2947. # Make sure it accepts both list and tuples.
  2948. change = presubmit.Change('foo1', 'description1', self.fake_root_dir,
  2949. None, 0, 0, None)
  2950. input_api = self.MockInputApi(change, False)
  2951. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  2952. input_api.AffectedFiles.return_value = [affected_file]
  2953. affected_file.NewContents.return_value = 'Hey!\nHo!\nHey!\nHo!\n\n'
  2954. # CheckChangeHasNoTabs() calls _FindNewViolationsOfRule() which calls
  2955. # ChangedContents().
  2956. affected_file.ChangedContents.return_value = [
  2957. (0, 'Hey!\n'), (1, 'Ho!\n'), (2, 'Hey!\n'), (3, 'Ho!\n'), (4, '\n')
  2958. ]
  2959. affected_file.LocalPath.return_value = 'hello.py'
  2960. # CheckingLicense() calls AffectedSourceFiles() instead of
  2961. # AffectedFiles().
  2962. input_api.AffectedSourceFiles.return_value = [affected_file]
  2963. input_api.ReadFile.return_value = 'Hey!\nHo!\nHey!\nHo!\n\n'
  2964. results = presubmit_canned_checks.PanProjectChecks(input_api,
  2965. presubmit.OutputApi,
  2966. excluded_paths=None,
  2967. text_files=None,
  2968. license_header=None,
  2969. project_name=None,
  2970. owners_check=False)
  2971. self.assertEqual(2, len(results))
  2972. self.assertEqual('Found line ending with white spaces in:',
  2973. results[0]._message)
  2974. self.checkstdout('')
  2975. def testCheckCIPDManifest_file(self):
  2976. input_api = self.MockInputApi(None, False)
  2977. command = presubmit_canned_checks.CheckCIPDManifest(input_api,
  2978. presubmit.OutputApi,
  2979. path='/path/to/foo')
  2980. self.assertEqual(
  2981. command.cmd,
  2982. ['cipd', 'ensure-file-verify', '-ensure-file', '/path/to/foo'])
  2983. self.assertEqual(
  2984. command.kwargs, {
  2985. 'stdin': subprocess.PIPE,
  2986. 'stdout': subprocess.PIPE,
  2987. 'stderr': subprocess.STDOUT,
  2988. })
  2989. def testCheckCIPDManifest_content(self):
  2990. input_api = self.MockInputApi(None, False)
  2991. input_api.verbose = True
  2992. command = presubmit_canned_checks.CheckCIPDManifest(
  2993. input_api, presubmit.OutputApi, content='manifest_content')
  2994. self.assertEqual(command.cmd, [
  2995. 'cipd', 'ensure-file-verify', '-log-level', 'debug',
  2996. '-ensure-file=-'
  2997. ])
  2998. self.assertEqual(command.stdin, b'manifest_content')
  2999. self.assertEqual(
  3000. command.kwargs, {
  3001. 'stdin': subprocess.PIPE,
  3002. 'stdout': subprocess.PIPE,
  3003. 'stderr': subprocess.STDOUT,
  3004. })
  3005. def testCheckCIPDPackages(self):
  3006. content = '\n'.join([
  3007. '$VerifiedPlatform foo-bar',
  3008. '$VerifiedPlatform baz-qux',
  3009. 'foo/bar/baz/${platform} version:ohaithere',
  3010. 'qux version:kthxbye',
  3011. ])
  3012. input_api = self.MockInputApi(None, False)
  3013. command = presubmit_canned_checks.CheckCIPDPackages(
  3014. input_api,
  3015. presubmit.OutputApi,
  3016. platforms=['foo-bar', 'baz-qux'],
  3017. packages={
  3018. 'foo/bar/baz/${platform}': 'version:ohaithere',
  3019. 'qux': 'version:kthxbye',
  3020. })
  3021. self.assertEqual(command.cmd,
  3022. ['cipd', 'ensure-file-verify', '-ensure-file=-'])
  3023. self.assertEqual(command.stdin, content.encode())
  3024. self.assertEqual(
  3025. command.kwargs, {
  3026. 'stdin': subprocess.PIPE,
  3027. 'stdout': subprocess.PIPE,
  3028. 'stderr': subprocess.STDOUT,
  3029. })
  3030. def testCheckCIPDClientDigests(self):
  3031. input_api = self.MockInputApi(None, False)
  3032. input_api.verbose = True
  3033. command = presubmit_canned_checks.CheckCIPDClientDigests(
  3034. input_api, presubmit.OutputApi, client_version_file='ver')
  3035. self.assertEqual(command.cmd, [
  3036. 'cipd',
  3037. 'selfupdate-roll',
  3038. '-check',
  3039. '-version-file',
  3040. 'ver',
  3041. '-log-level',
  3042. 'debug',
  3043. ])
  3044. def testCannedCheckVPythonSpec(self):
  3045. change = presubmit.Change('a', 'b', self.fake_root_dir, None, 0, 0,
  3046. None)
  3047. input_api = self.MockInputApi(change, False)
  3048. affected_filenames = ['/path1/to/.vpython', '/path1/to/.vpython3']
  3049. affected_files = []
  3050. for filename in affected_filenames:
  3051. affected_file = mock.MagicMock(presubmit.GitAffectedFile)
  3052. affected_file.AbsoluteLocalPath.return_value = filename
  3053. affected_files.append(affected_file)
  3054. input_api.AffectedTestableFiles.return_value = affected_files
  3055. commands = presubmit_canned_checks.CheckVPythonSpec(
  3056. input_api, presubmit.OutputApi)
  3057. self.assertEqual(len(commands), len(affected_filenames))
  3058. for i in range(0, len(commands)):
  3059. self.assertEqual(commands[i].name,
  3060. 'Verify ' + affected_filenames[i])
  3061. self.assertEqual(commands[i].cmd, [
  3062. input_api.python3_executable, '-vpython-spec',
  3063. affected_filenames[i], '-vpython-tool', 'verify'
  3064. ])
  3065. self.assertDictEqual(
  3066. commands[0].kwargs, {
  3067. 'stderr': input_api.subprocess.STDOUT,
  3068. 'stdout': input_api.subprocess.PIPE,
  3069. 'stdin': input_api.subprocess.PIPE,
  3070. })
  3071. self.assertEqual(commands[0].message,
  3072. presubmit.OutputApi.PresubmitError)
  3073. self.assertIsNone(commands[0].info)
  3074. class ThreadPoolTest(unittest.TestCase):
  3075. def setUp(self):
  3076. super(ThreadPoolTest, self).setUp()
  3077. mock.patch('subprocess2.Popen').start()
  3078. mock.patch('presubmit_support.sigint_handler').start()
  3079. mock.patch('presubmit_support.time_time', return_value=0).start()
  3080. presubmit.sigint_handler.wait.return_value = (b'stdout', '')
  3081. self.addCleanup(mock.patch.stopall)
  3082. def testSurfaceExceptions(self):
  3083. def FakePopen(cmd, **kwargs):
  3084. if cmd[0] == '3':
  3085. raise TypeError('TypeError')
  3086. if cmd[0] == '4':
  3087. raise OSError('OSError')
  3088. if cmd[0] == '5':
  3089. return mock.Mock(returncode=1)
  3090. return mock.Mock(returncode=0)
  3091. subprocess.Popen.side_effect = FakePopen
  3092. mock_tests = [
  3093. presubmit.CommandData(
  3094. name=str(i),
  3095. cmd=[str(i)],
  3096. kwargs={},
  3097. message=lambda x, **kwargs: x,
  3098. ) for i in range(10)
  3099. ]
  3100. t = presubmit.ThreadPool(1)
  3101. t.AddTests(mock_tests)
  3102. messages = sorted(t.RunAsync())
  3103. self.assertEqual(3, len(messages))
  3104. self.assertIn(
  3105. '3\n3 exec failure (0.00s)\nTraceback (most recent call last):',
  3106. messages[0])
  3107. self.assertIn(
  3108. '4\n4 exec failure (0.00s)\nTraceback (most recent call last):',
  3109. messages[1])
  3110. self.assertEqual('5\n5 (0.00s) failed\nstdout', messages[2])
  3111. if __name__ == '__main__':
  3112. import unittest
  3113. unittest.main()