Ejemplo n.º 1
1
func TestClientMassError_json(t *testing.T) {
	cli, srv := net.Pipe()
	go ServeConn(srv)
	client := NewClient(cli)
	defer client.Close()

	for i := len(svcMsg); i < cap(svcMsg); i++ {
		svcMsg <- ""
	}
	defer func() {
		for len(svcMsg) > 0 {
			<-svcMsg
		}
	}()

	wanterr1 := NewError(-32603, "json: cannot unmarshal number into Go value of type string")
	wanterr2 := NewError(-32603, "some other Call failed to unmarshal Reply")

	call2 := client.Go("Svc.Msg", []string{"test"}, nil, nil)
	var badreply string
	err1 := client.Call("Svc.Sum", [2]int{}, &badreply)
	if err1 == nil || !reflect.DeepEqual(ServerError(err1), wanterr1) {
		t.Errorf("%serr1 = %v, wanterr1 = %v", caller(), err1, wanterr1)
	}
	<-call2.Done
	err2 := call2.Error
	if err2 == nil || !reflect.DeepEqual(ServerError(err2), wanterr2) {
		t.Errorf("%serr2 = %v, wanterr2 = %v", caller(), err2, wanterr2)
	}
}
Ejemplo n.º 2
1
func TestPathUnmarshalJSON(t *testing.T) {
	type in struct {
		data string
	}
	type out struct {
		device Path
		err    error
	}

	tests := []struct {
		in  in
		out out
	}{
		{
			in:  in{data: `"/path"`},
			out: out{device: Path("/path")},
		},
		{
			in:  in{data: `"bad"`},
			out: out{device: Path("bad"), err: ErrPathRelative},
		},
	}

	for i, test := range tests {
		var device Path
		err := json.Unmarshal([]byte(test.in.data), &device)
		if !reflect.DeepEqual(test.out.err, err) {
			t.Errorf("#%d: bad error: want %v, got %v", i, test.out.err, err)
		}
		if !reflect.DeepEqual(test.out.device, device) {
			t.Errorf("#%d: bad device: want %#v, got %#v", i, test.out.device, device)
		}
	}
}
Ejemplo n.º 3
1
func validateClusteringFlags(t *testing.T, cfg *config) {
	wcfg := newConfig()
	wcfg.APUrls = []url.URL{{Scheme: "http", Host: "localhost:8000"}, {Scheme: "https", Host: "localhost:8001"}}
	wcfg.ACUrls = []url.URL{{Scheme: "http", Host: "localhost:7000"}, {Scheme: "https", Host: "localhost:7001"}}
	wcfg.ClusterState = embed.ClusterStateFlagExisting
	wcfg.fallback.Set(fallbackFlagExit)
	wcfg.InitialCluster = "0=http://localhost:8000"
	wcfg.InitialClusterToken = "etcdtest"

	if cfg.ClusterState != wcfg.ClusterState {
		t.Errorf("clusterState = %v, want %v", cfg.ClusterState, wcfg.ClusterState)
	}
	if cfg.fallback.String() != wcfg.fallback.String() {
		t.Errorf("fallback = %v, want %v", cfg.fallback, wcfg.fallback)
	}
	if cfg.InitialCluster != wcfg.InitialCluster {
		t.Errorf("initialCluster = %v, want %v", cfg.InitialCluster, wcfg.InitialCluster)
	}
	if cfg.InitialClusterToken != wcfg.InitialClusterToken {
		t.Errorf("initialClusterToken = %v, want %v", cfg.InitialClusterToken, wcfg.InitialClusterToken)
	}
	if !reflect.DeepEqual(cfg.APUrls, wcfg.APUrls) {
		t.Errorf("initial-advertise-peer-urls = %v, want %v", cfg.LPUrls, wcfg.LPUrls)
	}
	if !reflect.DeepEqual(cfg.ACUrls, wcfg.ACUrls) {
		t.Errorf("advertise-client-urls = %v, want %v", cfg.LCUrls, wcfg.LCUrls)
	}
}
Ejemplo n.º 4
0
func Test_runCommand(t *testing.T) {
	cmd := &runCommand{}
	for _, v := range [][]interface{}{
		{"Name", cmd.Name(), "run"},
		{"Alias", cmd.Alias(), ""},
		{"Short", cmd.Short(), "run the your application"},
		{"Usage", cmd.Usage(), "run"},
	} {
		name, actual, expected := v[0], v[1], v[2]
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(".%v expect %v, but %v", name, expected, actual)
		}
	}

	if cmd.flag != nil {
		t.Fatalf("Expect nil, but %v", cmd.flag)
	}
	flags := flag.NewFlagSet("testflags", flag.ExitOnError)
	cmd.DefineFlags(flags)
	flags.Parse([]string{})
	actual, expected := cmd.flag, flags
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
}
Ejemplo n.º 5
0
func TestArgsPeekMulti(t *testing.T) {
	var a Args
	a.Parse("foo=123&bar=121&foo=321&foo=&barz=sdf")

	vv := a.PeekMulti("foo")
	expectedVV := [][]byte{
		[]byte("123"),
		[]byte("321"),
		[]byte(nil),
	}
	if !reflect.DeepEqual(vv, expectedVV) {
		t.Fatalf("unexpected vv\n%#v\nExpecting\n%#v\n", vv, expectedVV)
	}

	vv = a.PeekMulti("aaaa")
	if len(vv) > 0 {
		t.Fatalf("expecting empty result for non-existing key. Got %#v", vv)
	}

	vv = a.PeekMulti("bar")
	expectedVV = [][]byte{[]byte("121")}
	if !reflect.DeepEqual(vv, expectedVV) {
		t.Fatalf("unexpected vv\n%#v\nExpecting\n%#v\n", vv, expectedVV)
	}
}
Ejemplo n.º 6
0
func TestReverse(t *testing.T) {
	oldAppConfig := appConfig
	appConfig = newTestAppConfig()
	defer func() {
		appConfig = oldAppConfig
	}()

	actual := Reverse("root")
	expected := "/"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}

	actual = Reverse("user", 77)
	expected = "/user/77"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}

	actual = Reverse("date", 2013, 10, 26, "naoina")
	expected = "/2013/10/26/user/naoina"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}

	for _, v := range []string{"/hoge.png", "hoge.png"} {
		actual = Reverse("static", v)
		expected = "/static/hoge.png"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %v, but %v", expected, actual)
		}
	}
}
Ejemplo n.º 7
0
func TestCsvPairToRecord(t *testing.T) {
	eRecord := []string{"INVITE", "2daec40c", "548625ac", "dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0", "200", "OK", "1436454408", "*prepaid", "1001", "1002", "", "3401:2069362475", "2"}
	invPr := &UnpairedRecord{Method: "INVITE", Timestamp: time.Date(2015, 7, 9, 15, 6, 48, 0, time.UTC),
		Values: []string{"INVITE", "2daec40c", "548625ac", "dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0", "200", "OK", "1436454408", "*prepaid", "1001", "1002", "", "3401:2069362475"}}
	byePr := &UnpairedRecord{Method: "BYE", Timestamp: time.Date(2015, 7, 9, 15, 6, 50, 0, time.UTC),
		Values: []string{"BYE", "2daec40c", "548625ac", "dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0", "200", "OK", "1436454410", "", "", "", "", "3401:2069362475"}}
	if rec, err := pairToRecord(invPr, byePr); err != nil {
		t.Error(err)
	} else if !reflect.DeepEqual(eRecord, rec) {
		t.Errorf("Expected: %+v, received: %+v", eRecord, rec)
	}
	if rec, err := pairToRecord(byePr, invPr); err != nil {
		t.Error(err)
	} else if !reflect.DeepEqual(eRecord, rec) {
		t.Errorf("Expected: %+v, received: %+v", eRecord, rec)
	}
	if _, err := pairToRecord(byePr, byePr); err == nil || err.Error() != "MISSING_INVITE" {
		t.Error(err)
	}
	if _, err := pairToRecord(invPr, invPr); err == nil || err.Error() != "MISSING_BYE" {
		t.Error(err)
	}
	byePr.Values = []string{"BYE", "2daec40c", "548625ac", "dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0", "200", "OK", "1436454410", "", "", "", "3401:2069362475"} // Took one value out
	if _, err := pairToRecord(invPr, byePr); err == nil || err.Error() != "INCONSISTENT_VALUES_LENGTH" {
		t.Error(err)
	}
}
Ejemplo n.º 8
0
func (self *ContainerSpec) Eq(b *ContainerSpec) bool {
	// Creation within 1s of each other.
	diff := self.CreationTime.Sub(b.CreationTime)
	if (diff > time.Second) || (diff < -time.Second) {
		return false
	}

	if self.HasCpu != b.HasCpu {
		return false
	}
	if !reflect.DeepEqual(self.Cpu, b.Cpu) {
		return false
	}
	if self.HasMemory != b.HasMemory {
		return false
	}
	if !reflect.DeepEqual(self.Memory, b.Memory) {
		return false
	}
	if self.HasNetwork != b.HasNetwork {
		return false
	}
	if self.HasFilesystem != b.HasFilesystem {
		return false
	}
	if self.HasDiskIo != b.HasDiskIo {
		return false
	}
	if self.HasCustomMetrics != b.HasCustomMetrics {
		return false
	}
	return true
}
Ejemplo n.º 9
0
// Tests two Packages for equality, checking only those fields that we care
// about in tests. E.g., ignores fields that contain absolute paths
// (for now).
func checkPackagesEqual(t *testing.T, importPath string, exp, actual *Package) {
	if exp.ImportPath != actual.ImportPath {
		t.Errorf("%s: ImportPath: want %v, got %v", importPath, exp.ImportPath, actual.ImportPath)
	}
	if exp.Name != actual.Name {
		t.Errorf("%s: Name: want %v, got %v", importPath, exp.Name, actual.Name)
	}
	if exp.Goroot != actual.Goroot {
		t.Errorf("%s: Goroot: want %v, got %v", importPath, exp.Goroot, actual.Goroot)
	}
	if exp.Standard != actual.Standard {
		t.Errorf("%s: Standard: want %v, got %v", importPath, exp.Standard, actual.Standard)
	}
	if !reflect.DeepEqual(exp.Imports, actual.Imports) {
		t.Errorf("%s: Imports: want %v, got %v", importPath, exp.Imports, actual.Imports)
	}
	if !reflect.DeepEqual(exp.Deps, actual.Deps) {
		t.Errorf("%s: Deps: want %v, got %v", importPath, exp.Deps, actual.Deps)
	}
	if !reflect.DeepEqual(exp.DepsNotFound, actual.DepsNotFound) {
		t.Errorf("%s: DepsNotFound: want %v, got %v", importPath, exp.DepsNotFound, actual.DepsNotFound)
	}
	if exp.Incomplete != actual.Incomplete {
		t.Errorf("%s: Incomplete: want %v, got %v", importPath, exp.Incomplete, actual.Incomplete)
	}
	checkPackageErrorsEqual(t, importPath, exp.Error, actual.Error)
	if len(exp.DepsErrors) == len(actual.DepsErrors) {
		for i, expe := range exp.DepsErrors {
			actuale := actual.DepsErrors[i]
			checkPackageErrorsEqual(t, importPath, expe, actuale)
		}
	} else {
		t.Errorf("%s: DepsErrors: want len %d (%v), got len %d (%v)", importPath, len(exp.DepsErrors), exp.DepsErrors, len(actual.DepsErrors), actual.DepsErrors)
	}
}
Ejemplo n.º 10
0
func TestPatchQuery(t *testing.T) {
	req, _ := NewRequest("PATCH", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&empty=not",
		strings.NewReader("z=post&both=y&prio=2&empty="))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")

	if q := req.FormValue("q"); q != "foo" {
		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
	}
	if z := req.FormValue("z"); z != "post" {
		t.Errorf(`req.FormValue("z") = %q, want "post"`, z)
	}
	if bq, found := req.PostForm["q"]; found {
		t.Errorf(`req.PostForm["q"] = %q, want no entry in map`, bq)
	}
	if bz := req.PostFormValue("z"); bz != "post" {
		t.Errorf(`req.PostFormValue("z") = %q, want "post"`, bz)
	}
	if qs := req.Form["q"]; !reflect.DeepEqual(qs, []string{"foo", "bar"}) {
		t.Errorf(`req.Form["q"] = %q, want ["foo", "bar"]`, qs)
	}
	if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"y", "x"}) {
		t.Errorf(`req.Form["both"] = %q, want ["y", "x"]`, both)
	}
	if prio := req.FormValue("prio"); prio != "2" {
		t.Errorf(`req.FormValue("prio") = %q, want "2" (from body)`, prio)
	}
	if empty := req.FormValue("empty"); empty != "" {
		t.Errorf(`req.FormValue("empty") = %q, want "" (from body)`, empty)
	}
}
Ejemplo n.º 11
0
// TODO(vmarmol): Refactor to not need this equality comparison.
// ContainerInfo may be (un)marshaled by json or other en/decoder. In that
// case, the Timestamp field in each stats/sample may not be precisely
// en/decoded.  This will lead to small but acceptable differences between a
// ContainerInfo and its encode-then-decode version.  Eq() is used to compare
// two ContainerInfo accepting small difference (<10ms) of Time fields.
func (self *ContainerInfo) Eq(b *ContainerInfo) bool {

	// If both self and b are nil, then Eq() returns true
	if self == nil {
		return b == nil
	}
	if b == nil {
		return self == nil
	}

	// For fields other than time.Time, we will compare them precisely.
	// This would require that any slice should have same order.
	if !reflect.DeepEqual(self.ContainerReference, b.ContainerReference) {
		return false
	}
	if !reflect.DeepEqual(self.Subcontainers, b.Subcontainers) {
		return false
	}
	if !self.Spec.Eq(&b.Spec) {
		return false
	}

	for i, expectedStats := range b.Stats {
		selfStats := self.Stats[i]
		if !expectedStats.Eq(selfStats) {
			return false
		}
	}

	return true
}
Ejemplo n.º 12
0
func TestPoolPubSubCleanup(t *testing.T) {
	d := poolDialer{t: t}
	p := &redis.Pool{
		MaxIdle:   2,
		MaxActive: 2,
		Dial:      d.dial,
	}
	defer p.Close()

	c := p.Get()
	c.Send("SUBSCRIBE", "x")
	c.Close()

	want := []string{"SUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"}
	if !reflect.DeepEqual(d.commands, want) {
		t.Errorf("got commands %v, want %v", d.commands, want)
	}
	d.commands = nil

	c = p.Get()
	c.Send("PSUBSCRIBE", "x*")
	c.Close()

	want = []string{"PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"}
	if !reflect.DeepEqual(d.commands, want) {
		t.Errorf("got commands %v, want %v", d.commands, want)
	}
	d.commands = nil
}
Ejemplo n.º 13
0
func TestCollector(t *testing.T) {
	window := time.Millisecond
	c := xfer.NewCollector(window)

	r1 := report.MakeReport()
	r1.Endpoint.NodeMetadatas["foo"] = report.MakeNodeMetadata()

	r2 := report.MakeReport()
	r2.Endpoint.NodeMetadatas["bar"] = report.MakeNodeMetadata()

	if want, have := report.MakeReport(), c.Report(); !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}

	c.Add(r1)
	if want, have := r1, c.Report(); !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}

	c.Add(r2)

	merged := report.MakeReport()
	merged = merged.Merge(r1)
	merged = merged.Merge(r2)
	if want, have := merged, c.Report(); !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}
