# This file contains support code for the Tcl test suite.  It is
# normally sourced by the individual files in the test suite before
# they run their tests.  This improved approach to testing was designed
# and initially implemented by Mary Ann May-Pumphrey of Sun Microsystems.
#
# Copyright (c) 1990-1994 The Regents of the University of California.
# Copyright (c) 1994-1997 Sun Microsystems, Inc.
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# RCS: @(#) $Id: defs,v 1.3 1999/08/15 19:39:00 mo Exp $

if {! [info exists VERBOSE]} {
    set VERBOSE 0
}
if {! [info exists TESTS]} {
    set TESTS {}
}

# If tests are being run as root, issue a warning message and set a
# variable to prevent some tests from running at all.

set user {}
if {$tcl_platform(platform) == "unix"} {
    catch {set user [exec whoami]}
    if {$user == ""} {
        catch {regexp {^[^(]*\(([^)]*)\)} [exec id] dummy user}
    }
    if {$user == ""} {set user root}
    if {$user == "root"} {
        puts stdout "Warning: you're executing as root.  I'll have to"
        puts stdout "skip some of the tests, since they'll fail as root."
    }
}

# Some of the tests don't work on some system configurations due to
# differences in word length, file system configuration, etc.  In order
# to prevent false alarms, these tests are generally only run in the
# master development directory for Tcl.  The presence of a file
# "doAllTests" in this directory is used to indicate that the non-portable
# tests should be run.

set doNonPortableTests [file exists doAllTests]

# If there is no "memory" command (because memory debugging isn't
# enabled), generate a dummy command that does nothing.

if {[info commands memory] == ""} {
    proc memory args {}
}

# Check configuration information that will determine which tests
# to run.  To do this, create an array testConfig.  Each element
# has a 0 or 1 value, and the following elements are defined:
#	unixOnly -	1 means this is a UNIX platform, so it's OK
#			to run tests that only work under UNIX.
#	macOnly -	1 means this is a Mac platform, so it's OK
#			to run tests that only work on Macs.
#	pcOnly -	1 means this is a PC platform, so it's OK to
#			run tests that only work on PCs.
#	jaclOnly -	1 means we are running in the Jacl
#			interpreter, so it's OK to
#			run tests that only work in Jacl.
#	blendOnly -	1 means we are running Tcl Blend so it's OK to
#			run tests that only work with Tcl Blend.
#	unixOrPc -	1 means this is a UNIX or PC platform.
#	macOrPc -	1 means this is a Mac or PC platform.
#	macOrUnix -	1 means this is a Mac or UNIX platform.
#	nonPortable -	1 means this the tests are being running in
#			the master Tcl/Tk development environment;
#			Some tests are inherently non-portable because
#			they depend on things like word length, file system
#			configuration, window manager, etc.  These tests
#			are only run in the main Tcl development directory
#			where the configuration is well known.  The presence
#			of the file "doAllTests" in this directory indicates
#			that it is safe to run non-portable tests.
#	tempNotPc -	The inverse of pcOnly.  This flag is used to
#			temporarily disable a test.
#	tempNotJacl -   The inverse of jaclOnly.  This flag is used to
#			temporarily disable a test.
#	tempNotJacl -   The inverse of blendOnly.  This flag is used to
#			temporarily disable a test.
#	nonBlockFiles - 1 means this platform supports setting files into
#			nonblocking mode.
#	asyncPipeClose- 1 means this platform supports async flush and
#			async close on a pipe.
#	unixExecs     - 1 means this machine has commands such as 'cat',
#			'echo' etc available.
#	tempRegexpOnly- 0 means regexp is not yet implemented, so we
#			don't run the tests that uses regexp to check
#			the results.

catch {unset testConfig}
if {$tcl_platform(platform) == "unix"} {
    set testConfig(unixOnly) 1
    set testConfig(tempNotPc) 1
} else {
    set testConfig(unixOnly) 0
} 
if {$tcl_platform(platform) == "macintosh"} {
    set testConfig(tempNotPc) 1
    set testConfig(macOnly) 1
} else {
    set testConfig(macOnly) 0
} 
if {$tcl_platform(platform) == "windows"} {
    set testConfig(pcOnly) 1
} else {
    set testConfig(pcOnly) 0
}
if {$tcl_platform(platform) == "java"} {
    set testConfig(jaclOnly) 1
    set testConfig(tempNotBlend) 1
} else {
    set testConfig(blendOnly) 1
    set testConfig(tempNotJacl) 1
}
if [catch {regexp a a}] {
    set testConfig(tempRegexpOnly) 0
} else {
    set testConfig(tempRegexpOnly) 1
}

set testConfig(unixOrPc) [expr $testConfig(unixOnly) || $testConfig(pcOnly)]
set testConfig(macOrPc) [expr $testConfig(macOnly) || $testConfig(pcOnly)]
set testConfig(macOrUnix) [expr $testConfig(macOnly) || $testConfig(unixOnly)]
set testConfig(nonPortable) [file exists doAllTests]

