From 3cbbe120aa63cc7199a117652f5092f89e2b12c1 Mon Sep 17 00:00:00 2001 From: Qi Xiao Date: Mon, 6 Jan 2020 23:51:55 +0000 Subject: [PATCH] pkg/eval/vals: Add TestValue, and use it to test Pipe. --- pkg/eval/vals/kind_test.go | 1 - pkg/eval/vals/pipe_test.go | 26 +++++++++++++++++++++ pkg/eval/vals/testutils.go | 46 +++++++++++++++++++++++++++++++++++++- 3 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 pkg/eval/vals/pipe_test.go diff --git a/pkg/eval/vals/kind_test.go b/pkg/eval/vals/kind_test.go index ea846dac..c8b41a43 100644 --- a/pkg/eval/vals/kind_test.go +++ b/pkg/eval/vals/kind_test.go @@ -22,6 +22,5 @@ func TestKind(t *testing.T) { Args(xtype(0)).Rets("!!vals.xtype"), Args(os.Stdin).Rets("file"), - Args(NewPipe(os.Stdin, os.Stdout)).Rets("pipe"), }) } diff --git a/pkg/eval/vals/pipe_test.go b/pkg/eval/vals/pipe_test.go new file mode 100644 index 00000000..b9bef2a4 --- /dev/null +++ b/pkg/eval/vals/pipe_test.go @@ -0,0 +1,26 @@ +package vals + +import ( + "fmt" + "os" + "testing" + + "github.com/xiaq/persistent/hash" +) + +func TestPipe(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + panic(err) + } + defer r.Close() + defer w.Close() + + TestValue(t, NewPipe(r, w), Want{ + Kind: "pipe", + Hash: hash.DJB(hash.UIntPtr(r.Fd()), hash.UIntPtr(w.Fd())), + Repr: fmt.Sprintf("", r.Fd(), w.Fd()), + EqualTo: NewPipe(r, w), + NotEqualTo: []interface{}{123, "a string", NewPipe(w, r)}, + }) +} diff --git a/pkg/eval/vals/testutils.go b/pkg/eval/vals/testutils.go index 5590ff8a..7d8da7e4 100644 --- a/pkg/eval/vals/testutils.go +++ b/pkg/eval/vals/testutils.go @@ -1,6 +1,50 @@ package vals -import "github.com/elves/elvish/pkg/tt" +import ( + "testing" + + "github.com/elves/elvish/pkg/tt" +) + +// Want keeps wanted properties of a value. +type Want struct { + Kind string + Hash uint32 + Repr string + + EqualTo interface{} + NotEqualTo []interface{} +} + +// TestValue tests properties of a value. +func TestValue(t *testing.T, v interface{}, want Want) { + t.Helper() + if want.Kind != "" { + if kind := Kind(v); kind != want.Kind { + t.Errorf("Kind() = %s, want %s", kind, want.Kind) + } + } + if want.Hash != 0 { + if hash := Hash(v); hash != want.Hash { + t.Errorf("Hash() = %v, want %v", hash, want.Hash) + } + } + if want.Repr != "" { + if repr := Repr(v, -1); repr != want.Repr { + t.Errorf("Repr() = %q, want %q", repr, want.Repr) + } + } + if want.EqualTo != nil { + if eq := Equal(v, want.EqualTo); !eq { + t.Errorf("Equal(%v) = false, want true", want.EqualTo) + } + } + for _, other := range want.NotEqualTo { + if eq := Equal(v, other); eq { + t.Errorf("Equal(%v) = true, want false", other) + } + } +} // Eq returns a tt.Matcher that matches using the Equal function. func Eq(r interface{}) tt.Matcher { return equalMatcher{r} }