gtest.cc 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898
  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: [email protected] (Zhanyong Wan)
  31. //
  32. // The Google C++ Testing Framework (Google Test)
  33. #include "gtest/gtest.h"
  34. #include "gtest/gtest-spi.h"
  35. #include <ctype.h>
  36. #include <math.h>
  37. #include <stdarg.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <wchar.h>
  41. #include <wctype.h>
  42. #include <algorithm>
  43. #include <ostream> // NOLINT
  44. #include <sstream>
  45. #include <vector>
  46. #if GTEST_OS_LINUX
  47. // TODO([email protected]): Use autoconf to detect availability of
  48. // gettimeofday().
  49. # define GTEST_HAS_GETTIMEOFDAY_ 1
  50. # include <fcntl.h> // NOLINT
  51. # include <limits.h> // NOLINT
  52. # include <sched.h> // NOLINT
  53. // Declares vsnprintf(). This header is not available on Windows.
  54. # include <strings.h> // NOLINT
  55. # include <sys/mman.h> // NOLINT
  56. # include <sys/time.h> // NOLINT
  57. # include <unistd.h> // NOLINT
  58. # include <string>
  59. #elif GTEST_OS_SYMBIAN
  60. # define GTEST_HAS_GETTIMEOFDAY_ 1
  61. # include <sys/time.h> // NOLINT
  62. #elif GTEST_OS_ZOS
  63. # define GTEST_HAS_GETTIMEOFDAY_ 1
  64. # include <sys/time.h> // NOLINT
  65. // On z/OS we additionally need strings.h for strcasecmp.
  66. # include <strings.h> // NOLINT
  67. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  68. # include <windows.h> // NOLINT
  69. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  70. # include <io.h> // NOLINT
  71. # include <sys/timeb.h> // NOLINT
  72. # include <sys/types.h> // NOLINT
  73. # include <sys/stat.h> // NOLINT
  74. # if GTEST_OS_WINDOWS_MINGW
  75. // MinGW has gettimeofday() but not _ftime64().
  76. // TODO([email protected]): Use autoconf to detect availability of
  77. // gettimeofday().
  78. // TODO([email protected]): There are other ways to get the time on
  79. // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
  80. // supports these. consider using them instead.
  81. # define GTEST_HAS_GETTIMEOFDAY_ 1
  82. # include <sys/time.h> // NOLINT
  83. # endif // GTEST_OS_WINDOWS_MINGW
  84. // cpplint thinks that the header is already included, so we want to
  85. // silence it.
  86. # include <windows.h> // NOLINT
  87. #else
  88. // Assume other platforms have gettimeofday().
  89. // TODO([email protected]): Use autoconf to detect availability of
  90. // gettimeofday().
  91. # define GTEST_HAS_GETTIMEOFDAY_ 1
  92. // cpplint thinks that the header is already included, so we want to
  93. // silence it.
  94. # include <sys/time.h> // NOLINT
  95. # include <unistd.h> // NOLINT
  96. #endif // GTEST_OS_LINUX
  97. #if GTEST_HAS_EXCEPTIONS
  98. # include <stdexcept>
  99. #endif
  100. #if GTEST_CAN_STREAM_RESULTS_
  101. # include <arpa/inet.h> // NOLINT
  102. # include <netdb.h> // NOLINT
  103. #endif
  104. // Indicates that this translation unit is part of Google Test's
  105. // implementation. It must come before gtest-internal-inl.h is
  106. // included, or there will be a compiler error. This trick is to
  107. // prevent a user from accidentally including gtest-internal-inl.h in
  108. // his code.
  109. #define GTEST_IMPLEMENTATION_ 1
  110. #include "src/gtest-internal-inl.h"
  111. #undef GTEST_IMPLEMENTATION_
  112. #if GTEST_OS_WINDOWS
  113. # define vsnprintf _vsnprintf
  114. #endif // GTEST_OS_WINDOWS
  115. namespace testing {
  116. using internal::CountIf;
  117. using internal::ForEach;
  118. using internal::GetElementOr;
  119. using internal::Shuffle;
  120. // Constants.
  121. // A test whose test case name or test name matches this filter is
  122. // disabled and not run.
  123. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  124. // A test case whose name matches this filter is considered a death
  125. // test case and will be run before test cases whose name doesn't
  126. // match this filter.
  127. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  128. // A test filter that matches everything.
  129. static const char kUniversalFilter[] = "*";
  130. // The default output file for XML output.
  131. static const char kDefaultOutputFile[] = "test_detail.xml";
  132. // The environment variable name for the test shard index.
  133. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  134. // The environment variable name for the total number of test shards.
  135. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  136. // The environment variable name for the test shard status file.
  137. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  138. namespace internal {
  139. // The text used in failure messages to indicate the start of the
  140. // stack trace.
  141. const char kStackTraceMarker[] = "\nStack trace:\n";
  142. // g_help_flag is true iff the --help flag or an equivalent form is
  143. // specified on the command line.
  144. bool g_help_flag = false;
  145. } // namespace internal
  146. GTEST_DEFINE_bool_(
  147. also_run_disabled_tests,
  148. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  149. "Run disabled tests too, in addition to the tests normally being run.");
  150. GTEST_DEFINE_bool_(
  151. break_on_failure,
  152. internal::BoolFromGTestEnv("break_on_failure", false),
  153. "True iff a failed assertion should be a debugger break-point.");
  154. GTEST_DEFINE_bool_(
  155. catch_exceptions,
  156. internal::BoolFromGTestEnv("catch_exceptions", true),
  157. "True iff " GTEST_NAME_
  158. " should catch exceptions and treat them as test failures.");
  159. GTEST_DEFINE_string_(
  160. color,
  161. internal::StringFromGTestEnv("color", "auto"),
  162. "Whether to use colors in the output. Valid values: yes, no, "
  163. "and auto. 'auto' means to use colors if the output is "
  164. "being sent to a terminal and the TERM environment variable "
  165. "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
  166. GTEST_DEFINE_string_(
  167. filter,
  168. internal::StringFromGTestEnv("filter", kUniversalFilter),
  169. "A colon-separated list of glob (not regex) patterns "
  170. "for filtering the tests to run, optionally followed by a "
  171. "'-' and a : separated list of negative patterns (tests to "
  172. "exclude). A test is run if it matches one of the positive "
  173. "patterns and does not match any of the negative patterns.");
  174. GTEST_DEFINE_bool_(list_tests, false,
  175. "List all tests without running them.");
  176. GTEST_DEFINE_string_(
  177. output,
  178. internal::StringFromGTestEnv("output", ""),
  179. "A format (currently must be \"xml\"), optionally followed "
  180. "by a colon and an output file name or directory. A directory "
  181. "is indicated by a trailing pathname separator. "
  182. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  183. "If a directory is specified, output files will be created "
  184. "within that directory, with file-names based on the test "
  185. "executable's name and, if necessary, made unique by adding "
  186. "digits.");
  187. GTEST_DEFINE_bool_(
  188. print_time,
  189. internal::BoolFromGTestEnv("print_time", true),
  190. "True iff " GTEST_NAME_
  191. " should display elapsed time in text output.");
  192. GTEST_DEFINE_int32_(
  193. random_seed,
  194. internal::Int32FromGTestEnv("random_seed", 0),
  195. "Random number seed to use when shuffling test orders. Must be in range "
  196. "[1, 99999], or 0 to use a seed based on the current time.");
  197. GTEST_DEFINE_int32_(
  198. repeat,
  199. internal::Int32FromGTestEnv("repeat", 1),
  200. "How many times to repeat each test. Specify a negative number "
  201. "for repeating forever. Useful for shaking out flaky tests.");
  202. GTEST_DEFINE_bool_(
  203. show_internal_stack_frames, false,
  204. "True iff " GTEST_NAME_ " should include internal stack frames when "
  205. "printing test failure stack traces.");
  206. GTEST_DEFINE_bool_(
  207. shuffle,
  208. internal::BoolFromGTestEnv("shuffle", false),
  209. "True iff " GTEST_NAME_
  210. " should randomize tests' order on every run.");
  211. GTEST_DEFINE_int32_(
  212. stack_trace_depth,
  213. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  214. "The maximum number of stack frames to print when an "
  215. "assertion fails. The valid range is 0 through 100, inclusive.");
  216. GTEST_DEFINE_string_(
  217. stream_result_to,
  218. internal::StringFromGTestEnv("stream_result_to", ""),
  219. "This flag specifies the host name and the port number on which to stream "
  220. "test results. Example: \"localhost:555\". The flag is effective only on "
  221. "Linux.");
  222. GTEST_DEFINE_bool_(
  223. throw_on_failure,
  224. internal::BoolFromGTestEnv("throw_on_failure", false),
  225. "When this flag is specified, a failed assertion will throw an exception "
  226. "if exceptions are enabled or exit the program with a non-zero code "
  227. "otherwise.");
  228. namespace internal {
  229. // Generates a random number from [0, range), using a Linear
  230. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  231. // than kMaxRange.
  232. UInt32 Random::Generate(UInt32 range) {
  233. // These constants are the same as are used in glibc's rand(3).
  234. state_ = (1103515245U*state_ + 12345U) % kMaxRange;
  235. GTEST_CHECK_(range > 0)
  236. << "Cannot generate a number in the range [0, 0).";
  237. GTEST_CHECK_(range <= kMaxRange)
  238. << "Generation of a number in [0, " << range << ") was requested, "
  239. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  240. // Converting via modulus introduces a bit of downward bias, but
  241. // it's simple, and a linear congruential generator isn't too good
  242. // to begin with.
  243. return state_ % range;
  244. }
  245. // GTestIsInitialized() returns true iff the user has initialized
  246. // Google Test. Useful for catching the user mistake of not initializing
  247. // Google Test before calling RUN_ALL_TESTS().
  248. //
  249. // A user must call testing::InitGoogleTest() to initialize Google
  250. // Test. g_init_gtest_count is set to the number of times
  251. // InitGoogleTest() has been called. We don't protect this variable
  252. // under a mutex as it is only accessed in the main thread.
  253. int g_init_gtest_count = 0;
  254. static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
  255. // Iterates over a vector of TestCases, keeping a running sum of the
  256. // results of calling a given int-returning method on each.
  257. // Returns the sum.
  258. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  259. int (TestCase::*method)() const) {
  260. int sum = 0;
  261. for (size_t i = 0; i < case_list.size(); i++) {
  262. sum += (case_list[i]->*method)();
  263. }
  264. return sum;
  265. }
  266. // Returns true iff the test case passed.
  267. static bool TestCasePassed(const TestCase* test_case) {
  268. return test_case->should_run() && test_case->Passed();
  269. }
  270. // Returns true iff the test case failed.
  271. static bool TestCaseFailed(const TestCase* test_case) {
  272. return test_case->should_run() && test_case->Failed();
  273. }
  274. // Returns true iff test_case contains at least one test that should
  275. // run.
  276. static bool ShouldRunTestCase(const TestCase* test_case) {
  277. return test_case->should_run();
  278. }
  279. // AssertHelper constructor.
  280. AssertHelper::AssertHelper(TestPartResult::Type type,
  281. const char* file,
  282. int line,
  283. const char* message)
  284. : data_(new AssertHelperData(type, file, line, message)) {
  285. }
  286. AssertHelper::~AssertHelper() {
  287. delete data_;
  288. }
  289. // Message assignment, for assertion streaming support.
  290. void AssertHelper::operator=(const Message& message) const {
  291. UnitTest::GetInstance()->
  292. AddTestPartResult(data_->type, data_->file, data_->line,
  293. AppendUserMessage(data_->message, message),
  294. UnitTest::GetInstance()->impl()
  295. ->CurrentOsStackTraceExceptTop(1)
  296. // Skips the stack frame for this function itself.
  297. ); // NOLINT
  298. }
  299. // Mutex for linked pointers.
  300. GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  301. // Application pathname gotten in InitGoogleTest.
  302. String g_executable_path;
  303. // Returns the current application's name, removing directory path if that
  304. // is present.
  305. FilePath GetCurrentExecutableName() {
  306. FilePath result;
  307. #if GTEST_OS_WINDOWS
  308. result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
  309. #else
  310. result.Set(FilePath(g_executable_path));
  311. #endif // GTEST_OS_WINDOWS
  312. return result.RemoveDirectoryName();
  313. }
  314. // Functions for processing the gtest_output flag.
  315. // Returns the output format, or "" for normal printed output.
  316. String UnitTestOptions::GetOutputFormat() {
  317. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  318. if (gtest_output_flag == NULL) return String("");
  319. const char* const colon = strchr(gtest_output_flag, ':');
  320. return (colon == NULL) ?
  321. String(gtest_output_flag) :
  322. String(gtest_output_flag, colon - gtest_output_flag);
  323. }
  324. // Returns the name of the requested output file, or the default if none
  325. // was explicitly specified.
  326. String UnitTestOptions::GetAbsolutePathToOutputFile() {
  327. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  328. if (gtest_output_flag == NULL)
  329. return String("");
  330. const char* const colon = strchr(gtest_output_flag, ':');
  331. if (colon == NULL)
  332. return String(internal::FilePath::ConcatPaths(
  333. internal::FilePath(
  334. UnitTest::GetInstance()->original_working_dir()),
  335. internal::FilePath(kDefaultOutputFile)).ToString() );
  336. internal::FilePath output_name(colon + 1);
  337. if (!output_name.IsAbsolutePath())
  338. // TODO([email protected]): on Windows \some\path is not an absolute
  339. // path (as its meaning depends on the current drive), yet the
  340. // following logic for turning it into an absolute path is wrong.
  341. // Fix it.
  342. output_name = internal::FilePath::ConcatPaths(
  343. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  344. internal::FilePath(colon + 1));
  345. if (!output_name.IsDirectory())
  346. return output_name.ToString();
  347. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  348. output_name, internal::GetCurrentExecutableName(),
  349. GetOutputFormat().c_str()));
  350. return result.ToString();
  351. }
  352. // Returns true iff the wildcard pattern matches the string. The
  353. // first ':' or '\0' character in pattern marks the end of it.
  354. //
  355. // This recursive algorithm isn't very efficient, but is clear and
  356. // works well enough for matching test names, which are short.
  357. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  358. const char *str) {
  359. switch (*pattern) {
  360. case '\0':
  361. case ':': // Either ':' or '\0' marks the end of the pattern.
  362. return *str == '\0';
  363. case '?': // Matches any single character.
  364. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  365. case '*': // Matches any string (possibly empty) of characters.
  366. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  367. PatternMatchesString(pattern + 1, str);
  368. default: // Non-special character. Matches itself.
  369. return *pattern == *str &&
  370. PatternMatchesString(pattern + 1, str + 1);
  371. }
  372. }
  373. bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
  374. const char *cur_pattern = filter;
  375. for (;;) {
  376. if (PatternMatchesString(cur_pattern, name.c_str())) {
  377. return true;
  378. }
  379. // Finds the next pattern in the filter.
  380. cur_pattern = strchr(cur_pattern, ':');
  381. // Returns if no more pattern can be found.
  382. if (cur_pattern == NULL) {
  383. return false;
  384. }
  385. // Skips the pattern separater (the ':' character).
  386. cur_pattern++;
  387. }
  388. }
  389. // TODO(keithray): move String function implementations to gtest-string.cc.
  390. // Returns true iff the user-specified filter matches the test case
  391. // name and the test name.
  392. bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
  393. const String &test_name) {
  394. const String& full_name = String::Format("%s.%s",
  395. test_case_name.c_str(),
  396. test_name.c_str());
  397. // Split --gtest_filter at '-', if there is one, to separate into
  398. // positive filter and negative filter portions
  399. const char* const p = GTEST_FLAG(filter).c_str();
  400. const char* const dash = strchr(p, '-');
  401. String positive;
  402. String negative;
  403. if (dash == NULL) {
  404. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  405. negative = String("");
  406. } else {
  407. positive = String(p, dash - p); // Everything up to the dash
  408. negative = String(dash+1); // Everything after the dash
  409. if (positive.empty()) {
  410. // Treat '-test1' as the same as '*-test1'
  411. positive = kUniversalFilter;
  412. }
  413. }
  414. // A filter is a colon-separated list of patterns. It matches a
  415. // test if any pattern in it matches the test.
  416. return (MatchesFilter(full_name, positive.c_str()) &&
  417. !MatchesFilter(full_name, negative.c_str()));
  418. }
  419. #if GTEST_HAS_SEH
  420. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  421. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  422. // This function is useful as an __except condition.
  423. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  424. // Google Test should handle a SEH exception if:
  425. // 1. the user wants it to, AND
  426. // 2. this is not a breakpoint exception, AND
  427. // 3. this is not a C++ exception (VC++ implements them via SEH,
  428. // apparently).
  429. //
  430. // SEH exception code for C++ exceptions.
  431. // (see http://support.microsoft.com/kb/185294 for more information).
  432. const DWORD kCxxExceptionCode = 0xe06d7363;
  433. bool should_handle = true;
  434. if (!GTEST_FLAG(catch_exceptions))
  435. should_handle = false;
  436. else if (exception_code == EXCEPTION_BREAKPOINT)
  437. should_handle = false;
  438. else if (exception_code == kCxxExceptionCode)
  439. should_handle = false;
  440. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  441. }
  442. #endif // GTEST_HAS_SEH
  443. } // namespace internal
  444. // The c'tor sets this object as the test part result reporter used by
  445. // Google Test. The 'result' parameter specifies where to report the
  446. // results. Intercepts only failures from the current thread.
  447. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  448. TestPartResultArray* result)
  449. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  450. result_(result) {
  451. Init();
  452. }
  453. // The c'tor sets this object as the test part result reporter used by
  454. // Google Test. The 'result' parameter specifies where to report the
  455. // results.
  456. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  457. InterceptMode intercept_mode, TestPartResultArray* result)
  458. : intercept_mode_(intercept_mode),
  459. result_(result) {
  460. Init();
  461. }
  462. void ScopedFakeTestPartResultReporter::Init() {
  463. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  464. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  465. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  466. impl->SetGlobalTestPartResultReporter(this);
  467. } else {
  468. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  469. impl->SetTestPartResultReporterForCurrentThread(this);
  470. }
  471. }
  472. // The d'tor restores the test part result reporter used by Google Test
  473. // before.
  474. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  475. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  476. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  477. impl->SetGlobalTestPartResultReporter(old_reporter_);
  478. } else {
  479. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  480. }
  481. }
  482. // Increments the test part result count and remembers the result.
  483. // This method is from the TestPartResultReporterInterface interface.
  484. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  485. const TestPartResult& result) {
  486. result_->Append(result);
  487. }
  488. namespace internal {
  489. // Returns the type ID of ::testing::Test. We should always call this
  490. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  491. // testing::Test. This is to work around a suspected linker bug when
  492. // using Google Test as a framework on Mac OS X. The bug causes
  493. // GetTypeId< ::testing::Test>() to return different values depending
  494. // on whether the call is from the Google Test framework itself or
  495. // from user test code. GetTestTypeId() is guaranteed to always
  496. // return the same value, as it always calls GetTypeId<>() from the
  497. // gtest.cc, which is within the Google Test framework.
  498. TypeId GetTestTypeId() {
  499. return GetTypeId<Test>();
  500. }
  501. // The value of GetTestTypeId() as seen from within the Google Test
  502. // library. This is solely for testing GetTestTypeId().
  503. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  504. // This predicate-formatter checks that 'results' contains a test part
  505. // failure of the given type and that the failure message contains the
  506. // given substring.
  507. AssertionResult HasOneFailure(const char* /* results_expr */,
  508. const char* /* type_expr */,
  509. const char* /* substr_expr */,
  510. const TestPartResultArray& results,
  511. TestPartResult::Type type,
  512. const string& substr) {
  513. const String expected(type == TestPartResult::kFatalFailure ?
  514. "1 fatal failure" :
  515. "1 non-fatal failure");
  516. Message msg;
  517. if (results.size() != 1) {
  518. msg << "Expected: " << expected << "\n"
  519. << " Actual: " << results.size() << " failures";
  520. for (int i = 0; i < results.size(); i++) {
  521. msg << "\n" << results.GetTestPartResult(i);
  522. }
  523. return AssertionFailure() << msg;
  524. }
  525. const TestPartResult& r = results.GetTestPartResult(0);
  526. if (r.type() != type) {
  527. return AssertionFailure() << "Expected: " << expected << "\n"
  528. << " Actual:\n"
  529. << r;
  530. }
  531. if (strstr(r.message(), substr.c_str()) == NULL) {
  532. return AssertionFailure() << "Expected: " << expected << " containing \""
  533. << substr << "\"\n"
  534. << " Actual:\n"
  535. << r;
  536. }
  537. return AssertionSuccess();
  538. }
  539. // The constructor of SingleFailureChecker remembers where to look up
  540. // test part results, what type of failure we expect, and what
  541. // substring the failure message should contain.
  542. SingleFailureChecker:: SingleFailureChecker(
  543. const TestPartResultArray* results,
  544. TestPartResult::Type type,
  545. const string& substr)
  546. : results_(results),
  547. type_(type),
  548. substr_(substr) {}
  549. // The destructor of SingleFailureChecker verifies that the given
  550. // TestPartResultArray contains exactly one failure that has the given
  551. // type and contains the given substring. If that's not the case, a
  552. // non-fatal failure will be generated.
  553. SingleFailureChecker::~SingleFailureChecker() {
  554. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  555. }
  556. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  557. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  558. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  559. const TestPartResult& result) {
  560. unit_test_->current_test_result()->AddTestPartResult(result);
  561. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  562. }
  563. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  564. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  565. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  566. const TestPartResult& result) {
  567. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  568. }
  569. // Returns the global test part result reporter.
  570. TestPartResultReporterInterface*
  571. UnitTestImpl::GetGlobalTestPartResultReporter() {
  572. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  573. return global_test_part_result_repoter_;
  574. }
  575. // Sets the global test part result reporter.
  576. void UnitTestImpl::SetGlobalTestPartResultReporter(
  577. TestPartResultReporterInterface* reporter) {
  578. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  579. global_test_part_result_repoter_ = reporter;
  580. }
  581. // Returns the test part result reporter for the current thread.
  582. TestPartResultReporterInterface*
  583. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  584. return per_thread_test_part_result_reporter_.get();
  585. }
  586. // Sets the test part result reporter for the current thread.
  587. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  588. TestPartResultReporterInterface* reporter) {
  589. per_thread_test_part_result_reporter_.set(reporter);
  590. }
  591. // Gets the number of successful test cases.
  592. int UnitTestImpl::successful_test_case_count() const {
  593. return CountIf(test_cases_, TestCasePassed);
  594. }
  595. // Gets the number of failed test cases.
  596. int UnitTestImpl::failed_test_case_count() const {
  597. return CountIf(test_cases_, TestCaseFailed);
  598. }
  599. // Gets the number of all test cases.
  600. int UnitTestImpl::total_test_case_count() const {
  601. return static_cast<int>(test_cases_.size());
  602. }
  603. // Gets the number of all test cases that contain at least one test
  604. // that should run.
  605. int UnitTestImpl::test_case_to_run_count() const {
  606. return CountIf(test_cases_, ShouldRunTestCase);
  607. }
  608. // Gets the number of successful tests.
  609. int UnitTestImpl::successful_test_count() const {
  610. return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  611. }
  612. // Gets the number of failed tests.
  613. int UnitTestImpl::failed_test_count() const {
  614. return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  615. }
  616. // Gets the number of disabled tests.
  617. int UnitTestImpl::disabled_test_count() const {
  618. return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  619. }
  620. // Gets the number of all tests.
  621. int UnitTestImpl::total_test_count() const {
  622. return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  623. }
  624. // Gets the number of tests that should run.
  625. int UnitTestImpl::test_to_run_count() const {
  626. return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  627. }
  628. // Returns the current OS stack trace as a String.
  629. //
  630. // The maximum number of stack frames to be included is specified by
  631. // the gtest_stack_trace_depth flag. The skip_count parameter
  632. // specifies the number of top frames to be skipped, which doesn't
  633. // count against the number of frames to be included.
  634. //
  635. // For example, if Foo() calls Bar(), which in turn calls
  636. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  637. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  638. String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  639. (void)skip_count;
  640. return String("");
  641. }
  642. // Returns the current time in milliseconds.
  643. TimeInMillis GetTimeInMillis() {
  644. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  645. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  646. // http://analogous.blogspot.com/2005/04/epoch.html
  647. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  648. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  649. const DWORD kTenthMicrosInMilliSecond = 10000;
  650. SYSTEMTIME now_systime;
  651. FILETIME now_filetime;
  652. ULARGE_INTEGER now_int64;
  653. // TODO([email protected]): Shouldn't this just use
  654. // GetSystemTimeAsFileTime()?
  655. GetSystemTime(&now_systime);
  656. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  657. now_int64.LowPart = now_filetime.dwLowDateTime;
  658. now_int64.HighPart = now_filetime.dwHighDateTime;
  659. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  660. kJavaEpochToWinFileTimeDelta;
  661. return now_int64.QuadPart;
  662. }
  663. return 0;
  664. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  665. __timeb64 now;
  666. # ifdef _MSC_VER
  667. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  668. // (deprecated function) there.
  669. // TODO([email protected]): Use GetTickCount()? Or use
  670. // SystemTimeToFileTime()
  671. # pragma warning(push) // Saves the current warning state.
  672. # pragma warning(disable:4996) // Temporarily disables warning 4996.
  673. _ftime64(&now);
  674. # pragma warning(pop) // Restores the warning state.
  675. # else
  676. _ftime64(&now);
  677. # endif // _MSC_VER
  678. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  679. #elif GTEST_HAS_GETTIMEOFDAY_
  680. struct timeval now;
  681. gettimeofday(&now, NULL);
  682. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  683. #else
  684. # error "Don't know how to get the current time on your system."
  685. #endif
  686. }
  687. // Utilities
  688. // class String
  689. // Returns the input enclosed in double quotes if it's not NULL;
  690. // otherwise returns "(null)". For example, "\"Hello\"" is returned
  691. // for input "Hello".
  692. //
  693. // This is useful for printing a C string in the syntax of a literal.
  694. //
  695. // Known issue: escape sequences are not handled yet.
  696. String String::ShowCStringQuoted(const char* c_str) {
  697. return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
  698. }
  699. // Copies at most length characters from str into a newly-allocated
  700. // piece of memory of size length+1. The memory is allocated with new[].
  701. // A terminating null byte is written to the memory, and a pointer to it
  702. // is returned. If str is NULL, NULL is returned.
  703. static char* CloneString(const char* str, size_t length) {
  704. if (str == NULL) {
  705. return NULL;
  706. } else {
  707. char* const clone = new char[length + 1];
  708. posix::StrNCpy(clone, str, length);
  709. clone[length] = '\0';
  710. return clone;
  711. }
  712. }
  713. // Clones a 0-terminated C string, allocating memory using new. The
  714. // caller is responsible for deleting[] the return value. Returns the
  715. // cloned string, or NULL if the input is NULL.
  716. const char * String::CloneCString(const char* c_str) {
  717. return (c_str == NULL) ?
  718. NULL : CloneString(c_str, strlen(c_str));
  719. }
  720. #if GTEST_OS_WINDOWS_MOBILE
  721. // Creates a UTF-16 wide string from the given ANSI string, allocating
  722. // memory using new. The caller is responsible for deleting the return
  723. // value using delete[]. Returns the wide string, or NULL if the
  724. // input is NULL.
  725. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  726. if (!ansi) return NULL;
  727. const int length = strlen(ansi);
  728. const int unicode_length =
  729. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  730. NULL, 0);
  731. WCHAR* unicode = new WCHAR[unicode_length + 1];
  732. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  733. unicode, unicode_length);
  734. unicode[unicode_length] = 0;
  735. return unicode;
  736. }
  737. // Creates an ANSI string from the given wide string, allocating
  738. // memory using new. The caller is responsible for deleting the return
  739. // value using delete[]. Returns the ANSI string, or NULL if the
  740. // input is NULL.
  741. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  742. if (!utf16_str) return NULL;
  743. const int ansi_length =
  744. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  745. NULL, 0, NULL, NULL);
  746. char* ansi = new char[ansi_length + 1];
  747. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  748. ansi, ansi_length, NULL, NULL);
  749. ansi[ansi_length] = 0;
  750. return ansi;
  751. }
  752. #endif // GTEST_OS_WINDOWS_MOBILE
  753. // Compares two C strings. Returns true iff they have the same content.
  754. //
  755. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  756. // C string is considered different to any non-NULL C string,
  757. // including the empty string.
  758. bool String::CStringEquals(const char * lhs, const char * rhs) {
  759. if ( lhs == NULL ) return rhs == NULL;
  760. if ( rhs == NULL ) return false;
  761. return strcmp(lhs, rhs) == 0;
  762. }
  763. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  764. // Converts an array of wide chars to a narrow string using the UTF-8
  765. // encoding, and streams the result to the given Message object.
  766. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  767. Message* msg) {
  768. // TODO(wan): consider allowing a testing::String object to
  769. // contain '\0'. This will make it behave more like std::string,
  770. // and will allow ToUtf8String() to return the correct encoding
  771. // for '\0' s.t. we can get rid of the conditional here (and in
  772. // several other places).
  773. for (size_t i = 0; i != length; ) { // NOLINT
  774. if (wstr[i] != L'\0') {
  775. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  776. while (i != length && wstr[i] != L'\0')
  777. i++;
  778. } else {
  779. *msg << '\0';
  780. i++;
  781. }
  782. }
  783. }
  784. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  785. } // namespace internal
  786. #if GTEST_HAS_STD_WSTRING
  787. // Converts the given wide string to a narrow string using the UTF-8
  788. // encoding, and streams the result to this Message object.
  789. Message& Message::operator <<(const ::std::wstring& wstr) {
  790. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  791. return *this;
  792. }
  793. #endif // GTEST_HAS_STD_WSTRING
  794. #if GTEST_HAS_GLOBAL_WSTRING
  795. // Converts the given wide string to a narrow string using the UTF-8
  796. // encoding, and streams the result to this Message object.
  797. Message& Message::operator <<(const ::wstring& wstr) {
  798. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  799. return *this;
  800. }
  801. #endif // GTEST_HAS_GLOBAL_WSTRING
  802. // AssertionResult constructors.
  803. // Used in EXPECT_TRUE/FALSE(assertion_result).
  804. AssertionResult::AssertionResult(const AssertionResult& other)
  805. : success_(other.success_),
  806. message_(other.message_.get() != NULL ?
  807. new ::std::string(*other.message_) :
  808. static_cast< ::std::string*>(NULL)) {
  809. }
  810. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  811. AssertionResult AssertionResult::operator!() const {
  812. AssertionResult negation(!success_);
  813. if (message_.get() != NULL)
  814. negation << *message_;
  815. return negation;
  816. }
  817. // Makes a successful assertion result.
  818. AssertionResult AssertionSuccess() {
  819. return AssertionResult(true);
  820. }
  821. // Makes a failed assertion result.
  822. AssertionResult AssertionFailure() {
  823. return AssertionResult(false);
  824. }
  825. // Makes a failed assertion result with the given failure message.
  826. // Deprecated; use AssertionFailure() << message.
  827. AssertionResult AssertionFailure(const Message& message) {
  828. return AssertionFailure() << message;
  829. }
  830. namespace internal {
  831. // Constructs and returns the message for an equality assertion
  832. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  833. //
  834. // The first four parameters are the expressions used in the assertion
  835. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  836. // where foo is 5 and bar is 6, we have:
  837. //
  838. // expected_expression: "foo"
  839. // actual_expression: "bar"
  840. // expected_value: "5"
  841. // actual_value: "6"
  842. //
  843. // The ignoring_case parameter is true iff the assertion is a
  844. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  845. // be inserted into the message.
  846. AssertionResult EqFailure(const char* expected_expression,
  847. const char* actual_expression,
  848. const String& expected_value,
  849. const String& actual_value,
  850. bool ignoring_case) {
  851. Message msg;
  852. msg << "Value of: " << actual_expression;
  853. if (actual_value != actual_expression) {
  854. msg << "\n Actual: " << actual_value;
  855. }
  856. msg << "\nExpected: " << expected_expression;
  857. if (ignoring_case) {
  858. msg << " (ignoring case)";
  859. }
  860. if (expected_value != expected_expression) {
  861. msg << "\nWhich is: " << expected_value;
  862. }
  863. return AssertionFailure() << msg;
  864. }
  865. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  866. String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
  867. const char* expression_text,
  868. const char* actual_predicate_value,
  869. const char* expected_predicate_value) {
  870. const char* actual_message = assertion_result.message();
  871. Message msg;
  872. msg << "Value of: " << expression_text
  873. << "\n Actual: " << actual_predicate_value;
  874. if (actual_message[0] != '\0')
  875. msg << " (" << actual_message << ")";
  876. msg << "\nExpected: " << expected_predicate_value;
  877. return msg.GetString();
  878. }
  879. // Helper function for implementing ASSERT_NEAR.
  880. AssertionResult DoubleNearPredFormat(const char* expr1,
  881. const char* expr2,
  882. const char* abs_error_expr,
  883. double val1,
  884. double val2,
  885. double abs_error) {
  886. const double diff = fabs(val1 - val2);
  887. if (diff <= abs_error) return AssertionSuccess();
  888. // TODO(wan): do not print the value of an expression if it's
  889. // already a literal.
  890. return AssertionFailure()
  891. << "The difference between " << expr1 << " and " << expr2
  892. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  893. << expr1 << " evaluates to " << val1 << ",\n"
  894. << expr2 << " evaluates to " << val2 << ", and\n"
  895. << abs_error_expr << " evaluates to " << abs_error << ".";
  896. }
  897. // Helper template for implementing FloatLE() and DoubleLE().
  898. template <typename RawType>
  899. AssertionResult FloatingPointLE(const char* expr1,
  900. const char* expr2,
  901. RawType val1,
  902. RawType val2) {
  903. // Returns success if val1 is less than val2,
  904. if (val1 < val2) {
  905. return AssertionSuccess();
  906. }
  907. // or if val1 is almost equal to val2.
  908. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  909. if (lhs.AlmostEquals(rhs)) {
  910. return AssertionSuccess();
  911. }
  912. // Note that the above two checks will both fail if either val1 or
  913. // val2 is NaN, as the IEEE floating-point standard requires that
  914. // any predicate involving a NaN must return false.
  915. ::std::stringstream val1_ss;
  916. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  917. << val1;
  918. ::std::stringstream val2_ss;
  919. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  920. << val2;
  921. return AssertionFailure()
  922. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  923. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  924. << StringStreamToString(&val2_ss);
  925. }
  926. } // namespace internal
  927. // Asserts that val1 is less than, or almost equal to, val2. Fails
  928. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  929. AssertionResult FloatLE(const char* expr1, const char* expr2,
  930. float val1, float val2) {
  931. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  932. }
  933. // Asserts that val1 is less than, or almost equal to, val2. Fails
  934. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  935. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  936. double val1, double val2) {
  937. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  938. }
  939. namespace internal {
  940. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  941. // arguments.
  942. AssertionResult CmpHelperEQ(const char* expected_expression,
  943. const char* actual_expression,
  944. BiggestInt expected,
  945. BiggestInt actual) {
  946. if (expected == actual) {
  947. return AssertionSuccess();
  948. }
  949. return EqFailure(expected_expression,
  950. actual_expression,
  951. FormatForComparisonFailureMessage(expected, actual),
  952. FormatForComparisonFailureMessage(actual, expected),
  953. false);
  954. }
  955. // A macro for implementing the helper functions needed to implement
  956. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  957. // just to avoid copy-and-paste of similar code.
  958. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  959. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  960. BiggestInt val1, BiggestInt val2) {\
  961. if (val1 op val2) {\
  962. return AssertionSuccess();\
  963. } else {\
  964. return AssertionFailure() \
  965. << "Expected: (" << expr1 << ") " #op " (" << expr2\
  966. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  967. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  968. }\
  969. }
  970. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  971. // enum arguments.
  972. GTEST_IMPL_CMP_HELPER_(NE, !=)
  973. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  974. // enum arguments.
  975. GTEST_IMPL_CMP_HELPER_(LE, <=)
  976. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  977. // enum arguments.
  978. GTEST_IMPL_CMP_HELPER_(LT, < )
  979. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  980. // enum arguments.
  981. GTEST_IMPL_CMP_HELPER_(GE, >=)
  982. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  983. // enum arguments.
  984. GTEST_IMPL_CMP_HELPER_(GT, > )
  985. #undef GTEST_IMPL_CMP_HELPER_
  986. // The helper function for {ASSERT|EXPECT}_STREQ.
  987. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  988. const char* actual_expression,
  989. const char* expected,
  990. const char* actual) {
  991. if (String::CStringEquals(expected, actual)) {
  992. return AssertionSuccess();
  993. }
  994. return EqFailure(expected_expression,
  995. actual_expression,
  996. String::ShowCStringQuoted(expected),
  997. String::ShowCStringQuoted(actual),
  998. false);
  999. }
  1000. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  1001. AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
  1002. const char* actual_expression,
  1003. const char* expected,
  1004. const char* actual) {
  1005. if (String::CaseInsensitiveCStringEquals(expected, actual)) {
  1006. return AssertionSuccess();
  1007. }
  1008. return EqFailure(expected_expression,
  1009. actual_expression,
  1010. String::ShowCStringQuoted(expected),
  1011. String::ShowCStringQuoted(actual),
  1012. true);
  1013. }
  1014. // The helper function for {ASSERT|EXPECT}_STRNE.
  1015. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1016. const char* s2_expression,
  1017. const char* s1,
  1018. const char* s2) {
  1019. if (!String::CStringEquals(s1, s2)) {
  1020. return AssertionSuccess();
  1021. } else {
  1022. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  1023. << s2_expression << "), actual: \""
  1024. << s1 << "\" vs \"" << s2 << "\"";
  1025. }
  1026. }
  1027. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  1028. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  1029. const char* s2_expression,
  1030. const char* s1,
  1031. const char* s2) {
  1032. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  1033. return AssertionSuccess();
  1034. } else {
  1035. return AssertionFailure()
  1036. << "Expected: (" << s1_expression << ") != ("
  1037. << s2_expression << ") (ignoring case), actual: \""
  1038. << s1 << "\" vs \"" << s2 << "\"";
  1039. }
  1040. }
  1041. } // namespace internal
  1042. namespace {
  1043. // Helper functions for implementing IsSubString() and IsNotSubstring().
  1044. // This group of overloaded functions return true iff needle is a
  1045. // substring of haystack. NULL is considered a substring of itself
  1046. // only.
  1047. bool IsSubstringPred(const char* needle, const char* haystack) {
  1048. if (needle == NULL || haystack == NULL)
  1049. return needle == haystack;
  1050. return strstr(haystack, needle) != NULL;
  1051. }
  1052. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  1053. if (needle == NULL || haystack == NULL)
  1054. return needle == haystack;
  1055. return wcsstr(haystack, needle) != NULL;
  1056. }
  1057. // StringType here can be either ::std::string or ::std::wstring.
  1058. template <typename StringType>
  1059. bool IsSubstringPred(const StringType& needle,
  1060. const StringType& haystack) {
  1061. return haystack.find(needle) != StringType::npos;
  1062. }
  1063. // This function implements either IsSubstring() or IsNotSubstring(),
  1064. // depending on the value of the expected_to_be_substring parameter.
  1065. // StringType here can be const char*, const wchar_t*, ::std::string,
  1066. // or ::std::wstring.
  1067. template <typename StringType>
  1068. AssertionResult IsSubstringImpl(
  1069. bool expected_to_be_substring,
  1070. const char* needle_expr, const char* haystack_expr,
  1071. const StringType& needle, const StringType& haystack) {
  1072. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  1073. return AssertionSuccess();
  1074. const bool is_wide_string = sizeof(needle[0]) > 1;
  1075. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  1076. return AssertionFailure()
  1077. << "Value of: " << needle_expr << "\n"
  1078. << " Actual: " << begin_string_quote << needle << "\"\n"
  1079. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  1080. << "a substring of " << haystack_expr << "\n"
  1081. << "Which is: " << begin_string_quote << haystack << "\"";
  1082. }
  1083. } // namespace
  1084. // IsSubstring() and IsNotSubstring() check whether needle is a
  1085. // substring of haystack (NULL is considered a substring of itself
  1086. // only), and return an appropriate error message when they fail.
  1087. AssertionResult IsSubstring(
  1088. const char* needle_expr, const char* haystack_expr,
  1089. const char* needle, const char* haystack) {
  1090. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1091. }
  1092. AssertionResult IsSubstring(
  1093. const char* needle_expr, const char* haystack_expr,
  1094. const wchar_t* needle, const wchar_t* haystack) {
  1095. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1096. }
  1097. AssertionResult IsNotSubstring(
  1098. const char* needle_expr, const char* haystack_expr,
  1099. const char* needle, const char* haystack) {
  1100. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1101. }
  1102. AssertionResult IsNotSubstring(
  1103. const char* needle_expr, const char* haystack_expr,
  1104. const wchar_t* needle, const wchar_t* haystack) {
  1105. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1106. }
  1107. AssertionResult IsSubstring(
  1108. const char* needle_expr, const char* haystack_expr,
  1109. const ::std::string& needle, const ::std::string& haystack) {
  1110. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1111. }
  1112. AssertionResult IsNotSubstring(
  1113. const char* needle_expr, const char* haystack_expr,
  1114. const ::std::string& needle, const ::std::string& haystack) {
  1115. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1116. }
  1117. #if GTEST_HAS_STD_WSTRING
  1118. AssertionResult IsSubstring(
  1119. const char* needle_expr, const char* haystack_expr,
  1120. const ::std::wstring& needle, const ::std::wstring& haystack) {
  1121. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1122. }
  1123. AssertionResult IsNotSubstring(
  1124. const char* needle_expr, const char* haystack_expr,
  1125. const ::std::wstring& needle, const ::std::wstring& haystack) {
  1126. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1127. }
  1128. #endif // GTEST_HAS_STD_WSTRING
  1129. namespace internal {
  1130. #if GTEST_OS_WINDOWS
  1131. namespace {
  1132. // Helper function for IsHRESULT{SuccessFailure} predicates
  1133. AssertionResult HRESULTFailureHelper(const char* expr,
  1134. const char* expected,
  1135. long hr) { // NOLINT
  1136. # if GTEST_OS_WINDOWS_MOBILE
  1137. // Windows CE doesn't support FormatMessage.
  1138. const char error_text[] = "";
  1139. # else
  1140. // Looks up the human-readable system message for the HRESULT code
  1141. // and since we're not passing any params to FormatMessage, we don't
  1142. // want inserts expanded.
  1143. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  1144. FORMAT_MESSAGE_IGNORE_INSERTS;
  1145. const DWORD kBufSize = 4096; // String::Format can't exceed this length.
  1146. // Gets the system's human readable message string for this HRESULT.
  1147. char error_text[kBufSize] = { '\0' };
  1148. DWORD message_length = ::FormatMessageA(kFlags,
  1149. 0, // no source, we're asking system
  1150. hr, // the error
  1151. 0, // no line width restrictions
  1152. error_text, // output buffer
  1153. kBufSize, // buf size
  1154. NULL); // no arguments for inserts
  1155. // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
  1156. for (; message_length && IsSpace(error_text[message_length - 1]);
  1157. --message_length) {
  1158. error_text[message_length - 1] = '\0';
  1159. }
  1160. # endif // GTEST_OS_WINDOWS_MOBILE
  1161. const String error_hex(String::Format("0x%08X ", hr));
  1162. return ::testing::AssertionFailure()
  1163. << "Expected: " << expr << " " << expected << ".\n"
  1164. << " Actual: " << error_hex << error_text << "\n";
  1165. }
  1166. } // namespace
  1167. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  1168. if (SUCCEEDED(hr)) {
  1169. return AssertionSuccess();
  1170. }
  1171. return HRESULTFailureHelper(expr, "succeeds", hr);
  1172. }
  1173. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  1174. if (FAILED(hr)) {
  1175. return AssertionSuccess();
  1176. }
  1177. return HRESULTFailureHelper(expr, "fails", hr);
  1178. }
  1179. #endif // GTEST_OS_WINDOWS
  1180. // Utility functions for encoding Unicode text (wide strings) in
  1181. // UTF-8.
  1182. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
  1183. // like this:
  1184. //
  1185. // Code-point length Encoding
  1186. // 0 - 7 bits 0xxxxxxx
  1187. // 8 - 11 bits 110xxxxx 10xxxxxx
  1188. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  1189. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1190. // The maximum code-point a one-byte UTF-8 sequence can represent.
  1191. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  1192. // The maximum code-point a two-byte UTF-8 sequence can represent.
  1193. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  1194. // The maximum code-point a three-byte UTF-8 sequence can represent.
  1195. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  1196. // The maximum code-point a four-byte UTF-8 sequence can represent.
  1197. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  1198. // Chops off the n lowest bits from a bit pattern. Returns the n
  1199. // lowest bits. As a side effect, the original bit pattern will be
  1200. // shifted to the right by n bits.
  1201. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  1202. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  1203. *bits >>= n;
  1204. return low_bits;
  1205. }
  1206. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  1207. // code_point parameter is of type UInt32 because wchar_t may not be
  1208. // wide enough to contain a code point.
  1209. // The output buffer str must containt at least 32 characters.
  1210. // The function returns the address of the output buffer.
  1211. // If the code_point is not a valid Unicode code point
  1212. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
  1213. // as '(Invalid Unicode 0xXXXXXXXX)'.
  1214. char* CodePointToUtf8(UInt32 code_point, char* str) {
  1215. if (code_point <= kMaxCodePoint1) {
  1216. str[1] = '\0';
  1217. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  1218. } else if (code_point <= kMaxCodePoint2) {
  1219. str[2] = '\0';
  1220. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1221. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  1222. } else if (code_point <= kMaxCodePoint3) {
  1223. str[3] = '\0';
  1224. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1225. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1226. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  1227. } else if (code_point <= kMaxCodePoint4) {
  1228. str[4] = '\0';
  1229. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1230. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1231. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1232. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  1233. } else {
  1234. // The longest string String::Format can produce when invoked
  1235. // with these parameters is 28 character long (not including
  1236. // the terminating nul character). We are asking for 32 character
  1237. // buffer just in case. This is also enough for strncpy to
  1238. // null-terminate the destination string.
  1239. posix::StrNCpy(
  1240. str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
  1241. str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
  1242. // the result unterminated.
  1243. }
  1244. return str;
  1245. }
  1246. // The following two functions only make sense if the the system
  1247. // uses UTF-16 for wide string encoding. All supported systems
  1248. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  1249. // Determines if the arguments constitute UTF-16 surrogate pair
  1250. // and thus should be combined into a single Unicode code point
  1251. // using CreateCodePointFromUtf16SurrogatePair.
  1252. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  1253. return sizeof(wchar_t) == 2 &&
  1254. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  1255. }
  1256. // Creates a Unicode code point from UTF16 surrogate pair.
  1257. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  1258. wchar_t second) {
  1259. const UInt32 mask = (1 << 10) - 1;
  1260. return (sizeof(wchar_t) == 2) ?
  1261. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  1262. // This function should not be called when the condition is
  1263. // false, but we provide a sensible default in case it is.
  1264. static_cast<UInt32>(first);
  1265. }
  1266. // Converts a wide string to a narrow string in UTF-8 encoding.
  1267. // The wide string is assumed to have the following encoding:
  1268. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  1269. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  1270. // Parameter str points to a null-terminated wide string.
  1271. // Parameter num_chars may additionally limit the number
  1272. // of wchar_t characters processed. -1 is used when the entire string
  1273. // should be processed.
  1274. // If the string contains code points that are not valid Unicode code points
  1275. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  1276. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  1277. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  1278. // will be encoded as individual Unicode characters from Basic Normal Plane.
  1279. String WideStringToUtf8(const wchar_t* str, int num_chars) {
  1280. if (num_chars == -1)
  1281. num_chars = static_cast<int>(wcslen(str));
  1282. ::std::stringstream stream;
  1283. for (int i = 0; i < num_chars; ++i) {
  1284. UInt32 unicode_code_point;
  1285. if (str[i] == L'\0') {
  1286. break;
  1287. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  1288. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  1289. str[i + 1]);
  1290. i++;
  1291. } else {
  1292. unicode_code_point = static_cast<UInt32>(str[i]);
  1293. }
  1294. char buffer[32]; // CodePointToUtf8 requires a buffer this big.
  1295. stream << CodePointToUtf8(unicode_code_point, buffer);
  1296. }
  1297. return StringStreamToString(&stream);
  1298. }
  1299. // Converts a wide C string to a String using the UTF-8 encoding.
  1300. // NULL will be converted to "(null)".
  1301. String String::ShowWideCString(const wchar_t * wide_c_str) {
  1302. if (wide_c_str == NULL) return String("(null)");
  1303. return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
  1304. }
  1305. // Similar to ShowWideCString(), except that this function encloses
  1306. // the converted string in double quotes.
  1307. String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
  1308. if (wide_c_str == NULL) return String("(null)");
  1309. return String::Format("L\"%s\"",
  1310. String::ShowWideCString(wide_c_str).c_str());
  1311. }
  1312. // Compares two wide C strings. Returns true iff they have the same
  1313. // content.
  1314. //
  1315. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  1316. // C string is considered different to any non-NULL C string,
  1317. // including the empty string.
  1318. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  1319. if (lhs == NULL) return rhs == NULL;
  1320. if (rhs == NULL) return false;
  1321. return wcscmp(lhs, rhs) == 0;
  1322. }
  1323. // Helper function for *_STREQ on wide strings.
  1324. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  1325. const char* actual_expression,
  1326. const wchar_t* expected,
  1327. const wchar_t* actual) {
  1328. if (String::WideCStringEquals(expected, actual)) {
  1329. return AssertionSuccess();
  1330. }
  1331. return EqFailure(expected_expression,
  1332. actual_expression,
  1333. String::ShowWideCStringQuoted(expected),
  1334. String::ShowWideCStringQuoted(actual),
  1335. false);
  1336. }
  1337. // Helper function for *_STRNE on wide strings.
  1338. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1339. const char* s2_expression,
  1340. const wchar_t* s1,
  1341. const wchar_t* s2) {
  1342. if (!String::WideCStringEquals(s1, s2)) {
  1343. return AssertionSuccess();
  1344. }
  1345. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  1346. << s2_expression << "), actual: "
  1347. << String::ShowWideCStringQuoted(s1)
  1348. << " vs " << String::ShowWideCStringQuoted(s2);
  1349. }
  1350. // Compares two C strings, ignoring case. Returns true iff they have
  1351. // the same content.
  1352. //
  1353. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  1354. // NULL C string is considered different to any non-NULL C string,
  1355. // including the empty string.
  1356. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  1357. if (lhs == NULL)
  1358. return rhs == NULL;
  1359. if (rhs == NULL)
  1360. return false;
  1361. return posix::StrCaseCmp(lhs, rhs) == 0;
  1362. }
  1363. // Compares two wide C strings, ignoring case. Returns true iff they
  1364. // have the same content.
  1365. //
  1366. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  1367. // A NULL C string is considered different to any non-NULL wide C string,
  1368. // including the empty string.
  1369. // NB: The implementations on different platforms slightly differ.
  1370. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  1371. // environment variable. On GNU platform this method uses wcscasecmp
  1372. // which compares according to LC_CTYPE category of the current locale.
  1373. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  1374. // current locale.
  1375. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  1376. const wchar_t* rhs) {
  1377. if (lhs == NULL) return rhs == NULL;
  1378. if (rhs == NULL) return false;
  1379. #if GTEST_OS_WINDOWS
  1380. return _wcsicmp(lhs, rhs) == 0;
  1381. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  1382. return wcscasecmp(lhs, rhs) == 0;
  1383. #else
  1384. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  1385. // Other unknown OSes may not define it either.
  1386. wint_t left, right;
  1387. do {
  1388. left = towlower(*lhs++);
  1389. right = towlower(*rhs++);
  1390. } while (left && left == right);
  1391. return left == right;
  1392. #endif // OS selector
  1393. }
  1394. // Compares this with another String.
  1395. // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
  1396. // if this is greater than rhs.
  1397. int String::Compare(const String & rhs) const {
  1398. const char* const lhs_c_str = c_str();
  1399. const char* const rhs_c_str = rhs.c_str();
  1400. if (lhs_c_str == NULL) {
  1401. return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
  1402. } else if (rhs_c_str == NULL) {
  1403. return 1;
  1404. }
  1405. const size_t shorter_str_len =
  1406. length() <= rhs.length() ? length() : rhs.length();
  1407. for (size_t i = 0; i != shorter_str_len; i++) {
  1408. if (lhs_c_str[i] < rhs_c_str[i]) {
  1409. return -1;
  1410. } else if (lhs_c_str[i] > rhs_c_str[i]) {
  1411. return 1;
  1412. }
  1413. }
  1414. return (length() < rhs.length()) ? -1 :
  1415. (length() > rhs.length()) ? 1 : 0;
  1416. }
  1417. // Returns true iff this String ends with the given suffix. *Any*
  1418. // String is considered to end with a NULL or empty suffix.
  1419. bool String::EndsWith(const char* suffix) const {
  1420. if (suffix == NULL || CStringEquals(suffix, "")) return true;
  1421. if (c_str() == NULL) return false;
  1422. const size_t this_len = strlen(c_str());
  1423. const size_t suffix_len = strlen(suffix);
  1424. return (this_len >= suffix_len) &&
  1425. CStringEquals(c_str() + this_len - suffix_len, suffix);
  1426. }
  1427. // Returns true iff this String ends with the given suffix, ignoring case.
  1428. // Any String is considered to end with a NULL or empty suffix.
  1429. bool String::EndsWithCaseInsensitive(const char* suffix) const {
  1430. if (suffix == NULL || CStringEquals(suffix, "")) return true;
  1431. if (c_str() == NULL) return false;
  1432. const size_t this_len = strlen(c_str());
  1433. const size_t suffix_len = strlen(suffix);
  1434. return (this_len >= suffix_len) &&
  1435. CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
  1436. }
  1437. // Formats a list of arguments to a String, using the same format
  1438. // spec string as for printf.
  1439. //
  1440. // We do not use the StringPrintf class as it is not universally
  1441. // available.
  1442. //
  1443. // The result is limited to 4096 characters (including the tailing 0).
  1444. // If 4096 characters are not enough to format the input, or if
  1445. // there's an error, "<formatting error or buffer exceeded>" is
  1446. // returned.
  1447. String String::Format(const char * format, ...) {
  1448. va_list args;
  1449. va_start(args, format);
  1450. char buffer[4096];
  1451. const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
  1452. // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
  1453. // 4996 (deprecated function) there.
  1454. #ifdef _MSC_VER // We are using MSVC.
  1455. # pragma warning(push) // Saves the current warning state.
  1456. # pragma warning(disable:4996) // Temporarily disables warning 4996.
  1457. const int size = vsnprintf(buffer, kBufferSize, format, args);
  1458. # pragma warning(pop) // Restores the warning state.
  1459. #else // We are not using MSVC.
  1460. const int size = vsnprintf(buffer, kBufferSize, format, args);
  1461. #endif // _MSC_VER
  1462. va_end(args);
  1463. // vsnprintf()'s behavior is not portable. When the buffer is not
  1464. // big enough, it returns a negative value in MSVC, and returns the
  1465. // needed buffer size on Linux. When there is an output error, it
  1466. // always returns a negative value. For simplicity, we lump the two
  1467. // error cases together.
  1468. if (size < 0 || size >= kBufferSize) {
  1469. return String("<formatting error or buffer exceeded>");
  1470. } else {
  1471. return String(buffer, size);
  1472. }
  1473. }
  1474. // Converts the buffer in a stringstream to a String, converting NUL
  1475. // bytes to "\\0" along the way.
  1476. String StringStreamToString(::std::stringstream* ss) {
  1477. const ::std::string& str = ss->str();
  1478. const char* const start = str.c_str();
  1479. const char* const end = start + str.length();
  1480. // We need to use a helper stringstream to do this transformation
  1481. // because String doesn't support push_back().
  1482. ::std::stringstream helper;
  1483. for (const char* ch = start; ch != end; ++ch) {
  1484. if (*ch == '\0') {
  1485. helper << "\\0"; // Replaces NUL with "\\0";
  1486. } else {
  1487. helper.put(*ch);
  1488. }
  1489. }
  1490. return String(helper.str().c_str());
  1491. }
  1492. // Appends the user-supplied message to the Google-Test-generated message.
  1493. String AppendUserMessage(const String& gtest_msg,
  1494. const Message& user_msg) {
  1495. // Appends the user message if it's non-empty.
  1496. const String user_msg_string = user_msg.GetString();
  1497. if (user_msg_string.empty()) {
  1498. return gtest_msg;
  1499. }
  1500. Message msg;
  1501. msg << gtest_msg << "\n" << user_msg_string;
  1502. return msg.GetString();
  1503. }
  1504. } // namespace internal
  1505. // class TestResult
  1506. // Creates an empty TestResult.
  1507. TestResult::TestResult()
  1508. : death_test_count_(0),
  1509. elapsed_time_(0) {
  1510. }
  1511. // D'tor.
  1512. TestResult::~TestResult() {
  1513. }
  1514. // Returns the i-th test part result among all the results. i can
  1515. // range from 0 to total_part_count() - 1. If i is not in that range,
  1516. // aborts the program.
  1517. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  1518. if (i < 0 || i >= total_part_count())
  1519. internal::posix::Abort();
  1520. return test_part_results_.at(i);
  1521. }
  1522. // Returns the i-th test property. i can range from 0 to
  1523. // test_property_count() - 1. If i is not in that range, aborts the
  1524. // program.
  1525. const TestProperty& TestResult::GetTestProperty(int i) const {
  1526. if (i < 0 || i >= test_property_count())
  1527. internal::posix::Abort();
  1528. return test_properties_.at(i);
  1529. }
  1530. // Clears the test part results.
  1531. void TestResult::ClearTestPartResults() {
  1532. test_part_results_.clear();
  1533. }
  1534. // Adds a test part result to the list.
  1535. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  1536. test_part_results_.push_back(test_part_result);
  1537. }
  1538. // Adds a test property to the list. If a property with the same key as the
  1539. // supplied property is already represented, the value of this test_property
  1540. // replaces the old value for that key.
  1541. void TestResult::RecordProperty(const TestProperty& test_property) {
  1542. if (!ValidateTestProperty(test_property)) {
  1543. return;
  1544. }
  1545. internal::MutexLock lock(&test_properites_mutex_);
  1546. const std::vector<TestProperty>::iterator property_with_matching_key =
  1547. std::find_if(test_properties_.begin(), test_properties_.end(),
  1548. internal::TestPropertyKeyIs(test_property.key()));
  1549. if (property_with_matching_key == test_properties_.end()) {
  1550. test_properties_.push_back(test_property);
  1551. return;
  1552. }
  1553. property_with_matching_key->SetValue(test_property.value());
  1554. }
  1555. // Adds a failure if the key is a reserved attribute of Google Test
  1556. // testcase tags. Returns true if the property is valid.
  1557. bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
  1558. internal::String key(test_property.key());
  1559. if (key == "name" || key == "status" || key == "time" || key == "classname") {
  1560. ADD_FAILURE()
  1561. << "Reserved key used in RecordProperty(): "
  1562. << key
  1563. << " ('name', 'status', 'time', and 'classname' are reserved by "
  1564. << GTEST_NAME_ << ")";
  1565. return false;
  1566. }
  1567. return true;
  1568. }
  1569. // Clears the object.
  1570. void TestResult::Clear() {
  1571. test_part_results_.clear();
  1572. test_properties_.clear();
  1573. death_test_count_ = 0;
  1574. elapsed_time_ = 0;
  1575. }
  1576. // Returns true iff the test failed.
  1577. bool TestResult::Failed() const {
  1578. for (int i = 0; i < total_part_count(); ++i) {
  1579. if (GetTestPartResult(i).failed())
  1580. return true;
  1581. }
  1582. return false;
  1583. }
  1584. // Returns true iff the test part fatally failed.
  1585. static bool TestPartFatallyFailed(const TestPartResult& result) {
  1586. return result.fatally_failed();
  1587. }
  1588. // Returns true iff the test fatally failed.
  1589. bool TestResult::HasFatalFailure() const {
  1590. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  1591. }
  1592. // Returns true iff the test part non-fatally failed.
  1593. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  1594. return result.nonfatally_failed();
  1595. }
  1596. // Returns true iff the test has a non-fatal failure.
  1597. bool TestResult::HasNonfatalFailure() const {
  1598. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  1599. }
  1600. // Gets the number of all test parts. This is the sum of the number
  1601. // of successful test parts and the number of failed test parts.
  1602. int TestResult::total_part_count() const {
  1603. return static_cast<int>(test_part_results_.size());
  1604. }
  1605. // Returns the number of the test properties.
  1606. int TestResult::test_property_count() const {
  1607. return static_cast<int>(test_properties_.size());
  1608. }
  1609. // class Test
  1610. // Creates a Test object.
  1611. // The c'tor saves the values of all Google Test flags.
  1612. Test::Test()
  1613. : gtest_flag_saver_(new internal::GTestFlagSaver) {
  1614. }
  1615. // The d'tor restores the values of all Google Test flags.
  1616. Test::~Test() {
  1617. delete gtest_flag_saver_;
  1618. }
  1619. // Sets up the test fixture.
  1620. //
  1621. // A sub-class may override this.
  1622. void Test::SetUp() {
  1623. }
  1624. // Tears down the test fixture.
  1625. //
  1626. // A sub-class may override this.
  1627. void Test::TearDown() {
  1628. }
  1629. // Allows user supplied key value pairs to be recorded for later output.
  1630. void Test::RecordProperty(const char* key, const char* value) {
  1631. UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
  1632. }
  1633. // Allows user supplied key value pairs to be recorded for later output.
  1634. void Test::RecordProperty(const char* key, int value) {
  1635. Message value_message;
  1636. value_message << value;
  1637. RecordProperty(key, value_message.GetString().c_str());
  1638. }
  1639. namespace internal {
  1640. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  1641. const String& message) {
  1642. // This function is a friend of UnitTest and as such has access to
  1643. // AddTestPartResult.
  1644. UnitTest::GetInstance()->AddTestPartResult(
  1645. result_type,
  1646. NULL, // No info about the source file where the exception occurred.
  1647. -1, // We have no info on which line caused the exception.
  1648. message,
  1649. String()); // No stack trace, either.
  1650. }
  1651. } // namespace internal
  1652. // Google Test requires all tests in the same test case to use the same test
  1653. // fixture class. This function checks if the current test has the
  1654. // same fixture class as the first test in the current test case. If
  1655. // yes, it returns true; otherwise it generates a Google Test failure and
  1656. // returns false.
  1657. bool Test::HasSameFixtureClass() {
  1658. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1659. const TestCase* const test_case = impl->current_test_case();
  1660. // Info about the first test in the current test case.
  1661. const TestInfo* const first_test_info = test_case->test_info_list()[0];
  1662. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  1663. const char* const first_test_name = first_test_info->name();
  1664. // Info about the current test.
  1665. const TestInfo* const this_test_info = impl->current_test_info();
  1666. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  1667. const char* const this_test_name = this_test_info->name();
  1668. if (this_fixture_id != first_fixture_id) {
  1669. // Is the first test defined using TEST?
  1670. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  1671. // Is this test defined using TEST?
  1672. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  1673. if (first_is_TEST || this_is_TEST) {
  1674. // The user mixed TEST and TEST_F in this test case - we'll tell
  1675. // him/her how to fix it.
  1676. // Gets the name of the TEST and the name of the TEST_F. Note
  1677. // that first_is_TEST and this_is_TEST cannot both be true, as
  1678. // the fixture IDs are different for the two tests.
  1679. const char* const TEST_name =
  1680. first_is_TEST ? first_test_name : this_test_name;
  1681. const char* const TEST_F_name =
  1682. first_is_TEST ? this_test_name : first_test_name;
  1683. ADD_FAILURE()
  1684. << "All tests in the same test case must use the same test fixture\n"
  1685. << "class, so mixing TEST_F and TEST in the same test case is\n"
  1686. << "illegal. In test case " << this_test_info->test_case_name()
  1687. << ",\n"
  1688. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  1689. << "test " << TEST_name << " is defined using TEST. You probably\n"
  1690. << "want to change the TEST to TEST_F or move it to another test\n"
  1691. << "case.";
  1692. } else {
  1693. // The user defined two fixture classes with the same name in
  1694. // two namespaces - we'll tell him/her how to fix it.
  1695. ADD_FAILURE()
  1696. << "All tests in the same test case must use the same test fixture\n"
  1697. << "class. However, in test case "
  1698. << this_test_info->test_case_name() << ",\n"
  1699. << "you defined test " << first_test_name
  1700. << " and test " << this_test_name << "\n"
  1701. << "using two different test fixture classes. This can happen if\n"
  1702. << "the two classes are from different namespaces or translation\n"
  1703. << "units and have the same name. You should probably rename one\n"
  1704. << "of the classes to put the tests into different test cases.";
  1705. }
  1706. return false;
  1707. }
  1708. return true;
  1709. }
  1710. #if GTEST_HAS_SEH
  1711. // Adds an "exception thrown" fatal failure to the current test. This
  1712. // function returns its result via an output parameter pointer because VC++
  1713. // prohibits creation of objects with destructors on stack in functions
  1714. // using __try (see error C2712).
  1715. static internal::String* FormatSehExceptionMessage(DWORD exception_code,
  1716. const char* location) {
  1717. Message message;
  1718. message << "SEH exception with code 0x" << std::setbase(16) <<
  1719. exception_code << std::setbase(10) << " thrown in " << location << ".";
  1720. return new internal::String(message.GetString());
  1721. }
  1722. #endif // GTEST_HAS_SEH
  1723. #if GTEST_HAS_EXCEPTIONS
  1724. // Adds an "exception thrown" fatal failure to the current test.
  1725. static internal::String FormatCxxExceptionMessage(const char* description,
  1726. const char* location) {
  1727. Message message;
  1728. if (description != NULL) {
  1729. message << "C++ exception with description \"" << description << "\"";
  1730. } else {
  1731. message << "Unknown C++ exception";
  1732. }
  1733. message << " thrown in " << location << ".";
  1734. return message.GetString();
  1735. }
  1736. static internal::String PrintTestPartResultToString(
  1737. const TestPartResult& test_part_result);
  1738. // A failed Google Test assertion will throw an exception of this type when
  1739. // GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
  1740. // derive it from std::runtime_error, which is for errors presumably
  1741. // detectable only at run time. Since std::runtime_error inherits from
  1742. // std::exception, many testing frameworks know how to extract and print the
  1743. // message inside it.
  1744. class GoogleTestFailureException : public ::std::runtime_error {
  1745. public:
  1746. explicit GoogleTestFailureException(const TestPartResult& failure)
  1747. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  1748. };
  1749. #endif // GTEST_HAS_EXCEPTIONS
  1750. namespace internal {
  1751. // We put these helper functions in the internal namespace as IBM's xlC
  1752. // compiler rejects the code if they were declared static.
  1753. // Runs the given method and handles SEH exceptions it throws, when
  1754. // SEH is supported; returns the 0-value for type Result in case of an
  1755. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  1756. // exceptions in the same function. Therefore, we provide a separate
  1757. // wrapper function for handling SEH exceptions.)
  1758. template <class T, typename Result>
  1759. Result HandleSehExceptionsInMethodIfSupported(
  1760. T* object, Result (T::*method)(), const char* location) {
  1761. #if GTEST_HAS_SEH
  1762. __try {
  1763. return (object->*method)();
  1764. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  1765. GetExceptionCode())) {
  1766. // We create the exception message on the heap because VC++ prohibits
  1767. // creation of objects with destructors on stack in functions using __try
  1768. // (see error C2712).
  1769. internal::String* exception_message = FormatSehExceptionMessage(
  1770. GetExceptionCode(), location);
  1771. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  1772. *exception_message);
  1773. delete exception_message;
  1774. return static_cast<Result>(0);
  1775. }
  1776. #else
  1777. (void)location;
  1778. return (object->*method)();
  1779. #endif // GTEST_HAS_SEH
  1780. }
  1781. // Runs the given method and catches and reports C++ and/or SEH-style
  1782. // exceptions, if they are supported; returns the 0-value for type
  1783. // Result in case of an SEH exception.
  1784. template <class T, typename Result>
  1785. Result HandleExceptionsInMethodIfSupported(
  1786. T* object, Result (T::*method)(), const char* location) {
  1787. // NOTE: The user code can affect the way in which Google Test handles
  1788. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  1789. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  1790. // after the exception is caught and either report or re-throw the
  1791. // exception based on the flag's value:
  1792. //
  1793. // try {
  1794. // // Perform the test method.
  1795. // } catch (...) {
  1796. // if (GTEST_FLAG(catch_exceptions))
  1797. // // Report the exception as failure.
  1798. // else
  1799. // throw; // Re-throws the original exception.
  1800. // }
  1801. //
  1802. // However, the purpose of this flag is to allow the program to drop into
  1803. // the debugger when the exception is thrown. On most platforms, once the
  1804. // control enters the catch block, the exception origin information is
  1805. // lost and the debugger will stop the program at the point of the
  1806. // re-throw in this function -- instead of at the point of the original
  1807. // throw statement in the code under test. For this reason, we perform
  1808. // the check early, sacrificing the ability to affect Google Test's
  1809. // exception handling in the method where the exception is thrown.
  1810. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  1811. #if GTEST_HAS_EXCEPTIONS
  1812. try {
  1813. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  1814. } catch (const GoogleTestFailureException&) { // NOLINT
  1815. // This exception doesn't originate in code under test. It makes no
  1816. // sense to report it as a test failure.
  1817. throw;
  1818. } catch (const std::exception& e) { // NOLINT
  1819. internal::ReportFailureInUnknownLocation(
  1820. TestPartResult::kFatalFailure,
  1821. FormatCxxExceptionMessage(e.what(), location));
  1822. } catch (...) { // NOLINT
  1823. internal::ReportFailureInUnknownLocation(
  1824. TestPartResult::kFatalFailure,
  1825. FormatCxxExceptionMessage(NULL, location));
  1826. }
  1827. return static_cast<Result>(0);
  1828. #else
  1829. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  1830. #endif // GTEST_HAS_EXCEPTIONS
  1831. } else {
  1832. return (object->*method)();
  1833. }
  1834. }
  1835. } // namespace internal
  1836. // Runs the test and updates the test result.
  1837. void Test::Run() {
  1838. if (!HasSameFixtureClass()) return;
  1839. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1840. impl->os_stack_trace_getter()->UponLeavingGTest();
  1841. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  1842. // We will run the test only if SetUp() was successful.
  1843. if (!HasFatalFailure()) {
  1844. impl->os_stack_trace_getter()->UponLeavingGTest();
  1845. internal::HandleExceptionsInMethodIfSupported(
  1846. this, &Test::TestBody, "the test body");
  1847. }
  1848. // However, we want to clean up as much as possible. Hence we will
  1849. // always call TearDown(), even if SetUp() or the test body has
  1850. // failed.
  1851. impl->os_stack_trace_getter()->UponLeavingGTest();
  1852. internal::HandleExceptionsInMethodIfSupported(
  1853. this, &Test::TearDown, "TearDown()");
  1854. }
  1855. // Returns true iff the current test has a fatal failure.
  1856. bool Test::HasFatalFailure() {
  1857. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  1858. }
  1859. // Returns true iff the current test has a non-fatal failure.
  1860. bool Test::HasNonfatalFailure() {
  1861. return internal::GetUnitTestImpl()->current_test_result()->
  1862. HasNonfatalFailure();
  1863. }
  1864. // class TestInfo
  1865. // Constructs a TestInfo object. It assumes ownership of the test factory
  1866. // object.
  1867. // TODO([email protected]): Make a_test_case_name and a_name const string&'s
  1868. // to signify they cannot be NULLs.
  1869. TestInfo::TestInfo(const char* a_test_case_name,
  1870. const char* a_name,
  1871. const char* a_type_param,
  1872. const char* a_value_param,
  1873. internal::TypeId fixture_class_id,
  1874. internal::TestFactoryBase* factory)
  1875. : test_case_name_(a_test_case_name),
  1876. name_(a_name),
  1877. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  1878. value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  1879. fixture_class_id_(fixture_class_id),
  1880. should_run_(false),
  1881. is_disabled_(false),
  1882. matches_filter_(false),
  1883. factory_(factory),
  1884. result_() {}
  1885. // Destructs a TestInfo object.
  1886. TestInfo::~TestInfo() { delete factory_; }
  1887. namespace internal {
  1888. // Creates a new TestInfo object and registers it with Google Test;
  1889. // returns the created object.
  1890. //
  1891. // Arguments:
  1892. //
  1893. // test_case_name: name of the test case
  1894. // name: name of the test
  1895. // type_param: the name of the test's type parameter, or NULL if
  1896. // this is not a typed or a type-parameterized test.
  1897. // value_param: text representation of the test's value parameter,
  1898. // or NULL if this is not a value-parameterized test.
  1899. // fixture_class_id: ID of the test fixture class
  1900. // set_up_tc: pointer to the function that sets up the test case
  1901. // tear_down_tc: pointer to the function that tears down the test case
  1902. // factory: pointer to the factory that creates a test object.
  1903. // The newly created TestInfo instance will assume
  1904. // ownership of the factory object.
  1905. TestInfo* MakeAndRegisterTestInfo(
  1906. const char* test_case_name, const char* name,
  1907. const char* type_param,
  1908. const char* value_param,
  1909. TypeId fixture_class_id,
  1910. SetUpTestCaseFunc set_up_tc,
  1911. TearDownTestCaseFunc tear_down_tc,
  1912. TestFactoryBase* factory) {
  1913. TestInfo* const test_info =
  1914. new TestInfo(test_case_name, name, type_param, value_param,
  1915. fixture_class_id, factory);
  1916. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  1917. return test_info;
  1918. }
  1919. #if GTEST_HAS_PARAM_TEST
  1920. void ReportInvalidTestCaseType(const char* test_case_name,
  1921. const char* file, int line) {
  1922. Message errors;
  1923. errors
  1924. << "Attempted redefinition of test case " << test_case_name << ".\n"
  1925. << "All tests in the same test case must use the same test fixture\n"
  1926. << "class. However, in test case " << test_case_name << ", you tried\n"
  1927. << "to define a test using a fixture class different from the one\n"
  1928. << "used earlier. This can happen if the two fixture classes are\n"
  1929. << "from different namespaces and have the same name. You should\n"
  1930. << "probably rename one of the classes to put the tests into different\n"
  1931. << "test cases.";
  1932. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  1933. errors.GetString().c_str());
  1934. }
  1935. #endif // GTEST_HAS_PARAM_TEST
  1936. } // namespace internal
  1937. namespace {
  1938. // A predicate that checks the test name of a TestInfo against a known
  1939. // value.
  1940. //
  1941. // This is used for implementation of the TestCase class only. We put
  1942. // it in the anonymous namespace to prevent polluting the outer
  1943. // namespace.
  1944. //
  1945. // TestNameIs is copyable.
  1946. class TestNameIs {
  1947. public:
  1948. // Constructor.
  1949. //
  1950. // TestNameIs has NO default constructor.
  1951. explicit TestNameIs(const char* name)
  1952. : name_(name) {}
  1953. // Returns true iff the test name of test_info matches name_.
  1954. bool operator()(const TestInfo * test_info) const {
  1955. return test_info && internal::String(test_info->name()).Compare(name_) == 0;
  1956. }
  1957. private:
  1958. internal::String name_;
  1959. };
  1960. } // namespace
  1961. namespace internal {
  1962. // This method expands all parameterized tests registered with macros TEST_P
  1963. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  1964. // This will be done just once during the program runtime.
  1965. void UnitTestImpl::RegisterParameterizedTests() {
  1966. #if GTEST_HAS_PARAM_TEST
  1967. if (!parameterized_tests_registered_) {
  1968. parameterized_test_registry_.RegisterTests();
  1969. parameterized_tests_registered_ = true;
  1970. }
  1971. #endif
  1972. }
  1973. } // namespace internal
  1974. // Creates the test object, runs it, records its result, and then
  1975. // deletes it.
  1976. void TestInfo::Run() {
  1977. if (!should_run_) return;
  1978. // Tells UnitTest where to store test result.
  1979. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1980. impl->set_current_test_info(this);
  1981. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  1982. // Notifies the unit test event listeners that a test is about to start.
  1983. repeater->OnTestStart(*this);
  1984. const TimeInMillis start = internal::GetTimeInMillis();
  1985. impl->os_stack_trace_getter()->UponLeavingGTest();
  1986. // Creates the test object.
  1987. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  1988. factory_, &internal::TestFactoryBase::CreateTest,
  1989. "the test fixture's constructor");
  1990. // Runs the test only if the test object was created and its
  1991. // constructor didn't generate a fatal failure.
  1992. if ((test != NULL) && !Test::HasFatalFailure()) {
  1993. // This doesn't throw as all user code that can throw are wrapped into
  1994. // exception handling code.
  1995. test->Run();
  1996. }
  1997. // Deletes the test object.
  1998. impl->os_stack_trace_getter()->UponLeavingGTest();
  1999. internal::HandleExceptionsInMethodIfSupported(
  2000. test, &Test::DeleteSelf_, "the test fixture's destructor");
  2001. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  2002. // Notifies the unit test event listener that a test has just finished.
  2003. repeater->OnTestEnd(*this);
  2004. // Tells UnitTest to stop associating assertion results to this
  2005. // test.
  2006. impl->set_current_test_info(NULL);
  2007. }
  2008. // class TestCase
  2009. // Gets the number of successful tests in this test case.
  2010. int TestCase::successful_test_count() const {
  2011. return CountIf(test_info_list_, TestPassed);
  2012. }
  2013. // Gets the number of failed tests in this test case.
  2014. int TestCase::failed_test_count() const {
  2015. return CountIf(test_info_list_, TestFailed);
  2016. }
  2017. int TestCase::disabled_test_count() const {
  2018. return CountIf(test_info_list_, TestDisabled);
  2019. }
  2020. // Get the number of tests in this test case that should run.
  2021. int TestCase::test_to_run_count() const {
  2022. return CountIf(test_info_list_, ShouldRunTest);
  2023. }
  2024. // Gets the number of all tests.
  2025. int TestCase::total_test_count() const {
  2026. return static_cast<int>(test_info_list_.size());
  2027. }
  2028. // Creates a TestCase with the given name.
  2029. //
  2030. // Arguments:
  2031. //
  2032. // name: name of the test case
  2033. // a_type_param: the name of the test case's type parameter, or NULL if
  2034. // this is not a typed or a type-parameterized test case.
  2035. // set_up_tc: pointer to the function that sets up the test case
  2036. // tear_down_tc: pointer to the function that tears down the test case
  2037. TestCase::TestCase(const char* a_name, const char* a_type_param,
  2038. Test::SetUpTestCaseFunc set_up_tc,
  2039. Test::TearDownTestCaseFunc tear_down_tc)
  2040. : name_(a_name),
  2041. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  2042. set_up_tc_(set_up_tc),
  2043. tear_down_tc_(tear_down_tc),
  2044. should_run_(false),
  2045. elapsed_time_(0) {
  2046. }
  2047. // Destructor of TestCase.
  2048. TestCase::~TestCase() {
  2049. // Deletes every Test in the collection.
  2050. ForEach(test_info_list_, internal::Delete<TestInfo>);
  2051. }
  2052. // Returns the i-th test among all the tests. i can range from 0 to
  2053. // total_test_count() - 1. If i is not in that range, returns NULL.
  2054. const TestInfo* TestCase::GetTestInfo(int i) const {
  2055. const int index = GetElementOr(test_indices_, i, -1);
  2056. return index < 0 ? NULL : test_info_list_[index];
  2057. }
  2058. // Returns the i-th test among all the tests. i can range from 0 to
  2059. // total_test_count() - 1. If i is not in that range, returns NULL.
  2060. TestInfo* TestCase::GetMutableTestInfo(int i) {
  2061. const int index = GetElementOr(test_indices_, i, -1);
  2062. return index < 0 ? NULL : test_info_list_[index];
  2063. }
  2064. // Adds a test to this test case. Will delete the test upon
  2065. // destruction of the TestCase object.
  2066. void TestCase::AddTestInfo(TestInfo * test_info) {
  2067. test_info_list_.push_back(test_info);
  2068. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  2069. }
  2070. // Runs every test in this TestCase.
  2071. void TestCase::Run() {
  2072. if (!should_run_) return;
  2073. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2074. impl->set_current_test_case(this);
  2075. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2076. repeater->OnTestCaseStart(*this);
  2077. impl->os_stack_trace_getter()->UponLeavingGTest();
  2078. internal::HandleExceptionsInMethodIfSupported(
  2079. this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  2080. const internal::TimeInMillis start = internal::GetTimeInMillis();
  2081. for (int i = 0; i < total_test_count(); i++) {
  2082. GetMutableTestInfo(i)->Run();
  2083. }
  2084. elapsed_time_ = internal::GetTimeInMillis() - start;
  2085. impl->os_stack_trace_getter()->UponLeavingGTest();
  2086. internal::HandleExceptionsInMethodIfSupported(
  2087. this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  2088. repeater->OnTestCaseEnd(*this);
  2089. impl->set_current_test_case(NULL);
  2090. }
  2091. // Clears the results of all tests in this test case.
  2092. void TestCase::ClearResult() {
  2093. ForEach(test_info_list_, TestInfo::ClearTestResult);
  2094. }
  2095. // Shuffles the tests in this test case.
  2096. void TestCase::ShuffleTests(internal::Random* random) {
  2097. Shuffle(random, &test_indices_);
  2098. }
  2099. // Restores the test order to before the first shuffle.
  2100. void TestCase::UnshuffleTests() {
  2101. for (size_t i = 0; i < test_indices_.size(); i++) {
  2102. test_indices_[i] = static_cast<int>(i);
  2103. }
  2104. }
  2105. // Formats a countable noun. Depending on its quantity, either the
  2106. // singular form or the plural form is used. e.g.
  2107. //
  2108. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  2109. // FormatCountableNoun(5, "book", "books") returns "5 books".
  2110. static internal::String FormatCountableNoun(int count,
  2111. const char * singular_form,
  2112. const char * plural_form) {
  2113. return internal::String::Format("%d %s", count,
  2114. count == 1 ? singular_form : plural_form);
  2115. }
  2116. // Formats the count of tests.
  2117. static internal::String FormatTestCount(int test_count) {
  2118. return FormatCountableNoun(test_count, "test", "tests");
  2119. }
  2120. // Formats the count of test cases.
  2121. static internal::String FormatTestCaseCount(int test_case_count) {
  2122. return FormatCountableNoun(test_case_count, "test case", "test cases");
  2123. }
  2124. // Converts a TestPartResult::Type enum to human-friendly string
  2125. // representation. Both kNonFatalFailure and kFatalFailure are translated
  2126. // to "Failure", as the user usually doesn't care about the difference
  2127. // between the two when viewing the test result.
  2128. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  2129. switch (type) {
  2130. case TestPartResult::kSuccess:
  2131. return "Success";
  2132. case TestPartResult::kNonFatalFailure:
  2133. case TestPartResult::kFatalFailure:
  2134. #ifdef _MSC_VER
  2135. return "error: ";
  2136. #else
  2137. return "Failure\n";
  2138. #endif
  2139. default:
  2140. return "Unknown result type";
  2141. }
  2142. }
  2143. // Prints a TestPartResult to a String.
  2144. static internal::String PrintTestPartResultToString(
  2145. const TestPartResult& test_part_result) {
  2146. return (Message()
  2147. << internal::FormatFileLocation(test_part_result.file_name(),
  2148. test_part_result.line_number())
  2149. << " " << TestPartResultTypeToString(test_part_result.type())
  2150. << test_part_result.message()).GetString();
  2151. }
  2152. // Prints a TestPartResult.
  2153. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  2154. const internal::String& result =
  2155. PrintTestPartResultToString(test_part_result);
  2156. printf("%s\n", result.c_str());
  2157. fflush(stdout);
  2158. // If the test program runs in Visual Studio or a debugger, the
  2159. // following statements add the test part result message to the Output
  2160. // window such that the user can double-click on it to jump to the
  2161. // corresponding source code location; otherwise they do nothing.
  2162. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2163. // We don't call OutputDebugString*() on Windows Mobile, as printing
  2164. // to stdout is done by OutputDebugString() there already - we don't
  2165. // want the same message printed twice.
  2166. ::OutputDebugStringA(result.c_str());
  2167. ::OutputDebugStringA("\n");
  2168. #endif
  2169. }
  2170. // class PrettyUnitTestResultPrinter
  2171. namespace internal {
  2172. enum GTestColor {
  2173. COLOR_DEFAULT,
  2174. COLOR_RED,
  2175. COLOR_GREEN,
  2176. COLOR_YELLOW
  2177. };
  2178. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2179. // Returns the character attribute for the given color.
  2180. WORD GetColorAttribute(GTestColor color) {
  2181. switch (color) {
  2182. case COLOR_RED: return FOREGROUND_RED;
  2183. case COLOR_GREEN: return FOREGROUND_GREEN;
  2184. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  2185. default: return 0;
  2186. }
  2187. }
  2188. #else
  2189. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  2190. // an invalid input.
  2191. const char* GetAnsiColorCode(GTestColor color) {
  2192. switch (color) {
  2193. case COLOR_RED: return "1";
  2194. case COLOR_GREEN: return "2";
  2195. case COLOR_YELLOW: return "3";
  2196. default: return NULL;
  2197. };
  2198. }
  2199. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2200. // Returns true iff Google Test should use colors in the output.
  2201. bool ShouldUseColor(bool stdout_is_tty) {
  2202. const char* const gtest_color = GTEST_FLAG(color).c_str();
  2203. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  2204. #if GTEST_OS_WINDOWS
  2205. // On Windows the TERM variable is usually not set, but the
  2206. // console there does support colors.
  2207. return stdout_is_tty;
  2208. #else
  2209. // On non-Windows platforms, we rely on the TERM variable.
  2210. const char* const term = posix::GetEnv("TERM");
  2211. const bool term_supports_color =
  2212. String::CStringEquals(term, "xterm") ||
  2213. String::CStringEquals(term, "xterm-color") ||
  2214. String::CStringEquals(term, "xterm-256color") ||
  2215. String::CStringEquals(term, "screen") ||
  2216. String::CStringEquals(term, "linux") ||
  2217. String::CStringEquals(term, "cygwin");
  2218. return stdout_is_tty && term_supports_color;
  2219. #endif // GTEST_OS_WINDOWS
  2220. }
  2221. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  2222. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  2223. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  2224. String::CStringEquals(gtest_color, "1");
  2225. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  2226. // value is neither one of these nor "auto", we treat it as "no" to
  2227. // be conservative.
  2228. }
  2229. // Helpers for printing colored strings to stdout. Note that on Windows, we
  2230. // cannot simply emit special characters and have the terminal change colors.
  2231. // This routine must actually emit the characters rather than return a string
  2232. // that would be colored when printed, as can be done on Linux.
  2233. void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  2234. va_list args;
  2235. va_start(args, fmt);
  2236. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  2237. const bool use_color = false;
  2238. #else
  2239. static const bool in_color_mode =
  2240. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  2241. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  2242. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  2243. // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  2244. if (!use_color) {
  2245. vprintf(fmt, args);
  2246. va_end(args);
  2247. return;
  2248. }
  2249. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2250. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  2251. // Gets the current text color.
  2252. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  2253. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  2254. const WORD old_color_attrs = buffer_info.wAttributes;
  2255. // We need to flush the stream buffers into the console before each
  2256. // SetConsoleTextAttribute call lest it affect the text that is already
  2257. // printed but has not yet reached the console.
  2258. fflush(stdout);
  2259. SetConsoleTextAttribute(stdout_handle,
  2260. GetColorAttribute(color) | FOREGROUND_INTENSITY);
  2261. vprintf(fmt, args);
  2262. fflush(stdout);
  2263. // Restores the text color.
  2264. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  2265. #else
  2266. printf("\033[0;3%sm", GetAnsiColorCode(color));
  2267. vprintf(fmt, args);
  2268. printf("\033[m"); // Resets the terminal to default.
  2269. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2270. va_end(args);
  2271. }
  2272. void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  2273. const char* const type_param = test_info.type_param();
  2274. const char* const value_param = test_info.value_param();
  2275. if (type_param != NULL || value_param != NULL) {
  2276. printf(", where ");
  2277. if (type_param != NULL) {
  2278. printf("TypeParam = %s", type_param);
  2279. if (value_param != NULL)
  2280. printf(" and ");
  2281. }
  2282. if (value_param != NULL) {
  2283. printf("GetParam() = %s", value_param);
  2284. }
  2285. }
  2286. }
  2287. // This class implements the TestEventListener interface.
  2288. //
  2289. // Class PrettyUnitTestResultPrinter is copyable.
  2290. class PrettyUnitTestResultPrinter : public TestEventListener {
  2291. public:
  2292. PrettyUnitTestResultPrinter() {}
  2293. static void PrintTestName(const char * test_case, const char * test) {
  2294. printf("%s.%s", test_case, test);
  2295. }
  2296. // The following methods override what's in the TestEventListener class.
  2297. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  2298. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  2299. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  2300. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  2301. virtual void OnTestCaseStart(const TestCase& test_case);
  2302. virtual void OnTestStart(const TestInfo& test_info);
  2303. virtual void OnTestPartResult(const TestPartResult& result);
  2304. virtual void OnTestEnd(const TestInfo& test_info);
  2305. virtual void OnTestCaseEnd(const TestCase& test_case);
  2306. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  2307. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  2308. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  2309. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  2310. private:
  2311. static void PrintFailedTests(const UnitTest& unit_test);
  2312. internal::String test_case_name_;
  2313. };
  2314. // Fired before each iteration of tests starts.
  2315. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  2316. const UnitTest& unit_test, int iteration) {
  2317. if (GTEST_FLAG(repeat) != 1)
  2318. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  2319. const char* const filter = GTEST_FLAG(filter).c_str();
  2320. // Prints the filter if it's not *. This reminds the user that some
  2321. // tests may be skipped.
  2322. if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
  2323. ColoredPrintf(COLOR_YELLOW,
  2324. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  2325. }
  2326. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  2327. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  2328. ColoredPrintf(COLOR_YELLOW,
  2329. "Note: This is test shard %d of %s.\n",
  2330. static_cast<int>(shard_index) + 1,
  2331. internal::posix::GetEnv(kTestTotalShards));
  2332. }
  2333. if (GTEST_FLAG(shuffle)) {
  2334. ColoredPrintf(COLOR_YELLOW,
  2335. "Note: Randomizing tests' orders with a seed of %d .\n",
  2336. unit_test.random_seed());
  2337. }
  2338. ColoredPrintf(COLOR_GREEN, "[==========] ");
  2339. printf("Running %s from %s.\n",
  2340. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  2341. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  2342. fflush(stdout);
  2343. }
  2344. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  2345. const UnitTest& /*unit_test*/) {
  2346. ColoredPrintf(COLOR_GREEN, "[----------] ");
  2347. printf("Global test environment set-up.\n");
  2348. fflush(stdout);
  2349. }
  2350. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  2351. test_case_name_ = test_case.name();
  2352. const internal::String counts =
  2353. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  2354. ColoredPrintf(COLOR_GREEN, "[----------] ");
  2355. printf("%s from %s", counts.c_str(), test_case_name_.c_str());
  2356. if (test_case.type_param() == NULL) {
  2357. printf("\n");
  2358. } else {
  2359. printf(", where TypeParam = %s\n", test_case.type_param());
  2360. }
  2361. fflush(stdout);
  2362. }
  2363. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  2364. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  2365. PrintTestName(test_case_name_.c_str(), test_info.name());
  2366. printf("\n");
  2367. fflush(stdout);
  2368. }
  2369. // Called after an assertion failure.
  2370. void PrettyUnitTestResultPrinter::OnTestPartResult(
  2371. const TestPartResult& result) {
  2372. // If the test part succeeded, we don't need to do anything.
  2373. if (result.type() == TestPartResult::kSuccess)
  2374. return;
  2375. // Print failure message from the assertion (e.g. expected this and got that).
  2376. PrintTestPartResult(result);
  2377. fflush(stdout);
  2378. }
  2379. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  2380. if (test_info.result()->Passed()) {
  2381. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  2382. } else {
  2383. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  2384. }
  2385. PrintTestName(test_case_name_.c_str(), test_info.name());
  2386. if (test_info.result()->Failed())
  2387. PrintFullTestCommentIfPresent(test_info);
  2388. if (GTEST_FLAG(print_time)) {
  2389. printf(" (%s ms)\n", internal::StreamableToString(
  2390. test_info.result()->elapsed_time()).c_str());
  2391. } else {
  2392. printf("\n");
  2393. }
  2394. fflush(stdout);
  2395. }
  2396. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  2397. if (!GTEST_FLAG(print_time)) return;
  2398. test_case_name_ = test_case.name();
  2399. const internal::String counts =
  2400. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  2401. ColoredPrintf(COLOR_GREEN, "[----------] ");
  2402. printf("%s from %s (%s ms total)\n\n",
  2403. counts.c_str(), test_case_name_.c_str(),
  2404. internal::StreamableToString(test_case.elapsed_time()).c_str());
  2405. fflush(stdout);
  2406. }
  2407. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  2408. const UnitTest& /*unit_test*/) {
  2409. ColoredPrintf(COLOR_GREEN, "[----------] ");
  2410. printf("Global test environment tear-down\n");
  2411. fflush(stdout);
  2412. }
  2413. // Internal helper for printing the list of failed tests.
  2414. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  2415. const int failed_test_count = unit_test.failed_test_count();
  2416. if (failed_test_count == 0) {
  2417. return;
  2418. }
  2419. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  2420. const TestCase& test_case = *unit_test.GetTestCase(i);
  2421. if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  2422. continue;
  2423. }
  2424. for (int j = 0; j < test_case.total_test_count(); ++j) {
  2425. const TestInfo& test_info = *test_case.GetTestInfo(j);
  2426. if (!test_info.should_run() || test_info.result()->Passed()) {
  2427. continue;
  2428. }
  2429. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  2430. printf("%s.%s", test_case.name(), test_info.name());
  2431. PrintFullTestCommentIfPresent(test_info);
  2432. printf("\n");
  2433. }
  2434. }
  2435. }
  2436. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  2437. int /*iteration*/) {
  2438. ColoredPrintf(COLOR_GREEN, "[==========] ");
  2439. printf("%s from %s ran.",
  2440. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  2441. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  2442. if (GTEST_FLAG(print_time)) {
  2443. printf(" (%s ms total)",
  2444. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  2445. }
  2446. printf("\n");
  2447. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  2448. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  2449. int num_failures = unit_test.failed_test_count();
  2450. if (!unit_test.Passed()) {
  2451. const int failed_test_count = unit_test.failed_test_count();
  2452. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  2453. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  2454. PrintFailedTests(unit_test);
  2455. printf("\n%2d FAILED %s\n", num_failures,
  2456. num_failures == 1 ? "TEST" : "TESTS");
  2457. }
  2458. int num_disabled = unit_test.disabled_test_count();
  2459. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  2460. if (!num_failures) {
  2461. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  2462. }
  2463. ColoredPrintf(COLOR_YELLOW,
  2464. " YOU HAVE %d DISABLED %s\n\n",
  2465. num_disabled,
  2466. num_disabled == 1 ? "TEST" : "TESTS");
  2467. }
  2468. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  2469. fflush(stdout);
  2470. }
  2471. // End PrettyUnitTestResultPrinter
  2472. // class TestEventRepeater
  2473. //
  2474. // This class forwards events to other event listeners.
  2475. class TestEventRepeater : public TestEventListener {
  2476. public:
  2477. TestEventRepeater() : forwarding_enabled_(true) {}
  2478. virtual ~TestEventRepeater();
  2479. void Append(TestEventListener *listener);
  2480. TestEventListener* Release(TestEventListener* listener);
  2481. // Controls whether events will be forwarded to listeners_. Set to false
  2482. // in death test child processes.
  2483. bool forwarding_enabled() const { return forwarding_enabled_; }
  2484. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  2485. virtual void OnTestProgramStart(const UnitTest& unit_test);
  2486. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  2487. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  2488. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  2489. virtual void OnTestCaseStart(const TestCase& test_case);
  2490. virtual void OnTestStart(const TestInfo& test_info);
  2491. virtual void OnTestPartResult(const TestPartResult& result);
  2492. virtual void OnTestEnd(const TestInfo& test_info);
  2493. virtual void OnTestCaseEnd(const TestCase& test_case);
  2494. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  2495. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  2496. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  2497. virtual void OnTestProgramEnd(const UnitTest& unit_test);
  2498. private:
  2499. // Controls whether events will be forwarded to listeners_. Set to false
  2500. // in death test child processes.
  2501. bool forwarding_enabled_;
  2502. // The list of listeners that receive events.
  2503. std::vector<TestEventListener*> listeners_;
  2504. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  2505. };
  2506. TestEventRepeater::~TestEventRepeater() {
  2507. ForEach(listeners_, Delete<TestEventListener>);
  2508. }
  2509. void TestEventRepeater::Append(TestEventListener *listener) {
  2510. listeners_.push_back(listener);
  2511. }
  2512. // TODO([email protected]): Factor the search functionality into Vector::Find.
  2513. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  2514. for (size_t i = 0; i < listeners_.size(); ++i) {
  2515. if (listeners_[i] == listener) {
  2516. listeners_.erase(listeners_.begin() + i);
  2517. return listener;
  2518. }
  2519. }
  2520. return NULL;
  2521. }
  2522. // Since most methods are very similar, use macros to reduce boilerplate.
  2523. // This defines a member that forwards the call to all listeners.
  2524. #define GTEST_REPEATER_METHOD_(Name, Type) \
  2525. void TestEventRepeater::Name(const Type& parameter) { \
  2526. if (forwarding_enabled_) { \
  2527. for (size_t i = 0; i < listeners_.size(); i++) { \
  2528. listeners_[i]->Name(parameter); \
  2529. } \
  2530. } \
  2531. }
  2532. // This defines a member that forwards the call to all listeners in reverse
  2533. // order.
  2534. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  2535. void TestEventRepeater::Name(const Type& parameter) { \
  2536. if (forwarding_enabled_) { \
  2537. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  2538. listeners_[i]->Name(parameter); \
  2539. } \
  2540. } \
  2541. }
  2542. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  2543. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  2544. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  2545. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  2546. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  2547. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  2548. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  2549. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  2550. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  2551. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  2552. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  2553. #undef GTEST_REPEATER_METHOD_
  2554. #undef GTEST_REVERSE_REPEATER_METHOD_
  2555. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  2556. int iteration) {
  2557. if (forwarding_enabled_) {
  2558. for (size_t i = 0; i < listeners_.size(); i++) {
  2559. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  2560. }
  2561. }
  2562. }
  2563. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  2564. int iteration) {
  2565. if (forwarding_enabled_) {
  2566. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  2567. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  2568. }
  2569. }
  2570. }
  2571. // End TestEventRepeater
  2572. // This class generates an XML output file.
  2573. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  2574. public:
  2575. explicit XmlUnitTestResultPrinter(const char* output_file);
  2576. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  2577. private:
  2578. // Is c a whitespace character that is normalized to a space character
  2579. // when it appears in an XML attribute value?
  2580. static bool IsNormalizableWhitespace(char c) {
  2581. return c == 0x9 || c == 0xA || c == 0xD;
  2582. }
  2583. // May c appear in a well-formed XML document?
  2584. static bool IsValidXmlCharacter(char c) {
  2585. return IsNormalizableWhitespace(c) || c >= 0x20;
  2586. }
  2587. // Returns an XML-escaped copy of the input string str. If
  2588. // is_attribute is true, the text is meant to appear as an attribute
  2589. // value, and normalizable whitespace is preserved by replacing it
  2590. // with character references.
  2591. static String EscapeXml(const char* str, bool is_attribute);
  2592. // Returns the given string with all characters invalid in XML removed.
  2593. static string RemoveInvalidXmlCharacters(const string& str);
  2594. // Convenience wrapper around EscapeXml when str is an attribute value.
  2595. static String EscapeXmlAttribute(const char* str) {
  2596. return EscapeXml(str, true);
  2597. }
  2598. // Convenience wrapper around EscapeXml when str is not an attribute value.
  2599. static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
  2600. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  2601. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  2602. // Streams an XML representation of a TestInfo object.
  2603. static void OutputXmlTestInfo(::std::ostream* stream,
  2604. const char* test_case_name,
  2605. const TestInfo& test_info);
  2606. // Prints an XML representation of a TestCase object
  2607. static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
  2608. // Prints an XML summary of unit_test to output stream out.
  2609. static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
  2610. // Produces a string representing the test properties in a result as space
  2611. // delimited XML attributes based on the property key="value" pairs.
  2612. // When the String is not empty, it includes a space at the beginning,
  2613. // to delimit this attribute from prior attributes.
  2614. static String TestPropertiesAsXmlAttributes(const TestResult& result);
  2615. // The output file.
  2616. const String output_file_;
  2617. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  2618. };
  2619. // Creates a new XmlUnitTestResultPrinter.
  2620. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  2621. : output_file_(output_file) {
  2622. if (output_file_.c_str() == NULL || output_file_.empty()) {
  2623. fprintf(stderr, "XML output file may not be null\n");
  2624. fflush(stderr);
  2625. exit(EXIT_FAILURE);
  2626. }
  2627. }
  2628. // Called after the unit test ends.
  2629. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  2630. int /*iteration*/) {
  2631. FILE* xmlout = NULL;
  2632. FilePath output_file(output_file_);
  2633. FilePath output_dir(output_file.RemoveFileName());
  2634. if (output_dir.CreateDirectoriesRecursively()) {
  2635. xmlout = posix::FOpen(output_file_.c_str(), "w");
  2636. }
  2637. if (xmlout == NULL) {
  2638. // TODO(wan): report the reason of the failure.
  2639. //
  2640. // We don't do it for now as:
  2641. //
  2642. // 1. There is no urgent need for it.
  2643. // 2. It's a bit involved to make the errno variable thread-safe on
  2644. // all three operating systems (Linux, Windows, and Mac OS).
  2645. // 3. To interpret the meaning of errno in a thread-safe way,
  2646. // we need the strerror_r() function, which is not available on
  2647. // Windows.
  2648. fprintf(stderr,
  2649. "Unable to open file \"%s\"\n",
  2650. output_file_.c_str());
  2651. fflush(stderr);
  2652. exit(EXIT_FAILURE);
  2653. }
  2654. PrintXmlUnitTest(xmlout, unit_test);
  2655. fclose(xmlout);
  2656. }
  2657. // Returns an XML-escaped copy of the input string str. If is_attribute
  2658. // is true, the text is meant to appear as an attribute value, and
  2659. // normalizable whitespace is preserved by replacing it with character
  2660. // references.
  2661. //
  2662. // Invalid XML characters in str, if any, are stripped from the output.
  2663. // It is expected that most, if not all, of the text processed by this
  2664. // module will consist of ordinary English text.
  2665. // If this module is ever modified to produce version 1.1 XML output,
  2666. // most invalid characters can be retained using character references.
  2667. // TODO(wan): It might be nice to have a minimally invasive, human-readable
  2668. // escaping scheme for invalid characters, rather than dropping them.
  2669. String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
  2670. Message m;
  2671. if (str != NULL) {
  2672. for (const char* src = str; *src; ++src) {
  2673. switch (*src) {
  2674. case '<':
  2675. m << "&lt;";
  2676. break;
  2677. case '>':
  2678. m << "&gt;";
  2679. break;
  2680. case '&':
  2681. m << "&amp;";
  2682. break;
  2683. case '\'':
  2684. if (is_attribute)
  2685. m << "&apos;";
  2686. else
  2687. m << '\'';
  2688. break;
  2689. case '"':
  2690. if (is_attribute)
  2691. m << "&quot;";
  2692. else
  2693. m << '"';
  2694. break;
  2695. default:
  2696. if (IsValidXmlCharacter(*src)) {
  2697. if (is_attribute && IsNormalizableWhitespace(*src))
  2698. m << String::Format("&#x%02X;", unsigned(*src));
  2699. else
  2700. m << *src;
  2701. }
  2702. break;
  2703. }
  2704. }
  2705. }
  2706. return m.GetString();
  2707. }
  2708. // Returns the given string with all characters invalid in XML removed.
  2709. // Currently invalid characters are dropped from the string. An
  2710. // alternative is to replace them with certain characters such as . or ?.
  2711. string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
  2712. string output;
  2713. output.reserve(str.size());
  2714. for (string::const_iterator it = str.begin(); it != str.end(); ++it)
  2715. if (IsValidXmlCharacter(*it))
  2716. output.push_back(*it);
  2717. return output;
  2718. }
  2719. // The following routines generate an XML representation of a UnitTest
  2720. // object.
  2721. //
  2722. // This is how Google Test concepts map to the DTD:
  2723. //
  2724. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  2725. // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
  2726. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  2727. // <failure message="...">...</failure>
  2728. // <failure message="...">...</failure>
  2729. // <failure message="...">...</failure>
  2730. // <-- individual assertion failures
  2731. // </testcase>
  2732. // </testsuite>
  2733. // </testsuites>
  2734. // Formats the given time in milliseconds as seconds.
  2735. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  2736. ::std::stringstream ss;
  2737. ss << ms/1000.0;
  2738. return ss.str();
  2739. }
  2740. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  2741. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  2742. const char* data) {
  2743. const char* segment = data;
  2744. *stream << "<![CDATA[";
  2745. for (;;) {
  2746. const char* const next_segment = strstr(segment, "]]>");
  2747. if (next_segment != NULL) {
  2748. stream->write(
  2749. segment, static_cast<std::streamsize>(next_segment - segment));
  2750. *stream << "]]>]]&gt;<![CDATA[";
  2751. segment = next_segment + strlen("]]>");
  2752. } else {
  2753. *stream << segment;
  2754. break;
  2755. }
  2756. }
  2757. *stream << "]]>";
  2758. }
  2759. // Prints an XML representation of a TestInfo object.
  2760. // TODO(wan): There is also value in printing properties with the plain printer.
  2761. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  2762. const char* test_case_name,
  2763. const TestInfo& test_info) {
  2764. const TestResult& result = *test_info.result();
  2765. *stream << " <testcase name=\""
  2766. << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
  2767. if (test_info.value_param() != NULL) {
  2768. *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
  2769. << "\"";
  2770. }
  2771. if (test_info.type_param() != NULL) {
  2772. *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
  2773. << "\"";
  2774. }
  2775. *stream << " status=\""
  2776. << (test_info.should_run() ? "run" : "notrun")
  2777. << "\" time=\""
  2778. << FormatTimeInMillisAsSeconds(result.elapsed_time())
  2779. << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
  2780. << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
  2781. int failures = 0;
  2782. for (int i = 0; i < result.total_part_count(); ++i) {
  2783. const TestPartResult& part = result.GetTestPartResult(i);
  2784. if (part.failed()) {
  2785. if (++failures == 1)
  2786. *stream << ">\n";
  2787. *stream << " <failure message=\""
  2788. << EscapeXmlAttribute(part.summary()).c_str()
  2789. << "\" type=\"\">";
  2790. const string location = internal::FormatCompilerIndependentFileLocation(
  2791. part.file_name(), part.line_number());
  2792. const string message = location + "\n" + part.message();
  2793. OutputXmlCDataSection(stream,
  2794. RemoveInvalidXmlCharacters(message).c_str());
  2795. *stream << "</failure>\n";
  2796. }
  2797. }
  2798. if (failures == 0)
  2799. *stream << " />\n";
  2800. else
  2801. *stream << " </testcase>\n";
  2802. }
  2803. // Prints an XML representation of a TestCase object
  2804. void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
  2805. const TestCase& test_case) {
  2806. fprintf(out,
  2807. " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
  2808. "disabled=\"%d\" ",
  2809. EscapeXmlAttribute(test_case.name()).c_str(),
  2810. test_case.total_test_count(),
  2811. test_case.failed_test_count(),
  2812. test_case.disabled_test_count());
  2813. fprintf(out,
  2814. "errors=\"0\" time=\"%s\">\n",
  2815. FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
  2816. for (int i = 0; i < test_case.total_test_count(); ++i) {
  2817. ::std::stringstream stream;
  2818. OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
  2819. fprintf(out, "%s", StringStreamToString(&stream).c_str());
  2820. }
  2821. fprintf(out, " </testsuite>\n");
  2822. }
  2823. // Prints an XML summary of unit_test to output stream out.
  2824. void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
  2825. const UnitTest& unit_test) {
  2826. fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  2827. fprintf(out,
  2828. "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
  2829. "errors=\"0\" time=\"%s\" ",
  2830. unit_test.total_test_count(),
  2831. unit_test.failed_test_count(),
  2832. unit_test.disabled_test_count(),
  2833. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
  2834. if (GTEST_FLAG(shuffle)) {
  2835. fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
  2836. }
  2837. fprintf(out, "name=\"AllTests\">\n");
  2838. for (int i = 0; i < unit_test.total_test_case_count(); ++i)
  2839. PrintXmlTestCase(out, *unit_test.GetTestCase(i));
  2840. fprintf(out, "</testsuites>\n");
  2841. }
  2842. // Produces a string representing the test properties in a result as space
  2843. // delimited XML attributes based on the property key="value" pairs.
  2844. String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  2845. const TestResult& result) {
  2846. Message attributes;
  2847. for (int i = 0; i < result.test_property_count(); ++i) {
  2848. const TestProperty& property = result.GetTestProperty(i);
  2849. attributes << " " << property.key() << "="
  2850. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  2851. }
  2852. return attributes.GetString();
  2853. }
  2854. // End XmlUnitTestResultPrinter
  2855. #if GTEST_CAN_STREAM_RESULTS_
  2856. // Streams test results to the given port on the given host machine.
  2857. class StreamingListener : public EmptyTestEventListener {
  2858. public:
  2859. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  2860. static string UrlEncode(const char* str);
  2861. StreamingListener(const string& host, const string& port)
  2862. : sockfd_(-1), host_name_(host), port_num_(port) {
  2863. MakeConnection();
  2864. Send("gtest_streaming_protocol_version=1.0\n");
  2865. }
  2866. virtual ~StreamingListener() {
  2867. if (sockfd_ != -1)
  2868. CloseConnection();
  2869. }
  2870. void OnTestProgramStart(const UnitTest& /* unit_test */) {
  2871. Send("event=TestProgramStart\n");
  2872. }
  2873. void OnTestProgramEnd(const UnitTest& unit_test) {
  2874. // Note that Google Test current only report elapsed time for each
  2875. // test iteration, not for the entire test program.
  2876. Send(String::Format("event=TestProgramEnd&passed=%d\n",
  2877. unit_test.Passed()));
  2878. // Notify the streaming server to stop.
  2879. CloseConnection();
  2880. }
  2881. void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
  2882. Send(String::Format("event=TestIterationStart&iteration=%d\n",
  2883. iteration));
  2884. }
  2885. void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
  2886. Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
  2887. unit_test.Passed(),
  2888. StreamableToString(unit_test.elapsed_time()).c_str()));
  2889. }
  2890. void OnTestCaseStart(const TestCase& test_case) {
  2891. Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
  2892. }
  2893. void OnTestCaseEnd(const TestCase& test_case) {
  2894. Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
  2895. test_case.Passed(),
  2896. StreamableToString(test_case.elapsed_time()).c_str()));
  2897. }
  2898. void OnTestStart(const TestInfo& test_info) {
  2899. Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
  2900. }
  2901. void OnTestEnd(const TestInfo& test_info) {
  2902. Send(String::Format(
  2903. "event=TestEnd&passed=%d&elapsed_time=%sms\n",
  2904. (test_info.result())->Passed(),
  2905. StreamableToString((test_info.result())->elapsed_time()).c_str()));
  2906. }
  2907. void OnTestPartResult(const TestPartResult& test_part_result) {
  2908. const char* file_name = test_part_result.file_name();
  2909. if (file_name == NULL)
  2910. file_name = "";
  2911. Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
  2912. UrlEncode(file_name).c_str(),
  2913. test_part_result.line_number()));
  2914. Send(UrlEncode(test_part_result.message()) + "\n");
  2915. }
  2916. private:
  2917. // Creates a client socket and connects to the server.
  2918. void MakeConnection();
  2919. // Closes the socket.
  2920. void CloseConnection() {
  2921. GTEST_CHECK_(sockfd_ != -1)
  2922. << "CloseConnection() can be called only when there is a connection.";
  2923. close(sockfd_);
  2924. sockfd_ = -1;
  2925. }
  2926. // Sends a string to the socket.
  2927. void Send(const string& message) {
  2928. GTEST_CHECK_(sockfd_ != -1)
  2929. << "Send() can be called only when there is a connection.";
  2930. const int len = static_cast<int>(message.length());
  2931. if (write(sockfd_, message.c_str(), len) != len) {
  2932. GTEST_LOG_(WARNING)
  2933. << "stream_result_to: failed to stream to "
  2934. << host_name_ << ":" << port_num_;
  2935. }
  2936. }
  2937. int sockfd_; // socket file descriptor
  2938. const string host_name_;
  2939. const string port_num_;
  2940. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  2941. }; // class StreamingListener
  2942. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  2943. // replaces them by "%xx" where xx is their hexadecimal value. For
  2944. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  2945. // in both time and space -- important as the input str may contain an
  2946. // arbitrarily long test failure message and stack trace.
  2947. string StreamingListener::UrlEncode(const char* str) {
  2948. string result;
  2949. result.reserve(strlen(str) + 1);
  2950. for (char ch = *str; ch != '\0'; ch = *++str) {
  2951. switch (ch) {
  2952. case '%':
  2953. case '=':
  2954. case '&':
  2955. case '\n':
  2956. result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
  2957. break;
  2958. default:
  2959. result.push_back(ch);
  2960. break;
  2961. }
  2962. }
  2963. return result;
  2964. }
  2965. void StreamingListener::MakeConnection() {
  2966. GTEST_CHECK_(sockfd_ == -1)
  2967. << "MakeConnection() can't be called when there is already a connection.";
  2968. addrinfo hints;
  2969. memset(&hints, 0, sizeof(hints));
  2970. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  2971. hints.ai_socktype = SOCK_STREAM;
  2972. addrinfo* servinfo = NULL;
  2973. // Use the getaddrinfo() to get a linked list of IP addresses for
  2974. // the given host name.
  2975. const int error_num = getaddrinfo(
  2976. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  2977. if (error_num != 0) {
  2978. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  2979. << gai_strerror(error_num);
  2980. }
  2981. // Loop through all the results and connect to the first we can.
  2982. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  2983. cur_addr = cur_addr->ai_next) {
  2984. sockfd_ = socket(
  2985. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  2986. if (sockfd_ != -1) {
  2987. // Connect the client socket to the server socket.
  2988. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  2989. close(sockfd_);
  2990. sockfd_ = -1;
  2991. }
  2992. }
  2993. }
  2994. freeaddrinfo(servinfo); // all done with this structure
  2995. if (sockfd_ == -1) {
  2996. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  2997. << host_name_ << ":" << port_num_;
  2998. }
  2999. }
  3000. // End of class Streaming Listener
  3001. #endif // GTEST_CAN_STREAM_RESULTS__
  3002. // Class ScopedTrace
  3003. // Pushes the given source file location and message onto a per-thread
  3004. // trace stack maintained by Google Test.
  3005. // L < UnitTest::mutex_
  3006. ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
  3007. TraceInfo trace;
  3008. trace.file = file;
  3009. trace.line = line;
  3010. trace.message = message.GetString();
  3011. UnitTest::GetInstance()->PushGTestTrace(trace);
  3012. }
  3013. // Pops the info pushed by the c'tor.
  3014. // L < UnitTest::mutex_
  3015. ScopedTrace::~ScopedTrace() {
  3016. UnitTest::GetInstance()->PopGTestTrace();
  3017. }
  3018. // class OsStackTraceGetter
  3019. // Returns the current OS stack trace as a String. Parameters:
  3020. //
  3021. // max_depth - the maximum number of stack frames to be included
  3022. // in the trace.
  3023. // skip_count - the number of top frames to be skipped; doesn't count
  3024. // against max_depth.
  3025. //
  3026. // L < mutex_
  3027. // We use "L < mutex_" to denote that the function may acquire mutex_.
  3028. String OsStackTraceGetter::CurrentStackTrace(int, int) {
  3029. return String("");
  3030. }
  3031. // L < mutex_
  3032. void OsStackTraceGetter::UponLeavingGTest() {
  3033. }
  3034. const char* const
  3035. OsStackTraceGetter::kElidedFramesMarker =
  3036. "... " GTEST_NAME_ " internal frames ...";
  3037. } // namespace internal
  3038. // class TestEventListeners
  3039. TestEventListeners::TestEventListeners()
  3040. : repeater_(new internal::TestEventRepeater()),
  3041. default_result_printer_(NULL),
  3042. default_xml_generator_(NULL) {
  3043. }
  3044. TestEventListeners::~TestEventListeners() { delete repeater_; }
  3045. // Returns the standard listener responsible for the default console
  3046. // output. Can be removed from the listeners list to shut down default
  3047. // console output. Note that removing this object from the listener list
  3048. // with Release transfers its ownership to the user.
  3049. void TestEventListeners::Append(TestEventListener* listener) {
  3050. repeater_->Append(listener);
  3051. }
  3052. // Removes the given event listener from the list and returns it. It then
  3053. // becomes the caller's responsibility to delete the listener. Returns
  3054. // NULL if the listener is not found in the list.
  3055. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  3056. if (listener == default_result_printer_)
  3057. default_result_printer_ = NULL;
  3058. else if (listener == default_xml_generator_)
  3059. default_xml_generator_ = NULL;
  3060. return repeater_->Release(listener);
  3061. }
  3062. // Returns repeater that broadcasts the TestEventListener events to all
  3063. // subscribers.
  3064. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  3065. // Sets the default_result_printer attribute to the provided listener.
  3066. // The listener is also added to the listener list and previous
  3067. // default_result_printer is removed from it and deleted. The listener can
  3068. // also be NULL in which case it will not be added to the list. Does
  3069. // nothing if the previous and the current listener objects are the same.
  3070. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  3071. if (default_result_printer_ != listener) {
  3072. // It is an error to pass this method a listener that is already in the
  3073. // list.
  3074. delete Release(default_result_printer_);
  3075. default_result_printer_ = listener;
  3076. if (listener != NULL)
  3077. Append(listener);
  3078. }
  3079. }
  3080. // Sets the default_xml_generator attribute to the provided listener. The
  3081. // listener is also added to the listener list and previous
  3082. // default_xml_generator is removed from it and deleted. The listener can
  3083. // also be NULL in which case it will not be added to the list. Does
  3084. // nothing if the previous and the current listener objects are the same.
  3085. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  3086. if (default_xml_generator_ != listener) {
  3087. // It is an error to pass this method a listener that is already in the
  3088. // list.
  3089. delete Release(default_xml_generator_);
  3090. default_xml_generator_ = listener;
  3091. if (listener != NULL)
  3092. Append(listener);
  3093. }
  3094. }
  3095. // Controls whether events will be forwarded by the repeater to the
  3096. // listeners in the list.
  3097. bool TestEventListeners::EventForwardingEnabled() const {
  3098. return repeater_->forwarding_enabled();
  3099. }
  3100. void TestEventListeners::SuppressEventForwarding() {
  3101. repeater_->set_forwarding_enabled(false);
  3102. }
  3103. // class UnitTest
  3104. // Gets the singleton UnitTest object. The first time this method is
  3105. // called, a UnitTest object is constructed and returned. Consecutive
  3106. // calls will return the same object.
  3107. //
  3108. // We don't protect this under mutex_ as a user is not supposed to
  3109. // call this before main() starts, from which point on the return
  3110. // value will never change.
  3111. UnitTest * UnitTest::GetInstance() {
  3112. // When compiled with MSVC 7.1 in optimized mode, destroying the
  3113. // UnitTest object upon exiting the program messes up the exit code,
  3114. // causing successful tests to appear failed. We have to use a
  3115. // different implementation in this case to bypass the compiler bug.
  3116. // This implementation makes the compiler happy, at the cost of
  3117. // leaking the UnitTest object.
  3118. // CodeGear C++Builder insists on a public destructor for the
  3119. // default implementation. Use this implementation to keep good OO
  3120. // design with private destructor.
  3121. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  3122. static UnitTest* const instance = new UnitTest;
  3123. return instance;
  3124. #else
  3125. static UnitTest instance;
  3126. return &instance;
  3127. #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  3128. }
  3129. // Gets the number of successful test cases.
  3130. int UnitTest::successful_test_case_count() const {
  3131. return impl()->successful_test_case_count();
  3132. }
  3133. // Gets the number of failed test cases.
  3134. int UnitTest::failed_test_case_count() const {
  3135. return impl()->failed_test_case_count();
  3136. }
  3137. // Gets the number of all test cases.
  3138. int UnitTest::total_test_case_count() const {
  3139. return impl()->total_test_case_count();
  3140. }
  3141. // Gets the number of all test cases that contain at least one test
  3142. // that should run.
  3143. int UnitTest::test_case_to_run_count() const {
  3144. return impl()->test_case_to_run_count();
  3145. }
  3146. // Gets the number of successful tests.
  3147. int UnitTest::successful_test_count() const {
  3148. return impl()->successful_test_count();
  3149. }
  3150. // Gets the number of failed tests.
  3151. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  3152. // Gets the number of disabled tests.
  3153. int UnitTest::disabled_test_count() const {
  3154. return impl()->disabled_test_count();
  3155. }
  3156. // Gets the number of all tests.
  3157. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  3158. // Gets the number of tests that should run.
  3159. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  3160. // Gets the elapsed time, in milliseconds.
  3161. internal::TimeInMillis UnitTest::elapsed_time() const {
  3162. return impl()->elapsed_time();
  3163. }
  3164. // Returns true iff the unit test passed (i.e. all test cases passed).
  3165. bool UnitTest::Passed() const { return impl()->Passed(); }
  3166. // Returns true iff the unit test failed (i.e. some test case failed
  3167. // or something outside of all tests failed).
  3168. bool UnitTest::Failed() const { return impl()->Failed(); }
  3169. // Gets the i-th test case among all the test cases. i can range from 0 to
  3170. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  3171. const TestCase* UnitTest::GetTestCase(int i) const {
  3172. return impl()->GetTestCase(i);
  3173. }
  3174. // Gets the i-th test case among all the test cases. i can range from 0 to
  3175. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  3176. TestCase* UnitTest::GetMutableTestCase(int i) {
  3177. return impl()->GetMutableTestCase(i);
  3178. }
  3179. // Returns the list of event listeners that can be used to track events
  3180. // inside Google Test.
  3181. TestEventListeners& UnitTest::listeners() {
  3182. return *impl()->listeners();
  3183. }
  3184. // Registers and returns a global test environment. When a test
  3185. // program is run, all global test environments will be set-up in the
  3186. // order they were registered. After all tests in the program have
  3187. // finished, all global test environments will be torn-down in the
  3188. // *reverse* order they were registered.
  3189. //
  3190. // The UnitTest object takes ownership of the given environment.
  3191. //
  3192. // We don't protect this under mutex_, as we only support calling it
  3193. // from the main thread.
  3194. Environment* UnitTest::AddEnvironment(Environment* env) {
  3195. if (env == NULL) {
  3196. return NULL;
  3197. }
  3198. impl_->environments().push_back(env);
  3199. return env;
  3200. }
  3201. // Adds a TestPartResult to the current TestResult object. All Google Test
  3202. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  3203. // this to report their results. The user code should use the
  3204. // assertion macros instead of calling this directly.
  3205. // L < mutex_
  3206. void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
  3207. const char* file_name,
  3208. int line_number,
  3209. const internal::String& message,
  3210. const internal::String& os_stack_trace) {
  3211. Message msg;
  3212. msg << message;
  3213. internal::MutexLock lock(&mutex_);
  3214. if (impl_->gtest_trace_stack().size() > 0) {
  3215. msg << "\n" << GTEST_NAME_ << " trace:";
  3216. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  3217. i > 0; --i) {
  3218. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  3219. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  3220. << " " << trace.message;
  3221. }
  3222. }
  3223. if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  3224. msg << internal::kStackTraceMarker << os_stack_trace;
  3225. }
  3226. const TestPartResult result =
  3227. TestPartResult(result_type, file_name, line_number,
  3228. msg.GetString().c_str());
  3229. impl_->GetTestPartResultReporterForCurrentThread()->
  3230. ReportTestPartResult(result);
  3231. if (result_type != TestPartResult::kSuccess) {
  3232. // gtest_break_on_failure takes precedence over
  3233. // gtest_throw_on_failure. This allows a user to set the latter
  3234. // in the code (perhaps in order to use Google Test assertions
  3235. // with another testing framework) and specify the former on the
  3236. // command line for debugging.
  3237. if (GTEST_FLAG(break_on_failure)) {
  3238. #if GTEST_OS_WINDOWS
  3239. // Using DebugBreak on Windows allows gtest to still break into a debugger
  3240. // when a failure happens and both the --gtest_break_on_failure and
  3241. // the --gtest_catch_exceptions flags are specified.
  3242. DebugBreak();
  3243. #else
  3244. // Dereference NULL through a volatile pointer to prevent the compiler
  3245. // from removing. We use this rather than abort() or __builtin_trap() for
  3246. // portability: Symbian doesn't implement abort() well, and some debuggers
  3247. // don't correctly trap abort().
  3248. *static_cast<volatile int*>(NULL) = 1;
  3249. #endif // GTEST_OS_WINDOWS
  3250. } else if (GTEST_FLAG(throw_on_failure)) {
  3251. #if GTEST_HAS_EXCEPTIONS
  3252. throw GoogleTestFailureException(result);
  3253. #else
  3254. // We cannot call abort() as it generates a pop-up in debug mode
  3255. // that cannot be suppressed in VC 7.1 or below.
  3256. exit(1);
  3257. #endif
  3258. }
  3259. }
  3260. }
  3261. // Creates and adds a property to the current TestResult. If a property matching
  3262. // the supplied value already exists, updates its value instead.
  3263. void UnitTest::RecordPropertyForCurrentTest(const char* key,
  3264. const char* value) {
  3265. const TestProperty test_property(key, value);
  3266. impl_->current_test_result()->RecordProperty(test_property);
  3267. }
  3268. // Runs all tests in this UnitTest object and prints the result.
  3269. // Returns 0 if successful, or 1 otherwise.
  3270. //
  3271. // We don't protect this under mutex_, as we only support calling it
  3272. // from the main thread.
  3273. int UnitTest::Run() {
  3274. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  3275. // used for the duration of the program.
  3276. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  3277. #if GTEST_HAS_SEH
  3278. const bool in_death_test_child_process =
  3279. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  3280. // Either the user wants Google Test to catch exceptions thrown by the
  3281. // tests or this is executing in the context of death test child
  3282. // process. In either case the user does not want to see pop-up dialogs
  3283. // about crashes - they are expected.
  3284. if (impl()->catch_exceptions() || in_death_test_child_process) {
  3285. # if !GTEST_OS_WINDOWS_MOBILE
  3286. // SetErrorMode doesn't exist on CE.
  3287. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  3288. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  3289. # endif // !GTEST_OS_WINDOWS_MOBILE
  3290. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  3291. // Death test children can be terminated with _abort(). On Windows,
  3292. // _abort() can show a dialog with a warning message. This forces the
  3293. // abort message to go to stderr instead.
  3294. _set_error_mode(_OUT_TO_STDERR);
  3295. # endif
  3296. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  3297. // In the debug version, Visual Studio pops up a separate dialog
  3298. // offering a choice to debug the aborted program. We need to suppress
  3299. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  3300. // executed. Google Test will notify the user of any unexpected
  3301. // failure via stderr.
  3302. //
  3303. // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  3304. // Users of prior VC versions shall suffer the agony and pain of
  3305. // clicking through the countless debug dialogs.
  3306. // TODO([email protected]): find a way to suppress the abort dialog() in the
  3307. // debug mode when compiled with VC 7.1 or lower.
  3308. if (!GTEST_FLAG(break_on_failure))
  3309. _set_abort_behavior(
  3310. 0x0, // Clear the following flags:
  3311. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  3312. # endif
  3313. }
  3314. #endif // GTEST_HAS_SEH
  3315. return internal::HandleExceptionsInMethodIfSupported(
  3316. impl(),
  3317. &internal::UnitTestImpl::RunAllTests,
  3318. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  3319. }
  3320. // Returns the working directory when the first TEST() or TEST_F() was
  3321. // executed.
  3322. const char* UnitTest::original_working_dir() const {
  3323. return impl_->original_working_dir_.c_str();
  3324. }
  3325. // Returns the TestCase object for the test that's currently running,
  3326. // or NULL if no test is running.
  3327. // L < mutex_
  3328. const TestCase* UnitTest::current_test_case() const {
  3329. internal::MutexLock lock(&mutex_);
  3330. return impl_->current_test_case();
  3331. }
  3332. // Returns the TestInfo object for the test that's currently running,
  3333. // or NULL if no test is running.
  3334. // L < mutex_
  3335. const TestInfo* UnitTest::current_test_info() const {
  3336. internal::MutexLock lock(&mutex_);
  3337. return impl_->current_test_info();
  3338. }
  3339. // Returns the random seed used at the start of the current test run.
  3340. int UnitTest::random_seed() const { return impl_->random_seed(); }
  3341. #if GTEST_HAS_PARAM_TEST
  3342. // Returns ParameterizedTestCaseRegistry object used to keep track of
  3343. // value-parameterized tests and instantiate and register them.
  3344. // L < mutex_
  3345. internal::ParameterizedTestCaseRegistry&
  3346. UnitTest::parameterized_test_registry() {
  3347. return impl_->parameterized_test_registry();
  3348. }
  3349. #endif // GTEST_HAS_PARAM_TEST
  3350. // Creates an empty UnitTest.
  3351. UnitTest::UnitTest() {
  3352. impl_ = new internal::UnitTestImpl(this);
  3353. }
  3354. // Destructor of UnitTest.
  3355. UnitTest::~UnitTest() {
  3356. delete impl_;
  3357. }
  3358. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  3359. // Google Test trace stack.
  3360. // L < mutex_
  3361. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
  3362. internal::MutexLock lock(&mutex_);
  3363. impl_->gtest_trace_stack().push_back(trace);
  3364. }
  3365. // Pops a trace from the per-thread Google Test trace stack.
  3366. // L < mutex_
  3367. void UnitTest::PopGTestTrace() {
  3368. internal::MutexLock lock(&mutex_);
  3369. impl_->gtest_trace_stack().pop_back();
  3370. }
  3371. namespace internal {
  3372. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  3373. : parent_(parent),
  3374. #ifdef _MSC_VER
  3375. # pragma warning(push) // Saves the current warning state.
  3376. # pragma warning(disable:4355) // Temporarily disables warning 4355
  3377. // (using this in initializer).
  3378. default_global_test_part_result_reporter_(this),
  3379. default_per_thread_test_part_result_reporter_(this),
  3380. # pragma warning(pop) // Restores the warning state again.
  3381. #else
  3382. default_global_test_part_result_reporter_(this),
  3383. default_per_thread_test_part_result_reporter_(this),
  3384. #endif // _MSC_VER
  3385. global_test_part_result_repoter_(
  3386. &default_global_test_part_result_reporter_),
  3387. per_thread_test_part_result_reporter_(
  3388. &default_per_thread_test_part_result_reporter_),
  3389. #if GTEST_HAS_PARAM_TEST
  3390. parameterized_test_registry_(),
  3391. parameterized_tests_registered_(false),
  3392. #endif // GTEST_HAS_PARAM_TEST
  3393. last_death_test_case_(-1),
  3394. current_test_case_(NULL),
  3395. current_test_info_(NULL),
  3396. ad_hoc_test_result_(),
  3397. os_stack_trace_getter_(NULL),
  3398. post_flag_parse_init_performed_(false),
  3399. random_seed_(0), // Will be overridden by the flag before first use.
  3400. random_(0), // Will be reseeded before first use.
  3401. elapsed_time_(0),
  3402. #if GTEST_HAS_DEATH_TEST
  3403. internal_run_death_test_flag_(NULL),
  3404. death_test_factory_(new DefaultDeathTestFactory),
  3405. #endif
  3406. // Will be overridden by the flag before first use.
  3407. catch_exceptions_(false) {
  3408. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  3409. }
  3410. UnitTestImpl::~UnitTestImpl() {
  3411. // Deletes every TestCase.
  3412. ForEach(test_cases_, internal::Delete<TestCase>);
  3413. // Deletes every Environment.
  3414. ForEach(environments_, internal::Delete<Environment>);
  3415. delete os_stack_trace_getter_;
  3416. }
  3417. #if GTEST_HAS_DEATH_TEST
  3418. // Disables event forwarding if the control is currently in a death test
  3419. // subprocess. Must not be called before InitGoogleTest.
  3420. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  3421. if (internal_run_death_test_flag_.get() != NULL)
  3422. listeners()->SuppressEventForwarding();
  3423. }
  3424. #endif // GTEST_HAS_DEATH_TEST
  3425. // Initializes event listeners performing XML output as specified by
  3426. // UnitTestOptions. Must not be called before InitGoogleTest.
  3427. void UnitTestImpl::ConfigureXmlOutput() {
  3428. const String& output_format = UnitTestOptions::GetOutputFormat();
  3429. if (output_format == "xml") {
  3430. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  3431. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  3432. } else if (output_format != "") {
  3433. printf("WARNING: unrecognized output format \"%s\" ignored.\n",
  3434. output_format.c_str());
  3435. fflush(stdout);
  3436. }
  3437. }
  3438. #if GTEST_CAN_STREAM_RESULTS_
  3439. // Initializes event listeners for streaming test results in String form.
  3440. // Must not be called before InitGoogleTest.
  3441. void UnitTestImpl::ConfigureStreamingOutput() {
  3442. const string& target = GTEST_FLAG(stream_result_to);
  3443. if (!target.empty()) {
  3444. const size_t pos = target.find(':');
  3445. if (pos != string::npos) {
  3446. listeners()->Append(new StreamingListener(target.substr(0, pos),
  3447. target.substr(pos+1)));
  3448. } else {
  3449. printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
  3450. target.c_str());
  3451. fflush(stdout);
  3452. }
  3453. }
  3454. }
  3455. #endif // GTEST_CAN_STREAM_RESULTS_
  3456. // Performs initialization dependent upon flag values obtained in
  3457. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  3458. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  3459. // this function is also called from RunAllTests. Since this function can be
  3460. // called more than once, it has to be idempotent.
  3461. void UnitTestImpl::PostFlagParsingInit() {
  3462. // Ensures that this function does not execute more than once.
  3463. if (!post_flag_parse_init_performed_) {
  3464. post_flag_parse_init_performed_ = true;
  3465. #if GTEST_HAS_DEATH_TEST
  3466. InitDeathTestSubprocessControlInfo();
  3467. SuppressTestEventsIfInSubprocess();
  3468. #endif // GTEST_HAS_DEATH_TEST
  3469. // Registers parameterized tests. This makes parameterized tests
  3470. // available to the UnitTest reflection API without running
  3471. // RUN_ALL_TESTS.
  3472. RegisterParameterizedTests();
  3473. // Configures listeners for XML output. This makes it possible for users
  3474. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  3475. ConfigureXmlOutput();
  3476. #if GTEST_CAN_STREAM_RESULTS_
  3477. // Configures listeners for streaming test results to the specified server.
  3478. ConfigureStreamingOutput();
  3479. #endif // GTEST_CAN_STREAM_RESULTS_
  3480. }
  3481. }
  3482. // A predicate that checks the name of a TestCase against a known
  3483. // value.
  3484. //
  3485. // This is used for implementation of the UnitTest class only. We put
  3486. // it in the anonymous namespace to prevent polluting the outer
  3487. // namespace.
  3488. //
  3489. // TestCaseNameIs is copyable.
  3490. class TestCaseNameIs {
  3491. public:
  3492. // Constructor.
  3493. explicit TestCaseNameIs(const String& name)
  3494. : name_(name) {}
  3495. // Returns true iff the name of test_case matches name_.
  3496. bool operator()(const TestCase* test_case) const {
  3497. return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  3498. }
  3499. private:
  3500. String name_;
  3501. };
  3502. // Finds and returns a TestCase with the given name. If one doesn't
  3503. // exist, creates one and returns it. It's the CALLER'S
  3504. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  3505. // TESTS ARE NOT SHUFFLED.
  3506. //
  3507. // Arguments:
  3508. //
  3509. // test_case_name: name of the test case
  3510. // type_param: the name of the test case's type parameter, or NULL if
  3511. // this is not a typed or a type-parameterized test case.
  3512. // set_up_tc: pointer to the function that sets up the test case
  3513. // tear_down_tc: pointer to the function that tears down the test case
  3514. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  3515. const char* type_param,
  3516. Test::SetUpTestCaseFunc set_up_tc,
  3517. Test::TearDownTestCaseFunc tear_down_tc) {
  3518. // Can we find a TestCase with the given name?
  3519. const std::vector<TestCase*>::const_iterator test_case =
  3520. std::find_if(test_cases_.begin(), test_cases_.end(),
  3521. TestCaseNameIs(test_case_name));
  3522. if (test_case != test_cases_.end())
  3523. return *test_case;
  3524. // No. Let's create one.
  3525. TestCase* const new_test_case =
  3526. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  3527. // Is this a death test case?
  3528. if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
  3529. kDeathTestCaseFilter)) {
  3530. // Yes. Inserts the test case after the last death test case
  3531. // defined so far. This only works when the test cases haven't
  3532. // been shuffled. Otherwise we may end up running a death test
  3533. // after a non-death test.
  3534. ++last_death_test_case_;
  3535. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  3536. new_test_case);
  3537. } else {
  3538. // No. Appends to the end of the list.
  3539. test_cases_.push_back(new_test_case);
  3540. }
  3541. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  3542. return new_test_case;
  3543. }
  3544. // Helpers for setting up / tearing down the given environment. They
  3545. // are for use in the ForEach() function.
  3546. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  3547. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  3548. // Runs all tests in this UnitTest object, prints the result, and
  3549. // returns true if all tests are successful. If any exception is
  3550. // thrown during a test, the test is considered to be failed, but the
  3551. // rest of the tests will still be run.
  3552. //
  3553. // When parameterized tests are enabled, it expands and registers
  3554. // parameterized tests first in RegisterParameterizedTests().
  3555. // All other functions called from RunAllTests() may safely assume that
  3556. // parameterized tests are ready to be counted and run.
  3557. bool UnitTestImpl::RunAllTests() {
  3558. // Makes sure InitGoogleTest() was called.
  3559. if (!GTestIsInitialized()) {
  3560. printf("%s",
  3561. "\nThis test program did NOT call ::testing::InitGoogleTest "
  3562. "before calling RUN_ALL_TESTS(). Please fix it.\n");
  3563. return false;
  3564. }
  3565. // Do not run any test if the --help flag was specified.
  3566. if (g_help_flag)
  3567. return true;
  3568. // Repeats the call to the post-flag parsing initialization in case the
  3569. // user didn't call InitGoogleTest.
  3570. PostFlagParsingInit();
  3571. // Even if sharding is not on, test runners may want to use the
  3572. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  3573. // protocol.
  3574. internal::WriteToShardStatusFileIfNeeded();
  3575. // True iff we are in a subprocess for running a thread-safe-style
  3576. // death test.
  3577. bool in_subprocess_for_death_test = false;
  3578. #if GTEST_HAS_DEATH_TEST
  3579. in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  3580. #endif // GTEST_HAS_DEATH_TEST
  3581. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  3582. in_subprocess_for_death_test);
  3583. // Compares the full test names with the filter to decide which
  3584. // tests to run.
  3585. const bool has_tests_to_run = FilterTests(should_shard
  3586. ? HONOR_SHARDING_PROTOCOL
  3587. : IGNORE_SHARDING_PROTOCOL) > 0;
  3588. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  3589. if (GTEST_FLAG(list_tests)) {
  3590. // This must be called *after* FilterTests() has been called.
  3591. ListTestsMatchingFilter();
  3592. return true;
  3593. }
  3594. random_seed_ = GTEST_FLAG(shuffle) ?
  3595. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  3596. // True iff at least one test has failed.
  3597. bool failed = false;
  3598. TestEventListener* repeater = listeners()->repeater();
  3599. repeater->OnTestProgramStart(*parent_);
  3600. // How many times to repeat the tests? We don't want to repeat them
  3601. // when we are inside the subprocess of a death test.
  3602. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  3603. // Repeats forever if the repeat count is negative.
  3604. const bool forever = repeat < 0;
  3605. for (int i = 0; forever || i != repeat; i++) {
  3606. // We want to preserve failures generated by ad-hoc test
  3607. // assertions executed before RUN_ALL_TESTS().
  3608. ClearNonAdHocTestResult();
  3609. const TimeInMillis start = GetTimeInMillis();
  3610. // Shuffles test cases and tests if requested.
  3611. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  3612. random()->Reseed(random_seed_);
  3613. // This should be done before calling OnTestIterationStart(),
  3614. // such that a test event listener can see the actual test order
  3615. // in the event.
  3616. ShuffleTests();
  3617. }
  3618. // Tells the unit test event listeners that the tests are about to start.
  3619. repeater->OnTestIterationStart(*parent_, i);
  3620. // Runs each test case if there is at least one test to run.
  3621. if (has_tests_to_run) {
  3622. // Sets up all environments beforehand.
  3623. repeater->OnEnvironmentsSetUpStart(*parent_);
  3624. ForEach(environments_, SetUpEnvironment);
  3625. repeater->OnEnvironmentsSetUpEnd(*parent_);
  3626. // Runs the tests only if there was no fatal failure during global
  3627. // set-up.
  3628. if (!Test::HasFatalFailure()) {
  3629. for (int test_index = 0; test_index < total_test_case_count();
  3630. test_index++) {
  3631. GetMutableTestCase(test_index)->Run();
  3632. }
  3633. }
  3634. // Tears down all environments in reverse order afterwards.
  3635. repeater->OnEnvironmentsTearDownStart(*parent_);
  3636. std::for_each(environments_.rbegin(), environments_.rend(),
  3637. TearDownEnvironment);
  3638. repeater->OnEnvironmentsTearDownEnd(*parent_);
  3639. }
  3640. elapsed_time_ = GetTimeInMillis() - start;
  3641. // Tells the unit test event listener that the tests have just finished.
  3642. repeater->OnTestIterationEnd(*parent_, i);
  3643. // Gets the result and clears it.
  3644. if (!Passed()) {
  3645. failed = true;
  3646. }
  3647. // Restores the original test order after the iteration. This
  3648. // allows the user to quickly repro a failure that happens in the
  3649. // N-th iteration without repeating the first (N - 1) iterations.
  3650. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  3651. // case the user somehow changes the value of the flag somewhere
  3652. // (it's always safe to unshuffle the tests).
  3653. UnshuffleTests();
  3654. if (GTEST_FLAG(shuffle)) {
  3655. // Picks a new random seed for each iteration.
  3656. random_seed_ = GetNextRandomSeed(random_seed_);
  3657. }
  3658. }
  3659. repeater->OnTestProgramEnd(*parent_);
  3660. return !failed;
  3661. }
  3662. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  3663. // if the variable is present. If a file already exists at this location, this
  3664. // function will write over it. If the variable is present, but the file cannot
  3665. // be created, prints an error and exits.
  3666. void WriteToShardStatusFileIfNeeded() {
  3667. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  3668. if (test_shard_file != NULL) {
  3669. FILE* const file = posix::FOpen(test_shard_file, "w");
  3670. if (file == NULL) {
  3671. ColoredPrintf(COLOR_RED,
  3672. "Could not write to the test shard status file \"%s\" "
  3673. "specified by the %s environment variable.\n",
  3674. test_shard_file, kTestShardStatusFile);
  3675. fflush(stdout);
  3676. exit(EXIT_FAILURE);
  3677. }
  3678. fclose(file);
  3679. }
  3680. }
  3681. // Checks whether sharding is enabled by examining the relevant
  3682. // environment variable values. If the variables are present,
  3683. // but inconsistent (i.e., shard_index >= total_shards), prints
  3684. // an error and exits. If in_subprocess_for_death_test, sharding is
  3685. // disabled because it must only be applied to the original test
  3686. // process. Otherwise, we could filter out death tests we intended to execute.
  3687. bool ShouldShard(const char* total_shards_env,
  3688. const char* shard_index_env,
  3689. bool in_subprocess_for_death_test) {
  3690. if (in_subprocess_for_death_test) {
  3691. return false;
  3692. }
  3693. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  3694. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  3695. if (total_shards == -1 && shard_index == -1) {
  3696. return false;
  3697. } else if (total_shards == -1 && shard_index != -1) {
  3698. const Message msg = Message()
  3699. << "Invalid environment variables: you have "
  3700. << kTestShardIndex << " = " << shard_index
  3701. << ", but have left " << kTestTotalShards << " unset.\n";
  3702. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  3703. fflush(stdout);
  3704. exit(EXIT_FAILURE);
  3705. } else if (total_shards != -1 && shard_index == -1) {
  3706. const Message msg = Message()
  3707. << "Invalid environment variables: you have "
  3708. << kTestTotalShards << " = " << total_shards
  3709. << ", but have left " << kTestShardIndex << " unset.\n";
  3710. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  3711. fflush(stdout);
  3712. exit(EXIT_FAILURE);
  3713. } else if (shard_index < 0 || shard_index >= total_shards) {
  3714. const Message msg = Message()
  3715. << "Invalid environment variables: we require 0 <= "
  3716. << kTestShardIndex << " < " << kTestTotalShards
  3717. << ", but you have " << kTestShardIndex << "=" << shard_index
  3718. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  3719. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  3720. fflush(stdout);
  3721. exit(EXIT_FAILURE);
  3722. }
  3723. return total_shards > 1;
  3724. }
  3725. // Parses the environment variable var as an Int32. If it is unset,
  3726. // returns default_val. If it is not an Int32, prints an error
  3727. // and aborts.
  3728. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  3729. const char* str_val = posix::GetEnv(var);
  3730. if (str_val == NULL) {
  3731. return default_val;
  3732. }
  3733. Int32 result;
  3734. if (!ParseInt32(Message() << "The value of environment variable " << var,
  3735. str_val, &result)) {
  3736. exit(EXIT_FAILURE);
  3737. }
  3738. return result;
  3739. }
  3740. // Given the total number of shards, the shard index, and the test id,
  3741. // returns true iff the test should be run on this shard. The test id is
  3742. // some arbitrary but unique non-negative integer assigned to each test
  3743. // method. Assumes that 0 <= shard_index < total_shards.
  3744. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  3745. return (test_id % total_shards) == shard_index;
  3746. }
  3747. // Compares the name of each test with the user-specified filter to
  3748. // decide whether the test should be run, then records the result in
  3749. // each TestCase and TestInfo object.
  3750. // If shard_tests == true, further filters tests based on sharding
  3751. // variables in the environment - see
  3752. // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
  3753. // Returns the number of tests that should run.
  3754. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  3755. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  3756. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  3757. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  3758. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  3759. // num_runnable_tests are the number of tests that will
  3760. // run across all shards (i.e., match filter and are not disabled).
  3761. // num_selected_tests are the number of tests to be run on
  3762. // this shard.
  3763. int num_runnable_tests = 0;
  3764. int num_selected_tests = 0;
  3765. for (size_t i = 0; i < test_cases_.size(); i++) {
  3766. TestCase* const test_case = test_cases_[i];
  3767. const String &test_case_name = test_case->name();
  3768. test_case->set_should_run(false);
  3769. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  3770. TestInfo* const test_info = test_case->test_info_list()[j];
  3771. const String test_name(test_info->name());
  3772. // A test is disabled if test case name or test name matches
  3773. // kDisableTestFilter.
  3774. const bool is_disabled =
  3775. internal::UnitTestOptions::MatchesFilter(test_case_name,
  3776. kDisableTestFilter) ||
  3777. internal::UnitTestOptions::MatchesFilter(test_name,
  3778. kDisableTestFilter);
  3779. test_info->is_disabled_ = is_disabled;
  3780. const bool matches_filter =
  3781. internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  3782. test_name);
  3783. test_info->matches_filter_ = matches_filter;
  3784. const bool is_runnable =
  3785. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  3786. matches_filter;
  3787. const bool is_selected = is_runnable &&
  3788. (shard_tests == IGNORE_SHARDING_PROTOCOL ||
  3789. ShouldRunTestOnShard(total_shards, shard_index,
  3790. num_runnable_tests));
  3791. num_runnable_tests += is_runnable;
  3792. num_selected_tests += is_selected;
  3793. test_info->should_run_ = is_selected;
  3794. test_case->set_should_run(test_case->should_run() || is_selected);
  3795. }
  3796. }
  3797. return num_selected_tests;
  3798. }
  3799. // Prints the names of the tests matching the user-specified filter flag.
  3800. void UnitTestImpl::ListTestsMatchingFilter() {
  3801. for (size_t i = 0; i < test_cases_.size(); i++) {
  3802. const TestCase* const test_case = test_cases_[i];
  3803. bool printed_test_case_name = false;
  3804. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  3805. const TestInfo* const test_info =
  3806. test_case->test_info_list()[j];
  3807. if (test_info->matches_filter_) {
  3808. if (!printed_test_case_name) {
  3809. printed_test_case_name = true;
  3810. printf("%s.\n", test_case->name());
  3811. }
  3812. printf(" %s\n", test_info->name());
  3813. }
  3814. }
  3815. }
  3816. fflush(stdout);
  3817. }
  3818. // Sets the OS stack trace getter.
  3819. //
  3820. // Does nothing if the input and the current OS stack trace getter are
  3821. // the same; otherwise, deletes the old getter and makes the input the
  3822. // current getter.
  3823. void UnitTestImpl::set_os_stack_trace_getter(
  3824. OsStackTraceGetterInterface* getter) {
  3825. if (os_stack_trace_getter_ != getter) {
  3826. delete os_stack_trace_getter_;
  3827. os_stack_trace_getter_ = getter;
  3828. }
  3829. }
  3830. // Returns the current OS stack trace getter if it is not NULL;
  3831. // otherwise, creates an OsStackTraceGetter, makes it the current
  3832. // getter, and returns it.
  3833. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  3834. if (os_stack_trace_getter_ == NULL) {
  3835. os_stack_trace_getter_ = new OsStackTraceGetter;
  3836. }
  3837. return os_stack_trace_getter_;
  3838. }
  3839. // Returns the TestResult for the test that's currently running, or
  3840. // the TestResult for the ad hoc test if no test is running.
  3841. TestResult* UnitTestImpl::current_test_result() {
  3842. return current_test_info_ ?
  3843. &(current_test_info_->result_) : &ad_hoc_test_result_;
  3844. }
  3845. // Shuffles all test cases, and the tests within each test case,
  3846. // making sure that death tests are still run first.
  3847. void UnitTestImpl::ShuffleTests() {
  3848. // Shuffles the death test cases.
  3849. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  3850. // Shuffles the non-death test cases.
  3851. ShuffleRange(random(), last_death_test_case_ + 1,
  3852. static_cast<int>(test_cases_.size()), &test_case_indices_);
  3853. // Shuffles the tests inside each test case.
  3854. for (size_t i = 0; i < test_cases_.size(); i++) {
  3855. test_cases_[i]->ShuffleTests(random());
  3856. }
  3857. }
  3858. // Restores the test cases and tests to their order before the first shuffle.
  3859. void UnitTestImpl::UnshuffleTests() {
  3860. for (size_t i = 0; i < test_cases_.size(); i++) {
  3861. // Unshuffles the tests in each test case.
  3862. test_cases_[i]->UnshuffleTests();
  3863. // Resets the index of each test case.
  3864. test_case_indices_[i] = static_cast<int>(i);
  3865. }
  3866. }
  3867. // Returns the current OS stack trace as a String.
  3868. //
  3869. // The maximum number of stack frames to be included is specified by
  3870. // the gtest_stack_trace_depth flag. The skip_count parameter
  3871. // specifies the number of top frames to be skipped, which doesn't
  3872. // count against the number of frames to be included.
  3873. //
  3874. // For example, if Foo() calls Bar(), which in turn calls
  3875. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  3876. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  3877. String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  3878. int skip_count) {
  3879. // We pass skip_count + 1 to skip this wrapper function in addition
  3880. // to what the user really wants to skip.
  3881. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  3882. }
  3883. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  3884. // suppress unreachable code warnings.
  3885. namespace {
  3886. class ClassUniqueToAlwaysTrue {};
  3887. }
  3888. bool IsTrue(bool condition) { return condition; }
  3889. bool AlwaysTrue() {
  3890. #if GTEST_HAS_EXCEPTIONS
  3891. // This condition is always false so AlwaysTrue() never actually throws,
  3892. // but it makes the compiler think that it may throw.
  3893. if (IsTrue(false))
  3894. throw ClassUniqueToAlwaysTrue();
  3895. #endif // GTEST_HAS_EXCEPTIONS
  3896. return true;
  3897. }
  3898. // If *pstr starts with the given prefix, modifies *pstr to be right
  3899. // past the prefix and returns true; otherwise leaves *pstr unchanged
  3900. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  3901. bool SkipPrefix(const char* prefix, const char** pstr) {
  3902. const size_t prefix_len = strlen(prefix);
  3903. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  3904. *pstr += prefix_len;
  3905. return true;
  3906. }
  3907. return false;
  3908. }
  3909. // Parses a string as a command line flag. The string should have
  3910. // the format "--flag=value". When def_optional is true, the "=value"
  3911. // part can be omitted.
  3912. //
  3913. // Returns the value of the flag, or NULL if the parsing failed.
  3914. const char* ParseFlagValue(const char* str,
  3915. const char* flag,
  3916. bool def_optional) {
  3917. // str and flag must not be NULL.
  3918. if (str == NULL || flag == NULL) return NULL;
  3919. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  3920. const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
  3921. const size_t flag_len = flag_str.length();
  3922. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  3923. // Skips the flag name.
  3924. const char* flag_end = str + flag_len;
  3925. // When def_optional is true, it's OK to not have a "=value" part.
  3926. if (def_optional && (flag_end[0] == '\0')) {
  3927. return flag_end;
  3928. }
  3929. // If def_optional is true and there are more characters after the
  3930. // flag name, or if def_optional is false, there must be a '=' after
  3931. // the flag name.
  3932. if (flag_end[0] != '=') return NULL;
  3933. // Returns the string after "=".
  3934. return flag_end + 1;
  3935. }
  3936. // Parses a string for a bool flag, in the form of either
  3937. // "--flag=value" or "--flag".
  3938. //
  3939. // In the former case, the value is taken as true as long as it does
  3940. // not start with '0', 'f', or 'F'.
  3941. //
  3942. // In the latter case, the value is taken as true.
  3943. //
  3944. // On success, stores the value of the flag in *value, and returns
  3945. // true. On failure, returns false without changing *value.
  3946. bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  3947. // Gets the value of the flag as a string.
  3948. const char* const value_str = ParseFlagValue(str, flag, true);
  3949. // Aborts if the parsing failed.
  3950. if (value_str == NULL) return false;
  3951. // Converts the string value to a bool.
  3952. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  3953. return true;
  3954. }
  3955. // Parses a string for an Int32 flag, in the form of
  3956. // "--flag=value".
  3957. //
  3958. // On success, stores the value of the flag in *value, and returns
  3959. // true. On failure, returns false without changing *value.
  3960. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  3961. // Gets the value of the flag as a string.
  3962. const char* const value_str = ParseFlagValue(str, flag, false);
  3963. // Aborts if the parsing failed.
  3964. if (value_str == NULL) return false;
  3965. // Sets *value to the value of the flag.
  3966. return ParseInt32(Message() << "The value of flag --" << flag,
  3967. value_str, value);
  3968. }
  3969. // Parses a string for a string flag, in the form of
  3970. // "--flag=value".
  3971. //
  3972. // On success, stores the value of the flag in *value, and returns
  3973. // true. On failure, returns false without changing *value.
  3974. bool ParseStringFlag(const char* str, const char* flag, String* value) {
  3975. // Gets the value of the flag as a string.
  3976. const char* const value_str = ParseFlagValue(str, flag, false);
  3977. // Aborts if the parsing failed.
  3978. if (value_str == NULL) return false;
  3979. // Sets *value to the value of the flag.
  3980. *value = value_str;
  3981. return true;
  3982. }
  3983. // Determines whether a string has a prefix that Google Test uses for its
  3984. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  3985. // If Google Test detects that a command line flag has its prefix but is not
  3986. // recognized, it will print its help message. Flags starting with
  3987. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  3988. // internal flags and do not trigger the help message.
  3989. static bool HasGoogleTestFlagPrefix(const char* str) {
  3990. return (SkipPrefix("--", &str) ||
  3991. SkipPrefix("-", &str) ||
  3992. SkipPrefix("/", &str)) &&
  3993. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  3994. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  3995. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  3996. }
  3997. // Prints a string containing code-encoded text. The following escape
  3998. // sequences can be used in the string to control the text color:
  3999. //
  4000. // @@ prints a single '@' character.
  4001. // @R changes the color to red.
  4002. // @G changes the color to green.
  4003. // @Y changes the color to yellow.
  4004. // @D changes to the default terminal text color.
  4005. //
  4006. // TODO([email protected]): Write tests for this once we add stdout
  4007. // capturing to Google Test.
  4008. static void PrintColorEncoded(const char* str) {
  4009. GTestColor color = COLOR_DEFAULT; // The current color.
  4010. // Conceptually, we split the string into segments divided by escape
  4011. // sequences. Then we print one segment at a time. At the end of
  4012. // each iteration, the str pointer advances to the beginning of the
  4013. // next segment.
  4014. for (;;) {
  4015. const char* p = strchr(str, '@');
  4016. if (p == NULL) {
  4017. ColoredPrintf(color, "%s", str);
  4018. return;
  4019. }
  4020. ColoredPrintf(color, "%s", String(str, p - str).c_str());
  4021. const char ch = p[1];
  4022. str = p + 2;
  4023. if (ch == '@') {
  4024. ColoredPrintf(color, "@");
  4025. } else if (ch == 'D') {
  4026. color = COLOR_DEFAULT;
  4027. } else if (ch == 'R') {
  4028. color = COLOR_RED;
  4029. } else if (ch == 'G') {
  4030. color = COLOR_GREEN;
  4031. } else if (ch == 'Y') {
  4032. color = COLOR_YELLOW;
  4033. } else {
  4034. --str;
  4035. }
  4036. }
  4037. }
  4038. static const char kColorEncodedHelpMessage[] =
  4039. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  4040. "following command line flags to control its behavior:\n"
  4041. "\n"
  4042. "Test Selection:\n"
  4043. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  4044. " List the names of all tests instead of running them. The name of\n"
  4045. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  4046. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  4047. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  4048. " Run only the tests whose name matches one of the positive patterns but\n"
  4049. " none of the negative patterns. '?' matches any single character; '*'\n"
  4050. " matches any substring; ':' separates two patterns.\n"
  4051. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  4052. " Run all disabled tests too.\n"
  4053. "\n"
  4054. "Test Execution:\n"
  4055. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  4056. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  4057. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  4058. " Randomize tests' orders on every iteration.\n"
  4059. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  4060. " Random number seed to use for shuffling test orders (between 1 and\n"
  4061. " 99999, or 0 to use a seed based on the current time).\n"
  4062. "\n"
  4063. "Test Output:\n"
  4064. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  4065. " Enable/disable colored output. The default is @Gauto@D.\n"
  4066. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  4067. " Don't print the elapsed time of each test.\n"
  4068. " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
  4069. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  4070. " Generate an XML report in the given directory or with the given file\n"
  4071. " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  4072. #if GTEST_CAN_STREAM_RESULTS_
  4073. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  4074. " Stream test results to the given server.\n"
  4075. #endif // GTEST_CAN_STREAM_RESULTS_
  4076. "\n"
  4077. "Assertion Behavior:\n"
  4078. #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  4079. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  4080. " Set the default death test style.\n"
  4081. #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  4082. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  4083. " Turn assertion failures into debugger break-points.\n"
  4084. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  4085. " Turn assertion failures into C++ exceptions.\n"
  4086. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  4087. " Do not report exceptions as test failures. Instead, allow them\n"
  4088. " to crash the program or throw a pop-up (on Windows).\n"
  4089. "\n"
  4090. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  4091. "the corresponding\n"
  4092. "environment variable of a flag (all letters in upper-case). For example, to\n"
  4093. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  4094. "color=no@D or set\n"
  4095. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  4096. "\n"
  4097. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  4098. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  4099. "(not one in your own code or tests), please report it to\n"
  4100. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  4101. // Parses the command line for Google Test flags, without initializing
  4102. // other parts of Google Test. The type parameter CharType can be
  4103. // instantiated to either char or wchar_t.
  4104. template <typename CharType>
  4105. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  4106. for (int i = 1; i < *argc; i++) {
  4107. const String arg_string = StreamableToString(argv[i]);
  4108. const char* const arg = arg_string.c_str();
  4109. using internal::ParseBoolFlag;
  4110. using internal::ParseInt32Flag;
  4111. using internal::ParseStringFlag;
  4112. // Do we see a Google Test flag?
  4113. if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  4114. &GTEST_FLAG(also_run_disabled_tests)) ||
  4115. ParseBoolFlag(arg, kBreakOnFailureFlag,
  4116. &GTEST_FLAG(break_on_failure)) ||
  4117. ParseBoolFlag(arg, kCatchExceptionsFlag,
  4118. &GTEST_FLAG(catch_exceptions)) ||
  4119. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  4120. ParseStringFlag(arg, kDeathTestStyleFlag,
  4121. &GTEST_FLAG(death_test_style)) ||
  4122. ParseBoolFlag(arg, kDeathTestUseFork,
  4123. &GTEST_FLAG(death_test_use_fork)) ||
  4124. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  4125. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  4126. &GTEST_FLAG(internal_run_death_test)) ||
  4127. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  4128. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  4129. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  4130. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  4131. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  4132. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  4133. ParseInt32Flag(arg, kStackTraceDepthFlag,
  4134. &GTEST_FLAG(stack_trace_depth)) ||
  4135. ParseStringFlag(arg, kStreamResultToFlag,
  4136. &GTEST_FLAG(stream_result_to)) ||
  4137. ParseBoolFlag(arg, kThrowOnFailureFlag,
  4138. &GTEST_FLAG(throw_on_failure))
  4139. ) {
  4140. // Yes. Shift the remainder of the argv list left by one. Note
  4141. // that argv has (*argc + 1) elements, the last one always being
  4142. // NULL. The following loop moves the trailing NULL element as
  4143. // well.
  4144. for (int j = i; j != *argc; j++) {
  4145. argv[j] = argv[j + 1];
  4146. }
  4147. // Decrements the argument count.
  4148. (*argc)--;
  4149. // We also need to decrement the iterator as we just removed
  4150. // an element.
  4151. i--;
  4152. } else if (arg_string == "--help" || arg_string == "-h" ||
  4153. arg_string == "-?" || arg_string == "/?" ||
  4154. HasGoogleTestFlagPrefix(arg)) {
  4155. // Both help flag and unrecognized Google Test flags (excluding
  4156. // internal ones) trigger help display.
  4157. g_help_flag = true;
  4158. }
  4159. }
  4160. if (g_help_flag) {
  4161. // We print the help here instead of in RUN_ALL_TESTS(), as the
  4162. // latter may not be called at all if the user is using Google
  4163. // Test with another testing framework.
  4164. PrintColorEncoded(kColorEncodedHelpMessage);
  4165. }
  4166. }
  4167. // Parses the command line for Google Test flags, without initializing
  4168. // other parts of Google Test.
  4169. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  4170. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  4171. }
  4172. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  4173. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  4174. }
  4175. // The internal implementation of InitGoogleTest().
  4176. //
  4177. // The type parameter CharType can be instantiated to either char or
  4178. // wchar_t.
  4179. template <typename CharType>
  4180. void InitGoogleTestImpl(int* argc, CharType** argv) {
  4181. g_init_gtest_count++;
  4182. // We don't want to run the initialization code twice.
  4183. if (g_init_gtest_count != 1) return;
  4184. if (*argc <= 0) return;
  4185. internal::g_executable_path = internal::StreamableToString(argv[0]);
  4186. #if GTEST_HAS_DEATH_TEST
  4187. g_argvs.clear();
  4188. for (int i = 0; i != *argc; i++) {
  4189. g_argvs.push_back(StreamableToString(argv[i]));
  4190. }
  4191. #endif // GTEST_HAS_DEATH_TEST
  4192. ParseGoogleTestFlagsOnly(argc, argv);
  4193. GetUnitTestImpl()->PostFlagParsingInit();
  4194. }
  4195. } // namespace internal
  4196. // Initializes Google Test. This must be called before calling
  4197. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  4198. // flags that Google Test recognizes. Whenever a Google Test flag is
  4199. // seen, it is removed from argv, and *argc is decremented.
  4200. //
  4201. // No value is returned. Instead, the Google Test flag variables are
  4202. // updated.
  4203. //
  4204. // Calling the function for the second time has no user-visible effect.
  4205. void InitGoogleTest(int* argc, char** argv) {
  4206. internal::InitGoogleTestImpl(argc, argv);
  4207. }
  4208. // This overloaded version can be used in Windows programs compiled in
  4209. // UNICODE mode.
  4210. void InitGoogleTest(int* argc, wchar_t** argv) {
  4211. internal::InitGoogleTestImpl(argc, argv);
  4212. }
  4213. } // namespace testing