PRESUBMIT_test.py 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. 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. ]),
  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 accepted even if
  723. # it's an old file.
  724. MockAffectedFile('third_party/blink/StillInBlink.h', [
  725. '// New contents',
  726. '#ifndef AcceptedInBlink_h',
  727. '#define AcceptedInBlink_h',
  728. 'struct McBoatFace;',
  729. '#endif // AcceptedInBlink_h',
  730. ], [
  731. '// Old contents',
  732. '#ifndef AcceptedInBlink_h',
  733. '#define AcceptedInBlink_h',
  734. 'struct McBoatFace;',
  735. '#endif // AcceptedInBlink_h',
  736. ]),
  737. # Using a non-Chromium include guard in third_party
  738. # (outside blink) is accepted.
  739. MockAffectedFile('third_party/foo/some_file.h', [
  740. '#ifndef REQUIRED_RPCNDR_H_',
  741. '#define REQUIRED_RPCNDR_H_',
  742. 'struct SomeFileFoo;',
  743. '#endif // REQUIRED_RPCNDR_H_',
  744. ]),
  745. # Not having proper include guard in *_message_generator.h
  746. # for old IPC messages is allowed.
  747. MockAffectedFile('content/common/content_message_generator.h', [
  748. '#undef CONTENT_COMMON_FOO_MESSAGES_H_',
  749. '#include "content/common/foo_messages.h"',
  750. '#ifndef CONTENT_COMMON_FOO_MESSAGES_H_',
  751. '#error "Failed to include content/common/foo_messages.h"',
  752. '#endif',
  753. ]),
  754. ]
  755. msgs = PRESUBMIT.CheckForIncludeGuards(
  756. mock_input_api, mock_output_api)
  757. expected_fail_count = 8
  758. self.assertEqual(expected_fail_count, len(msgs),
  759. 'Expected %d items, found %d: %s'
  760. % (expected_fail_count, len(msgs), msgs))
  761. self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
  762. self.assertEqual(msgs[0].message,
  763. 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
  764. 'not covering the whole file')
  765. self.assertIn('content/browser/test1.h', msgs[1].message)
  766. self.assertIn('Recommended name: CONTENT_BROWSER_TEST1_H_',
  767. msgs[1].message)
  768. self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
  769. self.assertEqual(msgs[2].message,
  770. 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
  771. 'include guard')
  772. self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
  773. self.assertEqual(msgs[3].message,
  774. 'Header using the wrong include guard name '
  775. 'CONTENT_BROWSER_SPLLEING_H_')
  776. self.assertIn('content/browser/foo+bar.h', msgs[4].message)
  777. self.assertIn('Recommended name: CONTENT_BROWSER_FOO_BAR_H_',
  778. msgs[4].message)
  779. self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
  780. self.assertEqual(msgs[5].message,
  781. 'Header using the wrong include guard name '
  782. 'NotInBlink_h')
  783. self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
  784. self.assertEqual(msgs[6].message,
  785. 'Header using the wrong include guard name '
  786. 'InBlink_h')
  787. self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
  788. self.assertEqual(msgs[7].message,
  789. 'Header using the wrong include guard name '
  790. 'WrongInBlink_h')
  791. class AccessibilityRelnotesFieldTest(unittest.TestCase):
  792. def testRelnotesPresent(self):
  793. mock_input_api = MockInputApi()
  794. mock_output_api = MockOutputApi()
  795. mock_input_api.files = [MockAffectedFile('ui/accessibility/foo.bar', [''])]
  796. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  797. mock_input_api.change.footers['AX-Relnotes'] = [
  798. 'Important user facing change']
  799. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  800. mock_input_api, mock_output_api)
  801. self.assertEqual(0, len(msgs),
  802. 'Expected %d messages, found %d: %s'
  803. % (0, len(msgs), msgs))
  804. def testRelnotesMissingFromAccessibilityChange(self):
  805. mock_input_api = MockInputApi()
  806. mock_output_api = MockOutputApi()
  807. mock_input_api.files = [
  808. MockAffectedFile('some/file', ['']),
  809. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  810. MockAffectedFile('some/other/file', [''])
  811. ]
  812. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  813. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  814. mock_input_api, mock_output_api)
  815. self.assertEqual(1, len(msgs),
  816. 'Expected %d messages, found %d: %s'
  817. % (1, len(msgs), msgs))
  818. self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
  819. 'Missing AX-Relnotes field message not found in errors')
  820. # The relnotes footer is not required for changes which do not touch any
  821. # accessibility directories.
  822. def testIgnoresNonAccesssibilityCode(self):
  823. mock_input_api = MockInputApi()
  824. mock_output_api = MockOutputApi()
  825. mock_input_api.files = [
  826. MockAffectedFile('some/file', ['']),
  827. MockAffectedFile('some/other/file', [''])
  828. ]
  829. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  830. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  831. mock_input_api, mock_output_api)
  832. self.assertEqual(0, len(msgs),
  833. 'Expected %d messages, found %d: %s'
  834. % (0, len(msgs), msgs))
  835. # Test that our presubmit correctly raises an error for a set of known paths.
  836. def testExpectedPaths(self):
  837. filesToTest = [
  838. "chrome/browser/accessibility/foo.py",
  839. "chrome/browser/ash/arc/accessibility/foo.cc",
  840. "chrome/browser/ui/views/accessibility/foo.h",
  841. "chrome/browser/extensions/api/automation/foo.h",
  842. "chrome/browser/extensions/api/automation_internal/foo.cc",
  843. "chrome/renderer/extensions/accessibility_foo.h",
  844. "chrome/tests/data/accessibility/foo.html",
  845. "content/browser/accessibility/foo.cc",
  846. "content/renderer/accessibility/foo.h",
  847. "content/tests/data/accessibility/foo.cc",
  848. "extensions/renderer/api/automation/foo.h",
  849. "ui/accessibility/foo/bar/baz.cc",
  850. "ui/views/accessibility/foo/bar/baz.h",
  851. ]
  852. for testFile in filesToTest:
  853. mock_input_api = MockInputApi()
  854. mock_output_api = MockOutputApi()
  855. mock_input_api.files = [
  856. MockAffectedFile(testFile, [''])
  857. ]
  858. mock_input_api.change.DescriptionText = lambda : 'Commit description'
  859. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  860. mock_input_api, mock_output_api)
  861. self.assertEqual(1, len(msgs),
  862. 'Expected %d messages, found %d: %s, for file %s'
  863. % (1, len(msgs), msgs, testFile))
  864. self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
  865. ('Missing AX-Relnotes field message not found in errors '
  866. ' for file %s' % (testFile)))
  867. # Test that AX-Relnotes field can appear in the commit description (as long
  868. # as it appears at the beginning of a line).
  869. def testRelnotesInCommitDescription(self):
  870. mock_input_api = MockInputApi()
  871. mock_output_api = MockOutputApi()
  872. mock_input_api.files = [
  873. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  874. ]
  875. mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
  876. 'AX-Relnotes: solves all accessibility issues forever')
  877. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  878. mock_input_api, mock_output_api)
  879. self.assertEqual(0, len(msgs),
  880. 'Expected %d messages, found %d: %s'
  881. % (0, len(msgs), msgs))
  882. # Test that we don't match AX-Relnotes if it appears in the middle of a line.
  883. def testRelnotesMustAppearAtBeginningOfLine(self):
  884. mock_input_api = MockInputApi()
  885. mock_output_api = MockOutputApi()
  886. mock_input_api.files = [
  887. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  888. ]
  889. mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
  890. 'This change has no AX-Relnotes: we should print a warning')
  891. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  892. mock_input_api, mock_output_api)
  893. self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
  894. 'Missing AX-Relnotes field message not found in errors')
  895. # Tests that the AX-Relnotes field can be lowercase and use a '=' in place
  896. # of a ':'.
  897. def testRelnotesLowercaseWithEqualSign(self):
  898. mock_input_api = MockInputApi()
  899. mock_output_api = MockOutputApi()
  900. mock_input_api.files = [
  901. MockAffectedFile('ui/accessibility/foo.bar', ['']),
  902. ]
  903. mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
  904. 'ax-relnotes= this is a valid format for accessibiliy relnotes')
  905. msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
  906. mock_input_api, mock_output_api)
  907. self.assertEqual(0, len(msgs),
  908. 'Expected %d messages, found %d: %s'
  909. % (0, len(msgs), msgs))
  910. class AccessibilityEventsTestsAreIncludedForAndroidTest(unittest.TestCase):
  911. # Test that no warning is raised when the Android file is also modified.
  912. def testAndroidChangeIncluded(self):
  913. mock_input_api = MockInputApi()
  914. mock_input_api.files = [
  915. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  916. [''], action='A'),
  917. MockAffectedFile(
  918. 'accessibility/WebContentsAccessibilityEventsTest.java',
  919. [''], action='M')
  920. ]
  921. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  922. mock_input_api, MockOutputApi())
  923. self.assertEqual(0, len(msgs),
  924. 'Expected %d messages, found %d: %s'
  925. % (0, len(msgs), msgs))
  926. # Test that a warning is raised when the Android file is not modified.
  927. def testAndroidChangeMissing(self):
  928. mock_input_api = MockInputApi()
  929. mock_input_api.files = [
  930. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  931. [''], action='A'),
  932. ]
  933. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  934. mock_input_api, MockOutputApi())
  935. self.assertEqual(1, len(msgs),
  936. 'Expected %d messages, found %d: %s'
  937. % (1, len(msgs), msgs))
  938. # Test that Android change is not required when no html file is added/removed.
  939. def testIgnoreNonHtmlFiles(self):
  940. mock_input_api = MockInputApi()
  941. mock_input_api.files = [
  942. MockAffectedFile('content/test/data/accessibility/event/foo.txt',
  943. [''], action='A'),
  944. MockAffectedFile('content/test/data/accessibility/event/foo.cc',
  945. [''], action='A'),
  946. MockAffectedFile('content/test/data/accessibility/event/foo.h',
  947. [''], action='A'),
  948. MockAffectedFile('content/test/data/accessibility/event/foo.py',
  949. [''], action='A')
  950. ]
  951. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  952. mock_input_api, MockOutputApi())
  953. self.assertEqual(0, len(msgs),
  954. 'Expected %d messages, found %d: %s'
  955. % (0, len(msgs), msgs))
  956. # Test that Android change is not required for unrelated html files.
  957. def testIgnoreNonRelatedHtmlFiles(self):
  958. mock_input_api = MockInputApi()
  959. mock_input_api.files = [
  960. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  961. [''], action='A'),
  962. MockAffectedFile('content/test/data/accessibility/html/foo.html',
  963. [''], action='A'),
  964. MockAffectedFile('chrome/tests/data/accessibility/foo.html',
  965. [''], action='A')
  966. ]
  967. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  968. mock_input_api, MockOutputApi())
  969. self.assertEqual(0, len(msgs),
  970. 'Expected %d messages, found %d: %s'
  971. % (0, len(msgs), msgs))
  972. # Test that only modifying an html file will not trigger the warning.
  973. def testIgnoreModifiedFiles(self):
  974. mock_input_api = MockInputApi()
  975. mock_input_api.files = [
  976. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  977. [''], action='M')
  978. ]
  979. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  980. mock_input_api, MockOutputApi())
  981. self.assertEqual(0, len(msgs),
  982. 'Expected %d messages, found %d: %s'
  983. % (0, len(msgs), msgs))
  984. # Test that deleting an html file will trigger the warning.
  985. def testAndroidChangeMissingOnDeletedFile(self):
  986. mock_input_api = MockInputApi()
  987. mock_input_api.files = [
  988. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  989. [], action='D')
  990. ]
  991. msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
  992. mock_input_api, MockOutputApi())
  993. self.assertEqual(1, len(msgs),
  994. 'Expected %d messages, found %d: %s'
  995. % (1, len(msgs), msgs))
  996. class AccessibilityTreeTestsAreIncludedForAndroidTest(unittest.TestCase):
  997. # Test that no warning is raised when the Android file is also modified.
  998. def testAndroidChangeIncluded(self):
  999. mock_input_api = MockInputApi()
  1000. mock_input_api.files = [
  1001. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1002. [''], action='A'),
  1003. MockAffectedFile(
  1004. 'accessibility/WebContentsAccessibilityTreeTest.java',
  1005. [''], action='M')
  1006. ]
  1007. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1008. mock_input_api, MockOutputApi())
  1009. self.assertEqual(0, len(msgs),
  1010. 'Expected %d messages, found %d: %s'
  1011. % (0, len(msgs), msgs))
  1012. # Test that no warning is raised when the Android file is also modified.
  1013. def testAndroidChangeIncludedManyFiles(self):
  1014. mock_input_api = MockInputApi()
  1015. mock_input_api.files = [
  1016. MockAffectedFile('content/test/data/accessibility/accname/foo.html',
  1017. [''], action='A'),
  1018. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1019. [''], action='A'),
  1020. MockAffectedFile('content/test/data/accessibility/css/foo.html',
  1021. [''], action='A'),
  1022. MockAffectedFile('content/test/data/accessibility/html/foo.html',
  1023. [''], action='A'),
  1024. MockAffectedFile(
  1025. 'accessibility/WebContentsAccessibilityTreeTest.java',
  1026. [''], action='M')
  1027. ]
  1028. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1029. mock_input_api, MockOutputApi())
  1030. self.assertEqual(0, len(msgs),
  1031. 'Expected %d messages, found %d: %s'
  1032. % (0, len(msgs), msgs))
  1033. # Test that a warning is raised when the Android file is not modified.
  1034. def testAndroidChangeMissing(self):
  1035. mock_input_api = MockInputApi()
  1036. mock_input_api.files = [
  1037. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1038. [''], action='A'),
  1039. ]
  1040. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1041. mock_input_api, MockOutputApi())
  1042. self.assertEqual(1, len(msgs),
  1043. 'Expected %d messages, found %d: %s'
  1044. % (1, len(msgs), msgs))
  1045. # Test that Android change is not required when no html file is added/removed.
  1046. def testIgnoreNonHtmlFiles(self):
  1047. mock_input_api = MockInputApi()
  1048. mock_input_api.files = [
  1049. MockAffectedFile('content/test/data/accessibility/accname/foo.txt',
  1050. [''], action='A'),
  1051. MockAffectedFile('content/test/data/accessibility/aria/foo.cc',
  1052. [''], action='A'),
  1053. MockAffectedFile('content/test/data/accessibility/css/foo.h',
  1054. [''], action='A'),
  1055. MockAffectedFile('content/test/data/accessibility/tree/foo.py',
  1056. [''], action='A')
  1057. ]
  1058. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1059. mock_input_api, MockOutputApi())
  1060. self.assertEqual(0, len(msgs),
  1061. 'Expected %d messages, found %d: %s'
  1062. % (0, len(msgs), msgs))
  1063. # Test that Android change is not required for unrelated html files.
  1064. def testIgnoreNonRelatedHtmlFiles(self):
  1065. mock_input_api = MockInputApi()
  1066. mock_input_api.files = [
  1067. MockAffectedFile('content/test/data/accessibility/event/foo.html',
  1068. [''], action='A'),
  1069. ]
  1070. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1071. mock_input_api, MockOutputApi())
  1072. self.assertEqual(0, len(msgs),
  1073. 'Expected %d messages, found %d: %s'
  1074. % (0, len(msgs), msgs))
  1075. # Test that only modifying an html file will not trigger the warning.
  1076. def testIgnoreModifiedFiles(self):
  1077. mock_input_api = MockInputApi()
  1078. mock_input_api.files = [
  1079. MockAffectedFile('content/test/data/accessibility/aria/foo.html',
  1080. [''], action='M')
  1081. ]
  1082. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1083. mock_input_api, MockOutputApi())
  1084. self.assertEqual(0, len(msgs),
  1085. 'Expected %d messages, found %d: %s'
  1086. % (0, len(msgs), msgs))
  1087. # Test that deleting an html file will trigger the warning.
  1088. def testAndroidChangeMissingOnDeletedFile(self):
  1089. mock_input_api = MockInputApi()
  1090. mock_input_api.files = [
  1091. MockAffectedFile('content/test/data/accessibility/accname/foo.html',
  1092. [], action='D')
  1093. ]
  1094. msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
  1095. mock_input_api, MockOutputApi())
  1096. self.assertEqual(1, len(msgs),
  1097. 'Expected %d messages, found %d: %s'
  1098. % (1, len(msgs), msgs))
  1099. class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
  1100. def testCheckAndroidTestAnnotationUsage(self):
  1101. mock_input_api = MockInputApi()
  1102. mock_output_api = MockOutputApi()
  1103. mock_input_api.files = [
  1104. MockAffectedFile('LalaLand.java', [
  1105. 'random stuff'
  1106. ]),
  1107. MockAffectedFile('CorrectUsage.java', [
  1108. 'import android.support.test.filters.LargeTest;',
  1109. 'import android.support.test.filters.MediumTest;',
  1110. 'import android.support.test.filters.SmallTest;',
  1111. ]),
  1112. MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
  1113. 'import android.test.suitebuilder.annotation.LargeTest;',
  1114. ]),
  1115. MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
  1116. 'import android.test.suitebuilder.annotation.MediumTest;',
  1117. ]),
  1118. MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
  1119. 'import android.test.suitebuilder.annotation.SmallTest;',
  1120. ]),
  1121. MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
  1122. 'import android.test.suitebuilder.annotation.Smoke;',
  1123. ])
  1124. ]
  1125. msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
  1126. mock_input_api, mock_output_api)
  1127. self.assertEqual(1, len(msgs),
  1128. 'Expected %d items, found %d: %s'
  1129. % (1, len(msgs), msgs))
  1130. self.assertEqual(4, len(msgs[0].items),
  1131. 'Expected %d items, found %d: %s'
  1132. % (4, len(msgs[0].items), msgs[0].items))
  1133. self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
  1134. 'UsedDeprecatedLargeTestAnnotation not found in errors')
  1135. self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
  1136. in msgs[0].items,
  1137. 'UsedDeprecatedMediumTestAnnotation not found in errors')
  1138. self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
  1139. 'UsedDeprecatedSmallTestAnnotation not found in errors')
  1140. self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
  1141. 'UsedDeprecatedSmokeAnnotation not found in errors')
  1142. class CheckNoDownstreamDepsTest(unittest.TestCase):
  1143. def testInvalidDepFromUpstream(self):
  1144. mock_input_api = MockInputApi()
  1145. mock_output_api = MockOutputApi()
  1146. mock_input_api.files = [
  1147. MockAffectedFile('BUILD.gn', [
  1148. 'deps = [',
  1149. ' "//clank/target:test",',
  1150. ']'
  1151. ]),
  1152. MockAffectedFile('chrome/android/BUILD.gn', [
  1153. 'deps = [ "//clank/target:test" ]'
  1154. ]),
  1155. MockAffectedFile('chrome/chrome_java_deps.gni', [
  1156. 'java_deps = [',
  1157. ' "//clank/target:test",',
  1158. ']'
  1159. ]),
  1160. ]
  1161. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
  1162. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1163. mock_input_api, mock_output_api)
  1164. self.assertEqual(1, len(msgs),
  1165. 'Expected %d items, found %d: %s'
  1166. % (1, len(msgs), msgs))
  1167. self.assertEqual(3, len(msgs[0].items),
  1168. 'Expected %d items, found %d: %s'
  1169. % (3, len(msgs[0].items), msgs[0].items))
  1170. self.assertTrue(any('BUILD.gn:2' in item for item in msgs[0].items),
  1171. 'BUILD.gn not found in errors')
  1172. self.assertTrue(
  1173. any('chrome/android/BUILD.gn:1' in item for item in msgs[0].items),
  1174. 'chrome/android/BUILD.gn:1 not found in errors')
  1175. self.assertTrue(
  1176. any('chrome/chrome_java_deps.gni:2' in item for item in msgs[0].items),
  1177. 'chrome/chrome_java_deps.gni:2 not found in errors')
  1178. def testAllowsComments(self):
  1179. mock_input_api = MockInputApi()
  1180. mock_output_api = MockOutputApi()
  1181. mock_input_api.files = [
  1182. MockAffectedFile('BUILD.gn', [
  1183. '# real implementation in //clank/target:test',
  1184. ]),
  1185. ]
  1186. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
  1187. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1188. mock_input_api, mock_output_api)
  1189. self.assertEqual(0, len(msgs),
  1190. 'Expected %d items, found %d: %s'
  1191. % (0, len(msgs), msgs))
  1192. def testOnlyChecksBuildFiles(self):
  1193. mock_input_api = MockInputApi()
  1194. mock_output_api = MockOutputApi()
  1195. mock_input_api.files = [
  1196. MockAffectedFile('README.md', [
  1197. 'DEPS = [ "//clank/target:test" ]'
  1198. ]),
  1199. MockAffectedFile('chrome/android/java/file.java', [
  1200. '//clank/ only function'
  1201. ]),
  1202. ]
  1203. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
  1204. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1205. mock_input_api, mock_output_api)
  1206. self.assertEqual(0, len(msgs),
  1207. 'Expected %d items, found %d: %s'
  1208. % (0, len(msgs), msgs))
  1209. def testValidDepFromDownstream(self):
  1210. mock_input_api = MockInputApi()
  1211. mock_output_api = MockOutputApi()
  1212. mock_input_api.files = [
  1213. MockAffectedFile('BUILD.gn', [
  1214. 'DEPS = [',
  1215. ' "//clank/target:test",',
  1216. ']'
  1217. ]),
  1218. MockAffectedFile('java/BUILD.gn', [
  1219. 'DEPS = [ "//clank/target:test" ]'
  1220. ]),
  1221. ]
  1222. mock_input_api.change.RepositoryRoot = lambda: 'chromium/src/clank'
  1223. msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
  1224. mock_input_api, mock_output_api)
  1225. self.assertEqual(0, len(msgs),
  1226. 'Expected %d items, found %d: %s'
  1227. % (0, len(msgs), msgs))
  1228. class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
  1229. def testCheckAndroidTestJUnitFramework(self):
  1230. mock_input_api = MockInputApi()
  1231. mock_output_api = MockOutputApi()
  1232. mock_input_api.files = [
  1233. MockAffectedFile('LalaLand.java', [
  1234. 'random stuff'
  1235. ]),
  1236. MockAffectedFile('CorrectUsage.java', [
  1237. 'import org.junit.ABC',
  1238. 'import org.junit.XYZ;',
  1239. ]),
  1240. MockAffectedFile('UsedDeprecatedJUnit.java', [
  1241. 'import junit.framework.*;',
  1242. ]),
  1243. MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
  1244. 'import junit.framework.Assert;',
  1245. ]),
  1246. ]
  1247. msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
  1248. mock_input_api, mock_output_api)
  1249. self.assertEqual(1, len(msgs),
  1250. 'Expected %d items, found %d: %s'
  1251. % (1, len(msgs), msgs))
  1252. self.assertEqual(2, len(msgs[0].items),
  1253. 'Expected %d items, found %d: %s'
  1254. % (2, len(msgs[0].items), msgs[0].items))
  1255. self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
  1256. 'UsedDeprecatedJUnit.java not found in errors')
  1257. self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
  1258. in msgs[0].items,
  1259. 'UsedDeprecatedJUnitAssert not found in errors')
  1260. class AndroidJUnitBaseClassTest(unittest.TestCase):
  1261. def testCheckAndroidTestJUnitBaseClass(self):
  1262. mock_input_api = MockInputApi()
  1263. mock_output_api = MockOutputApi()
  1264. mock_input_api.files = [
  1265. MockAffectedFile('LalaLand.java', [
  1266. 'random stuff'
  1267. ]),
  1268. MockAffectedFile('CorrectTest.java', [
  1269. '@RunWith(ABC.class);'
  1270. 'public class CorrectTest {',
  1271. '}',
  1272. ]),
  1273. MockAffectedFile('HistoricallyIncorrectTest.java', [
  1274. 'public class Test extends BaseCaseA {',
  1275. '}',
  1276. ], old_contents=[
  1277. 'public class Test extends BaseCaseB {',
  1278. '}',
  1279. ]),
  1280. MockAffectedFile('CorrectTestWithInterface.java', [
  1281. '@RunWith(ABC.class);'
  1282. 'public class CorrectTest implement Interface {',
  1283. '}',
  1284. ]),
  1285. MockAffectedFile('IncorrectTest.java', [
  1286. 'public class IncorrectTest extends TestCase {',
  1287. '}',
  1288. ]),
  1289. MockAffectedFile('IncorrectWithInterfaceTest.java', [
  1290. 'public class Test implements X extends BaseClass {',
  1291. '}',
  1292. ]),
  1293. MockAffectedFile('IncorrectMultiLineTest.java', [
  1294. 'public class Test implements X, Y, Z',
  1295. ' extends TestBase {',
  1296. '}',
  1297. ]),
  1298. ]
  1299. msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
  1300. mock_input_api, mock_output_api)
  1301. self.assertEqual(1, len(msgs),
  1302. 'Expected %d items, found %d: %s'
  1303. % (1, len(msgs), msgs))
  1304. self.assertEqual(3, len(msgs[0].items),
  1305. 'Expected %d items, found %d: %s'
  1306. % (3, len(msgs[0].items), msgs[0].items))
  1307. self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
  1308. 'IncorrectTest not found in errors')
  1309. self.assertTrue('IncorrectWithInterfaceTest.java:1'
  1310. in msgs[0].items,
  1311. 'IncorrectWithInterfaceTest not found in errors')
  1312. self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
  1313. 'IncorrectMultiLineTest not found in errors')
  1314. class AndroidDebuggableBuildTest(unittest.TestCase):
  1315. def testCheckAndroidDebuggableBuild(self):
  1316. mock_input_api = MockInputApi()
  1317. mock_output_api = MockOutputApi()
  1318. mock_input_api.files = [
  1319. MockAffectedFile('RandomStuff.java', [
  1320. 'random stuff'
  1321. ]),
  1322. MockAffectedFile('CorrectUsage.java', [
  1323. 'import org.chromium.base.BuildInfo;',
  1324. 'some random stuff',
  1325. 'boolean isOsDebuggable = BuildInfo.isDebugAndroid();',
  1326. ]),
  1327. MockAffectedFile('JustCheckUserdebugBuild.java', [
  1328. 'import android.os.Build;',
  1329. 'some random stuff',
  1330. 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")',
  1331. ]),
  1332. MockAffectedFile('JustCheckEngineeringBuild.java', [
  1333. 'import android.os.Build;',
  1334. 'some random stuff',
  1335. 'boolean isOsDebuggable = "eng".equals(Build.TYPE)',
  1336. ]),
  1337. MockAffectedFile('UsedBuildType.java', [
  1338. 'import android.os.Build;',
  1339. 'some random stuff',
  1340. 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")'
  1341. '|| "eng".equals(Build.TYPE)',
  1342. ]),
  1343. MockAffectedFile('UsedExplicitBuildType.java', [
  1344. 'some random stuff',
  1345. 'boolean isOsDebuggable = android.os.Build.TYPE.equals("userdebug")'
  1346. '|| "eng".equals(android.os.Build.TYPE)',
  1347. ]),
  1348. ]
  1349. msgs = PRESUBMIT._CheckAndroidDebuggableBuild(
  1350. mock_input_api, mock_output_api)
  1351. self.assertEqual(1, len(msgs),
  1352. 'Expected %d items, found %d: %s'
  1353. % (1, len(msgs), msgs))
  1354. self.assertEqual(4, len(msgs[0].items),
  1355. 'Expected %d items, found %d: %s'
  1356. % (4, len(msgs[0].items), msgs[0].items))
  1357. self.assertTrue('JustCheckUserdebugBuild.java:3' in msgs[0].items)
  1358. self.assertTrue('JustCheckEngineeringBuild.java:3' in msgs[0].items)
  1359. self.assertTrue('UsedBuildType.java:3' in msgs[0].items)
  1360. self.assertTrue('UsedExplicitBuildType.java:2' in msgs[0].items)
  1361. class LogUsageTest(unittest.TestCase):
  1362. def testCheckAndroidCrLogUsage(self):
  1363. mock_input_api = MockInputApi()
  1364. mock_output_api = MockOutputApi()
  1365. mock_input_api.files = [
  1366. MockAffectedFile('RandomStuff.java', [
  1367. 'random stuff'
  1368. ]),
  1369. MockAffectedFile('HasAndroidLog.java', [
  1370. 'import android.util.Log;',
  1371. 'some random stuff',
  1372. 'Log.d("TAG", "foo");',
  1373. ]),
  1374. MockAffectedFile('HasExplicitUtilLog.java', [
  1375. 'some random stuff',
  1376. 'android.util.Log.d("TAG", "foo");',
  1377. ]),
  1378. MockAffectedFile('IsInBasePackage.java', [
  1379. 'package org.chromium.base;',
  1380. 'private static final String TAG = "cr_Foo";',
  1381. 'Log.d(TAG, "foo");',
  1382. ]),
  1383. MockAffectedFile('IsInBasePackageButImportsLog.java', [
  1384. 'package org.chromium.base;',
  1385. 'import android.util.Log;',
  1386. 'private static final String TAG = "cr_Foo";',
  1387. 'Log.d(TAG, "foo");',
  1388. ]),
  1389. MockAffectedFile('HasBothLog.java', [
  1390. 'import org.chromium.base.Log;',
  1391. 'some random stuff',
  1392. 'private static final String TAG = "cr_Foo";',
  1393. 'Log.d(TAG, "foo");',
  1394. 'android.util.Log.d("TAG", "foo");',
  1395. ]),
  1396. MockAffectedFile('HasCorrectTag.java', [
  1397. 'import org.chromium.base.Log;',
  1398. 'some random stuff',
  1399. 'private static final String TAG = "cr_Foo";',
  1400. 'Log.d(TAG, "foo");',
  1401. ]),
  1402. MockAffectedFile('HasOldTag.java', [
  1403. 'import org.chromium.base.Log;',
  1404. 'some random stuff',
  1405. 'private static final String TAG = "cr.Foo";',
  1406. 'Log.d(TAG, "foo");',
  1407. ]),
  1408. MockAffectedFile('HasDottedTag.java', [
  1409. 'import org.chromium.base.Log;',
  1410. 'some random stuff',
  1411. 'private static final String TAG = "cr_foo.bar";',
  1412. 'Log.d(TAG, "foo");',
  1413. ]),
  1414. MockAffectedFile('HasDottedTagPublic.java', [
  1415. 'import org.chromium.base.Log;',
  1416. 'some random stuff',
  1417. 'public static final String TAG = "cr_foo.bar";',
  1418. 'Log.d(TAG, "foo");',
  1419. ]),
  1420. MockAffectedFile('HasNoTagDecl.java', [
  1421. 'import org.chromium.base.Log;',
  1422. 'some random stuff',
  1423. 'Log.d(TAG, "foo");',
  1424. ]),
  1425. MockAffectedFile('HasIncorrectTagDecl.java', [
  1426. 'import org.chromium.base.Log;',
  1427. 'private static final String TAHG = "cr_Foo";',
  1428. 'some random stuff',
  1429. 'Log.d(TAG, "foo");',
  1430. ]),
  1431. MockAffectedFile('HasInlineTag.java', [
  1432. 'import org.chromium.base.Log;',
  1433. 'some random stuff',
  1434. 'private static final String TAG = "cr_Foo";',
  1435. 'Log.d("TAG", "foo");',
  1436. ]),
  1437. MockAffectedFile('HasInlineTagWithSpace.java', [
  1438. 'import org.chromium.base.Log;',
  1439. 'some random stuff',
  1440. 'private static final String TAG = "cr_Foo";',
  1441. 'Log.d("log message", "foo");',
  1442. ]),
  1443. MockAffectedFile('HasUnprefixedTag.java', [
  1444. 'import org.chromium.base.Log;',
  1445. 'some random stuff',
  1446. 'private static final String TAG = "rubbish";',
  1447. 'Log.d(TAG, "foo");',
  1448. ]),
  1449. MockAffectedFile('HasTooLongTag.java', [
  1450. 'import org.chromium.base.Log;',
  1451. 'some random stuff',
  1452. 'private static final String TAG = "21_charachers_long___";',
  1453. 'Log.d(TAG, "foo");',
  1454. ]),
  1455. MockAffectedFile('HasTooLongTagWithNoLogCallsInDiff.java', [
  1456. 'import org.chromium.base.Log;',
  1457. 'some random stuff',
  1458. 'private static final String TAG = "21_charachers_long___";',
  1459. ]),
  1460. ]
  1461. msgs = PRESUBMIT._CheckAndroidCrLogUsage(
  1462. mock_input_api, mock_output_api)
  1463. self.assertEqual(5, len(msgs),
  1464. 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
  1465. # Declaration format
  1466. nb = len(msgs[0].items)
  1467. self.assertEqual(2, nb,
  1468. 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
  1469. self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
  1470. self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
  1471. # Tag length
  1472. nb = len(msgs[1].items)
  1473. self.assertEqual(2, nb,
  1474. 'Expected %d items, found %d: %s' % (2, nb, msgs[1].items))
  1475. self.assertTrue('HasTooLongTag.java' in msgs[1].items)
  1476. self.assertTrue('HasTooLongTagWithNoLogCallsInDiff.java' in msgs[1].items)
  1477. # Tag must be a variable named TAG
  1478. nb = len(msgs[2].items)
  1479. self.assertEqual(3, nb,
  1480. 'Expected %d items, found %d: %s' % (3, nb, msgs[2].items))
  1481. self.assertTrue('HasBothLog.java:5' in msgs[2].items)
  1482. self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
  1483. self.assertTrue('HasInlineTagWithSpace.java:4' in msgs[2].items)
  1484. # Util Log usage
  1485. nb = len(msgs[3].items)
  1486. self.assertEqual(3, nb,
  1487. 'Expected %d items, found %d: %s' % (3, nb, msgs[3].items))
  1488. self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
  1489. self.assertTrue('HasExplicitUtilLog.java:2' in msgs[3].items)
  1490. self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
  1491. # Tag must not contain
  1492. nb = len(msgs[4].items)
  1493. self.assertEqual(3, nb,
  1494. 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
  1495. self.assertTrue('HasDottedTag.java' in msgs[4].items)
  1496. self.assertTrue('HasDottedTagPublic.java' in msgs[4].items)
  1497. self.assertTrue('HasOldTag.java' in msgs[4].items)
  1498. class GoogleAnswerUrlFormatTest(unittest.TestCase):
  1499. def testCatchAnswerUrlId(self):
  1500. input_api = MockInputApi()
  1501. input_api.files = [
  1502. MockFile('somewhere/file.cc',
  1503. ['char* host = '
  1504. ' "https://support.google.com/chrome/answer/123456";']),
  1505. MockFile('somewhere_else/file.cc',
  1506. ['char* host = '
  1507. ' "https://support.google.com/chrome/a/answer/123456";']),
  1508. ]
  1509. warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
  1510. input_api, MockOutputApi())
  1511. self.assertEqual(1, len(warnings))
  1512. self.assertEqual(2, len(warnings[0].items))
  1513. def testAllowAnswerUrlParam(self):
  1514. input_api = MockInputApi()
  1515. input_api.files = [
  1516. MockFile('somewhere/file.cc',
  1517. ['char* host = '
  1518. ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
  1519. ]
  1520. warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
  1521. input_api, MockOutputApi())
  1522. self.assertEqual(0, len(warnings))
  1523. class HardcodedGoogleHostsTest(unittest.TestCase):
  1524. def testWarnOnAssignedLiterals(self):
  1525. input_api = MockInputApi()
  1526. input_api.files = [
  1527. MockFile('content/file.cc',
  1528. ['char* host = "https://www.google.com";']),
  1529. MockFile('content/file.cc',
  1530. ['char* host = "https://www.googleapis.com";']),
  1531. MockFile('content/file.cc',
  1532. ['char* host = "https://clients1.google.com";']),
  1533. ]
  1534. warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
  1535. input_api, MockOutputApi())
  1536. self.assertEqual(1, len(warnings))
  1537. self.assertEqual(3, len(warnings[0].items))
  1538. def testAllowInComment(self):
  1539. input_api = MockInputApi()
  1540. input_api.files = [
  1541. MockFile('content/file.cc',
  1542. ['char* host = "https://www.aol.com"; // google.com'])
  1543. ]
  1544. warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
  1545. input_api, MockOutputApi())
  1546. self.assertEqual(0, len(warnings))
  1547. class ChromeOsSyncedPrefRegistrationTest(unittest.TestCase):
  1548. def testWarnsOnChromeOsDirectories(self):
  1549. files = [
  1550. MockFile('ash/file.cc',
  1551. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1552. MockFile('chrome/browser/chromeos/file.cc',
  1553. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1554. MockFile('chromeos/file.cc',
  1555. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1556. MockFile('components/arc/file.cc',
  1557. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1558. MockFile('components/exo/file.cc',
  1559. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1560. ]
  1561. input_api = MockInputApi()
  1562. for file in files:
  1563. input_api.files = [file]
  1564. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1565. input_api, MockOutputApi())
  1566. self.assertEqual(1, len(warnings))
  1567. def testDoesNotWarnOnSyncOsPref(self):
  1568. input_api = MockInputApi()
  1569. input_api.files = [
  1570. MockFile('chromeos/file.cc',
  1571. ['PrefRegistrySyncable::SYNCABLE_OS_PREF']),
  1572. ]
  1573. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1574. input_api, MockOutputApi())
  1575. self.assertEqual(0, len(warnings))
  1576. def testDoesNotWarnOnOtherDirectories(self):
  1577. input_api = MockInputApi()
  1578. input_api.files = [
  1579. MockFile('chrome/browser/ui/file.cc',
  1580. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1581. MockFile('components/sync/file.cc',
  1582. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1583. MockFile('content/browser/file.cc',
  1584. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1585. MockFile('a/notchromeos/file.cc',
  1586. ['PrefRegistrySyncable::SYNCABLE_PREF']),
  1587. ]
  1588. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1589. input_api, MockOutputApi())
  1590. self.assertEqual(0, len(warnings))
  1591. def testSeparateWarningForPriorityPrefs(self):
  1592. input_api = MockInputApi()
  1593. input_api.files = [
  1594. MockFile('chromeos/file.cc',
  1595. ['PrefRegistrySyncable::SYNCABLE_PREF',
  1596. 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF']),
  1597. ]
  1598. warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
  1599. input_api, MockOutputApi())
  1600. self.assertEqual(2, len(warnings))
  1601. class ForwardDeclarationTest(unittest.TestCase):
  1602. def testCheckHeadersOnlyOutsideThirdParty(self):
  1603. mock_input_api = MockInputApi()
  1604. mock_input_api.files = [
  1605. MockAffectedFile('somewhere/file.cc', [
  1606. 'class DummyClass;'
  1607. ]),
  1608. MockAffectedFile('third_party/header.h', [
  1609. 'class DummyClass;'
  1610. ])
  1611. ]
  1612. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1613. MockOutputApi())
  1614. self.assertEqual(0, len(warnings))
  1615. def testNoNestedDeclaration(self):
  1616. mock_input_api = MockInputApi()
  1617. mock_input_api.files = [
  1618. MockAffectedFile('somewhere/header.h', [
  1619. 'class SomeClass {',
  1620. ' protected:',
  1621. ' class NotAMatch;',
  1622. '};'
  1623. ])
  1624. ]
  1625. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1626. MockOutputApi())
  1627. self.assertEqual(0, len(warnings))
  1628. def testSubStrings(self):
  1629. mock_input_api = MockInputApi()
  1630. mock_input_api.files = [
  1631. MockAffectedFile('somewhere/header.h', [
  1632. 'class NotUsefulClass;',
  1633. 'struct SomeStruct;',
  1634. 'UsefulClass *p1;',
  1635. 'SomeStructPtr *p2;'
  1636. ])
  1637. ]
  1638. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1639. MockOutputApi())
  1640. self.assertEqual(2, len(warnings))
  1641. def testUselessForwardDeclaration(self):
  1642. mock_input_api = MockInputApi()
  1643. mock_input_api.files = [
  1644. MockAffectedFile('somewhere/header.h', [
  1645. 'class DummyClass;',
  1646. 'struct DummyStruct;',
  1647. 'class UsefulClass;',
  1648. 'std::unique_ptr<UsefulClass> p;'
  1649. ])
  1650. ]
  1651. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1652. MockOutputApi())
  1653. self.assertEqual(2, len(warnings))
  1654. def testBlinkHeaders(self):
  1655. mock_input_api = MockInputApi()
  1656. mock_input_api.files = [
  1657. MockAffectedFile('third_party/blink/header.h', [
  1658. 'class DummyClass;',
  1659. 'struct DummyStruct;',
  1660. ]),
  1661. MockAffectedFile('third_party\\blink\\header.h', [
  1662. 'class DummyClass;',
  1663. 'struct DummyStruct;',
  1664. ])
  1665. ]
  1666. warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
  1667. MockOutputApi())
  1668. self.assertEqual(4, len(warnings))
  1669. class RelativeIncludesTest(unittest.TestCase):
  1670. def testThirdPartyNotWebKitIgnored(self):
  1671. mock_input_api = MockInputApi()
  1672. mock_input_api.files = [
  1673. MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
  1674. MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
  1675. ]
  1676. mock_output_api = MockOutputApi()
  1677. errors = PRESUBMIT.CheckForRelativeIncludes(
  1678. mock_input_api, mock_output_api)
  1679. self.assertEqual(0, len(errors))
  1680. def testNonCppFileIgnored(self):
  1681. mock_input_api = MockInputApi()
  1682. mock_input_api.files = [
  1683. MockAffectedFile('test.py', '#include "../header.h"'),
  1684. ]
  1685. mock_output_api = MockOutputApi()
  1686. errors = PRESUBMIT.CheckForRelativeIncludes(
  1687. mock_input_api, mock_output_api)
  1688. self.assertEqual(0, len(errors))
  1689. def testInnocuousChangesAllowed(self):
  1690. mock_input_api = MockInputApi()
  1691. mock_input_api.files = [
  1692. MockAffectedFile('test.cpp', '#include "header.h"'),
  1693. MockAffectedFile('test2.cpp', '../'),
  1694. ]
  1695. mock_output_api = MockOutputApi()
  1696. errors = PRESUBMIT.CheckForRelativeIncludes(
  1697. mock_input_api, mock_output_api)
  1698. self.assertEqual(0, len(errors))
  1699. def testRelativeIncludeNonWebKitProducesError(self):
  1700. mock_input_api = MockInputApi()
  1701. mock_input_api.files = [
  1702. MockAffectedFile('test.cpp', ['#include "../header.h"']),
  1703. ]
  1704. mock_output_api = MockOutputApi()
  1705. errors = PRESUBMIT.CheckForRelativeIncludes(
  1706. mock_input_api, mock_output_api)
  1707. self.assertEqual(1, len(errors))
  1708. def testRelativeIncludeWebKitProducesError(self):
  1709. mock_input_api = MockInputApi()
  1710. mock_input_api.files = [
  1711. MockAffectedFile('third_party/blink/test.cpp',
  1712. ['#include "../header.h']),
  1713. ]
  1714. mock_output_api = MockOutputApi()
  1715. errors = PRESUBMIT.CheckForRelativeIncludes(
  1716. mock_input_api, mock_output_api)
  1717. self.assertEqual(1, len(errors))
  1718. class CCIncludeTest(unittest.TestCase):
  1719. def testThirdPartyNotBlinkIgnored(self):
  1720. mock_input_api = MockInputApi()
  1721. mock_input_api.files = [
  1722. MockAffectedFile('third_party/test.cpp', '#include "file.cc"'),
  1723. ]
  1724. mock_output_api = MockOutputApi()
  1725. errors = PRESUBMIT.CheckForCcIncludes(
  1726. mock_input_api, mock_output_api)
  1727. self.assertEqual(0, len(errors))
  1728. def testPythonFileIgnored(self):
  1729. mock_input_api = MockInputApi()
  1730. mock_input_api.files = [
  1731. MockAffectedFile('test.py', '#include "file.cc"'),
  1732. ]
  1733. mock_output_api = MockOutputApi()
  1734. errors = PRESUBMIT.CheckForCcIncludes(
  1735. mock_input_api, mock_output_api)
  1736. self.assertEqual(0, len(errors))
  1737. def testIncFilesAccepted(self):
  1738. mock_input_api = MockInputApi()
  1739. mock_input_api.files = [
  1740. MockAffectedFile('test.py', '#include "file.inc"'),
  1741. ]
  1742. mock_output_api = MockOutputApi()
  1743. errors = PRESUBMIT.CheckForCcIncludes(
  1744. mock_input_api, mock_output_api)
  1745. self.assertEqual(0, len(errors))
  1746. def testInnocuousChangesAllowed(self):
  1747. mock_input_api = MockInputApi()
  1748. mock_input_api.files = [
  1749. MockAffectedFile('test.cpp', '#include "header.h"'),
  1750. MockAffectedFile('test2.cpp', 'Something "file.cc"'),
  1751. ]
  1752. mock_output_api = MockOutputApi()
  1753. errors = PRESUBMIT.CheckForCcIncludes(
  1754. mock_input_api, mock_output_api)
  1755. self.assertEqual(0, len(errors))
  1756. def testCcIncludeNonBlinkProducesError(self):
  1757. mock_input_api = MockInputApi()
  1758. mock_input_api.files = [
  1759. MockAffectedFile('test.cpp', ['#include "file.cc"']),
  1760. ]
  1761. mock_output_api = MockOutputApi()
  1762. errors = PRESUBMIT.CheckForCcIncludes(
  1763. mock_input_api, mock_output_api)
  1764. self.assertEqual(1, len(errors))
  1765. def testCppIncludeBlinkProducesError(self):
  1766. mock_input_api = MockInputApi()
  1767. mock_input_api.files = [
  1768. MockAffectedFile('third_party/blink/test.cpp',
  1769. ['#include "foo/file.cpp"']),
  1770. ]
  1771. mock_output_api = MockOutputApi()
  1772. errors = PRESUBMIT.CheckForCcIncludes(
  1773. mock_input_api, mock_output_api)
  1774. self.assertEqual(1, len(errors))
  1775. class GnGlobForwardTest(unittest.TestCase):
  1776. def testAddBareGlobs(self):
  1777. mock_input_api = MockInputApi()
  1778. mock_input_api.files = [
  1779. MockAffectedFile('base/stuff.gni', [
  1780. 'forward_variables_from(invoker, "*")']),
  1781. MockAffectedFile('base/BUILD.gn', [
  1782. 'forward_variables_from(invoker, "*")']),
  1783. ]
  1784. warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api, MockOutputApi())
  1785. self.assertEqual(1, len(warnings))
  1786. msg = '\n'.join(warnings[0].items)
  1787. self.assertIn('base/stuff.gni', msg)
  1788. # Should not check .gn files. Local templates don't need to care about
  1789. # visibility / testonly.
  1790. self.assertNotIn('base/BUILD.gn', msg)
  1791. def testValidUses(self):
  1792. mock_input_api = MockInputApi()
  1793. mock_input_api.files = [
  1794. MockAffectedFile('base/stuff.gni', [
  1795. 'forward_variables_from(invoker, "*", [])']),
  1796. MockAffectedFile('base/stuff2.gni', [
  1797. 'forward_variables_from(invoker, "*", TESTONLY_AND_VISIBILITY)']),
  1798. MockAffectedFile('base/stuff3.gni', [
  1799. 'forward_variables_from(invoker, [ "testonly" ])']),
  1800. ]
  1801. warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api, MockOutputApi())
  1802. self.assertEqual([], warnings)
  1803. class NewHeaderWithoutGnChangeTest(unittest.TestCase):
  1804. def testAddHeaderWithoutGn(self):
  1805. mock_input_api = MockInputApi()
  1806. mock_input_api.files = [
  1807. MockAffectedFile('base/stuff.h', ''),
  1808. ]
  1809. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1810. mock_input_api, MockOutputApi())
  1811. self.assertEqual(1, len(warnings))
  1812. self.assertTrue('base/stuff.h' in warnings[0].items)
  1813. def testModifyHeader(self):
  1814. mock_input_api = MockInputApi()
  1815. mock_input_api.files = [
  1816. MockAffectedFile('base/stuff.h', '', action='M'),
  1817. ]
  1818. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1819. mock_input_api, MockOutputApi())
  1820. self.assertEqual(0, len(warnings))
  1821. def testDeleteHeader(self):
  1822. mock_input_api = MockInputApi()
  1823. mock_input_api.files = [
  1824. MockAffectedFile('base/stuff.h', '', action='D'),
  1825. ]
  1826. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1827. mock_input_api, MockOutputApi())
  1828. self.assertEqual(0, len(warnings))
  1829. def testAddHeaderWithGn(self):
  1830. mock_input_api = MockInputApi()
  1831. mock_input_api.files = [
  1832. MockAffectedFile('base/stuff.h', ''),
  1833. MockAffectedFile('base/BUILD.gn', 'stuff.h'),
  1834. ]
  1835. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1836. mock_input_api, MockOutputApi())
  1837. self.assertEqual(0, len(warnings))
  1838. def testAddHeaderWithGni(self):
  1839. mock_input_api = MockInputApi()
  1840. mock_input_api.files = [
  1841. MockAffectedFile('base/stuff.h', ''),
  1842. MockAffectedFile('base/files.gni', 'stuff.h'),
  1843. ]
  1844. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1845. mock_input_api, MockOutputApi())
  1846. self.assertEqual(0, len(warnings))
  1847. def testAddHeaderWithOther(self):
  1848. mock_input_api = MockInputApi()
  1849. mock_input_api.files = [
  1850. MockAffectedFile('base/stuff.h', ''),
  1851. MockAffectedFile('base/stuff.cc', 'stuff.h'),
  1852. ]
  1853. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1854. mock_input_api, MockOutputApi())
  1855. self.assertEqual(1, len(warnings))
  1856. def testAddHeaderWithWrongGn(self):
  1857. mock_input_api = MockInputApi()
  1858. mock_input_api.files = [
  1859. MockAffectedFile('base/stuff.h', ''),
  1860. MockAffectedFile('base/BUILD.gn', 'stuff_h'),
  1861. ]
  1862. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1863. mock_input_api, MockOutputApi())
  1864. self.assertEqual(1, len(warnings))
  1865. def testAddHeadersWithGn(self):
  1866. mock_input_api = MockInputApi()
  1867. mock_input_api.files = [
  1868. MockAffectedFile('base/stuff.h', ''),
  1869. MockAffectedFile('base/another.h', ''),
  1870. MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
  1871. ]
  1872. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1873. mock_input_api, MockOutputApi())
  1874. self.assertEqual(0, len(warnings))
  1875. def testAddHeadersWithWrongGn(self):
  1876. mock_input_api = MockInputApi()
  1877. mock_input_api.files = [
  1878. MockAffectedFile('base/stuff.h', ''),
  1879. MockAffectedFile('base/another.h', ''),
  1880. MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
  1881. ]
  1882. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1883. mock_input_api, MockOutputApi())
  1884. self.assertEqual(1, len(warnings))
  1885. self.assertFalse('base/stuff.h' in warnings[0].items)
  1886. self.assertTrue('base/another.h' in warnings[0].items)
  1887. def testAddHeadersWithWrongGn2(self):
  1888. mock_input_api = MockInputApi()
  1889. mock_input_api.files = [
  1890. MockAffectedFile('base/stuff.h', ''),
  1891. MockAffectedFile('base/another.h', ''),
  1892. MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
  1893. ]
  1894. warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
  1895. mock_input_api, MockOutputApi())
  1896. self.assertEqual(1, len(warnings))
  1897. self.assertTrue('base/stuff.h' in warnings[0].items)
  1898. self.assertTrue('base/another.h' in warnings[0].items)
  1899. class CorrectProductNameInMessagesTest(unittest.TestCase):
  1900. def testProductNameInDesc(self):
  1901. mock_input_api = MockInputApi()
  1902. mock_input_api.files = [
  1903. MockAffectedFile('chrome/app/google_chrome_strings.grd', [
  1904. '<message name="Foo" desc="Welcome to Chrome">',
  1905. ' Welcome to Chrome!',
  1906. '</message>',
  1907. ]),
  1908. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1909. '<message name="Bar" desc="Welcome to Chrome">',
  1910. ' Welcome to Chromium!',
  1911. '</message>',
  1912. ]),
  1913. ]
  1914. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1915. mock_input_api, MockOutputApi())
  1916. self.assertEqual(0, len(warnings))
  1917. def testChromeInChromium(self):
  1918. mock_input_api = MockInputApi()
  1919. mock_input_api.files = [
  1920. MockAffectedFile('chrome/app/google_chrome_strings.grd', [
  1921. '<message name="Foo" desc="Welcome to Chrome">',
  1922. ' Welcome to Chrome!',
  1923. '</message>',
  1924. ]),
  1925. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1926. '<message name="Bar" desc="Welcome to Chrome">',
  1927. ' Welcome to Chrome!',
  1928. '</message>',
  1929. ]),
  1930. ]
  1931. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1932. mock_input_api, MockOutputApi())
  1933. self.assertEqual(1, len(warnings))
  1934. self.assertTrue('chrome/app/chromium_strings.grd' in warnings[0].items[0])
  1935. def testChromiumInChrome(self):
  1936. mock_input_api = MockInputApi()
  1937. mock_input_api.files = [
  1938. MockAffectedFile('chrome/app/google_chrome_strings.grd', [
  1939. '<message name="Foo" desc="Welcome to Chrome">',
  1940. ' Welcome to Chromium!',
  1941. '</message>',
  1942. ]),
  1943. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1944. '<message name="Bar" desc="Welcome to Chrome">',
  1945. ' Welcome to Chromium!',
  1946. '</message>',
  1947. ]),
  1948. ]
  1949. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1950. mock_input_api, MockOutputApi())
  1951. self.assertEqual(1, len(warnings))
  1952. self.assertTrue(
  1953. 'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
  1954. def testMultipleInstances(self):
  1955. mock_input_api = MockInputApi()
  1956. mock_input_api.files = [
  1957. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1958. '<message name="Bar" desc="Welcome to Chrome">',
  1959. ' Welcome to Chrome!',
  1960. '</message>',
  1961. '<message name="Baz" desc="A correct message">',
  1962. ' Chromium is the software you are using.',
  1963. '</message>',
  1964. '<message name="Bat" desc="An incorrect message">',
  1965. ' Google Chrome is the software you are using.',
  1966. '</message>',
  1967. ]),
  1968. ]
  1969. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  1970. mock_input_api, MockOutputApi())
  1971. self.assertEqual(1, len(warnings))
  1972. self.assertTrue(
  1973. 'chrome/app/chromium_strings.grd:2' in warnings[0].items[0])
  1974. self.assertTrue(
  1975. 'chrome/app/chromium_strings.grd:8' in warnings[0].items[1])
  1976. def testMultipleWarnings(self):
  1977. mock_input_api = MockInputApi()
  1978. mock_input_api.files = [
  1979. MockAffectedFile('chrome/app/chromium_strings.grd', [
  1980. '<message name="Bar" desc="Welcome to Chrome">',
  1981. ' Welcome to Chrome!',
  1982. '</message>',
  1983. '<message name="Baz" desc="A correct message">',
  1984. ' Chromium is the software you are using.',
  1985. '</message>',
  1986. '<message name="Bat" desc="An incorrect message">',
  1987. ' Google Chrome is the software you are using.',
  1988. '</message>',
  1989. ]),
  1990. MockAffectedFile('components/components_google_chrome_strings.grd', [
  1991. '<message name="Bar" desc="Welcome to Chrome">',
  1992. ' Welcome to Chrome!',
  1993. '</message>',
  1994. '<message name="Baz" desc="A correct message">',
  1995. ' Chromium is the software you are using.',
  1996. '</message>',
  1997. '<message name="Bat" desc="An incorrect message">',
  1998. ' Google Chrome is the software you are using.',
  1999. '</message>',
  2000. ]),
  2001. ]
  2002. warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
  2003. mock_input_api, MockOutputApi())
  2004. self.assertEqual(2, len(warnings))
  2005. self.assertTrue(
  2006. 'components/components_google_chrome_strings.grd:5'
  2007. in warnings[0].items[0])
  2008. self.assertTrue(
  2009. 'chrome/app/chromium_strings.grd:2' in warnings[1].items[0])
  2010. self.assertTrue(
  2011. 'chrome/app/chromium_strings.grd:8' in warnings[1].items[1])
  2012. class ServiceManifestOwnerTest(unittest.TestCase):
  2013. def testServiceManifestChangeNeedsSecurityOwner(self):
  2014. mock_input_api = MockInputApi()
  2015. mock_input_api.files = [
  2016. MockAffectedFile('services/goat/public/cpp/manifest.cc',
  2017. [
  2018. '#include "services/goat/public/cpp/manifest.h"',
  2019. 'const service_manager::Manifest& GetManifest() {}',
  2020. ])]
  2021. mock_output_api = MockOutputApi()
  2022. errors = PRESUBMIT.CheckSecurityOwners(
  2023. mock_input_api, mock_output_api)
  2024. self.assertEqual(1, len(errors))
  2025. self.assertEqual(
  2026. 'Found OWNERS files that need to be updated for IPC security review ' +
  2027. 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
  2028. def testNonServiceManifestSourceChangesDoNotRequireSecurityOwner(self):
  2029. mock_input_api = MockInputApi()
  2030. mock_input_api.files = [
  2031. MockAffectedFile('some/non/service/thing/foo_manifest.cc',
  2032. [
  2033. 'const char kNoEnforcement[] = "not a manifest!";',
  2034. ])]
  2035. mock_output_api = MockOutputApi()
  2036. errors = PRESUBMIT.CheckSecurityOwners(
  2037. mock_input_api, mock_output_api)
  2038. self.assertEqual([], errors)
  2039. class FuchsiaSecurityOwnerTest(unittest.TestCase):
  2040. def testFidlChangeNeedsSecurityOwner(self):
  2041. mock_input_api = MockInputApi()
  2042. mock_input_api.files = [
  2043. MockAffectedFile('potentially/scary/ipc.fidl',
  2044. [
  2045. 'library test.fidl'
  2046. ])]
  2047. mock_output_api = MockOutputApi()
  2048. errors = PRESUBMIT.CheckSecurityOwners(
  2049. mock_input_api, mock_output_api)
  2050. self.assertEqual(1, len(errors))
  2051. self.assertEqual(
  2052. 'Found OWNERS files that need to be updated for IPC security review ' +
  2053. 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
  2054. def testComponentManifestV1ChangeNeedsSecurityOwner(self):
  2055. mock_input_api = MockInputApi()
  2056. mock_input_api.files = [
  2057. MockAffectedFile('potentially/scary/v2_manifest.cmx',
  2058. [
  2059. '{ "that is no": "manifest!" }'
  2060. ])]
  2061. mock_output_api = MockOutputApi()
  2062. errors = PRESUBMIT.CheckSecurityOwners(
  2063. mock_input_api, mock_output_api)
  2064. self.assertEqual(1, len(errors))
  2065. self.assertEqual(
  2066. 'Found OWNERS files that need to be updated for IPC security review ' +
  2067. 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
  2068. def testComponentManifestV2NeedsSecurityOwner(self):
  2069. mock_input_api = MockInputApi()
  2070. mock_input_api.files = [
  2071. MockAffectedFile('potentially/scary/v2_manifest.cml',
  2072. [
  2073. '{ "that is no": "manifest!" }'
  2074. ])]
  2075. mock_output_api = MockOutputApi()
  2076. errors = PRESUBMIT.CheckSecurityOwners(
  2077. mock_input_api, mock_output_api)
  2078. self.assertEqual(1, len(errors))
  2079. self.assertEqual(
  2080. 'Found OWNERS files that need to be updated for IPC security review ' +
  2081. 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
  2082. def testThirdPartyTestsDoNotRequireSecurityOwner(self):
  2083. mock_input_api = MockInputApi()
  2084. mock_input_api.files = [
  2085. MockAffectedFile('third_party/crashpad/test/tests.cmx',
  2086. [
  2087. 'const char kNoEnforcement[] = "Security?!? Pah!";',
  2088. ])]
  2089. mock_output_api = MockOutputApi()
  2090. errors = PRESUBMIT.CheckSecurityOwners(
  2091. mock_input_api, mock_output_api)
  2092. self.assertEqual([], errors)
  2093. def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self):
  2094. mock_input_api = MockInputApi()
  2095. mock_input_api.files = [
  2096. MockAffectedFile('some/non/service/thing/fuchsia_fidl_cml_cmx_magic.cc',
  2097. [
  2098. 'const char kNoEnforcement[] = "Security?!? Pah!";',
  2099. ])]
  2100. mock_output_api = MockOutputApi()
  2101. errors = PRESUBMIT.CheckSecurityOwners(
  2102. mock_input_api, mock_output_api)
  2103. self.assertEqual([], errors)
  2104. class SecurityChangeTest(unittest.TestCase):
  2105. class _MockOwnersClient(object):
  2106. def ListOwners(self, f):
  2107. return ['apple@chromium.org', 'orange@chromium.org']
  2108. def _mockChangeOwnerAndReviewers(self, input_api, owner, reviewers):
  2109. def __MockOwnerAndReviewers(input_api, email_regexp, approval_needed=False):
  2110. return [owner, reviewers]
  2111. input_api.canned_checks.GetCodereviewOwnerAndReviewers = \
  2112. __MockOwnerAndReviewers
  2113. def testDiffGetServiceSandboxType(self):
  2114. mock_input_api = MockInputApi()
  2115. mock_input_api.files = [
  2116. MockAffectedFile(
  2117. 'services/goat/teleporter_host.cc',
  2118. [
  2119. 'template <>',
  2120. 'inline content::SandboxType',
  2121. 'content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {',
  2122. '#if defined(OS_WIN)',
  2123. ' return SandboxType::kGoaty;',
  2124. '#else',
  2125. ' return SandboxType::kNoSandbox;',
  2126. '#endif // !defined(OS_WIN)',
  2127. '}'
  2128. ]
  2129. ),
  2130. ]
  2131. files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
  2132. mock_input_api)
  2133. self.assertEqual({
  2134. 'services/goat/teleporter_host.cc': set([
  2135. 'content::GetServiceSandboxType<>()'
  2136. ])},
  2137. files_to_functions)
  2138. def testDiffRemovingLine(self):
  2139. mock_input_api = MockInputApi()
  2140. mock_file = MockAffectedFile('services/goat/teleporter_host.cc', '')
  2141. mock_file._scm_diff = """--- old 2020-05-04 14:08:25.000000000 -0400
  2142. +++ new 2020-05-04 14:08:32.000000000 -0400
  2143. @@ -1,5 +1,4 @@
  2144. template <>
  2145. inline content::SandboxType
  2146. -content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {
  2147. #if defined(OS_WIN)
  2148. return SandboxType::kGoaty;
  2149. """
  2150. mock_input_api.files = [mock_file]
  2151. files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
  2152. mock_input_api)
  2153. self.assertEqual({
  2154. 'services/goat/teleporter_host.cc': set([
  2155. 'content::GetServiceSandboxType<>()'
  2156. ])},
  2157. files_to_functions)
  2158. def testChangeOwnersMissing(self):
  2159. mock_input_api = MockInputApi()
  2160. mock_input_api.owners_client = self._MockOwnersClient()
  2161. mock_input_api.is_committing = False
  2162. mock_input_api.files = [
  2163. MockAffectedFile('file.cc', ['GetServiceSandboxType<Goat>(Sandbox)'])
  2164. ]
  2165. mock_output_api = MockOutputApi()
  2166. self._mockChangeOwnerAndReviewers(
  2167. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2168. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2169. self.assertEqual(1, len(result))
  2170. self.assertEqual(result[0].type, 'notify')
  2171. self.assertEqual(result[0].message,
  2172. 'The following files change calls to security-sensive functions\n' \
  2173. 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
  2174. ' file.cc\n'
  2175. ' content::GetServiceSandboxType<>()\n\n')
  2176. def testChangeOwnersMissingAtCommit(self):
  2177. mock_input_api = MockInputApi()
  2178. mock_input_api.owners_client = self._MockOwnersClient()
  2179. mock_input_api.is_committing = True
  2180. mock_input_api.files = [
  2181. MockAffectedFile('file.cc', ['GetServiceSandboxType<mojom::Goat>()'])
  2182. ]
  2183. mock_output_api = MockOutputApi()
  2184. self._mockChangeOwnerAndReviewers(
  2185. mock_input_api, 'owner@chromium.org', ['banana@chromium.org'])
  2186. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2187. self.assertEqual(1, len(result))
  2188. self.assertEqual(result[0].type, 'error')
  2189. self.assertEqual(result[0].message,
  2190. 'The following files change calls to security-sensive functions\n' \
  2191. 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
  2192. ' file.cc\n'
  2193. ' content::GetServiceSandboxType<>()\n\n')
  2194. def testChangeOwnersPresent(self):
  2195. mock_input_api = MockInputApi()
  2196. mock_input_api.owners_client = self._MockOwnersClient()
  2197. mock_input_api.files = [
  2198. MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
  2199. ]
  2200. mock_output_api = MockOutputApi()
  2201. self._mockChangeOwnerAndReviewers(
  2202. mock_input_api, 'owner@chromium.org',
  2203. ['apple@chromium.org', 'banana@chromium.org'])
  2204. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2205. self.assertEqual(0, len(result))
  2206. def testChangeOwnerIsSecurityOwner(self):
  2207. mock_input_api = MockInputApi()
  2208. mock_input_api.owners_client = self._MockOwnersClient()
  2209. mock_input_api.files = [
  2210. MockAffectedFile('file.cc', ['GetServiceSandboxType<T>(Sandbox)'])
  2211. ]
  2212. mock_output_api = MockOutputApi()
  2213. self._mockChangeOwnerAndReviewers(
  2214. mock_input_api, 'orange@chromium.org', ['pear@chromium.org'])
  2215. result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
  2216. self.assertEqual(1, len(result))
  2217. class BannedTypeCheckTest(unittest.TestCase):
  2218. def testBannedCppFunctions(self):
  2219. input_api = MockInputApi()
  2220. input_api.files = [
  2221. MockFile('some/cpp/problematic/file.cc',
  2222. ['using namespace std;']),
  2223. MockFile('third_party/blink/problematic/file.cc',
  2224. ['GetInterfaceProvider()']),
  2225. MockFile('some/cpp/ok/file.cc',
  2226. ['using std::string;']),
  2227. MockFile('some/cpp/problematic/file2.cc',
  2228. ['set_owned_by_client()']),
  2229. MockFile('some/cpp/nocheck/file.cc',
  2230. ['using namespace std; // nocheck']),
  2231. MockFile('some/cpp/comment/file.cc',
  2232. [' // A comment about `using namespace std;`']),
  2233. ]
  2234. results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2235. # warnings are results[0], errors are results[1]
  2236. self.assertEqual(2, len(results))
  2237. self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
  2238. self.assertTrue(
  2239. 'third_party/blink/problematic/file.cc' in results[0].message)
  2240. self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
  2241. self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
  2242. self.assertFalse('some/cpp/nocheck/file.cc' in results[0].message)
  2243. self.assertFalse('some/cpp/nocheck/file.cc' in results[1].message)
  2244. self.assertFalse('some/cpp/comment/file.cc' in results[0].message)
  2245. self.assertFalse('some/cpp/comment/file.cc' in results[1].message)
  2246. def testBannedIosObjcFunctions(self):
  2247. input_api = MockInputApi()
  2248. input_api.files = [
  2249. MockFile('some/ios/file.mm',
  2250. ['TEST(SomeClassTest, SomeInteraction) {',
  2251. '}']),
  2252. MockFile('some/mac/file.mm',
  2253. ['TEST(SomeClassTest, SomeInteraction) {',
  2254. '}']),
  2255. MockFile('another/ios_file.mm',
  2256. ['class SomeTest : public testing::Test {};']),
  2257. MockFile('some/ios/file_egtest.mm',
  2258. ['- (void)testSomething { EXPECT_OCMOCK_VERIFY(aMock); }']),
  2259. MockFile('some/ios/file_unittest.mm',
  2260. ['TEST_F(SomeTest, TestThis) { EXPECT_OCMOCK_VERIFY(aMock); }']),
  2261. ]
  2262. errors = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2263. self.assertEqual(1, len(errors))
  2264. self.assertTrue('some/ios/file.mm' in errors[0].message)
  2265. self.assertTrue('another/ios_file.mm' in errors[0].message)
  2266. self.assertTrue('some/mac/file.mm' not in errors[0].message)
  2267. self.assertTrue('some/ios/file_egtest.mm' in errors[0].message)
  2268. self.assertTrue('some/ios/file_unittest.mm' not in errors[0].message)
  2269. def testBannedMojoFunctions(self):
  2270. input_api = MockInputApi()
  2271. input_api.files = [
  2272. MockFile('some/cpp/problematic/file2.cc',
  2273. ['mojo::ConvertTo<>']),
  2274. MockFile('third_party/blink/ok/file3.cc',
  2275. ['mojo::ConvertTo<>']),
  2276. MockFile('content/renderer/ok/file3.cc',
  2277. ['mojo::ConvertTo<>']),
  2278. ]
  2279. results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2280. # warnings are results[0], errors are results[1]
  2281. self.assertEqual(1, len(results))
  2282. self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
  2283. self.assertTrue('third_party/blink/ok/file3.cc' not in results[0].message)
  2284. self.assertTrue('content/renderer/ok/file3.cc' not in results[0].message)
  2285. def testBannedMojomPatterns(self):
  2286. input_api = MockInputApi()
  2287. input_api.files = [
  2288. MockFile('bad.mojom',
  2289. ['struct Bad {',
  2290. ' handle<shared_buffer> buffer;',
  2291. '};']),
  2292. MockFile('good.mojom',
  2293. ['struct Good {',
  2294. ' mojo_base.mojom.ReadOnlySharedMemoryRegion region1;',
  2295. ' mojo_base.mojom.WritableSharedMemoryRegion region2;',
  2296. ' mojo_base.mojom.UnsafeSharedMemoryRegion region3;',
  2297. '};']),
  2298. ]
  2299. results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
  2300. # warnings are results[0], errors are results[1]
  2301. self.assertEqual(1, len(results))
  2302. self.assertTrue('bad.mojom' in results[0].message)
  2303. self.assertTrue('good.mojom' not in results[0].message)
  2304. class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
  2305. def testTruePositives(self):
  2306. mock_input_api = MockInputApi()
  2307. mock_input_api.files = [
  2308. MockFile('some/path/foo.cc', ['foo_for_testing();']),
  2309. MockFile('some/path/foo.mm', ['FooForTesting();']),
  2310. MockFile('some/path/foo.cxx', ['FooForTests();']),
  2311. MockFile('some/path/foo.cpp', ['foo_for_test();']),
  2312. ]
  2313. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
  2314. mock_input_api, MockOutputApi())
  2315. self.assertEqual(1, len(results))
  2316. self.assertEqual(4, len(results[0].items))
  2317. self.assertTrue('foo.cc' in results[0].items[0])
  2318. self.assertTrue('foo.mm' in results[0].items[1])
  2319. self.assertTrue('foo.cxx' in results[0].items[2])
  2320. self.assertTrue('foo.cpp' in results[0].items[3])
  2321. def testFalsePositives(self):
  2322. mock_input_api = MockInputApi()
  2323. mock_input_api.files = [
  2324. MockFile('some/path/foo.h', ['foo_for_testing();']),
  2325. MockFile('some/path/foo.mm', ['FooForTesting() {']),
  2326. MockFile('some/path/foo.cc', ['::FooForTests();']),
  2327. MockFile('some/path/foo.cpp', ['// foo_for_test();']),
  2328. ]
  2329. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
  2330. mock_input_api, MockOutputApi())
  2331. self.assertEqual(0, len(results))
  2332. def testAllowedFiles(self):
  2333. mock_input_api = MockInputApi()
  2334. mock_input_api.files = [
  2335. MockFile('path/foo_unittest.cc', ['foo_for_testing();']),
  2336. MockFile('path/bar_unittest_mac.cc', ['foo_for_testing();']),
  2337. MockFile('path/baz_unittests.cc', ['foo_for_testing();']),
  2338. ]
  2339. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
  2340. mock_input_api, MockOutputApi())
  2341. self.assertEqual(0, len(results))
  2342. class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
  2343. def testTruePositives(self):
  2344. mock_input_api = MockInputApi()
  2345. mock_input_api.files = [
  2346. MockFile('dir/java/src/foo.java', ['FooForTesting();']),
  2347. MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
  2348. MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
  2349. MockFile('dir/java/src/mult.java', [
  2350. 'int x = SomethingLongHere()',
  2351. ' * SomethingLongHereForTesting();'
  2352. ])
  2353. ]
  2354. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
  2355. mock_input_api, MockOutputApi())
  2356. self.assertEqual(1, len(results))
  2357. self.assertEqual(4, len(results[0].items))
  2358. self.assertTrue('foo.java' in results[0].items[0])
  2359. self.assertTrue('bar.java' in results[0].items[1])
  2360. self.assertTrue('baz.java' in results[0].items[2])
  2361. self.assertTrue('mult.java' in results[0].items[3])
  2362. def testFalsePositives(self):
  2363. mock_input_api = MockInputApi()
  2364. mock_input_api.files = [
  2365. MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
  2366. MockFile('dir/java/src/foo.java', ['FooForTests() {']),
  2367. MockFile('dir/java/src/bar.java', ['// FooForTest();']),
  2368. MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
  2369. MockFile('dir/java/src/bar3.java', ['@VisibleForTesting']),
  2370. MockFile('dir/java/src/bar4.java', ['@VisibleForTesting()']),
  2371. MockFile('dir/java/src/bar5.java', [
  2372. '@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)'
  2373. ]),
  2374. MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
  2375. MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
  2376. MockFile('dir/junit/src/javadoc.java', [
  2377. '/** Use FooForTest(); to obtain foo in tests.'
  2378. ' */'
  2379. ]),
  2380. MockFile('dir/junit/src/javadoc2.java', [
  2381. '/** ',
  2382. ' * Use FooForTest(); to obtain foo in tests.'
  2383. ' */'
  2384. ]),
  2385. ]
  2386. results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
  2387. mock_input_api, MockOutputApi())
  2388. self.assertEqual(0, len(results))
  2389. class NewImagesWarningTest(unittest.TestCase):
  2390. def testTruePositives(self):
  2391. mock_input_api = MockInputApi()
  2392. mock_input_api.files = [
  2393. MockFile('dir/android/res/drawable/foo.png', []),
  2394. MockFile('dir/android/res/drawable-v21/bar.svg', []),
  2395. MockFile('dir/android/res/mipmap-v21-en/baz.webp', []),
  2396. MockFile('dir/android/res_gshoe/drawable-mdpi/foobar.png', []),
  2397. ]
  2398. results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
  2399. self.assertEqual(1, len(results))
  2400. self.assertEqual(4, len(results[0].items))
  2401. self.assertTrue('foo.png' in results[0].items[0].LocalPath())
  2402. self.assertTrue('bar.svg' in results[0].items[1].LocalPath())
  2403. self.assertTrue('baz.webp' in results[0].items[2].LocalPath())
  2404. self.assertTrue('foobar.png' in results[0].items[3].LocalPath())
  2405. def testFalsePositives(self):
  2406. mock_input_api = MockInputApi()
  2407. mock_input_api.files = [
  2408. MockFile('dir/pngs/README.md', []),
  2409. MockFile('java/test/res/drawable/foo.png', []),
  2410. MockFile('third_party/blink/foo.png', []),
  2411. MockFile('dir/third_party/libpng/src/foo.cc', ['foobar']),
  2412. MockFile('dir/resources.webp/.gitignore', ['foo.png']),
  2413. ]
  2414. results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
  2415. self.assertEqual(0, len(results))
  2416. class CheckUniquePtrTest(unittest.TestCase):
  2417. def testTruePositivesNullptr(self):
  2418. mock_input_api = MockInputApi()
  2419. mock_input_api.files = [
  2420. MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
  2421. MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
  2422. ]
  2423. results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
  2424. self.assertEqual(1, len(results))
  2425. self.assertTrue('nullptr' in results[0].message)
  2426. self.assertEqual(2, len(results[0].items))
  2427. self.assertTrue('baz.cc' in results[0].items[0])
  2428. self.assertTrue('baz-p.cc' in results[0].items[1])
  2429. def testTruePositivesConstructor(self):
  2430. mock_input_api = MockInputApi()
  2431. mock_input_api.files = [
  2432. MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
  2433. MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
  2434. MockFile('dir/mult.cc', [
  2435. 'return',
  2436. ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
  2437. ]),
  2438. MockFile('dir/mult2.cc', [
  2439. 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
  2440. ' std::unique_ptr<T>(foo);'
  2441. ]),
  2442. MockFile('dir/mult3.cc', [
  2443. 'bar = std::unique_ptr<T>(',
  2444. ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
  2445. ]),
  2446. MockFile('dir/multi_arg.cc', [
  2447. 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
  2448. ]
  2449. results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
  2450. self.assertEqual(1, len(results))
  2451. self.assertTrue('std::make_unique' in results[0].message)
  2452. self.assertEqual(6, len(results[0].items))
  2453. self.assertTrue('foo.cc' in results[0].items[0])
  2454. self.assertTrue('bar.mm' in results[0].items[1])
  2455. self.assertTrue('mult.cc' in results[0].items[2])
  2456. self.assertTrue('mult2.cc' in results[0].items[3])
  2457. self.assertTrue('mult3.cc' in results[0].items[4])
  2458. self.assertTrue('multi_arg.cc' in results[0].items[5])
  2459. def testFalsePositives(self):
  2460. mock_input_api = MockInputApi()
  2461. mock_input_api.files = [
  2462. MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
  2463. MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
  2464. MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
  2465. MockFile('dir/baz.cc', [
  2466. 'std::unique_ptr<T> result = std::make_unique<T>();'
  2467. ]),
  2468. MockFile('dir/baz2.cc', [
  2469. 'std::unique_ptr<T> result = std::make_unique<T>('
  2470. ]),
  2471. MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
  2472. MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
  2473. # Two-argument invocation of std::unique_ptr is exempt because there is
  2474. # no equivalent using std::make_unique.
  2475. MockFile('dir/multi_arg.cc', [
  2476. 'auto p = std::unique_ptr<T, D>(new T(), D());']),
  2477. ]
  2478. results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
  2479. self.assertEqual(0, len(results))
  2480. class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
  2481. def testBlocksDirectIncludes(self):
  2482. mock_input_api = MockInputApi()
  2483. mock_input_api.files = [
  2484. MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
  2485. MockFile('dir/bar.h', ['#include <propvarutil.h>']),
  2486. MockFile('dir/baz.h', ['#include <atlbase.h>']),
  2487. MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
  2488. ]
  2489. results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2490. self.assertEqual(1, len(results))
  2491. self.assertEqual(4, len(results[0].items))
  2492. self.assertTrue('StrCat' in results[0].message)
  2493. self.assertTrue('foo_win.cc' in results[0].items[0])
  2494. self.assertTrue('bar.h' in results[0].items[1])
  2495. self.assertTrue('baz.h' in results[0].items[2])
  2496. self.assertTrue('jumbo.h' in results[0].items[3])
  2497. def testAllowsToIncludeWrapper(self):
  2498. mock_input_api = MockInputApi()
  2499. mock_input_api.files = [
  2500. MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
  2501. MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
  2502. ]
  2503. results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2504. self.assertEqual(0, len(results))
  2505. def testAllowsToCreateWrapper(self):
  2506. mock_input_api = MockInputApi()
  2507. mock_input_api.files = [
  2508. MockFile('base/win/shlwapi.h', [
  2509. '#include <shlwapi.h>',
  2510. '#include "base/win/windows_defines.inc"']),
  2511. ]
  2512. results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
  2513. self.assertEqual(0, len(results))
  2514. class StringTest(unittest.TestCase):
  2515. """Tests ICU syntax check and translation screenshots check."""
  2516. # An empty grd file.
  2517. OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
  2518. <grit latest_public_release="1" current_release="1">
  2519. <release seq="1">
  2520. <messages></messages>
  2521. </release>
  2522. </grit>
  2523. """.splitlines()
  2524. # A grd file with a single message.
  2525. NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
  2526. <grit latest_public_release="1" current_release="1">
  2527. <release seq="1">
  2528. <messages>
  2529. <message name="IDS_TEST1">
  2530. Test string 1
  2531. </message>
  2532. <message name="IDS_TEST_STRING_NON_TRANSLATEABLE1"
  2533. translateable="false">
  2534. Non translateable message 1, should be ignored
  2535. </message>
  2536. <message name="IDS_TEST_STRING_ACCESSIBILITY"
  2537. is_accessibility_with_no_ui="true">
  2538. Accessibility label 1, should be ignored
  2539. </message>
  2540. </messages>
  2541. </release>
  2542. </grit>
  2543. """.splitlines()
  2544. # A grd file with two messages.
  2545. NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
  2546. <grit latest_public_release="1" current_release="1">
  2547. <release seq="1">
  2548. <messages>
  2549. <message name="IDS_TEST1">
  2550. Test string 1
  2551. </message>
  2552. <message name="IDS_TEST2">
  2553. Test string 2
  2554. </message>
  2555. <message name="IDS_TEST_STRING_NON_TRANSLATEABLE2"
  2556. translateable="false">
  2557. Non translateable message 2, should be ignored
  2558. </message>
  2559. </messages>
  2560. </release>
  2561. </grit>
  2562. """.splitlines()
  2563. # A grd file with one ICU syntax message without syntax errors.
  2564. NEW_GRD_CONTENTS_ICU_SYNTAX_OK1 = """<?xml version="1.0" encoding="UTF-8"?>
  2565. <grit latest_public_release="1" current_release="1">
  2566. <release seq="1">
  2567. <messages>
  2568. <message name="IDS_TEST1">
  2569. {NUM, plural,
  2570. =1 {Test text for numeric one}
  2571. other {Test text for plural with {NUM} as number}}
  2572. </message>
  2573. </messages>
  2574. </release>
  2575. </grit>
  2576. """.splitlines()
  2577. # A grd file with one ICU syntax message without syntax errors.
  2578. NEW_GRD_CONTENTS_ICU_SYNTAX_OK2 = """<?xml version="1.0" encoding="UTF-8"?>
  2579. <grit latest_public_release="1" current_release="1">
  2580. <release seq="1">
  2581. <messages>
  2582. <message name="IDS_TEST1">
  2583. {NUM, plural,
  2584. =1 {Different test text for numeric one}
  2585. other {Different test text for plural with {NUM} as number}}
  2586. </message>
  2587. </messages>
  2588. </release>
  2589. </grit>
  2590. """.splitlines()
  2591. # A grd file with one ICU syntax message with syntax errors (misses a comma).
  2592. NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR = """<?xml version="1.0" encoding="UTF-8"?>
  2593. <grit latest_public_release="1" current_release="1">
  2594. <release seq="1">
  2595. <messages>
  2596. <message name="IDS_TEST1">
  2597. {NUM, plural
  2598. =1 {Test text for numeric one}
  2599. other {Test text for plural with {NUM} as number}}
  2600. </message>
  2601. </messages>
  2602. </release>
  2603. </grit>
  2604. """.splitlines()
  2605. OLD_GRDP_CONTENTS = (
  2606. '<?xml version="1.0" encoding="utf-8"?>',
  2607. '<grit-part>',
  2608. '</grit-part>'
  2609. )
  2610. NEW_GRDP_CONTENTS1 = (
  2611. '<?xml version="1.0" encoding="utf-8"?>',
  2612. '<grit-part>',
  2613. '<message name="IDS_PART_TEST1">',
  2614. 'Part string 1',
  2615. '</message>',
  2616. '</grit-part>')
  2617. NEW_GRDP_CONTENTS2 = (
  2618. '<?xml version="1.0" encoding="utf-8"?>',
  2619. '<grit-part>',
  2620. '<message name="IDS_PART_TEST1">',
  2621. 'Part string 1',
  2622. '</message>',
  2623. '<message name="IDS_PART_TEST2">',
  2624. 'Part string 2',
  2625. '</message>',
  2626. '</grit-part>')
  2627. NEW_GRDP_CONTENTS3 = (
  2628. '<?xml version="1.0" encoding="utf-8"?>',
  2629. '<grit-part>',
  2630. '<message name="IDS_PART_TEST1" desc="Description with typo.">',
  2631. 'Part string 1',
  2632. '</message>',
  2633. '</grit-part>')
  2634. NEW_GRDP_CONTENTS4 = (
  2635. '<?xml version="1.0" encoding="utf-8"?>',
  2636. '<grit-part>',
  2637. '<message name="IDS_PART_TEST1" desc="Description with typo fixed.">',
  2638. 'Part string 1',
  2639. '</message>',
  2640. '</grit-part>')
  2641. NEW_GRDP_CONTENTS5 = (
  2642. '<?xml version="1.0" encoding="utf-8"?>',
  2643. '<grit-part>',
  2644. '<message name="IDS_PART_TEST1" meaning="Meaning with typo.">',
  2645. 'Part string 1',
  2646. '</message>',
  2647. '</grit-part>')
  2648. NEW_GRDP_CONTENTS6 = (
  2649. '<?xml version="1.0" encoding="utf-8"?>',
  2650. '<grit-part>',
  2651. '<message name="IDS_PART_TEST1" meaning="Meaning with typo fixed.">',
  2652. 'Part string 1',
  2653. '</message>',
  2654. '</grit-part>')
  2655. # A grdp file with one ICU syntax message without syntax errors.
  2656. NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1 = (
  2657. '<?xml version="1.0" encoding="utf-8"?>',
  2658. '<grit-part>',
  2659. '<message name="IDS_PART_TEST1">',
  2660. '{NUM, plural,',
  2661. '=1 {Test text for numeric one}',
  2662. 'other {Test text for plural with {NUM} as number}}',
  2663. '</message>',
  2664. '</grit-part>')
  2665. # A grdp file with one ICU syntax message without syntax errors.
  2666. NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2 = (
  2667. '<?xml version="1.0" encoding="utf-8"?>',
  2668. '<grit-part>',
  2669. '<message name="IDS_PART_TEST1">',
  2670. '{NUM, plural,',
  2671. '=1 {Different test text for numeric one}',
  2672. 'other {Different test text for plural with {NUM} as number}}',
  2673. '</message>',
  2674. '</grit-part>')
  2675. # A grdp file with one ICU syntax message with syntax errors (superfluent
  2676. # whitespace).
  2677. NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR = (
  2678. '<?xml version="1.0" encoding="utf-8"?>',
  2679. '<grit-part>',
  2680. '<message name="IDS_PART_TEST1">',
  2681. '{NUM, plural,',
  2682. '= 1 {Test text for numeric one}',
  2683. 'other {Test text for plural with {NUM} as number}}',
  2684. '</message>',
  2685. '</grit-part>')
  2686. DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
  2687. 'changelist. Run '
  2688. 'tools/translate/upload_screenshots.py to '
  2689. 'upload them instead:')
  2690. GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
  2691. 'To ensure the best translations, take '
  2692. 'screenshots of the relevant UI '
  2693. '(https://g.co/chrome/translation) and add '
  2694. 'these files to your changelist:')
  2695. REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
  2696. 'files. Remove:')
  2697. ICU_SYNTAX_ERROR_MESSAGE = ('ICU syntax errors were found in the following '
  2698. 'strings (problems or feedback? Contact '
  2699. 'rainhard@chromium.org):')
  2700. def makeInputApi(self, files):
  2701. input_api = MockInputApi()
  2702. input_api.files = files
  2703. # Override os_path.exists because the presubmit uses the actual
  2704. # os.path.exists.
  2705. input_api.CreateMockFileInPath(
  2706. [x.LocalPath() for x in input_api.AffectedFiles(include_deletes=True)])
  2707. return input_api
  2708. """ CL modified and added messages, but didn't add any screenshots."""
  2709. def testNoScreenshots(self):
  2710. # No new strings (file contents same). Should not warn.
  2711. input_api = self.makeInputApi([
  2712. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
  2713. self.NEW_GRD_CONTENTS1, action='M'),
  2714. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS1,
  2715. self.NEW_GRDP_CONTENTS1, action='M')])
  2716. warnings = PRESUBMIT.CheckStrings(input_api,
  2717. MockOutputApi())
  2718. self.assertEqual(0, len(warnings))
  2719. # Add two new strings. Should have two warnings.
  2720. input_api = self.makeInputApi([
  2721. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
  2722. self.NEW_GRD_CONTENTS1, action='M'),
  2723. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
  2724. self.NEW_GRDP_CONTENTS1, action='M')])
  2725. warnings = PRESUBMIT.CheckStrings(input_api,
  2726. MockOutputApi())
  2727. self.assertEqual(1, len(warnings))
  2728. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
  2729. self.assertEqual('error', warnings[0].type)
  2730. self.assertEqual([
  2731. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2732. os.path.join('test_grd', 'IDS_TEST2.png.sha1')],
  2733. warnings[0].items)
  2734. # Add four new strings. Should have four warnings.
  2735. input_api = self.makeInputApi([
  2736. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
  2737. self.OLD_GRD_CONTENTS, action='M'),
  2738. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
  2739. self.OLD_GRDP_CONTENTS, action='M')])
  2740. warnings = PRESUBMIT.CheckStrings(input_api,
  2741. MockOutputApi())
  2742. self.assertEqual(1, len(warnings))
  2743. self.assertEqual('error', warnings[0].type)
  2744. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
  2745. self.assertEqual([
  2746. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2747. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2748. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  2749. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  2750. ], warnings[0].items)
  2751. def testModifiedMessageDescription(self):
  2752. # CL modified a message description for a message that does not yet have a
  2753. # screenshot. Should not warn.
  2754. input_api = self.makeInputApi([
  2755. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
  2756. self.NEW_GRDP_CONTENTS4, action='M')])
  2757. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2758. self.assertEqual(0, len(warnings))
  2759. # CL modified a message description for a message that already has a
  2760. # screenshot. Should not warn.
  2761. input_api = self.makeInputApi([
  2762. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
  2763. self.NEW_GRDP_CONTENTS4, action='M'),
  2764. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2765. 'binary', action='A')])
  2766. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2767. self.assertEqual(0, len(warnings))
  2768. def testModifiedMessageMeaning(self):
  2769. # CL modified a message meaning for a message that does not yet have a
  2770. # screenshot. Should warn.
  2771. input_api = self.makeInputApi([
  2772. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
  2773. self.NEW_GRDP_CONTENTS6, action='M')])
  2774. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2775. self.assertEqual(1, len(warnings))
  2776. # CL modified a message meaning for a message that already has a
  2777. # screenshot. Should not warn.
  2778. input_api = self.makeInputApi([
  2779. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
  2780. self.NEW_GRDP_CONTENTS6, action='M'),
  2781. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2782. 'binary', action='A')])
  2783. warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  2784. self.assertEqual(0, len(warnings))
  2785. def testPngAddedSha1NotAdded(self):
  2786. # CL added one new message in a grd file and added the png file associated
  2787. # with it, but did not add the corresponding sha1 file. This should warn
  2788. # twice:
  2789. # - Once for the added png file (because we don't want developers to upload
  2790. # actual images)
  2791. # - Once for the missing .sha1 file
  2792. input_api = self.makeInputApi([
  2793. MockAffectedFile(
  2794. 'test.grd',
  2795. self.NEW_GRD_CONTENTS1,
  2796. self.OLD_GRD_CONTENTS,
  2797. action='M'),
  2798. MockAffectedFile(
  2799. os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A')
  2800. ])
  2801. warnings = PRESUBMIT.CheckStrings(input_api,
  2802. MockOutputApi())
  2803. self.assertEqual(2, len(warnings))
  2804. self.assertEqual('error', warnings[0].type)
  2805. self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
  2806. self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png')],
  2807. warnings[0].items)
  2808. self.assertEqual('error', warnings[1].type)
  2809. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
  2810. self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
  2811. warnings[1].items)
  2812. # CL added two messages (one in grd, one in grdp) and added the png files
  2813. # associated with the messages, but did not add the corresponding sha1
  2814. # files. This should warn twice:
  2815. # - Once for the added png files (because we don't want developers to upload
  2816. # actual images)
  2817. # - Once for the missing .sha1 files
  2818. input_api = self.makeInputApi([
  2819. # Modified files:
  2820. MockAffectedFile(
  2821. 'test.grd',
  2822. self.NEW_GRD_CONTENTS1,
  2823. self.OLD_GRD_CONTENTS,
  2824. action='M'),
  2825. MockAffectedFile(
  2826. 'part.grdp',
  2827. self.NEW_GRDP_CONTENTS1,
  2828. self.OLD_GRDP_CONTENTS,
  2829. action='M'),
  2830. # Added files:
  2831. MockAffectedFile(
  2832. os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A'),
  2833. MockAffectedFile(
  2834. os.path.join('part_grdp', 'IDS_PART_TEST1.png'), 'binary',
  2835. action='A')
  2836. ])
  2837. warnings = PRESUBMIT.CheckStrings(input_api,
  2838. MockOutputApi())
  2839. self.assertEqual(2, len(warnings))
  2840. self.assertEqual('error', warnings[0].type)
  2841. self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
  2842. self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png'),
  2843. os.path.join('test_grd', 'IDS_TEST1.png')],
  2844. warnings[0].items)
  2845. self.assertEqual('error', warnings[0].type)
  2846. self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
  2847. self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2848. os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
  2849. warnings[1].items)
  2850. def testScreenshotsWithSha1(self):
  2851. # CL added four messages (two each in a grd and grdp) and their
  2852. # corresponding .sha1 files. No warnings.
  2853. input_api = self.makeInputApi([
  2854. # Modified files:
  2855. MockAffectedFile(
  2856. 'test.grd',
  2857. self.NEW_GRD_CONTENTS2,
  2858. self.OLD_GRD_CONTENTS,
  2859. action='M'),
  2860. MockAffectedFile(
  2861. 'part.grdp',
  2862. self.NEW_GRDP_CONTENTS2,
  2863. self.OLD_GRDP_CONTENTS,
  2864. action='M'),
  2865. # Added files:
  2866. MockFile(
  2867. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  2868. 'binary',
  2869. action='A'),
  2870. MockFile(
  2871. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  2872. 'binary',
  2873. action='A'),
  2874. MockFile(
  2875. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2876. 'binary',
  2877. action='A'),
  2878. MockFile(
  2879. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2880. 'binary',
  2881. action='A'),
  2882. ])
  2883. warnings = PRESUBMIT.CheckStrings(input_api,
  2884. MockOutputApi())
  2885. self.assertEqual([], warnings)
  2886. def testScreenshotsRemovedWithSha1(self):
  2887. # Replace new contents with old contents in grd and grp files, removing
  2888. # IDS_TEST1, IDS_TEST2, IDS_PART_TEST1 and IDS_PART_TEST2.
  2889. # Should warn to remove the sha1 files associated with these strings.
  2890. input_api = self.makeInputApi([
  2891. # Modified files:
  2892. MockAffectedFile(
  2893. 'test.grd',
  2894. self.OLD_GRD_CONTENTS, # new_contents
  2895. self.NEW_GRD_CONTENTS2, # old_contents
  2896. action='M'),
  2897. MockAffectedFile(
  2898. 'part.grdp',
  2899. self.OLD_GRDP_CONTENTS, # new_contents
  2900. self.NEW_GRDP_CONTENTS2, # old_contents
  2901. action='M'),
  2902. # Unmodified files:
  2903. MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
  2904. MockFile(os.path.join('test_grd', 'IDS_TEST2.png.sha1'), 'binary', ''),
  2905. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2906. 'binary', ''),
  2907. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2908. 'binary', '')
  2909. ])
  2910. warnings = PRESUBMIT.CheckStrings(input_api,
  2911. MockOutputApi())
  2912. self.assertEqual(1, len(warnings))
  2913. self.assertEqual('error', warnings[0].type)
  2914. self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
  2915. self.assertEqual([
  2916. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2917. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2918. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  2919. os.path.join('test_grd', 'IDS_TEST2.png.sha1')
  2920. ], warnings[0].items)
  2921. # Same as above, but this time one of the .sha1 files is also removed.
  2922. input_api = self.makeInputApi([
  2923. # Modified files:
  2924. MockAffectedFile(
  2925. 'test.grd',
  2926. self.OLD_GRD_CONTENTS, # new_contents
  2927. self.NEW_GRD_CONTENTS2, # old_contents
  2928. action='M'),
  2929. MockAffectedFile(
  2930. 'part.grdp',
  2931. self.OLD_GRDP_CONTENTS, # new_contents
  2932. self.NEW_GRDP_CONTENTS2, # old_contents
  2933. action='M'),
  2934. # Unmodified files:
  2935. MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
  2936. MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2937. 'binary', ''),
  2938. # Deleted files:
  2939. MockAffectedFile(
  2940. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  2941. '',
  2942. 'old_contents',
  2943. action='D'),
  2944. MockAffectedFile(
  2945. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2946. '',
  2947. 'old_contents',
  2948. action='D')
  2949. ])
  2950. warnings = PRESUBMIT.CheckStrings(input_api,
  2951. MockOutputApi())
  2952. self.assertEqual(1, len(warnings))
  2953. self.assertEqual('error', warnings[0].type)
  2954. self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
  2955. self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2956. os.path.join('test_grd', 'IDS_TEST1.png.sha1')
  2957. ], warnings[0].items)
  2958. # Remove all sha1 files. There should be no warnings.
  2959. input_api = self.makeInputApi([
  2960. # Modified files:
  2961. MockAffectedFile(
  2962. 'test.grd',
  2963. self.OLD_GRD_CONTENTS,
  2964. self.NEW_GRD_CONTENTS2,
  2965. action='M'),
  2966. MockAffectedFile(
  2967. 'part.grdp',
  2968. self.OLD_GRDP_CONTENTS,
  2969. self.NEW_GRDP_CONTENTS2,
  2970. action='M'),
  2971. # Deleted files:
  2972. MockFile(
  2973. os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
  2974. 'binary',
  2975. action='D'),
  2976. MockFile(
  2977. os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
  2978. 'binary',
  2979. action='D'),
  2980. MockFile(
  2981. os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
  2982. 'binary',
  2983. action='D'),
  2984. MockFile(
  2985. os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
  2986. 'binary',
  2987. action='D')
  2988. ])
  2989. warnings = PRESUBMIT.CheckStrings(input_api,
  2990. MockOutputApi())
  2991. self.assertEqual([], warnings)
  2992. def testIcuSyntax(self):
  2993. # Add valid ICU syntax string. Should not raise an error.
  2994. input_api = self.makeInputApi([
  2995. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
  2996. self.NEW_GRD_CONTENTS1, action='M'),
  2997. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
  2998. self.NEW_GRDP_CONTENTS1, action='M')])
  2999. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3000. # We expect no ICU syntax errors.
  3001. icu_errors = [e for e in results
  3002. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3003. self.assertEqual(0, len(icu_errors))
  3004. # Valid changes in ICU syntax. Should not raise an error.
  3005. input_api = self.makeInputApi([
  3006. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
  3007. self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
  3008. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
  3009. self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
  3010. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3011. # We expect no ICU syntax errors.
  3012. icu_errors = [e for e in results
  3013. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3014. self.assertEqual(0, len(icu_errors))
  3015. # Add invalid ICU syntax strings. Should raise two errors.
  3016. input_api = self.makeInputApi([
  3017. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
  3018. self.NEW_GRD_CONTENTS1, action='M'),
  3019. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
  3020. self.NEW_GRD_CONTENTS1, action='M')])
  3021. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3022. # We expect 2 ICU syntax errors.
  3023. icu_errors = [e for e in results
  3024. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3025. self.assertEqual(1, len(icu_errors))
  3026. self.assertEqual([
  3027. 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
  3028. 'ICU syntax.',
  3029. 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
  3030. ], icu_errors[0].items)
  3031. # Change two strings to have ICU syntax errors. Should raise two errors.
  3032. input_api = self.makeInputApi([
  3033. MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
  3034. self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
  3035. MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
  3036. self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
  3037. results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
  3038. # We expect 2 ICU syntax errors.
  3039. icu_errors = [e for e in results
  3040. if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
  3041. self.assertEqual(1, len(icu_errors))
  3042. self.assertEqual([
  3043. 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
  3044. 'ICU syntax.',
  3045. 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
  3046. ], icu_errors[0].items)
  3047. class TranslationExpectationsTest(unittest.TestCase):
  3048. ERROR_MESSAGE_FORMAT = (
  3049. "Failed to get a list of translatable grd files. "
  3050. "This happens when:\n"
  3051. " - One of the modified grd or grdp files cannot be parsed or\n"
  3052. " - %s is not updated.\n"
  3053. "Stack:\n"
  3054. )
  3055. REPO_ROOT = os.path.join('tools', 'translation', 'testdata')
  3056. # This lists all .grd files under REPO_ROOT.
  3057. EXPECTATIONS = os.path.join(REPO_ROOT,
  3058. "translation_expectations.pyl")
  3059. # This lists all .grd files under REPO_ROOT except unlisted.grd.
  3060. EXPECTATIONS_WITHOUT_UNLISTED_FILE = os.path.join(
  3061. REPO_ROOT, "translation_expectations_without_unlisted_file.pyl")
  3062. # Tests that the presubmit doesn't return when no grd or grdp files are
  3063. # modified.
  3064. def testExpectationsNoModifiedGrd(self):
  3065. input_api = MockInputApi()
  3066. input_api.files = [
  3067. MockAffectedFile('not_used.txt', 'not used', 'not used', action='M')
  3068. ]
  3069. # Fake list of all grd files in the repo. This list is missing all grd/grdps
  3070. # under tools/translation/testdata. This is OK because the presubmit won't
  3071. # run in the first place since there are no modified grd/grps in input_api.
  3072. grd_files = ['doesnt_exist_doesnt_matter.grd']
  3073. warnings = PRESUBMIT.CheckTranslationExpectations(
  3074. input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
  3075. grd_files)
  3076. self.assertEqual(0, len(warnings))
  3077. # Tests that the list of files passed to the presubmit matches the list of
  3078. # files in the expectations.
  3079. def testExpectationsSuccess(self):
  3080. # Mock input file list needs a grd or grdp file in order to run the
  3081. # presubmit. The file itself doesn't matter.
  3082. input_api = MockInputApi()
  3083. input_api.files = [
  3084. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3085. ]
  3086. # List of all grd files in the repo.
  3087. grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
  3088. 'internal.grd']
  3089. warnings = PRESUBMIT.CheckTranslationExpectations(
  3090. input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
  3091. grd_files)
  3092. self.assertEqual(0, len(warnings))
  3093. # Tests that the presubmit warns when a file is listed in expectations, but
  3094. # does not actually exist.
  3095. def testExpectationsMissingFile(self):
  3096. # Mock input file list needs a grd or grdp file in order to run the
  3097. # presubmit.
  3098. input_api = MockInputApi()
  3099. input_api.files = [
  3100. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3101. ]
  3102. # unlisted.grd is listed under tools/translation/testdata but is not
  3103. # included in translation expectations.
  3104. grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
  3105. warnings = PRESUBMIT.CheckTranslationExpectations(
  3106. input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
  3107. grd_files)
  3108. self.assertEqual(1, len(warnings))
  3109. self.assertTrue(warnings[0].message.startswith(
  3110. self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS))
  3111. self.assertTrue(
  3112. ("test.grd is listed in the translation expectations, "
  3113. "but this grd file does not exist")
  3114. in warnings[0].message)
  3115. # Tests that the presubmit warns when a file is not listed in expectations but
  3116. # does actually exist.
  3117. def testExpectationsUnlistedFile(self):
  3118. # Mock input file list needs a grd or grdp file in order to run the
  3119. # presubmit.
  3120. input_api = MockInputApi()
  3121. input_api.files = [
  3122. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3123. ]
  3124. # unlisted.grd is listed under tools/translation/testdata but is not
  3125. # included in translation expectations.
  3126. grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
  3127. 'internal.grd']
  3128. warnings = PRESUBMIT.CheckTranslationExpectations(
  3129. input_api, MockOutputApi(), self.REPO_ROOT,
  3130. self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
  3131. self.assertEqual(1, len(warnings))
  3132. self.assertTrue(warnings[0].message.startswith(
  3133. self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
  3134. self.assertTrue(
  3135. ("unlisted.grd appears to be translatable "
  3136. "(because it contains <file> or <message> elements), "
  3137. "but is not listed in the translation expectations.")
  3138. in warnings[0].message)
  3139. # Tests that the presubmit warns twice:
  3140. # - for a non-existing file listed in expectations
  3141. # - for an existing file not listed in expectations
  3142. def testMultipleWarnings(self):
  3143. # Mock input file list needs a grd or grdp file in order to run the
  3144. # presubmit.
  3145. input_api = MockInputApi()
  3146. input_api.files = [
  3147. MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
  3148. ]
  3149. # unlisted.grd is listed under tools/translation/testdata but is not
  3150. # included in translation expectations.
  3151. # test.grd is not listed under tools/translation/testdata but is included
  3152. # in translation expectations.
  3153. grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
  3154. warnings = PRESUBMIT.CheckTranslationExpectations(
  3155. input_api, MockOutputApi(), self.REPO_ROOT,
  3156. self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
  3157. self.assertEqual(1, len(warnings))
  3158. self.assertTrue(warnings[0].message.startswith(
  3159. self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
  3160. self.assertTrue(
  3161. ("unlisted.grd appears to be translatable "
  3162. "(because it contains <file> or <message> elements), "
  3163. "but is not listed in the translation expectations.")
  3164. in warnings[0].message)
  3165. self.assertTrue(
  3166. ("test.grd is listed in the translation expectations, "
  3167. "but this grd file does not exist")
  3168. in warnings[0].message)
  3169. class DISABLETypoInTest(unittest.TestCase):
  3170. def testPositive(self):
  3171. # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
  3172. # where the desire is to disable a test.
  3173. tests = [
  3174. # Disabled on one platform:
  3175. '#if defined(OS_WIN)\n'
  3176. '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
  3177. '#else\n'
  3178. '#define MAYBE_FoobarTest FoobarTest\n'
  3179. '#endif\n',
  3180. # Disabled on one platform spread cross lines:
  3181. '#if defined(OS_WIN)\n'
  3182. '#define MAYBE_FoobarTest \\\n'
  3183. ' DISABLE_FoobarTest\n'
  3184. '#else\n'
  3185. '#define MAYBE_FoobarTest FoobarTest\n'
  3186. '#endif\n',
  3187. # Disabled on all platforms:
  3188. ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
  3189. # Disabled on all platforms but multiple lines
  3190. ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
  3191. ]
  3192. for test in tests:
  3193. mock_input_api = MockInputApi()
  3194. mock_input_api.files = [
  3195. MockFile('some/path/foo_unittest.cc', test.splitlines()),
  3196. ]
  3197. results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
  3198. MockOutputApi())
  3199. self.assertEqual(
  3200. 1,
  3201. len(results),
  3202. msg=('expected len(results) == 1 but got %d in test: %s' %
  3203. (len(results), test)))
  3204. self.assertTrue(
  3205. 'foo_unittest.cc' in results[0].message,
  3206. msg=('expected foo_unittest.cc in message but got %s in test %s' %
  3207. (results[0].message, test)))
  3208. def testIngoreNotTestFiles(self):
  3209. mock_input_api = MockInputApi()
  3210. mock_input_api.files = [
  3211. MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
  3212. ]
  3213. results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
  3214. MockOutputApi())
  3215. self.assertEqual(0, len(results))
  3216. def testIngoreDeletedFiles(self):
  3217. mock_input_api = MockInputApi()
  3218. mock_input_api.files = [
  3219. MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
  3220. ]
  3221. results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
  3222. MockOutputApi())
  3223. self.assertEqual(0, len(results))
  3224. class ForgettingMAYBEInTests(unittest.TestCase):
  3225. def testPositive(self):
  3226. test = (
  3227. '#if defined(HAS_ENERGY)\n'
  3228. '#define MAYBE_CastExplosion DISABLED_CastExplosion\n'
  3229. '#else\n'
  3230. '#define MAYBE_CastExplosion CastExplosion\n'
  3231. '#endif\n'
  3232. 'TEST_F(ArchWizard, CastExplosion) {\n'
  3233. '#if defined(ARCH_PRIEST_IN_PARTY)\n'
  3234. '#define MAYBE_ArchPriest ArchPriest\n'
  3235. '#else\n'
  3236. '#define MAYBE_ArchPriest DISABLED_ArchPriest\n'
  3237. '#endif\n'
  3238. 'TEST_F(ArchPriest, CastNaturesBounty) {\n'
  3239. '#if !defined(CRUSADER_IN_PARTY)\n'
  3240. '#define MAYBE_Crusader \\\n'
  3241. ' DISABLED_Crusader \n'
  3242. '#else\n'
  3243. '#define MAYBE_Crusader \\\n'
  3244. ' Crusader\n'
  3245. '#endif\n'
  3246. ' TEST_F(\n'
  3247. ' Crusader,\n'
  3248. ' CastTaunt) { }\n'
  3249. '#if defined(LEARNED_BASIC_SKILLS)\n'
  3250. '#define MAYBE_CastSteal \\\n'
  3251. ' DISABLED_CastSteal \n'
  3252. '#else\n'
  3253. '#define MAYBE_CastSteal \\\n'
  3254. ' CastSteal\n'
  3255. '#endif\n'
  3256. ' TEST_F(\n'
  3257. ' ThiefClass,\n'
  3258. ' CastSteal) { }\n'
  3259. )
  3260. mock_input_api = MockInputApi()
  3261. mock_input_api.files = [
  3262. MockFile('fantasyworld/classes_unittest.cc', test.splitlines()),
  3263. ]
  3264. results = PRESUBMIT.CheckForgettingMAYBEInTests(mock_input_api,
  3265. MockOutputApi())
  3266. self.assertEqual(4, len(results))
  3267. self.assertTrue('CastExplosion' in results[0].message)
  3268. self.assertTrue('fantasyworld/classes_unittest.cc:2' in results[0].message)
  3269. self.assertTrue('ArchPriest' in results[1].message)
  3270. self.assertTrue('fantasyworld/classes_unittest.cc:8' in results[1].message)
  3271. self.assertTrue('Crusader' in results[2].message)
  3272. self.assertTrue('fantasyworld/classes_unittest.cc:14' in results[2].message)
  3273. self.assertTrue('CastSteal' in results[3].message)
  3274. self.assertTrue('fantasyworld/classes_unittest.cc:24' in results[3].message)
  3275. def testNegative(self):
  3276. test = (
  3277. '#if defined(HAS_ENERGY)\n'
  3278. '#define MAYBE_CastExplosion DISABLED_CastExplosion\n'
  3279. '#else\n'
  3280. '#define MAYBE_CastExplosion CastExplosion\n'
  3281. '#endif\n'
  3282. 'TEST_F(ArchWizard, MAYBE_CastExplosion) {\n'
  3283. '#if defined(ARCH_PRIEST_IN_PARTY)\n'
  3284. '#define MAYBE_ArchPriest ArchPriest\n'
  3285. '#else\n'
  3286. '#define MAYBE_ArchPriest DISABLED_ArchPriest\n'
  3287. '#endif\n'
  3288. 'TEST_F(MAYBE_ArchPriest, CastNaturesBounty) {\n'
  3289. '#if !defined(CRUSADER_IN_PARTY)\n'
  3290. '#define MAYBE_Crusader \\\n'
  3291. ' DISABLED_Crusader \n'
  3292. '#else\n'
  3293. '#define MAYBE_Crusader \\\n'
  3294. ' Crusader\n'
  3295. '#endif\n'
  3296. ' TEST_F(\n'
  3297. ' MAYBE_Crusader,\n'
  3298. ' CastTaunt) { }\n'
  3299. '#if defined(LEARNED_BASIC_SKILLS)\n'
  3300. '#define MAYBE_CastSteal \\\n'
  3301. ' DISABLED_CastSteal \n'
  3302. '#else\n'
  3303. '#define MAYBE_CastSteal \\\n'
  3304. ' CastSteal\n'
  3305. '#endif\n'
  3306. ' TEST_F(\n'
  3307. ' ThiefClass,\n'
  3308. ' MAYBE_CastSteal) { }\n'
  3309. )
  3310. mock_input_api = MockInputApi()
  3311. mock_input_api.files = [
  3312. MockFile('fantasyworld/classes_unittest.cc', test.splitlines()),
  3313. ]
  3314. results = PRESUBMIT.CheckForgettingMAYBEInTests(mock_input_api,
  3315. MockOutputApi())
  3316. self.assertEqual(0, len(results))
  3317. class CheckFuzzTargetsTest(unittest.TestCase):
  3318. def _check(self, files):
  3319. mock_input_api = MockInputApi()
  3320. mock_input_api.files = []
  3321. for fname, contents in files.items():
  3322. mock_input_api.files.append(MockFile(fname, contents.splitlines()))
  3323. return PRESUBMIT.CheckFuzzTargetsOnUpload(mock_input_api, MockOutputApi())
  3324. def testLibFuzzerSourcesIgnored(self):
  3325. results = self._check({
  3326. "third_party/lib/Fuzzer/FuzzerDriver.cpp": "LLVMFuzzerInitialize",
  3327. })
  3328. self.assertEqual(results, [])
  3329. def testNonCodeFilesIgnored(self):
  3330. results = self._check({
  3331. "README.md": "LLVMFuzzerInitialize",
  3332. })
  3333. self.assertEqual(results, [])
  3334. def testNoErrorHeaderPresent(self):
  3335. results = self._check({
  3336. "fuzzer.cc": (
  3337. "#include \"testing/libfuzzer/libfuzzer_exports.h\"\n" +
  3338. "LLVMFuzzerInitialize"
  3339. )
  3340. })
  3341. self.assertEqual(results, [])
  3342. def testErrorMissingHeader(self):
  3343. results = self._check({
  3344. "fuzzer.cc": "LLVMFuzzerInitialize"
  3345. })
  3346. self.assertEqual(len(results), 1)
  3347. self.assertEqual(results[0].items, ['fuzzer.cc'])
  3348. class SetNoParentTest(unittest.TestCase):
  3349. def testSetNoParentTopLevelAllowed(self):
  3350. mock_input_api = MockInputApi()
  3351. mock_input_api.files = [
  3352. MockAffectedFile('goat/OWNERS',
  3353. [
  3354. 'set noparent',
  3355. 'jochen@chromium.org',
  3356. ])
  3357. ]
  3358. mock_output_api = MockOutputApi()
  3359. errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
  3360. self.assertEqual([], errors)
  3361. def testSetNoParentMissing(self):
  3362. mock_input_api = MockInputApi()
  3363. mock_input_api.files = [
  3364. MockAffectedFile('services/goat/OWNERS',
  3365. [
  3366. 'set noparent',
  3367. 'jochen@chromium.org',
  3368. 'per-file *.json=set noparent',
  3369. 'per-file *.json=jochen@chromium.org',
  3370. ])
  3371. ]
  3372. mock_output_api = MockOutputApi()
  3373. errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
  3374. self.assertEqual(1, len(errors))
  3375. self.assertTrue('goat/OWNERS:1' in errors[0].long_text)
  3376. self.assertTrue('goat/OWNERS:3' in errors[0].long_text)
  3377. def testSetNoParentWithCorrectRule(self):
  3378. mock_input_api = MockInputApi()
  3379. mock_input_api.files = [
  3380. MockAffectedFile('services/goat/OWNERS',
  3381. [
  3382. 'set noparent',
  3383. 'file://ipc/SECURITY_OWNERS',
  3384. 'per-file *.json=set noparent',
  3385. 'per-file *.json=file://ipc/SECURITY_OWNERS',
  3386. ])
  3387. ]
  3388. mock_output_api = MockOutputApi()
  3389. errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
  3390. self.assertEqual([], errors)
  3391. class MojomStabilityCheckTest(unittest.TestCase):
  3392. def runTestWithAffectedFiles(self, affected_files):
  3393. mock_input_api = MockInputApi()
  3394. mock_input_api.files = affected_files
  3395. mock_output_api = MockOutputApi()
  3396. return PRESUBMIT.CheckStableMojomChanges(
  3397. mock_input_api, mock_output_api)
  3398. def testSafeChangePasses(self):
  3399. errors = self.runTestWithAffectedFiles([
  3400. MockAffectedFile('foo/foo.mojom',
  3401. ['[Stable] struct S { [MinVersion=1] int32 x; };'],
  3402. old_contents=['[Stable] struct S {};'])
  3403. ])
  3404. self.assertEqual([], errors)
  3405. def testBadChangeFails(self):
  3406. errors = self.runTestWithAffectedFiles([
  3407. MockAffectedFile('foo/foo.mojom',
  3408. ['[Stable] struct S { int32 x; };'],
  3409. old_contents=['[Stable] struct S {};'])
  3410. ])
  3411. self.assertEqual(1, len(errors))
  3412. self.assertTrue('not backward-compatible' in errors[0].message)
  3413. def testDeletedFile(self):
  3414. """Regression test for https://crbug.com/1091407."""
  3415. errors = self.runTestWithAffectedFiles([
  3416. MockAffectedFile('a.mojom', [], old_contents=['struct S {};'],
  3417. action='D'),
  3418. MockAffectedFile('b.mojom',
  3419. ['struct S {}; struct T { S s; };'],
  3420. old_contents=['import "a.mojom"; struct T { S s; };'])
  3421. ])
  3422. self.assertEqual([], errors)
  3423. class CheckForUseOfChromeAppsDeprecationsTest(unittest.TestCase):
  3424. ERROR_MSG_PIECE = 'technologies which will soon be deprecated'
  3425. # Each positive test is also a naive negative test for the other cases.
  3426. def testWarningNMF(self):
  3427. mock_input_api = MockInputApi()
  3428. mock_input_api.files = [
  3429. MockAffectedFile(
  3430. 'foo.NMF',
  3431. ['"program"', '"Z":"content"', 'B'],
  3432. ['"program"', 'B'],
  3433. scm_diff='\n'.join([
  3434. '--- foo.NMF.old 2020-12-02 20:40:54.430676385 +0100',
  3435. '+++ foo.NMF.new 2020-12-02 20:41:02.086700197 +0100',
  3436. '@@ -1,2 +1,3 @@',
  3437. ' "program"',
  3438. '+"Z":"content"',
  3439. ' B']),
  3440. action='M')
  3441. ]
  3442. mock_output_api = MockOutputApi()
  3443. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3444. mock_output_api)
  3445. self.assertEqual(1, len(errors))
  3446. self.assertTrue( self.ERROR_MSG_PIECE in errors[0].message)
  3447. self.assertTrue( 'foo.NMF' in errors[0].message)
  3448. def testWarningManifest(self):
  3449. mock_input_api = MockInputApi()
  3450. mock_input_api.files = [
  3451. MockAffectedFile(
  3452. 'manifest.json',
  3453. ['"app":', '"Z":"content"', 'B'],
  3454. ['"app":"', 'B'],
  3455. scm_diff='\n'.join([
  3456. '--- manifest.json.old 2020-12-02 20:40:54.430676385 +0100',
  3457. '+++ manifest.json.new 2020-12-02 20:41:02.086700197 +0100',
  3458. '@@ -1,2 +1,3 @@',
  3459. ' "app"',
  3460. '+"Z":"content"',
  3461. ' B']),
  3462. action='M')
  3463. ]
  3464. mock_output_api = MockOutputApi()
  3465. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3466. mock_output_api)
  3467. self.assertEqual(1, len(errors))
  3468. self.assertTrue( self.ERROR_MSG_PIECE in errors[0].message)
  3469. self.assertTrue( 'manifest.json' in errors[0].message)
  3470. def testOKWarningManifestWithoutApp(self):
  3471. mock_input_api = MockInputApi()
  3472. mock_input_api.files = [
  3473. MockAffectedFile(
  3474. 'manifest.json',
  3475. ['"name":', '"Z":"content"', 'B'],
  3476. ['"name":"', 'B'],
  3477. scm_diff='\n'.join([
  3478. '--- manifest.json.old 2020-12-02 20:40:54.430676385 +0100',
  3479. '+++ manifest.json.new 2020-12-02 20:41:02.086700197 +0100',
  3480. '@@ -1,2 +1,3 @@',
  3481. ' "app"',
  3482. '+"Z":"content"',
  3483. ' B']),
  3484. action='M')
  3485. ]
  3486. mock_output_api = MockOutputApi()
  3487. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3488. mock_output_api)
  3489. self.assertEqual(0, len(errors))
  3490. def testWarningPPAPI(self):
  3491. mock_input_api = MockInputApi()
  3492. mock_input_api.files = [
  3493. MockAffectedFile(
  3494. 'foo.hpp',
  3495. ['A', '#include <ppapi.h>', 'B'],
  3496. ['A', 'B'],
  3497. scm_diff='\n'.join([
  3498. '--- foo.hpp.old 2020-12-02 20:40:54.430676385 +0100',
  3499. '+++ foo.hpp.new 2020-12-02 20:41:02.086700197 +0100',
  3500. '@@ -1,2 +1,3 @@',
  3501. ' A',
  3502. '+#include <ppapi.h>',
  3503. ' B']),
  3504. action='M')
  3505. ]
  3506. mock_output_api = MockOutputApi()
  3507. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3508. mock_output_api)
  3509. self.assertEqual(1, len(errors))
  3510. self.assertTrue( self.ERROR_MSG_PIECE in errors[0].message)
  3511. self.assertTrue( 'foo.hpp' in errors[0].message)
  3512. def testNoWarningPPAPI(self):
  3513. mock_input_api = MockInputApi()
  3514. mock_input_api.files = [
  3515. MockAffectedFile(
  3516. 'foo.txt',
  3517. ['A', 'Peppapig', 'B'],
  3518. ['A', 'B'],
  3519. scm_diff='\n'.join([
  3520. '--- foo.txt.old 2020-12-02 20:40:54.430676385 +0100',
  3521. '+++ foo.txt.new 2020-12-02 20:41:02.086700197 +0100',
  3522. '@@ -1,2 +1,3 @@',
  3523. ' A',
  3524. '+Peppapig',
  3525. ' B']),
  3526. action='M')
  3527. ]
  3528. mock_output_api = MockOutputApi()
  3529. errors = PRESUBMIT.CheckForUseOfChromeAppsDeprecations(mock_input_api,
  3530. mock_output_api)
  3531. self.assertEqual(0, len(errors))
  3532. class CheckDeprecationOfPreferencesTest(unittest.TestCase):
  3533. # Test that a warning is generated if a preference registration is removed
  3534. # from a random file.
  3535. def testWarning(self):
  3536. mock_input_api = MockInputApi()
  3537. mock_input_api.files = [
  3538. MockAffectedFile(
  3539. 'foo.cc',
  3540. ['A', 'B'],
  3541. ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
  3542. scm_diff='\n'.join([
  3543. '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
  3544. '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
  3545. '@@ -1,3 +1,2 @@',
  3546. ' A',
  3547. '-prefs->RegisterStringPref("foo", "default");',
  3548. ' B']),
  3549. action='M')
  3550. ]
  3551. mock_output_api = MockOutputApi()
  3552. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3553. mock_output_api)
  3554. self.assertEqual(1, len(errors))
  3555. self.assertTrue(
  3556. 'Discovered possible removal of preference registrations' in
  3557. errors[0].message)
  3558. # Test that a warning is inhibited if the preference registration was moved
  3559. # to the deprecation functions in browser prefs.
  3560. def testNoWarningForMigration(self):
  3561. mock_input_api = MockInputApi()
  3562. mock_input_api.files = [
  3563. # RegisterStringPref was removed from foo.cc.
  3564. MockAffectedFile(
  3565. 'foo.cc',
  3566. ['A', 'B'],
  3567. ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
  3568. scm_diff='\n'.join([
  3569. '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
  3570. '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
  3571. '@@ -1,3 +1,2 @@',
  3572. ' A',
  3573. '-prefs->RegisterStringPref("foo", "default");',
  3574. ' B']),
  3575. action='M'),
  3576. # But the preference was properly migrated.
  3577. MockAffectedFile(
  3578. 'chrome/browser/prefs/browser_prefs.cc',
  3579. [
  3580. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3581. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3582. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3583. 'prefs->RegisterStringPref("foo", "default");',
  3584. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3585. ],
  3586. [
  3587. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3588. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3589. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3590. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3591. ],
  3592. scm_diff='\n'.join([
  3593. '--- browser_prefs.cc.old 2020-12-02 20:51:40.812686731 +0100',
  3594. '+++ browser_prefs.cc.new 2020-12-02 20:52:02.936755539 +0100',
  3595. '@@ -2,3 +2,4 @@',
  3596. ' // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3597. ' // BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3598. '+prefs->RegisterStringPref("foo", "default");',
  3599. ' // END_MIGRATE_OBSOLETE_PROFILE_PREFS']),
  3600. action='M'),
  3601. ]
  3602. mock_output_api = MockOutputApi()
  3603. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3604. mock_output_api)
  3605. self.assertEqual(0, len(errors))
  3606. # Test that a warning is NOT inhibited if the preference registration was
  3607. # moved to a place outside of the migration functions in browser_prefs.cc
  3608. def testWarningForImproperMigration(self):
  3609. mock_input_api = MockInputApi()
  3610. mock_input_api.files = [
  3611. # RegisterStringPref was removed from foo.cc.
  3612. MockAffectedFile(
  3613. 'foo.cc',
  3614. ['A', 'B'],
  3615. ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
  3616. scm_diff='\n'.join([
  3617. '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
  3618. '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
  3619. '@@ -1,3 +1,2 @@',
  3620. ' A',
  3621. '-prefs->RegisterStringPref("foo", "default");',
  3622. ' B']),
  3623. action='M'),
  3624. # The registration call was moved to a place in browser_prefs.cc that
  3625. # is outside the migration functions.
  3626. MockAffectedFile(
  3627. 'chrome/browser/prefs/browser_prefs.cc',
  3628. [
  3629. 'prefs->RegisterStringPref("foo", "default");',
  3630. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3631. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3632. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3633. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3634. ],
  3635. [
  3636. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3637. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3638. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3639. '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3640. ],
  3641. scm_diff='\n'.join([
  3642. '--- browser_prefs.cc.old 2020-12-02 20:51:40.812686731 +0100',
  3643. '+++ browser_prefs.cc.new 2020-12-02 20:52:02.936755539 +0100',
  3644. '@@ -1,2 +1,3 @@',
  3645. '+prefs->RegisterStringPref("foo", "default");',
  3646. ' // BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3647. ' // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS']),
  3648. action='M'),
  3649. ]
  3650. mock_output_api = MockOutputApi()
  3651. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3652. mock_output_api)
  3653. self.assertEqual(1, len(errors))
  3654. self.assertTrue(
  3655. 'Discovered possible removal of preference registrations' in
  3656. errors[0].message)
  3657. # Check that the presubmit fails if a marker line in brower_prefs.cc is
  3658. # deleted.
  3659. def testDeletedMarkerRaisesError(self):
  3660. mock_input_api = MockInputApi()
  3661. mock_input_api.files = [
  3662. MockAffectedFile('chrome/browser/prefs/browser_prefs.cc',
  3663. [
  3664. '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3665. '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
  3666. '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3667. # The following line is deleted for this test
  3668. # '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
  3669. ])
  3670. ]
  3671. mock_output_api = MockOutputApi()
  3672. errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
  3673. mock_output_api)
  3674. self.assertEqual(1, len(errors))
  3675. self.assertEqual(
  3676. 'Broken .*MIGRATE_OBSOLETE_.*_PREFS markers in browser_prefs.cc.',
  3677. errors[0].message)
  3678. class MPArchApiUsage(unittest.TestCase):
  3679. def _assert_notify(
  3680. self, expected_uses, msg, local_path, new_contents):
  3681. mock_input_api = MockInputApi()
  3682. mock_output_api = MockOutputApi()
  3683. mock_input_api.files = [
  3684. MockFile(local_path, new_contents),
  3685. ]
  3686. result = PRESUBMIT.CheckMPArchApiUsage(mock_input_api, mock_output_api)
  3687. self.assertEqual(
  3688. bool(expected_uses),
  3689. 'mparch-reviews+watch@chromium.org' in mock_output_api.more_cc,
  3690. msg)
  3691. if expected_uses:
  3692. self.assertEqual(1, len(result), msg)
  3693. self.assertEqual(result[0].type, 'notify', msg)
  3694. self.assertEqual(sorted(result[0].items), sorted(expected_uses), msg)
  3695. def testNotify(self):
  3696. self._assert_notify(
  3697. ['WebContentsObserver', 'WebContentsUserData'],
  3698. 'Introduce WCO and WCUD',
  3699. 'chrome/my_feature.h',
  3700. ['class MyFeature',
  3701. ' : public content::WebContentsObserver,',
  3702. ' public content::WebContentsUserData<MyFeature> {};',
  3703. ])
  3704. self._assert_notify(
  3705. ['DidFinishNavigation'],
  3706. 'Introduce WCO override',
  3707. 'chrome/my_feature.h',
  3708. ['void DidFinishNavigation(',
  3709. ' content::NavigationHandle* navigation_handle) override;',
  3710. ])
  3711. self._assert_notify(
  3712. ['IsInMainFrame'],
  3713. 'Introduce IsInMainFrame',
  3714. 'chrome/my_feature.cc',
  3715. ['void DoSomething(content::NavigationHandle* navigation_handle) {',
  3716. ' if (navigation_handle->IsInMainFrame())',
  3717. ' all_of_our_page_state.reset();',
  3718. '}',
  3719. ])
  3720. self._assert_notify(
  3721. ['FromRenderFrameHost'],
  3722. 'Introduce WC::FromRenderFrameHost',
  3723. 'chrome/my_feature.cc',
  3724. ['void DoSomething(content::RenderFrameHost* rfh) {',
  3725. ' auto* wc = content::WebContents::FromRenderFrameHost(rfh);',
  3726. ' ChangeTabState(wc);',
  3727. '}',
  3728. ])
  3729. def testNoNotify(self):
  3730. self._assert_notify(
  3731. [],
  3732. 'No API usage',
  3733. 'chrome/my_feature.cc',
  3734. ['void DoSomething() {',
  3735. ' // TODO: Something',
  3736. '}',
  3737. ])
  3738. # Something under a top level directory we're not concerned about happens
  3739. # to share a name with a content API.
  3740. self._assert_notify(
  3741. [],
  3742. 'Uninteresting top level directory',
  3743. 'third_party/my_dep/my_code.cc',
  3744. ['bool HasParent(Node* node) {',
  3745. ' return node->GetParent();',
  3746. '}',
  3747. ])
  3748. # We're not concerned with usage in test code.
  3749. self._assert_notify(
  3750. [],
  3751. 'Usage in test code',
  3752. 'chrome/my_feature_unittest.cc',
  3753. ['TEST_F(MyFeatureTest, DoesSomething) {',
  3754. ' EXPECT_TRUE(web_contents()->GetMainFrame());',
  3755. '}',
  3756. ])
  3757. class AssertAshOnlyCodeTest(unittest.TestCase):
  3758. def testErrorsOnlyOnAshDirectories(self):
  3759. files_in_ash = [
  3760. MockFile('ash/BUILD.gn', []),
  3761. MockFile('chrome/browser/ash/BUILD.gn', []),
  3762. ]
  3763. other_files = [
  3764. MockFile('chrome/browser/BUILD.gn', []),
  3765. MockFile('chrome/browser/BUILD.gn', ['assert(is_chromeos_ash)']),
  3766. ]
  3767. input_api = MockInputApi()
  3768. input_api.files = files_in_ash
  3769. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  3770. self.assertEqual(2, len(errors))
  3771. input_api.files = other_files
  3772. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  3773. self.assertEqual(0, len(errors))
  3774. def testDoesNotErrorOnNonGNFiles(self):
  3775. input_api = MockInputApi()
  3776. input_api.files = [
  3777. MockFile('ash/test.h', ['assert(is_chromeos_ash)']),
  3778. MockFile('chrome/browser/ash/test.cc',
  3779. ['assert(is_chromeos_ash)']),
  3780. ]
  3781. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  3782. self.assertEqual(0, len(errors))
  3783. def testDeletedFile(self):
  3784. input_api = MockInputApi()
  3785. input_api.files = [
  3786. MockFile('ash/BUILD.gn', []),
  3787. MockFile('ash/foo/BUILD.gn', [], action='D'),
  3788. ]
  3789. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  3790. self.assertEqual(1, len(errors))
  3791. def testDoesNotErrorWithAssertion(self):
  3792. input_api = MockInputApi()
  3793. input_api.files = [
  3794. MockFile('ash/BUILD.gn', ['assert(is_chromeos_ash)']),
  3795. MockFile('chrome/browser/ash/BUILD.gn',
  3796. ['assert(is_chromeos_ash)']),
  3797. MockFile('chrome/browser/ash/BUILD.gn',
  3798. ['assert(is_chromeos_ash, "test")']),
  3799. ]
  3800. errors = PRESUBMIT.CheckAssertAshOnlyCode(input_api, MockOutputApi())
  3801. self.assertEqual(0, len(errors))
  3802. class CheckRawPtrUsageTest(unittest.TestCase):
  3803. def testAllowedCases(self):
  3804. mock_input_api = MockInputApi()
  3805. mock_input_api.files = [
  3806. # Browser-side files are allowed.
  3807. MockAffectedFile('test10/browser/foo.h', ['raw_ptr<int>']),
  3808. MockAffectedFile('test11/browser/foo.cc', ['raw_ptr<int>']),
  3809. MockAffectedFile('test12/blink/common/foo.cc', ['raw_ptr<int>']),
  3810. MockAffectedFile('test13/blink/public/common/foo.cc', ['raw_ptr<int>']),
  3811. MockAffectedFile('test14/blink/public/platform/foo.cc',
  3812. ['raw_ptr<int>']),
  3813. # Non-C++ files are allowed.
  3814. MockAffectedFile('test20/renderer/foo.md', ['raw_ptr<int>']),
  3815. # Mentions in a comment are allowed.
  3816. MockAffectedFile('test30/renderer/foo.cc', ['//raw_ptr<int>']),
  3817. ]
  3818. mock_output_api = MockOutputApi()
  3819. errors = PRESUBMIT.CheckRawPtrUsage(mock_input_api, mock_output_api)
  3820. self.assertFalse(errors)
  3821. def testDisallowedCases(self):
  3822. mock_input_api = MockInputApi()
  3823. mock_input_api.files = [
  3824. MockAffectedFile('test1/renderer/foo.h', ['raw_ptr<int>']),
  3825. MockAffectedFile('test2/renderer/foo.cc', ['raw_ptr<int>']),
  3826. MockAffectedFile('test3/blink/public/web/foo.cc', ['raw_ptr<int>']),
  3827. ]
  3828. mock_output_api = MockOutputApi()
  3829. errors = PRESUBMIT.CheckRawPtrUsage(mock_input_api, mock_output_api)
  3830. self.assertEqual(len(mock_input_api.files), len(errors))
  3831. for error in errors:
  3832. self.assertTrue(
  3833. 'raw_ptr<T> should not be used in Renderer-only code' in
  3834. error.message)
  3835. class AssertPythonShebangTest(unittest.TestCase):
  3836. def testError(self):
  3837. input_api = MockInputApi()
  3838. input_api.files = [
  3839. MockFile('ash/test.py', ['#!/usr/bin/python']),
  3840. MockFile('chrome/test.py', ['#!/usr/bin/python2']),
  3841. MockFile('third_party/blink/test.py', ['#!/usr/bin/python3']),
  3842. MockFile('empty.py', []),
  3843. ]
  3844. errors = PRESUBMIT.CheckPythonShebang(input_api, MockOutputApi())
  3845. self.assertEqual(3, len(errors))
  3846. def testNonError(self):
  3847. input_api = MockInputApi()
  3848. input_api.files = [
  3849. MockFile('chrome/browser/BUILD.gn', ['#!/usr/bin/python']),
  3850. MockFile('third_party/blink/web_tests/external/test.py',
  3851. ['#!/usr/bin/python2']),
  3852. MockFile('third_party/test/test.py', ['#!/usr/bin/python3']),
  3853. ]
  3854. errors = PRESUBMIT.CheckPythonShebang(input_api, MockOutputApi())
  3855. self.assertEqual(0, len(errors))
  3856. if __name__ == '__main__':
  3857. unittest.main()