if {! [file exists defs]} {
  puts "ERROR : the defs file must be sourced from the current directory!"
  exit -1
}
set f [open defs r]
if {[expr [catch {fconfigure $f -blocking off}]] == 0} {
    set testConfig(nonBlockFiles) 1
} else {
    set testConfig(nonBlockFiles) 0
}
close $f

# Test for SCO Unix - cannot run async flushing tests because a potential
# problem with select is apparently interfering. (Mark Diekhans).

if {$tcl_platform(platform) == "unix"} {
    if {[catch {exec uname -X | fgrep {Release = 3.2v}}] == 0} {
	set testConfig(asyncPipeClose) 0
    } else {
	set testConfig(asyncPipeClose) 1
    }
} else {
    set testConfig(asyncPipeClose) 1
}

# Test to see if execed commands such as cat, echo, rm and so forth are
# present on this machine.

set testConfig(unixExecs) 1
if {$tcl_platform(platform) == "macintosh"} {
    set testConfig(unixExecs) 0
}
if {($testConfig(unixExecs) == 1) && ($tcl_platform(platform) == "windows")} {
    if {[catch {exec cat defs}] == 1} {
	set testConfig(unixExecs) 0
    }
    if {($testConfig(unixExecs) == 1) && ([catch {exec echo hello}] == 1)} {
	set testConfig(unixExecs) 0
    }
    if {($testConfig(unixExecs) == 1) && \
		([catch {exec sh -c echo hello}] == 1)} {
	set testConfig(unixExecs) 0
    }
    if {($testConfig(unixExecs) == 1) && ([catch {exec wc defs}] == 1)} {
	set testConfig(unixExecs) 0
    }
    if {$testConfig(unixExecs) == 1} {
	exec echo hello > removeMe
        if {[catch {exec rm removeMe}] == 1} {
	    set testConfig(unixExecs) 0
	}
    }
    if {($testConfig(unixExecs) == 1) && ([catch {exec sleep 1}] == 1)} {
	set testConfig(unixExecs) 0
    }
    if {($testConfig(unixExecs) == 1) && \
		([catch {exec fgrep unixExecs defs}] == 1)} {
	set testConfig(unixExecs) 0
    }
    if {($testConfig(unixExecs) == 1) && ([catch {exec ps}] == 1)} {
	set testConfig(unixExecs) 0
    }
    if {($testConfig(unixExecs) == 1) && \
		([catch {exec echo abc > removeMe}] == 0) && \
		([catch {exec chmod 644 removeMe}] == 1) && \
		([catch {exec rm removeMe}] == 0)} {
	set testConfig(unixExecs) 0
    } else {
	catch {exec rm -f removeMe}
    }
    if {($testConfig(unixExecs) == 1) && \
		([catch {exec mkdir removeMe}] == 1)} {
	set testConfig(unixExecs) 0
    } else {
	catch {exec rm -r removeMe}
    }
    if {$testConfig(unixExecs) == 0} {
	puts stdout "Warning: Unix-style executables are not available, so"
	puts stdout "some tests will be skipped."
    }
}    

proc print_verbose {name description script code answer} {
    puts stdout "\n"
    puts stdout "==== $name $description"
    puts stdout "==== Contents of test case:"
    puts stdout "$script"
    if {$code != 0} {
	if {$code == 1} {
	    puts stdout "==== Test generated error:"
	    puts stdout $answer
	} elseif {$code == 2} {
	    puts stdout "==== Test generated return exception;  result was:"
	    puts stdout $answer
	} elseif {$code == 3} {
	    puts stdout "==== Test generated break exception"
	} elseif {$code == 4} {
	    puts stdout "==== Test generated continue exception"
	} else {
	    puts stdout "==== Test generated exception $code;  message was:"
	    puts stdout $answer
	}
    } else {
	puts stdout "==== Result was:"
	puts stdout "$answer"
    }
    flush stdout
}

# test --
# This procedure runs a test and prints an error message if the
# test fails.  If VERBOSE has been set, it also prints a message
# even if the test succeeds.  The test will be skipped if it
# doesn't match the TESTS variable, or if one of the elements
# of "constraints" turns out not to be true.
#
# Arguments:
# name -		Name of test, in the form foo-1.2.
# description -		Short textual description of the test, to
#			help humans understand what it does.
# constraints -		A list of one or more keywords, each of
#			which must be the name of an element in
#			the array "testConfig".  If any of these
#			elements is zero, the test is skipped.
#			This argument may be omitted.
# script -		Script to run to carry out the test.  It must
#			return a result that can be checked for
#			correctness.
# answer -		Expected result from script.

