source [file dirname [info script]]/testing.tcl

needs cmd load
needs cmd interp

# In order to test loadable modules we need a working build-jim-ext
# (from the same directory as jimsh).
# And to support an uninstalled jimsh, we need to explicitly use jimsh
# and add an include path to the parent dir and also to the build dir (in case it is different)
set topdir [file dirname [file dirname [info script]]]
set builddir [file dirname [info nameofexecutable]]
set buildjimext [list [info nameofexecutable] [file join $builddir build-jim-ext] -I$topdir -L$topdir -I$builddir -L$builddir]

# loadtest.c is in the same directory as this script
set src [file join [file dirname [info script]] loadtest.c]

catch {
	exec {*}$buildjimext $src
} msg opts
if {![file exists loadtest.so]} {
	#puts [errorInfo $msg $opts(-errorinfo)]
	skiptest "  (no working build-jim-ext)"
}

test load-1.0 {load usage} -body {
	load
} -returnCodes error -result {wrong # args: should be "load libraryFile"}

# Now everything is done in a child interpreter so that
# because loadable modules only get unloaded on interpreter exit
test load-1.1 {load initial} {
	set interp [interp]
	$interp eval {exists -command loadtest}
} {0}

test load-1.2 {create loadable extension} -body {
	exec {*}$buildjimext $src
	file exists loadtest.so
} -result {1}

test load-1.3 {load dynamic extension} -body {
	$interp eval {
		load ./loadtest.so
		exists -command loadtest
	}
} -result {1}

test load-1.4 {run dynamic extension command} -body {
	$interp eval {
		loadtest test abc
	}
} -result {abc}

test load-1.5 {load invalid dynamic extension} -body {
	$interp eval {
		load nonexistent
	}
} -returnCodes error -match glob -result {error loading extension "nonexistent": *}

$interp delete

test load-1.6 {load via package require} {
	set interp [interp]
	$interp eval {
		lappend auto_path [pwd]
		package require loadtest
		exists -command loadtest
	}
} {1}

$interp delete

test load-2.1 {loadable extension with full path} -body {
	set interp [interp]
	exec {*}$buildjimext $src
	$interp eval {
		load [pwd]/loadtest.so
		loadtest test def
	}
} -result {def} -cleanup {
	$interp delete
}

test load-2.2 {loadable extension without extension} -body {
	set interp [interp]
	file rename loadtest.so loadtest
	$interp eval {
		load ./loadtest
		loadtest test def
	}
} -result {def} -cleanup {
	$interp delete
	file delete loadtest
}

test load-2.1 {loadable extension with no entrypoint} -body {
	set interp [interp]
	exec {*}$buildjimext --notest -DNO_ENTRYPOINT $src
	$interp eval {
		load ./loadtest.so
	}
} -returnCodes error -result {No Jim_loadtestInit symbol found in extension ./loadtest.so} -cleanup {
	$interp delete
}

file delete loadtest.so

testreport
