示例#1
0
文件: context_test.go 项目: gourd/kit
func TestSetGet(t *testing.T) {

	type tempKey int

	const (
		srcKey tempKey = iota
		key
	)

	randString := func(n int) string {
		var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
		b := make([]rune, n)
		for i := range b {
			b[i] = letterRunes[rand.Intn(len(letterRunes))]
		}
		return string(b)
	}

	msg := randString(20)
	ch := make(chan int)

	// prepare the context
	ctx := func(msg interface{}, ch chan<- int) context.Context {

		dummySrc := func() (conn store.Conn, err error) {
			conn = tConn{msg, ch}
			return
		}

		factory := store.NewFactory()
		factory.SetSource(srcKey, store.SourceFunc(dummySrc))
		factory.Set(key, srcKey, func(sess interface{}) (s store.Store, err error) {
			err = fmt.Errorf("%s", sess)
			return
		})

		return store.WithFactory(context.Background(), factory)

	}(msg, ch)

	// get a store
	if _, err := store.Get(ctx, key); err == nil {
		t.Error("unexpected nil error")
	} else if want, have := msg, err.Error(); want != have {
		t.Errorf("expected %#v, got %#v", want, have)
	}

	// test if store would close before timeout
	d, _ := time.ParseDuration("1s")
	timeout := time.After(d)
	store.CloseAllIn(ctx)

	select {
	case <-timeout:
		t.Error("tConn not closed before timeout")
	case <-ch:
		t.Log("tConn closed")
	}

}
示例#2
0
文件: factory_test.go 项目: gourd/kit
func TestFactory_source(t *testing.T) {
	dummySrc1 := func() (conn store.Conn, err error) {
		err = fmt.Errorf("hello dummySrc")
		return
	}

	factory := store.NewFactory()
	factory.SetSource(store.DefaultSrc, store.SourceFunc(dummySrc1))
	dummySrc2 := factory.GetSource(store.DefaultSrc)

	if _, err1 := dummySrc1(); err1 == nil {
		t.Errorf("unexpected nil value")
	} else if _, err2 := dummySrc2.Open(); err2 == nil {
		t.Errorf("unexpected nil value")
	} else if want, have := err1.Error(), err2.Error(); want != have {
		t.Errorf("expected %#v, got %#v", want, have)
	}
}