Esempio n. 1
0
func TestGeneralCase(t *testing.T) {
	fn := new(WalkFn)
	root := makeEmptyRoot(t)
	defer os.RemoveAll(root)

	ensure.Nil(t, os.MkdirAll(filepath.Join(root, "a", "a1"), 0755))
	createFile(t, filepath.Join(root, "a", "a1", "1"))

	ensure.Nil(t, os.Mkdir(filepath.Join(root, "b"), 0755))
	createFile(t, filepath.Join(root, "b", "2"))

	ensure.Nil(t, os.Symlink(filepath.Join(root, "b"), filepath.Join(root, "a", "a1", "a2")))

	ensure.Nil(t, os.Symlink(filepath.Join(root, "a", "a1", "1"), filepath.Join(root, "top")))

	ensure.Nil(t, Walk(root, fn.walkFn))

	ensure.DeepEqual(t,
		fn.List,
		[]string{
			root,
			filepath.Join(root, "a"),
			filepath.Join(root, "a", "a1"),
			filepath.Join(root, "a", "a1", "1"),
			filepath.Join(root, "a", "a1", "a2"),
			filepath.Join(root, "a", "a1", "a2", "2"),
			filepath.Join(root, "b"),
			filepath.Join(root, "b", "2"),
			filepath.Join(root, "top"),
		},
	)
}
Esempio n. 2
0
func TestParserEmail(t *testing.T) {
	t.Parallel()

	h := parsecli.NewTokenHarness(t)
	h.MakeEmptyRoot()
	defer h.Stop()

	ensure.Nil(t, parsecli.CreateConfigWithContent(filepath.Join(h.Env.Root, parsecli.ParseLocal), "{}"))
	ensure.Nil(t,
		parsecli.CreateConfigWithContent(
			filepath.Join(h.Env.Root, parsecli.ParseProject),
			`{"project_type": 1}`,
		),
	)

	var c configureCmd
	ensure.Nil(t, c.parserEmail(h.Env, []string{"email2"}))
	ensure.DeepEqual(
		t,
		h.Out.String(),
		`Successfully configured email for current project to: "email2"
`,
	)

	ensure.Err(t, c.parserEmail(h.Env, nil), regexp.MustCompile("Invalid args:"))
	ensure.Err(t, c.parserEmail(h.Env, []string{"a", "b"}), regexp.MustCompile("Invalid args:"))
}
func TestTriggerHooksUpdate(t *testing.T) {
	t.Parallel()

	h := newTriggersHarness(t)

	var tr triggerHooksCmd
	h.env.In =
		ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/_foo/beforeSave\n"))
	ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter following details about the trigger webhook
Class name: Trigger name: URL: https://Successfully update the "beforeSave" trigger for class "foo" to point to "https://api.example.com/_foo/beforeSave"
`)

	ensure.DeepEqual(t, h.Err.String(), "WARNING: beforeSave trigger already exists for class: foo\n")

	h.Out.Reset()
	h.Err.Reset()

	h.env.In =
		ioutil.NopCloser(strings.NewReader("bar\nafterSave\napi.example.com/_bar/afterSave\n"))
	ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter following details about the trigger webhook
Class name: Trigger name: URL: https://Successfully update the "afterSave" trigger for class "bar" to point to "https://api.example.com/_bar/afterSave"
`)

	ensure.DeepEqual(t, h.Err.String(), "")
}
Esempio n. 4
0
func TestExistingConnState(t *testing.T) {
	t.Parallel()
	hello := []byte("hello")
	fin := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(fin)
		w.Write(hello)
	}

	var called int32
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	ensure.Nil(t, err)
	server := &http.Server{
		Handler: http.HandlerFunc(okHandler),
		ConnState: func(c net.Conn, s http.ConnState) {
			atomic.AddInt32(&called, 1)
		},
	}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)
	actualBody, err := ioutil.ReadAll(res.Body)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actualBody, hello)
	ensure.Nil(t, res.Body.Close())

	ensure.Nil(t, s.Stop())
	<-fin

	ensure.True(t, atomic.LoadInt32(&called) > 0)
}
Esempio n. 5
0
func TestMergeOperator(t *testing.T) {
	var (
		givenKey    = []byte("hello")
		givenVal1   = []byte("foo")
		givenVal2   = []byte("bar")
		givenMerged = []byte("foobar")
	)
	merger := &mockMergeOperator{
		fullMerge: func(key, existingValue []byte, operands [][]byte) ([]byte, bool) {
			ensure.DeepEqual(&fatalAsError{t}, key, givenKey)
			ensure.DeepEqual(&fatalAsError{t}, existingValue, givenVal1)
			ensure.DeepEqual(&fatalAsError{t}, operands, [][]byte{givenVal2})
			return givenMerged, true
		},
	}
	db := newTestDB(t, "TestMergeOperator", func(opts *Options) {
		opts.SetMergeOperator(merger)
	})
	defer db.Close()

	wo := NewDefaultWriteOptions()
	ensure.Nil(t, db.Put(wo, givenKey, givenVal1))
	ensure.Nil(t, db.Merge(wo, givenKey, givenVal2))

	// trigger a compaction to ensure that a merge is performed
	db.CompactRange(Range{nil, nil})

	ro := NewDefaultReadOptions()
	v1, err := db.Get(ro, givenKey)
	defer v1.Free()
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v1.Data(), givenMerged)
}
Esempio n. 6
0
func TestCreateNewApp(t *testing.T) {
	t.Parallel()

	h, _ := newAppHarness(t)
	defer h.Stop()

	a := defaultApps
	h.env.In = ioutil.NopCloser(strings.NewReader("D"))
	app, err := a.createApp(h.env)
	ensure.Nil(t, err)

	ensure.Nil(t, a.printApp(h.env, app))
	ensure.DeepEqual(t, h.Out.String(),
		`Please choose a name for your Parse app.
Note that this name will appear on the Parse website,
but it does not have to be the same as your mobile app's public name.
Name: Name				D
DashboardURL			https://api.example.com/dashboard/D
ApplicationID			applicationID.D
ClientKey			clientKey.D
JavaScriptKey			javaScriptKey.D
WindowsKey			windowsKey.D
WebhookKey			webhookKey.D
RestKey				restKey.D
MasterKey			masterKey.D
ClientPushEnabled		false
ClientClassCreationEnabled	true
RequireRevocableSessions	true
RevokeSessionOnPasswordChange	true
`)
}
Esempio n. 7
0
func TestDeleteHook(t *testing.T) {
	t.Parallel()
	h := newHarness(t)
	defer h.Stop()

	c := &configureCmd{}
	_, _, err := c.deleteHook(h.env, nil, "delete")
	ensure.Err(t, err, regexp.MustCompile("invalid format"))

	_, _, err = c.deleteHook(h.env, nil, "invalid", "1")
	ensure.Err(t, err, regexp.MustCompile("invalid format"))

	_, _, err = c.deleteHook(h.env, nil, "delete", "1", "2")
	ensure.Err(t, err, regexp.MustCompile("invalid trigger name"))

	var hooksOps []*hookOperation
	_, ops, err := c.deleteHook(h.env, hooksOps, "delete", "call")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, ops[len(ops)-1].method, "DELETE")
	ensure.DeepEqual(
		t,
		*ops[len(ops)-1].function,
		functionHook{FunctionName: "call"},
	)

	_, ops, err = c.deleteHook(h.env, hooksOps, "delete", "_User", "beforeSave")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, ops[len(ops)-1].method, "DELETE")
	ensure.DeepEqual(
		t,
		*ops[len(ops)-1].trigger,
		triggerHook{ClassName: "_User", TriggerName: "beforeSave"},
	)
}
Esempio n. 8
0
func newServer(t *testing.T, handler func(net.Conn)) *testServer {
	ln, err := net.Listen("tcp", ":")
	ensure.Nil(t, err)

	ts := &testServer{
		ln:   ln,
		stop: make(chan struct{}),
	}
	go func() {
		for {
			select {
			case <-ts.stop:
				return
			case <-time.After(100 * time.Millisecond):
				conn, err := ts.ln.Accept()
				if err != nil {
					ensure.Nil(t, err)
					continue
				}
				go handler(conn)
			}
		}
	}()
	return ts
}
Esempio n. 9
0
func TestClientDo(t *testing.T) {
	given := map[string]string{"answer": "42"}
	givenJSON, err := json.Marshal(given)
	ensure.Nil(t, err)
	wrapped := []map[string]interface{}{
		{
			"code": http.StatusOK,
			"body": string(givenJSON),
		},
	}
	c := &Client{
		Client: &fbapi.Client{
			Transport: fTransport(func(r *http.Request) (*http.Response, error) {
				return &http.Response{
					StatusCode: http.StatusOK,
					Body:       ioutil.NopCloser(jsonpipe.Encode(wrapped)),
				}, nil
			}),
		},
	}
	var actual map[string]string
	_, err = c.Do(&http.Request{
		Method: "GET",
		URL:    &url.URL{},
	}, &actual)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actual, given)
}
Esempio n. 10
0
func TestApplyForceRemoveExistingWhenNotFound(t *testing.T) {
	var inspectCalls int
	container, err := NewContainer(
		ContainerName("x"),
		ContainerConfig(&dockerclient.ContainerConfig{Image: "foo"}),
		ContainerForceRemoveExisting(),
	)
	ensure.Nil(t, err)
	client := &mockClient{
		inspectContainer: func(name string) (*dockerclient.ContainerInfo, error) {
			inspectCalls++
			switch inspectCalls {
			case 1:
				return nil, dockerclient.ErrNotFound
			case 2:
				return &dockerclient.ContainerInfo{Id: "y"}, nil
			}
			panic("not reached")
		},
		createContainer: func(config *dockerclient.ContainerConfig, name string) (string, error) {
			return "", nil
		},
		startContainer: func(id string, config *dockerclient.HostConfig) error {
			return nil
		},
	}
	ensure.Nil(t, container.Apply(client))
}
Esempio n. 11
0
func TestGetHostFromURL(t *testing.T) {
	urlStr := "https://api.parse.com/1/"
	host, err := getHostFromURL(urlStr, "")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, host, "api.parse.com")

	urlStr = "https://api.parse.com/1/"
	host, err = getHostFromURL(urlStr, "*****@*****.**")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, host, "api.parse.com#[email protected]")

	urlStr = "https://api.example.com:8080/1/"
	host, err = getHostFromURL(urlStr, "")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, host, "api.example.com")

	urlStr = "https://api.example.com:8080/1/"
	host, err = getHostFromURL(urlStr, "*****@*****.**")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, host, "api.example.com#[email protected]")

	urlStr = "api.example.com:8080:90"
	host, err = getHostFromURL(urlStr, "")
	ensure.Err(t, err, regexp.MustCompile("not a valid url"))
}
Esempio n. 12
0
func TestComparator(t *testing.T) {
	db := newTestDB(t, "TestComparator", func(opts *Options) {
		opts.SetComparator(&bytesReverseComparator{})
	})
	defer db.Close()

	// insert keys
	givenKeys := [][]byte{[]byte("key1"), []byte("key2"), []byte("key3")}
	wo := NewDefaultWriteOptions()
	for _, k := range givenKeys {
		ensure.Nil(t, db.Put(wo, k, []byte("val")))
	}

	// create a iterator to collect the keys
	ro := NewDefaultReadOptions()
	iter := db.NewIterator(ro)
	defer iter.Close()

	// we seek to the last key and iterate in reverse order
	// to match given keys
	var actualKeys [][]byte
	for iter.SeekToLast(); iter.Valid(); iter.Prev() {
		key := make([]byte, 4)
		copy(key, iter.Key().Data())
		actualKeys = append(actualKeys, key)
	}
	ensure.Nil(t, iter.Err())

	// ensure that the order is correct
	ensure.DeepEqual(t, actualKeys, givenKeys)
}
Esempio n. 13
0
func TestSecondUnixListenInherited(t *testing.T) {
	var n Net
	tmpfile, err := ioutil.TempFile("", "TestSecondUnixListenInherited-")
	ensure.Nil(t, err)
	ensure.Nil(t, tmpfile.Close())
	ensure.Nil(t, os.Remove(tmpfile.Name()))
	defer os.Remove(tmpfile.Name())
	l1, err := net.Listen("unix", tmpfile.Name())
	ensure.Nil(t, err)
	file, err := l1.(*net.UnixListener).File()
	ensure.Nil(t, err)
	n.fdStart = dup(t, int(file.Fd()))
	ensure.Nil(t, file.Close())
	os.Setenv(envCountKey, "1")
	ensure.Nil(t, n.inherit())
	ensure.DeepEqual(t, len(n.inherited), 1)
	l2, err := n.Listen("unix", tmpfile.Name())
	ensure.Nil(t, err)
	ensure.DeepEqual(t, len(n.active), 1)
	ensure.DeepEqual(t, n.inherited[0], nil)
	_, err = n.Listen("unix", tmpfile.Name())
	ensure.Err(t, err, regexp.MustCompile("bind: address already in use$"))
	ensure.Nil(t, l1.Close())
	ensure.Nil(t, l2.Close())
}
Esempio n. 14
0
func TestNewError(t *testing.T) {
	t.Parallel()

	// expected stats
	statsDone := make(chan struct{})
	hc := &stats.HookClient{
		BumpSumHook: func(key string, val float64) {
			if key == "acquire.error.new" {
				close(statsDone)
			}
		},
	}

	expected := errors.New("")
	p := Pool{
		New:           func() (io.Closer, error) { return nil, expected },
		Stats:         hc,
		Max:           1,
		MinIdle:       1,
		IdleTimeout:   time.Hour,
		ClosePoolSize: 2,
	}
	r, actual := p.Acquire()
	ensure.Nil(t, r)
	ensure.DeepEqual(t, actual, expected)
	ensure.Nil(t, p.Close())
	<-statsDone
}
Esempio n. 15
0
func initProject(t *testing.T, root string) ([]string, []string) {
	dirs := []string{
		filepath.Join(root, "tester"),
		filepath.Join(root, "tester", "inside"),
		filepath.Join(root, "tester", "inside", "test"),
		filepath.Join(root, "tester", "inside", "tester"),
	}

	for _, dir := range dirs {
		ensure.Nil(t, os.MkdirAll(dir, 0755))
	}

	files := []string{
		filepath.Join(root, "tester", "test"),
		filepath.Join(root, "tester", "inside", "tester", "test"),
	}

	for _, file := range files {
		f, err := os.Create(file)
		ensure.Nil(t, err)
		defer f.Close()
	}

	return files, dirs
}
Esempio n. 16
0
func TestBatchDo(t *testing.T) {
	const (
		method      = "GET"
		relativeURL = "/me"
		accessToken = "at"
		appID       = 42
	)
	given := []*Response{{Code: 42}}
	br := &Request{
		Method:      method,
		RelativeURL: relativeURL,
	}
	b := &Batch{
		AccessToken: accessToken,
		AppID:       appID,
		Request:     []*Request{br},
	}
	c := &fbapi.Client{
		Transport: fTransport(func(r *http.Request) (*http.Response, error) {
			ensure.Nil(t, r.ParseForm())
			ensure.DeepEqual(t, r.URL.String(), "https://graph.facebook.com/")
			ensure.DeepEqual(t, r.Method, "POST")
			ensure.DeepEqual(t, r.PostFormValue("access_token"), accessToken)
			ensure.DeepEqual(t, r.PostFormValue("batch_app_id"), fmt.Sprint(appID))
			return &http.Response{
				StatusCode: http.StatusOK,
				Body:       ioutil.NopCloser(jsonpipe.Encode(given)),
			}, nil
		}),
	}
	actual, err := BatchDo(c, b)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actual, given)
}
Esempio n. 17
0
func TestNewCmdContent(t *testing.T) {
	t.Parallel()

	h, n := newNewCmdHarness(t)
	defer h.Stop()

	ensure.Nil(t, n.cloneSampleCloudCode(h.env, true))

	for _, newProjectFile := range newProjectFiles {
		content, err := ioutil.ReadFile(
			filepath.Join(h.env.Root, newProjectFile.dirname, newProjectFile.filename),
		)
		ensure.Nil(t, err)
		ensure.DeepEqual(t, string(content), newProjectFile.content)
	}

	content, err := ioutil.ReadFile(filepath.Join(h.env.Root, parseProject))
	ensure.Nil(t, err)
	ensure.DeepEqual(t,
		string(content),
		fmt.Sprintf(
			`{
  "project_type" : %d,
  "parse": {"jssdk":""}
}`,
			parseFormat,
		),
	)

	content, err = ioutil.ReadFile(filepath.Join(h.env.Root, parseLocal))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, string(content), "{}")

}
Esempio n. 18
0
func TestEncodeUint(t *testing.T) {
	var buf bytes.Buffer

	// Uint8
	var ui8 uint8
	ui8 = math.MaxUint8
	ensure.Nil(t, encode(&buf, reflect.ValueOf(ui8)))
	ensure.DeepEqual(t, fmt.Sprintf("%d\r\n", ui8), buf.String())
	buf.Reset()

	// Uint16
	var ui16 uint16
	ui16 = math.MaxUint16
	ensure.Nil(t, encode(&buf, reflect.ValueOf(ui16)))
	ensure.DeepEqual(t, fmt.Sprintf("%d\r\n", ui16), buf.String())
	buf.Reset()

	// Uint32
	var ui32 uint32
	ui32 = math.MaxUint32
	ensure.Nil(t, encode(&buf, reflect.ValueOf(ui32)))
	ensure.DeepEqual(t, fmt.Sprintf("%d\r\n", ui32), buf.String())
	buf.Reset()

	// Uint64
	var ui64 uint64
	ui64 = math.MaxUint64
	ensure.Nil(t, encode(&buf, reflect.ValueOf(ui64)))
	ensure.DeepEqual(t, fmt.Sprintf("%v\r\n", ui64), buf.String())
	buf.Reset()
}
Esempio n. 19
0
func TestGenericGetSourceFiles(t *testing.T) {
	t.Parallel()

	h := newHarness(t)
	h.makeEmptyRoot()
	defer h.Stop()

	ensure.Nil(t, os.Mkdir(filepath.Join(h.env.Root, "src"), 0755))
	for _, name := range []string{"index.html"} {
		file, err := os.Create(filepath.Join(h.env.Root, "src", name))
		ensure.Nil(t, err)
		ensure.Nil(t, file.Close())
	}

	ensure.Nil(t, os.Symlink(filepath.Join(h.env.Root, "src"), filepath.Join(h.env.Root, "public")))

	var d deployCmd

	files, ignored, err := d.getSourceFiles(
		filepath.Join(h.env.Root, "public"),
		map[string]struct{}{".html": {}},
		h.env,
	)

	ensure.Nil(t, err)
	ensure.DeepEqual(t, files, []string{filepath.Join(h.env.Root, "public", "index.html")})
	ensure.DeepEqual(t, len(ignored), 0)
}
Esempio n. 20
0
func TestShouldCreateNewApp(t *testing.T) {
	t.Parallel()
	h := parsecli.NewHarness(t)
	defer h.Stop()

	n := &newCmd{}

	h.Env.In = ioutil.NopCloser(strings.NewReader("new"))
	decision, err := n.promptCreateNewApp(h.Env, false)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, decision, "new")

	h.Env.In = ioutil.NopCloser(strings.NewReader("existing"))
	decision, err = n.promptCreateNewApp(h.Env, false)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, decision, "existing")

	h.Env.In = ioutil.NopCloser(strings.NewReader("other"))
	_, err = n.promptCreateNewApp(h.Env, false)
	ensure.Err(t, err, regexp.MustCompile("are the only valid options"))

	decision, err = n.promptCreateNewApp(h.Env, true)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, decision, "existing")

	n.createNewApp = true
	decision, err = n.promptCreateNewApp(h.Env, true)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, decision, "new")
}
Esempio n. 21
0
func TestHTTPWithinStopTimeout(t *testing.T) {
	t.Parallel()
	hello := []byte("hello")
	finOkHandler := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(finOkHandler)
		w.WriteHeader(200)
		w.Write(hello)
	}

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	ensure.Nil(t, err)
	server := &http.Server{Handler: http.HandlerFunc(okHandler)}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{StopTimeout: time.Minute}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)

	finStop := make(chan struct{})
	go func() {
		defer close(finStop)
		ensure.Nil(t, s.Stop())
	}()

	actualBody, err := ioutil.ReadAll(res.Body)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actualBody, hello)
	ensure.Nil(t, res.Body.Close())
	<-finOkHandler
	<-finStop
}
Esempio n. 22
0
func TestSetupAndConfigure(t *testing.T) {
	t.Parallel()
	h := parsecli.NewHarness(t)
	h.MakeEmptyRoot()
	defer h.Stop()

	n := &newCmd{}
	h.Env.Type = parsecli.ParseFormat
	h.Env.In = ioutil.NopCloser(strings.NewReader("\n"))
	code, err := n.setupSample(h.Env, "myapp", &parsecli.ParseAppConfig{ApplicationID: "a"}, true, false)
	ensure.Nil(t, err)
	ensure.True(t, code)

	type jsSDKVersion struct {
		JS []string `json:"js"`
	}
	ht := parsecli.TransportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/jsVersions")
		rows := jsSDKVersion{JS: []string{"1.5.0", "1.6.0"}}
		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(jsonStr(t, rows))),
		}, nil
	})
	h.Env.ParseAPIClient = &parsecli.ParseAPIClient{APIClient: &parse.Client{Transport: ht}}
	err = n.configureSample(
		&addCmd{MakeDefault: true},
		"yolo",
		(&parsecli.ParseAppConfig{ApplicationID: "a"}).WithInternalMasterKey("m"),
		nil,
		h.Env,
	)
	ensure.Nil(t, err)
}
Esempio n. 23
0
func TestWriteBatch(t *testing.T) {
	db := newTestDB(t, "TestWriteBatch", nil)
	defer db.Close()

	var (
		givenKey1 = []byte("key1")
		givenVal1 = []byte("val1")
		givenKey2 = []byte("key2")
	)
	wo := NewDefaultWriteOptions()
	ensure.Nil(t, db.Put(wo, givenKey2, []byte("foo")))

	// create and fill the write batch
	wb := NewWriteBatch()
	defer wb.Destroy()
	wb.Put(givenKey1, givenVal1)
	wb.Delete(givenKey2)
	ensure.DeepEqual(t, wb.Count(), 2)

	// perform the batch
	ensure.Nil(t, db.Write(wo, wb))

	// check changes
	ro := NewDefaultReadOptions()
	v1, err := db.Get(ro, givenKey1)
	defer v1.Free()
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v1.Data(), givenVal1)

	v2, err := db.Get(ro, givenKey2)
	defer v2.Free()
	ensure.Nil(t, err)
	ensure.True(t, v2.Data() == nil)
}
Esempio n. 24
0
func TestIntegrateNoResults(t *testing.T) {
	client, err := NewClient(ClientRawURL(prodURL))
	ensure.Nil(t, err)
	actual, err := client.Search("8B924976-8B90-400C-84F8-70F7E1FDF617")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, len(actual), 0)
}
Esempio n. 25
0
func TestProjectType(t *testing.T) {
	t.Parallel()
	h := parsecli.NewHarness(t)
	defer h.Stop()

	h.MakeEmptyRoot()
	ensure.Nil(t, parsecli.CloneSampleCloudCode(h.Env, false))

	c := &configureCmd{}
	err := c.projectType(h.Env, []string{"1", "2"})
	ensure.Err(t, err, regexp.MustCompile("only an optional project type argument is expected"))

	h.Env.In = ioutil.NopCloser(strings.NewReader("invalid\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Err.String(), "Invalid selection. Please enter a number")
	ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
	h.Err.Reset()
	h.Out.Reset()

	h.Env.In = ioutil.NopCloser(strings.NewReader("0\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Err.String(), "Please enter a number between 1 and")
	ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
	h.Err.Reset()
	h.Out.Reset()

	h.Env.In = ioutil.NopCloser(strings.NewReader("1\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Out.String(), "Successfully set project type to: parse")
	ensure.Nil(t, err)
}
Esempio n. 26
0
func newHarnessInternal(url string, s stopper, t testing.TB) *Harness {
	replicaSet := ReplicaSet{
		Addrs:                   url,
		PortStart:               2000,
		PortEnd:                 3000,
		MaxConnections:          5,
		MinIdleConnections:      5,
		ServerIdleTimeout:       5 * time.Minute,
		ServerClosePoolSize:     5,
		ClientIdleTimeout:       5 * time.Minute,
		MaxPerClientConnections: 250,
		GetLastErrorTimeout:     5 * time.Minute,
		MessageTimeout:          time.Minute,
	}
	log := tLogger{TB: t}
	var graph inject.Graph
	err := graph.Provide(
		&inject.Object{Value: &log},
		&inject.Object{Value: &replicaSet},
		&inject.Object{Value: &stats.HookClient{}},
	)
	ensure.Nil(t, err)
	ensure.Nil(t, graph.Populate())
	objects := graph.Objects()
	ensure.Nil(t, startstop.Start(objects, &log))
	return &Harness{
		T:          t,
		Stopper:    s,
		ReplicaSet: &replicaSet,
		Graph:      &graph,
		Log:        &log,
	}
}
func TestReadTriggerParams(t *testing.T) {
	t.Parallel()

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

	h.env.In = ioutil.NopCloser(strings.NewReader("\n"))
	_, err := readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Class name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\n"))
	_, err = readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Trigger name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave"))
	hook, err := readTriggerName(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{ClassName: "foo", TriggerName: "beforeSave"})

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/foo/beforeSave\n"))
	hook, err = readTriggerParams(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{
		ClassName:   "foo",
		TriggerName: "beforeSave",
		URL:         "https://api.example.com/foo/beforeSave",
	})
}
Esempio n. 28
0
func TestFunctionHooksUpdate(t *testing.T) {
	t.Parallel()

	h := newFunctionsHarness(t)

	var f functionHooksCmd
	h.Env.In = strings.NewReader("foo\napi.example.com/_foo\n")
	ensure.Nil(t, f.functionHooksUpdate(h.Env, nil))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter the function name: URL: https://Successfully update the webhook function "foo" to point to "https://api.example.com/_foo"
`)

	ensure.DeepEqual(t, h.Err.String(), "WARNING: function foo already exists\n")

	h.Out.Reset()
	h.Err.Reset()

	h.Env.In = strings.NewReader("bar\napi.example.com/_bar\n")
	ensure.Nil(t, f.functionHooksUpdate(h.Env, nil))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter the function name: URL: https://Successfully update the webhook function "bar" to point to "https://api.example.com/_bar"
`)

	ensure.DeepEqual(t, h.Err.String(), "")
}
Esempio n. 29
0
// Basically tests manager.GetReplicaIDs
func TestGetReplicaIDs(t *testing.T) {
	skipIfOldMongo(t)

	s3 := s3storage.NewMockS3(t)
	defer s3.Stop()
	s, err := s3storage.NewStorageWithMockS3(s3)
	ensure.Nil(t, err)

	replicaID1 := "faux-replicaID1"
	replicaID2 := "faux-replicaID2"

	mongo := mgotest.NewStartedServer(t, "--storageEngine=rocksdb")
	defer mongo.Stop()

	r := lreplica.NewMockLocalReplica(mongo, 1)
	manager, err := strata.NewSnapshotManager(r, s)
	ensure.Nil(t, err)

	_, err = manager.CreateSnapshot(replicaID1)
	ensure.Nil(t, err)
	_, err = manager.CreateSnapshot(replicaID2)
	ensure.Nil(t, err)
	_, err = manager.CreateSnapshot(replicaID1)
	ensure.Nil(t, err)

	replicaIDs := manager.GetReplicaIDs()
	ensure.DeepEqual(t, len(replicaIDs), 2)
}
Esempio n. 30
0
func TestIgnoreSuggestedResults(t *testing.T) {
	c, err := NewClient(
		ClientTransport(fTransport(func(*http.Request) (*http.Response, error) {
			return &http.Response{
				Body: ioutil.NopCloser(strings.NewReader(`
				<body>
					<table>
						<tr>
							<td>
								<a href="magnet:a">l</a>
							</td>
						</tr>
					</table>
					<table>
						<tr>
							<td>
								<a href="magnet:b">l</a>
							</td>
						</tr>
					</table>
				</body>
			`)),
			}, nil
		})),
	)
	ensure.Nil(t, err)
	res, err := c.Search("unimportant")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, res, []Result{{Magnet: "magnet:a"}})
}