PRESUBMIT_test.py 175 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643
  1. #!/usr/bin/env python3
  2. # Copyright 2012 The Chromium Authors
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. import io
  6. import os.path
  7. import subprocess
  8. import unittest
  9. import PRESUBMIT
  10. from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
  11. from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
  12. _TEST_DATA_DIR = 'base/test/data/presubmit'
  13. class VersionControlConflictsTest(unittest.TestCase):
  14. def testTypicalConflict(self):
  15. lines = ['<<<<<<< HEAD',
  16. ' base::ScopedTempDir temp_dir_;',
  17. '=======',
  18. ' ScopedTempDir temp_dir_;',
  19. '>>>>>>> master']
  20. errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
  21. MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
  22. self.assertEqual(3, len(errors))
  23. self.assertTrue('1' in errors[0])
  24. self.assertTrue('3' in errors[1])
  25. self.assertTrue('5' in errors[2])
  26. def testIgnoresReadmes(self):
  27. lines = ['A First Level Header',
  28. '====================',
  29. '',
  30. 'A Second Level Header',
  31. '---------------------']
  32. errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
  33. MockInputApi(), MockFile('some/polymer/README.md', lines))
  34. self.assertEqual(0, len(errors))
  35. class BadExtensionsTest(unittest.TestCase):
  36. def testBadRejFile(self):
  37. mock_input_api = MockInputApi()
  38. mock_input_api.files = [
  39. MockFile('some/path/foo.cc', ''),
  40. MockFile('some/path/foo.cc.rej', ''),
  41. MockFile('some/path2/bar.h.rej', ''),
  42. ]
  43. results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
  44. self.assertEqual(1, len(results))
  45. self.assertEqual(2, len(results[0].items))
  46. self.assertTrue('foo.cc.rej' in results[0].items[0])
  47. self.assertTrue('bar.h.rej' in results[0].items[1])
  48. def testBadOrigFile(self):
  49. mock_input_api = MockInputApi()
  50. mock_input_api.files = [
  51. MockFile('other/path/qux.h.orig', ''),
  52. MockFile('other/path/qux.h', ''),
  53. MockFile('other/path/qux.cc', ''),
  54. ]
  55. results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
  56. self.assertEqual(1, len(results))
  57. self.assertEqual(1, len(results[0].items))
  58. self.assertTrue('qux.h.orig' in results[0].items[0])
  59. def testGoodFiles(self):
  60. mock_input_api = MockInputApi()
  61. mock_input_api.files = [
  62. MockFile('other/path/qux.h', ''),
  63. MockFile('other/path/qux.cc', ''),
  64. ]
  65. results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
  66. self.assertEqual(0, len(results))
  67. class CheckForSuperfluousStlIncludesInHeadersTest(unittest.TestCase):
  68. def testGoodFiles(self):
  69. mock_input_api = MockInputApi()
  70. mock_input_api.files = [
  71. # The check is not smart enough to figure out which definitions correspond
  72. # to which header.
  73. MockFile('other/path/foo.h',
  74. ['#include <string>',
  75. 'std::vector']),
  76. # The check is not smart enough to do IWYU.
  77. MockFile('other/path/bar.h',
  78. ['#include "base/check.h"',
  79. 'std::vector']),
  80. MockFile('other/path/qux.h',
  81. ['#include "base/stl_util.h"',
  82. 'foobar']),
  83. MockFile('other/path/baz.h',
  84. ['#include "set/vector.h"',
  85. 'bazzab']),
  86. # The check is only for header files.
  87. MockFile('other/path/not_checked.cc',
  88. ['#include <vector>',
  89. 'bazbaz']),
  90. ]
  91. results = PRESUBMIT.CheckForSuperfluousStlIncludesInHeaders(
  92. mock_input_api, MockOutputApi())
  93. self.assertEqual(0, len(results))
  94. def testBadFiles(self):
  95. mock_input_api = MockInputApi()
  96. mock_input_api.files = [
  97. MockFile('other/path/foo.h',
  98. ['#include <vector>',
  99. 'vector']),
  100. MockFile('other/path/bar.h',
  101. ['#include <limits>',
  102. '#include <set>',
  103. 'no_std_namespace']),
  104. ]
  105. results = PRESUBMIT.CheckForSuperfluousStlIncludesInHeaders(
  106. mock_input_api, MockOutputApi())
  107. self.assertEqual(1, len(results))
  108. self.assertTrue('foo.h: Includes STL' in results[0].message)
  109. self.assertTrue('bar.h: Includes STL' in results[0].message)
  110. class CheckSingletonInHeadersTest(unittest.TestCase):
  111. def testSingletonInArbitraryHeader(self):
  112. diff_singleton_h = ['base::subtle::AtomicWord '
  113. 'base::Singleton<Type, Traits, DifferentiatingType>::']
  114. diff_foo_h = ['// base::Singleton<Foo> in comment.',
  115. 'friend class base::Singleton<Foo>']
  116. diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
  117. diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
  118. mock_input_api = MockInputApi()
  119. mock_input_api.files = [MockAffectedFile('base/memory/singleton.h',
  120. diff_singleton_h),
  121. MockAffectedFile('foo.h', diff_foo_h),
  122. MockAffectedFile('foo2.h', diff_foo2_h),
  123. MockAffectedFile('bad.h', diff_bad_h)]
  124. warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
  125. MockOutputApi())
  126. self.assertEqual(1, len(warnings))
  127. self.assertEqual(1, len(warnings[0].items))
  128. self.assertEqual('error', warnings[0].type)
  129. self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
  130. def testSingletonInCC(self):
  131. diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
  132. mock_input_api = MockInputApi()
  133. mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
  134. warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
  135. MockOutputApi())
  136. self.assertEqual(0, len(warnings))
  137. class DeprecatedOSMacroNamesTest(unittest.TestCase):
  138. def testDeprecatedOSMacroNames(self):
  139. lines = ['#if defined(OS_WIN)',
  140. ' #elif defined(OS_WINDOW)',
  141. ' # if defined(OS_MAC) || defined(OS_CHROME)']
  142. errors = PRESUBMIT._CheckForDeprecatedOSMacrosInFile(
  143. MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
  144. self.assertEqual(len(lines) + 1, len(errors))
  145. self.assertTrue(':1: defined(OS_WIN) -> BUILDFLAG(IS_WIN)' in errors[0])
  146. class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
  147. def testInvalidIfDefinedMacroNames(self):
  148. lines = ['#if defined(TARGET_IPHONE_SIMULATOR)',
  149. '#if !defined(TARGET_IPHONE_SIMULATOR)',
  150. '#elif defined(TARGET_IPHONE_SIMULATOR)',
  151. '#ifdef TARGET_IPHONE_SIMULATOR',
  152. ' # ifdef TARGET_IPHONE_SIMULATOR',
  153. '# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
  154. '# else // defined(TARGET_IPHONE_SIMULATOR)',
  155. '#endif // defined(TARGET_IPHONE_SIMULATOR)']
  156. errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
  157. MockInputApi(), MockFile('some/path/source.mm', lines))
  158. self.assertEqual(len(lines), len(errors))
  159. def testValidIfDefinedMacroNames(self):
  160. lines = ['#if defined(FOO)',
  161. '#ifdef BAR']
  162. errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
  163. MockInputApi(), MockFile('some/path/source.cc', lines))
  164. self.assertEqual(0, len(errors))
  165. class CheckAddedDepsHaveTestApprovalsTest(unittest.TestCase):
  166. def calculate(self, old_include_rules, old_specific_include_rules,
  167. new_include_rules, new_specific_include_rules):
  168. return PRESUBMIT._CalculateAddedDeps(
  169. os.path, 'include_rules = %r\nspecific_include_rules = %r' % (
  170. old_include_rules, old_specific_include_rules),
  171. 'include_rules = %r\nspecific_include_rules = %r' % (
  172. new_include_rules, new_specific_include_rules))
  173. def testCalculateAddedDeps(self):
  174. old_include_rules = [
  175. '+base',
  176. '-chrome',
  177. '+content',
  178. '-grit',
  179. '-grit/",',
  180. '+jni/fooblat.h',
  181. '!sandbox',
  182. ]
  183. old_specific_include_rules = {
  184. 'compositor\.*': {
  185. '+cc',
  186. },
  187. }
  188. new_include_rules = [
  189. '-ash',
  190. '+base',
  191. '+chrome',
  192. '+components',
  193. '+content',
  194. '+grit',
  195. '+grit/generated_resources.h",',
  196. '+grit/",',
  197. '+jni/fooblat.h',
  198. '+policy',
  199. '+' + os.path.join('third_party', 'WebKit'),
  200. ]
  201. new_specific_include_rules = {
  202. 'compositor\.*': {
  203. '+cc',
  204. },
  205. 'widget\.*': {
  206. '+gpu',
  207. },
  208. }
  209. expected = set([
  210. os.path.join('chrome', 'DEPS'),
  211. os.path.join('gpu', 'DEPS'),
  212. os.path.join('components', 'DEPS'),
  213. os.path.join('policy', 'DEPS'),
  214. os.path.join('third_party', 'WebKit', 'DEPS'),
  215. ])
  216. self.assertEqual(
  217. expected,
  218. self.calculate(old_include_rules, old_specific_include_rules,
  219. new_include_rules, new_specific_include_rules))
  220. def testCalculateAddedDepsIgnoresPermutations(self):
  221. old_include_rules = [
  222. '+base',
  223. '+chrome',
  224. ]
  225. new_include_rules = [
  226. '+chrome',
  227. '+base',
  228. ]
  229. self.assertEqual(set(),
  230. self.calculate(old_include_rules, {}, new_include_rules,
  231. {}))
  232. class JSONParsingTest(unittest.TestCase):
  233. def testSuccess(self):
  234. input_api = MockInputApi()
  235. filename = 'valid_json.json'
  236. contents = ['// This is a comment.',
  237. '{',
  238. ' "key1": ["value1", "value2"],',
  239. ' "key2": 3 // This is an inline comment.',
  240. '}'
  241. ]
  242. input_api.files = [MockFile(filename, contents)]
  243. self.assertEqual(None,
  244. PRESUBMIT._GetJSONParseError(input_api, filename))
  245. def testFailure(self):
  246. input_api = MockInputApi()
  247. test_data = [
  248. ('invalid_json_1.json',
  249. ['{ x }'],
  250. 'Expecting property name'),
  251. ('invalid_json_2.json',
  252. ['// Hello world!',
  253. '{ "hello": "world }'],
  254. 'Unterminated string starting at:'),
  255. ('invalid_json_3.json',
  256. ['{ "a": "b", "c": "d", }'],
  257. 'Expecting property name'),
  258. ('invalid_json_4.json',
  259. ['{ "a": "b" "c": "d" }'],
  260. "Expecting ',' delimiter:"),
  261. ]
  262. input_api.files = [MockFile(filename, contents)
  263. for (filename, contents, _) in test_data]
  264. for (filename, _, expected_error) in test_data:
  265. actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
  266. self.assertTrue(expected_error in str(actual_error),
  267. "'%s' not found in '%s'" % (expected_error, actual_error))
  268. def testNoEatComments(self):
  269. input_api = MockInputApi()
  270. file_with_comments = 'file_with_comments.json'
  271. contents_with_comments = ['// This is a comment.',
  272. '{',
  273. ' "key1": ["value1", "value2"],',
  274. ' "key2": 3 // This is an inline comment.',
  275. '}'
  276. ]
  277. file_without_comments = 'file_without_comments.json'
  278. contents_without_comments = ['{',
  279. ' "key1": ["value1", "value2"],',
  280. ' "key2": 3',
  281. '}'
  282. ]
  283. input_api.files = [MockFile(file_with_comments, contents_with_comments),
  284. MockFile(file_without_comments,
  285. contents_without_comments)]
  286. self.assertNotEqual(None,
  287. str(PRESUBMIT._GetJSONParseError(input_api,
  288. file_with_comments,
  289. eat_comments=False)))
  290. self.assertEqual(None,
  291. PRESUBMIT._GetJSONParseError(input_api,
  292. file_without_comments,
  293. eat_comments=False))
  294. class IDLParsingTest(unittest.TestCase):
  295. def testSuccess(self):
  296. input_api = MockInputApi()
  297. filename = 'valid_idl_basics.idl'
  298. contents = ['// Tests a valid IDL file.',
  299. 'namespace idl_basics {',
  300. ' enum EnumType {',
  301. ' name1,',
  302. ' name2',
  303. ' };',
  304. '',
  305. ' dictionary MyType1 {',
  306. ' DOMString a;',
  307. ' };',
  308. '',
  309. ' callback Callback1 = void();',
  310. ' callback Callback2 = void(long x);',
  311. ' callback Callback3 = void(MyType1 arg);',
  312. ' callback Callback4 = void(EnumType type);',
  313. '',
  314. ' interface Functions {',
  315. ' static void function1();',
  316. ' static void function2(long x);',
  317. ' static void function3(MyType1 arg);',
  318. ' static void function4(Callback1 cb);',
  319. ' static void function5(Callback2 cb);',
  320. ' static void function6(Callback3 cb);',
  321. ' static void function7(Callback4 cb);',
  322. ' };',
  323. '',
  324. ' interface Events {',
  325. ' static void onFoo1();',
  326. ' static void onFoo2(long x);',
  327. ' static void onFoo2(MyType1 arg);',
  328. ' static void onFoo3(EnumType type);',
  329. ' };',
  330. '};'
  331. ]
  332. input_api.files = [MockFile(filename, contents)]
  333. self.assertEqual(None,
  334. PRESUBMIT._GetIDLParseError(input_api, filename))
  335. def testFailure(self):
  336. input_api = MockInputApi()
  337. test_data = [
  338. ('invalid_idl_1.idl',
  339. ['//',
  340. 'namespace test {',
  341. ' dictionary {',
  342. ' DOMString s;',
  343. ' };',
  344. '};'],
  345. 'Unexpected "{" after keyword "dictionary".\n'),
  346. # TODO(yoz): Disabled because it causes the IDL parser to hang.
  347. # See crbug.com/363830.
  348. # ('invalid_idl_2.idl',
  349. # (['namespace test {',
  350. # ' dictionary MissingSemicolon {',
  351. # ' DOMString a',
  352. # ' DOMString b;',
  353. # ' };',
  354. # '};'],
  355. # 'Unexpected symbol DOMString after symbol a.'),
  356. ('invalid_idl_3.idl',
  357. ['//',
  358. 'namespace test {',
  359. ' enum MissingComma {',
  360. ' name1',
  361. ' name2',
  362. ' };',
  363. '};'],
  364. 'Unexpected symbol name2 after symbol name1.'),
  365. ('invalid_idl_4.idl',
  366. ['//',
  367. 'namespace test {',
  368. ' enum TrailingComma {',
  369. ' name1,',
  370. ' name2,',
  371. ' };',
  372. '};'],
  373. 'Trailing comma in block.'),
  374. ('invalid_idl_5.idl',
  375. ['//',
  376. 'namespace test {',
  377. ' callback Callback1 = void(;',
  378. '};'],
  379. 'Unexpected ";" after "(".'),
  380. ('invalid_idl_6.idl',
  381. ['//',
  382. 'namespace test {',
  383. ' callback Callback1 = void(long );',
  384. '};'],
  385. 'Unexpected ")" after symbol long.'),
  386. ('invalid_idl_7.idl',
  387. ['//',
  388. 'namespace test {',
  389. ' interace Events {',
  390. ' static void onFoo1();',
  391. ' };',
  392. '};'],
  393. 'Unexpected symbol Events after symbol interace.'),
  394. ('invalid_idl_8.idl',
  395. ['//',
  396. 'namespace test {',
  397. ' interface NotEvent {',
  398. ' static void onFoo1();',
  399. ' };',
  400. '};'],
  401. 'Did not process Interface Interface(NotEvent)'),
  402. ('invalid_idl_9.idl',
  403. ['//',
  404. 'namespace test {',
  405. ' interface {',
  406. ' static void function1();',
  407. ' };',
  408. '};'],
  409. 'Interface missing name.'),
  410. ]
  411. input_api.files = [MockFile(filename, contents)
  412. for (filename, contents, _) in test_data]
  413. for (filename, _, expected_error) in test_data:
  414. actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
  415. self.assertTrue(expected_error in str(actual_error),
  416. "'%s' not found in '%s'" % (expected_error, actual_error))
  417. class UserMetricsActionTest(unittest.TestCase):
  418. def testUserMetricsActionInActions(self):
  419. input_api = MockInputApi()
  420. file_with_user_action = 'file_with_user_action.cc'
  421. contents_with_user_action = [
  422. 'base::UserMetricsAction("AboutChrome")'
  423. ]
  424. input_api.files = [MockFile(file_with_user_action,
  425. contents_with_user_action)]
  426. self.assertEqual(
  427. [], PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi()))
  428. def testUserMetricsActionNotAddedToActions(self):
  429. input_api = MockInputApi()
  430. file_with_user_action = 'file_with_user_action.cc'
  431. contents_with_user_action = [
  432. 'base::UserMetricsAction("NotInActionsXml")'
  433. ]
  434. input_api.files = [MockFile(file_with_user_action,
  435. contents_with_user_action)]
  436. output = PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi())
  437. self.assertEqual(
  438. ('File %s line %d: %s is missing in '
  439. 'tools/metrics/actions/actions.xml. Please run '
  440. 'tools/metrics/actions/extract_actions.py to update.'
  441. % (file_with_user_action, 1, 'NotInActionsXml')),
  442. output[0].message)
  443. def testUserMetricsActionInTestFile(self):
  444. input_api = MockInputApi()
  445. file_with_user_action = 'file_with_user_action_unittest.cc'
  446. contents_with_user_action = [
  447. 'base::UserMetricsAction("NotInActionsXml")'
  448. ]
  449. input_api.files = [MockFile(file_with_user_action,
  450. contents_with_user_action)]
  451. self.assertEqual(
  452. [], PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi()))
  453. class PydepsNeedsUpdatingTest(unittest.TestCase):
  454. class MockPopen:
  455. def __init__(self, stdout_func):
  456. self._stdout_func = stdout_func
  457. def wait(self):
  458. self.stdout = io.StringIO(self._stdout_func())
  459. return 0
  460. class MockSubprocess:
  461. CalledProcessError = subprocess.CalledProcessError
  462. PIPE = 0
  463. def __init__(self):
  464. self._popen_func = None
  465. def SetPopenCallback(self, func):
  466. self._popen_func = func
  467. def Popen(self, cmd, *args, **kwargs):
  468. return PydepsNeedsUpdatingTest.MockPopen(lambda: self._popen_func(cmd))
  469. def _MockParseGclientArgs(self, is_android=True):
  470. return lambda: {'checkout_android': 'true' if is_android else 'false' }
  471. def setUp(self):
  472. mock_all_pydeps = ['A.pydeps', 'B.pydeps', 'D.pydeps']
  473. self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
  474. PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
  475. mock_android_pydeps = ['D.pydeps']
  476. self.old_ANDROID_SPECIFIC_PYDEPS_FILES = (
  477. PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES)
  478. PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = mock_android_pydeps
  479. self.old_ParseGclientArgs = PRESUBMIT._ParseGclientArgs
  480. PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs()
  481. self.mock_input_api = MockInputApi()
  482. self.mock_output_api = MockOutputApi()
  483. self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess()
  484. self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api, mock_all_pydeps)
  485. self.checker._file_cache = {
  486. 'A.pydeps': '# Generated by:\n# CMD --output A.pydeps A\nA.py\nC.py\n',
  487. 'B.pydeps': '# Generated by:\n# CMD --output B.pydeps B\nB.py\nC.py\n',
  488. 'D.pydeps': '# Generated by:\n# CMD --output D.pydeps D\nD.py\n',
  489. }
  490. def tearDown(self):
  491. PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
  492. PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = (
  493. self.old_ANDROID_SPECIFIC_PYDEPS_FILES)
  494. PRESUBMIT._ParseGclientArgs = self.old_ParseGclientArgs
  495. def _RunCheck(self):
  496. return PRESUBMIT.CheckPydepsNeedsUpdating(self.mock_input_api,
  497. self.mock_output_api,
  498. checker_for_tests=self.checker)
  499. def testAddedPydep(self):
  500. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  501. if not self.mock_input_api.platform.startswith('linux'):
  502. return []
  503. self.mock_input_api.files = [
  504. MockAffectedFile('new.pydeps', [], action='A'),
  505. ]
  506. self.mock_input_api.CreateMockFileInPath(
  507. [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
  508. include_deletes=True)])
  509. results = self._RunCheck()
  510. self.assertEqual(1, len(results))
  511. self.assertIn('PYDEPS_FILES', str(results[0]))
  512. def testPydepNotInSrc(self):
  513. self.mock_input_api.files = [
  514. MockAffectedFile('new.pydeps', [], action='A'),
  515. ]
  516. self.mock_input_api.CreateMockFileInPath([])
  517. results = self._RunCheck()
  518. self.assertEqual(0, len(results))
  519. def testRemovedPydep(self):
  520. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  521. if not self.mock_input_api.platform.startswith('linux'):
  522. return []
  523. self.mock_input_api.files = [
  524. MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
  525. ]
  526. self.mock_input_api.CreateMockFileInPath(
  527. [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
  528. include_deletes=True)])
  529. results = self._RunCheck()
  530. self.assertEqual(1, len(results))
  531. self.assertIn('PYDEPS_FILES', str(results[0]))
  532. def testRandomPyIgnored(self):
  533. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  534. if not self.mock_input_api.platform.startswith('linux'):
  535. return []
  536. self.mock_input_api.files = [
  537. MockAffectedFile('random.py', []),
  538. ]
  539. results = self._RunCheck()
  540. self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
  541. def testRelevantPyNoChange(self):
  542. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  543. if not self.mock_input_api.platform.startswith('linux'):
  544. return []
  545. self.mock_input_api.files = [
  546. MockAffectedFile('A.py', []),
  547. ]
  548. def popen_callback(cmd):
  549. self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
  550. return self.checker._file_cache['A.pydeps']
  551. self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
  552. results = self._RunCheck()
  553. self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
  554. def testRelevantPyOneChange(self):
  555. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  556. if not self.mock_input_api.platform.startswith('linux'):
  557. return []
  558. self.mock_input_api.files = [
  559. MockAffectedFile('A.py', []),
  560. ]
  561. def popen_callback(cmd):
  562. self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
  563. return 'changed data'
  564. self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
  565. results = self._RunCheck()
  566. self.assertEqual(1, len(results))
  567. # Check that --output "" is not included.
  568. self.assertNotIn('""', str(results[0]))
  569. self.assertIn('File is stale', str(results[0]))
  570. def testRelevantPyTwoChanges(self):
  571. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  572. if not self.mock_input_api.platform.startswith('linux'):
  573. return []
  574. self.mock_input_api.files = [
  575. MockAffectedFile('C.py', []),
  576. ]
  577. def popen_callback(cmd):
  578. return 'changed data'
  579. self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
  580. results = self._RunCheck()
  581. self.assertEqual(2, len(results))
  582. self.assertIn('File is stale', str(results[0]))
  583. self.assertIn('File is stale', str(results[1]))
  584. def testRelevantAndroidPyInNonAndroidCheckout(self):
  585. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  586. if not self.mock_input_api.platform.startswith('linux'):
  587. return []
  588. self.mock_input_api.files = [
  589. MockAffectedFile('D.py', []),
  590. ]
  591. def popen_callback(cmd):
  592. self.assertEqual('CMD --output D.pydeps D --output ""', cmd)
  593. return 'changed data'
  594. self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
  595. PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs(is_android=False)
  596. results = self._RunCheck()
  597. self.assertEqual(1, len(results))
  598. self.assertIn('Android', str(results[0]))
  599. self.assertIn('D.pydeps', str(results[0]))
  600. def testGnPathsAndMissingOutputFlag(self):
  601. # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
  602. if not self.mock_input_api.platform.startswith('linux'):
  603. return []
  604. self.checker._file_cache = {
  605. 'A.pydeps': '# Generated by:\n# CMD --gn-paths A\n//A.py\n//C.py\n',
  606. 'B.pydeps': '# Generated by:\n# CMD --gn-paths B\n//B.py\n//C.py\n',
  607. 'D.pydeps': '# Generated by:\n# CMD --gn-paths D\n//D.py\n',
  608. }
  609. self.mock_input_api.files = [
  610. MockAffectedFile('A.py', []),
  611. ]
  612. def popen_callback(cmd):
  613. self.assertEqual('CMD --gn-paths A --output A.pydeps --output ""', cmd)
  614. return 'changed data'
  615. self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
  616. results = self._RunCheck()
  617. self.assertEqual(1, len(results))
  618. self.assertIn('File is stale', str(results[0]))
  619. class IncludeGuardTest(unittest.TestCase):
  620. def testIncludeGuardChecks(self):
  621. mock_input_api = MockInputApi()
  622. mock_output_api = MockOutputApi()
  623. mock_input_api.files = [
  624. MockAffectedFile('content/browser/thing/foo.h', [
  625. '// Comment',
  626. '#ifndef CONTENT_BROWSER_THING_FOO_H_',
  627. '#define CONTENT_BROWSER_THING_FOO_H_',
  628. 'struct McBoatFace;',
  629. '#endif // CONTENT_BROWSER_THING_FOO_H_',
  630. ]),
  631. MockAffectedFile('content/browser/thing/bar.h', [
  632. '#ifndef CONTENT_BROWSER_THING_BAR_H_',
  633. '#define CONTENT_BROWSER_THING_BAR_H_',
  634. 'namespace content {',
  635. '#endif // CONTENT_BROWSER_THING_BAR_H_',
  636. '} // namespace content',
  637. ]),
  638. MockAffectedFile('content/browser/test1.h', [
  639. 'namespace content {',
  640. '} // namespace content',
  641. ]),
  642. MockAffectedFile('content\\browser\\win.h', [
  643. '#ifndef CONTENT_BROWSER_WIN_H_',
  644. '#define CONTENT_BROWSER_WIN_H_',
  645. 'struct McBoatFace;',
  646. '#endif // CONTENT_BROWSER_WIN_H_',
  647. ]),
  648. MockAffectedFile('content/browser/test2.h', [
  649. '// Comment',
  650. '#ifndef CONTENT_BROWSER_TEST2_H_',
  651. 'struct McBoatFace;',
  652. '#endif // CONTENT_BROWSER_TEST2_H_',
  653. ]),
  654. MockAffectedFile('content/browser/internal.h', [
  655. '// Comment',
  656. '#ifndef CONTENT_BROWSER_INTERNAL_H_',
  657. '#define CONTENT_BROWSER_INTERNAL_H_',
  658. '// Comment',
  659. '#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
  660. '#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
  661. 'namespace internal {',
  662. '} // namespace internal',
  663. '#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
  664. 'namespace content {',
  665. '} // namespace content',
  666. '#endif // CONTENT_BROWSER_THING_BAR_H_',
  667. ]),
  668. MockAffectedFile('content/browser/thing/foo.cc', [
  669. '// This is a non-header.',
  670. ]),
  671. MockAffectedFile('content/browser/disabled.h', [
  672. '// no-include-guard-because-multiply-included',
  673. 'struct McBoatFace;',
  674. ]),
  675. # New files don't allow misspelled include guards.
  676. MockAffectedFile('content/browser/spleling.h', [
  677. '#ifndef CONTENT_BROWSER_SPLLEING_H_',
  678. '#define CONTENT_BROWSER_SPLLEING_H_',
  679. 'struct McBoatFace;',
  680. '#endif // CONTENT_BROWSER_SPLLEING_H_',
  681. ]),
  682. # New files don't allow + in include guards.
  683. MockAffectedFile('content/browser/foo+bar.h', [
  684. '#ifndef CONTENT_BROWSER_FOO+BAR_H_',
  685. '#define CONTENT_BROWSER_FOO+BAR_H_',
  686. 'struct McBoatFace;',
  687. '#endif // CONTENT_BROWSER_FOO+BAR_H_',
  688. ]),
  689. # Old files allow misspelled include guards (for now).
  690. MockAffectedFile('chrome/old.h', [
  691. '// New contents',
  692. '#ifndef CHROME_ODL_H_',
  693. '#define CHROME_ODL_H_',
  694. '#endif // CHROME_ODL_H_',
  695. ], [
  696. '// Old contents',
  697. '#ifndef CHROME_ODL_H_',
  698. '#define CHROME_ODL_H_',
  699. '#endif // CHROME_ODL_H_',
  700. ], action='M'),
  701. # Using a Blink style include guard outside Blink is wrong.
  702. MockAffectedFile('content/NotInBlink.h', [
  703. '#ifndef NotInBlink_h',
  704. '#define NotInBlink_h',
  705. 'struct McBoatFace;',
  706. '#endif // NotInBlink_h',
  707. ]),
  708. # Using a Blink style include guard in Blink is no longer ok.
  709. MockAffectedFile('third_party/blink/InBlink.h', [
  710. '#ifndef InBlink_h',
  711. '#define InBlink_h',
  712. 'struct McBoatFace;',
  713. '#endif // InBlink_h',
  714. ]),
  715. # Using a bad include guard in Blink is not ok.
  716. MockAffectedFile('third_party/blink/AlsoInBlink.h', [
  717. '#ifndef WrongInBlink_h',
  718. '#define WrongInBlink_h',
  719. 'struct McBoatFace;',
  720. '#endif // WrongInBlink_h',
  721. ]),
  722. # Using a bad include guard in Blink is not supposed to be accepted even
  723. # if it's an old file. However the current presubmit has accepted this
  724. # for a while.
  725. MockAffectedFile('third_party/blink/StillInBlink.h', [
  726. '// New contents',
  727. '#ifndef AcceptedInBlink_h',
  728. '#define AcceptedInBlink_h',
  729. 'struct McBoatFace;',
  730. '#endif // AcceptedInBlink_h',
  731. ], [
  732. '// Old contents',
  733. '#ifndef AcceptedInBlink_h',
  734. '#define AcceptedInBlink_h',
  735. 'struct McBoatFace;',
  736. '#endif // AcceptedInBlink_h',
  737. ], action='M'),
  738. # Using a non-Chromium include guard in third_party
  739. # (outside blink) is accepted.
  740. MockAffectedFile('third_party/foo/some_file.h', [
  741. '#ifndef REQUIRED_RPCNDR_H_',
  742. '#define REQUIRED_RPCNDR_H_',
  743. 'struct SomeFileFoo;',
  744. '#endif // REQUIRED_RPCNDR_H_',
  745. ]),
  746. # Not having proper include guard in *_message_generator.h
  747. # for old IPC messages is allowed.
  748. MockAffectedFile('content/common/content_message_generator.h', [
  749. '#undef CONTENT_COMMON_FOO_MESSAGES_H_',
  750. '#include "content/common/foo_messages.h"',
  751. '#ifndef CONTENT_COMMON_FOO_MESSAGES_H_',
  752. '#error "Failed to include content/common/foo_messages.h"',
  753. '#endif',
  754. ]),
  755. ]
  756. msgs = PRESUBMIT.CheckForIncludeGuards(
  757. mock_input_api, mock_output_api)
  758. expected_fail_count = 8
  759. self.assertEqual(expected_fail_count, len(msgs),
  760. 'Expected %d items, found %d: %s'
  761. % (expected_fail_count, len(msgs), msgs))
  762. self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
  763. self.assertEqual(msgs[0].message,
  764. 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
  765. 'not covering the whole file')
  766. self.assertIn('content/browser/test1.h', msgs[1].message)
  767. self.assertIn('Recommended name: CONTENT_BROWSER_TEST1_H_',
  768. msgs[1].message)
  769. self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
  770. self.assertEqual(msgs[2].message,
  771. 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
  772. 'include guard')
  773. self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
  774. self.assertEqual(msgs[3].message,
  775. 'Header using the wrong include guard name '
  776. 'CONTENT_BROWSER_SPLLEING_H_')
  777. self.assertIn('content/browser/foo+bar.h', msgs[4].message)
  778. self.assertIn('Recommended name: CONTENT_BROWSER_FOO_BAR_H_',
  779. msgs[4].message)
  780. self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
  781. self.assertEqual(msgs[5].message,
  782. 'Header using the wrong include guard name '
  783. 'NotInBlink_h')
  784. self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
  785. self.assertEqual(msgs[6].message,
  786. 'Header using the wrong include guard name '
  787. 'InBlink_h')
  788. self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
  789. self.assertEqual(msgs[7].message,
  790. 'Header using the wrong include guard name '
  791. 'WrongInBlink_h')
  792. class AccessibilityRelnotesFieldTest(unittest.TestCase):
  793. def testRelnotesPresent(self):
  794. mock_input_api = MockInputApi()
  795. mock_output_api = MockOutputApi()
  796. mock_input_api.files = [MockAffectedFile('ui/accessibility/foo.bar', [''])]
  797. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  798. mock_input_api.change.footers['AX-Relnotes'] = [
  799. 'Important user facing change']
  800. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  801. mock_input_api, mock_output_api)
  802. self.assertEqual(0, len(msgs),
  803. 'Expected %d messages, found %d: %s'
  804. % (0, len(msgs), msgs))
  805. def testRelnotesMissingFromAccessibilityChange(self):
  806. mock_input_api = MockInputApi()
  807. mock_output_api = MockOutputApi()
  808. mock_input_api.files = [
  809. MockAffectedFile('some/file', ['']),
  810. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  811. MockAffectedFile('some/other/file', [''])
  812. ]
  813. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  814. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  815. mock_input_api, mock_output_api)
  816. self.assertEqual(1, len(msgs),
  817. 'Expected %d messages, found %d: %s'
  818. % (1, len(msgs), msgs))
  819. self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
  820. 'Missing AX-Relnotes field message not found in errors')
  821. # The relnotes footer is not required for changes which do not touch any
  822. # accessibility directories.
  823. def testIgnoresNonAccessibilityCode(self):
  824. mock_input_api = MockInputApi()
  825. mock_output_api = MockOutputApi()
  826. mock_input_api.files = [
  827. MockAffectedFile('some/file', ['']),
  828. MockAffectedFile('some/other/file', [''])
  829. ]
  830. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  831. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  832. mock_input_api, mock_output_api)
  833. self.assertEqual(0, len(msgs),
  834. 'Expected %d messages, found %d: %s'
  835. % (0, len(msgs), msgs))
  836. # Test that our presubmit correctly raises an error for a set of known paths.
  837. def testExpectedPaths(self):
  838. filesToTest = [
  839. "chrome/browser/accessibility/foo.py",
  840. "chrome/browser/ash/arc/accessibility/foo.cc",
  841. "chrome/browser/ui/views/accessibility/foo.h",
  842. "chrome/browser/extensions/api/automation/foo.h",
  843. "chrome/browser/extensions/api/automation_internal/foo.cc",
  844. "chrome/renderer/extensions/accessibility_foo.h",
  845. "chrome/tests/data/accessibility/foo.html",
  846. "content/browser/accessibility/foo.cc",
  847. "content/renderer/accessibility/foo.h",
  848. "content/tests/data/accessibility/foo.cc",
  849. "extensions/renderer/api/automation/foo.h",
  850. "ui/accessibility/foo/bar/baz.cc",
  851. "ui/views/accessibility/foo/bar/baz.h",
  852. ]
  853. for testFile in filesToTest:
  854. mock_input_api = MockInputApi()
  855. mock_output_api = MockOutputApi()
  856. mock_input_api.files = [
  857. MockAffectedFile(testFile, [''])
  858. ]
  859. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  860. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  861. mock_input_api, mock_output_api)
  862. self.assertEqual(1, len(msgs),
  863. 'Expected %d messages, found %d: %s, for file %s'
  864. % (1, len(msgs), msgs, testFile))
  865. self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
  866. ('Missing AX-Relnotes field message not found in errors '
  867. ' for file %s' % (testFile)))
  868. # Test that AX-Relnotes field can appear in the commit description (as long
  869. # as it appears at the beginning of a line).
  870. def testRelnotesInCommitDescription(self):
  871. mock_input_api = MockInputApi()
  872. mock_output_api = MockOutputApi()
  873. mock_input_api.files = [
  874. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  875. ]
  876. mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
  877. 'AX-Relnotes: solves all accessibility issues forever')
  878. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  879. mock_input_api, mock_output_api)
  880. self.assertEqual(0, len(msgs),
  881. 'Expected %d messages, found %d: %s'
  882. % (0, len(msgs), msgs))
  883. # Test that we don't match AX-Relnotes if it appears in the middle of a line.
  884. def testRelnotesMustAppearAtBeginningOfLine(self):
  885. mock_input_api = MockInputApi()
  886. mock_output_api = MockOutputApi()
  887. mock_input_api.files = [
  888. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  889. ]
  890. mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
  891. 'This change has no AX-Relnotes: we should print a warning')
  892. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  893. mock_input_api, mock_output_api)
  894. self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
  895. 'Missing AX-Relnotes field message not found in errors')
  896. # Tests that the AX-Relnotes field can be lowercase and use a '=' in place
  897. # of a ':'.
  898. def testRelnotesLowercaseWithEqualSign(self):
  899. mock_input_api = MockInputApi()
  900. mock_output_api = MockOutputApi()
  901. mock_input_api.files = [
  902. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  903. ]
  904. mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
  905. 'ax-relnotes= this is a valid format for accessibility relnotes')
  906. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  907. mock_input_api, mock_output_api)
  908. self.assertEqual(0, len(msgs),
  909. 'Expected %d messages, found %d: %s'
  910. % (0, len(msgs), msgs))
  911. class AccessibilityEventsTestsAreIncludedForAndroidTest(unittest.TestCase):
  912. # Test that no warning is raised when the Android file is also modified.
  913. def testAndroidChangeIncluded(self):
  914. mock_input_api = MockInputApi()
  915. mock_input_api.files = [
  916. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  917. [''], action='A'),
  918. MockAffectedFile(
  919. 'accessibility/WebContentsAccessibilityEventsTest.java',
  920. [''], action='M')
  921. ]
  922. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  923. mock_input_api, MockOutputApi())
  924. self.assertEqual(0, len(msgs),
  925. 'Expected %d messages, found %d: %s'
  926. % (0, len(msgs), msgs))
  927. # Test that a warning is raised when the Android file is not modified.
  928. def testAndroidChangeMissing(self):
  929. mock_input_api = MockInputApi()
  930. mock_input_api.files = [
  931. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  932. [''], action='A'),
  933. ]
  934. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  935. mock_input_api, MockOutputApi())
  936. self.assertEqual(1, len(msgs),
  937. 'Expected %d messages, found %d: %s'
  938. % (1, len(msgs), msgs))
  939. # Test that Android change is not required when no html file is added/removed.
  940. def testIgnoreNonHtmlFiles(self):
  941. mock_input_api = MockInputApi()
  942. mock_input_api.files = [
  943. MockAffectedFile('content/test/data/accessibility/event/foo.txt',
  944. [''], action='A'),
  945. MockAffectedFile('content/test/data/accessibility/event/foo.cc',
  946. [''], action='A'),
  947. MockAffectedFile('content/test/data/accessibility/event/foo.h',
  948. [''], action='A'),
  949. MockAffectedFile('content/test/data/accessibility/event/foo.py',
  950. [''], action='A')
  951. ]
  952. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  953. mock_input_api, MockOutputApi())
  954. self.assertEqual(0, len(msgs),
  955. 'Expected %d messages, found %d: %s'
  956. % (0, len(msgs), msgs))
  957. # Test that Android change is not required for unrelated html files.
  958. def testIgnoreNonRelatedHtmlFiles(self):
  959. mock_input_api = MockInputApi()
  960. mock_input_api.files = [
  961. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  962. [''], action='A'),
  963. MockAffectedFile('content/test/data/accessibility/html/foo.html',
  964. [''], action='A'),
  965. MockAffectedFile('chrome/tests/data/accessibility/foo.html',
  966. [''], action='A')
  967. ]
  968. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  969. mock_input_api, MockOutputApi())
  970. self.assertEqual(0, len(msgs),
  971. 'Expected %d messages, found %d: %s'
  972. % (0, len(msgs), msgs))
  973. # Test that only modifying an html file will not trigger the warning.
  974. def testIgnoreModifiedFiles(self):
  975. mock_input_api = MockInputApi()
  976. mock_input_api.files = [
  977. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  978. [''], action='M')
  979. ]
  980. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  981. mock_input_api, MockOutputApi())
  982. self.assertEqual(0, len(msgs),
  983. 'Expected %d messages, found %d: %s'
  984. % (0, len(msgs), msgs))
  985. # Test that deleting an html file will trigger the warning.
  986. def testAndroidChangeMissingOnDeletedFile(self):
  987. mock_input_api = MockInputApi()
  988. mock_input_api.files = [
  989. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  990. [], action='D')
  991. ]
  992. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  993. mock_input_api, MockOutputApi())
  994. self.assertEqual(1, len(msgs),
  995. 'Expected %d messages, found %d: %s'
  996. % (1, len(msgs), msgs))
  997. class AccessibilityTreeTestsAreIncludedForAndroidTest(unittest.TestCase):
  998. # Test that no warning is raised when the Android file is also modified.
  999. def testAndroidChangeIncluded(self):
  1000. mock_input_api = MockInputApi()
  1001. mock_input_api.files = [
  1002. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1003. [''], action='A'),
  1004. MockAffectedFile(
  1005. 'accessibility/WebContentsAccessibilityTreeTest.java',
  1006. [''], action='M')
  1007. ]
  1008. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1009. mock_input_api, MockOutputApi())
  1010. self.assertEqual(0, len(msgs),
  1011. 'Expected %d messages, found %d: %s'
  1012. % (0, len(msgs), msgs))
  1013. # Test that no warning is raised when the Android file is also modified.
  1014. def testAndroidChangeIncludedManyFiles(self):
  1015. mock_input_api = MockInputApi()
  1016. mock_input_api.files = [
  1017. MockAffectedFile('content/test/data/accessibility/accname/foo.html',
  1018. [''], action='A'),
  1019. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1020. [''], action='A'),
  1021. MockAffectedFile('content/test/data/accessibility/css/foo.html',
  1022. [''], action='A'),
  1023. MockAffectedFile('content/test/data/accessibility/html/foo.html',
  1024. [''], action='A'),
  1025. MockAffectedFile(
  1026. 'accessibility/WebContentsAccessibilityTreeTest.java',
  1027. [''], action='M')
  1028. ]
  1029. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1030. mock_input_api, MockOutputApi())
  1031. self.assertEqual(0, len(msgs),
  1032. 'Expected %d messages, found %d: %s'
  1033. % (0, len(msgs), msgs))
  1034. # Test that a warning is raised when the Android file is not modified.
  1035. def testAndroidChangeMissing(self):
  1036. mock_input_api = MockInputApi()
  1037. mock_input_api.files = [
  1038. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1039. [''], action='A'),
  1040. ]
  1041. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1042. mock_input_api, MockOutputApi())
  1043. self.assertEqual(1, len(msgs),
  1044. 'Expected %d messages, found %d: %s'
  1045. % (1, len(msgs), msgs))
  1046. # Test that Android change is not required when no html file is added/removed.
  1047. def testIgnoreNonHtmlFiles(self):
  1048. mock_input_api = MockInputApi()
  1049. mock_input_api.files = [
  1050. MockAffectedFile('content/test/data/accessibility/accname/foo.txt',
  1051. [''], action='A'),
  1052. MockAffectedFile('content/test/data/accessibility/aria/foo.cc',
  1053. [''], action='A'),
  1054. MockAffectedFile('content/test/data/accessibility/css/foo.h',
  1055. [''], action='A'),
  1056. MockAffectedFile('content/test/data/accessibility/tree/foo.py',
  1057. [''], action='A')
  1058. ]
  1059. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1060. mock_input_api, MockOutputApi())
  1061. self.assertEqual(0, len(msgs),
  1062. 'Expected %d messages, found %d: %s'
  1063. % (0, len(msgs), msgs))
  1064. # Test that Android change is not required for unrelated html files.
  1065. def testIgnoreNonRelatedHtmlFiles(self):
  1066. mock_input_api = MockInputApi()
  1067. mock_input_api.files = [
  1068. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  1069. [''], action='A'),
  1070. ]
  1071. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1072. mock_input_api, MockOutputApi())
  1073. self.assertEqual(0, len(msgs),
  1074. 'Expected %d messages, found %d: %s'
  1075. % (0, len(msgs), msgs))
  1076. # Test that only modifying an html file will not trigger the warning.
  1077. def testIgnoreModifiedFiles(self):
  1078. mock_input_api = MockInputApi()
  1079. mock_input_api.files = [
  1080. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1081. [''], action='M')
  1082. ]
  1083. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1084. mock_input_api, MockOutputApi())
  1085. self.assertEqual(0, len(msgs),
  1086. 'Expected %d messages, found %d: %s'
  1087. % (0, len(msgs), msgs))
  1088. # Test that deleting an html file will trigger the warning.
  1089. def testAndroidChangeMissingOnDeletedFile(self):
  1090. mock_input_api = MockInputApi()
  1091. mock_input_api.files = [
  1092. MockAffectedFile('content/test/data/accessibility/accname/foo.html',
  1093. [], action='D')
  1094. ]
  1095. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1096. mock_input_api, MockOutputApi())
  1097. self.assertEqual(1, len(msgs),
  1098. 'Expected %d messages, found %d: %s'
  1099. % (1, len(msgs), msgs))
  1100. class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
  1101. def testCheckAndroidTestAnnotationUsage(self):
  1102. mock_input_api = MockInputApi()
  1103. mock_output_api = MockOutputApi()
  1104. mock_input_api.files = [
  1105. MockAffectedFile('LalaLand.java', [
  1106. 'random stuff'
  1107. ]),
  1108. MockAffectedFile('CorrectUsage.java', [
  1109. 'import android.support.test.filters.LargeTest;',
  1110. 'import android.support.test.filters.MediumTest;',
  1111. 'import android.support.test.filters.SmallTest;',
  1112. ]),
  1113. MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
  1114. 'import android.test.suitebuilder.annotation.LargeTest;',
  1115. ]),
  1116. MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
  1117. 'import android.test.suitebuilder.annotation.MediumTest;',
  1118. ]),
  1119. MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
  1120. 'import android.test.suitebuilder.annotation.SmallTest;',
  1121. ]),
  1122. MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
  1123. 'import android.test.suitebuilder.annotation.Smoke;',
  1124. ])
  1125. ]
  1126. msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
  1127. mock_input_api, mock_output_api)
  1128. self.assertEqual(1, len(msgs),
  1129. 'Expected %d items, found %d: %s'
  1130. % (1, len(msgs), msgs))
  1131. self.assertEqual(4, len(msgs[0].items),
  1132. 'Expected %d items, found %d: %s'
  1133. % (4, len(msgs[0].items), msgs[0].items))
  1134. self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
  1135. 'UsedDeprecatedLargeTestAnnotation not found in errors')
  1136. self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
  1137. in msgs[0].items,
  1138. 'UsedDeprecatedMediumTestAnnotation not found in errors')
  1139. self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
  1140. 'UsedDeprecatedSmallTestAnnotation not found in errors')
  1141. self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
  1142. 'UsedDeprecatedSmokeAnnotation not found in errors')
  1143. class CheckNoDownstreamDepsTest(unittest.TestCase):
  1144. def testInvalidDepFromUpstream(self):
  1145. mock_input_api = MockInputApi()
  1146. mock_output_api = MockOutputApi()
  1147. mock_input_api.files = [
  1148. MockAffectedFile('BUILD.gn', [
  1149. 'deps = [',
  1150. ' "//clank/target:test",',
  1151. ']'
  1152. ]),
  1153. MockAffectedFile('chrome/android/BUILD.gn', [
  1154. 'deps = [ "//clank/target:test" ]'
  1155. ]),
  1156. MockAffectedFile('chrome/chrome_java_deps.gni', [
  1157. 'java_deps = [',
  1158. ' "//clank/target:test",',
  1159. ']'
  1160. ]),
  1161. ]
  1162. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
  1163. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1164. mock_input_api, mock_output_api)
  1165. self.assertEqual(1, len(msgs),
  1166. 'Expected %d items, found %d: %s'
  1167. % (1, len(msgs), msgs))
  1168. self.assertEqual(3, len(msgs[0].items),
  1169. 'Expected %d items, found %d: %s'
  1170. % (3, len(msgs[0].items), msgs[0].items))
  1171. self.assertTrue(any('BUILD.gn:2' in item for item in msgs[0].items),
  1172. 'BUILD.gn not found in errors')
  1173. self.assertTrue(
  1174. any('chrome/android/BUILD.gn:1' in item for item in msgs[0].items),
  1175. 'chrome/android/BUILD.gn:1 not found in errors')
  1176. self.assertTrue(
  1177. any('chrome/chrome_java_deps.gni:2' in item for item in msgs[0].items),
  1178. 'chrome/chrome_java_deps.gni:2 not found in errors')
  1179. def testAllowsComments(self):
  1180. mock_input_api = MockInputApi()
  1181. mock_output_api = MockOutputApi()
  1182. mock_input_api.files = [
  1183. MockAffectedFile('BUILD.gn', [
  1184. '# real implementation in //clank/target:test',
  1185. ]),
  1186. ]
  1187. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
  1188. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1189. mock_input_api, mock_output_api)
  1190. self.assertEqual(0, len(msgs),
  1191. 'Expected %d items, found %d: %s'
  1192. % (0, len(msgs), msgs))
  1193. def testOnlyChecksBuildFiles(self):
  1194. mock_input_api = MockInputApi()
  1195. mock_output_api = MockOutputApi()
  1196. mock_input_api.files = [
  1197. MockAffectedFile('README.md', [
  1198. 'DEPS = [ "//clank/target:test" ]'
  1199. ]),
  1200. MockAffectedFile('chrome/android/java/file.java', [
  1201. '//clank/ only function'
  1202. ]),
  1203. ]
  1204. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
  1205. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1206. mock_input_api, mock_output_api)
  1207. self.assertEqual(0, len(msgs),
  1208. 'Expected %d items, found %d: %s'
  1209. % (0, len(msgs), msgs))
  1210. def testValidDepFromDownstream(self):
  1211. mock_input_api = MockInputApi()
  1212. mock_output_api = MockOutputApi()
  1213. mock_input_api.files = [
  1214. MockAffectedFile('BUILD.gn', [
  1215. 'DEPS = [',
  1216. ' "//clank/target:test",',
  1217. ']'
  1218. ]),
  1219. MockAffectedFile('java/BUILD.gn', [
  1220. 'DEPS = [ "//clank/target:test" ]'
  1221. ]),
  1222. ]
  1223. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src/clank'
  1224. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1225. mock_input_api, mock_output_api)
  1226. self.assertEqual(0, len(msgs),
  1227. 'Expected %d items, found %d: %s'
  1228. % (0, len(msgs), msgs))
  1229. class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
  1230. def testCheckAndroidTestJUnitFramework(self):
  1231. mock_input_api = MockInputApi()
  1232. mock_output_api = MockOutputApi()
  1233. mock_input_api.files = [
  1234. MockAffectedFile('LalaLand.java', [
  1235. 'random stuff'
  1236. ]),
  1237. MockAffectedFile('CorrectUsage.java', [
  1238. 'import org.junit.ABC',
  1239. 'import org.junit.XYZ;',
  1240. ]),
  1241. MockAffectedFile('UsedDeprecatedJUnit.java', [
  1242. 'import junit.framework.*;',
  1243. ]),
  1244. MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
  1245. 'import junit.framework.Assert;',
  1246. ]),
  1247. ]
  1248. msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
  1249. mock_input_api, mock_output_api)
  1250. self.assertEqual(1, len(msgs),
  1251. 'Expected %d items, found %d: %s'
  1252. % (1, len(msgs), msgs))
  1253. self.assertEqual(2, len(msgs[0].items),
  1254. 'Expected %d items, found %d: %s'
  1255. % (2, len(msgs[0].items), msgs[0].items))
  1256. self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
  1257. 'UsedDeprecatedJUnit.java not found in errors')
  1258. self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
  1259. in msgs[0].items,
  1260. 'UsedDeprecatedJUnitAssert not found in errors')
  1261. class AndroidJUnitBaseClassTest(unittest.TestCase):
  1262. def testCheckAndroidTestJUnitBaseClass(self):
  1263. mock_input_api = MockInputApi()
  1264. mock_output_api = MockOutputApi()
  1265. mock_input_api.files = [
  1266. MockAffectedFile('LalaLand.java', [
  1267. 'random stuff'
  1268. ]),
  1269. MockAffectedFile('CorrectTest.java', [
  1270. '@RunWith(ABC.class);'
  1271. 'public class CorrectTest {',
  1272. '}',
  1273. ]),
  1274. MockAffectedFile('HistoricallyIncorrectTest.java', [
  1275. 'public class Test extends BaseCaseA {',
  1276. '}',
  1277. ], old_contents=[
  1278. 'public class Test extends BaseCaseB {',
  1279. '}',
  1280. ]),
  1281. MockAffectedFile('CorrectTestWithInterface.java', [
  1282. '@RunWith(ABC.class);'
  1283. 'public class CorrectTest implement Interface {',
  1284. '}',
  1285. ]),
  1286. MockAffectedFile('IncorrectTest.java', [
  1287. 'public class IncorrectTest extends TestCase {',
  1288. '}',
  1289. ]),
  1290. MockAffectedFile('IncorrectWithInterfaceTest.java', [
  1291. 'public class Test implements X extends BaseClass {',
  1292. '}',
  1293. ]),
  1294. MockAffectedFile('IncorrectMultiLineTest.java', [
  1295. 'public class Test implements X, Y, Z',
  1296. ' extends TestBase {',
  1297. '}',
  1298. ]),
  1299. ]
  1300. msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
  1301. mock_input_api, mock_output_api)
  1302. self.assertEqual(1, len(msgs),
  1303. 'Expected %d items, found %d: %s'
  1304. % (1, len(msgs), msgs))
  1305. self.assertEqual(3, len(msgs[0].items),
  1306. 'Expected %d items, found %d: %s'
  1307. % (3, len(msgs[0].items), msgs[0].items))
  1308. self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
  1309. 'IncorrectTest not found in errors')
  1310. self.assertTrue('IncorrectWithInterfaceTest.java:1'
  1311. in msgs[0].items,
  1312. 'IncorrectWithInterfaceTest not found in errors')
  1313. self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
  1314. 'IncorrectMultiLineTest not found in errors')
  1315. class AndroidDebuggableBuildTest(unittest.TestCase):
  1316. def testCheckAndroidDebuggableBuild(self):
  1317. mock_input_api = MockInputApi()
  1318. mock_output_api = MockOutputApi()
  1319. mock_input_api.files = [
  1320. MockAffectedFile('RandomStuff.java', [
  1321. 'random stuff'
  1322. ]),
  1323. MockAffectedFile('CorrectUsage.java', [
  1324. 'import org.chromium.base.BuildInfo;',
  1325. 'some random stuff',
  1326. 'boolean isOsDebuggable = BuildInfo.isDebugAndroid();',
  1327. ]),
  1328. MockAffectedFile('JustCheckUserdebugBuild.java', [
  1329. 'import android.os.Build;',
  1330. 'some random stuff',
  1331. 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")',
  1332. ]),
  1333. MockAffectedFile('JustCheckEngineeringBuild.java', [
  1334. 'import android.os.Build;',
  1335. 'some random stuff',
  1336. 'boolean isOsDebuggable = "eng".equals(Build.TYPE)',
  1337. ]),
  1338. MockAffectedFile('UsedBuildType.java', [
  1339. 'import android.os.Build;',
  1340. 'some random stuff',
  1341. 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")'
  1342. '|| "eng".equals(Build.TYPE)',
  1343. ]),
  1344. MockAffectedFile('UsedExplicitBuildType.java', [
  1345. 'some random stuff',
  1346. 'boolean isOsDebuggable = android.os.Build.TYPE.equals("userdebug")'
  1347. '|| "eng".equals(android.os.Build.TYPE)',
  1348. ]),
  1349. ]
  1350. msgs = PRESUBMIT._CheckAndroidDebuggableBuild(
  1351. mock_input_api, mock_output_api)
  1352. self.assertEqual(1, len(msgs),
  1353. 'Expected %d items, found %d: %s'
  1354. % (1, len(msgs), msgs))
  1355. self.assertEqual(4, len(msgs[0].items),
  1356. 'Expected %d items, found %d: %s'
  1357. % (4, len(msgs[0].items), msgs[0].items))
  1358. self.assertTrue('JustCheckUserdebugBuild.java:3' in msgs[0].items)
  1359. self.assertTrue('JustCheckEngineeringBuild.java:3' in msgs[0].items)
  1360. self.assertTrue('UsedBuildType.java:3' in msgs[0].items)
  1361. self.assertTrue('UsedExplicitBuildType.java:2' in msgs[0].items)
  1362. class LogUsageTest(unittest.TestCase):
  1363. def testCheckAndroidCrLogUsage(self):
  1364. mock_input_api = MockInputApi()
  1365. mock_output_api = MockOutputApi()
  1366. mock_input_api.files = [
  1367. MockAffectedFile('RandomStuff.java', [
  1368. 'random stuff'
  1369. ]),
  1370. MockAffectedFile('HasAndroidLog.java', [
  1371. 'import android.util.Log;',
  1372. 'some random stuff',
  1373. 'Log.d("TAG", "foo");',
  1374. ]),
  1375. MockAffectedFile('HasExplicitUtilLog.java', [
  1376. 'some random stuff',
  1377. 'android.util.Log.d("TAG", "foo");',
  1378. ]),
  1379. MockAffectedFile('IsInBasePackage.java', [
  1380. 'package org.chromium.base;',
  1381. 'private static final String TAG = "cr_Foo";',
  1382. 'Log.d(TAG, "foo");',
  1383. ]),
  1384. MockAffectedFile('IsInBasePackageButImportsLog.java', [
  1385. 'package org.chromium.base;',
  1386. 'import android.util.Log;',
  1387. 'private static final String TAG = "cr_Foo";',
  1388. 'Log.d(TAG, "foo");',
  1389. ]),
  1390. MockAffectedFile('HasBothLog.java', [
  1391. 'import org.chromium.base.Log;',
  1392. 'some random stuff',
  1393. 'private static final String TAG = "cr_Foo";',
  1394. 'Log.d(TAG, "foo");',
  1395. 'android.util.Log.d("TAG", "foo");',
  1396. ]),
  1397. MockAffectedFile('HasCorrectTag.java', [
  1398. 'import org.chromium.base.Log;',
  1399. 'some random stuff',
  1400. 'private static final String TAG = "cr_Foo";',
  1401. 'Log.d(TAG, "foo");',
  1402. ]),
  1403. MockAffectedFile('HasOldTag.java', [
  1404. 'import org.chromium.base.Log;',
  1405. 'some random stuff',
  1406. 'private static final String TAG = "cr.Foo";',
  1407. 'Log.d(TAG, "foo");',
  1408. ]),
  1409. MockAffectedFile('HasDottedTag.java', [
  1410. 'import org.chromium.base.Log;',
  1411. 'some random stuff',
  1412. 'private static final String TAG = "cr_foo.bar";',
  1413. 'Log.d(TAG, "foo");',
  1414. ]),
  1415. MockAffectedFile('HasDottedTagPublic.java', [
  1416. 'import org.chromium.base.Log;',
  1417. 'some random stuff',
  1418. 'public static final String TAG = "cr_foo.bar";',
  1419. 'Log.d(TAG, "foo");',
  1420. ]),
  1421. MockAffectedFile('HasNoTagDecl.java', [
  1422. 'import org.chromium.base.Log;',
  1423. 'some random stuff',
  1424. 'Log.d(TAG, "foo");',
  1425. ]),
  1426. MockAffectedFile('HasIncorrectTagDecl.java', [
  1427. 'import org.chromium.base.Log;',
  1428. 'private static final String TAHG = "cr_Foo";',
  1429. 'some random stuff',
  1430. 'Log.d(TAG, "foo");',
  1431. ]),
  1432. MockAffectedFile('HasInlineTag.java', [
  1433. 'import org.chromium.base.Log;',
  1434. 'some random stuff',
  1435. 'private static final String TAG = "cr_Foo";',
  1436. 'Log.d("TAG", "foo");',
  1437. ]),
  1438. MockAffectedFile('HasInlineTagWithSpace.java', [
  1439. 'import org.chromium.base.Log;',
  1440. 'some random stuff',
  1441. 'private static final String TAG = "cr_Foo";',
  1442. 'Log.d("log message", "foo");',
  1443. ]),
  1444. MockAffectedFile('HasUnprefixedTag.java', [
  1445. 'import org.chromium.base.Log;',
  1446. 'some random stuff',
  1447. 'private static final String TAG = "rubbish";',
  1448. 'Log.d(TAG, "foo");',
  1449. ]),
  1450. MockAffectedFile('HasTooLongTag.java', [
  1451. 'import org.chromium.base.Log;',
  1452. 'some random stuff',
  1453. 'private static final String TAG = "21_characters_long___";',
  1454. 'Log.d(TAG, "foo");',
  1455. ]),
  1456. MockAffectedFile('HasTooLongTagWithNoLogCallsInDiff.java', [
  1457. 'import org.chromium.base.Log;',
  1458. 'some random stuff',
  1459. 'private static final String TAG = "21_characters_long___";',
  1460. ]),
  1461. ]
  1462. msgs = PRESUBMIT._CheckAndroidCrLogUsage(
  1463. mock_input_api, mock_output_api)
  1464. self.assertEqual(5, len(msgs),
  1465. 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
  1466. # Declaration format
  1467. nb = len(msgs[0].items)
  1468. self.assertEqual(2, nb,
  1469. 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
  1470. self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
  1471. self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
  1472. # Tag length
  1473. nb = len(msgs[1].items)
  1474. self.assertEqual(2, nb,
  1475. 'Expected %d items, found %d: %s' % (2, nb, msgs[1].items))
  1476. self.assertTrue('HasTooLongTag.java' in msgs[1].items)
  1477. self.assertTrue('HasTooLongTagWithNoLogCallsInDiff.java' in msgs[1].items)
  1478. # Tag must be a variable named TAG
  1479. nb = len(msgs[2].items)
  1480. self.assertEqual(3, nb,
  1481. 'Expected %d items, found %d: %s' % (3, nb, msgs[2].items))
  1482. self.assertTrue('HasBothLog.java:5' in msgs[2].items)
  1483. self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
  1484. self.assertTrue('HasInlineTagWithSpace.java:4' in msgs[2].items)
  1485. # Util Log usage
  1486. nb = len(msgs[3].items)
  1487. self.assertEqual(3, nb,
  1488. 'Expected %d items, found %d: %s' % (3, nb, msgs[3].items))
  1489. self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
  1490. self.assertTrue('HasExplicitUtilLog.java:2' in msgs[3].items)
  1491. self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
  1492. # Tag must not contain
  1493. nb = len(msgs[4].items)
  1494. self.assertEqual(3, nb,
  1495. 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
  1496. self.assertTrue('HasDottedTag.java' in msgs[4].items)
  1497. self.assertTrue('HasDottedTagPublic.java' in msgs[4].items)
  1498. self.assertTrue('HasOldTag.java' in msgs[4].items)
  1499. class GoogleAnswerUrlFormatTest(unittest.TestCase):
  1500. def testCatchAnswerUrlId(self):
  1501. input_api = MockInputApi()
  1502. input_api.files = [
  1503. MockFile('somewhere/file.cc',
  1504. ['char* host = '
  1505. ' "https://support.google.com/chrome/answer/123456";']),
  1506. MockFile('somewhere_else/file.cc',
  1507. ['char* host = '
  1508. ' "https://support.google.com/chrome/a/answer/123456";']),
  1509. ]
  1510. warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
  1511. input_api, MockOutputApi())
  1512. self.assertEqual(1, len(warnings))
  1513. self.assertEqual(2, len(warnings[0].items))
  1514. def testAllowAnswerUrlParam(self):
  1515. input_api = MockInputApi()
  1516. input_api.files = [
  1517. MockFile('somewhere/file.cc',
  1518. ['char* host = '
  1519. ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
  1520. ]
  1521. warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
  1522. input_api, MockOutputApi())
  1523. self.assertEqual(0, len(warnings))
  1524. class HardcodedGoogleHostsTest(unittest.TestCase):
  1525. def testWarnOnAssignedLiterals(self):
  1526. input_api = MockInputApi()
  1527. input_api.files = [
  1528. MockFile('content/file.cc',
  1529. ['char* host = "https://www.google.com";']),
  1530. MockFile('content/file.cc',
  1531. ['char* host = "https://www.googleapis.com";']),
  1532. MockFile('content/file.cc',
  1533. ['char* host = "https://clients1.google.com";']),
  1534. ]
  1535. warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
  1536. input_api, MockOutputApi())
  1537. self.assertEqual(1, len(warnings))
  1538. self.assertEqual(3, len(warnings[0].items))
  1539. def testAllowInComment(self):
  1540. input_api = MockInputApi()
  1541. input_api.files = [
  1542. MockFile('content/file.cc',
  1543. ['char* host = "https://www.aol.com"; // google.com'])
  1544. ]
  1545. warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
  1546. input_api, MockOutputApi())
  1547. self.assertEqual(0, len(warnings))
  1548. class ChromeOsSyncedPrefRegistrationTest(unittest.TestCase):
  1549. def testWarnsOnChromeOsDirectories(self):
  1550. files = [
  1551. MockFile('ash/file.cc',
  1552. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1553. MockFile('chrome/browser/chromeos/file.cc',
  1554. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1555. MockFile('chromeos/file.cc',
  1556. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1557. MockFile('components/arc/file.cc',
  1558. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1559. MockFile('components/exo/file.cc',
  1560. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1561. ]
  1562. input_api = MockInputApi()
  1563. for file in files:
  1564. input_api.files = [file]
  1565. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1566. input_api, MockOutputApi())
  1567. self.assertEqual(1, len(warnings))
  1568. def testDoesNotWarnOnSyncOsPref(self):
  1569. input_api = MockInputApi()
  1570. input_api.files = [
  1571. MockFile('chromeos/file.cc',
  1572. ['PrefRegistrySyncable::SYNCABLE_OS_PREF']),
  1573. ]
  1574. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1575. input_api, MockOutputApi())
  1576. self.assertEqual(0, len(warnings))
  1577. def testDoesNotWarnOnOtherDirectories(self):
  1578. input_api = MockInputApi()
  1579. input_api.files = [
  1580. MockFile('chrome/browser/ui/file.cc',
  1581. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1582. MockFile('components/sync/file.cc',
  1583. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1584. MockFile('content/browser/file.cc',
  1585. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1586. MockFile('a/notchromeos/file.cc',
  1587. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1588. ]
  1589. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1590. input_api, MockOutputApi())
  1591. self.assertEqual(0, len(warnings))
  1592. def testSeparateWarningForPriorityPrefs(self):
  1593. input_api = MockInputApi()
  1594. input_api.files = [
  1595. MockFile('chromeos/file.cc',
  1596. ['PrefRegistrySyncable::SYNCABLE_PREF',
  1597. 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF']),
  1598. ]
  1599. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1600. input_api, MockOutputApi())
  1601. self.assertEqual(2, len(warnings))
  1602. class ForwardDeclarationTest(unittest.TestCase):
  1603. def testCheckHeadersOnlyOutsideThirdParty(self):
  1604. mock_input_api = MockInputApi()
  1605. mock_input_api.files = [
  1606. MockAffectedFile('somewhere/file.cc', [
  1607. 'class DummyClass;'
  1608. ]),
  1609. MockAffectedFile('third_party/header.h', [
  1610. 'class DummyClass;'
  1611. ])
  1612. ]
  1613. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1614. MockOutputApi())
  1615. self.assertEqual(0, len(warnings))
  1616. def testNoNestedDeclaration(self):
  1617. mock_input_api = MockInputApi()
  1618. mock_input_api.files = [
  1619. MockAffectedFile('somewhere/header.h', [
  1620. 'class SomeClass {',
  1621. ' protected:',
  1622. ' class NotAMatch;',
  1623. '};'
  1624. ])
  1625. ]
  1626. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1627. MockOutputApi())
  1628. self.assertEqual(0, len(warnings))
  1629. def testSubStrings(self):
  1630. mock_input_api = MockInputApi()
  1631. mock_input_api.files = [
  1632. MockAffectedFile('somewhere/header.h', [
  1633. 'class NotUsefulClass;',
  1634. 'struct SomeStruct;',
  1635. 'UsefulClass *p1;',
  1636. 'SomeStructPtr *p2;'
  1637. ])
  1638. ]
  1639. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1640. MockOutputApi())
  1641. self.assertEqual(2, len(warnings))
  1642. def testUselessForwardDeclaration(self):
  1643. mock_input_api = MockInputApi()
  1644. mock_input_api.files = [
  1645. MockAffectedFile('somewhere/header.h', [
  1646. 'class DummyClass;',
  1647. 'struct DummyStruct;',
  1648. 'class UsefulClass;',
  1649. 'std::unique_ptr<UsefulClass> p;'
  1650. ])
  1651. ]
  1652. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1653. MockOutputApi())
  1654. self.assertEqual(2, len(warnings))
  1655. def testBlinkHeaders(self):
  1656. mock_input_api = MockInputApi()
  1657. mock_input_api.files = [
  1658. MockAffectedFile('third_party/blink/header.h', [
  1659. 'class DummyClass;',
  1660. 'struct DummyStruct;',
  1661. ]),
  1662. MockAffectedFile('third_party\\blink\\header.h', [
  1663. 'class DummyClass;',
  1664. 'struct DummyStruct;',
  1665. ])
  1666. ]
  1667. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1668. MockOutputApi())
  1669. self.assertEqual(4, len(warnings))
  1670. class RelativeIncludesTest(unittest.TestCase):
  1671. def testThirdPartyNotWebKitIgnored(self):
  1672. mock_input_api = MockInputApi()
  1673. mock_input_api.files = [
  1674. MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
  1675. MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
  1676. ]
  1677. mock_output_api = MockOutputApi()
  1678. errors = PRESUBMIT.CheckForRelativeIncludes(
  1679. mock_input_api, mock_output_api)
  1680. self.assertEqual(0, len(errors))
  1681. def testNonCppFileIgnored(self):
  1682. mock_input_api = MockInputApi()
  1683. mock_input_api.files = [
  1684. MockAffectedFile('test.py', '#include "../header.h"'),
  1685. ]
  1686. mock_output_api = MockOutputApi()
  1687. errors = PRESUBMIT.CheckForRelativeIncludes(
  1688. mock_input_api, mock_output_api)
  1689. self.assertEqual(0, len(errors))
  1690. def testInnocuousChangesAllowed(self):
  1691. mock_input_api = MockInputApi()
  1692. mock_input_api.files = [
  1693. MockAffectedFile('test.cpp', '#include "header.h"'),
  1694. MockAffectedFile('test2.cpp', '../'),
  1695. ]
  1696. mock_output_api = MockOutputApi()
  1697. errors = PRESUBMIT.CheckForRelativeIncludes(
  1698. mock_input_api, mock_output_api)
  1699. self.assertEqual(0, len(errors))
  1700. def testRelativeIncludeNonWebKitProducesError(self):
  1701. mock_input_api = MockInputApi()
  1702. mock_input_api.files = [
  1703. MockAffectedFile('test.cpp', ['#include "../header.h"']),
  1704. ]
  1705. mock_output_api = MockOutputApi()
  1706. errors = PRESUBMIT.CheckForRelativeIncludes(
  1707. mock_input_api, mock_output_api)
  1708. self.assertEqual(1, len(errors))
  1709. def testRelativeIncludeWebKitProducesError(self):
  1710. mock_input_api = MockInputApi()
  1711. mock_input_api.files = [
  1712. MockAffectedFile('third_party/blink/test.cpp',
  1713. ['#include "../header.h']),
  1714. ]
  1715. mock_output_api = MockOutputApi()
  1716. errors = PRESUBMIT.CheckForRelativeIncludes(
  1717. mock_input_api, mock_output_api)
  1718. self.assertEqual(1, len(errors))
  1719. class CCIncludeTest(unittest.TestCase):
  1720. def testThirdPartyNotBlinkIgnored(self):
  1721. mock_input_api = MockInputApi()
  1722. mock_input_api.files = [
  1723. MockAffectedFile('third_party/test.cpp', '#include "file.cc"'),
  1724. ]
  1725. mock_output_api = MockOutputApi()
  1726. errors = PRESUBMIT.CheckForCcIncludes(
  1727. mock_input_api, mock_output_api)
  1728. self.assertEqual(0, len(errors))
  1729. def testPythonFileIgnored(self):
  1730. mock_input_api = MockInputApi()
  1731. mock_input_api.files = [
  1732. MockAffectedFile('test.py', '#include "file.cc"'),
  1733. ]
  1734. mock_output_api = MockOutputApi()
  1735. errors = PRESUBMIT.CheckForCcIncludes(
  1736. mock_input_api, mock_output_api)
  1737. self.assertEqual(0, len(errors))
  1738. def testIncFilesAccepted(self):
  1739. mock_input_api = MockInputApi()
  1740. mock_input_api.files = [
  1741. MockAffectedFile('test.py', '#include "file.inc"'),
  1742. ]
  1743. mock_output_api = MockOutputApi()
  1744. errors = PRESUBMIT.CheckForCcIncludes(
  1745. mock_input_api, mock_output_api)
  1746. self.assertEqual(0, len(errors))
  1747. def testInnocuousChangesAllowed(self):
  1748. mock_input_api = MockInputApi()
  1749. mock_input_api.files = [
  1750. MockAffectedFile('test.cpp', '#include "header.h"'),
  1751. MockAffectedFile('test2.cpp', 'Something "file.cc"'),
  1752. ]
  1753. mock_output_api = MockOutputApi()
  1754. errors = PRESUBMIT.CheckForCcIncludes(
  1755. mock_input_api, mock_output_api)
  1756. self.assertEqual(0, len(errors))
  1757. def testCcIncludeNonBlinkProducesError(self):
  1758. mock_input_api = MockInputApi()
  1759. mock_input_api.files = [
  1760. MockAffectedFile('test.cpp', ['#include "file.cc"']),
  1761. ]
  1762. mock_output_api = MockOutputApi()
  1763. errors = PRESUBMIT.CheckForCcIncludes(
  1764. mock_input_api, mock_output_api)
  1765. self.assertEqual(1, len(errors))
  1766. def testCppIncludeBlinkProducesError(self):
  1767. mock_input_api = MockInputApi()
  1768. mock_input_api.files = [
  1769. MockAffectedFile('third_party/blink/test.cpp',
  1770. ['#include "foo/file.cpp"']),
  1771. ]
  1772. mock_output_api = MockOutputApi()
  1773. errors = PRESUBMIT.CheckForCcIncludes(
  1774. mock_input_api, mock_output_api)
  1775. self.assertEqual(1, len(errors))
  1776. class GnGlobForwardTest(unittest.TestCase):
  1777. def testAddBareGlobs(self):
  1778. mock_input_api = MockInputApi()
  1779. mock_input_api.files = [
  1780. MockAffectedFile('base/stuff.gni', [
  1781. 'forward_variables_from(invoker, "*")']),
  1782. MockAffectedFile('base/BUILD.gn', [
  1783. 'forward_variables_from(invoker, "*")']),
  1784. ]
  1785. warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api, MockOutputApi())
  1786. self.assertEqual(1, len(warnings))
  1787. msg = '\n'.join(warnings[0].items)
  1788. self.assertIn('base/stuff.gni', msg)
  1789. # Should not check .gn files. Local templates don't need to care about
  1790. # visibility / testonly.
  1791. self.assertNotIn('base/BUILD.gn', msg)
  1792. def testValidUses(self):
  1793. mock_input_api = MockInputApi()
  1794. mock_input_api.files = [
  1795. MockAffectedFile('base/stuff.gni', [
  1796. 'forward_variables_from(invoker, "*", [])']),
  1797. MockAffectedFile('base/stuff2.gni', [
  1798. 'forward_variables_from(invoker, "*", TESTONLY_AND_VISIBILITY)']),
  1799. MockAffectedFile('base/stuff3.gni', [
  1800. 'forward_variables_from(invoker, [ "testonly" ])']),
  1801. ]
  1802. warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api, MockOutputApi())
  1803. self.assertEqual([], warnings)
  1804. class NewHeaderWithoutGnChangeTest(unittest.TestCase):
  1805. def testAddHeaderWithoutGn(self):
  1806. mock_input_api = MockInputApi()
  1807. mock_input_api.files = [
  1808. MockAffectedFile('base/stuff.h', ''),
  1809. ]
  1810. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1811. mock_input_api, MockOutputApi())
  1812. self.assertEqual(1, len(warnings))
  1813. self.assertTrue('base/stuff.h' in warnings[0].items)
  1814. def testModifyHeader(self):
  1815. mock_input_api = MockInputApi()
  1816. mock_input_api.files = [
  1817. MockAffectedFile('base/stuff.h', '', action='M'),
  1818. ]
  1819. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1820. mock_input_api, MockOutputApi())
  1821. self.assertEqual(0, len(warnings))
  1822. def testDeleteHeader(self):
  1823. mock_input_api = MockInputApi()
  1824. mock_input_api.files = [
  1825. MockAffectedFile('base/stuff.h', '', action='D'),
  1826. ]
  1827. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1828. mock_input_api, MockOutputApi())
  1829. self.assertEqual(0, len(warnings))
  1830. def testAddHeaderWithGn(self):
  1831. mock_input_api = MockInputApi()
  1832. mock_input_api.files = [
  1833. MockAffectedFile('base/stuff.h', ''),
  1834. MockAffectedFile('base/BUILD.gn', 'stuff.h'),
  1835. ]
  1836. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1837. mock_input_api, MockOutputApi())
  1838. self.assertEqual(0, len(warnings))
  1839. def testAddHeaderWithGni(self):
  1840. mock_input_api = MockInputApi()
  1841. mock_input_api.files = [
  1842. MockAffectedFile('base/stuff.h', ''),
  1843. MockAffectedFile('base/files.gni', 'stuff.h'),
  1844. ]
  1845. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1846. mock_input_api, MockOutputApi())
  1847. self.assertEqual(0, len(warnings))
  1848. def testAddHeaderWithOther(self):
  1849. mock_input_api = MockInputApi()
  1850. mock_input_api.files = [
  1851. MockAffectedFile('base/stuff.h', ''),
  1852. MockAffectedFile('base/stuff.cc', 'stuff.h'),
  1853. ]
  1854. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1855. mock_input_api, MockOutputApi())
  1856. self.assertEqual(1, len(warnings))
  1857. def testAddHeaderWithWrongGn(self):
  1858. mock_input_api = MockInputApi()
  1859. mock_input_api.files = [
  1860. MockAffectedFile('base/stuff.h', ''),
  1861. MockAffectedFile('base/BUILD.gn', 'stuff_h'),
  1862. ]
  1863. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1864. mock_input_api, MockOutputApi())
  1865. self.assertEqual(1, len(warnings))
  1866. def testAddHeadersWithGn(self):
  1867. mock_input_api = MockInputApi()
  1868. mock_input_api.files = [
  1869. MockAffectedFile('base/stuff.h', ''),
  1870. MockAffectedFile('base/another.h', ''),
  1871. MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
  1872. ]
  1873. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1874. mock_input_api, MockOutputApi())
  1875. self.assertEqual(0, len(warnings))
  1876. def testAddHeadersWithWrongGn(self):
  1877. mock_input_api = MockInputApi()
  1878. mock_input_api.files = [
  1879. MockAffectedFile('base/stuff.h', ''),
  1880. MockAffectedFile('base/another.h', ''),
  1881. MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
  1882. ]
  1883. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1884. mock_input_api, MockOutputApi())
  1885. self.assertEqual(1, len(warnings))
  1886. self.assertFalse('base/stuff.h' in warnings[0].items)
  1887. self.assertTrue('base/another.h' in warnings[0].items)
  1888. def testAddHeadersWithWrongGn2(self):
  1889. mock_input_api = MockInputApi()
  1890. mock_input_api.files = [
  1891. MockAffectedFile('base/stuff.h', ''),
  1892. MockAffectedFile('base/another.h', ''),
  1893. MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
  1894. ]
  1895. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1896. mock_input_api, MockOutputApi())
  1897. self.assertEqual(1, len(warnings))
  1898. self.assertTrue('base/stuff.h' in warnings[0].items)
  1899. self.assertTrue('base/another.h' in warnings[0].items)
  1900. class CorrectProductNameInMessagesTest(unittest.TestCase):
  1901. def testProductNameInDesc(self):
  1902. mock_input_api = MockInputApi()
  1903. mock_input_api.files = [
  1904. MockAffectedFile('chrome/app/google_chrome_strings.grd', [
  1905. '<message name="Foo" desc="Welcome to Chrome">',
  1906. ' Welcome to Chrome!',
  1907. '</message>',
  1908. ]),
  1909. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1910. '<message name="Bar" desc="Welcome to Chrome">',
  1911. ' Welcome to Chromium!',
  1912. '</message>',
  1913. ]),
  1914. ]
  1915. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1916. mock_input_api, MockOutputApi())
  1917. self.assertEqual(0, len(warnings))
  1918. def testChromeInChromium(self):
  1919. mock_input_api = MockInputApi()
  1920. mock_input_api.files = [
  1921. MockAffectedFile('chrome/app/google_chrome_strings.grd', [
  1922. '<message name="Foo" desc="Welcome to Chrome">',
  1923. ' Welcome to Chrome!',
  1924. '</message>',
  1925. ]),
  1926. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1927. '<message name="Bar" desc="Welcome to Chrome">',
  1928. ' Welcome to Chrome!',
  1929. '</message>',
  1930. ]),
  1931. ]
  1932. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1933. mock_input_api, MockOutputApi())
  1934. self.assertEqual(1, len(warnings))
  1935. self.assertTrue('chrome/app/chromium_strings.grd' in warnings[0].items[0])
  1936. def testChromiumInChrome(self):
  1937. mock_input_api = MockInputApi()
  1938. mock_input_api.files = [
  1939. MockAffectedFile('chrome/app/google_chrome_strings.grd', [
  1940. '<message name="Foo" desc="Welcome to Chrome">',
  1941. ' Welcome to Chromium!',
  1942. '</message>',
  1943. ]),
  1944. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1945. '<message name="Bar" desc="Welcome to Chrome">',
  1946. ' Welcome to Chromium!',
  1947. '</message>',
  1948. ]),
  1949. ]
  1950. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1951. mock_input_api, MockOutputApi())
  1952. self.assertEqual(1, len(warnings))
  1953. self.assertTrue(
  1954. 'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
  1955. def testMultipleInstances(self):
  1956. mock_input_api = MockInputApi()
  1957. mock_input_api.files = [
  1958. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1959. '<message name="Bar" desc="Welcome to Chrome">',
  1960. ' Welcome to Chrome!',
  1961. '</message>',
  1962. '<message name="Baz" desc="A correct message">',
  1963. ' Chromium is the software you are using.',
  1964. '</message>',
  1965. '<message name="Bat" desc="An incorrect message">',
  1966. ' Google Chrome is the software you are using.',
  1967. '</message>',
  1968. ]),
  1969. ]
  1970. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1971. mock_input_api, MockOutputApi())
  1972. self.assertEqual(1, len(warnings))
  1973. self.assertTrue(
  1974. 'chrome/app/chromium_strings.grd:2' in warnings[0].items[0])
  1975. self.assertTrue(
  1976. 'chrome/app/chromium_strings.grd:8' in warnings[0].items[1])
  1977. def testMultipleWarnings(self):
  1978. mock_input_api = MockInputApi()
  1979. mock_input_api.files = [
  1980. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1981. '<message name="Bar" desc="Welcome to Chrome">',
  1982. ' Welcome to Chrome!',
  1983. '</message>',
  1984. '<message name="Baz" desc="A correct message">',
  1985. ' Chromium is the software you are using.',
  1986. '</message>',
  1987. '<message name="Bat" desc="An incorrect message">',
  1988. ' Google Chrome is the software you are using.',
  1989. '</message>',
  1990. ]),
  1991. MockAffectedFile('components/components_google_chrome_strings.grd', [
  1992. '<message name="Bar" desc="Welcome to Chrome">',
  1993. ' Welcome to Chrome!',
  1994. '</message>',
  1995. '<message name="Baz" desc="A correct message">',
  1996. ' Chromium is the software you are using.',
  1997. '</message>',
  1998. '<message name="Bat" desc="An incorrect message">',
  1999. ' Google Chrome is the software you are using.',
  2000. '</message>',
  2001. ]),
  2002. ]
  2003. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  2004. mock_input_api, MockOutputApi())
  2005. self.assertEqual(2, len(warnings))
  2006. self.assertTrue(
  2007. 'components/components_google_chrome_strings.grd:5'
  2008. in warnings[0].items[0])
  2009. self.assertTrue(
  2010. 'chrome/app/chromium_strings.grd:2' in warnings[1].items[0])
  2011. self.assertTrue(
  2012. 'chrome/app/chromium_strings.grd:8' in warnings[1].items[1])
  2013. class _SecurityOwnersTestCase(unittest.TestCase):
  2014. def _createMockInputApi(self):
  2015. mock_input_api = MockInputApi()
  2016. def FakeRepositoryRoot():
  2017. return mock_input_api.os_path.join('chromium', 'src')
  2018. mock_input_api.change.RepositoryRoot = FakeRepositoryRoot
  2019. self._injectFakeOwnersClient(
  2020. mock_input_api,
  2021. ['apple@chromium.org', 'orange@chromium.org'])
  2022. return mock_input_api
  2023. def _setupFakeChange(self, input_api):
  2024. class FakeGerrit(object):
  2025. def IsOwnersOverrideApproved(self, issue):
  2026. return False
  2027. input_api.change.issue = 123
  2028. input_api.gerrit = FakeGerrit()
  2029. def _injectFakeOwnersClient(self, input_api, owners):
  2030. class FakeOwnersClient(object):
  2031. def ListOwners(self, f):
  2032. return owners
  2033. input_api.owners_client = FakeOwnersClient()
  2034. def _injectFakeChangeOwnerAndReviewers(self, input_api, owner, reviewers):
  2035. def MockOwnerAndReviewers(input_api, email_regexp, approval_needed=False):
  2036. return [owner, reviewers]
  2037. input_api.canned_checks.GetCodereviewOwnerAndReviewers = \
  2038. MockOwnerAndReviewers
  2039. class IpcSecurityOwnerTest(_SecurityOwnersTestCase):
  2040. _test_cases = [
  2041. ('*_messages.cc', 'scary_messages.cc'),
  2042. ('*_messages*.h', 'scary_messages.h'),
  2043. ('*_messages*.h', 'scary_messages_android.h'),
  2044. ('*_param_traits*.*', 'scary_param_traits.h'),
  2045. ('*_param_traits*.*', 'scary_param_traits_win.h'),
  2046. ('*.mojom', 'scary.mojom'),
  2047. ('*_mojom_traits*.*', 'scary_mojom_traits.h'),
  2048. ('*_mojom_traits*.*', 'scary_mojom_traits_mac.h'),
  2049. ('*_type_converter*.*', 'scary_type_converter.h'),
  2050. ('*_type_converter*.*', 'scary_type_converter_nacl.h'),
  2051. ('*.aidl', 'scary.aidl'),
  2052. ]
  2053. def testHasCorrectPerFileRulesAndSecurityReviewer(self):
  2054. mock_input_api = self._createMockInputApi()
  2055. new_owners_file_path = mock_input_api.os_path.join(
  2056. 'services', 'goat', 'public', 'OWNERS')
  2057. new_owners_file = [
  2058. 'per-file *.mojom=set noparent',
  2059. 'per-file *.mojom=file://ipc/SECURITY_OWNERS'
  2060. ]
  2061. def FakeReadFile(filename):
  2062. self.assertEqual(
  2063. mock_input_api.os_path.join('chromium', 'src', new_owners_file_path),
  2064. filename)
  2065. return '\n'.join(new_owners_file)
  2066. mock_input_api.ReadFile = FakeReadFile
  2067. mock_input_api.files = [
  2068. MockAffectedFile(
  2069. new_owners_file_path, new_owners_file),
  2070. MockAffectedFile(
  2071. mock_input_api.os_path.join(
  2072. 'services', 'goat', 'public', 'goat.mojom'),
  2073. ['// Scary contents.'])]
  2074. self._setupFakeChange(mock_input_api)
  2075. self._injectFakeChangeOwnerAndReviewers(
  2076. mock_input_api, 'owner@chromium.org', ['orange@chromium.org'])
  2077. mock_input_api.is_committing = True
  2078. mock_input_api.dry_run = False
  2079. mock_output_api = MockOutputApi()
  2080. results = PRESUBMIT.CheckSecurityOwners(
  2081. mock_input_api, mock_output_api)
  2082. self.assertEqual(0, len(results))
  2083. def testMissingSecurityReviewerAtUpload(self):
  2084. mock_input_api = self._createMockInputApi()
  2085. new_owners_file_path = mock_input_api.os_path.join(
  2086. 'services', 'goat', 'public', 'OWNERS')
  2087. new_owners_file = [
  2088. 'per-file *.mojom=set noparent',
  2089. 'per-file *.mojom=file://ipc/SECURITY_OWNERS'
  2090. ]
  2091. def FakeReadFile(filename):
  2092. self.assertEqual(
  2093. mock_input_api.os_path.join('chromium', 'src', new_owners_file_path),
  2094. filename)
  2095. return '\n'.join(new_owners_file)
  2096. mock_input_api.ReadFile = FakeReadFile
  2097. mock_input_api.files = [
  2098. MockAffectedFile(
  2099. new_owners_file_path, new_owners_file),
  2100. MockAffectedFile(
  2101. mock_input_api.os_path.join(
  2102. 'services', 'goat', 'public', 'goat.mojom'),
  2103. ['// Scary contents.'])]
  2104. self._setupFakeChange(mock_input_api)
  2105. self._injectFakeChangeOwnerAndReviewers(
  2106. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2107. mock_input_api.is_committing = False
  2108. mock_input_api.dry_run = False
  2109. mock_output_api = MockOutputApi()
  2110. results = PRESUBMIT.CheckSecurityOwners(
  2111. mock_input_api, mock_output_api)
  2112. self.assertEqual(1, len(results))
  2113. self.assertEqual('notify', results[0].type)
  2114. self.assertEqual(
  2115. 'Review from an owner in ipc/SECURITY_OWNERS is required for the '
  2116. 'following newly-added files:', results[0].message)
  2117. def testMissingSecurityReviewerAtDryRunCommit(self):
  2118. mock_input_api = self._createMockInputApi()
  2119. new_owners_file_path = mock_input_api.os_path.join(
  2120. 'services', 'goat', 'public', 'OWNERS')
  2121. new_owners_file = [
  2122. 'per-file *.mojom=set noparent',
  2123. 'per-file *.mojom=file://ipc/SECURITY_OWNERS'
  2124. ]
  2125. def FakeReadFile(filename):
  2126. self.assertEqual(
  2127. mock_input_api.os_path.join('chromium', 'src', new_owners_file_path),
  2128. filename)
  2129. return '\n'.join(new_owners_file)
  2130. mock_input_api.ReadFile = FakeReadFile
  2131. mock_input_api.files = [
  2132. MockAffectedFile(
  2133. new_owners_file_path, new_owners_file),
  2134. MockAffectedFile(
  2135. mock_input_api.os_path.join(
  2136. 'services', 'goat', 'public', 'goat.mojom'),
  2137. ['// Scary contents.'])]
  2138. self._setupFakeChange(mock_input_api)
  2139. self._injectFakeChangeOwnerAndReviewers(
  2140. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2141. mock_input_api.is_committing = True
  2142. mock_input_api.dry_run = True
  2143. mock_output_api = MockOutputApi()
  2144. results = PRESUBMIT.CheckSecurityOwners(
  2145. mock_input_api, mock_output_api)
  2146. self.assertEqual(1, len(results))
  2147. self.assertEqual('error', results[0].type)
  2148. self.assertEqual(
  2149. 'Review from an owner in ipc/SECURITY_OWNERS is required for the '
  2150. 'following newly-added files:', results[0].message)
  2151. def testMissingSecurityApprovalAtRealCommit(self):
  2152. mock_input_api = self._createMockInputApi()
  2153. new_owners_file_path = mock_input_api.os_path.join(
  2154. 'services', 'goat', 'public', 'OWNERS')
  2155. new_owners_file = [
  2156. 'per-file *.mojom=set noparent',
  2157. 'per-file *.mojom=file://ipc/SECURITY_OWNERS'
  2158. ]
  2159. def FakeReadFile(filename):
  2160. self.assertEqual(
  2161. mock_input_api.os_path.join('chromium', 'src', new_owners_file_path),
  2162. filename)
  2163. return '\n'.join(new_owners_file)
  2164. mock_input_api.ReadFile = FakeReadFile
  2165. mock_input_api.files = [
  2166. MockAffectedFile(
  2167. new_owners_file_path, new_owners_file),
  2168. MockAffectedFile(
  2169. mock_input_api.os_path.join(
  2170. 'services', 'goat', 'public', 'goat.mojom'),
  2171. ['// Scary contents.'])]
  2172. self._setupFakeChange(mock_input_api)
  2173. self._injectFakeChangeOwnerAndReviewers(
  2174. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2175. mock_input_api.is_committing = True
  2176. mock_input_api.dry_run = False
  2177. mock_output_api = MockOutputApi()
  2178. results = PRESUBMIT.CheckSecurityOwners(
  2179. mock_input_api, mock_output_api)
  2180. self.assertEqual('error', results[0].type)
  2181. self.assertEqual(
  2182. 'Review from an owner in ipc/SECURITY_OWNERS is required for the '
  2183. 'following newly-added files:', results[0].message)
  2184. def testIpcChangeNeedsSecurityOwner(self):
  2185. for is_committing in [True, False]:
  2186. for pattern, filename in self._test_cases:
  2187. with self.subTest(
  2188. line=f'is_committing={is_committing}, filename={filename}'):
  2189. mock_input_api = self._createMockInputApi()
  2190. mock_input_api.files = [
  2191. MockAffectedFile(
  2192. mock_input_api.os_path.join(
  2193. 'services', 'goat', 'public', filename),
  2194. ['// Scary contents.'])]
  2195. self._setupFakeChange(mock_input_api)
  2196. self._injectFakeChangeOwnerAndReviewers(
  2197. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2198. mock_input_api.is_committing = is_committing
  2199. mock_input_api.dry_run = False
  2200. mock_output_api = MockOutputApi()
  2201. results = PRESUBMIT.CheckSecurityOwners(
  2202. mock_input_api, mock_output_api)
  2203. self.assertEqual(1, len(results))
  2204. self.assertEqual('error', results[0].type)
  2205. self.assertTrue(results[0].message.replace('\\', '/').startswith(
  2206. 'Found missing OWNERS lines for security-sensitive files. '
  2207. 'Please add the following lines to services/goat/public/OWNERS:'))
  2208. self.assertEqual(['ipc-security-reviews@chromium.org'],
  2209. mock_output_api.more_cc)
  2210. def testServiceManifestChangeNeedsSecurityOwner(self):
  2211. mock_input_api = self._createMockInputApi()
  2212. mock_input_api.files = [
  2213. MockAffectedFile(
  2214. mock_input_api.os_path.join(
  2215. 'services', 'goat', 'public', 'cpp', 'manifest.cc'),
  2216. [
  2217. '#include "services/goat/public/cpp/manifest.h"',
  2218. 'const service_manager::Manifest& GetManifest() {}',
  2219. ])]
  2220. self._setupFakeChange(mock_input_api)
  2221. self._injectFakeChangeOwnerAndReviewers(
  2222. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2223. mock_output_api = MockOutputApi()
  2224. errors = PRESUBMIT.CheckSecurityOwners(
  2225. mock_input_api, mock_output_api)
  2226. self.assertEqual(1, len(errors))
  2227. self.assertTrue(errors[0].message.replace('\\', '/').startswith(
  2228. 'Found missing OWNERS lines for security-sensitive files. '
  2229. 'Please add the following lines to services/goat/public/cpp/OWNERS:'))
  2230. self.assertEqual(['ipc-security-reviews@chromium.org'], mock_output_api.more_cc)
  2231. def testNonServiceManifestSourceChangesDoNotRequireSecurityOwner(self):
  2232. mock_input_api = self._createMockInputApi()
  2233. self._injectFakeChangeOwnerAndReviewers(
  2234. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2235. mock_input_api.files = [
  2236. MockAffectedFile('some/non/service/thing/foo_manifest.cc',
  2237. [
  2238. 'const char kNoEnforcement[] = "not a manifest!";',
  2239. ])]
  2240. mock_output_api = MockOutputApi()
  2241. errors = PRESUBMIT.CheckSecurityOwners(
  2242. mock_input_api, mock_output_api)
  2243. self.assertEqual([], errors)
  2244. self.assertEqual([], mock_output_api.more_cc)
  2245. class FuchsiaSecurityOwnerTest(_SecurityOwnersTestCase):
  2246. def testFidlChangeNeedsSecurityOwner(self):
  2247. mock_input_api = self._createMockInputApi()
  2248. mock_input_api.files = [
  2249. MockAffectedFile('potentially/scary/ipc.fidl',
  2250. [
  2251. 'library test.fidl'
  2252. ])]
  2253. self._setupFakeChange(mock_input_api)
  2254. self._injectFakeChangeOwnerAndReviewers(
  2255. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2256. mock_output_api = MockOutputApi()
  2257. errors = PRESUBMIT.CheckSecurityOwners(
  2258. mock_input_api, mock_output_api)
  2259. self.assertEqual(1, len(errors))
  2260. self.assertTrue(errors[0].message.replace('\\', '/').startswith(
  2261. 'Found missing OWNERS lines for security-sensitive files. '
  2262. 'Please add the following lines to potentially/scary/OWNERS:'))
  2263. def testComponentManifestV1ChangeNeedsSecurityOwner(self):
  2264. mock_input_api = self._createMockInputApi()
  2265. mock_input_api.files = [
  2266. MockAffectedFile('potentially/scary/v2_manifest.cmx',
  2267. [
  2268. '{ "that is no": "manifest!" }'
  2269. ])]
  2270. self._setupFakeChange(mock_input_api)
  2271. self._injectFakeChangeOwnerAndReviewers(
  2272. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2273. mock_output_api = MockOutputApi()
  2274. errors = PRESUBMIT.CheckSecurityOwners(
  2275. mock_input_api, mock_output_api)
  2276. self.assertEqual(1, len(errors))
  2277. self.assertTrue(errors[0].message.replace('\\', '/').startswith(
  2278. 'Found missing OWNERS lines for security-sensitive files. '
  2279. 'Please add the following lines to potentially/scary/OWNERS:'))
  2280. def testComponentManifestV2NeedsSecurityOwner(self):
  2281. mock_input_api = self._createMockInputApi()
  2282. mock_input_api.files = [
  2283. MockAffectedFile('potentially/scary/v2_manifest.cml',
  2284. [
  2285. '{ "that is no": "manifest!" }'
  2286. ])]
  2287. self._setupFakeChange(mock_input_api)
  2288. self._injectFakeChangeOwnerAndReviewers(
  2289. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2290. mock_output_api = MockOutputApi()
  2291. errors = PRESUBMIT.CheckSecurityOwners(
  2292. mock_input_api, mock_output_api)
  2293. self.assertEqual(1, len(errors))
  2294. self.assertTrue(errors[0].message.replace('\\', '/').startswith(
  2295. 'Found missing OWNERS lines for security-sensitive files. '
  2296. 'Please add the following lines to potentially/scary/OWNERS:'))
  2297. def testThirdPartyTestsDoNotRequireSecurityOwner(self):
  2298. mock_input_api = MockInputApi()
  2299. self._injectFakeChangeOwnerAndReviewers(
  2300. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2301. mock_input_api.files = [
  2302. MockAffectedFile('third_party/crashpad/test/tests.cmx',
  2303. [
  2304. 'const char kNoEnforcement[] = "Security?!? Pah!";',
  2305. ])]
  2306. mock_output_api = MockOutputApi()
  2307. errors = PRESUBMIT.CheckSecurityOwners(
  2308. mock_input_api, mock_output_api)
  2309. self.assertEqual([], errors)
  2310. def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self):
  2311. mock_input_api = MockInputApi()
  2312. self._injectFakeChangeOwnerAndReviewers(
  2313. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2314. mock_input_api.files = [
  2315. MockAffectedFile('some/non/service/thing/fuchsia_fidl_cml_cmx_magic.cc',
  2316. [
  2317. 'const char kNoEnforcement[] = "Security?!? Pah!";',
  2318. ])]
  2319. mock_output_api = MockOutputApi()
  2320. errors = PRESUBMIT.CheckSecurityOwners(
  2321. mock_input_api, mock_output_api)
  2322. self.assertEqual([], errors)
  2323. class SecurityChangeTest(_SecurityOwnersTestCase):
  2324. def testDiffGetServiceSandboxType(self):
  2325. mock_input_api = MockInputApi()
  2326. mock_input_api.files = [
  2327. MockAffectedFile(
  2328. 'services/goat/teleporter_host.cc',
  2329. [
  2330. 'template <>',
  2331. 'inline content::SandboxType',
  2332. 'content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {',
  2333. '#if defined(OS_WIN)',
  2334. ' return SandboxType::kGoaty;',
  2335. '#else',
  2336. ' return SandboxType::kNoSandbox;',
  2337. '#endif // !defined(OS_WIN)',
  2338. '}'
  2339. ]
  2340. ),
  2341. ]
  2342. files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
  2343. mock_input_api)
  2344. self.assertEqual({
  2345. 'services/goat/teleporter_host.cc': set([
  2346. 'content::GetServiceSandboxType<>()'
  2347. ])},
  2348. files_to_functions)
  2349. def testDiffRemovingLine(self):
  2350. mock_input_api = MockInputApi()
  2351. mock_file = MockAffectedFile('services/goat/teleporter_host.cc', '')
  2352. mock_file._scm_diff = """--- old 2020-05-04 14:08:25.000000000 -0400
  2353. +++ new 2020-05-04 14:08:32.000000000 -0400
  2354. @@ -1,5 +1,4 @@
  2355. template <>
  2356. inline content::SandboxType
  2357. -content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {
  2358. #if defined(OS_WIN)
  2359. return SandboxType::kGoaty;
  2360. """
  2361. mock_input_api.files = [mock_file]
  2362. files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
  2363. mock_input_api)
  2364. self.assertEqual({
  2365. 'services/goat/teleporter_host.cc': set([
  2366. 'content::GetServiceSandboxType<>()'
  2367. ])},
  2368. files_to_functions)
  2369. def testChangeOwnersMissing(self):
  2370. mock_input_api = self._createMockInputApi()
  2371. self._setupFakeChange(mock_input_api)
  2372. self._injectFakeChangeOwnerAndReviewers(
  2373. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2374. mock_input_api.is_committing = False
  2375. mock_input_api.files = [
  2376. MockAffectedFile('file.cc', ['GetServiceSandboxType<Goat>(Sandbox)'])
  2377. ]
  2378. mock_output_api = MockOutputApi()
  2379. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2380. self.assertEqual(1, len(result))
  2381. self.assertEqual(result[0].type, 'notify')
  2382. self.assertEqual(result[0].message,
  2383. 'The following files change calls to security-sensitive functions\n' \
  2384. 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
  2385. ' file.cc\n'
  2386. ' content::GetServiceSandboxType<>()\n\n')
  2387. def testChangeOwnersMissingAtCommit(self):
  2388. mock_input_api = self._createMockInputApi()
  2389. self._setupFakeChange(mock_input_api)
  2390. self._injectFakeChangeOwnerAndReviewers(
  2391. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2392. mock_input_api.is_committing = True
  2393. mock_input_api.dry_run = False
  2394. mock_input_api.files = [
  2395. MockAffectedFile('file.cc', ['GetServiceSandboxType<mojom::Goat>()'])
  2396. ]
  2397. mock_output_api = MockOutputApi()
  2398. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2399. self.assertEqual(1, len(result))
  2400. self.assertEqual(result[0].type, 'error')
  2401. self.assertEqual(result[0].message,
  2402. 'The following files change calls to security-sensitive functions\n' \
  2403. 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
  2404. ' file.cc\n'
  2405. ' content::GetServiceSandboxType<>()\n\n')
  2406. def testChangeOwnersPresent(self):
  2407. mock_input_api = self._createMockInputApi()
  2408. self._injectFakeChangeOwnerAndReviewers(
  2409. mock_input_api, 'owner@chromium.org',
  2410. ['apple@chromium.org', 'banana@chromium.org'])
  2411. mock_input_api.files = [
  2412. MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
  2413. ]
  2414. mock_output_api = MockOutputApi()
  2415. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2416. self.assertEqual(0, len(result))
  2417. def testChangeOwnerIsSecurityOwner(self):
  2418. mock_input_api = self._createMockInputApi()
  2419. self._setupFakeChange(mock_input_api)
  2420. self._injectFakeChangeOwnerAndReviewers(
  2421. mock_input_api, 'orange@chromium.org', ['pear@chromium.org'])
  2422. mock_input_api.files = [
  2423. MockAffectedFile('file.cc', ['GetServiceSandboxType<T>(Sandbox)'])
  2424. ]
  2425. mock_output_api = MockOutputApi()
  2426. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2427. self.assertEqual(1, len(result))
  2428. class BannedTypeCheckTest(unittest.TestCase):
  2429. def testBannedCppFunctions(self):
  2430. input_api = MockInputApi()
  2431. input_api.files = [
  2432. MockFile('some/cpp/problematic/file.cc',
  2433. ['using namespace std;']),
  2434. MockFile('third_party/blink/problematic/file.cc',
  2435. ['GetInterfaceProvider()']),
  2436. MockFile('some/cpp/ok/file.cc',
  2437. ['using std::string;']),
  2438. MockFile('some/cpp/problematic/file2.cc',
  2439. ['set_owned_by_client()']),
  2440. MockFile('some/cpp/nocheck/file.cc',
  2441. ['using namespace std; // nocheck']),
  2442. MockFile('some/cpp/comment/file.cc',
  2443. [' // A comment about `using namespace std;`']),
  2444. ]
  2445. results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2446. # warnings are results[0], errors are results[1]
  2447. self.assertEqual(2, len(results))
  2448. self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
  2449. self.assertTrue(
  2450. 'third_party/blink/problematic/file.cc' in results[0].message)
  2451. self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
  2452. self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
  2453. self.assertFalse('some/cpp/nocheck/file.cc' in results[0].message)
  2454. self.assertFalse('some/cpp/nocheck/file.cc' in results[1].message)
  2455. self.assertFalse('some/cpp/comment/file.cc' in results[0].message)
  2456. self.assertFalse('some/cpp/comment/file.cc' in results[1].message)
  2457. def testBannedIosObjcFunctions(self):
  2458. input_api = MockInputApi()
  2459. input_api.files = [
  2460. MockFile('some/ios/file.mm',
  2461. ['TEST(SomeClassTest, SomeInteraction) {',
  2462. '}']),
  2463. MockFile('some/mac/file.mm',
  2464. ['TEST(SomeClassTest, SomeInteraction) {',
  2465. '}']),
  2466. MockFile('another/ios_file.mm',
  2467. ['class SomeTest : public testing::Test {};']),
  2468. MockFile('some/ios/file_egtest.mm',
  2469. ['- (void)testSomething { EXPECT_OCMOCK_VERIFY(aMock); }']),
  2470. MockFile('some/ios/file_unittest.mm',
  2471. ['TEST_F(SomeTest, TestThis) { EXPECT_OCMOCK_VERIFY(aMock); }']),
  2472. ]
  2473. errors = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2474. self.assertEqual(1, len(errors))
  2475. self.assertTrue('some/ios/file.mm' in errors[0].message)
  2476. self.assertTrue('another/ios_file.mm' in errors[0].message)
  2477. self.assertTrue('some/mac/file.mm' not in errors[0].message)
  2478. self.assertTrue('some/ios/file_egtest.mm' in errors[0].message)
  2479. self.assertTrue('some/ios/file_unittest.mm' not in errors[0].message)
  2480. def testBannedMojoFunctions(self):
  2481. input_api = MockInputApi()
  2482. input_api.files = [
  2483. MockFile('some/cpp/problematic/file2.cc',
  2484. ['mojo::ConvertTo<>']),
  2485. MockFile('third_party/blink/ok/file3.cc',
  2486. ['mojo::ConvertTo<>']),
  2487. MockFile('content/renderer/ok/file3.cc',
  2488. ['mojo::ConvertTo<>']),
  2489. ]
  2490. results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2491. # warnings are results[0], errors are results[1]
  2492. self.assertEqual(1, len(results))
  2493. self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
  2494. self.assertTrue('third_party/blink/ok/file3.cc' not in results[0].message)
  2495. self.assertTrue('content/renderer/ok/file3.cc' not in results[0].message)
  2496. def testBannedMojomPatterns(self):
  2497. input_api = MockInputApi()
  2498. input_api.files = [
  2499. MockFile('bad.mojom',
  2500. ['struct Bad {',
  2501. ' handle<shared_buffer> buffer;',
  2502. '};']),
  2503. MockFile('good.mojom',
  2504. ['struct Good {',
  2505. ' mojo_base.mojom.ReadOnlySharedMemoryRegion region1;',
  2506. ' mojo_base.mojom.WritableSharedMemoryRegion region2;',
  2507. ' mojo_base.mojom.UnsafeSharedMemoryRegion region3;',
  2508. '};']),
  2509. ]
  2510. results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2511. # warnings are results[0], errors are results[1]
  2512. self.assertEqual(1, len(results))
  2513. self.assertTrue('bad.mojom' in results[0].message)
  2514. self.assertTrue('good.mojom' not in results[0].message)
  2515. class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
  2516. def testTruePositives(self):
  2517. mock_input_api = MockInputApi()
  2518. mock_input_api.files = [
  2519. MockFile('some/path/foo.cc', ['foo_for_testing();']),
  2520. MockFile('some/path/foo.mm', ['FooForTesting();']),
  2521. MockFile('some/path/foo.cxx', ['FooForTests();']),
  2522. MockFile('some/path/foo.cpp', ['foo_for_test();']),
  2523. ]
  2524. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
  2525. mock_input_api, MockOutputApi())
  2526. self.assertEqual(1, len(results))
  2527. self.assertEqual(4, len(results[0].items))
  2528. self.assertTrue('foo.cc' in results[0].items[0])
  2529. self.assertTrue('foo.mm' in results[0].items[1])
  2530. self.assertTrue('foo.cxx' in results[0].items[2])
  2531. self.assertTrue('foo.cpp' in results[0].items[3])
  2532. def testFalsePositives(self):
  2533. mock_input_api = MockInputApi()
  2534. mock_input_api.files = [
  2535. MockFile('some/path/foo.h', ['foo_for_testing();']),
  2536. MockFile('some/path/foo.mm', ['FooForTesting() {']),
  2537. MockFile('some/path/foo.cc', ['::FooForTests();']),
  2538. MockFile('some/path/foo.cpp', ['// foo_for_test();']),
  2539. ]
  2540. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
  2541. mock_input_api, MockOutputApi())
  2542. self.assertEqual(0, len(results))
  2543. def testAllowedFiles(self):
  2544. mock_input_api = MockInputApi()
  2545. mock_input_api.files = [
  2546. MockFile('path/foo_unittest.cc', ['foo_for_testing();']),
  2547. MockFile('path/bar_unittest_mac.cc', ['foo_for_testing();']),
  2548. MockFile('path/baz_unittests.cc', ['foo_for_testing();']),
  2549. ]
  2550. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
  2551. mock_input_api, MockOutputApi())
  2552. self.assertEqual(0, len(results))
  2553. class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
  2554. def testTruePositives(self):
  2555. mock_input_api = MockInputApi()
  2556. mock_input_api.files = [
  2557. MockFile('dir/java/src/foo.java', ['FooForTesting();']),
  2558. MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
  2559. MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
  2560. MockFile('dir/java/src/mult.java', [
  2561. 'int x = SomethingLongHere()',
  2562. ' * SomethingLongHereForTesting();'
  2563. ])
  2564. ]
  2565. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
  2566. mock_input_api, MockOutputApi())
  2567. self.assertEqual(1, len(results))
  2568. self.assertEqual(4, len(results[0].items))
  2569. self.assertTrue('foo.java' in results[0].items[0])
  2570. self.assertTrue('bar.java' in results[0].items[1])
  2571. self.assertTrue('baz.java' in results[0].items[2])
  2572. self.assertTrue('mult.java' in results[0].items[3])
  2573. def testFalsePositives(self):
  2574. mock_input_api = MockInputApi()
  2575. mock_input_api.files = [
  2576. MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
  2577. MockFile('dir/java/src/foo.java', ['FooForTests() {']),
  2578. MockFile('dir/java/src/bar.java', ['// FooForTest();']),
  2579. MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
  2580. MockFile('dir/java/src/bar3.java', ['@VisibleForTesting']),
  2581. MockFile('dir/java/src/bar4.java', ['@VisibleForTesting()']),
  2582. MockFile('dir/java/src/bar5.java', [
  2583. '@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)'
  2584. ]),
  2585. MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
  2586. MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
  2587. MockFile('dir/junit/src/javadoc.java', [
  2588. '/** Use FooForTest(); to obtain foo in tests.'
  2589. ' */'
  2590. ]),
  2591. MockFile('dir/junit/src/javadoc2.java', [
  2592. '/** ',
  2593. ' * Use FooForTest(); to obtain foo in tests.'
  2594. ' */'
  2595. ]),
  2596. ]
  2597. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
  2598. mock_input_api, MockOutputApi())
  2599. self.assertEqual(0, len(results))
  2600. class NewImagesWarningTest(unittest.TestCase):
  2601. def testTruePositives(self):
  2602. mock_input_api = MockInputApi()
  2603. mock_input_api.files = [
  2604. MockFile('dir/android/res/drawable/foo.png', []),
  2605. MockFile('dir/android/res/drawable-v21/bar.svg', []),
  2606. MockFile('dir/android/res/mipmap-v21-en/baz.webp', []),
  2607. MockFile('dir/android/res_gshoe/drawable-mdpi/foobar.png', []),
  2608. ]
  2609. results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
  2610. self.assertEqual(1, len(results))
  2611. self.assertEqual(4, len(results[0].items))
  2612. self.assertTrue('foo.png' in results[0].items[0].LocalPath())
  2613. self.assertTrue('bar.svg' in results[0].items[1].LocalPath())
  2614. self.assertTrue('baz.webp' in results[0].items[2].LocalPath())
  2615. self.assertTrue('foobar.png' in results[0].items[3].LocalPath())
  2616. def testFalsePositives(self):
  2617. mock_input_api = MockInputApi()
  2618. mock_input_api.files = [
  2619. MockFile('dir/pngs/README.md', []),
  2620. MockFile('java/test/res/drawable/foo.png', []),
  2621. MockFile('third_party/blink/foo.png', []),
  2622. MockFile('dir/third_party/libpng/src/foo.cc', ['foobar']),
  2623. MockFile('dir/resources.webp/.gitignore', ['foo.png']),
  2624. ]
  2625. results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
  2626. self.assertEqual(0, len(results))
  2627. class ProductIconsTest(unittest.TestCase):
  2628. def test(self):
  2629. mock_input_api = MockInputApi()
  2630. mock_input_api.files = [
  2631. MockFile('components/vector_icons/google_jetpack.icon', []),
  2632. MockFile('components/vector_icons/generic_jetpack.icon', []),
  2633. ]
  2634. results = PRESUBMIT.CheckNoProductIconsAddedToPublicRepo(mock_input_api, MockOutputApi())
  2635. self.assertEqual(1, len(results))
  2636. self.assertEqual(1, len(results[0].items))
  2637. self.assertTrue('google_jetpack.icon' in results[0].items[0])
  2638. class CheckUniquePtrTest(unittest.TestCase):
  2639. def testTruePositivesNullptr(self):
  2640. mock_input_api = MockInputApi()
  2641. mock_input_api.files = [
  2642. MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
  2643. MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
  2644. ]
  2645. results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
  2646. self.assertEqual(1, len(results))
  2647. self.assertTrue('nullptr' in results[0].message)
  2648. self.assertEqual(2, len(results[0].items))
  2649. self.assertTrue('baz.cc' in results[0].items[0])
  2650. self.assertTrue('baz-p.cc' in results[0].items[1])
  2651. def testTruePositivesConstructor(self):
  2652. mock_input_api = MockInputApi()
  2653. mock_input_api.files = [
  2654. MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
  2655. MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
  2656. MockFile('dir/mult.cc', [
  2657. 'return',
  2658. ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
  2659. ]),
  2660. MockFile('dir/mult2.cc', [
  2661. 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
  2662. ' std::unique_ptr<T>(foo);'
  2663. ]),
  2664. MockFile('dir/mult3.cc', [
  2665. 'bar = std::unique_ptr<T>(',
  2666. ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
  2667. ]),
  2668. MockFile('dir/multi_arg.cc', [
  2669. 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
  2670. ]
  2671. results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
  2672. self.assertEqual(1, len(results))
  2673. self.assertTrue('std::make_unique' in results[0].message)
  2674. self.assertEqual(6, len(results[0].items))
  2675. self.assertTrue('foo.cc' in results[0].items[0])
  2676. self.assertTrue('bar.mm' in results[0].items[1])
  2677. self.assertTrue('mult.cc' in results[0].items[2])
  2678. self.assertTrue('mult2.cc' in results[0].items[3])
  2679. self.assertTrue('mult3.cc' in results[0].items[4])
  2680. self.assertTrue('multi_arg.cc' in results[0].items[5])
  2681. def testFalsePositives(self):
  2682. mock_input_api = MockInputApi()
  2683. mock_input_api.files = [
  2684. MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
  2685. MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
  2686. MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
  2687. MockFile('dir/baz.cc', [
  2688. 'std::unique_ptr<T> result = std::make_unique<T>();'
  2689. ]),
  2690. MockFile('dir/baz2.cc', [
  2691. 'std::unique_ptr<T> result = std::make_unique<T>('
  2692. ]),
  2693. MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
  2694. MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
  2695. # Two-argument invocation of std::unique_ptr is exempt because there is
  2696. # no equivalent using std::make_unique.
  2697. MockFile('dir/multi_arg.cc', [
  2698. 'auto p = std::unique_ptr<T, D>(new T(), D());']),
  2699. ]
  2700. results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
  2701. self.assertEqual(0, len(results))
  2702. class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
  2703. def testBlocksDirectIncludes(self):
  2704. mock_input_api = MockInputApi()
  2705. mock_input_api.files = [
  2706. MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
  2707. MockFile('dir/bar.h', ['#include <propvarutil.h>']),
  2708. MockFile('dir/baz.h', ['#include <atlbase.h>']),
  2709. MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
  2710. ]
  2711. results = PRESUBMIT.CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2712. self.assertEqual(1, len(results))
  2713. self.assertEqual(4, len(results[0].items))
  2714. self.assertTrue('StrCat' in results[0].message)
  2715. self.assertTrue('foo_win.cc' in results[0].items[0])
  2716. self.assertTrue('bar.h' in results[0].items[1])
  2717. self.assertTrue('baz.h' in results[0].items[2])
  2718. self.assertTrue('jumbo.h' in results[0].items[3])
  2719. def testAllowsToIncludeWrapper(self):
  2720. mock_input_api = MockInputApi()
  2721. mock_input_api.files = [
  2722. MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
  2723. MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
  2724. ]
  2725. results = PRESUBMIT.CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2726. self.assertEqual(0, len(results))
  2727. def testAllowsToCreateWrapper(self):
  2728. mock_input_api = MockInputApi()
  2729. mock_input_api.files = [
  2730. MockFile('base/win/shlwapi.h', [
  2731. '#include <shlwapi.h>',
  2732. '#include "base/win/windows_defines.inc"']),
  2733. ]
  2734. results = PRESUBMIT.CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2735. self.assertEqual(0, len(results))
  2736. def testIgnoresNonImplAndHeaders(self):
  2737. mock_input_api = MockInputApi()
  2738. mock_input_api.files = [
  2739. MockFile('dir/foo_win.txt', ['#include "shlwapi.h"']),
  2740. MockFile('dir/bar.asm', ['#include <propvarutil.h>']),
  2741. ]
  2742. results = PRESUBMIT.CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2743. self.assertEqual(0, len(results))
  2744. class StringTest(unittest.TestCase):
  2745. """Tests ICU syntax check and translation screenshots check."""
  2746. # An empty grd file.
  2747. OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
  2748. <grit latest_public_release="1" current_release="1">
  2749. <release seq="1">
  2750. <messages></messages>
  2751. </release>
  2752. </grit>
  2753. """.splitlines()
  2754. # A grd file with a single message.
  2755. NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
  2756. <grit latest_public_release="1" current_release="1">
  2757. <release seq="1">
  2758. <messages>
  2759. <message name="IDS_TEST1">
  2760. Test string 1
  2761. </message>
  2762. <message name="IDS_TEST_STRING_NON_TRANSLATEABLE1"
  2763. translateable="false">
  2764. Non translateable message 1, should be ignored
  2765. </message>
  2766. <message name="IDS_TEST_STRING_ACCESSIBILITY"
  2767. is_accessibility_with_no_ui="true">
  2768. Accessibility label 1, should be ignored
  2769. </message>
  2770. </messages>
  2771. </release>
  2772. </grit>
  2773. """.splitlines()
  2774. # A grd file with two messages.
  2775. NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
  2776. <grit latest_public_release="1" current_release="1">
  2777. <release seq="1">
  2778. <messages>
  2779. <message name="IDS_TEST1">
  2780. Test string 1
  2781. </message>
  2782. <message name="IDS_TEST2">
  2783. Test string 2
  2784. </message>
  2785. <message name="IDS_TEST_STRING_NON_TRANSLATEABLE2"
  2786. translateable="false">
  2787. Non translateable message 2, should be ignored
  2788. </message>
  2789. </messages>
  2790. </release>
  2791. </grit>
  2792. """.splitlines()
  2793. # A grd file with one ICU syntax message without syntax errors.
  2794. NEW_GRD_CONTENTS_ICU_SYNTAX_OK1 = """<?xml version="1.0" encoding="UTF-8"?>
  2795. <grit latest_public_release="1" current_release="1">
  2796. <release seq="1">
  2797. <messages>
  2798. <message name="IDS_TEST1">
  2799. {NUM, plural,
  2800. =1 {Test text for numeric one}
  2801. other {Test text for plural with {NUM} as number}}
  2802. </message>
  2803. </messages>
  2804. </release>
  2805. </grit>
  2806. """.splitlines()
  2807. # A grd file with one ICU syntax message without syntax errors.
  2808. NEW_GRD_CONTENTS_ICU_SYNTAX_OK2 = """<?xml version="1.0" encoding="UTF-8"?>
  2809. <grit latest_public_release="1" current_release="1">
  2810. <release seq="1">
  2811. <messages>
  2812. <message name="IDS_TEST1">
  2813. {NUM, plural,
  2814. =1 {Different test text for numeric one}
  2815. other {Different test text for plural with {NUM} as number}}
  2816. </message>
  2817. </messages>
  2818. </release>
  2819. </grit>
  2820. """.splitlines()
  2821. # A grd file with one ICU syntax message with syntax errors (misses a comma).
  2822. NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR = """<?xml version="1.0" encoding="UTF-8"?>
  2823. <grit latest_public_release="1" current_release="1">
  2824. <release seq="1">
  2825. <messages>
  2826. <message name="IDS_TEST1">
  2827. {NUM, plural
  2828. =1 {Test text for numeric one}
  2829. other {Test text for plural with {NUM} as number}}
  2830. </message>
  2831. </messages>
  2832. </release>
  2833. </grit>
  2834. """.splitlines()
  2835. OLD_GRDP_CONTENTS = (
  2836. '<?xml version="1.0" encoding="utf-8"?>',
  2837. '<grit-part>',
  2838. '</grit-part>'
  2839. )
  2840. NEW_GRDP_CONTENTS1 = (
  2841. '<?xml version="1.0" encoding="utf-8"?>',
  2842. '<grit-part>',
  2843. '<message name="IDS_PART_TEST1">',
  2844. 'Part string 1',
  2845. '</message>',
  2846. '</grit-part>')
  2847. NEW_GRDP_CONTENTS2 = (
  2848. '<?xml version="1.0" encoding="utf-8"?>',
  2849. '<grit-part>',
  2850. '<message name="IDS_PART_TEST1">',
  2851. 'Part string 1',
  2852. '</message>',
  2853. '<message name="IDS_PART_TEST2">',
  2854. 'Part string 2',
  2855. '</message>',
  2856. '</grit-part>')
  2857. NEW_GRDP_CONTENTS3 = (
  2858. '<?xml version="1.0" encoding="utf-8"?>',
  2859. '<grit-part>',
  2860. '<message name="IDS_PART_TEST1" desc="Description with typo.">',
  2861. 'Part string 1',
  2862. '</message>',
  2863. '</grit-part>')
  2864. NEW_GRDP_CONTENTS4 = (
  2865. '<?xml version="1.0" encoding="utf-8"?>',
  2866. '<grit-part>',
  2867. '<message name="IDS_PART_TEST1" desc="Description with typo fixed.">',
  2868. 'Part string 1',
  2869. '</message>',
  2870. '</grit-part>')
  2871. NEW_GRDP_CONTENTS5 = (
  2872. '<?xml version="1.0" encoding="utf-8"?>',
  2873. '<grit-part>',
  2874. '<message name="IDS_PART_TEST1" meaning="Meaning with typo.">',
  2875. 'Part string 1',
  2876. '</message>',
  2877. '</grit-part>')
  2878. NEW_GRDP_CONTENTS6 = (
  2879. '<?xml version="1.0" encoding="utf-8"?>',
  2880. '<grit-part>',
  2881. '<message name="IDS_PART_TEST1" meaning="Meaning with typo fixed.">',
  2882. 'Part string 1',
  2883. '</message>',
  2884. '</grit-part>')
  2885. # A grdp file with one ICU syntax message without syntax errors.
  2886. NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1 = (
  2887. '<?xml version="1.0" encoding="utf-8"?>',
  2888. '<grit-part>',
  2889. '<message name="IDS_PART_TEST1">',
  2890. '{NUM, plural,',
  2891. '=1 {Test text for numeric one}',
  2892. 'other {Test text for plural with {NUM} as number}}',
  2893. '</message>',
  2894. '</grit-part>')
  2895. # A grdp file with one ICU syntax message without syntax errors.
  2896. NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2 = (
  2897. '<?xml version="1.0" encoding="utf-8"?>',
  2898. '<grit-part>',
  2899. '<message name="IDS_PART_TEST1">',
  2900. '{NUM, plural,',
  2901. '=1 {Different test text for numeric one}',
  2902. 'other {Different test text for plural with {NUM} as number}}',
  2903. '</message>',
  2904. '</grit-part>')
  2905. # A grdp file with one ICU syntax message with syntax errors (superfluent
  2906. # whitespace).
  2907. NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR = (
  2908. '<?xml version="1.0" encoding="utf-8"?>',
  2909. '<grit-part>',
  2910. '<message name="IDS_PART_TEST1">',
  2911. '{NUM, plural,',
  2912. '= 1 {Test text for numeric one}',
  2913. 'other {Test text for plural with {NUM} as number}}',
  2914. '</message>',
  2915. '</grit-part>')
  2916. DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
  2917. 'changelist. Run '
  2918. 'tools/translate/upload_screenshots.py to '
  2919. 'upload them instead:')
  2920. GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
  2921. 'To ensure the best translations, take '
  2922. 'screenshots of the relevant UI '
  2923. '(https://g.co/chrome/translation) and add '
  2924. 'these files to your changelist:')
  2925. REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
  2926. 'files. Remove:')
  2927. ICU_SYNTAX_ERROR_MESSAGE = ('ICU syntax errors were found in the following '
  2928. 'strings (problems or feedback? Contact '
  2929. 'rainhard@chromium.org):')
  2930. def makeInputApi(self, files):
  2931. input_api = MockInputApi()
  2932. input_api.files = files
  2933. # Override os_path.exists because the presubmit uses the actual
  2934. # os.path.exists.
  2935. input_api.CreateMockFileInPath(
  2936. [x.LocalPath() for x in input_api.AffectedFiles(include_deletes=True)])
  2937. return input_api
  2938. """ CL modified and added messages, but didn't add any screenshots."""
  2939. def testNoScreenshots(self):
  2940. # No new strings (file contents same). Should not warn.
  2941. input_api = self.makeInputApi([
  2942. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
  2943. self.NEW_GRD_CONTENTS1, action='M'),
  2944. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS1,
  2945. self.NEW_GRDP_CONTENTS1, action='M')])
  2946. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2947. self.assertEqual(0, len(warnings))
  2948. # Add two new strings. Should have two warnings.
  2949. input_api = self.makeInputApi([
  2950. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
  2951. self.NEW_GRD_CONTENTS1, action='M'),
  2952. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
  2953. self.NEW_GRDP_CONTENTS1, action='M')])
  2954. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2955. self.assertEqual(1, len(warnings))
  2956. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
  2957. self.assertEqual('error', warnings[0].type)
  2958. self.assertEqual([
  2959. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2960. os.path.join('test_grd', 'IDS_TEST2.png.sha1')],
  2961. warnings[0].items)
  2962. # Add four new strings. Should have four warnings.
  2963. input_api = self.makeInputApi([
  2964. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
  2965. self.OLD_GRD_CONTENTS, action='M'),
  2966. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
  2967. self.OLD_GRDP_CONTENTS, action='M')])
  2968. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2969. self.assertEqual(1, len(warnings))
  2970. self.assertEqual('error', warnings[0].type)
  2971. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
  2972. self.assertEqual([
  2973. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2974. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2975. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  2976. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  2977. ], warnings[0].items)
  2978. def testModifiedMessageDescription(self):
  2979. # CL modified a message description for a message that does not yet have a
  2980. # screenshot. Should not warn.
  2981. input_api = self.makeInputApi([
  2982. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
  2983. self.NEW_GRDP_CONTENTS4, action='M')])
  2984. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2985. self.assertEqual(0, len(warnings))
  2986. # CL modified a message description for a message that already has a
  2987. # screenshot. Should not warn.
  2988. input_api = self.makeInputApi([
  2989. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
  2990. self.NEW_GRDP_CONTENTS4, action='M'),
  2991. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2992. 'binary', action='A')])
  2993. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2994. self.assertEqual(0, len(warnings))
  2995. def testModifiedMessageMeaning(self):
  2996. # CL modified a message meaning for a message that does not yet have a
  2997. # screenshot. Should warn.
  2998. input_api = self.makeInputApi([
  2999. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
  3000. self.NEW_GRDP_CONTENTS6, action='M')])
  3001. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3002. self.assertEqual(1, len(warnings))
  3003. # CL modified a message meaning for a message that already has a
  3004. # screenshot. Should not warn.
  3005. input_api = self.makeInputApi([
  3006. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
  3007. self.NEW_GRDP_CONTENTS6, action='M'),
  3008. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3009. 'binary', action='A')])
  3010. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3011. self.assertEqual(0, len(warnings))
  3012. def testPngAddedSha1NotAdded(self):
  3013. # CL added one new message in a grd file and added the png file associated
  3014. # with it, but did not add the corresponding sha1 file. This should warn
  3015. # twice:
  3016. # - Once for the added png file (because we don't want developers to upload
  3017. # actual images)
  3018. # - Once for the missing .sha1 file
  3019. input_api = self.makeInputApi([
  3020. MockAffectedFile(
  3021. 'test.grd',
  3022. self.NEW_GRD_CONTENTS1,
  3023. self.OLD_GRD_CONTENTS,
  3024. action='M'),
  3025. MockAffectedFile(
  3026. os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A')
  3027. ])
  3028. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3029. self.assertEqual(2, len(warnings))
  3030. self.assertEqual('error', warnings[0].type)
  3031. self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
  3032. self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png')],
  3033. warnings[0].items)
  3034. self.assertEqual('error', warnings[1].type)
  3035. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
  3036. self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
  3037. warnings[1].items)
  3038. # CL added two messages (one in grd, one in grdp) and added the png files
  3039. # associated with the messages, but did not add the corresponding sha1
  3040. # files. This should warn twice:
  3041. # - Once for the added png files (because we don't want developers to upload
  3042. # actual images)
  3043. # - Once for the missing .sha1 files
  3044. input_api = self.makeInputApi([
  3045. # Modified files:
  3046. MockAffectedFile(
  3047. 'test.grd',
  3048. self.NEW_GRD_CONTENTS1,
  3049. self.OLD_GRD_CONTENTS,
  3050. action='M'),
  3051. MockAffectedFile(
  3052. 'part.grdp',
  3053. self.NEW_GRDP_CONTENTS1,
  3054. self.OLD_GRDP_CONTENTS,
  3055. action='M'),
  3056. # Added files:
  3057. MockAffectedFile(
  3058. os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A'),
  3059. MockAffectedFile(
  3060. os.path.join('part_grdp', 'IDS_PART_TEST1.png'), 'binary',
  3061. action='A')
  3062. ])
  3063. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3064. self.assertEqual(2, len(warnings))
  3065. self.assertEqual('error', warnings[0].type)
  3066. self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
  3067. self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png'),
  3068. os.path.join('test_grd', 'IDS_TEST1.png')],
  3069. warnings[0].items)
  3070. self.assertEqual('error', warnings[0].type)
  3071. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
  3072. self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3073. os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
  3074. warnings[1].items)
  3075. def testScreenshotsWithSha1(self):
  3076. # CL added four messages (two each in a grd and grdp) and their
  3077. # corresponding .sha1 files. No warnings.
  3078. input_api = self.makeInputApi([
  3079. # Modified files:
  3080. MockAffectedFile(
  3081. 'test.grd',
  3082. self.NEW_GRD_CONTENTS2,
  3083. self.OLD_GRD_CONTENTS,
  3084. action='M'),
  3085. MockAffectedFile(
  3086. 'part.grdp',
  3087. self.NEW_GRDP_CONTENTS2,
  3088. self.OLD_GRDP_CONTENTS,
  3089. action='M'),
  3090. # Added files:
  3091. MockFile(
  3092. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  3093. 'binary',
  3094. action='A'),
  3095. MockFile(
  3096. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  3097. 'binary',
  3098. action='A'),
  3099. MockFile(
  3100. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3101. 'binary',
  3102. action='A'),
  3103. MockFile(
  3104. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  3105. 'binary',
  3106. action='A'),
  3107. ])
  3108. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3109. self.assertEqual([], warnings)
  3110. def testScreenshotsRemovedWithSha1(self):
  3111. # Replace new contents with old contents in grd and grp files, removing
  3112. # IDS_TEST1, IDS_TEST2, IDS_PART_TEST1 and IDS_PART_TEST2.
  3113. # Should warn to remove the sha1 files associated with these strings.
  3114. input_api = self.makeInputApi([
  3115. # Modified files:
  3116. MockAffectedFile(
  3117. 'test.grd',
  3118. self.OLD_GRD_CONTENTS, # new_contents
  3119. self.NEW_GRD_CONTENTS2, # old_contents
  3120. action='M'),
  3121. MockAffectedFile(
  3122. 'part.grdp',
  3123. self.OLD_GRDP_CONTENTS, # new_contents
  3124. self.NEW_GRDP_CONTENTS2, # old_contents
  3125. action='M'),
  3126. # Unmodified files:
  3127. MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
  3128. MockFile(os.path.join('test_grd', 'IDS_TEST2.png.sha1'), 'binary', ''),
  3129. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3130. 'binary', ''),
  3131. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  3132. 'binary', '')
  3133. ])
  3134. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3135. self.assertEqual(1, len(warnings))
  3136. self.assertEqual('error', warnings[0].type)
  3137. self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
  3138. self.assertEqual([
  3139. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3140. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  3141. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  3142. os.path.join('test_grd', 'IDS_TEST2.png.sha1')
  3143. ], warnings[0].items)
  3144. # Same as above, but this time one of the .sha1 files is also removed.
  3145. input_api = self.makeInputApi([
  3146. # Modified files:
  3147. MockAffectedFile(
  3148. 'test.grd',
  3149. self.OLD_GRD_CONTENTS, # new_contents
  3150. self.NEW_GRD_CONTENTS2, # old_contents
  3151. action='M'),
  3152. MockAffectedFile(
  3153. 'part.grdp',
  3154. self.OLD_GRDP_CONTENTS, # new_contents
  3155. self.NEW_GRDP_CONTENTS2, # old_contents
  3156. action='M'),
  3157. # Unmodified files:
  3158. MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
  3159. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3160. 'binary', ''),
  3161. # Deleted files:
  3162. MockAffectedFile(
  3163. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  3164. '',
  3165. 'old_contents',
  3166. action='D'),
  3167. MockAffectedFile(
  3168. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  3169. '',
  3170. 'old_contents',
  3171. action='D')
  3172. ])
  3173. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3174. self.assertEqual(1, len(warnings))
  3175. self.assertEqual('error', warnings[0].type)
  3176. self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
  3177. self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3178. os.path.join('test_grd', 'IDS_TEST1.png.sha1')
  3179. ], warnings[0].items)
  3180. # Remove all sha1 files. There should be no warnings.
  3181. input_api = self.makeInputApi([
  3182. # Modified files:
  3183. MockAffectedFile(
  3184. 'test.grd',
  3185. self.OLD_GRD_CONTENTS,
  3186. self.NEW_GRD_CONTENTS2,
  3187. action='M'),
  3188. MockAffectedFile(
  3189. 'part.grdp',
  3190. self.OLD_GRDP_CONTENTS,
  3191. self.NEW_GRDP_CONTENTS2,
  3192. action='M'),
  3193. # Deleted files:
  3194. MockFile(
  3195. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  3196. 'binary',
  3197. action='D'),
  3198. MockFile(
  3199. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  3200. 'binary',
  3201. action='D'),
  3202. MockFile(
  3203. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  3204. 'binary',
  3205. action='D'),
  3206. MockFile(
  3207. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  3208. 'binary',
  3209. action='D')
  3210. ])
  3211. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3212. self.assertEqual([], warnings)
  3213. def testIcuSyntax(self):
  3214. # Add valid ICU syntax string. Should not raise an error.
  3215. input_api = self.makeInputApi([
  3216. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
  3217. self.NEW_GRD_CONTENTS1, action='M'),
  3218. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
  3219. self.NEW_GRDP_CONTENTS1, action='M')])
  3220. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3221. # We expect no ICU syntax errors.
  3222. icu_errors = [e for e in results
  3223. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3224. self.assertEqual(0, len(icu_errors))
  3225. # Valid changes in ICU syntax. Should not raise an error.
  3226. input_api = self.makeInputApi([
  3227. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
  3228. self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
  3229. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
  3230. self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
  3231. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3232. # We expect no ICU syntax errors.
  3233. icu_errors = [e for e in results
  3234. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3235. self.assertEqual(0, len(icu_errors))
  3236. # Add invalid ICU syntax strings. Should raise two errors.
  3237. input_api = self.makeInputApi([
  3238. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
  3239. self.NEW_GRD_CONTENTS1, action='M'),
  3240. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
  3241. self.NEW_GRD_CONTENTS1, action='M')])
  3242. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3243. # We expect 2 ICU syntax errors.
  3244. icu_errors = [e for e in results
  3245. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3246. self.assertEqual(1, len(icu_errors))
  3247. self.assertEqual([
  3248. 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
  3249. 'ICU syntax.',
  3250. 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
  3251. ], icu_errors[0].items)
  3252. # Change two strings to have ICU syntax errors. Should raise two errors.
  3253. input_api = self.makeInputApi([
  3254. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
  3255. self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
  3256. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
  3257. self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
  3258. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3259. # We expect 2 ICU syntax errors.
  3260. icu_errors = [e for e in results
  3261. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3262. self.assertEqual(1, len(icu_errors))
  3263. self.assertEqual([
  3264. 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
  3265. 'ICU syntax.',
  3266. 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
  3267. ], icu_errors[0].items)
  3268. class TranslationExpectationsTest(unittest.TestCase):
  3269. ERROR_MESSAGE_FORMAT = (
  3270. "Failed to get a list of translatable grd files. "
  3271. "This happens when:\n"
  3272. " - One of the modified grd or grdp files cannot be parsed or\n"
  3273. " - %s is not updated.\n"
  3274. "Stack:\n"
  3275. )
  3276. REPO_ROOT = os.path.join('tools', 'translation', 'testdata')
  3277. # This lists all .grd files under REPO_ROOT.
  3278. EXPECTATIONS = os.path.join(REPO_ROOT,
  3279. "translation_expectations.pyl")
  3280. # This lists all .grd files under REPO_ROOT except unlisted.grd.
  3281. EXPECTATIONS_WITHOUT_UNLISTED_FILE = os.path.join(
  3282. REPO_ROOT, "translation_expectations_without_unlisted_file.pyl")
  3283. # Tests that the presubmit doesn't return when no grd or grdp files are
  3284. # modified.
  3285. def testExpectationsNoModifiedGrd(self):
  3286. input_api = MockInputApi()
  3287. input_api.files = [
  3288. MockAffectedFile('not_used.txt', 'not used', 'not used', action='M')
  3289. ]
  3290. # Fake list of all grd files in the repo. This list is missing all grd/grdps
  3291. # under tools/translation/testdata. This is OK because the presubmit won't
  3292. # run in the first place since there are no modified grd/grps in input_api.
  3293. grd_files = ['doesnt_exist_doesnt_matter.grd']
  3294. warnings = PRESUBMIT.CheckTranslationExpectations(
  3295. input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
  3296. grd_files)
  3297. self.assertEqual(0, len(warnings))
  3298. # Tests that the list of files passed to the presubmit matches the list of
  3299. # files in the expectations.
  3300. def testExpectationsSuccess(self):
  3301. # Mock input file list needs a grd or grdp file in order to run the
  3302. # presubmit. The file itself doesn't matter.
  3303. input_api = MockInputApi()
  3304. input_api.files = [
  3305. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3306. ]
  3307. # List of all grd files in the repo.
  3308. grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
  3309. 'internal.grd']
  3310. warnings = PRESUBMIT.CheckTranslationExpectations(
  3311. input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
  3312. grd_files)
  3313. self.assertEqual(0, len(warnings))
  3314. # Tests that the presubmit warns when a file is listed in expectations, but
  3315. # does not actually exist.
  3316. def testExpectationsMissingFile(self):
  3317. # Mock input file list needs a grd or grdp file in order to run the
  3318. # presubmit.
  3319. input_api = MockInputApi()
  3320. input_api.files = [
  3321. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3322. ]
  3323. # unlisted.grd is listed under tools/translation/testdata but is not
  3324. # included in translation expectations.
  3325. grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
  3326. warnings = PRESUBMIT.CheckTranslationExpectations(
  3327. input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
  3328. grd_files)
  3329. self.assertEqual(1, len(warnings))
  3330. self.assertTrue(warnings[0].message.startswith(
  3331. self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS))
  3332. self.assertTrue(
  3333. ("test.grd is listed in the translation expectations, "
  3334. "but this grd file does not exist")
  3335. in warnings[0].message)
  3336. # Tests that the presubmit warns when a file is not listed in expectations but
  3337. # does actually exist.
  3338. def testExpectationsUnlistedFile(self):
  3339. # Mock input file list needs a grd or grdp file in order to run the
  3340. # presubmit.
  3341. input_api = MockInputApi()
  3342. input_api.files = [
  3343. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3344. ]
  3345. # unlisted.grd is listed under tools/translation/testdata but is not
  3346. # included in translation expectations.
  3347. grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
  3348. 'internal.grd']
  3349. warnings = PRESUBMIT.CheckTranslationExpectations(
  3350. input_api, MockOutputApi(), self.REPO_ROOT,
  3351. self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
  3352. self.assertEqual(1, len(warnings))
  3353. self.assertTrue(warnings[0].message.startswith(
  3354. self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
  3355. self.assertTrue(
  3356. ("unlisted.grd appears to be translatable "
  3357. "(because it contains <file> or <message> elements), "
  3358. "but is not listed in the translation expectations.")
  3359. in warnings[0].message)
  3360. # Tests that the presubmit warns twice:
  3361. # - for a non-existing file listed in expectations
  3362. # - for an existing file not listed in expectations
  3363. def testMultipleWarnings(self):
  3364. # Mock input file list needs a grd or grdp file in order to run the
  3365. # presubmit.
  3366. input_api = MockInputApi()
  3367. input_api.files = [
  3368. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3369. ]
  3370. # unlisted.grd is listed under tools/translation/testdata but is not
  3371. # included in translation expectations.
  3372. # test.grd is not listed under tools/translation/testdata but is included
  3373. # in translation expectations.
  3374. grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
  3375. warnings = PRESUBMIT.CheckTranslationExpectations(
  3376. input_api, MockOutputApi(), self.REPO_ROOT,
  3377. self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
  3378. self.assertEqual(1, len(warnings))
  3379. self.assertTrue(warnings[0].message.startswith(
  3380. self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
  3381. self.assertTrue(
  3382. ("unlisted.grd appears to be translatable "
  3383. "(because it contains <file> or <message> elements), "
  3384. "but is not listed in the translation expectations.")
  3385. in warnings[0].message)
  3386. self.assertTrue(
  3387. ("test.grd is listed in the translation expectations, "
  3388. "but this grd file does not exist")
  3389. in warnings[0].message)
  3390. class DISABLETypoInTest(unittest.TestCase):
  3391. def testPositive(self):
  3392. # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
  3393. # where the desire is to disable a test.
  3394. tests = [
  3395. # Disabled on one platform:
  3396. '#if defined(OS_WIN)\n'
  3397. '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
  3398. '#else\n'
  3399. '#define MAYBE_FoobarTest FoobarTest\n'
  3400. '#endif\n',
  3401. # Disabled on one platform spread cross lines:
  3402. '#if defined(OS_WIN)\n'
  3403. '#define MAYBE_FoobarTest \\\n'
  3404. ' DISABLE_FoobarTest\n'
  3405. '#else\n'
  3406. '#define MAYBE_FoobarTest FoobarTest\n'
  3407. '#endif\n',
  3408. # Disabled on all platforms:
  3409. ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
  3410. # Disabled on all platforms but multiple lines
  3411. ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
  3412. ]
  3413. for test in tests:
  3414. mock_input_api = MockInputApi()
  3415. mock_input_api.files = [
  3416. MockFile('some/path/foo_unittest.cc', test.splitlines()),
  3417. ]
  3418. results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
  3419. MockOutputApi())
  3420. self.assertEqual(
  3421. 1,
  3422. len(results),
  3423. msg=('expected len(results) == 1 but got %d in test: %s' %
  3424. (len(results), test)))
  3425. self.assertTrue(
  3426. 'foo_unittest.cc' in results[0].message,
  3427. msg=('expected foo_unittest.cc in message but got %s in test %s' %
  3428. (results[0].message, test)))
  3429. def testIgnoreNotTestFiles(self):
  3430. mock_input_api = MockInputApi()
  3431. mock_input_api.files = [
  3432. MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
  3433. ]
  3434. results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
  3435. MockOutputApi())
  3436. self.assertEqual(0, len(results))
  3437. def testIgnoreDeletedFiles(self):
  3438. mock_input_api = MockInputApi()
  3439. mock_input_api.files = [
  3440. MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
  3441. ]
  3442. results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
  3443. MockOutputApi())
  3444. self.assertEqual(0, len(results))
  3445. class ForgettingMAYBEInTests(unittest.TestCase):
  3446. def testPositive(self):
  3447. test = (
  3448. '#if defined(HAS_ENERGY)\n'
  3449. '#define MAYBE_CastExplosion DISABLED_CastExplosion\n'
  3450. '#else\n'
  3451. '#define MAYBE_CastExplosion CastExplosion\n'
  3452. '#endif\n'
  3453. 'TEST_F(ArchWizard, CastExplosion) {\n'
  3454. '#if defined(ARCH_PRIEST_IN_PARTY)\n'
  3455. '#define MAYBE_ArchPriest ArchPriest\n'
  3456. '#else\n'
  3457. '#define MAYBE_ArchPriest DISABLED_ArchPriest\n'
  3458. '#endif\n'
  3459. 'TEST_F(ArchPriest, CastNaturesBounty) {\n'
  3460. '#if !defined(CRUSADER_IN_PARTY)\n'
  3461. '#define MAYBE_Crusader \\\n'
  3462. ' DISABLED_Crusader \n'
  3463. '#else\n'
  3464. '#define MAYBE_Crusader \\\n'
  3465. ' Crusader\n'
  3466. '#endif\n'
  3467. ' TEST_F(\n'
  3468. ' Crusader,\n'
  3469. ' CastTaunt) { }\n'
  3470. '#if defined(LEARNED_BASIC_SKILLS)\n'
  3471. '#define MAYBE_CastSteal \\\n'
  3472. ' DISABLED_CastSteal \n'
  3473. '#else\n'
  3474. '#define MAYBE_CastSteal \\\n'
  3475. ' CastSteal\n'
  3476. '#endif\n'
  3477. ' TEST_F(\n'
  3478. ' ThiefClass,\n'
  3479. ' CastSteal) { }\n'
  3480. )
  3481. mock_input_api = MockInputApi()
  3482. mock_input_api.files = [
  3483. MockFile('fantasyworld/classes_unittest.cc', test.splitlines()),
  3484. ]
  3485. results = PRESUBMIT.CheckForgettingMAYBEInTests(mock_input_api,
  3486. MockOutputApi())
  3487. self.assertEqual(4, len(results))
  3488. self.assertTrue('CastExplosion' in results[0].message)
  3489. self.assertTrue('fantasyworld/classes_unittest.cc:2' in results[0].message)
  3490. self.assertTrue('ArchPriest' in results[1].message)
  3491. self.assertTrue('fantasyworld/classes_unittest.cc:8' in results[1].message)
  3492. self.assertTrue('Crusader' in results[2].message)
  3493. self.assertTrue('fantasyworld/classes_unittest.cc:14' in results[2].message)
  3494. self.assertTrue('CastSteal' in results[3].message)
  3495. self.assertTrue('fantasyworld/classes_unittest.cc:24' in results[3].message)
  3496. def testNegative(self):
  3497. test = (
  3498. '#if defined(HAS_ENERGY)\n'
  3499. '#define MAYBE_CastExplosion DISABLED_CastExplosion\n'
  3500. '#else\n'
  3501. '#define MAYBE_CastExplosion CastExplosion\n'
  3502. '#endif\n'
  3503. 'TEST_F(ArchWizard, MAYBE_CastExplosion) {\n'
  3504. '#if defined(ARCH_PRIEST_IN_PARTY)\n'
  3505. '#define MAYBE_ArchPriest ArchPriest\n'
  3506. '#else\n'
  3507. '#define MAYBE_ArchPriest DISABLED_ArchPriest\n'
  3508. '#endif\n'
  3509. 'TEST_F(MAYBE_ArchPriest, CastNaturesBounty) {\n'
  3510. '#if !defined(CRUSADER_IN_PARTY)\n'
  3511. '#define MAYBE_Crusader \\\n'
  3512. ' DISABLED_Crusader \n'
  3513. '#else\n'
  3514. '#define MAYBE_Crusader \\\n'
  3515. ' Crusader\n'
  3516. '#endif\n'
  3517. ' TEST_F(\n'
  3518. ' MAYBE_Crusader,\n'
  3519. ' CastTaunt) { }\n'
  3520. '#if defined(LEARNED_BASIC_SKILLS)\n'
  3521. '#define MAYBE_CastSteal \\\n'
  3522. ' DISABLED_CastSteal \n'
  3523. '#else\n'
  3524. '#define MAYBE_CastSteal \\\n'
  3525. ' CastSteal\n'
  3526. '#endif\n'
  3527. ' TEST_F(\n'
  3528. ' ThiefClass,\n'
  3529. ' MAYBE_CastSteal) { }\n'
  3530. )
  3531. mock_input_api = MockInputApi()
  3532. mock_input_api.files = [
  3533. MockFile('fantasyworld/classes_unittest.cc', test.splitlines()),
  3534. ]
  3535. results = PRESUBMIT.CheckForgettingMAYBEInTests(mock_input_api,
  3536. MockOutputApi())
  3537. self.assertEqual(0, len(results))
  3538. class CheckFuzzTargetsTest(unittest.TestCase):
  3539. def _check(self, files):
  3540. mock_input_api = MockInputApi()
  3541. mock_input_api.files = []
  3542. for fname, contents in files.items():
  3543. mock_input_api.files.append(MockFile(fname, contents.splitlines()))
  3544. return PRESUBMIT.CheckFuzzTargetsOnUpload(mock_input_api, MockOutputApi())
  3545. def testLibFuzzerSourcesIgnored(self):
  3546. results = self._check({
  3547. "third_party/lib/Fuzzer/FuzzerDriver.cpp": "LLVMFuzzerInitialize",
  3548. })
  3549. self.assertEqual(results, [])
  3550. def testNonCodeFilesIgnored(self):
  3551. results = self._check({
  3552. "README.md": "LLVMFuzzerInitialize",
  3553. })
  3554. self.assertEqual(results, [])
  3555. def testNoErrorHeaderPresent(self):
  3556. results = self._check({
  3557. "fuzzer.cc": (
  3558. "#include \"testing/libfuzzer/libfuzzer_exports.h\"\n" +
  3559. "LLVMFuzzerInitialize"
  3560. )
  3561. })
  3562. self.assertEqual(results, [])
  3563. def testErrorMissingHeader(self):
  3564. results = self._check({
  3565. "fuzzer.cc": "LLVMFuzzerInitialize"
  3566. })
  3567. self.assertEqual(len(results), 1)
  3568. self.assertEqual(results[0].items, ['fuzzer.cc'])
  3569. class SetNoParentTest(unittest.TestCase):
  3570. def testSetNoParentTopLevelAllowed(self):
  3571. mock_input_api = MockInputApi()
  3572. mock_input_api.files = [
  3573. MockAffectedFile('goat/OWNERS',
  3574. [
  3575. 'set noparent',
  3576. 'jochen@chromium.org',
  3577. ])
  3578. ]
  3579. mock_output_api = MockOutputApi()
  3580. errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
  3581. self.assertEqual([], errors)
  3582. def testSetNoParentMissing(self):
  3583. mock_input_api = MockInputApi()
  3584. mock_input_api.files = [
  3585. MockAffectedFile('services/goat/OWNERS',
  3586. [
  3587. 'set noparent',
  3588. 'jochen@chromium.org',
  3589. 'per-file *.json=set noparent',
  3590. 'per-file *.json=jochen@chromium.org',
  3591. ])
  3592. ]
  3593. mock_output_api = MockOutputApi()
  3594. errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
  3595. self.assertEqual(1, len(errors))
  3596. self.assertTrue('goat/OWNERS:1' in errors[0].long_text)
  3597. self.assertTrue('goat/OWNERS:3' in errors[0].long_text)
  3598. def testSetNoParentWithCorrectRule(self):
  3599. mock_input_api = MockInputApi()
  3600. mock_input_api.files = [
  3601. MockAffectedFile('services/goat/OWNERS',
  3602. [
  3603. 'set noparent',
  3604. 'file://ipc/SECURITY_OWNERS',
  3605. 'per-file *.json=set noparent',
  3606. 'per-file *.json=file://ipc/SECURITY_OWNERS',
  3607. ])
  3608. ]
  3609. mock_output_api = MockOutputApi()
  3610. errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
  3611. self.assertEqual([], errors)
  3612. class MojomStabilityCheckTest(unittest.TestCase):
  3613. def runTestWithAffectedFiles(self, affected_files):
  3614. mock_input_api = MockInputApi()
  3615. mock_input_api.files = affected_files
  3616. mock_output_api = MockOutputApi()
  3617. return PRESUBMIT.CheckStableMojomChanges(
  3618. mock_input_api, mock_output_api)
  3619. def testSafeChangePasses(self):
  3620. errors = self.runTestWithAffectedFiles([
  3621. MockAffectedFile('foo/foo.mojom',
  3622. ['[Stable] struct S { [MinVersion=1] int32 x; };'],
  3623. old_contents=['[Stable] struct S {};'])
  3624. ])
  3625. self.assertEqual([], errors)
  3626. def testBadChangeFails(self):
  3627. errors = self.runTestWithAffectedFiles([
  3628. MockAffectedFile('foo/foo.mojom',
  3629. ['[Stable] struct S { int32 x; };'],
  3630. old_contents=['[Stable] struct S {};'])
  3631. ])
  3632. self.assertEqual(1, len(errors))
  3633. self.assertTrue('not backward-compatible' in errors[0].message)
  3634. def testDeletedFile(self):
  3635. """Regression test for https://crbug.com/1091407."""
  3636. errors = self.runTestWithAffectedFiles([
  3637. MockAffectedFile('a.mojom', [], old_contents=['struct S {};'],
  3638. action='D'),
  3639. MockAffectedFile('b.mojom',
  3640. ['struct S {}; struct T { S s; };'],
  3641. old_contents=['import "a.mojom"; struct T { S s; };'])
  3642. ])
  3643. self.assertEqual([], errors)
  3644. class CheckForUseOfChromeAppsDeprecationsTest(unittest.TestCase):
  3645. ERROR_MSG_PIECE = 'technologies which will soon be deprecated'
  3646. # Each positive test is also a naive negative test for the other cases.
  3647. def testWarningNMF(self):
  3648. mock_input_api = MockInputApi()
  3649. mock_input_api.files = [
  3650. MockAffectedFile(
  3651. 'foo.NMF',
  3652. ['"program"', '"Z":"content"', 'B'],
  3653. ['"program"', 'B'],
  3654. scm_diff='\n'.join([
  3655. '--- foo.NMF.old 2020-12-02 20:40:54.430676385 +0100',
  3656. '+++ foo.NMF.new 2020-12-02 20:41:02.086700197 +0100',
  3657. '@@ -1,2 +1,3 @@',
  3658. ' "program"',
  3659. '+"Z":"content"',
  3660. ' B']),
  3661. action='M')
  3662. ]
  3663. mock_output_api = MockOutputApi()
  3664. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3665. mock_output_api)
  3666. self.assertEqual(1, len(errors))
  3667. self.assertTrue( self.ERROR_MSG_PIECE in errors[0].message)
  3668. self.assertTrue( 'foo.NMF' in errors[0].message)
  3669. def testWarningManifest(self):
  3670. mock_input_api = MockInputApi()
  3671. mock_input_api.files = [
  3672. MockAffectedFile(
  3673. 'manifest.json',
  3674. ['"app":', '"Z":"content"', 'B'],
  3675. ['"app":"', 'B'],
  3676. scm_diff='\n'.join([
  3677. '--- manifest.json.old 2020-12-02 20:40:54.430676385 +0100',
  3678. '+++ manifest.json.new 2020-12-02 20:41:02.086700197 +0100',
  3679. '@@ -1,2 +1,3 @@',
  3680. ' "app"',
  3681. '+"Z":"content"',
  3682. ' B']),
  3683. action='M')
  3684. ]
  3685. mock_output_api = MockOutputApi()
  3686. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3687. mock_output_api)
  3688. self.assertEqual(1, len(errors))
  3689. self.assertTrue( self.ERROR_MSG_PIECE in errors[0].message)
  3690. self.assertTrue( 'manifest.json' in errors[0].message)
  3691. def testOKWarningManifestWithoutApp(self):
  3692. mock_input_api = MockInputApi()
  3693. mock_input_api.files = [
  3694. MockAffectedFile(
  3695. 'manifest.json',
  3696. ['"name":', '"Z":"content"', 'B'],
  3697. ['"name":"', 'B'],
  3698. scm_diff='\n'.join([
  3699. '--- manifest.json.old 2020-12-02 20:40:54.430676385 +0100',
  3700. '+++ manifest.json.new 2020-12-02 20:41:02.086700197 +0100',
  3701. '@@ -1,2 +1,3 @@',
  3702. ' "app"',
  3703. '+"Z":"content"',
  3704. ' B']),
  3705. action='M')
  3706. ]
  3707. mock_output_api = MockOutputApi()
  3708. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3709. mock_output_api)
  3710. self.assertEqual(0, len(errors))
  3711. def testWarningPPAPI(self):
  3712. mock_input_api = MockInputApi()
  3713. mock_input_api.files = [
  3714. MockAffectedFile(
  3715. 'foo.hpp',
  3716. ['A', '#include <ppapi.h>', 'B'],
  3717. ['A', 'B'],
  3718. scm_diff='\n'.join([
  3719. '--- foo.hpp.old 2020-12-02 20:40:54.430676385 +0100',
  3720. '+++ foo.hpp.new 2020-12-02 20:41:02.086700197 +0100',
  3721. '@@ -1,2 +1,3 @@',
  3722. ' A',
  3723. '+#include <ppapi.h>',
  3724. ' B']),
  3725. action='M')
  3726. ]
  3727. mock_output_api = MockOutputApi()
  3728. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3729. mock_output_api)
  3730. self.assertEqual(1, len(errors))
  3731. self.assertTrue( self.ERROR_MSG_PIECE in errors[0].message)
  3732. self.assertTrue( 'foo.hpp' in errors[0].message)
  3733. def testNoWarningPPAPI(self):
  3734. mock_input_api = MockInputApi()
  3735. mock_input_api.files = [
  3736. MockAffectedFile(
  3737. 'foo.txt',
  3738. ['A', 'Peppapig', 'B'],
  3739. ['A', 'B'],
  3740. scm_diff='\n'.join([
  3741. '--- foo.txt.old 2020-12-02 20:40:54.430676385 +0100',
  3742. '+++ foo.txt.new 2020-12-02 20:41:02.086700197 +0100',
  3743. '@@ -1,2 +1,3 @@',
  3744. ' A',
  3745. '+Peppapig',
  3746. ' B']),
  3747. action='M')
  3748. ]
  3749. mock_output_api = MockOutputApi()
  3750. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3751. mock_output_api)
  3752. self.assertEqual(0, len(errors))
  3753. class CheckDeprecationOfPreferencesTest(unittest.TestCase):
  3754. # Test that a warning is generated if a preference registration is removed
  3755. # from a random file.
  3756. def testWarning(self):
  3757. mock_input_api = MockInputApi()
  3758. mock_input_api.files = [
  3759. MockAffectedFile(
  3760. 'foo.cc',
  3761. ['A', 'B'],
  3762. ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
  3763. scm_diff='\n'.join([
  3764. '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
  3765. '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
  3766. '@@ -1,3 +1,2 @@',
  3767. ' A',
  3768. '-prefs->RegisterStringPref("foo", "default");',
  3769. ' B']),
  3770. action='M')
  3771. ]
  3772. mock_output_api = MockOutputApi()
  3773. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3774. mock_output_api)
  3775. self.assertEqual(1, len(errors))
  3776. self.assertTrue(
  3777. 'Discovered possible removal of preference registrations' in
  3778. errors[0].message)
  3779. # Test that a warning is inhibited if the preference registration was moved
  3780. # to the deprecation functions in browser prefs.
  3781. def testNoWarningForMigration(self):
  3782. mock_input_api = MockInputApi()
  3783. mock_input_api.files = [
  3784. # RegisterStringPref was removed from foo.cc.
  3785. MockAffectedFile(
  3786. 'foo.cc',
  3787. ['A', 'B'],
  3788. ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
  3789. scm_diff='\n'.join([
  3790. '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
  3791. '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
  3792. '@@ -1,3 +1,2 @@',
  3793. ' A',
  3794. '-prefs->RegisterStringPref("foo", "default");',
  3795. ' B']),
  3796. action='M'),
  3797. # But the preference was properly migrated.
  3798. MockAffectedFile(
  3799. 'chrome/browser/prefs/browser_prefs.cc',
  3800. [
  3801. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3802. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3803. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3804. 'prefs->RegisterStringPref("foo", "default");',
  3805. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3806. ],
  3807. [
  3808. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3809. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3810. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3811. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3812. ],
  3813. scm_diff='\n'.join([
  3814. '--- browser_prefs.cc.old 2020-12-02 20:51:40.812686731 +0100',
  3815. '+++ browser_prefs.cc.new 2020-12-02 20:52:02.936755539 +0100',
  3816. '@@ -2,3 +2,4 @@',
  3817. ' // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3818. ' // BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3819. '+prefs->RegisterStringPref("foo", "default");',
  3820. ' // END_MIGRATE_OBSOLETE_PROFILE_PREFS']),
  3821. action='M'),
  3822. ]
  3823. mock_output_api = MockOutputApi()
  3824. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3825. mock_output_api)
  3826. self.assertEqual(0, len(errors))
  3827. # Test that a warning is NOT inhibited if the preference registration was
  3828. # moved to a place outside of the migration functions in browser_prefs.cc
  3829. def testWarningForImproperMigration(self):
  3830. mock_input_api = MockInputApi()
  3831. mock_input_api.files = [
  3832. # RegisterStringPref was removed from foo.cc.
  3833. MockAffectedFile(
  3834. 'foo.cc',
  3835. ['A', 'B'],
  3836. ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
  3837. scm_diff='\n'.join([
  3838. '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
  3839. '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
  3840. '@@ -1,3 +1,2 @@',
  3841. ' A',
  3842. '-prefs->RegisterStringPref("foo", "default");',
  3843. ' B']),
  3844. action='M'),
  3845. # The registration call was moved to a place in browser_prefs.cc that
  3846. # is outside the migration functions.
  3847. MockAffectedFile(
  3848. 'chrome/browser/prefs/browser_prefs.cc',
  3849. [
  3850. 'prefs->RegisterStringPref("foo", "default");',
  3851. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3852. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3853. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3854. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3855. ],
  3856. [
  3857. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3858. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3859. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3860. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3861. ],
  3862. scm_diff='\n'.join([
  3863. '--- browser_prefs.cc.old 2020-12-02 20:51:40.812686731 +0100',
  3864. '+++ browser_prefs.cc.new 2020-12-02 20:52:02.936755539 +0100',
  3865. '@@ -1,2 +1,3 @@',
  3866. '+prefs->RegisterStringPref("foo", "default");',
  3867. ' // BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3868. ' // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS']),
  3869. action='M'),
  3870. ]
  3871. mock_output_api = MockOutputApi()
  3872. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3873. mock_output_api)
  3874. self.assertEqual(1, len(errors))
  3875. self.assertTrue(
  3876. 'Discovered possible removal of preference registrations' in
  3877. errors[0].message)
  3878. # Check that the presubmit fails if a marker line in browser_prefs.cc is
  3879. # deleted.
  3880. def testDeletedMarkerRaisesError(self):
  3881. mock_input_api = MockInputApi()
  3882. mock_input_api.files = [
  3883. MockAffectedFile('chrome/browser/prefs/browser_prefs.cc',
  3884. [
  3885. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3886. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3887. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3888. # The following line is deleted for this test
  3889. # '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3890. ])
  3891. ]
  3892. mock_output_api = MockOutputApi()
  3893. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3894. mock_output_api)
  3895. self.assertEqual(1, len(errors))
  3896. self.assertEqual(
  3897. 'Broken .*MIGRATE_OBSOLETE_.*_PREFS markers in browser_prefs.cc.',
  3898. errors[0].message)
  3899. class MPArchApiUsage(unittest.TestCase):
  3900. def _assert_notify(
  3901. self, expected_uses, expect_fyi, msg, local_path, new_contents):
  3902. mock_input_api = MockInputApi()
  3903. mock_output_api = MockOutputApi()
  3904. mock_input_api.files = [
  3905. MockFile(local_path, new_contents),
  3906. ]
  3907. result = PRESUBMIT.CheckMPArchApiUsage(mock_input_api, mock_output_api)
  3908. watchlist_email = ('mparch-reviews+watchfyi@chromium.org'
  3909. if expect_fyi else 'mparch-reviews+watch@chromium.org')
  3910. self.assertEqual(
  3911. bool(expected_uses or expect_fyi),
  3912. watchlist_email in mock_output_api.more_cc,
  3913. msg)
  3914. if expected_uses:
  3915. self.assertEqual(1, len(result), msg)
  3916. self.assertEqual(result[0].type, 'notify', msg)
  3917. self.assertEqual(sorted(result[0].items), sorted(expected_uses), msg)
  3918. else:
  3919. self.assertEqual(0, len(result), msg)
  3920. def testNotify(self):
  3921. self._assert_notify(
  3922. ['IsInMainFrame'],
  3923. False,
  3924. 'Introduce IsInMainFrame',
  3925. 'chrome/my_feature.cc',
  3926. ['void DoSomething(content::NavigationHandle* navigation_handle) {',
  3927. ' if (navigation_handle->IsInMainFrame())',
  3928. ' all_of_our_page_state.reset();',
  3929. '}',
  3930. ])
  3931. self._assert_notify(
  3932. ['FromRenderFrameHost'],
  3933. False,
  3934. 'Introduce WC::FromRenderFrameHost',
  3935. 'chrome/my_feature.cc',
  3936. ['void DoSomething(content::RenderFrameHost* rfh) {',
  3937. ' auto* wc = content::WebContents::FromRenderFrameHost(rfh);',
  3938. ' ChangeTabState(wc);',
  3939. '}',
  3940. ])
  3941. def testFyi(self):
  3942. self._assert_notify(
  3943. [],
  3944. True,
  3945. 'Introduce WCO and WCUD',
  3946. 'chrome/my_feature.h',
  3947. ['class MyFeature',
  3948. ' : public content::WebContentsObserver,',
  3949. ' public content::WebContentsUserData<MyFeature> {};',
  3950. ])
  3951. self._assert_notify(
  3952. [],
  3953. True,
  3954. 'Introduce WCO override',
  3955. 'chrome/my_feature.h',
  3956. ['void DidFinishNavigation(',
  3957. ' content::NavigationHandle* navigation_handle) override;',
  3958. ])
  3959. def testNoNotify(self):
  3960. self._assert_notify(
  3961. [],
  3962. False,
  3963. 'No API usage',
  3964. 'chrome/my_feature.cc',
  3965. ['void DoSomething() {',
  3966. ' // TODO: Something',
  3967. '}',
  3968. ])
  3969. # Something under a top level directory we're not concerned about happens
  3970. # to share a name with a content API.
  3971. self._assert_notify(
  3972. [],
  3973. False,
  3974. 'Uninteresting top level directory',
  3975. 'third_party/my_dep/my_code.cc',
  3976. ['bool HasParent(Node* node) {',
  3977. ' return node->GetParent();',
  3978. '}',
  3979. ])
  3980. # We're not concerned with usage in test code.
  3981. self._assert_notify(
  3982. [],
  3983. False,
  3984. 'Usage in test code',
  3985. 'chrome/my_feature_unittest.cc',
  3986. ['TEST_F(MyFeatureTest, DoesSomething) {',
  3987. ' EXPECT_TRUE(rfh()->GetMainFrame());',
  3988. '}',
  3989. ])
  3990. class AssertAshOnlyCodeTest(unittest.TestCase):
  3991. def testErrorsOnlyOnAshDirectories(self):
  3992. files_in_ash = [
  3993. MockFile('ash/BUILD.gn', []),
  3994. MockFile('chrome/browser/ash/BUILD.gn', []),
  3995. ]
  3996. other_files = [
  3997. MockFile('chrome/browser/BUILD.gn', []),
  3998. MockFile('chrome/browser/BUILD.gn', ['assert(is_chromeos_ash)']),
  3999. ]
  4000. input_api = MockInputApi()
  4001. input_api.files = files_in_ash
  4002. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  4003. self.assertEqual(2, len(errors))
  4004. input_api.files = other_files
  4005. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  4006. self.assertEqual(0, len(errors))
  4007. def testDoesNotErrorOnNonGNFiles(self):
  4008. input_api = MockInputApi()
  4009. input_api.files = [
  4010. MockFile('ash/test.h', ['assert(is_chromeos_ash)']),
  4011. MockFile('chrome/browser/ash/test.cc',
  4012. ['assert(is_chromeos_ash)']),
  4013. ]
  4014. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  4015. self.assertEqual(0, len(errors))
  4016. def testDeletedFile(self):
  4017. input_api = MockInputApi()
  4018. input_api.files = [
  4019. MockFile('ash/BUILD.gn', []),
  4020. MockFile('ash/foo/BUILD.gn', [], action='D'),
  4021. ]
  4022. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  4023. self.assertEqual(1, len(errors))
  4024. def testDoesNotErrorWithAssertion(self):
  4025. input_api = MockInputApi()
  4026. input_api.files = [
  4027. MockFile('ash/BUILD.gn', ['assert(is_chromeos_ash)']),
  4028. MockFile('chrome/browser/ash/BUILD.gn',
  4029. ['assert(is_chromeos_ash)']),
  4030. MockFile('chrome/browser/ash/BUILD.gn',
  4031. ['assert(is_chromeos_ash, "test")']),
  4032. ]
  4033. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  4034. self.assertEqual(0, len(errors))
  4035. class CheckRawPtrUsageTest(unittest.TestCase):
  4036. def testAllowedCases(self):
  4037. mock_input_api = MockInputApi()
  4038. mock_input_api.files = [
  4039. # Browser-side files are allowed.
  4040. MockAffectedFile('test10/browser/foo.h', ['raw_ptr<int>']),
  4041. MockAffectedFile('test11/browser/foo.cc', ['raw_ptr<int>']),
  4042. MockAffectedFile('test12/blink/common/foo.cc', ['raw_ptr<int>']),
  4043. MockAffectedFile('test13/blink/public/common/foo.cc', ['raw_ptr<int>']),
  4044. MockAffectedFile('test14/blink/public/platform/foo.cc',
  4045. ['raw_ptr<int>']),
  4046. # Non-C++ files are allowed.
  4047. MockAffectedFile('test20/renderer/foo.md', ['raw_ptr<int>']),
  4048. # Mentions in a comment are allowed.
  4049. MockAffectedFile('test30/renderer/foo.cc', ['//raw_ptr<int>']),
  4050. ]
  4051. mock_output_api = MockOutputApi()
  4052. errors = PRESUBMIT.CheckRawPtrUsage(mock_input_api, mock_output_api)
  4053. self.assertFalse(errors)
  4054. def testDisallowedCases(self):
  4055. mock_input_api = MockInputApi()
  4056. mock_input_api.files = [
  4057. MockAffectedFile('test1/renderer/foo.h', ['raw_ptr<int>']),
  4058. MockAffectedFile('test2/renderer/foo.cc', ['raw_ptr<int>']),
  4059. MockAffectedFile('test3/blink/public/web/foo.cc', ['raw_ptr<int>']),
  4060. ]
  4061. mock_output_api = MockOutputApi()
  4062. errors = PRESUBMIT.CheckRawPtrUsage(mock_input_api, mock_output_api)
  4063. self.assertEqual(len(mock_input_api.files), len(errors))
  4064. for error in errors:
  4065. self.assertTrue(
  4066. 'raw_ptr<T> should not be used in Renderer-only code' in
  4067. error.message)
  4068. class AssertPythonShebangTest(unittest.TestCase):
  4069. def testError(self):
  4070. input_api = MockInputApi()
  4071. input_api.files = [
  4072. MockFile('ash/test.py', ['#!/usr/bin/python']),
  4073. MockFile('chrome/test.py', ['#!/usr/bin/python2']),
  4074. MockFile('third_party/blink/test.py', ['#!/usr/bin/python3']),
  4075. MockFile('empty.py', []),
  4076. ]
  4077. errors = PRESUBMIT.CheckPythonShebang(input_api, MockOutputApi())
  4078. self.assertEqual(3, len(errors))
  4079. def testNonError(self):
  4080. input_api = MockInputApi()
  4081. input_api.files = [
  4082. MockFile('chrome/browser/BUILD.gn', ['#!/usr/bin/python']),
  4083. MockFile('third_party/blink/web_tests/external/test.py',
  4084. ['#!/usr/bin/python2']),
  4085. MockFile('third_party/test/test.py', ['#!/usr/bin/python3']),
  4086. ]
  4087. errors = PRESUBMIT.CheckPythonShebang(input_api, MockOutputApi())
  4088. self.assertEqual(0, len(errors))
  4089. class VerifyDcheckParentheses(unittest.TestCase):
  4090. def testPermissibleUsage(self):
  4091. input_api = MockInputApi()
  4092. input_api.files = [
  4093. MockFile('okay1.cc', ['DCHECK_IS_ON()']),
  4094. MockFile('okay2.cc', ['#if DCHECK_IS_ON()']),
  4095. # Other constructs that aren't exactly `DCHECK_IS_ON()` do their
  4096. # own thing at their own risk.
  4097. MockFile('okay3.cc', ['PA_DCHECK_IS_ON']),
  4098. MockFile('okay4.cc', ['#if PA_DCHECK_IS_ON']),
  4099. MockFile('okay6.cc', ['BUILDFLAG(PA_DCHECK_IS_ON)']),
  4100. ]
  4101. errors = PRESUBMIT.CheckDCHECK_IS_ONHasBraces(input_api, MockOutputApi())
  4102. self.assertEqual(0, len(errors))
  4103. def testMissingParentheses(self):
  4104. input_api = MockInputApi()
  4105. input_api.files = [
  4106. MockFile('bad1.cc', ['DCHECK_IS_ON']),
  4107. MockFile('bad2.cc', ['#if DCHECK_IS_ON']),
  4108. MockFile('bad3.cc', ['DCHECK_IS_ON && foo']),
  4109. ]
  4110. errors = PRESUBMIT.CheckDCHECK_IS_ONHasBraces(input_api, MockOutputApi())
  4111. self.assertEqual(3, len(errors))
  4112. for error in errors:
  4113. self.assertRegex(error.message, r'DCHECK_IS_ON().+parentheses')
  4114. class CheckBatchAnnotation(unittest.TestCase):
  4115. """Test the CheckBatchAnnotation presubmit check."""
  4116. def testTruePositives(self):
  4117. """Examples of when there is no @Batch or @DoNotBatch is correctly flagged.
  4118. """
  4119. mock_input = MockInputApi()
  4120. mock_input.files = [
  4121. MockFile('path/OneTest.java', ['public class OneTest']),
  4122. MockFile('path/TwoTest.java', ['public class TwoTest']),
  4123. MockFile('path/ThreeTest.java',
  4124. ['@Batch(Batch.PER_CLASS)',
  4125. 'import org.chromium.base.test.BaseRobolectricTestRunner;',
  4126. 'public class Three {']),
  4127. MockFile('path/FourTest.java',
  4128. ['@DoNotBatch(reason = "dummy reason 1")',
  4129. 'import org.chromium.base.test.BaseRobolectricTestRunner;',
  4130. 'public class Four {']),
  4131. ]
  4132. errors = PRESUBMIT.CheckBatchAnnotation(mock_input, MockOutputApi())
  4133. self.assertEqual(2, len(errors))
  4134. self.assertEqual(2, len(errors[0].items))
  4135. self.assertIn('OneTest.java', errors[0].items[0])
  4136. self.assertIn('TwoTest.java', errors[0].items[1])
  4137. self.assertEqual(2, len(errors[1].items))
  4138. self.assertIn('ThreeTest.java', errors[1].items[0])
  4139. self.assertIn('FourTest.java', errors[1].items[1])
  4140. def testAnnotationsPresent(self):
  4141. """Examples of when there is @Batch or @DoNotBatch is correctly flagged."""
  4142. mock_input = MockInputApi()
  4143. mock_input.files = [
  4144. MockFile('path/OneTest.java',
  4145. ['@Batch(Batch.PER_CLASS)', 'public class One {']),
  4146. MockFile('path/TwoTest.java',
  4147. ['@DoNotBatch(reason = "dummy reasons.")', 'public class Two {'
  4148. ]),
  4149. MockFile('path/ThreeTest.java',
  4150. ['@Batch(Batch.PER_CLASS)',
  4151. 'public class Three extends BaseTestA {'],
  4152. ['@Batch(Batch.PER_CLASS)',
  4153. 'public class Three extends BaseTestB {']),
  4154. MockFile('path/FourTest.java',
  4155. ['@DoNotBatch(reason = "dummy reason 1")',
  4156. 'public class Four extends BaseTestA {'],
  4157. ['@DoNotBatch(reason = "dummy reason 2")',
  4158. 'public class Four extends BaseTestB {']),
  4159. MockFile('path/FiveTest.java',
  4160. ['import androidx.test.uiautomator.UiDevice;',
  4161. 'public class Five extends BaseTestA {'],
  4162. ['import androidx.test.uiautomator.UiDevice;',
  4163. 'public class Five extends BaseTestB {']),
  4164. MockFile('path/SixTest.java',
  4165. ['import org.chromium.base.test.BaseRobolectricTestRunner;',
  4166. 'public class Six extends BaseTestA {'],
  4167. ['import org.chromium.base.test.BaseRobolectricTestRunner;',
  4168. 'public class Six extends BaseTestB {']),
  4169. MockFile('path/SevenTest.java',
  4170. ['import org.robolectric.annotation.Config;',
  4171. 'public class Seven extends BaseTestA {'],
  4172. ['import org.robolectric.annotation.Config;',
  4173. 'public class Seven extends BaseTestB {']),
  4174. MockFile(
  4175. 'path/OtherClass.java',
  4176. ['public class OtherClass {'],
  4177. ),
  4178. MockFile('path/PRESUBMIT.py',
  4179. ['@Batch(Batch.PER_CLASS)',
  4180. '@DoNotBatch(reason = "dummy reason)']),
  4181. ]
  4182. errors = PRESUBMIT.CheckBatchAnnotation(mock_input, MockOutputApi())
  4183. self.assertEqual(0, len(errors))
  4184. if __name__ == '__main__':
  4185. unittest.main()