Exemplo n.º 1
0
func TestCmdScoreLess(t *testing.T) {
	t.Parallel()
	scores := cmdScores([]cmdScore{
		{levenshtein: 1, jaroWinkler: 0.9},
		{levenshtein: 2, jaroWinkler: 0.8},
	})

	ensure.True(t, scores.Less(0, 1))

	scores = cmdScores([]cmdScore{
		{levenshtein: 1, jaroWinkler: 0.9},
		{levenshtein: 1, jaroWinkler: 0.8},
	})

	ensure.True(t, scores.Less(0, 1))

	scores = cmdScores([]cmdScore{
		{levenshtein: 1, jaroWinkler: 0.8},
		{levenshtein: 1, jaroWinkler: 0.9},
	})

	ensure.False(t, scores.Less(0, 1))

	scores = cmdScores([]cmdScore{
		{levenshtein: 2, jaroWinkler: 0.9},
		{levenshtein: 1, jaroWinkler: 0.8},
	})

	ensure.False(t, scores.Less(0, 1))
}
Exemplo n.º 2
0
func TestShouldFilterOp(t *testing.T) {
	t.Parallel()

	ensure.True(t, shouldFilterOp(&Op{Type: Update}, []OpType{Update}))
	ensure.True(t, shouldFilterOp(&Op{Type: Update}, []OpType{Update, Query}))
	ensure.True(t, shouldFilterOp(&Op{Type: Query}, []OpType{Update, Query}))
	ensure.False(t, shouldFilterOp(&Op{Type: Command}, []OpType{Update, Query}))
	ensure.False(t, shouldFilterOp(&Op{Type: Command}, []OpType{}))
}
Exemplo n.º 3
0
func TestIsFileName(t *testing.T) {
	t.Parallel()

	ensure.True(t, isFilename("file"))
	ensure.True(t, isFilename("star\\*"))
	ensure.True(t, isFilename("bracket\\["))
	ensure.True(t, isFilename("question\\?"))

	ensure.False(t, isFilename("*"))
	ensure.False(t, isFilename("?"))
	ensure.False(t, isFilename("["))
}
Exemplo n.º 4
0
func TestCancelRequest(t *testing.T) {
	var called bool
	timer := time.AfterFunc(time.Hour, func() { called = true })
	var r Transport
	r.CancelRequest(&http.Request{
		Body: &bodyCloser{
			timer: timer,
		},
	})
	ensure.False(t, called)
	ensure.False(t, timer.Stop())
}
func TestAcceptsPath(t *testing.T) {
	t.Parallel()
	i := iosSymbolUploader{Path: testDwarfPath}
	ensure.True(t, i.acceptsPath())
	i.Path = ""
	ensure.False(t, i.acceptsPath())
}
Exemplo n.º 6
0
// Verify if the items being read are as expected.
func CheckOpsReader(t *testing.T, loader OpsReader) {
	expectedOpsRead := 0
	const startingTs = 1396456709420
	for op := loader.Next(); op != nil; op = loader.Next() {
		expectedOpsRead += 1
		ensure.NotNil(t, op)
		ensure.DeepEqual(t, loader.OpsRead(), expectedOpsRead)

		// check the "ts" field
		CheckTime(t, float64(startingTs+loader.OpsRead()), op.Timestamp)

		// check the insert doc
		// certain key exists
		for i := 1; i <= 5; i++ {
			logTypeKey := fmt.Sprintf("logType%d", i)
			logType, ok := GetElem(op.InsertDoc, logTypeKey)
			if i != expectedOpsRead {
				ensure.False(t, ok)
				ensure.Nil(t, logType)
			} else {
				ensure.True(t, ok)
				ensure.NotNil(t, logType)
			}
		}
		// check the value for the shared key
		message := fmt.Sprintf("m%d", expectedOpsRead)
		actualMessage, ok := GetElem(op.InsertDoc, "message")
		ensure.True(t, ok)
		ensure.DeepEqual(t, actualMessage.(string), message)
	}
	ensure.DeepEqual(t, expectedOpsRead, 5)
}
Exemplo n.º 7
0
func TestCheckExistingWithoutDesiredBindsWithRemoveExisting(t *testing.T) {
	const imageID = "ii1"
	const imageName = "in1"
	container := &Container{
		removeExisting: true,
		containerConfig: &dockerclient.ContainerConfig{
			Image: imageName,
		},
		hostConfig: &dockerclient.HostConfig{
			Binds: []string{"a:b"},
		},
	}
	client := &mockClient{
		listImages: func() ([]*dockerclient.Image, error) {
			return []*dockerclient.Image{
				{
					RepoTags: []string{imageName},
					Id:       imageID,
				},
			}, nil
		},
	}
	ci := &dockerclient.ContainerInfo{
		Image:   imageID,
		Id:      "y",
		Config:  &dockerclient.ContainerConfig{},
		Volumes: map[string]string{"a": "d"},
	}
	ok, err := container.checkExisting(client, ci)
	ensure.Nil(t, err)
	ensure.False(t, ok)
}
Exemplo n.º 8
0
func TestCheckExistingWithoutDesiredBinds(t *testing.T) {
	const imageID = "ii1"
	const imageName = "in1"
	container := &Container{
		containerConfig: &dockerclient.ContainerConfig{
			Image: imageName,
		},
		hostConfig: &dockerclient.HostConfig{
			Binds: []string{"a:b"},
		},
	}
	client := &mockClient{
		listImages: func() ([]*dockerclient.Image, error) {
			return []*dockerclient.Image{
				{
					RepoTags: []string{imageName},
					Id:       imageID,
				},
			}, nil
		},
	}
	ci := &dockerclient.ContainerInfo{
		Image:  imageID,
		Id:     "y",
		Config: &dockerclient.ContainerConfig{},
	}
	ok, err := container.checkExisting(client, ci)
	ensure.Err(t, err, regexp.MustCompile("but desired volumes are"))
	ensure.False(t, ok)
}
Exemplo n.º 9
0
func TestCheckExistingWithoutDesiredImageWithRemoveExisting(t *testing.T) {
	const image = "x"
	container := &Container{
		containerConfig: &dockerclient.ContainerConfig{
			Image: image,
		},
		removeExisting: true,
	}
	client := &mockClient{
		listImages: func() ([]*dockerclient.Image, error) {
			return []*dockerclient.Image{
				{
					RepoTags: []string{image},
					Id:       "y",
				},
			}, nil
		},
	}
	ci := &dockerclient.ContainerInfo{
		Image: "z",
		Id:    "y",
	}
	ok, err := container.checkExisting(client, ci)
	ensure.Nil(t, err)
	ensure.False(t, ok)
}
Exemplo n.º 10
0
func TestWriteBatchIterator(t *testing.T) {
	db := newTestDB(t, "TestWriteBatchIterator", nil)
	defer db.Close()

	var (
		givenKey1 = []byte("key1")
		givenVal1 = []byte("val1")
		givenKey2 = []byte("key2")
	)
	// create and fill the write batch
	wb := NewWriteBatch()
	defer wb.Destroy()
	wb.Put(givenKey1, givenVal1)
	wb.Delete(givenKey2)
	ensure.DeepEqual(t, wb.Count(), 2)

	// iterate over the batch
	iter := wb.NewIterator()
	ensure.True(t, iter.Next())
	record := iter.Record()
	ensure.DeepEqual(t, record.Type, WriteBatchRecordTypeValue)
	ensure.DeepEqual(t, record.Key, givenKey1)
	ensure.DeepEqual(t, record.Value, givenVal1)

	ensure.True(t, iter.Next())
	record = iter.Record()
	ensure.DeepEqual(t, record.Type, WriteBatchRecordTypeDeletion)
	ensure.DeepEqual(t, record.Key, givenKey2)

	// there shouldn't be any left
	ensure.False(t, iter.Next())
}
Exemplo n.º 11
0
func TestGetElem(t *testing.T) {
	doc := bson.D{{"a", 1}}
	value, exists := GetElem(doc, "a")
	ensure.True(t, exists)
	ensure.DeepEqual(t, value.(int), 1)
	value, exists = GetElem(doc, "b")
	ensure.False(t, exists)
	ensure.Nil(t, value)
}
Exemplo n.º 12
0
func TestFunctionHookExists(t *testing.T) {
	t.Parallel()
	h := newFunctionsHarness(t)
	c := &configureCmd{}
	exists, err := c.functionHookExists(h.env, "foo")
	ensure.Nil(t, err)
	ensure.True(t, exists)

	exists, err = c.functionHookExists(h.env, "bar")
	ensure.Nil(t, err)
	ensure.False(t, exists)
}
Exemplo n.º 13
0
func TestTriggerHookExists(t *testing.T) {
	t.Parallel()
	h := newTriggersHarness(t)
	c := &configureCmd{}
	exists, err := c.triggerHookExists(h.env, "foo", "beforeSave")
	ensure.Nil(t, err)
	ensure.True(t, exists)

	exists, err = c.triggerHookExists(h.env, "bar", "other")
	ensure.Nil(t, err)
	ensure.False(t, exists)
}
Exemplo n.º 14
0
func TestPruneEmptyKeys(t *testing.T) {
	t.Parallel()
	// Check findAndModify and update structures to ensure nil $unsets are removed
	testOps := []Op{
		Op{
			Ns:        "foo.bar",
			Timestamp: time.Unix(1396457119, int64(032*time.Millisecond)),
			Type:      Update,
			QueryDoc:  bson.D{{"_id", "foo"}},
			UpdateDoc: bson.D{{"$set", bson.D{{"a", 1}}}, {"$unset", bson.D{}}},
		},
		Op{
			Ns:        "foo.$cmd",
			Timestamp: time.Unix(1396457119, int64(032*time.Millisecond)),
			Type:      Command,
			CommandDoc: bson.D{
				{"findandmodify", "bar"},
				{"query", bson.D{{"_id", "foo"}}},
				{"update", bson.D{{"$set", bson.D{{"b", 1}}}, {"$unset", bson.D{}}}},
			},
		},
	}
	reader := newMockOpsStreamReader(t, testOps)
	err, loader := NewByLineOpsReader(reader, logger, "")
	ensure.Nil(t, err)

	for op := loader.Next(); op != nil; op = loader.Next() {
		if op.Type == Command {
			updateDoc, ok := GetElem(op.CommandDoc, "update")
			ensure.True(t, ok)
			_, found := GetElem(updateDoc.(bson.D), "$unset")
			ensure.False(t, found)
		} else if op.Type == Update {
			_, found := GetElem(op.UpdateDoc, "$unset")
			ensure.False(t, found)
		}
	}
}
Exemplo n.º 15
0
func TestCheckExistingImageIdentifyError(t *testing.T) {
	givenErr := errors.New("")
	const image = "x"
	container := &Container{
		containerConfig: &dockerclient.ContainerConfig{
			Image: image,
		},
	}
	client := &mockClient{
		listImages: func() ([]*dockerclient.Image, error) {
			return nil, givenErr
		},
	}
	ok, err := container.checkExisting(client, &dockerclient.ContainerInfo{Image: "z"})
	ensure.True(t, stackerr.HasUnderlying(err, stackerr.Equals(givenErr)))
	ensure.False(t, ok)
}
Exemplo n.º 16
0
func TestApplyForceRemoveExisting(t *testing.T) {
	const removeID = "y"
	const newID = "z"
	givenContainerConfig := &dockerclient.ContainerConfig{Image: "foo"}
	var removeCalls, inspectCalls, createCalls, startCalls int
	container, err := NewContainer(
		ContainerName("x"),
		ContainerConfig(givenContainerConfig),
		ContainerForceRemoveExisting(),
	)
	ensure.Nil(t, err)
	client := &mockClient{
		removeContainer: func(id string, force, volumes bool) error {
			removeCalls++
			ensure.DeepEqual(t, id, removeID)
			ensure.True(t, force)
			ensure.False(t, volumes)
			return nil
		},
		inspectContainer: func(name string) (*dockerclient.ContainerInfo, error) {
			inspectCalls++
			switch inspectCalls {
			case 1:
				return &dockerclient.ContainerInfo{Id: removeID}, nil
			case 2:
				return &dockerclient.ContainerInfo{Id: newID}, nil
			}
			panic("not reached")
		},
		createContainer: func(config *dockerclient.ContainerConfig, name string) (string, error) {
			createCalls++
			return "", nil
		},
		startContainer: func(id string, config *dockerclient.HostConfig) error {
			startCalls++
			ensure.DeepEqual(t, id, newID)
			return nil
		},
	}
	ensure.Nil(t, container.Apply(client))
	ensure.DeepEqual(t, removeCalls, 1)
	ensure.DeepEqual(t, inspectCalls, 2)
	ensure.DeepEqual(t, createCalls, 1)
	ensure.DeepEqual(t, startCalls, 1)
}
Exemplo n.º 17
0
func TestHash(t *testing.T) {
	db := New(newRocksDB(t))
	defer db.Close()

	h := db.Hash([]byte("user"))
	ensure.Nil(t, h.Set([]byte("name"), []byte("latermoon")))
	ensure.Nil(t, h.Set([]byte("age"), []byte("28")))
	ensure.Nil(t, h.Set([]byte("sex"), []byte("Male")))

	val, err := h.Get([]byte("name"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, val, []byte("latermoon"))

	val, err = h.Get([]byte("age"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, val, []byte("28"))

	val, err = h.Get([]byte("sex"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, val, []byte("Male"))

	// Exist and remove
	exist, err := h.Exist([]byte("age"))
	ensure.Nil(t, err)
	ensure.True(t, exist)

	err = h.Remove([]byte("name"))
	ensure.Nil(t, err)

	exist, err = h.Exist([]byte("name"))
	ensure.Nil(t, err)
	ensure.False(t, exist)

	vals, err := h.MGet([]byte("age"), []byte("sex"))
	ensure.Nil(t, err)
	ensure.True(t, len(vals) == 2)
	ensure.DeepEqual(t, vals[0], []byte("28"), vals[1], []byte("Male"))

	h.drop()

	db.RangeEnumerate([]byte{0}, []byte{'z'}, IterForward, func(i int, key, value []byte, quit *bool) {
		t.Log(i, string(key), string(value))
		t.Fail()
	})
}
Exemplo n.º 18
0
func TestContDeployConfigErr(t *testing.T) {
	t.Parallel()

	h := createParseProject(t)
	defer h.Stop()

	ensure.Nil(t,
		ioutil.WriteFile(
			filepath.Join(h.env.Root, legacyConfigFile),
			[]byte("}"),
			0600,
		),
	)
	h.env.Type = legacy

	deployer := deployFunc(func(parseVersion string,
		prevDeplInfo *deployInfo,
		forDevelop bool,
		e *env) (*deployInfo, error) {
		return &deployInfo{}, nil
	})

	done := make(chan struct{})
	go func() {
		h.Clock.Add(5 * time.Second)
		close(done)
	}()

	first := make(chan struct{})
	(&developCmd{}).contDeploy(h.env, deployer, first, done)
	_, opened := <-first
	ensure.False(t, opened)

	ensure.StringContains(
		t,
		h.Err.String(),
		fmt.Sprintf(
			`Config malformed.
Please fix your config file in %s and try again.
`,
			filepath.Join(h.env.Root, legacyConfigFile),
		),
	)
}
Exemplo n.º 19
0
func TestMetadata(t *testing.T) {
	m := NewMetadataStore()
	md0 := SnapshotMetadata{ReplicaID: "replset1_host1", ID: "1", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}}
	md1 := SnapshotMetadata{ReplicaID: "replset1_host1", ID: "2", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}}
	md2 := SnapshotMetadata{ReplicaID: "replset2_host2", ID: "1", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}}
	err := m.Add(NewLazySMFromM(&md0))
	ensure.Nil(t, err)
	err = m.Add(NewLazySMFromM(&md1))
	ensure.Nil(t, err)
	err = m.Add(NewLazySMFromM(&md2))
	ensure.Nil(t, err)

	ensure.SameElements(t, m.GetReplicaIDs(), []string{"replset1_host1", "replset2_host2"})

	lazyMD, err := m.getForReplica("replset1_host1")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, len(lazyMD), 2)
	mdRetrieved, err := lazyMD[0].Get()
	ensure.Nil(t, err)
	ensure.Subset(t, *mdRetrieved, SnapshotMetadata{ID: "1", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}})
	mdRetrieved, err = lazyMD[1].Get()
	ensure.Nil(t, err)
	ensure.Subset(t, *mdRetrieved, SnapshotMetadata{ID: "2", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}})

	lazyMD, err = m.getForReplica("replset2_host2")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, len(lazyMD), 1)
	mdRetrieved, err = lazyMD[0].Get()
	ensure.Nil(t, err)
	ensure.Subset(t, *mdRetrieved, SnapshotMetadata{ID: "1", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}})

	m.DeleteForReplicaByID("replset1_host1", "1")
	lazyMD, err = m.getForReplica("replset1_host1")
	ensure.Nil(t, err)
	// Both LazySnapshotMetadatas should still be in MetadataStore, but the first one should be marked for delete.
	ensure.DeepEqual(t, len(lazyMD), 2)
	ensure.True(t, lazyMD[0].DeleteMark)
	ensure.False(t, lazyMD[1].DeleteMark)

	mdRetrieved, err = lazyMD[1].Get()
	ensure.Nil(t, err)
	ensure.Subset(t, *mdRetrieved, SnapshotMetadata{ID: "2", Path: "/path/foo", Files: []File{{Name: "a"}, {Name: "b"}, {Name: "c"}}})
}
Exemplo n.º 20
0
func TestCheckExistingWithoutDesiredImageAndNoRemoveExisting(t *testing.T) {
	const image = "x"
	container := &Container{
		containerConfig: &dockerclient.ContainerConfig{
			Image: image,
		},
	}
	client := &mockClient{
		listImages: func() ([]*dockerclient.Image, error) {
			return []*dockerclient.Image{
				{
					RepoTags: []string{image},
					Id:       "y",
				},
			}, nil
		},
	}
	ok, err := container.checkExisting(client, &dockerclient.ContainerInfo{Image: "z"})
	ensure.Err(t, err, regexp.MustCompile("but desired image is"))
	ensure.False(t, ok)
}
Exemplo n.º 21
0
func TestContDeploy(t *testing.T) {
	t.Parallel()

	h := createParseProject(t)
	defer h.Stop()

	deployer := deployFunc(func(parseVersion string,
		prevDeplInfo *deployInfo,
		forDevelop bool,
		e *env) (*deployInfo, error) {
		return &deployInfo{}, nil
	})

	done := make(chan struct{})
	go func() {
		h.Clock.Add(time.Second)
		close(done)
	}()

	first := make(chan struct{})
	(&developCmd{}).contDeploy(h.env, deployer, first, done)
	_, opened := <-first
	ensure.False(t, opened)
}
Exemplo n.º 22
0
func TestShouldNotRetryRandomError(t *testing.T) {
	var r Transport
	ensure.False(t, r.shouldRetryError(errors.New("")))
}
Exemplo n.º 23
0
func TestFalse(t *testing.T) {
	var c capture
	ensure.False(t, false)
	ensure.False(&c, true)
	c.Equal(t, `ensure_test.go:214: expected false but got true`)
}
Exemplo n.º 24
0
func TestErrorCases(t *testing.T) {
	cases := []struct {
		Request    *http.Request
		Body       interface{}
		Error      string
		StatusCode int
		Transport  http.RoundTripper
	}{
		{
			Request: &http.Request{
				Method: "GET",
				URL: &url.URL{
					Scheme: "https",
					Host:   "api.parse.com",
					Path:   "/1/classes/Foo/Bar",
				},
			},
			Error:      `parse: api error with code=101 and message="object not found for get"`,
			StatusCode: http.StatusNotFound,
			Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
				j := jsonB(t, parse.Error{
					Code:    101,
					Message: "object not found for get",
				})
				return &http.Response{
					StatusCode: http.StatusNotFound,
					Status:     "404 Not Found",
					Body:       ioutil.NopCloser(bytes.NewReader(j)),
				}, nil
			}),
		},
		{
			Request: &http.Request{
				Method: "GET",
				URL: &url.URL{
					Scheme: "https",
					Host:   "api.parse.com",
					Path:   "/1/classes/Foo/Bar",
				},
			},
			Body:  map[int]int{},
			Error: "unsupported type: map[int]int",
			Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
				panic("not reached")
			}),
		},
		{
			Request: &http.Request{
				Method: "GET",
				URL:    &url.URL{Path: "/"},
			},
			Error:      `error with status=404 and body="<html>`,
			StatusCode: 404,
			Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
				return &http.Response{
					StatusCode: http.StatusNotFound,
					Status:     "404 Not Found",
					Body:       ioutil.NopCloser(strings.NewReader("<html>")),
				}, nil
			}),
		},
	}

	t.Parallel()
	for _, ec := range cases {
		c := &parse.Client{
			Credentials: defaultRestAPIKey,
		}
		if !realTransport {
			c.Transport = ec.Transport
		}
		res, err := c.Do(ec.Request, ec.Body, nil)
		ensure.NotNil(t, err)
		ensure.StringContains(t, err.Error(), ec.Error, ec)
		if ec.StatusCode != 0 {
			ensure.False(t, res == nil, ec)
			ensure.DeepEqual(t, res.StatusCode, ec.StatusCode, ec)
		}
	}
}
Exemplo n.º 25
0
func TestABWithNumbers(t *testing.T) {
	ensure.True(t, numericLessThan("abc9", "abc12"))
	ensure.False(t, numericLessThan("abc12", "abc9"))
	ensure.DeepEqual(t, numericLessThan("abc001", "abc1"), "abc001" < "abc1")
}
Exemplo n.º 26
0
func TestBPrefixOfA(t *testing.T) {
	t.Parallel()
	ensure.False(t, numericLessThan("abcd", "abc"))
}
Exemplo n.º 27
0
func TestBothEqual(t *testing.T) {
	t.Parallel()
	ensure.False(t, numericLessThan("abc", "abc"))
}
Exemplo n.º 28
0
func TestOnlyBEmpty(t *testing.T) {
	t.Parallel()
	ensure.False(t, numericLessThan("a", ""))
}
Exemplo n.º 29
0
func TestBothEmpty(t *testing.T) {
	t.Parallel()
	ensure.False(t, numericLessThan("", ""))
}