Ejemplo n.º 14
0
func TestHTTPClusterClientSyncFail(t *testing.T) {
	cf := newStaticHTTPClientFactory([]staticHTTPResponse{
		{err: errors.New("fail!")},
	})

	hc := &httpClusterClient{
		clientFactory: cf,
		rand:          rand.New(rand.NewSource(0)),
	}
	err := hc.SetEndpoints([]string{"http://127.0.0.1:2379"})
	if err != nil {
		t.Fatalf("unexpected error during setup: %#v", err)
	}

	want := []string{"http://127.0.0.1:2379"}
	got := hc.Endpoints()
	if !reflect.DeepEqual(want, got) {
		t.Fatalf("incorrect endpoints: want=%#v got=%#v", want, got)
	}

	err = hc.Sync(context.Background())
	if err == nil {
		t.Fatalf("got nil error during Sync")
	}

	got = hc.Endpoints()
	if !reflect.DeepEqual(want, got) {
		t.Fatalf("incorrect endpoints after failed Sync: want=%#v got=%#v", want, got)
	}
}
Ejemplo n.º 15
0
func TestMapFilesToFilesystems(t *testing.T) {
	type in struct {
		config types.Config
	}
	type out struct {
		files map[types.Filesystem][]types.File
		err   error
	}

	tests := []struct {
		in  in
		out out
	}{
		{
			in:  in{config: types.Config{}},
			out: out{files: map[types.Filesystem][]types.File{}},
		},
		{
			in:  in{config: types.Config{Storage: types.Storage{Files: []types.File{{Filesystem: "foo"}}}}},
			out: out{err: ErrFilesystemUndefined},
		},
		{
			in: in{config: types.Config{Storage: types.Storage{
				Filesystems: []types.Filesystem{{Name: "fs1"}},
				Files:       []types.File{{Filesystem: "fs1", Path: "/foo"}, {Filesystem: "fs1", Path: "/bar"}},
			}}},
			out: out{files: map[types.Filesystem][]types.File{types.Filesystem{Name: "fs1"}: {{Filesystem: "fs1", Path: "/foo"}, {Filesystem: "fs1", Path: "/bar"}}}},
		},
		{
			in: in{config: types.Config{Storage: types.Storage{
				Filesystems: []types.Filesystem{{Name: "fs1", Path: "/fs1"}, {Name: "fs2", Path: "/fs2"}},
				Files:       []types.File{{Filesystem: "fs1", Path: "/foo"}, {Filesystem: "fs2", Path: "/bar"}},
			}}},
			out: out{files: map[types.Filesystem][]types.File{
				types.Filesystem{Name: "fs1", Path: "/fs1"}: {{Filesystem: "fs1", Path: "/foo"}},
				types.Filesystem{Name: "fs2", Path: "/fs2"}: {{Filesystem: "fs2", Path: "/bar"}},
			}},
		},
		{
			in: in{config: types.Config{Storage: types.Storage{
				Filesystems: []types.Filesystem{{Name: "fs1"}, {Name: "fs1", Path: "/fs1"}},
				Files:       []types.File{{Filesystem: "fs1", Path: "/foo"}, {Filesystem: "fs1", Path: "/bar"}},
			}}},
			out: out{files: map[types.Filesystem][]types.File{
				types.Filesystem{Name: "fs1", Path: "/fs1"}: {{Filesystem: "fs1", Path: "/foo"}, {Filesystem: "fs1", Path: "/bar"}},
			}},
		},
	}

	for i, test := range tests {
		logger := log.New()
		files, err := stage{Util: util.Util{Logger: &logger}}.mapFilesToFilesystems(test.in.config)
		if !reflect.DeepEqual(test.out.err, err) {
			t.Errorf("#%d: bad error: want %v, got %v", i, test.out.err, err)
		}
		if !reflect.DeepEqual(test.out.files, files) {
			t.Errorf("#%d: bad map: want %#v, got %#v", i, test.out.files, files)
		}
	}
}
Ejemplo n.º 16
0
func TestEncodeDecode(t *testing.T) {
	arg := &RegisterRequest{
		Datacenter: "foo",
		Node:       "bar",
		Address:    "baz",
		Service: &NodeService{
			Service: "test",
			Address: "127.0.0.2",
		},
	}
	buf, err := Encode(RegisterRequestType, arg)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	var out RegisterRequest
	err = Decode(buf[1:], &out)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if !reflect.DeepEqual(arg.Service, out.Service) {
		t.Fatalf("bad: %#v %#v", arg.Service, out.Service)
	}
	if !reflect.DeepEqual(arg, &out) {
		t.Fatalf("bad: %#v %#v", arg, out)
	}
}
Ejemplo n.º 17
0
func TestMarshalParsePublicKey(t *testing.T) {
	pub, pubSerialized := getTestKey()
	line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized)

	authKeys := MarshalAuthorizedKey(pub)
	actualFields := strings.Fields(string(authKeys))
	if len(actualFields) == 0 {
		t.Fatalf("failed authKeys: %v", authKeys)
	}

	// drop the comment
	expectedFields := strings.Fields(line)[0:2]

	if !reflect.DeepEqual(actualFields, expectedFields) {
		t.Errorf("got %v, expected %v", actualFields, expectedFields)
	}

	actPub, _, _, _, err := ParseAuthorizedKey([]byte(line))
	if err != nil {
		t.Fatalf("cannot parse %v: %v", line, err)
	}
	if !reflect.DeepEqual(actPub, pub) {
		t.Errorf("got %v, expected %v", actPub, pub)
	}
}
Ejemplo n.º 18
0
// ChangeRequiresRestart returns true if updating the configuration requires a
// complete restart.
func ChangeRequiresRestart(from, to Configuration) bool {
	// Adding, removing or changing folders requires restart
	if !reflect.DeepEqual(from.Folders, to.Folders) {
		return true
	}

	// Removing a device requres restart
	toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
	for _, dev := range to.Devices {
		toDevs[dev.DeviceID] = true
	}
	for _, dev := range from.Devices {
		if _, ok := toDevs[dev.DeviceID]; !ok {
			return true
		}
	}

	// Changing usage reporting to on or off does not require a restart.
	to.Options.URAccepted = from.Options.URAccepted
	to.Options.URUniqueID = from.Options.URUniqueID

	// All of the generic options require restart
	if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
		return true
	}

	return false
}
Ejemplo n.º 19
0
func testStreamExecute(t *testing.T, conn tabletconn.TabletConn) {
	t.Log("testStreamExecute")
	ctx := context.Background()
	stream, errFunc, err := conn.StreamExecute(ctx, streamExecuteQuery, streamExecuteBindVars, streamExecuteTransactionID)
	if err != nil {
		t.Fatalf("StreamExecute failed: %v", err)
	}
	qr, ok := <-stream
	if !ok {
		t.Fatalf("StreamExecute failed: cannot read result1")
	}
	if len(qr.Rows) == 0 {
		qr.Rows = nil
	}
	if !reflect.DeepEqual(*qr, streamExecuteQueryResult1) {
		t.Errorf("Unexpected result1 from StreamExecute: got %v wanted %v", qr, streamExecuteQueryResult1)
	}
	qr, ok = <-stream
	if !ok {
		t.Fatalf("StreamExecute failed: cannot read result2")
	}
	if len(qr.Fields) == 0 {
		qr.Fields = nil
	}
	if !reflect.DeepEqual(*qr, streamExecuteQueryResult2) {
		t.Errorf("Unexpected result2 from StreamExecute: got %v wanted %v", qr, streamExecuteQueryResult2)
	}
	qr, ok = <-stream
	if ok {
		t.Fatalf("StreamExecute channel wasn't closed")
	}
	if err := errFunc(); err != nil {
		t.Fatalf("StreamExecute errFunc failed: %v", err)
	}
}
Ejemplo n.º 20
0
func TestServersRandomize(t *testing.T) {
	opts := DefaultOptions
	opts.Servers = testServers
	nc := &Conn{Opts: opts}
	if err := nc.setupServerPool(); err != nil {
		t.Fatalf("Problem setting up Server Pool: %v\n", err)
	}
	// Build []string from srvPool
	clientServers := []string{}
	for _, s := range nc.srvPool {
		clientServers = append(clientServers, s.url.String())
	}
	// In theory this could happen..
	if reflect.DeepEqual(testServers, clientServers) {
		t.Fatalf("ServerPool list not randomized\n")
	}

	// Now test that we do not randomize if proper flag is set.
	opts = DefaultOptions
	opts.Servers = testServers
	opts.NoRandomize = true
	nc = &Conn{Opts: opts}
	if err := nc.setupServerPool(); err != nil {
		t.Fatalf("Problem setting up Server Pool: %v\n", err)
	}
	// Build []string from srvPool
	clientServers = []string{}
	for _, s := range nc.srvPool {
		clientServers = append(clientServers, s.url.String())
	}
	if !reflect.DeepEqual(testServers, clientServers) {
		t.Fatalf("ServerPool list should not be randomized\n")
	}
}
Ejemplo n.º 21
0
func TestUnmarshal(t *testing.T) {
	for i, tt := range unmarshalTests {
		var scan scanner
		in := []byte(tt.in)
		if err := checkValid(in, &scan); err != nil {
			if !reflect.DeepEqual(err, tt.err) {
				t.Errorf("#%d: checkValid: %#v", i, err)
				continue
			}
		}
		if tt.ptr == nil {
			continue
		}
		// v = new(right-type)
		v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
		if err := Unmarshal([]byte(in), v.Interface()); !reflect.DeepEqual(err, tt.err) {
			t.Errorf("#%d: %v want %v", i, err, tt.err)
			continue
		}
		if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
			t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
			data, _ := Marshal(v.Elem().Interface())
			println(string(data))
			data, _ = Marshal(tt.out)
			println(string(data))
			continue
		}
	}
}
func TestSort(t *testing.T) {
	sorted_loglines, err := Parse("fixtures/sorted.out")
	if err != nil {
		t.Error(err)
	}
	if len(sorted_loglines) != 11 {
		t.Errorf("Logline length mismatch: %v != 11", len(sorted_loglines))
	}
	unsorted_loglines, err := Parse("fixtures/unsorted.out")
	if err != nil {
		t.Error(err)
	}
	if len(unsorted_loglines) != 11 {
		t.Errorf("Logline length mismatch: %v != 11", len(unsorted_loglines))
	}
	if reflect.DeepEqual(sorted_loglines, unsorted_loglines) {
		t.Error("Unsorted loglines match sorted loglines.")
	}
	sort.Sort(ByTime(unsorted_loglines))
	if !reflect.DeepEqual(sorted_loglines, unsorted_loglines) {
		t.Error("Sorted loglines do not match.")
	}
	sort.Sort(ByTime(sorted_loglines))
	if !reflect.DeepEqual(sorted_loglines, unsorted_loglines) {
		t.Error("Sorted loglines do not match after unnecessary sort.")
	}
}
Ejemplo n.º 23
0
func TestMatch(t *testing.T) {
	ctxt := Default
	what := "default"
	match := func(tag string, want map[string]bool) {
		m := make(map[string]bool)
		if !ctxt.match(tag, m) {
			t.Errorf("%s context should match %s, does not", what, tag)
		}
		if !reflect.DeepEqual(m, want) {
			t.Errorf("%s tags = %v, want %v", tag, m, want)
		}
	}
	nomatch := func(tag string, want map[string]bool) {
		m := make(map[string]bool)
		if ctxt.match(tag, m) {
			t.Errorf("%s context should NOT match %s, does", what, tag)
		}
		if !reflect.DeepEqual(m, want) {
			t.Errorf("%s tags = %v, want %v", tag, m, want)
		}
	}

	match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
	match(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
	nomatch(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})

	what = "modified"
	ctxt.BuildTags = []string{"foo"}
	match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
	match(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
	nomatch(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
	match(runtime.GOOS+","+runtime.GOARCH+",!bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
	nomatch(runtime.GOOS+","+runtime.GOARCH+",bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
	nomatch("!", map[string]bool{})
}
Ejemplo n.º 24
0
func assertRequest(got http.Request, wantMethod string, wantURL *url.URL, wantHeader http.Header, wantBody []byte) error {
	if wantMethod != got.Method {
		return fmt.Errorf("want.Method=%#v got.Method=%#v", wantMethod, got.Method)
	}

	if !reflect.DeepEqual(wantURL, got.URL) {
		return fmt.Errorf("want.URL=%#v got.URL=%#v", wantURL, got.URL)
	}

	if !reflect.DeepEqual(wantHeader, got.Header) {
		return fmt.Errorf("want.Header=%#v got.Header=%#v", wantHeader, got.Header)
	}

	if got.Body == nil {
		if wantBody != nil {
			return fmt.Errorf("want.Body=%v got.Body=%v", wantBody, got.Body)
		}
	} else {
		if wantBody == nil {
			return fmt.Errorf("want.Body=%v got.Body=%s", wantBody, got.Body)
		} else {
			gotBytes, err := ioutil.ReadAll(got.Body)
			if err != nil {
				return err
			}

			if !reflect.DeepEqual(wantBody, gotBytes) {
				return fmt.Errorf("want.Body=%s got.Body=%s", wantBody, gotBytes)
			}
		}
	}

	return nil
}
Ejemplo n.º 25
0
func TestPixels(t *testing.T) {
	rgba := decodeFile(t, "rgba.png")
	allExpected := []*Pixel{
		{Red: 255},
		{Green: 255},
		{Blue: 255},
		{Opacity: 127},
	}
	leftExpected := []*Pixel{
		allExpected[0],
		allExpected[2],
	}
	rightExpected := []*Pixel{
		allExpected[1],
		allExpected[3],
	}
	runPixelTests := func() {
		px1, err := rgba.Pixels(rgba.Rect())
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(px1, allExpected) {
			t.Errorf("expecting pixels %v, got %v instead", allExpected, px1)
		}
		px2, err := rgba.Pixels(Rect{Width: 1, Height: 2})
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(px2, leftExpected) {
			t.Errorf("expecting left pixels %v, got %v instead", leftExpected, px2)
		}
		px3, err := rgba.Pixels(Rect{X: 1, Width: 1, Height: 2})
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(px3, rightExpected) {
			t.Errorf("expecting right pixels %v, got %v instead", rightExpected, px3)
		}
	}
	// First test with the image as it's loaded
	runPixelTests()
	// Change the green pixel to blue and test again
	if err := rgba.SetPixel(1, 0, &Pixel{Blue: 255}); err != nil {
		t.Fatal(err)
	}
	allExpected[1].Green = 0
	allExpected[1].Blue = 255
	runPixelTests()
	// Encode the image, decode it and check again
	var buf bytes.Buffer
	if err := rgba.Encode(&buf, nil); err != nil {
		t.Fatal(err)
	}
	var err error
	rgba, err = DecodeData(buf.Bytes())
	if err != nil {
		t.Fatal(err)
	}
	runPixelTests()
}
Ejemplo n.º 26
0
func TestBuilderPrepare_VBoxManage(t *testing.T) {
	var b Builder
	config := testConfig()

	// Test with empty
	delete(config, "vboxmanage")
	err := b.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if !reflect.DeepEqual(b.config.VBoxManage, [][]string{}) {
		t.Fatalf("bad: %#v", b.config.VBoxManage)
	}

	// Test with a good one
	config["vboxmanage"] = [][]interface{}{
		[]interface{}{"foo", "bar", "baz"},
	}

	b = Builder{}
	err = b.Prepare(config)
	if err != nil {
		t.Fatalf("should not have error: %s", err)
	}

	expected := [][]string{
		[]string{"foo", "bar", "baz"},
	}

	if !reflect.DeepEqual(b.config.VBoxManage, expected) {
		t.Fatalf("bad: %#v", b.config.VBoxManage)
	}
}
Ejemplo n.º 27
0
func validateMemberFlags(t *testing.T, cfg *config) {
	wcfg := &embed.Config{
		Dir:          "testdir",
		LPUrls:       []url.URL{{Scheme: "http", Host: "localhost:8000"}, {Scheme: "https", Host: "localhost:8001"}},
		LCUrls:       []url.URL{{Scheme: "http", Host: "localhost:7000"}, {Scheme: "https", Host: "localhost:7001"}},
		MaxSnapFiles: 10,
		MaxWalFiles:  10,
		Name:         "testname",
		SnapCount:    10,
	}

	if cfg.Dir != wcfg.Dir {
		t.Errorf("dir = %v, want %v", cfg.Dir, wcfg.Dir)
	}
	if cfg.MaxSnapFiles != wcfg.MaxSnapFiles {
		t.Errorf("maxsnap = %v, want %v", cfg.MaxSnapFiles, wcfg.MaxSnapFiles)
	}
	if cfg.MaxWalFiles != wcfg.MaxWalFiles {
		t.Errorf("maxwal = %v, want %v", cfg.MaxWalFiles, wcfg.MaxWalFiles)
	}
	if cfg.Name != wcfg.Name {
		t.Errorf("name = %v, want %v", cfg.Name, wcfg.Name)
	}
	if cfg.SnapCount != wcfg.SnapCount {
		t.Errorf("snapcount = %v, want %v", cfg.SnapCount, wcfg.SnapCount)
	}
	if !reflect.DeepEqual(cfg.LPUrls, wcfg.LPUrls) {
		t.Errorf("listen-peer-urls = %v, want %v", cfg.LPUrls, wcfg.LPUrls)
	}
	if !reflect.DeepEqual(cfg.LCUrls, wcfg.LCUrls) {
		t.Errorf("listen-client-urls = %v, want %v", cfg.LCUrls, wcfg.LCUrls)
	}
}
Ejemplo n.º 28
0
// TestErrEntryNotFound checks that we wrap a zero-length list of results correctly if we search for a unique entry
func TestErrEntryNotFound(t *testing.T) {
	testConfig := testclient.NewConfig(testclient.New())
	testSearchRequest := &ldap.SearchRequest{
		BaseDN:       "dc=example,dc=com",
		Scope:        ldap.ScopeWholeSubtree,
		DerefAliases: int(DefaultDerefAliases),
		SizeLimit:    DefaultSizeLimit,
		TimeLimit:    DefaultTimeLimit,
		TypesOnly:    DefaultTypesOnly,
		Filter:       "(objectClass=*)",
		Attributes:   append(DefaultAttributes),
		Controls:     DefaultControls,
	}

	expectedErr := &errEntryNotFound{baseDN: "dc=example,dc=com", filter: "(objectClass=*)"}

	// test that a unique search errors on no result
	if _, err := QueryForUniqueEntry(testConfig, testSearchRequest); !reflect.DeepEqual(err, expectedErr) {
		t.Errorf("query for unique entry did not get correct error:\n\texpected:\n\t%v\n\tgot:\n\t%v", expectedErr, err)
	}

	// test that a non-unique search doesn't error
	if _, err := QueryForEntries(testConfig, testSearchRequest); !reflect.DeepEqual(err, nil) {
		t.Errorf("query for entries did not get correct error:\n\texpected:\n\t%v\n\tgot:\n\t%v", nil, err)
	}
}
Ejemplo n.º 29
0
func TestInspectContainer(t *testing.T) {
	server := DockerServer{}
	addContainers(&server, 2)
	server.buildMuxer()
	recorder := httptest.NewRecorder()
	path := fmt.Sprintf("/containers/%s/json", server.containers[0].ID)
	request, _ := http.NewRequest("GET", path, nil)
	server.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusOK {
		t.Errorf("InspectContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code)
	}
	expected := server.containers[0]
	var got docker.Container
	err := json.NewDecoder(recorder.Body).Decode(&got)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(got.Config, expected.Config) {
		t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got)
	}
	if !reflect.DeepEqual(got.NetworkSettings, expected.NetworkSettings) {
		t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got)
	}
	got.State.StartedAt = expected.State.StartedAt
	got.State.FinishedAt = expected.State.FinishedAt
	got.Config = expected.Config
	got.Created = expected.Created
	got.NetworkSettings = expected.NetworkSettings
	if !reflect.DeepEqual(got, *expected) {
		t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got)
	}
}
Ejemplo n.º 30
0
func TestWorkspaceUsersService_Update(t *testing.T) {
	setup()
	defer teardown()

	input := &WorkspaceUser{ID: 1}

	mux.HandleFunc("/workspace_users/1", func(w http.ResponseWriter, r *http.Request) {
		v := new(WorkspaceUserCreate)
		json.NewDecoder(r.Body).Decode(v)

		testMethod(t, r, "PUT")
		if !reflect.DeepEqual(v.WorkspaceUser, input) {
			t.Errorf("Request body = %+v, want %+v", v, input)
		}

		fmt.Fprint(w, `{"data":{"id": 1}}`)
	})

	result, err := client.WorkspaceUsers.Update(input)
	if err != nil {
		t.Errorf("WorkspaceUsers.Update returned error: %v", err)
	}

	want := &WorkspaceUser{ID: 1}
	if !reflect.DeepEqual(result, want) {
		t.Errorf("WorkspaceUsers.Update returned %v, want %v", result, want)
	}
}