github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/eval/purely_eval_test.go (about)

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