github.com/kolbycrouch/elvish@v0.14.1-0.20210614162631-215b9ac1c423/pkg/eval/purely_eval_test.go (about)

     1  package eval_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	. "src.elv.sh/pkg/eval"
     7  	"src.elv.sh/pkg/testutil"
     8  
     9  	"src.elv.sh/pkg/eval/vals"
    10  	"src.elv.sh/pkg/eval/vars"
    11  	"src.elv.sh/pkg/parse"
    12  )
    13  
    14  func TestPurelyEvalCompound(t *testing.T) {
    15  	home, cleanup := testutil.InTempHome()
    16  	defer cleanup()
    17  
    18  	var tests = []struct {
    19  		code      string
    20  		upto      int
    21  		wantValue string
    22  		wantBad   bool
    23  	}{
    24  		{code: "foobar", wantValue: "foobar"},
    25  		{code: "'foobar'", wantValue: "foobar"},
    26  		{code: "foo'bar'", wantValue: "foobar"},
    27  		{code: "$x", wantValue: "bar"},
    28  		{code: "foo$x", wantValue: "foobar"},
    29  		{code: "foo$x", upto: 3, wantValue: "foo"},
    30  		{code: "~", wantValue: home},
    31  		{code: "~/foo", wantValue: home + "/foo"},
    32  		{code: "$ns:x", wantValue: "foo"},
    33  
    34  		{code: "$bad", wantBad: true},
    35  		{code: "$ns:bad", wantBad: true},
    36  
    37  		{code: "[abc]", wantBad: true},
    38  		{code: "$y", wantBad: true},
    39  		{code: "a[0]", wantBad: true},
    40  		{code: "$@x", wantBad: true},
    41  	}
    42  
    43  	ev := NewEvaler()
    44  	g := NsBuilder{
    45  		"x": vars.NewReadOnly("bar"),
    46  		"y": vars.NewReadOnly(vals.MakeList()),
    47  	}.
    48  		AddNs("ns", NsBuilder{"x": vars.NewReadOnly("foo")}.Ns()).
    49  		Ns()
    50  	ev.AddGlobal(g)
    51  
    52  	for _, test := range tests {
    53  		t.Run(test.code, func(t *testing.T) {
    54  			n := &parse.Compound{}
    55  			err := parse.ParseAs(
    56  				parse.Source{Name: "[test]", Code: test.code}, n, parse.Config{})
    57  			if err != nil {
    58  				panic(err)
    59  			}
    60  
    61  			upto := test.upto
    62  			if upto == 0 {
    63  				upto = -1
    64  			}
    65  			value, ok := ev.PurelyEvalPartialCompound(n, upto)
    66  
    67  			if value != test.wantValue {
    68  				t.Errorf("got value %q, want %q", value, test.wantValue)
    69  			}
    70  			if ok != !test.wantBad {
    71  				t.Errorf("got ok %v, want %v", ok, !test.wantBad)
    72  			}
    73  		})
    74  	}
    75  }