pkg/eval/vals: Add TestValue, and use it to test Pipe.

This commit is contained in:
Qi Xiao 2020-01-06 23:51:55 +00:00
parent 0bb6088790
commit 3cbbe120aa
3 changed files with 71 additions and 2 deletions

View File

@ -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"),
})
}

View File

@ -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("<pipe{%v %v}>", r.Fd(), w.Fd()),
EqualTo: NewPipe(r, w),
NotEqualTo: []interface{}{123, "a string", NewPipe(w, r)},
})
}

View File

@ -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} }