tcltest-2.5.3.tm 101 KB

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