tcltest-2.5.7.tm 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584
  1. # tcltest.tcl --
  2. #
  3. # This file contains support code for the Tcl test suite. It
  4. # defines the tcltest namespace and finds and defines the output
  5. # directory, constraints available, output and error channels,
  6. # etc. used by Tcl tests. See the tcltest man page for more
  7. # details.
  8. #
  9. # This design was based on the Tcl testing approach designed and
  10. # initially implemented by Mary Ann May-Pumphrey of Sun
  11. # Microsystems.
  12. #
  13. # Copyright © 1994-1997 Sun Microsystems, Inc.
  14. # Copyright © 1998-1999 Scriptics Corporation.
  15. # Copyright © 2000 Ajuba Solutions
  16. # Contributions from Don Porter, NIST, 2002. (not subject to US copyright)
  17. # All rights reserved.
  18. namespace eval tcltest {
  19. # When the version number changes, be sure to update the pkgIndex.tcl file,
  20. # and the install directory in the Makefiles. When the minor version
  21. # changes (new feature) be sure to update the man page as well.
  22. variable Version 2.5.7
  23. # Compatibility support for dumb variables defined in tcltest 1
  24. # Do not use these. Call [package require] and [info patchlevel]
  25. # yourself. You don't need tcltest to wrap it for you.
  26. variable version [package require Tcl 8.5-]
  27. variable patchLevel [info patchlevel]
  28. # Detect if we can use code points >= \U10000
  29. variable fullutf [package vsatisfies $version 8.7-]
  30. ##### Export the public tcltest procs; several categories
  31. #
  32. # Export the main functional commands that do useful things
  33. namespace export cleanupTests loadTestedCommands makeDirectory \
  34. makeFile removeDirectory removeFile runAllTests test
  35. # Export configuration commands that control the functional commands
  36. namespace export configure customMatch errorChannel interpreter \
  37. outputChannel testConstraint
  38. # Export commands that are duplication (candidates for deprecation)
  39. if {!$fullutf} {
  40. namespace export bytestring ;# dups [encoding convertfrom identity]
  41. }
  42. namespace export debug ;# [configure -debug]
  43. namespace export errorFile ;# [configure -errfile]
  44. namespace export limitConstraints ;# [configure -limitconstraints]
  45. namespace export loadFile ;# [configure -loadfile]
  46. namespace export loadScript ;# [configure -load]
  47. namespace export match ;# [configure -match]
  48. namespace export matchFiles ;# [configure -file]
  49. namespace export matchDirectories ;# [configure -relateddir]
  50. namespace export normalizeMsg ;# application of [customMatch]
  51. namespace export normalizePath ;# [file normalize] (8.4)
  52. namespace export outputFile ;# [configure -outfile]
  53. namespace export preserveCore ;# [configure -preservecore]
  54. namespace export singleProcess ;# [configure -singleproc]
  55. namespace export skip ;# [configure -skip]
  56. namespace export skipFiles ;# [configure -notfile]
  57. namespace export skipDirectories ;# [configure -asidefromdir]
  58. namespace export temporaryDirectory ;# [configure -tmpdir]
  59. namespace export testsDirectory ;# [configure -testdir]
  60. namespace export verbose ;# [configure -verbose]
  61. namespace export viewFile ;# binary encoding [read]
  62. namespace export workingDirectory ;# [cd] [pwd]
  63. # Export deprecated commands for tcltest 1 compatibility
  64. namespace export getMatchingFiles mainThread restoreState saveState \
  65. threadReap
  66. # tcltest::normalizePath --
  67. #
  68. # This procedure resolves any symlinks in the path thus creating
  69. # a path without internal redirection. It assumes that the
  70. # incoming path is absolute.
  71. #
  72. # Arguments
  73. # pathVar - name of variable containing path to modify.
  74. #
  75. # Results
  76. # The path is modified in place.
  77. #
  78. # Side Effects:
  79. # None.
  80. #
  81. proc normalizePath {pathVar} {
  82. upvar 1 $pathVar path
  83. set oldpwd [pwd]
  84. catch {cd $path}
  85. set path [pwd]
  86. cd $oldpwd
  87. return $path
  88. }
  89. ##### Verification commands used to test values of variables and options
  90. #
  91. # Verification command that accepts everything
  92. proc AcceptAll {value} {
  93. return $value
  94. }
  95. # Verification command that accepts valid Tcl lists
  96. proc AcceptList { list } {
  97. return [lrange $list 0 end]
  98. }
  99. # Verification command that accepts a glob pattern
  100. proc AcceptPattern { pattern } {
  101. return [AcceptAll $pattern]
  102. }
  103. # Verification command that accepts integers
  104. proc AcceptInteger { level } {
  105. return [incr level 0]
  106. }
  107. # Verification command that accepts boolean values
  108. proc AcceptBoolean { boolean } {
  109. return [expr {$boolean && $boolean}]
  110. }
  111. # Verification command that accepts (syntactically) valid Tcl scripts
  112. proc AcceptScript { script } {
  113. if {![info complete $script]} {
  114. return -code error "invalid Tcl script: $script"
  115. }
  116. return $script
  117. }
  118. # Verification command that accepts (converts to) absolute pathnames
  119. proc AcceptAbsolutePath { path } {
  120. return [file join [pwd] $path]
  121. }
  122. # Verification command that accepts existing readable directories
  123. proc AcceptReadable { path } {
  124. if {![file readable $path]} {
  125. return -code error "\"$path\" is not readable"
  126. }
  127. return $path
  128. }
  129. proc AcceptDirectory { directory } {
  130. set directory [AcceptAbsolutePath $directory]
  131. if {![file exists $directory]} {
  132. return -code error "\"$directory\" does not exist"
  133. }
  134. if {![file isdir $directory]} {
  135. return -code error "\"$directory\" is not a directory"
  136. }
  137. return [AcceptReadable $directory]
  138. }
  139. ##### Initialize internal arrays of tcltest, but only if the caller
  140. # has not already preinitialized them. This is done to support
  141. # compatibility with older tests that directly access internals
  142. # rather than go through command interfaces.
  143. #
  144. proc ArrayDefault {varName value} {
  145. variable $varName
  146. if {[array exists $varName]} {
  147. return
  148. }
  149. if {[info exists $varName]} {
  150. # Preinitialized value is a scalar: Destroy it!
  151. unset $varName
  152. }
  153. array set $varName $value
  154. }
  155. # save the original environment so that it can be restored later
  156. ArrayDefault originalEnv [array get ::env]
  157. # initialize numTests array to keep track of the number of tests
  158. # that pass, fail, and are skipped.
  159. ArrayDefault numTests [list Total 0 Passed 0 Skipped 0 Failed 0]
  160. # createdNewFiles will store test files as indices and the list of
  161. # files (that should not have been) left behind by the test files
  162. # as values.
  163. ArrayDefault createdNewFiles {}
  164. # initialize skippedBecause array to keep track of constraints that
  165. # kept tests from running; a constraint name of "userSpecifiedSkip"
  166. # means that the test appeared on the list of tests that matched the
  167. # -skip value given to the flag; "userSpecifiedNonMatch" means that
  168. # the test didn't match the argument given to the -match flag; both
  169. # of these constraints are counted only if tcltest::debug is set to
  170. # true.
  171. ArrayDefault skippedBecause {}
  172. # initialize the testConstraints array to keep track of valid
  173. # predefined constraints (see the explanation for the
  174. # InitConstraints proc for more details).
  175. ArrayDefault testConstraints {}
  176. ##### Initialize internal variables of tcltest, but only if the caller
  177. # has not already preinitialized them. This is done to support
  178. # compatibility with older tests that directly access internals
  179. # rather than go through command interfaces.
  180. #
  181. proc Default {varName value {verify AcceptAll}} {
  182. variable $varName
  183. if {![info exists $varName]} {
  184. variable $varName [$verify $value]
  185. } else {
  186. variable $varName [$verify [set $varName]]
  187. }
  188. }
  189. # Save any arguments that we might want to pass through to other
  190. # programs. This is used by the -args flag.
  191. # FINDUSER
  192. Default parameters {}
  193. # Count the number of files tested (0 if runAllTests wasn't called).
  194. # runAllTests will set testSingleFile to false, so stats will
  195. # not be printed until runAllTests calls the cleanupTests proc.
  196. # The currentFailure var stores the boolean value of whether the
  197. # current test file has had any failures. The failFiles list
  198. # stores the names of test files that had failures.
  199. Default numTestFiles 0 AcceptInteger
  200. Default testSingleFile true AcceptBoolean
  201. Default currentFailure false AcceptBoolean
  202. Default failFiles {} AcceptList
  203. # Tests should remove all files they create. The test suite will
  204. # check the current working dir for files created by the tests.
  205. # filesMade keeps track of such files created using the makeFile and
  206. # makeDirectory procedures. filesExisted stores the names of
  207. # preexisting files.
  208. #
  209. # Note that $filesExisted lists only those files that exist in
  210. # the original [temporaryDirectory].
  211. Default filesMade {} AcceptList
  212. Default filesExisted {} AcceptList
  213. proc FillFilesExisted {} {
  214. variable filesExisted
  215. # Save the names of files that already exist in the scratch directory.
  216. foreach file [glob -nocomplain -directory [temporaryDirectory] *] {
  217. lappend filesExisted [file tail $file]
  218. }
  219. # After successful filling, turn this into a no-op.
  220. proc FillFilesExisted args {}
  221. }
  222. # Kept only for compatibility
  223. Default constraintsSpecified {} AcceptList
  224. trace add variable constraintsSpecified read [namespace code {
  225. set constraintsSpecified [array names testConstraints] ;#}]
  226. # tests that use threads need to know which is the main thread
  227. Default mainThread 1
  228. variable mainThread
  229. if {[info commands thread::id] ne {}} {
  230. set mainThread [thread::id]
  231. } elseif {[info commands testthread] ne {}} {
  232. set mainThread [testthread id]
  233. }
  234. # Set workingDirectory to [pwd]. The default output directory for
  235. # Tcl tests is the working directory. Whenever this value changes
  236. # change to that directory.
  237. variable workingDirectory
  238. trace add variable workingDirectory write \
  239. [namespace code {cd $workingDirectory ;#}]
  240. Default workingDirectory [pwd] AcceptAbsolutePath
  241. proc workingDirectory { {dir ""} } {
  242. variable workingDirectory
  243. if {[llength [info level 0]] == 1} {
  244. return $workingDirectory
  245. }
  246. set workingDirectory [AcceptAbsolutePath $dir]
  247. }
  248. # Set the location of the execuatble
  249. Default tcltest [info nameofexecutable]
  250. trace add variable tcltest write [namespace code {testConstraint stdio \
  251. [eval [ConstraintInitializer stdio]] ;#}]
  252. # save the platform information so it can be restored later
  253. Default originalTclPlatform [array get ::tcl_platform]
  254. # If a core file exists, save its modification time.
  255. if {[file exists [file join [workingDirectory] core]]} {
  256. Default coreModTime \
  257. [file mtime [file join [workingDirectory] core]]
  258. }
  259. # stdout and stderr buffers for use when we want to store them
  260. Default outData {}
  261. Default errData {}
  262. # keep track of test level for nested test commands
  263. variable testLevel 0
  264. # the variables and procedures that existed when saveState was called are
  265. # stored in a variable of the same name
  266. Default saveState {}
  267. # Internationalization support -- used in [SetIso8859_1_Locale] and
  268. # [RestoreLocale]. Those commands are used in cmdIL.test.
  269. if {![info exists [namespace current]::isoLocale]} {
  270. variable isoLocale fr
  271. switch -- $::tcl_platform(platform) {
  272. "unix" {
  273. # Try some 'known' values for some platforms:
  274. switch -exact -- $::tcl_platform(os) {
  275. "FreeBSD" {
  276. set isoLocale fr_FR.ISO_8859-1
  277. }
  278. HP-UX {
  279. set isoLocale fr_FR.iso88591
  280. }
  281. Linux -
  282. IRIX {
  283. set isoLocale fr
  284. }
  285. default {
  286. # Works on SunOS 4 and Solaris, and maybe
  287. # others... Define it to something else on your
  288. # system if you want to test those.
  289. set isoLocale iso_8859_1
  290. }
  291. }
  292. }
  293. "windows" {
  294. set isoLocale French
  295. }
  296. }
  297. }
  298. variable ChannelsWeOpened; array set ChannelsWeOpened {}
  299. # output goes to stdout by default
  300. Default outputChannel stdout
  301. proc outputChannel { {filename ""} } {
  302. variable outputChannel
  303. variable ChannelsWeOpened
  304. variable fullutf
  305. # This is very subtle and tricky, so let me try to explain.
  306. # (Hopefully this longer comment will be clear when I come
  307. # back in a few months, unlike its predecessor :) )
  308. #
  309. # The [outputChannel] command (and underlying variable) have to
  310. # be kept in sync with the [configure -outfile] configuration
  311. # option ( and underlying variable Option(-outfile) ). This is
  312. # accomplished with a write trace on Option(-outfile) that will
  313. # update [outputChannel] whenever a new value is written. That
  314. # much is easy.
  315. #
  316. # The trick is that in order to maintain compatibility with
  317. # version 1 of tcltest, we must allow every configuration option
  318. # to get its initial value from command line arguments. This is
  319. # accomplished by setting initial read traces on all the
  320. # configuration options to parse the command line option the first
  321. # time they are read. These traces are cancelled whenever the
  322. # program itself calls [configure].
  323. #
  324. # OK, then so to support tcltest 1 compatibility, it seems we want
  325. # to get the return from [outputFile] to trigger the read traces,
  326. # just in case.
  327. #
  328. # BUT! A little known feature of Tcl variable traces is that
  329. # traces are disabled during the handling of other traces. So,
  330. # if we trigger read traces on Option(-outfile) and that triggers
  331. # command line parsing which turns around and sets an initial
  332. # value for Option(-outfile) -- <whew!> -- the write trace that
  333. # would keep [outputChannel] in sync with that new initial value
  334. # would not fire!
  335. #
  336. # SO, finally, as a workaround, instead of triggering read traces
  337. # by invoking [outputFile], we instead trigger the same set of
  338. # read traces by invoking [debug]. Any command that reads a
  339. # configuration option would do. [debug] is just a handy one.
  340. # The end result is that we support tcltest 1 compatibility and
  341. # keep outputChannel and -outfile in sync in all cases.
  342. debug
  343. if {[llength [info level 0]] == 1} {
  344. return $outputChannel
  345. }
  346. if {[info exists ChannelsWeOpened($outputChannel)]} {
  347. close $outputChannel
  348. unset ChannelsWeOpened($outputChannel)
  349. }
  350. switch -exact -- $filename {
  351. stderr -
  352. stdout {
  353. set outputChannel $filename
  354. }
  355. default {
  356. set outputChannel [open $filename a]
  357. if {$fullutf} {
  358. fconfigure $outputChannel -profile tcl8 -encoding utf-8
  359. }
  360. set ChannelsWeOpened($outputChannel) 1
  361. # If we created the file in [temporaryDirectory], then
  362. # [cleanupTests] will delete it, unless we claim it was
  363. # already there.
  364. set outdir [normalizePath [file dirname \
  365. [file join [pwd] $filename]]]
  366. if {$outdir eq [temporaryDirectory]} {
  367. variable filesExisted
  368. FillFilesExisted
  369. set filename [file tail $filename]
  370. if {$filename ni $filesExisted} {
  371. lappend filesExisted $filename
  372. }
  373. }
  374. }
  375. }
  376. return $outputChannel
  377. }
  378. # errors go to stderr by default
  379. Default errorChannel stderr
  380. proc errorChannel { {filename ""} } {
  381. variable errorChannel
  382. variable ChannelsWeOpened
  383. variable fullutf
  384. # This is subtle and tricky. See the comment above in
  385. # [outputChannel] for a detailed explanation.
  386. debug
  387. if {[llength [info level 0]] == 1} {
  388. return $errorChannel
  389. }
  390. if {[info exists ChannelsWeOpened($errorChannel)]} {
  391. close $errorChannel
  392. unset ChannelsWeOpened($errorChannel)
  393. }
  394. switch -exact -- $filename {
  395. stderr -
  396. stdout {
  397. set errorChannel $filename
  398. }
  399. default {
  400. set errorChannel [open $filename a]
  401. if {$fullutf} {
  402. fconfigure $errorChannel -profile tcl8 -encoding utf-8
  403. }
  404. set ChannelsWeOpened($errorChannel) 1
  405. # If we created the file in [temporaryDirectory], then
  406. # [cleanupTests] will delete it, unless we claim it was
  407. # already there.
  408. set outdir [normalizePath [file dirname \
  409. [file join [pwd] $filename]]]
  410. if {$outdir eq [temporaryDirectory]} {
  411. variable filesExisted
  412. FillFilesExisted
  413. set filename [file tail $filename]
  414. if {$filename ni $filesExisted} {
  415. lappend filesExisted $filename
  416. }
  417. }
  418. }
  419. }
  420. return $errorChannel
  421. }
  422. ##### Set up the configurable options
  423. #
  424. # The configurable options of the package
  425. variable Option; array set Option {}
  426. # Usage strings for those options
  427. variable Usage; array set Usage {}
  428. # Verification commands for those options
  429. variable Verify; array set Verify {}
  430. # Initialize the default values of the configurable options that are
  431. # historically associated with an exported variable. If that variable
  432. # is already set, support compatibility by accepting its preset value.
  433. # Use [trace] to establish ongoing connection between the deprecated
  434. # exported variable and the modern option kept as a true internal var.
  435. # Also set up usage string and value testing for the option.
  436. proc Option {option value usage {verify AcceptAll} {varName {}}} {
  437. variable Option
  438. variable Verify
  439. variable Usage
  440. variable OptionControlledVariables
  441. variable DefaultValue
  442. set Usage($option) $usage
  443. set Verify($option) $verify
  444. set DefaultValue($option) $value
  445. if {[catch {$verify $value} msg]} {
  446. return -code error $msg
  447. } else {
  448. set Option($option) $msg
  449. }
  450. if {[string length $varName]} {
  451. variable $varName
  452. if {[info exists $varName]} {
  453. if {[catch {$verify [set $varName]} msg]} {
  454. return -code error $msg
  455. } else {
  456. set Option($option) $msg
  457. }
  458. unset $varName
  459. }
  460. namespace eval [namespace current] \
  461. [list upvar 0 Option($option) $varName]
  462. # Workaround for Bug (now Feature Request) 572889. Grrrr....
  463. # Track all the variables tied to options
  464. lappend OptionControlledVariables $varName
  465. # Later, set auto-configure read traces on all
  466. # of them, since a single trace on Option does not work.
  467. proc $varName {{value {}}} [subst -nocommands {
  468. if {[llength [info level 0]] == 2} {
  469. Configure $option [set value]
  470. }
  471. return [Configure $option]
  472. }]
  473. }
  474. }
  475. proc MatchingOption {option} {
  476. variable Option
  477. set match [array names Option $option*]
  478. switch -- [llength $match] {
  479. 0 {
  480. set sorted [lsort [array names Option]]
  481. set values [join [lrange $sorted 0 end-1] ", "]
  482. append values ", or [lindex $sorted end]"
  483. return -code error "unknown option $option: should be\
  484. one of $values"
  485. }
  486. 1 {
  487. return [lindex $match 0]
  488. }
  489. default {
  490. # Exact match trumps ambiguity
  491. if {$option in $match} {
  492. return $option
  493. }
  494. set values [join [lrange $match 0 end-1] ", "]
  495. append values ", or [lindex $match end]"
  496. return -code error "ambiguous option $option:\
  497. could match $values"
  498. }
  499. }
  500. }
  501. proc EstablishAutoConfigureTraces {} {
  502. variable OptionControlledVariables
  503. foreach varName [concat $OptionControlledVariables Option] {
  504. variable $varName
  505. trace add variable $varName read [namespace code {
  506. ProcessCmdLineArgs ;#}]
  507. }
  508. }
  509. proc RemoveAutoConfigureTraces {} {
  510. variable OptionControlledVariables
  511. foreach varName [concat $OptionControlledVariables Option] {
  512. variable $varName
  513. foreach pair [trace info variable $varName] {
  514. lassign $pair op cmd
  515. if {($op eq "read") &&
  516. [string match *ProcessCmdLineArgs* $cmd]} {
  517. trace remove variable $varName $op $cmd
  518. }
  519. }
  520. }
  521. # Once the traces are removed, this can become a no-op
  522. proc RemoveAutoConfigureTraces {} {}
  523. }
  524. proc Configure args {
  525. variable Option
  526. variable Verify
  527. set n [llength $args]
  528. if {$n == 0} {
  529. return [lsort [array names Option]]
  530. }
  531. if {$n == 1} {
  532. if {[catch {MatchingOption [lindex $args 0]} option]} {
  533. return -code error $option
  534. }
  535. return $Option($option)
  536. }
  537. while {[llength $args] > 1} {
  538. if {[catch {MatchingOption [lindex $args 0]} option]} {
  539. return -code error $option
  540. }
  541. if {[catch {$Verify($option) [lindex $args 1]} value]} {
  542. return -code error "invalid $option\
  543. value \"[lindex $args 1]\": $value"
  544. }
  545. set Option($option) $value
  546. set args [lrange $args 2 end]
  547. }
  548. if {[llength $args]} {
  549. if {[catch {MatchingOption [lindex $args 0]} option]} {
  550. return -code error $option
  551. }
  552. return -code error "missing value for option $option"
  553. }
  554. }
  555. proc configure args {
  556. if {[llength $args] > 1} {
  557. RemoveAutoConfigureTraces
  558. }
  559. set code [catch {Configure {*}$args} msg]
  560. return -code $code $msg
  561. }
  562. proc AcceptVerbose { level } {
  563. set level [AcceptList $level]
  564. set levelMap {
  565. l list
  566. p pass
  567. b body
  568. s skip
  569. t start
  570. e error
  571. l line
  572. m msec
  573. u usec
  574. }
  575. set levelRegexp "^([join [dict values $levelMap] |])\$"
  576. if {[llength $level] == 1} {
  577. if {![regexp $levelRegexp $level]} {
  578. # translate single characters abbreviations to expanded list
  579. set level [string map $levelMap [split $level {}]]
  580. }
  581. }
  582. set valid [list]
  583. foreach v $level {
  584. if {[regexp $levelRegexp $v]} {
  585. lappend valid $v
  586. }
  587. }
  588. return $valid
  589. }
  590. proc IsVerbose {level} {
  591. variable Option
  592. return [expr {$level in $Option(-verbose)}]
  593. }
  594. # Default verbosity is to show bodies of failed tests
  595. Option -verbose {body error} {
  596. Takes any combination of the values 'p', 's', 'b', 't', 'e' and 'l'.
  597. Test suite will display all passed tests if 'p' is specified, all
  598. skipped tests if 's' is specified, the bodies of failed tests if
  599. 'b' is specified, and when tests start if 't' is specified.
  600. ErrorInfo is displayed if 'e' is specified. Source file line
  601. information of failed tests is displayed if 'l' is specified.
  602. } AcceptVerbose verbose
  603. # Match and skip patterns default to the empty list, except for
  604. # matchFiles, which defaults to all .test files in the
  605. # testsDirectory and matchDirectories, which defaults to all
  606. # directories.
  607. Option -match * {
  608. Run all tests within the specified files that match one of the
  609. list of glob patterns given.
  610. } AcceptList match
  611. Option -skip {} {
  612. Skip all tests within the specified tests (via -match) and files
  613. that match one of the list of glob patterns given.
  614. } AcceptList skip
  615. Option -file *.test {
  616. Run tests in all test files that match the glob pattern given.
  617. } AcceptPattern matchFiles
  618. # By default, skip files that appear to be SCCS lock files.
  619. Option -notfile l.*.test {
  620. Skip all test files that match the glob pattern given.
  621. } AcceptPattern skipFiles
  622. Option -relateddir * {
  623. Run tests in directories that match the glob pattern given.
  624. } AcceptPattern matchDirectories
  625. Option -asidefromdir {} {
  626. Skip tests in directories that match the glob pattern given.
  627. } AcceptPattern skipDirectories
  628. # By default, don't save core files
  629. Option -preservecore 0 {
  630. If 2, save any core files produced during testing in the directory
  631. specified by -tmpdir. If 1, notify the user if core files are
  632. created.
  633. } AcceptInteger preserveCore
  634. # debug output doesn't get printed by default; debug level 1 spits
  635. # up only the tests that were skipped because they didn't match or
  636. # were specifically skipped. A debug level of 2 would spit up the
  637. # tcltest variables and flags provided; a debug level of 3 causes
  638. # some additional output regarding operations of the test harness.
  639. # The tcltest package currently implements only up to debug level 3.
  640. Option -debug 0 {
  641. Internal debug level
  642. } AcceptInteger debug
  643. proc SetSelectedConstraints args {
  644. variable Option
  645. foreach c $Option(-constraints) {
  646. testConstraint $c 1
  647. }
  648. }
  649. Option -constraints {} {
  650. Do not skip the listed constraints listed in -constraints.
  651. } AcceptList
  652. trace add variable Option(-constraints) write \
  653. [namespace code {SetSelectedConstraints ;#}]
  654. # Don't run only the "-constraint" specified tests by default
  655. proc ClearUnselectedConstraints args {
  656. variable Option
  657. variable testConstraints
  658. if {!$Option(-limitconstraints)} {return}
  659. foreach c [array names testConstraints] {
  660. if {$c ni $Option(-constraints)} {
  661. testConstraint $c 0
  662. }
  663. }
  664. }
  665. Option -limitconstraints 0 {
  666. whether to run only tests with the constraints
  667. } AcceptBoolean limitConstraints
  668. trace add variable Option(-limitconstraints) write \
  669. [namespace code {ClearUnselectedConstraints ;#}]
  670. # A test application has to know how to load the tested commands
  671. # into the interpreter.
  672. Option -load {} {
  673. Specifies the script to load the tested commands.
  674. } AcceptScript loadScript
  675. # Default is to run each test file in a separate process
  676. Option -singleproc 0 {
  677. whether to run all tests in one process
  678. } AcceptBoolean singleProcess
  679. proc AcceptTemporaryDirectory { directory } {
  680. set directory [AcceptAbsolutePath $directory]
  681. if {![file exists $directory]} {
  682. file mkdir $directory
  683. }
  684. set directory [AcceptDirectory $directory]
  685. if {![file writable $directory]} {
  686. if {[workingDirectory] eq $directory} {
  687. # Special exception: accept the default value
  688. # even if the directory is not writable
  689. return $directory
  690. }
  691. return -code error "\"$directory\" is not writable"
  692. }
  693. return $directory
  694. }
  695. # Directory where files should be created
  696. Option -tmpdir [workingDirectory] {
  697. Save temporary files in the specified directory.
  698. } AcceptTemporaryDirectory temporaryDirectory
  699. trace add variable Option(-tmpdir) write \
  700. [namespace code {normalizePath Option(-tmpdir) ;#}]
  701. # Tests should not rely on the current working directory.
  702. # Files that are part of the test suite should be accessed relative
  703. # to [testsDirectory]
  704. Option -testdir [workingDirectory] {
  705. Search tests in the specified directory.
  706. } AcceptDirectory testsDirectory
  707. trace add variable Option(-testdir) write \
  708. [namespace code {normalizePath Option(-testdir) ;#}]
  709. proc AcceptLoadFile { file } {
  710. if {$file eq {}} {return $file}
  711. set file [file join [temporaryDirectory] $file]
  712. return [AcceptReadable $file]
  713. }
  714. proc ReadLoadScript {args} {
  715. variable Option
  716. variable fullutf
  717. if {$Option(-loadfile) eq {}} {return}
  718. set tmp [open $Option(-loadfile) r]
  719. if {$fullutf} {
  720. fconfigure $tmp -profile tcl8 -encoding utf-8
  721. }
  722. loadScript [read $tmp]
  723. close $tmp
  724. }
  725. Option -loadfile {} {
  726. Read the script to load the tested commands from the specified file.
  727. } AcceptLoadFile loadFile
  728. trace add variable Option(-loadfile) write [namespace code ReadLoadScript]
  729. proc AcceptOutFile { file } {
  730. if {[string equal stderr $file]} {return $file}
  731. if {[string equal stdout $file]} {return $file}
  732. return [file join [temporaryDirectory] $file]
  733. }
  734. # output goes to stdout by default
  735. Option -outfile stdout {
  736. Send output from test runs to the specified file.
  737. } AcceptOutFile outputFile
  738. trace add variable Option(-outfile) write \
  739. [namespace code {outputChannel $Option(-outfile) ;#}]
  740. # errors go to stderr by default
  741. Option -errfile stderr {
  742. Send errors from test runs to the specified file.
  743. } AcceptOutFile errorFile
  744. trace add variable Option(-errfile) write \
  745. [namespace code {errorChannel $Option(-errfile) ;#}]
  746. proc loadIntoChildInterpreter {child args} {
  747. variable Version
  748. interp eval $child [package ifneeded tcltest $Version]
  749. interp eval $child "tcltest::configure {*}{$args}"
  750. interp alias $child ::tcltest::ReportToParent \
  751. {} ::tcltest::ReportedFromChild
  752. }
  753. proc ReportedFromChild {total passed skipped failed because newfiles} {
  754. variable numTests
  755. variable skippedBecause
  756. variable createdNewFiles
  757. incr numTests(Total) $total
  758. incr numTests(Passed) $passed
  759. incr numTests(Skipped) $skipped
  760. incr numTests(Failed) $failed
  761. foreach {constraint count} $because {
  762. incr skippedBecause($constraint) $count
  763. }
  764. foreach {testfile created} $newfiles {
  765. lappend createdNewFiles($testfile) {*}$created
  766. }
  767. return
  768. }
  769. }
  770. #####################################################################
  771. # tcltest::Debug* --
  772. #
  773. # Internal helper procedures to write out debug information
  774. # dependent on the chosen level. A test shell may override
  775. # them, f.e. to redirect the output into a different
  776. # channel, or even into a GUI.
  777. # tcltest::DebugPuts --
  778. #
  779. # Prints the specified string if the current debug level is
  780. # higher than the provided level argument.
  781. #
  782. # Arguments:
  783. # level The lowest debug level triggering the output
  784. # string The string to print out.
  785. #
  786. # Results:
  787. # Prints the string. Nothing else is allowed.
  788. #
  789. # Side Effects:
  790. # None.
  791. #
  792. proc tcltest::DebugPuts {level string} {
  793. variable debug
  794. if {$debug >= $level} {
  795. puts $string
  796. }
  797. return
  798. }
  799. # tcltest::DebugPArray --
  800. #
  801. # Prints the contents of the specified array if the current
  802. # debug level is higher than the provided level argument
  803. #
  804. # Arguments:
  805. # level The lowest debug level triggering the output
  806. # arrayvar The name of the array to print out.
  807. #
  808. # Results:
  809. # Prints the contents of the array. Nothing else is allowed.
  810. #
  811. # Side Effects:
  812. # None.
  813. #
  814. proc tcltest::DebugPArray {level arrayvar} {
  815. variable debug
  816. if {$debug >= $level} {
  817. catch {upvar 1 $arrayvar $arrayvar}
  818. parray $arrayvar
  819. }
  820. return
  821. }
  822. # Define our own [parray] in ::tcltest that will inherit use of the [puts]
  823. # defined in ::tcltest. NOTE: Ought to construct with [info args] and
  824. # [info default], but can't be bothered now. If [parray] changes, then
  825. # this will need changing too.
  826. auto_load ::parray
  827. proc tcltest::parray {a {pattern *}} [info body ::parray]
  828. # tcltest::DebugDo --
  829. #
  830. # Executes the script if the current debug level is greater than
  831. # the provided level argument
  832. #
  833. # Arguments:
  834. # level The lowest debug level triggering the execution.
  835. # script The tcl script executed upon a debug level high enough.
  836. #
  837. # Results:
  838. # Arbitrary side effects, dependent on the executed script.
  839. #
  840. # Side Effects:
  841. # None.
  842. #
  843. proc tcltest::DebugDo {level script} {
  844. variable debug
  845. if {$debug >= $level} {
  846. uplevel 1 $script
  847. }
  848. return
  849. }
  850. #####################################################################
  851. proc tcltest::Warn {msg} {
  852. puts [outputChannel] "WARNING: $msg"
  853. }
  854. # tcltest::mainThread
  855. #
  856. # Accessor command for tcltest variable mainThread.
  857. #
  858. proc tcltest::mainThread { {new ""} } {
  859. variable mainThread
  860. if {[llength [info level 0]] == 1} {
  861. return $mainThread
  862. }
  863. set mainThread $new
  864. }
  865. # tcltest::testConstraint --
  866. #
  867. # sets a test constraint to a value; to do multiple constraints,
  868. # call this proc multiple times. also returns the value of the
  869. # named constraint if no value was supplied.
  870. #
  871. # Arguments:
  872. # constraint - name of the constraint
  873. # value - new value for constraint (should be boolean) - if not
  874. # supplied, this is a query
  875. #
  876. # Results:
  877. # content of tcltest::testConstraints($constraint)
  878. #
  879. # Side effects:
  880. # none
  881. proc tcltest::testConstraint {constraint {value ""}} {
  882. variable testConstraints
  883. variable Option
  884. DebugPuts 3 "entering testConstraint $constraint $value"
  885. if {[llength [info level 0]] == 2} {
  886. return $testConstraints($constraint)
  887. }
  888. # Check for boolean values
  889. if {[catch {expr {$value && 1}} msg]} {
  890. return -code error $msg
  891. }
  892. if {[limitConstraints] && ($constraint ni $Option(-constraints))} {
  893. set value 0
  894. }
  895. set testConstraints($constraint) $value
  896. }
  897. # tcltest::interpreter --
  898. #
  899. # the interpreter name stored in tcltest::tcltest
  900. #
  901. # Arguments:
  902. # executable name
  903. #
  904. # Results:
  905. # content of tcltest::tcltest
  906. #
  907. # Side effects:
  908. # None.
  909. proc tcltest::interpreter { {interp ""} } {
  910. variable tcltest
  911. if {[llength [info level 0]] == 1} {
  912. return $tcltest
  913. }
  914. set tcltest $interp
  915. }
  916. #####################################################################
  917. # tcltest::AddToSkippedBecause --
  918. #
  919. # Increments the variable used to track how many tests were
  920. # skipped because of a particular constraint.
  921. #
  922. # Arguments:
  923. # constraint The name of the constraint to be modified
  924. #
  925. # Results:
  926. # Modifies tcltest::skippedBecause; sets the variable to 1 if
  927. # didn't previously exist - otherwise, it just increments it.
  928. #
  929. # Side effects:
  930. # None.
  931. proc tcltest::AddToSkippedBecause { constraint {value 1}} {
  932. # add the constraint to the list of constraints that kept tests
  933. # from running
  934. variable skippedBecause
  935. if {[info exists skippedBecause($constraint)]} {
  936. incr skippedBecause($constraint) $value
  937. } else {
  938. set skippedBecause($constraint) $value
  939. }
  940. return
  941. }
  942. # tcltest::PrintError --
  943. #
  944. # Prints errors to tcltest::errorChannel and then flushes that
  945. # channel, making sure that all messages are < 80 characters per
  946. # line.
  947. #
  948. # Arguments:
  949. # errorMsg String containing the error to be printed
  950. #
  951. # Results:
  952. # None.
  953. #
  954. # Side effects:
  955. # None.
  956. proc tcltest::PrintError {errorMsg} {
  957. set InitialMessage "Error: "
  958. set InitialMsgLen [string length $InitialMessage]
  959. puts -nonewline [errorChannel] $InitialMessage
  960. # Keep track of where the end of the string is.
  961. set endingIndex [string length $errorMsg]
  962. if {$endingIndex < (80 - $InitialMsgLen)} {
  963. puts [errorChannel] $errorMsg
  964. } else {
  965. # Print up to 80 characters on the first line, including the
  966. # InitialMessage.
  967. set beginningIndex [string last " " [string range $errorMsg 0 \
  968. [expr {80 - $InitialMsgLen}]]]
  969. puts [errorChannel] [string range $errorMsg 0 $beginningIndex]
  970. while {$beginningIndex ne "end"} {
  971. puts -nonewline [errorChannel] \
  972. [string repeat " " $InitialMsgLen]
  973. if {($endingIndex - $beginningIndex)
  974. < (80 - $InitialMsgLen)} {
  975. puts [errorChannel] [string trim \
  976. [string range $errorMsg $beginningIndex end]]
  977. break
  978. } else {
  979. set newEndingIndex [expr {[string last " " \
  980. [string range $errorMsg $beginningIndex \
  981. [expr {$beginningIndex
  982. + (80 - $InitialMsgLen)}]
  983. ]] + $beginningIndex}]
  984. if {($newEndingIndex <= 0)
  985. || ($newEndingIndex <= $beginningIndex)} {
  986. set newEndingIndex end
  987. }
  988. puts [errorChannel] [string trim \
  989. [string range $errorMsg \
  990. $beginningIndex $newEndingIndex]]
  991. set beginningIndex $newEndingIndex
  992. }
  993. }
  994. }
  995. flush [errorChannel]
  996. return
  997. }
  998. # tcltest::SafeFetch --
  999. #
  1000. # The following trace procedure makes it so that we can safely
  1001. # refer to non-existent members of the testConstraints array
  1002. # without causing an error. Instead, reading a non-existent
  1003. # member will return 0. This is necessary because tests are
  1004. # allowed to use constraint "X" without ensuring that
  1005. # testConstraints("X") is defined.
  1006. #
  1007. # Arguments:
  1008. # n1 - name of the array (testConstraints)
  1009. # n2 - array key value (constraint name)
  1010. # op - operation performed on testConstraints (generally r)
  1011. #
  1012. # Results:
  1013. # none
  1014. #
  1015. # Side effects:
  1016. # sets testConstraints($n2) to 0 if it's referenced but never
  1017. # before used
  1018. proc tcltest::SafeFetch {n1 n2 op} {
  1019. variable testConstraints
  1020. DebugPuts 3 "entering SafeFetch $n1 $n2 $op"
  1021. if {$n2 eq {}} {return}
  1022. if {![info exists testConstraints($n2)]} {
  1023. if {[catch {testConstraint $n2 [eval [ConstraintInitializer $n2]]}]} {
  1024. testConstraint $n2 0
  1025. }
  1026. }
  1027. }
  1028. # tcltest::Asciify --
  1029. #
  1030. # Transforms the passed string to contain only printable ascii characters.
  1031. # Useful for printing to terminals. Non-printables are mapped to
  1032. # \x, \u or \U sequences, except \n.
  1033. #
  1034. # Arguments:
  1035. # s - string to transform
  1036. #
  1037. # Results:
  1038. # The transformed strings
  1039. #
  1040. # Side effects:
  1041. # None.
  1042. proc tcltest::Asciify {s} {
  1043. set print ""
  1044. foreach c [split $s ""] {
  1045. if {(($c < "\x7F") && [string is print $c]) || ($c eq "\n")} {
  1046. append print $c
  1047. } elseif {$c < "\u0100"} {
  1048. append print \\x[format %02X [scan $c %c]]
  1049. } elseif {$c > "\uFFFF"} {
  1050. append print \\U[format %08X [scan $c %c]]
  1051. } else {
  1052. append print \\u[format %04X [scan $c %c]]
  1053. }
  1054. }
  1055. return $print
  1056. }
  1057. # tcltest::ConstraintInitializer --
  1058. #
  1059. # Get or set a script that when evaluated in the tcltest namespace
  1060. # will return a boolean value with which to initialize the
  1061. # associated constraint.
  1062. #
  1063. # Arguments:
  1064. # constraint - name of the constraint initialized by the script
  1065. # script - the initializer script
  1066. #
  1067. # Results
  1068. # boolean value of the constraint - enabled or disabled
  1069. #
  1070. # Side effects:
  1071. # Constraint is initialized for future reference by [test]
  1072. proc tcltest::ConstraintInitializer {constraint {script ""}} {
  1073. variable ConstraintInitializer
  1074. DebugPuts 3 "entering ConstraintInitializer $constraint $script"
  1075. if {[llength [info level 0]] == 2} {
  1076. return $ConstraintInitializer($constraint)
  1077. }
  1078. # Check for boolean values
  1079. if {![info complete $script]} {
  1080. return -code error "ConstraintInitializer must be complete script"
  1081. }
  1082. set ConstraintInitializer($constraint) $script
  1083. }
  1084. # tcltest::InitConstraints --
  1085. #
  1086. # Call all registered constraint initializers to force initialization
  1087. # of all known constraints.
  1088. # See the tcltest man page for the list of built-in constraints defined
  1089. # in this procedure.
  1090. #
  1091. # Arguments:
  1092. # none
  1093. #
  1094. # Results:
  1095. # The testConstraints array is reset to have an index for each
  1096. # built-in test constraint.
  1097. #
  1098. # Side Effects:
  1099. # None.
  1100. #
  1101. proc tcltest::InitConstraints {} {
  1102. variable ConstraintInitializer
  1103. initConstraintsHook
  1104. foreach constraint [array names ConstraintInitializer] {
  1105. testConstraint $constraint
  1106. }
  1107. }
  1108. proc tcltest::DefineConstraintInitializers {} {
  1109. ConstraintInitializer singleTestInterp {singleProcess}
  1110. # All the 'pc' constraints are here for backward compatibility and
  1111. # are not documented. They have been replaced with equivalent 'win'
  1112. # constraints.
  1113. ConstraintInitializer unixOnly \
  1114. {string equal $::tcl_platform(platform) unix}
  1115. ConstraintInitializer macOnly \
  1116. {string equal $::tcl_platform(platform) macintosh}
  1117. ConstraintInitializer pcOnly \
  1118. {string equal $::tcl_platform(platform) windows}
  1119. ConstraintInitializer winOnly \
  1120. {string equal $::tcl_platform(platform) windows}
  1121. ConstraintInitializer unix {testConstraint unixOnly}
  1122. ConstraintInitializer mac {testConstraint macOnly}
  1123. ConstraintInitializer pc {testConstraint pcOnly}
  1124. ConstraintInitializer win {testConstraint winOnly}
  1125. ConstraintInitializer unixOrPc \
  1126. {expr {[testConstraint unix] || [testConstraint pc]}}
  1127. ConstraintInitializer macOrPc \
  1128. {expr {[testConstraint mac] || [testConstraint pc]}}
  1129. ConstraintInitializer unixOrWin \
  1130. {expr {[testConstraint unix] || [testConstraint win]}}
  1131. ConstraintInitializer macOrWin \
  1132. {expr {[testConstraint mac] || [testConstraint win]}}
  1133. ConstraintInitializer macOrUnix \
  1134. {expr {[testConstraint mac] || [testConstraint unix]}}
  1135. ConstraintInitializer nt {string equal $::tcl_platform(os) "Windows NT"}
  1136. ConstraintInitializer 95 {string equal $::tcl_platform(os) "Windows 95"}
  1137. ConstraintInitializer 98 {string equal $::tcl_platform(os) "Windows 98"}
  1138. # The following Constraints switches are used to mark tests that
  1139. # should work, but have been temporarily disabled on certain
  1140. # platforms because they don't and we haven't gotten around to
  1141. # fixing the underlying problem.
  1142. ConstraintInitializer tempNotPc {expr {![testConstraint pc]}}
  1143. ConstraintInitializer tempNotWin {expr {![testConstraint win]}}
  1144. ConstraintInitializer tempNotMac {expr {![testConstraint mac]}}
  1145. ConstraintInitializer tempNotUnix {expr {![testConstraint unix]}}
  1146. # The following Constraints switches are used to mark tests that
  1147. # crash on certain platforms, so that they can be reactivated again
  1148. # when the underlying problem is fixed.
  1149. ConstraintInitializer pcCrash {expr {![testConstraint pc]}}
  1150. ConstraintInitializer winCrash {expr {![testConstraint win]}}
  1151. ConstraintInitializer macCrash {expr {![testConstraint mac]}}
  1152. ConstraintInitializer unixCrash {expr {![testConstraint unix]}}
  1153. # Skip empty tests
  1154. ConstraintInitializer emptyTest {format 0}
  1155. # By default, tests that expose known bugs are skipped.
  1156. ConstraintInitializer knownBug {format 0}
  1157. # By default, non-portable tests are skipped.
  1158. ConstraintInitializer nonPortable {format 0}
  1159. # Some tests require user interaction.
  1160. ConstraintInitializer userInteraction {format 0}
  1161. # Some tests must be skipped if the interpreter is not in
  1162. # interactive mode
  1163. ConstraintInitializer interactive \
  1164. {expr {[info exists ::tcl_interactive] && $::tcl_interactive}}
  1165. # Some tests can only be run if the installation came from a CD
  1166. # image instead of a web image. Some tests must be skipped if you
  1167. # are running as root on Unix. Other tests can only be run if you
  1168. # are running as root on Unix.
  1169. ConstraintInitializer root {expr \
  1170. {($::tcl_platform(platform) eq "unix") &&
  1171. ($::tcl_platform(user) in {root {}})}}
  1172. ConstraintInitializer notRoot {expr {![testConstraint root]}}
  1173. # Set nonBlockFiles constraint: 1 means this platform supports
  1174. # setting files into nonblocking mode.
  1175. ConstraintInitializer nonBlockFiles {
  1176. set code [expr {[catch {set f [open defs r]}]
  1177. || [catch {fconfigure $f -blocking off}]}]
  1178. catch {close $f}
  1179. set code
  1180. }
  1181. # Set asyncPipeClose constraint: 1 means this platform supports
  1182. # async flush and async close on a pipe.
  1183. #
  1184. # Test for SCO Unix - cannot run async flushing tests because a
  1185. # potential problem with select is apparently interfering.
  1186. # (Mark Diekhans).
  1187. ConstraintInitializer asyncPipeClose {expr {
  1188. !([string equal unix $::tcl_platform(platform)]
  1189. && ([catch {exec uname -X | fgrep {Release = 3.2v}}] == 0))}}
  1190. # Test to see if we have a broken version of sprintf with respect
  1191. # to the "e" format of floating-point numbers.
  1192. ConstraintInitializer eformat {string equal [format %g 5e-5] 5e-05}
  1193. # Test to see if execed commands such as cat, echo, rm and so forth
  1194. # are present on this machine.
  1195. ConstraintInitializer unixExecs {
  1196. set code 1
  1197. if {$::tcl_platform(platform) eq "macintosh"} {
  1198. set code 0
  1199. }
  1200. if {$::tcl_platform(platform) eq "windows"} {
  1201. if {[catch {
  1202. set file _tcl_test_remove_me.txt
  1203. makeFile {hello} $file
  1204. }]} {
  1205. set code 0
  1206. } elseif {
  1207. [catch {exec cat $file}] ||
  1208. [catch {exec echo hello}] ||
  1209. [catch {exec sh -c echo hello}] ||
  1210. [catch {exec wc $file}] ||
  1211. [catch {exec sleep 1}] ||
  1212. [catch {exec echo abc > $file}] ||
  1213. [catch {exec chmod 644 $file}] ||
  1214. [catch {exec rm $file}] ||
  1215. [llength [auto_execok mkdir]] == 0 ||
  1216. [llength [auto_execok fgrep]] == 0 ||
  1217. [llength [auto_execok grep]] == 0 ||
  1218. [llength [auto_execok ps]] == 0
  1219. } {
  1220. set code 0
  1221. }
  1222. removeFile $file
  1223. }
  1224. set code
  1225. }
  1226. ConstraintInitializer stdio {
  1227. variable fullutf
  1228. set code 0
  1229. if {![catch {set f [open "|[list [interpreter]]" w]}]} {
  1230. if {$fullutf} {
  1231. fconfigure $f -profile tcl8 -encoding utf-8
  1232. }
  1233. if {![catch {puts $f exit}]} {
  1234. if {![catch {close $f}]} {
  1235. set code 1
  1236. }
  1237. }
  1238. }
  1239. set code
  1240. }
  1241. # Deliberately call socket with the wrong number of arguments. The
  1242. # error message you get will indicate whether sockets are available
  1243. # on this system.
  1244. ConstraintInitializer socket {
  1245. catch {socket} msg
  1246. string compare $msg "sockets are not available on this system"
  1247. }
  1248. # Check for internationalization
  1249. ConstraintInitializer hasIsoLocale {
  1250. if {[llength [info commands testlocale]] == 0} {
  1251. set code 0
  1252. } else {
  1253. set code [string length [SetIso8859_1_Locale]]
  1254. RestoreLocale
  1255. }
  1256. set code
  1257. }
  1258. }
  1259. #####################################################################
  1260. # Usage and command line arguments processing.
  1261. # tcltest::PrintUsageInfo
  1262. #
  1263. # Prints out the usage information for package tcltest. This can
  1264. # be customized with the redefinition of [PrintUsageInfoHook].
  1265. #
  1266. # Arguments:
  1267. # none
  1268. #
  1269. # Results:
  1270. # none
  1271. #
  1272. # Side Effects:
  1273. # none
  1274. proc tcltest::PrintUsageInfo {} {
  1275. puts [Usage]
  1276. PrintUsageInfoHook
  1277. }
  1278. proc tcltest::Usage { {option ""} } {
  1279. variable Usage
  1280. variable Verify
  1281. if {[llength [info level 0]] == 1} {
  1282. set msg "Usage: [file tail [info nameofexecutable]] script "
  1283. append msg "?-help? ?flag value? ... \n"
  1284. append msg "Available flags (and valid input values) are:"
  1285. set max 0
  1286. set allOpts [concat -help [Configure]]
  1287. foreach opt $allOpts {
  1288. set foo [Usage $opt]
  1289. lassign $foo x type($opt) usage($opt)
  1290. set line($opt) " $opt $type($opt) "
  1291. set length($opt) [string length $line($opt)]
  1292. if {$length($opt) > $max} {set max $length($opt)}
  1293. }
  1294. set rest [expr {72 - $max}]
  1295. foreach opt $allOpts {
  1296. append msg \n$line($opt)
  1297. append msg [string repeat " " [expr {$max - $length($opt)}]]
  1298. set u [string trim $usage($opt)]
  1299. catch {append u " (default: \[[Configure $opt]])"}
  1300. regsub -all {\s*\n\s*} $u " " u
  1301. while {[string length $u] > $rest} {
  1302. set break [string wordstart $u $rest]
  1303. if {$break == 0} {
  1304. set break [string wordend $u 0]
  1305. }
  1306. append msg [string range $u 0 [expr {$break - 1}]]
  1307. set u [string trim [string range $u $break end]]
  1308. append msg \n[string repeat " " $max]
  1309. }
  1310. append msg $u
  1311. }
  1312. return $msg\n
  1313. } elseif {$option eq "-help"} {
  1314. return [list -help "" "Display this usage information."]
  1315. } else {
  1316. set type [lindex [info args $Verify($option)] 0]
  1317. return [list $option $type $Usage($option)]
  1318. }
  1319. }
  1320. # tcltest::ProcessFlags --
  1321. #
  1322. # process command line arguments supplied in the flagArray - this
  1323. # is called by processCmdLineArgs. Modifies tcltest variables
  1324. # according to the content of the flagArray.
  1325. #
  1326. # Arguments:
  1327. # flagArray - array containing name/value pairs of flags
  1328. #
  1329. # Results:
  1330. # sets tcltest variables according to their values as defined by
  1331. # flagArray
  1332. #
  1333. # Side effects:
  1334. # None.
  1335. proc tcltest::ProcessFlags {flagArray} {
  1336. # Process -help first
  1337. if {"-help" in $flagArray} {
  1338. PrintUsageInfo
  1339. exit 1
  1340. }
  1341. if {[llength $flagArray] == 0} {
  1342. RemoveAutoConfigureTraces
  1343. } else {
  1344. set args $flagArray
  1345. while {[llength $args] > 1 && [catch {configure {*}$args} msg]} {
  1346. # Something went wrong parsing $args for tcltest options
  1347. # Check whether the problem is "unknown option"
  1348. if {[regexp {^unknown option (\S+):} $msg -> option]} {
  1349. # Could be this is an option the Hook knows about
  1350. set moreOptions [processCmdLineArgsAddFlagsHook]
  1351. if {$option ni $moreOptions} {
  1352. # Nope. Report the error, including additional options,
  1353. # but keep going
  1354. if {[llength $moreOptions]} {
  1355. append msg ", "
  1356. append msg [join [lrange $moreOptions 0 end-1] ", "]
  1357. append msg "or [lindex $moreOptions end]"
  1358. }
  1359. Warn $msg
  1360. }
  1361. } else {
  1362. # error is something other than "unknown option"
  1363. # notify user of the error; and exit
  1364. puts [errorChannel] $msg
  1365. exit 1
  1366. }
  1367. # To recover, find that unknown option and remove up to it.
  1368. # then retry
  1369. while {[lindex $args 0] ne $option} {
  1370. set args [lrange $args 2 end]
  1371. }
  1372. set args [lrange $args 2 end]
  1373. }
  1374. if {[llength $args] == 1} {
  1375. puts [errorChannel] \
  1376. "missing value for option [lindex $args 0]"
  1377. exit 1
  1378. }
  1379. }
  1380. # Call the hook
  1381. catch {
  1382. array set flag $flagArray
  1383. processCmdLineArgsHook [array get flag]
  1384. }
  1385. return
  1386. }
  1387. # tcltest::ProcessCmdLineArgs --
  1388. #
  1389. # This procedure must be run after constraint initialization is
  1390. # set up (by [DefineConstraintInitializers]) because some constraints
  1391. # can be overridden.
  1392. #
  1393. # Perform configuration according to the command-line options.
  1394. #
  1395. # Arguments:
  1396. # none
  1397. #
  1398. # Results:
  1399. # Sets the above-named variables in the tcltest namespace.
  1400. #
  1401. # Side Effects:
  1402. # None.
  1403. #
  1404. proc tcltest::ProcessCmdLineArgs {} {
  1405. variable originalEnv
  1406. variable testConstraints
  1407. # The "argv" var doesn't exist in some cases, so use {}.
  1408. if {![info exists ::argv]} {
  1409. ProcessFlags {}
  1410. } else {
  1411. ProcessFlags $::argv
  1412. }
  1413. # Spit out everything you know if we're at a debug level 2 or
  1414. # greater
  1415. DebugPuts 2 "Flags passed into tcltest:"
  1416. if {[info exists ::env(TCLTEST_OPTIONS)]} {
  1417. DebugPuts 2 \
  1418. " ::env(TCLTEST_OPTIONS): $::env(TCLTEST_OPTIONS)"
  1419. }
  1420. if {[info exists ::argv]} {
  1421. DebugPuts 2 " argv: $::argv"
  1422. }
  1423. DebugPuts 2 "tcltest::debug = [debug]"
  1424. DebugPuts 2 "tcltest::testsDirectory = [testsDirectory]"
  1425. DebugPuts 2 "tcltest::workingDirectory = [workingDirectory]"
  1426. DebugPuts 2 "tcltest::temporaryDirectory = [temporaryDirectory]"
  1427. DebugPuts 2 "tcltest::outputChannel = [outputChannel]"
  1428. DebugPuts 2 "tcltest::errorChannel = [errorChannel]"
  1429. DebugPuts 2 "Original environment (tcltest::originalEnv):"
  1430. DebugPArray 2 originalEnv
  1431. DebugPuts 2 "Constraints:"
  1432. DebugPArray 2 testConstraints
  1433. }
  1434. #####################################################################
  1435. # Code to run the tests goes here.
  1436. # tcltest::TestPuts --
  1437. #
  1438. # Used to redefine puts in test environment. Stores whatever goes
  1439. # out on stdout in tcltest::outData and stderr in errData before
  1440. # sending it on to the regular puts.
  1441. #
  1442. # Arguments:
  1443. # same as standard puts
  1444. #
  1445. # Results:
  1446. # none
  1447. #
  1448. # Side effects:
  1449. # Intercepts puts; data that would otherwise go to stdout, stderr,
  1450. # or file channels specified in outputChannel and errorChannel
  1451. # does not get sent to the normal puts function.
  1452. namespace eval tcltest::Replace {
  1453. namespace export puts
  1454. }
  1455. proc tcltest::Replace::puts {args} {
  1456. variable [namespace parent]::outData
  1457. variable [namespace parent]::errData
  1458. switch [llength $args] {
  1459. 1 {
  1460. # Only the string to be printed is specified
  1461. append outData [lindex $args 0]\n
  1462. return
  1463. # return [Puts [lindex $args 0]]
  1464. }
  1465. 2 {
  1466. # Either -nonewline or channelId has been specified
  1467. if {[lindex $args 0] eq "-nonewline"} {
  1468. append outData [lindex $args end]
  1469. return
  1470. # return [Puts -nonewline [lindex $args end]]
  1471. } else {
  1472. set channel [lindex $args 0]
  1473. set newline \n
  1474. }
  1475. }
  1476. 3 {
  1477. if {[lindex $args 0] eq "-nonewline"} {
  1478. # Both -nonewline and channelId are specified, unless
  1479. # it's an error. -nonewline is supposed to be argv[0].
  1480. set channel [lindex $args 1]
  1481. set newline ""
  1482. }
  1483. }
  1484. }
  1485. if {[info exists channel]} {
  1486. if {$channel in [list [[namespace parent]::outputChannel] stdout]} {
  1487. append outData [lindex $args end]$newline
  1488. return
  1489. } elseif {$channel in [list [[namespace parent]::errorChannel] stderr]} {
  1490. append errData [lindex $args end]$newline
  1491. return
  1492. }
  1493. }
  1494. # If we haven't returned by now, we don't know how to handle the
  1495. # input. Let puts handle it.
  1496. return [Puts {*}$args]
  1497. }
  1498. # tcltest::Eval --
  1499. #
  1500. # Evaluate the script in the test environment. If ignoreOutput is
  1501. # false, store data sent to stderr and stdout in outData and
  1502. # errData. Otherwise, ignore this output altogether.
  1503. #
  1504. # Arguments:
  1505. # script Script to evaluate
  1506. # ?ignoreOutput? Indicates whether or not to ignore output
  1507. # sent to stdout & stderr
  1508. #
  1509. # Results:
  1510. # result from running the script
  1511. #
  1512. # Side effects:
  1513. # Empties the contents of outData and errData before running a
  1514. # test if ignoreOutput is set to 0.
  1515. proc tcltest::Eval {script {ignoreOutput 1}} {
  1516. variable outData
  1517. variable errData
  1518. DebugPuts 3 "[lindex [info level 0] 0] called"
  1519. if {!$ignoreOutput} {
  1520. set outData {}
  1521. set errData {}
  1522. rename ::puts [namespace current]::Replace::Puts
  1523. namespace eval :: [list namespace import [namespace origin Replace::puts]]
  1524. namespace import Replace::puts
  1525. }
  1526. set result [uplevel 1 $script]
  1527. if {!$ignoreOutput} {
  1528. namespace forget puts
  1529. namespace eval :: namespace forget puts
  1530. rename [namespace current]::Replace::Puts ::puts
  1531. }
  1532. return $result
  1533. }
  1534. # tcltest::CompareStrings --
  1535. #
  1536. # compares the expected answer to the actual answer, depending on
  1537. # the mode provided. Mode determines whether a regexp, exact,
  1538. # glob or custom comparison is done.
  1539. #
  1540. # Arguments:
  1541. # actual - string containing the actual result
  1542. # expected - pattern to be matched against
  1543. # mode - type of comparison to be done
  1544. #
  1545. # Results:
  1546. # result of the match
  1547. #
  1548. # Side effects:
  1549. # None.
  1550. proc tcltest::CompareStrings {actual expected mode} {
  1551. variable CustomMatch
  1552. if {![info exists CustomMatch($mode)]} {
  1553. return -code error "No matching command registered for `-match $mode'"
  1554. }
  1555. set match [namespace eval :: $CustomMatch($mode) [list $expected $actual]]
  1556. if {[catch {expr {$match && $match}} result]} {
  1557. return -code error "Invalid result from `-match $mode' command: $result"
  1558. }
  1559. return $match
  1560. }
  1561. # tcltest::customMatch --
  1562. #
  1563. # registers a command to be called when a particular type of
  1564. # matching is required.
  1565. #
  1566. # Arguments:
  1567. # nickname - Keyword for the type of matching
  1568. # cmd - Incomplete command that implements that type of matching
  1569. # when completed with expected string and actual string
  1570. # and then evaluated.
  1571. #
  1572. # Results:
  1573. # None.
  1574. #
  1575. # Side effects:
  1576. # Sets the variable tcltest::CustomMatch
  1577. proc tcltest::customMatch {mode script} {
  1578. variable CustomMatch
  1579. if {![info complete $script]} {
  1580. return -code error \
  1581. "invalid customMatch script; can't evaluate after completion"
  1582. }
  1583. set CustomMatch($mode) $script
  1584. }
  1585. # tcltest::SubstArguments list
  1586. #
  1587. # This helper function takes in a list of words, then perform a
  1588. # substitution on the list as though each word in the list is a separate
  1589. # argument to the Tcl function. For example, if this function is
  1590. # invoked as:
  1591. #
  1592. # SubstArguments {$a {$a}}
  1593. #
  1594. # Then it is as though the function is invoked as:
  1595. #
  1596. # SubstArguments $a {$a}
  1597. #
  1598. # This code is adapted from Paul Duffin's function "SplitIntoWords".
  1599. # The original function can be found on:
  1600. #
  1601. # http://purl.org/thecliff/tcl/wiki/858.html
  1602. #
  1603. # Results:
  1604. # a list containing the result of the substitution
  1605. #
  1606. # Exceptions:
  1607. # An error may occur if the list containing unbalanced quote or
  1608. # unknown variable.
  1609. #
  1610. # Side Effects:
  1611. # None.
  1612. #
  1613. proc tcltest::SubstArguments {argList} {
  1614. # We need to split the argList up into tokens but cannot use list
  1615. # operations as they throw away some significant quoting, and
  1616. # [split] ignores braces as it should. Therefore what we do is
  1617. # gradually build up a string out of whitespace-separated strings.
  1618. # We cannot use [split] to split the argList into whitespace
  1619. # separated strings as it throws away the whitespace which maybe
  1620. # important so we have to do it all by hand.
  1621. set result {}
  1622. set token ""
  1623. while {[string length $argList]} {
  1624. # Look for the next word containing a quote: " { }
  1625. if {[regexp -indices {[^ \t\n]*[\"\{\}]+[^ \t\n]*} \
  1626. $argList all]} {
  1627. # Get the text leading up to this word, but not including
  1628. # this word, from the argList.
  1629. set text [string range $argList 0 \
  1630. [expr {[lindex $all 0] - 1}]]
  1631. # Get the word with the quote
  1632. set word [string range $argList \
  1633. [lindex $all 0] [lindex $all 1]]
  1634. # Remove all text up to and including the word from the
  1635. # argList.
  1636. set argList [string range $argList \
  1637. [expr {[lindex $all 1] + 1}] end]
  1638. } else {
  1639. # Take everything up to the end of the argList.
  1640. set text $argList
  1641. set word {}
  1642. set argList {}
  1643. }
  1644. if {$token ne {}} {
  1645. # If we saw a word with quote before, then there is a
  1646. # multi-word token starting with that word. In this case,
  1647. # add the text and the current word to this token.
  1648. append token $text $word
  1649. } else {
  1650. # Add the text to the result. There is no need to parse
  1651. # the text because it couldn't be a part of any multi-word
  1652. # token. Then start a new multi-word token with the word
  1653. # because we need to pass this token to the Tcl parser to
  1654. # check for balancing quotes
  1655. append result $text
  1656. set token $word
  1657. }
  1658. if { [catch {llength $token} length] == 0 && $length == 1} {
  1659. # The token is a valid list so add it to the result.
  1660. # lappend result [string trim $token]
  1661. append result \{$token\}
  1662. set token {}
  1663. }
  1664. }
  1665. # If the last token has not been added to the list then there
  1666. # is a problem.
  1667. if { [string length $token] } {
  1668. error "incomplete token \"$token\""
  1669. }
  1670. return $result
  1671. }
  1672. # tcltest::test --
  1673. #
  1674. # This procedure runs a test and prints an error message if the test
  1675. # fails. If verbose has been set, it also prints a message even if the
  1676. # test succeeds. The test will be skipped if it doesn't match the
  1677. # match variable, if it matches an element in skip, or if one of the
  1678. # elements of "constraints" turns out not to be true.
  1679. #
  1680. # If testLevel is 1, then this is a top level test, and we record
  1681. # pass/fail information; otherwise, this information is not logged and
  1682. # is not added to running totals.
  1683. #
  1684. # Attributes:
  1685. # Only description is a required attribute. All others are optional.
  1686. # Default values are indicated.
  1687. #
  1688. # constraints - A list of one or more keywords, each of which
  1689. # must be the name of an element in the array
  1690. # "testConstraints". If any of these elements is
  1691. # zero, the test is skipped. This attribute is
  1692. # optional; default is {}
  1693. # body - Script to run to carry out the test. It must
  1694. # return a result that can be checked for
  1695. # correctness. This attribute is optional;
  1696. # default is {}
  1697. # result - Expected result from script. This attribute is
  1698. # optional; default is {}.
  1699. # output - Expected output sent to stdout. This attribute
  1700. # is optional; default is {}.
  1701. # errorOutput - Expected output sent to stderr. This attribute
  1702. # is optional; default is {}.
  1703. # returnCodes - Expected return codes. This attribute is
  1704. # optional; default is {0 2}.
  1705. # errorCode - Expected error code. This attribute is
  1706. # optional; default is {*}. It is a glob pattern.
  1707. # If given, returnCodes defaults to {1}.
  1708. # setup - Code to run before $script (above). This
  1709. # attribute is optional; default is {}.
  1710. # cleanup - Code to run after $script (above). This
  1711. # attribute is optional; default is {}.
  1712. # match - specifies type of matching to do on result,
  1713. # output, errorOutput; this must be a string
  1714. # previously registered by a call to [customMatch].
  1715. # The strings exact, glob, and regexp are preregistered
  1716. # by the tcltest package. Default value is exact.
  1717. #
  1718. # Arguments:
  1719. # name - Name of test, in the form foo-1.2.
  1720. # description - Short textual description of the test, to
  1721. # help humans understand what it does.
  1722. #
  1723. # Results:
  1724. # None.
  1725. #
  1726. # Side effects:
  1727. # Just about anything is possible depending on the test.
  1728. #
  1729. proc tcltest::test {name description args} {
  1730. global tcl_platform
  1731. variable testLevel
  1732. variable coreModTime
  1733. variable fullutf
  1734. DebugPuts 3 "test $name $args"
  1735. DebugDo 1 {
  1736. variable TestNames
  1737. catch {
  1738. puts "test name '$name' re-used; prior use in $TestNames($name)"
  1739. }
  1740. set TestNames($name) [info script]
  1741. }
  1742. FillFilesExisted
  1743. incr testLevel
  1744. # Predefine everything to null except output and errorOutput. We
  1745. # determine whether or not to trap output based on whether or not
  1746. # these variables (output & errorOutput) are defined.
  1747. lassign {} constraints setup cleanup body result returnCodes errorCode match
  1748. # Set the default match mode
  1749. set match exact
  1750. # Set the default match values for return codes (0 is the standard
  1751. # expected return value if everything went well; 2 represents
  1752. # 'return' being used in the test script).
  1753. set returnCodes [list 0 2]
  1754. # Set the default error code pattern
  1755. set errorCode "*"
  1756. # The old test format can't have a 3rd argument (constraints or
  1757. # script) that starts with '-'.
  1758. if {[string match -* [lindex $args 0]] || ([llength $args] <= 1)} {
  1759. if {[llength $args] == 1} {
  1760. set list [SubstArguments [lindex $args 0]]
  1761. foreach {element value} $list {
  1762. set testAttributes($element) $value
  1763. }
  1764. foreach item {constraints match setup body cleanup \
  1765. result returnCodes errorCode output errorOutput} {
  1766. if {[info exists testAttributes(-$item)]} {
  1767. set testAttributes(-$item) [uplevel 1 \
  1768. ::concat $testAttributes(-$item)]
  1769. }
  1770. }
  1771. } else {
  1772. array set testAttributes $args
  1773. }
  1774. set validFlags {-setup -cleanup -body -result -returnCodes \
  1775. -errorCode -match -output -errorOutput -constraints}
  1776. foreach flag [array names testAttributes] {
  1777. if {$flag ni $validFlags} {
  1778. incr testLevel -1
  1779. set sorted [lsort $validFlags]
  1780. set options [join [lrange $sorted 0 end-1] ", "]
  1781. append options ", or [lindex $sorted end]"
  1782. return -code error "bad option \"$flag\": must be $options"
  1783. }
  1784. }
  1785. # store whatever the user gave us
  1786. foreach item [array names testAttributes] {
  1787. set [string trimleft $item "-"] $testAttributes($item)
  1788. }
  1789. # Check the values supplied for -match
  1790. variable CustomMatch
  1791. if {$match ni [array names CustomMatch]} {
  1792. incr testLevel -1
  1793. set sorted [lsort [array names CustomMatch]]
  1794. set values [join [lrange $sorted 0 end-1] ", "]
  1795. append values ", or [lindex $sorted end]"
  1796. return -code error "bad -match value \"$match\":\
  1797. must be $values"
  1798. }
  1799. # Replace symbolic valies supplied for -returnCodes
  1800. foreach {strcode numcode} {ok 0 normal 0 error 1 return 2 break 3 continue 4} {
  1801. set returnCodes [string map -nocase [list $strcode $numcode] $returnCodes]
  1802. }
  1803. # errorCode without returnCode 1 is meaningless
  1804. if {$errorCode ne "*" && 1 ni $returnCodes} {
  1805. set returnCodes 1
  1806. }
  1807. } else {
  1808. # This is parsing for the old test command format; it is here
  1809. # for backward compatibility.
  1810. set result [lindex $args end]
  1811. if {[llength $args] == 2} {
  1812. set body [lindex $args 0]
  1813. } elseif {[llength $args] == 3} {
  1814. set constraints [lindex $args 0]
  1815. set body [lindex $args 1]
  1816. } else {
  1817. incr testLevel -1
  1818. return -code error "wrong # args:\
  1819. should be \"test name desc ?options?\""
  1820. }
  1821. }
  1822. if {[Skipped $name $constraints]} {
  1823. incr testLevel -1
  1824. return
  1825. }
  1826. # Save information about the core file.
  1827. if {[preserveCore]} {
  1828. if {[file exists [file join [workingDirectory] core]]} {
  1829. set coreModTime [file mtime [file join [workingDirectory] core]]
  1830. }
  1831. }
  1832. # First, run the setup script (or a hook if it presents):
  1833. if {[set cmd [namespace which -command [namespace current]::SetupTest]] ne ""} {
  1834. set setup [list $cmd $setup]
  1835. }
  1836. set processTest 1
  1837. set code [catch {uplevel 1 $setup} setupMsg]
  1838. if {$code == 1} {
  1839. set errorInfo(setup) $::errorInfo
  1840. set errorCodeRes(setup) $::errorCode
  1841. if {$errorCodeRes(setup) eq "BYPASS-SKIPPED-TEST"} {
  1842. _noticeSkipped $name $setupMsg
  1843. set processTest [set code 0]
  1844. }
  1845. }
  1846. set setupFailure [expr {$code != 0}]
  1847. # Only run the test body if the setup was successful
  1848. if {$processTest && !$setupFailure} {
  1849. # Register startup time
  1850. if {[IsVerbose msec] || [IsVerbose usec]} {
  1851. set timeStart [clock microseconds]
  1852. }
  1853. # Verbose notification of $body start
  1854. if {[IsVerbose start]} {
  1855. puts [outputChannel] "---- $name start"
  1856. flush [outputChannel]
  1857. }
  1858. set command [list [namespace origin RunTest] $name $body]
  1859. if {[info exists output] || [info exists errorOutput]} {
  1860. set testResult [uplevel 1 [list [namespace origin Eval] $command 0]]
  1861. } else {
  1862. set testResult [uplevel 1 [list [namespace origin Eval] $command 1]]
  1863. }
  1864. lassign $testResult actualAnswer returnCode
  1865. if {$returnCode == 1} {
  1866. set errorInfo(body) $::errorInfo
  1867. set errorCodeRes(body) $::errorCode
  1868. if {$errorCodeRes(body) eq "BYPASS-SKIPPED-TEST"} {
  1869. _noticeSkipped $name $actualAnswer
  1870. set processTest [set returnCode 0]
  1871. }
  1872. }
  1873. }
  1874. # check if the return code matched the expected return code
  1875. set codeFailure 0
  1876. if {$processTest && !$setupFailure && ($returnCode ni $returnCodes)} {
  1877. set codeFailure 1
  1878. }
  1879. set errorCodeFailure 0
  1880. if {$processTest && !$setupFailure && !$codeFailure && $returnCode == 1 && \
  1881. ![string match $errorCode $errorCodeRes(body)]} {
  1882. set errorCodeFailure 1
  1883. }
  1884. # If expected output/error strings exist, we have to compare
  1885. # them. If the comparison fails, then so did the test.
  1886. set outputFailure 0
  1887. variable outData
  1888. if {$processTest && [info exists output] && !$codeFailure} {
  1889. if {[set outputCompare [catch {
  1890. CompareStrings $outData $output $match
  1891. } outputMatch]] == 0} {
  1892. set outputFailure [expr {!$outputMatch}]
  1893. } else {
  1894. set outputFailure 1
  1895. }
  1896. }
  1897. set errorFailure 0
  1898. variable errData
  1899. if {$processTest && [info exists errorOutput] && !$codeFailure} {
  1900. if {[set errorCompare [catch {
  1901. CompareStrings $errData $errorOutput $match
  1902. } errorMatch]] == 0} {
  1903. set errorFailure [expr {!$errorMatch}]
  1904. } else {
  1905. set errorFailure 1
  1906. }
  1907. }
  1908. # check if the answer matched the expected answer
  1909. # Only check if we ran the body of the test (no setup failure)
  1910. if {!$processTest} {
  1911. set scriptFailure 0
  1912. } elseif {$setupFailure || $codeFailure} {
  1913. set scriptFailure 0
  1914. } elseif {[set scriptCompare [catch {
  1915. CompareStrings $actualAnswer $result $match
  1916. } scriptMatch]] == 0} {
  1917. set scriptFailure [expr {!$scriptMatch}]
  1918. } else {
  1919. set scriptFailure 1
  1920. }
  1921. # Always run the cleanup script (or a hook if it presents):
  1922. if {[set cmd [namespace which -command [namespace current]::CleanupTest]] ne ""} {
  1923. set cleanup [list $cmd $cleanup]
  1924. }
  1925. set code [catch {uplevel 1 $cleanup} cleanupMsg]
  1926. if {$code == 1} {
  1927. set errorInfo(cleanup) $::errorInfo
  1928. set errorCodeRes(cleanup) $::errorCode
  1929. }
  1930. set cleanupFailure [expr {$code != 0}]
  1931. set coreFailure 0
  1932. set coreMsg ""
  1933. # check for a core file first - if one was created by the test,
  1934. # then the test failed
  1935. if {[preserveCore]} {
  1936. if {[file exists [file join [workingDirectory] core]]} {
  1937. # There's only a test failure if there is a core file
  1938. # and (1) there previously wasn't one or (2) the new
  1939. # one is different from the old one.
  1940. if {[info exists coreModTime]} {
  1941. if {$coreModTime != [file mtime \
  1942. [file join [workingDirectory] core]]} {
  1943. set coreFailure 1
  1944. }
  1945. } else {
  1946. set coreFailure 1
  1947. }
  1948. if {([preserveCore] > 1) && ($coreFailure)} {
  1949. append coreMsg "\nMoving file to:\
  1950. [file join [temporaryDirectory] core-$name]"
  1951. catch {file rename -force -- \
  1952. [file join [workingDirectory] core] \
  1953. [file join [temporaryDirectory] core-$name]
  1954. } msg
  1955. if {$msg ne {}} {
  1956. append coreMsg "\nError:\
  1957. Problem renaming core file: $msg"
  1958. }
  1959. }
  1960. }
  1961. }
  1962. if {[IsVerbose msec] || [IsVerbose usec]} {
  1963. set t [expr {[clock microseconds] - $timeStart}]
  1964. if {[IsVerbose usec]} {
  1965. puts [outputChannel] "++++ $name took $t \xB5s"
  1966. }
  1967. if {[IsVerbose msec]} {
  1968. puts [outputChannel] "++++ $name took [expr {round($t/1000.)}] ms"
  1969. }
  1970. }
  1971. # if skipped, it is safe to return here
  1972. if {!$processTest} {
  1973. incr testLevel -1
  1974. return
  1975. }
  1976. # if we didn't experience any failures, then we passed
  1977. variable numTests
  1978. if {!($setupFailure || $cleanupFailure || $coreFailure
  1979. || $outputFailure || $errorFailure || $codeFailure
  1980. || $errorCodeFailure || $scriptFailure)} {
  1981. if {$testLevel == 1} {
  1982. incr numTests(Passed)
  1983. if {[IsVerbose pass]} {
  1984. puts [outputChannel] "++++ $name PASSED"
  1985. }
  1986. }
  1987. incr testLevel -1
  1988. return
  1989. }
  1990. # We know the test failed, tally it...
  1991. if {$testLevel == 1} {
  1992. incr numTests(Failed)
  1993. }
  1994. # ... then report according to the type of failure
  1995. variable currentFailure true
  1996. if {![IsVerbose body]} {
  1997. set body ""
  1998. }
  1999. puts [outputChannel] "\n"
  2000. if {[IsVerbose line]} {
  2001. if {![catch {set testFrame [info frame -1]}] &&
  2002. [dict get $testFrame type] eq "source"} {
  2003. set testFile [dict get $testFrame file]
  2004. set testLine [dict get $testFrame line]
  2005. } else {
  2006. set testFile [file normalize [uplevel 1 {info script}]]
  2007. if {[file readable $testFile]} {
  2008. set testFd [open $testFile r]
  2009. if {$fullutf} {
  2010. fconfigure $testFd -profile tcl8 -encoding utf-8
  2011. }
  2012. set testLine [expr {[lsearch -regexp \
  2013. [split [read $testFd] "\n"] \
  2014. "^\[ \t\]*test [string map {. \\.} $name] "] + 1}]
  2015. close $testFd
  2016. }
  2017. }
  2018. if {[info exists testLine]} {
  2019. puts [outputChannel] "$testFile:$testLine: error: test failed:\
  2020. $name [string trim $description]"
  2021. }
  2022. }
  2023. puts [outputChannel] "==== $name\
  2024. [string trim $description] FAILED"
  2025. if {[string length $body]} {
  2026. puts [outputChannel] "==== Contents of test case:"
  2027. puts [outputChannel] $body
  2028. }
  2029. if {$setupFailure} {
  2030. puts [outputChannel] "---- Test setup\
  2031. failed:\n$setupMsg"
  2032. if {[info exists errorInfo(setup)]} {
  2033. puts [outputChannel] "---- errorInfo(setup): $errorInfo(setup)"
  2034. puts [outputChannel] "---- errorCode(setup): $errorCodeRes(setup)"
  2035. }
  2036. }
  2037. if {$processTest && $scriptFailure} {
  2038. if {$scriptCompare} {
  2039. puts [outputChannel] "---- Error testing result: $scriptMatch"
  2040. } else {
  2041. if {[catch {
  2042. puts [outputChannel] "---- Result was:\n[Asciify $actualAnswer]"
  2043. } errMsg]} {
  2044. puts [outputChannel] "\n---- Result was:\n<error printing result: $errMsg>"
  2045. }
  2046. puts [outputChannel] "---- Result should have been\
  2047. ($match matching):\n[Asciify $result]"
  2048. }
  2049. }
  2050. if {$errorCodeFailure} {
  2051. puts [outputChannel] "---- Error code was: '$errorCodeRes(body)'"
  2052. puts [outputChannel] "---- Error code should have been: '$errorCode'"
  2053. }
  2054. if {$codeFailure} {
  2055. switch -- $returnCode {
  2056. 0 { set msg "Test completed normally" }
  2057. 1 { set msg "Test generated error" }
  2058. 2 { set msg "Test generated return exception" }
  2059. 3 { set msg "Test generated break exception" }
  2060. 4 { set msg "Test generated continue exception" }
  2061. default { set msg "Test generated exception" }
  2062. }
  2063. puts [outputChannel] "---- $msg; Return code was: $returnCode"
  2064. puts [outputChannel] "---- Return code should have been\
  2065. one of: $returnCodes"
  2066. if {[IsVerbose error]} {
  2067. if {[info exists errorInfo(body)] && (1 ni $returnCodes)} {
  2068. puts [outputChannel] "---- errorInfo: $errorInfo(body)"
  2069. puts [outputChannel] "---- errorCode: $errorCodeRes(body)"
  2070. }
  2071. }
  2072. }
  2073. if {$outputFailure} {
  2074. if {$outputCompare} {
  2075. puts [outputChannel] "---- Error testing output: $outputMatch"
  2076. } else {
  2077. puts [outputChannel] "---- Output was:\n$outData"
  2078. puts [outputChannel] "---- Output should have been\
  2079. ($match matching):\n$output"
  2080. }
  2081. }
  2082. if {$errorFailure} {
  2083. if {$errorCompare} {
  2084. puts [outputChannel] "---- Error testing errorOutput: $errorMatch"
  2085. } else {
  2086. puts [outputChannel] "---- Error output was:\n$errData"
  2087. puts [outputChannel] "---- Error output should have\
  2088. been ($match matching):\n$errorOutput"
  2089. }
  2090. }
  2091. if {$cleanupFailure} {
  2092. puts [outputChannel] "---- Test cleanup failed:\n$cleanupMsg"
  2093. if {[info exists errorInfo(cleanup)]} {
  2094. puts [outputChannel] "---- errorInfo(cleanup): $errorInfo(cleanup)"
  2095. puts [outputChannel] "---- errorCode(cleanup): $errorCodeRes(cleanup)"
  2096. }
  2097. }
  2098. if {$coreFailure} {
  2099. puts [outputChannel] "---- Core file produced while running\
  2100. test! $coreMsg"
  2101. }
  2102. puts [outputChannel] "==== $name FAILED\n"
  2103. incr testLevel -1
  2104. return
  2105. }
  2106. # Skip --
  2107. #
  2108. # Skips a running test and add a reason to skipped "constraints". Can be used
  2109. # to conditional intended abort of the test.
  2110. #
  2111. # Side Effects: Maintains tally of total tests seen and tests skipped.
  2112. #
  2113. proc tcltest::Skip {reason} {
  2114. return -code error -errorcode BYPASS-SKIPPED-TEST $reason
  2115. }
  2116. proc tcltest::_noticeSkipped {name reason} {
  2117. variable testLevel
  2118. variable numTests
  2119. if {[IsVerbose skip]} {
  2120. puts [outputChannel] "++++ $name SKIPPED: $reason"
  2121. }
  2122. if {$testLevel == 1} {
  2123. incr numTests(Skipped)
  2124. AddToSkippedBecause $reason
  2125. }
  2126. }
  2127. # Skipped --
  2128. #
  2129. # Given a test name and it constraints, returns a boolean indicating
  2130. # whether the current configuration says the test should be skipped.
  2131. #
  2132. # Side Effects: Maintains tally of total tests seen and tests skipped.
  2133. #
  2134. proc tcltest::Skipped {name constraints} {
  2135. variable testLevel
  2136. variable numTests
  2137. variable testConstraints
  2138. if {$testLevel == 1} {
  2139. incr numTests(Total)
  2140. }
  2141. # skip the test if it's name matches an element of skip
  2142. foreach pattern [skip] {
  2143. if {[string match $pattern $name]} {
  2144. if {$testLevel == 1} {
  2145. incr numTests(Skipped)
  2146. DebugDo 1 {AddToSkippedBecause userSpecifiedSkip}
  2147. }
  2148. return 1
  2149. }
  2150. }
  2151. # skip the test if it's name doesn't match any element of match
  2152. set ok 0
  2153. foreach pattern [match] {
  2154. if {[string match $pattern $name]} {
  2155. set ok 1
  2156. break
  2157. }
  2158. }
  2159. if {!$ok} {
  2160. if {$testLevel == 1} {
  2161. incr numTests(Skipped)
  2162. DebugDo 1 {AddToSkippedBecause userSpecifiedNonMatch}
  2163. }
  2164. return 1
  2165. }
  2166. if {$constraints eq {}} {
  2167. # If we're limited to the listed constraints and there aren't
  2168. # any listed, then we shouldn't run the test.
  2169. if {[limitConstraints]} {
  2170. AddToSkippedBecause userSpecifiedLimitConstraint
  2171. if {$testLevel == 1} {
  2172. incr numTests(Skipped)
  2173. }
  2174. return 1
  2175. }
  2176. } else {
  2177. # "constraints" argument exists;
  2178. # make sure that the constraints are satisfied.
  2179. set doTest 0
  2180. set constraints [string trim $constraints]
  2181. if {[string match {*[$\[]*} $constraints] != 0} {
  2182. # full expression, e.g. {$foo > [info tclversion]}
  2183. catch {set doTest [uplevel #0 [list expr $constraints]]}
  2184. } elseif {[regexp {[^.:_a-zA-Z0-9 \n\r\t]+} $constraints] != 0} {
  2185. # something like {a || b} should be turned into
  2186. # $testConstraints(a) || $testConstraints(b).
  2187. regsub -all {[.\w]+} $constraints {$testConstraints(&)} c
  2188. catch {set doTest [eval [list expr $c]]}
  2189. } elseif {![catch {llength $constraints}]} {
  2190. # just simple constraints such as {unixOnly fonts}.
  2191. set doTest 1
  2192. foreach constraint $constraints {
  2193. if {(![info exists testConstraints($constraint)]) \
  2194. || (!$testConstraints($constraint))} {
  2195. set doTest 0
  2196. # store the constraint that kept the test from
  2197. # running
  2198. set constraints $constraint
  2199. break
  2200. }
  2201. }
  2202. }
  2203. if {!$doTest} {
  2204. _noticeSkipped $name $constraints
  2205. return 1
  2206. }
  2207. }
  2208. return 0
  2209. }
  2210. # RunTest --
  2211. #
  2212. # This is where the body of a test is evaluated. The combination of
  2213. # [RunTest] and [Eval] allows the output and error output of the test
  2214. # body to be captured for comparison against the expected values.
  2215. proc tcltest::RunTest {name script} {
  2216. DebugPuts 3 "Running $name {$script}"
  2217. # If there is no "memory" command (because memory debugging isn't
  2218. # enabled), then don't attempt to use the command.
  2219. if {[llength [info commands memory]] == 1} {
  2220. memory tag $name
  2221. }
  2222. # run the test script (or a hook if it presents):
  2223. if {[set cmd [namespace which -command [namespace current]::EvalTest]] ne ""} {
  2224. set script [list $cmd $script]
  2225. }
  2226. set code [catch {uplevel 1 $script} actualAnswer]
  2227. return [list $actualAnswer $code]
  2228. }
  2229. #####################################################################
  2230. # tcltest::cleanupTestsHook --
  2231. #
  2232. # This hook allows a harness that builds upon tcltest to specify
  2233. # additional things that should be done at cleanup.
  2234. #
  2235. if {[llength [info commands tcltest::cleanupTestsHook]] == 0} {
  2236. proc tcltest::cleanupTestsHook {} {}
  2237. }
  2238. # tcltest::cleanupTests --
  2239. #
  2240. # Remove files and dirs created using the makeFile and makeDirectory
  2241. # commands since the last time this proc was invoked.
  2242. #
  2243. # Print the names of the files created without the makeFile command
  2244. # since the tests were invoked.
  2245. #
  2246. # Print the number tests (total, passed, failed, and skipped) since the
  2247. # tests were invoked.
  2248. #
  2249. # Restore original environment (as reported by special variable env).
  2250. #
  2251. # Arguments:
  2252. # calledFromAllFile - if 0, behave as if we are running a single
  2253. # test file within an entire suite of tests. if we aren't running
  2254. # a single test file, then don't report status. check for new
  2255. # files created during the test run and report on them. if 1,
  2256. # report collated status from all the test file runs.
  2257. #
  2258. # Results:
  2259. # None.
  2260. #
  2261. # Side Effects:
  2262. # None
  2263. #
  2264. proc tcltest::cleanupTests {{calledFromAllFile 0}} {
  2265. variable filesMade
  2266. variable filesExisted
  2267. variable createdNewFiles
  2268. variable testSingleFile
  2269. variable numTests
  2270. variable numTestFiles
  2271. variable failFiles
  2272. variable skippedBecause
  2273. variable currentFailure
  2274. variable originalEnv
  2275. variable originalTclPlatform
  2276. variable coreModTime
  2277. FillFilesExisted
  2278. set testFileName [file tail [info script]]
  2279. # Hook to handle reporting to a parent interpreter
  2280. if {[llength [info commands [namespace current]::ReportToParent]]} {
  2281. ReportToParent $numTests(Total) $numTests(Passed) $numTests(Skipped) \
  2282. $numTests(Failed) [array get skippedBecause] \
  2283. [array get createdNewFiles]
  2284. set testSingleFile false
  2285. }
  2286. # Call the cleanup hook
  2287. cleanupTestsHook
  2288. # Remove files and directories created by the makeFile and
  2289. # makeDirectory procedures. Record the names of files in
  2290. # workingDirectory that were not preexisting, and associate them
  2291. # with the test file that created them.
  2292. if {!$calledFromAllFile} {
  2293. foreach file $filesMade {
  2294. if {[file exists $file]} {
  2295. DebugDo 1 {Warn "cleanupTests deleting $file..."}
  2296. catch {file delete -force -- $file}
  2297. }
  2298. }
  2299. set currentFiles {}
  2300. foreach file [glob -nocomplain \
  2301. -directory [temporaryDirectory] *] {
  2302. lappend currentFiles [file tail $file]
  2303. }
  2304. set newFiles {}
  2305. foreach file $currentFiles {
  2306. if {$file ni $filesExisted} {
  2307. lappend newFiles $file
  2308. }
  2309. }
  2310. set filesExisted $currentFiles
  2311. if {[llength $newFiles] > 0} {
  2312. set createdNewFiles($testFileName) $newFiles
  2313. }
  2314. }
  2315. if {$calledFromAllFile || $testSingleFile} {
  2316. # print stats
  2317. puts -nonewline [outputChannel] "$testFileName:"
  2318. foreach index [list "Total" "Passed" "Skipped" "Failed"] {
  2319. puts -nonewline [outputChannel] \
  2320. "\t$index\t$numTests($index)"
  2321. }
  2322. puts [outputChannel] ""
  2323. # print number test files sourced
  2324. # print names of files that ran tests which failed
  2325. if {$calledFromAllFile} {
  2326. puts [outputChannel] \
  2327. "Sourced $numTestFiles Test Files."
  2328. set numTestFiles 0
  2329. if {[llength $failFiles] > 0} {
  2330. puts [outputChannel] \
  2331. "Files with failing tests: $failFiles"
  2332. set failFiles {}
  2333. }
  2334. }
  2335. # if any tests were skipped, print the constraints that kept
  2336. # them from running.
  2337. set constraintList [array names skippedBecause]
  2338. if {[llength $constraintList] > 0} {
  2339. puts [outputChannel] \
  2340. "Number of tests skipped for each constraint:"
  2341. foreach constraint [lsort $constraintList] {
  2342. puts [outputChannel] \
  2343. "\t$skippedBecause($constraint)\t$constraint"
  2344. unset skippedBecause($constraint)
  2345. }
  2346. }
  2347. # report the names of test files in createdNewFiles, and reset
  2348. # the array to be empty.
  2349. set testFilesThatTurded [lsort [array names createdNewFiles]]
  2350. if {[llength $testFilesThatTurded] > 0} {
  2351. puts [outputChannel] "Warning: files left behind:"
  2352. foreach testFile $testFilesThatTurded {
  2353. puts [outputChannel] \
  2354. "\t$testFile:\t$createdNewFiles($testFile)"
  2355. unset createdNewFiles($testFile)
  2356. }
  2357. }
  2358. # reset filesMade, filesExisted, and numTests
  2359. set filesMade {}
  2360. foreach index [list "Total" "Passed" "Skipped" "Failed"] {
  2361. set numTests($index) 0
  2362. }
  2363. # exit only if running Tk in non-interactive mode
  2364. # This should be changed to determine if an event
  2365. # loop is running, which is the real issue.
  2366. # Actually, this doesn't belong here at all. A package
  2367. # really has no business [exit]-ing an application.
  2368. if {[info exists ::tk_version] && ![testConstraint interactive]} {
  2369. exit
  2370. }
  2371. } else {
  2372. # if we're deferring stat-reporting until all files are sourced,
  2373. # then add current file to failFile list if any tests in this
  2374. # file failed
  2375. if {$currentFailure && ($testFileName ni $failFiles)} {
  2376. lappend failFiles $testFileName
  2377. }
  2378. set currentFailure false
  2379. # restore the environment to the state it was in before this package
  2380. # was loaded
  2381. set newEnv {}
  2382. set changedEnv {}
  2383. set removedEnv {}
  2384. foreach index [array names ::env] {
  2385. if {![info exists originalEnv($index)]} {
  2386. lappend newEnv $index
  2387. unset ::env($index)
  2388. }
  2389. }
  2390. foreach index [array names originalEnv] {
  2391. if {![info exists ::env($index)]} {
  2392. lappend removedEnv $index
  2393. set ::env($index) $originalEnv($index)
  2394. } elseif {$::env($index) ne $originalEnv($index)} {
  2395. lappend changedEnv $index
  2396. set ::env($index) $originalEnv($index)
  2397. }
  2398. }
  2399. if {[llength $newEnv] > 0} {
  2400. puts [outputChannel] \
  2401. "env array elements created:\t$newEnv"
  2402. }
  2403. if {[llength $changedEnv] > 0} {
  2404. puts [outputChannel] \
  2405. "env array elements changed:\t$changedEnv"
  2406. }
  2407. if {[llength $removedEnv] > 0} {
  2408. puts [outputChannel] \
  2409. "env array elements removed:\t$removedEnv"
  2410. }
  2411. set changedTclPlatform {}
  2412. foreach index [array names originalTclPlatform] {
  2413. if {$::tcl_platform($index) \
  2414. != $originalTclPlatform($index)} {
  2415. lappend changedTclPlatform $index
  2416. set ::tcl_platform($index) $originalTclPlatform($index)
  2417. }
  2418. }
  2419. if {[llength $changedTclPlatform] > 0} {
  2420. puts [outputChannel] "tcl_platform array elements\
  2421. changed:\t$changedTclPlatform"
  2422. }
  2423. if {[file exists [file join [workingDirectory] core]]} {
  2424. if {[preserveCore] > 1} {
  2425. puts "rename core file (> 1)"
  2426. puts [outputChannel] "produced core file! \
  2427. Moving file to: \
  2428. [file join [temporaryDirectory] core-$testFileName]"
  2429. catch {file rename -force -- \
  2430. [file join [workingDirectory] core] \
  2431. [file join [temporaryDirectory] core-$testFileName]
  2432. } msg
  2433. if {$msg ne {}} {
  2434. PrintError "Problem renaming file: $msg"
  2435. }
  2436. } else {
  2437. # Print a message if there is a core file and (1) there
  2438. # previously wasn't one or (2) the new one is different
  2439. # from the old one.
  2440. if {[info exists coreModTime]} {
  2441. if {$coreModTime != [file mtime \
  2442. [file join [workingDirectory] core]]} {
  2443. puts [outputChannel] "A core file was created!"
  2444. }
  2445. } else {
  2446. puts [outputChannel] "A core file was created!"
  2447. }
  2448. }
  2449. }
  2450. }
  2451. flush [outputChannel]
  2452. flush [errorChannel]
  2453. return
  2454. }
  2455. #####################################################################
  2456. # Procs that determine which tests/test files to run
  2457. # tcltest::GetMatchingFiles
  2458. #
  2459. # Looks at the patterns given to match and skip files and uses
  2460. # them to put together a list of the tests that will be run.
  2461. #
  2462. # Arguments:
  2463. # directory to search
  2464. #
  2465. # Results:
  2466. # The constructed list is returned to the user. This will
  2467. # primarily be used in 'all.tcl' files. It is used in
  2468. # runAllTests.
  2469. #
  2470. # Side Effects:
  2471. # None
  2472. # a lower case version is needed for compatibility with tcltest 1.0
  2473. proc tcltest::getMatchingFiles args {GetMatchingFiles {*}$args}
  2474. proc tcltest::GetMatchingFiles { args } {
  2475. if {[llength $args]} {
  2476. set dirList $args
  2477. } else {
  2478. # Finding tests only in [testsDirectory] is normal operation.
  2479. # This procedure is written to accept multiple directory arguments
  2480. # only to satisfy version 1 compatibility.
  2481. set dirList [list [testsDirectory]]
  2482. }
  2483. set matchingFiles [list]
  2484. foreach directory $dirList {
  2485. # List files in $directory that match patterns to run.
  2486. set matchFileList [list]
  2487. foreach match [matchFiles] {
  2488. set matchFileList [concat $matchFileList \
  2489. [glob -directory $directory -types {b c f p s} \
  2490. -nocomplain -- $match]]
  2491. }
  2492. # List files in $directory that match patterns to skip.
  2493. set skipFileList [list]
  2494. foreach skip [skipFiles] {
  2495. set skipFileList [concat $skipFileList \
  2496. [glob -directory $directory -types {b c f p s} \
  2497. -nocomplain -- $skip]]
  2498. }
  2499. # Add to result list all files in match list and not in skip list
  2500. foreach file $matchFileList {
  2501. if {$file ni $skipFileList} {
  2502. lappend matchingFiles $file
  2503. }
  2504. }
  2505. }
  2506. if {[llength $matchingFiles] == 0} {
  2507. PrintError "No test files remain after applying your match and\
  2508. skip patterns!"
  2509. }
  2510. return $matchingFiles
  2511. }
  2512. # tcltest::GetMatchingDirectories --
  2513. #
  2514. # Looks at the patterns given to match and skip directories and
  2515. # uses them to put together a list of the test directories that we
  2516. # should attempt to run. (Only subdirectories containing an
  2517. # "all.tcl" file are put into the list.)
  2518. #
  2519. # Arguments:
  2520. # root directory from which to search
  2521. #
  2522. # Results:
  2523. # The constructed list is returned to the user. This is used in
  2524. # the primary all.tcl file.
  2525. #
  2526. # Side Effects:
  2527. # None.
  2528. proc tcltest::GetMatchingDirectories {rootdir} {
  2529. # Determine the skip list first, to avoid [glob]-ing over subdirectories
  2530. # we're going to throw away anyway. Be sure we skip the $rootdir if it
  2531. # comes up to avoid infinite loops.
  2532. set skipDirs [list $rootdir]
  2533. foreach pattern [skipDirectories] {
  2534. set skipDirs [concat $skipDirs [glob -directory $rootdir -types d \
  2535. -nocomplain -- $pattern]]
  2536. }
  2537. # Now step through the matching directories, prune out the skipped ones
  2538. # as you go.
  2539. set matchDirs [list]
  2540. foreach pattern [matchDirectories] {
  2541. foreach path [glob -directory $rootdir -types d -nocomplain -- \
  2542. $pattern] {
  2543. if {$path ni $skipDirs} {
  2544. set matchDirs [concat $matchDirs [GetMatchingDirectories $path]]
  2545. if {[file exists [file join $path all.tcl]]} {
  2546. lappend matchDirs $path
  2547. }
  2548. }
  2549. }
  2550. }
  2551. if {[llength $matchDirs] == 0} {
  2552. DebugPuts 1 "No test directories remain after applying match\
  2553. and skip patterns!"
  2554. }
  2555. return [lsort $matchDirs]
  2556. }
  2557. # tcltest::runAllTests --
  2558. #
  2559. # prints output and sources test files according to the match and
  2560. # skip patterns provided. after sourcing test files, it goes on
  2561. # to source all.tcl files in matching test subdirectories.
  2562. #
  2563. # Arguments:
  2564. # shell being tested
  2565. #
  2566. # Results:
  2567. # Whether there were any failures.
  2568. #
  2569. # Side effects:
  2570. # None.
  2571. proc tcltest::runAllTests { {shell ""} } {
  2572. variable testSingleFile
  2573. variable numTestFiles
  2574. variable numTests
  2575. variable failFiles
  2576. variable DefaultValue
  2577. variable fullutf
  2578. FillFilesExisted
  2579. if {[llength [info level 0]] == 1} {
  2580. set shell [interpreter]
  2581. }
  2582. set testSingleFile false
  2583. puts [outputChannel] "Tests running in interp: $shell"
  2584. puts [outputChannel] "Tests located in: [testsDirectory]"
  2585. puts [outputChannel] "Tests running in: [workingDirectory]"
  2586. puts [outputChannel] "Temporary files stored in\
  2587. [temporaryDirectory]"
  2588. # [file system] first available in Tcl 8.4
  2589. if {![catch {file system [testsDirectory]} result]
  2590. && ([lindex $result 0] ne "native")} {
  2591. # If we aren't running in the native filesystem, then we must
  2592. # run the tests in a single process (via 'source'), because
  2593. # trying to run then via a pipe will fail since the files don't
  2594. # really exist.
  2595. singleProcess 1
  2596. }
  2597. if {[singleProcess]} {
  2598. puts [outputChannel] \
  2599. "Test files sourced into current interpreter"
  2600. } else {
  2601. puts [outputChannel] \
  2602. "Test files run in separate interpreters"
  2603. }
  2604. if {[llength [skip]] > 0} {
  2605. puts [outputChannel] "Skipping tests that match: [skip]"
  2606. }
  2607. puts [outputChannel] "Running tests that match: [match]"
  2608. if {[llength [skipFiles]] > 0} {
  2609. puts [outputChannel] \
  2610. "Skipping test files that match: [skipFiles]"
  2611. }
  2612. if {[llength [matchFiles]] > 0} {
  2613. puts [outputChannel] \
  2614. "Only running test files that match: [matchFiles]"
  2615. }
  2616. set timeCmd {clock format [clock seconds]}
  2617. puts [outputChannel] "Tests began at [eval $timeCmd]"
  2618. # Run each of the specified tests
  2619. foreach file [lsort [GetMatchingFiles]] {
  2620. set tail [file tail $file]
  2621. puts [outputChannel] $tail
  2622. flush [outputChannel]
  2623. if {[singleProcess]} {
  2624. if {[catch {
  2625. incr numTestFiles
  2626. uplevel 1 [list ::source $file]
  2627. } msg]} {
  2628. puts [outputChannel] "Test file error: $msg"
  2629. # append the name of the test to a list to be reported
  2630. # later
  2631. lappend testFileFailures $file
  2632. }
  2633. if {$numTests(Failed) > 0} {
  2634. set failFilesSet 1
  2635. }
  2636. } else {
  2637. # Pass along our configuration to the child processes.
  2638. # EXCEPT for the -outfile, because the parent process
  2639. # needs to read and process output of children.
  2640. set childargv [list]
  2641. foreach opt [Configure] {
  2642. if {$opt eq "-outfile"} {continue}
  2643. set value [Configure $opt]
  2644. # Don't bother passing default configuration options
  2645. if {$value eq $DefaultValue($opt)} {
  2646. continue
  2647. }
  2648. lappend childargv $opt $value
  2649. }
  2650. set cmd [linsert $childargv 0 | $shell $file]
  2651. if {[catch {
  2652. incr numTestFiles
  2653. set pipeFd [open $cmd "r"]
  2654. if {$fullutf} {
  2655. fconfigure $pipeFd -profile tcl8 -encoding utf-8
  2656. }
  2657. while {[gets $pipeFd line] >= 0} {
  2658. if {[regexp [join {
  2659. {^([^:]+):\t}
  2660. {Total\t([0-9]+)\t}
  2661. {Passed\t([0-9]+)\t}
  2662. {Skipped\t([0-9]+)\t}
  2663. {Failed\t([0-9]+)}
  2664. } ""] $line null testFile \
  2665. Total Passed Skipped Failed]} {
  2666. foreach index {Total Passed Skipped Failed} {
  2667. incr numTests($index) [set $index]
  2668. }
  2669. if {$Failed > 0} {
  2670. lappend failFiles $testFile
  2671. set failFilesSet 1
  2672. }
  2673. } elseif {[regexp [join {
  2674. {^Number of tests skipped }
  2675. {for each constraint:}
  2676. {|^\t(\d+)\t(.+)$}
  2677. } ""] $line match skipped constraint]} {
  2678. if {[string match \t* $match]} {
  2679. AddToSkippedBecause $constraint $skipped
  2680. }
  2681. } else {
  2682. puts [outputChannel] $line
  2683. }
  2684. }
  2685. close $pipeFd
  2686. } msg]} {
  2687. puts [outputChannel] "Test file error: $msg"
  2688. # append the name of the test to a list to be reported
  2689. # later
  2690. lappend testFileFailures $file
  2691. }
  2692. }
  2693. }
  2694. # cleanup
  2695. puts [outputChannel] "\nTests ended at [eval $timeCmd]"
  2696. cleanupTests 1
  2697. if {[info exists testFileFailures]} {
  2698. puts [outputChannel] "\nTest files exiting with errors: \n"
  2699. foreach file $testFileFailures {
  2700. puts [outputChannel] " [file tail $file]\n"
  2701. }
  2702. }
  2703. # Checking for subdirectories in which to run tests
  2704. foreach directory [GetMatchingDirectories [testsDirectory]] {
  2705. set dir [file tail $directory]
  2706. puts [outputChannel] [string repeat ~ 44]
  2707. puts [outputChannel] "$dir test began at [eval $timeCmd]\n"
  2708. uplevel 1 [list ::source [file join $directory all.tcl]]
  2709. set endTime [eval $timeCmd]
  2710. puts [outputChannel] "\n$dir test ended at $endTime"
  2711. puts [outputChannel] ""
  2712. puts [outputChannel] [string repeat ~ 44]
  2713. }
  2714. return [expr {[info exists testFileFailures] || [info exists failFilesSet]}]
  2715. }
  2716. #####################################################################
  2717. # Test utility procs - not used in tcltest, but may be useful for
  2718. # testing.
  2719. # tcltest::loadTestedCommands --
  2720. #
  2721. # Uses the specified script to load the commands to test. Allowed to
  2722. # be empty, as the tested commands could have been compiled into the
  2723. # interpreter.
  2724. #
  2725. # Arguments
  2726. # none
  2727. #
  2728. # Results
  2729. # none
  2730. #
  2731. # Side Effects:
  2732. # none.
  2733. proc tcltest::loadTestedCommands {} {
  2734. return [uplevel 1 [loadScript]]
  2735. }
  2736. # tcltest::saveState --
  2737. #
  2738. # Save information regarding what procs and variables exist.
  2739. #
  2740. # Arguments:
  2741. # none
  2742. #
  2743. # Results:
  2744. # Modifies the variable saveState
  2745. #
  2746. # Side effects:
  2747. # None.
  2748. proc tcltest::saveState {} {
  2749. variable saveState
  2750. uplevel 1 [list ::set [namespace which -variable saveState]] \
  2751. {[::list [::info procs] [::info vars]]}
  2752. DebugPuts 2 "[lindex [info level 0] 0]: $saveState"
  2753. return
  2754. }
  2755. # tcltest::restoreState --
  2756. #
  2757. # Remove procs and variables that didn't exist before the call to
  2758. # [saveState].
  2759. #
  2760. # Arguments:
  2761. # none
  2762. #
  2763. # Results:
  2764. # Removes procs and variables from your environment if they don't
  2765. # exist in the saveState variable.
  2766. #
  2767. # Side effects:
  2768. # None.
  2769. proc tcltest::restoreState {} {
  2770. variable saveState
  2771. foreach p [uplevel 1 {::info procs}] {
  2772. if {($p ni [lindex $saveState 0]) && ("[namespace current]::$p" ne
  2773. [uplevel 1 [list ::namespace origin $p]])} {
  2774. DebugPuts 2 "[lindex [info level 0] 0]: Removing proc $p"
  2775. uplevel 1 [list ::catch [list ::rename $p {}]]
  2776. }
  2777. }
  2778. foreach p [uplevel 1 {::info vars}] {
  2779. if {$p ni [lindex $saveState 1]} {
  2780. DebugPuts 2 "[lindex [info level 0] 0]:\
  2781. Removing variable $p"
  2782. uplevel 1 [list ::catch [list ::unset $p]]
  2783. }
  2784. }
  2785. return
  2786. }
  2787. # tcltest::normalizeMsg --
  2788. #
  2789. # Removes "extra" newlines from a string.
  2790. #
  2791. # Arguments:
  2792. # msg String to be modified
  2793. #
  2794. # Results:
  2795. # string with extra newlines removed
  2796. #
  2797. # Side effects:
  2798. # None.
  2799. proc tcltest::normalizeMsg {msg} {
  2800. regsub "\n$" [string tolower $msg] "" msg
  2801. set msg [string map [list "\n\n" "\n"] $msg]
  2802. return [string map [list "\n\}" "\}"] $msg]
  2803. }
  2804. # tcltest::makeFile --
  2805. #
  2806. # Create a new file with the name <name>, and write <contents> to it.
  2807. #
  2808. # If this file hasn't been created via makeFile since the last time
  2809. # cleanupTests was called, add it to the $filesMade list, so it will be
  2810. # removed by the next call to cleanupTests.
  2811. #
  2812. # Arguments:
  2813. # contents content of the new file
  2814. # name name of the new file
  2815. # directory directory name for new file
  2816. #
  2817. # Results:
  2818. # absolute path to the file created
  2819. #
  2820. # Side effects:
  2821. # None.
  2822. proc tcltest::makeFile {contents name {directory ""}} {
  2823. variable filesMade
  2824. variable fullutf
  2825. FillFilesExisted
  2826. if {[llength [info level 0]] == 3} {
  2827. set directory [temporaryDirectory]
  2828. }
  2829. set fullName [file join $directory $name]
  2830. DebugPuts 3 "[lindex [info level 0] 0]:\
  2831. putting ``$contents'' into $fullName"
  2832. set fd [open $fullName w]
  2833. fconfigure $fd -translation lf
  2834. if {$fullutf} {
  2835. fconfigure $fd -profile tcl8 -encoding utf-8
  2836. }
  2837. if {[string index $contents end] eq "\n"} {
  2838. puts -nonewline $fd $contents
  2839. } else {
  2840. puts $fd $contents
  2841. }
  2842. close $fd
  2843. if {$fullName ni $filesMade} {
  2844. lappend filesMade $fullName
  2845. }
  2846. return $fullName
  2847. }
  2848. # tcltest::removeFile --
  2849. #
  2850. # Removes the named file from the filesystem
  2851. #
  2852. # Arguments:
  2853. # name file to be removed
  2854. # directory directory from which to remove file
  2855. #
  2856. # Results:
  2857. # return value from [file delete]
  2858. #
  2859. # Side effects:
  2860. # None.
  2861. proc tcltest::removeFile {name {directory ""}} {
  2862. variable filesMade
  2863. FillFilesExisted
  2864. if {[llength [info level 0]] == 2} {
  2865. set directory [temporaryDirectory]
  2866. }
  2867. set fullName [file join $directory $name]
  2868. DebugPuts 3 "[lindex [info level 0] 0]: removing $fullName"
  2869. set idx [lsearch -exact $filesMade $fullName]
  2870. if {$idx < 0} {
  2871. DebugDo 1 {
  2872. Warn "removeFile removing \"$fullName\":\n not created by makeFile"
  2873. }
  2874. } else {
  2875. set filesMade [lreplace $filesMade $idx $idx]
  2876. }
  2877. if {![file isfile $fullName]} {
  2878. DebugDo 1 {
  2879. Warn "removeFile removing \"$fullName\":\n not a file"
  2880. }
  2881. }
  2882. if {[catch {file delete -- $fullName} msg ]} {
  2883. DebugDo 1 {
  2884. Warn "removeFile removing \"$fullName\":\n failed: $msg"
  2885. }
  2886. }
  2887. return
  2888. }
  2889. # tcltest::makeDirectory --
  2890. #
  2891. # Create a new dir with the name <name>.
  2892. #
  2893. # If this dir hasn't been created via makeDirectory since the last time
  2894. # cleanupTests was called, add it to the $directoriesMade list, so it
  2895. # will be removed by the next call to cleanupTests.
  2896. #
  2897. # Arguments:
  2898. # name name of the new directory
  2899. # directory directory in which to create new dir
  2900. #
  2901. # Results:
  2902. # absolute path to the directory created
  2903. #
  2904. # Side effects:
  2905. # None.
  2906. proc tcltest::makeDirectory {name {directory ""}} {
  2907. variable filesMade
  2908. FillFilesExisted
  2909. if {[llength [info level 0]] == 2} {
  2910. set directory [temporaryDirectory]
  2911. }
  2912. set fullName [file join $directory $name]
  2913. DebugPuts 3 "[lindex [info level 0] 0]: creating $fullName"
  2914. file mkdir $fullName
  2915. if {$fullName ni $filesMade} {
  2916. lappend filesMade $fullName
  2917. }
  2918. return $fullName
  2919. }
  2920. # tcltest::removeDirectory --
  2921. #
  2922. # Removes a named directory from the file system.
  2923. #
  2924. # Arguments:
  2925. # name Name of the directory to remove
  2926. # directory Directory from which to remove
  2927. #
  2928. # Results:
  2929. # return value from [file delete]
  2930. #
  2931. # Side effects:
  2932. # None
  2933. proc tcltest::removeDirectory {name {directory ""}} {
  2934. variable filesMade
  2935. FillFilesExisted
  2936. if {[llength [info level 0]] == 2} {
  2937. set directory [temporaryDirectory]
  2938. }
  2939. set fullName [file join $directory $name]
  2940. DebugPuts 3 "[lindex [info level 0] 0]: deleting $fullName"
  2941. set idx [lsearch -exact $filesMade $fullName]
  2942. set filesMade [lreplace $filesMade $idx $idx]
  2943. if {$idx < 0} {
  2944. DebugDo 1 {
  2945. Warn "removeDirectory removing \"$fullName\":\n not created\
  2946. by makeDirectory"
  2947. }
  2948. }
  2949. if {![file isdirectory $fullName]} {
  2950. DebugDo 1 {
  2951. Warn "removeDirectory removing \"$fullName\":\n not a directory"
  2952. }
  2953. }
  2954. return [file delete -force -- $fullName]
  2955. }
  2956. # tcltest::viewFile --
  2957. #
  2958. # reads the content of a file and returns it
  2959. #
  2960. # Arguments:
  2961. # name of the file to read
  2962. # directory in which file is located
  2963. #
  2964. # Results:
  2965. # content of the named file
  2966. #
  2967. # Side effects:
  2968. # None.
  2969. proc tcltest::viewFile {name {directory ""}} {
  2970. variable fullutf
  2971. FillFilesExisted
  2972. if {[llength [info level 0]] == 2} {
  2973. set directory [temporaryDirectory]
  2974. }
  2975. set fullName [file join $directory $name]
  2976. set f [open $fullName]
  2977. if {$fullutf} {
  2978. fconfigure $f -profile tcl8 -encoding utf-8
  2979. }
  2980. set data [read -nonewline $f]
  2981. close $f
  2982. return $data
  2983. }
  2984. # tcltest::bytestring --
  2985. #
  2986. # Construct a string that consists of the requested sequence of bytes,
  2987. # as opposed to a string of properly formed UTF-8 characters.
  2988. # This allows the tester to
  2989. # 1. Create denormalized or improperly formed strings to pass to C
  2990. # procedures that are supposed to accept strings with embedded NULL
  2991. # bytes.
  2992. # 2. Confirm that a string result has a certain pattern of bytes, for
  2993. # instance to confirm that "\xE0\0" in a Tcl script is stored
  2994. # internally in UTF-8 as the sequence of bytes "\xC3\xA0\xC0\x80".
  2995. #
  2996. # Generally, it's a bad idea to examine the bytes in a Tcl string or to
  2997. # construct improperly formed strings in this manner, because it involves
  2998. # exposing that Tcl uses UTF-8 internally.
  2999. #
  3000. # This function doesn't work any more in Tcl 8.7, since the 'identity'
  3001. # is gone (TIP #345)
  3002. #
  3003. # Arguments:
  3004. # string being converted
  3005. #
  3006. # Results:
  3007. # result fom encoding
  3008. #
  3009. # Side effects:
  3010. # None
  3011. if {!$::tcltest::fullutf} {
  3012. proc tcltest::bytestring {string} {
  3013. return [encoding convertfrom identity $string]
  3014. }
  3015. }
  3016. # tcltest::OpenFiles --
  3017. #
  3018. # used in io tests, uses testchannel
  3019. #
  3020. # Arguments:
  3021. # None.
  3022. #
  3023. # Results:
  3024. # ???
  3025. #
  3026. # Side effects:
  3027. # None.
  3028. proc tcltest::OpenFiles {} {
  3029. if {[catch {testchannel open} result]} {
  3030. return {}
  3031. }
  3032. return $result
  3033. }
  3034. # tcltest::LeakFiles --
  3035. #
  3036. # used in io tests, uses testchannel
  3037. #
  3038. # Arguments:
  3039. # None.
  3040. #
  3041. # Results:
  3042. # ???
  3043. #
  3044. # Side effects:
  3045. # None.
  3046. proc tcltest::LeakFiles {old} {
  3047. if {[catch {testchannel open} new]} {
  3048. return {}
  3049. }
  3050. set leak {}
  3051. foreach p $new {
  3052. if {$p ni $old} {
  3053. lappend leak $p
  3054. }
  3055. }
  3056. return $leak
  3057. }
  3058. #
  3059. # Internationalization / ISO support procs -- dl
  3060. #
  3061. # tcltest::SetIso8859_1_Locale --
  3062. #
  3063. # used in cmdIL.test, uses testlocale
  3064. #
  3065. # Arguments:
  3066. # None.
  3067. #
  3068. # Results:
  3069. # None.
  3070. #
  3071. # Side effects:
  3072. # None.
  3073. proc tcltest::SetIso8859_1_Locale {} {
  3074. variable previousLocale
  3075. variable isoLocale
  3076. if {[info commands testlocale] != ""} {
  3077. set previousLocale [testlocale ctype]
  3078. testlocale ctype $isoLocale
  3079. }
  3080. return
  3081. }
  3082. # tcltest::RestoreLocale --
  3083. #
  3084. # used in cmdIL.test, uses testlocale
  3085. #
  3086. # Arguments:
  3087. # None.
  3088. #
  3089. # Results:
  3090. # None.
  3091. #
  3092. # Side effects:
  3093. # None.
  3094. proc tcltest::RestoreLocale {} {
  3095. variable previousLocale
  3096. if {[info commands testlocale] != ""} {
  3097. testlocale ctype $previousLocale
  3098. }
  3099. return
  3100. }
  3101. # tcltest::threadReap --
  3102. #
  3103. # Kill all threads except for the main thread.
  3104. # Do nothing if testthread is not defined.
  3105. #
  3106. # Arguments:
  3107. # none.
  3108. #
  3109. # Results:
  3110. # Returns the number of existing threads.
  3111. #
  3112. # Side Effects:
  3113. # none.
  3114. #
  3115. proc tcltest::threadReap {} {
  3116. if {[info commands testthread] ne {}} {
  3117. # testthread built into tcltest
  3118. testthread errorproc ThreadNullError
  3119. while {[llength [testthread names]] > 1} {
  3120. foreach tid [testthread names] {
  3121. if {$tid != [mainThread]} {
  3122. catch {
  3123. testthread send -async $tid {testthread exit}
  3124. }
  3125. }
  3126. }
  3127. ## Enter a bit a sleep to give the threads enough breathing
  3128. ## room to kill themselves off, otherwise the end up with a
  3129. ## massive queue of repeated events
  3130. after 1
  3131. }
  3132. testthread errorproc ThreadError
  3133. return [llength [testthread names]]
  3134. } elseif {[info commands thread::id] ne {}} {
  3135. # Thread extension
  3136. thread::errorproc ThreadNullError
  3137. while {[llength [thread::names]] > 1} {
  3138. foreach tid [thread::names] {
  3139. if {$tid != [mainThread]} {
  3140. catch {thread::send -async $tid {thread::exit}}
  3141. }
  3142. }
  3143. ## Enter a bit a sleep to give the threads enough breathing
  3144. ## room to kill themselves off, otherwise the end up with a
  3145. ## massive queue of repeated events
  3146. after 1
  3147. }
  3148. thread::errorproc ThreadError
  3149. return [llength [thread::names]]
  3150. } else {
  3151. return 1
  3152. }
  3153. return 0
  3154. }
  3155. # Initialize the constraints and set up command line arguments
  3156. namespace eval tcltest {
  3157. # Define initializers for all the built-in constraint definitions
  3158. DefineConstraintInitializers
  3159. # Set up the constraints in the testConstraints array to be lazily
  3160. # initialized by a registered initializer, or by "false" if no
  3161. # initializer is registered.
  3162. trace add variable testConstraints read [namespace code SafeFetch]
  3163. # Only initialize constraints at package load time if an
  3164. # [initConstraintsHook] has been predefined. This is only
  3165. # for compatibility support. The modern way to add a custom
  3166. # test constraint is to just call the [testConstraint] command
  3167. # straight away, without all this "hook" nonsense.
  3168. if {[namespace current] eq
  3169. [namespace qualifiers [namespace which initConstraintsHook]]} {
  3170. InitConstraints
  3171. } else {
  3172. proc initConstraintsHook {} {}
  3173. }
  3174. # Define the standard match commands
  3175. customMatch exact [list string equal]
  3176. customMatch glob [list string match]
  3177. customMatch regexp [list regexp --]
  3178. # If the TCLTEST_OPTIONS environment variable exists, configure
  3179. # tcltest according to the option values it specifies. This has
  3180. # the effect of resetting tcltest's default configuration.
  3181. proc ConfigureFromEnvironment {} {
  3182. upvar #0 env(TCLTEST_OPTIONS) options
  3183. if {[catch {llength $options} msg]} {
  3184. Warn "invalid TCLTEST_OPTIONS \"$options\":\n invalid\
  3185. Tcl list: $msg"
  3186. return
  3187. }
  3188. if {[llength $options] % 2} {
  3189. Warn "invalid TCLTEST_OPTIONS: \"$options\":\n should be\
  3190. -option value ?-option value ...?"
  3191. return
  3192. }
  3193. if {[catch {Configure {*}$options} msg]} {
  3194. Warn "invalid TCLTEST_OPTIONS: \"$options\":\n $msg"
  3195. return
  3196. }
  3197. }
  3198. if {[info exists ::env(TCLTEST_OPTIONS)]} {
  3199. ConfigureFromEnvironment
  3200. }
  3201. proc LoadTimeCmdLineArgParsingRequired {} {
  3202. set required false
  3203. if {[info exists ::argv] && ("-help" in $::argv)} {
  3204. # The command line asks for -help, so give it (and exit)
  3205. # right now. ([configure] does not process -help)
  3206. set required true
  3207. }
  3208. foreach hook { PrintUsageInfoHook processCmdLineArgsHook
  3209. processCmdLineArgsAddFlagsHook } {
  3210. if {[namespace current] eq
  3211. [namespace qualifiers [namespace which $hook]]} {
  3212. set required true
  3213. } else {
  3214. proc $hook args {}
  3215. }
  3216. }
  3217. return $required
  3218. }
  3219. # Only initialize configurable options from the command line arguments
  3220. # at package load time if necessary for backward compatibility. This
  3221. # lets the tcltest user call [configure] for themselves if they wish.
  3222. # Traces are established for auto-configuration from the command line
  3223. # if any configurable options are accessed before the user calls
  3224. # [configure].
  3225. if {[LoadTimeCmdLineArgParsingRequired]} {
  3226. ProcessCmdLineArgs
  3227. } else {
  3228. EstablishAutoConfigureTraces
  3229. }
  3230. package provide [namespace tail [namespace current]] $Version
  3231. }