2024-04-13 10:11:44 +02:00
|
|
|
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
|
|
|
|
// All rights reserved.
|
|
|
|
|
|
|
|
// expr_test.go
|
|
|
|
package expr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestExpr(t *testing.T) {
|
|
|
|
type inputType struct {
|
|
|
|
source string
|
|
|
|
wantResult any
|
|
|
|
wantErr error
|
|
|
|
}
|
|
|
|
|
|
|
|
inputs := []inputType{
|
2024-04-20 06:56:26 +02:00
|
|
|
/* 1 */ {`0?{}`, nil, nil},
|
|
|
|
/* 2 */ {`fact=func(n){(n)?{1}::{n*fact(n-1)}}; fact(5)`, int64(120), nil},
|
|
|
|
/* 3 */ {`f=openFile("test-file.txt"); line=readFile(f); closeFile(f); line`, "uno", nil},
|
2024-04-20 08:50:05 +02:00
|
|
|
/* 4 */ {`mynot=func(v){int(v)?{true}::{false}}; mynot(0)`, true, nil},
|
2024-05-06 15:31:28 +02:00
|
|
|
/* 5 */ {`1 ? {1} : [1+0] {3*(1+1)}`, int64(6), nil},
|
2024-05-19 01:38:07 +02:00
|
|
|
/* 6 */ {`
|
2024-04-26 21:03:22 +02:00
|
|
|
ds={
|
|
|
|
"init":func(end){@end=end; @current=0 but true},
|
|
|
|
"current":func(){current},
|
|
|
|
"next":func(){
|
|
|
|
((next=current+1) <= end) ? [true] {@current=next but current} :: {nil}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
it=$(ds,3);
|
|
|
|
it++;
|
|
|
|
it++
|
|
|
|
`, int64(1), nil},
|
|
|
|
}
|
2024-04-13 10:11:44 +02:00
|
|
|
|
2024-05-06 15:31:28 +02:00
|
|
|
succeeded := 0
|
|
|
|
failed := 0
|
|
|
|
|
|
|
|
for i, input := range inputs {
|
2024-04-13 10:11:44 +02:00
|
|
|
var expr Expr
|
|
|
|
var gotResult any
|
|
|
|
var gotErr error
|
|
|
|
|
2024-05-23 07:46:31 +02:00
|
|
|
ctx := NewSimpleStore()
|
2024-04-13 10:11:44 +02:00
|
|
|
// ImportMathFuncs(ctx)
|
|
|
|
// ImportImportFunc(ctx)
|
2024-04-15 06:59:27 +02:00
|
|
|
ImportOsFuncs(ctx)
|
2024-04-13 10:11:44 +02:00
|
|
|
parser := NewParser(ctx)
|
|
|
|
|
2024-05-06 04:21:50 +02:00
|
|
|
logTest(t, i+1, "Expr", input.source, input.wantResult, input.wantErr)
|
2024-04-13 10:11:44 +02:00
|
|
|
|
|
|
|
r := strings.NewReader(input.source)
|
|
|
|
scanner := NewScanner(r, DefaultTranslations())
|
|
|
|
|
|
|
|
good := true
|
|
|
|
if expr, gotErr = parser.Parse(scanner); gotErr == nil {
|
|
|
|
gotResult, gotErr = expr.Eval(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
if gotResult != input.wantResult {
|
|
|
|
t.Errorf("%d: %q -> result = %v [%T], want %v [%T]", i+1, input.source, gotResult, gotResult, input.wantResult, input.wantResult)
|
|
|
|
good = false
|
|
|
|
}
|
|
|
|
|
|
|
|
if gotErr != input.wantErr {
|
|
|
|
if input.wantErr == nil || gotErr == nil || (gotErr.Error() != input.wantErr.Error()) {
|
|
|
|
t.Errorf("%d: %q -> err = <%v>, want <%v>", i+1, input.source, gotErr, input.wantErr)
|
|
|
|
good = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if good {
|
|
|
|
succeeded++
|
|
|
|
} else {
|
|
|
|
failed++
|
|
|
|
}
|
|
|
|
}
|
2024-05-06 04:21:50 +02:00
|
|
|
t.Logf("test count: %d, succeeded count: %d, failed count: %d", len(inputs), succeeded, failed)
|
2024-04-13 10:11:44 +02:00
|
|
|
}
|