proc test {name description script answer args} {
    global VERBOSE TESTS testConfig
    if {[string compare $TESTS ""] != 0} then {
	set ok 0
	foreach test $TESTS {
	    if [string match $test $name] then {
		set ok 1
		break
	    }
        }
	if !$ok then return
    }
    set i [llength $args]
    if {$i == 0} {
	# Empty body
    } elseif {$i == 1} {
	# "constraints" argument exists;  shuffle arguments down, then
	# make sure that the constraints are satisfied.

	set constraints $script
	set script $answer
	set answer [lindex $args 0]
	foreach constraint $constraints {
	    if {![info exists testConfig($constraint)]
		    || !$testConfig($constraint)} {
		if $VERBOSE then {
		    puts stdout "++++ $name SKIPPED"
                    flush stdout
		}
		return
	    }
	}
    } else {
	error "wrong # args: must be \"test name description ?constraints? script answer\""
    }
    memory tag $name
    flush stdout
# FIXME : verbose printing should be broken up into two parts, it should
# first print the test case, then run it, then print the results
    set code [catch {uplevel $script} result]
    if {$code != 0} {
	print_verbose $name $description $script \
		$code $result
    } elseif {[string compare $result $answer] == 0} then { 
	if $VERBOSE then {
	    if {$VERBOSE > 0} {
		print_verbose $name $description $script \
		    $code $result
	    }
	    puts stdout "++++ $name PASSED"
            flush stdout
	}
    } else { 
	print_verbose $name $description $script \
		$code $result
	puts stdout "---- Result should have been:"
	puts stdout "$answer"
	puts stdout "---- $name FAILED"
        flush stdout
    }
}

proc dotests {file args} {
    global TESTS
    set savedTests $TESTS
    set TESTS $args
    source $file
    set TESTS $savedTests
}

proc normalizeMsg {msg} {
    regsub "\n$" [string tolower $msg] "" msg
    regsub -all "\n\n" $msg "\n" msg
    regsub -all "\n\}" $msg "\}" msg
    return $msg
}

proc makeFile {contents name} {
    set fd [open $name w]
    fconfigure $fd -translation lf
    if {[string index $contents [expr [string length $contents] - 1]] == "\n"} {
	puts -nonewline $fd $contents
    } else {
	puts $fd $contents
    }
    close $fd
}

proc removeFile {name} {
    file delete $name
}

proc makeDirectory {name} {
    file mkdir $name
}

proc removeDirectory {name} {
    file delete -force $name
}

proc viewFile {name} {
    global tcl_platform testConfig
    if {($tcl_platform(platform) == "macintosh") || \
		($testConfig(unixExecs) == 0)} {
	set f [open $name]
	set data [read -nonewline $f]
	close $f
	return $data
    } else {
	exec cat $name
    }
}

# Locate tcltest executable

if {$tcl_platform(platform) != "java"} {
    set tcltest [list [info nameofexecutable]]
    if {$tcltest == "{}"} {
      set tcltest {}
      puts \
	"Unable to find tcltest executable, multiple process tests will fail."
    }
}

proc setupJavaPackage {} {
    global tcl_platform errorInfo

    if {[catch {package require java}]} {
	error "Unable to find the java package. Skipping entire test.:\n$errorInfo"
    }

    if {$tcl_platform(platform) == "java"} {
	set cls tcl.lang.JavaTestExtension
    } else {
	set cls tcl.lang.NativeTestExtension
    }

    if [catch {java::load $cls} errMsg] {
	puts "Unable to load $cls. Some tests may fail.\n$errMsg"
    }
}





# Tcl only implementation of commands defined in generic/tclTest.c


proc testgetplatform { } {
  if {[java::call System getProperty file.separator] == "\\"} {
    return "windows"
  } else {
    if {[java::call System getProperty os.name] == "Mac OS"} {
      return "mac"
    } else {
      return "unix"
    }
  }
}

# Try to set a variable, if it does not exist raise an error

proc testseterr { args } {
  if {[llength $args] == 1} {
    set result "before get"
    set varname [lindex $args 0]
    if {[catch {uplevel 1 [list set $varname]} val]} {
      # There was an error, set an error message
      error $val
    }
    lappend result $val
    return $result
  } elseif {[llength $args] == 2} {
    set result "before set"
    set varname [lindex $args 0]
    uplevel 1 [list set $varname [lindex $args 1]]
    if {[catch {uplevel 1 [list set $varname]} val]} {
      # There was an error, just return the set value
      set val [lindex $args 1]
    }
    lappend result $val
    return $result
  } else {
    error "wrong # args: should be \"testseterr varName ?newValue?\""
  }
}

# Try to set a variable, if it does not exist return {}

proc testsetnoerr { args } {
  if {[llength $args] == 1} {
    set result "before get"
    set varname [lindex $args 0]
    if {[catch {uplevel 1 [list set $varname]} val]} {
      # There was an error, return partial result
      error $result
    }
    lappend result $val
    return $result
  } elseif {[llength $args] == 2} {
    set result "before set"
    set varname [lindex $args 0]
    if {[catch {
      uplevel 1 [list set $varname [lindex $args 1]]
      uplevel 1 [list set $varname]} val]} {
      error $result
    }
    lappend result $val
    return $result
  } else {
    error "wrong # args: should be \"testsetnoerr varName ?newValue?\""
  }
}



