Пример #1
0
func TestAverage(t *testing.T) {
	t.Parallel()
	ensure.DeepEqual(t, stats.Average([]float64{}), 0.0)
	ensure.DeepEqual(t, stats.Average([]float64{1}), 1.0)
	ensure.DeepEqual(t, stats.Average([]float64{1, 2}), 1.5)
	ensure.DeepEqual(t, stats.Average([]float64{1, 2, 3}), 2.0)
}
Пример #2
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)
}
Пример #3
0
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",
	})
}
Пример #4
0
func TestConfigureAcessToken(t *testing.T) {
	t.Parallel()

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

	c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
	h.env.In = ioutil.NopCloser(strings.NewReader("n\ntoken\n"))
	ensure.Nil(t, c.accessToken(h.env))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter an access token if you already generated it.
If you do not have an access token or would like to generate a new one,
please type: "y" to open the browser or "n" to continue: Access Token: Successfully stored credentials.
`,
	)
	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n"))
	ensure.Err(t, c.accessToken(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, the access token you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new access token.
`,
	)
}
Пример #5
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)
}
Пример #6
0
func TestUploadSourceFilesChanged(t *testing.T) {
	t.Parallel()
	h := createParseProject(t)
	defer h.Stop()

	u := &uploader{
		DirName:  "cloud",
		Suffixes: map[string]struct{}{".js": {}},
		EndPoint: "uploads",
		Env:      h.env,
		PrevChecksums: map[string]string{
			"main.js": "d41d8cd98f00b204e9800998ecf8427e",
		},
		PrevVersions: map[string]string{
			"main.js": "f1",
		},
	}

	ht := transportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/uploads")
		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(`{"version": "f2"}`)),
		}, nil
	})

	h.env.ParseAPIClient = &ParseAPIClient{apiClient: &parse.Client{Transport: ht}}

	var d deployCmd
	checksums, versions, err := d.uploadSourceFiles(u)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, checksums, map[string]string{"main.js": "4ece160cc8e5e828ee718e7367cf5d37"})
	ensure.DeepEqual(t, versions, map[string]string{"main.js": "f2"})
}
Пример #7
0
func TestLogin(t *testing.T) {
	t.Parallel()

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

	l := &loginCmd{tokenReader: strings.NewReader("")}

	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ntoken\n"))
	ensure.Nil(t, l.run(h.env))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter the email id you used to register with Parse
and an account key if you already generated it.
If you do not have an account key or would like to generate a new one,
please type: "y" to open the browser or "n" to continue: Email: Account Key: Successfully stored credentials.
`)

	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n"))
	ensure.Err(t, l.run(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, we do not have a user with this email and account key.
Please follow instructions at https://www.parse.com/account/keys to generate a new account key.
`)
}
Пример #8
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()
}
Пример #9
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")
}
Пример #10
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"))
}
Пример #11
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)
}
Пример #12
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)
}
Пример #13
0
func TestPrepareInheriteFiles(t *testing.T) {
	var n Net

	port1, err := freeport.Get()
	ensure.Nil(t, err)
	addr1 := fmt.Sprintf(":%d", port1)
	l1, err := net.Listen("tcp", addr1)
	ensure.Nil(t, err)

	port2, err := freeport.Get()
	ensure.Nil(t, err)
	addr2 := fmt.Sprintf(":%d", port2)
	l2, err := net.Listen("tcp", addr2)
	ensure.Nil(t, err)

	files, err := n.prepareInheriteFiles([]net.Listener{l1, l2})
	ensure.Nil(t, err)
	ensure.DeepEqual(t, len(files), 2)

	// assign both to prevent GC from kicking in the finalizer
	fds := []int{dup(t, int(files[0].Fd())), dup(t, int(files[0].Fd()))}
	n.fdStart = fds[0]
	os.Setenv(envCountKey, "2")
	// Close these after to ensure we get coalaced file descriptors.
	ensure.Nil(t, l1.Close())
	ensure.Nil(t, l2.Close())

	ensure.Nil(t, n.inherit())
	ensure.DeepEqual(t, len(n.inherited), 2)
}
Пример #14
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())
}
Пример #15
0
func TestMakeNewRelease(t *testing.T) {
	t.Parallel()
	h := newHarness(t)
	defer h.Stop()

	var d deployCmd
	info := deployInfo{
		ReleaseName:  "v2",
		ParseVersion: "latest",
		Checksums: deployFileData{
			Cloud:  map[string]string{"main.js": "4ece160cc8e5e828ee718e7367cf5d37"},
			Public: map[string]string{"index.html": "9e2354a0ebac5852bc674026137c8612"},
		},
		Versions: deployFileData{
			Cloud:  map[string]string{"main.js": "f2"},
			Public: map[string]string{"index.html": "f2"},
		},
	}
	ht := transportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/deploy")
		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(jsonStr(t, &info))),
		}, nil
	})
	h.env.ParseAPIClient = &ParseAPIClient{apiClient: &parse.Client{Transport: ht}}
	res, err := d.makeNewRelease(&deployInfo{}, h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, info, res)
}
Пример #16
0
func TestStackErrorString(t *testing.T) {
	t.Parallel()

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

	err := stackerr.New("error")

	h.env.ErrorStack = false
	errStr := errorString(h.env, err)

	ensure.DeepEqual(t, errStr, "error")

	h.env.ErrorStack = true
	errStr = errorString(h.env, err)

	ensure.StringContains(t, errStr, "error")
	ensure.StringContains(t, errStr, ".go")

	err = stackerr.Wrap(&parse.Error{Message: "message", Code: 1})
	h.env.ErrorStack = false
	errStr = errorString(h.env, err)

	ensure.DeepEqual(t, errStr, "message")

	h.env.ErrorStack = true
	errStr = errorString(h.env, err)

	ensure.StringContains(t, errStr, `parse: api error with code=1 and message="message`)
	ensure.StringContains(t, errStr, ".go")
}
Пример #17
0
func TestGetPrevDeplInfo(t *testing.T) {
	t.Parallel()
	h := newHarness(t)
	defer h.Stop()

	var d deployCmd
	info := &deployInfo{
		ReleaseName:  "v1",
		ParseVersion: "latest",
		Checksums: deployFileData{
			Cloud:  map[string]string{"main.js": "d41d8cd98f00b204e9800998ecf8427e"},
			Public: map[string]string{"index.html": "d41d8cd98f00b204e9800998ecf8427e"},
		},
		Versions: deployFileData{
			Cloud:  map[string]string{"main.js": "f1"},
			Public: map[string]string{"index.html": "f1"},
		},
	}
	ht := transportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/deploy")
		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(jsonStr(t, info))),
		}, nil
	})
	h.env.ParseAPIClient = &ParseAPIClient{apiClient: &parse.Client{Transport: ht}}
	res, err := d.getPrevDeplInfo(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, res, info)
}
Пример #18
0
func TestParseResponse(t *testing.T) {
	response := "Asterisk Call Manager/1.0\r\nResponse: Success\r\nMessage: Authentication accepted\r\n\r\n"
	rsp, err := parseResponse(response)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, rsp.Get("Response"), "Success")
	ensure.DeepEqual(t, rsp.Get("Message"), "Authentication accepted")
}
Пример #19
0
func TestLatestVersion(t *testing.T) {
	t.Parallel()

	h := parsecli.NewHarness(t)
	defer h.Stop()

	ht := parsecli.TransportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/supported")
		return &http.Response{
			StatusCode: http.StatusOK,
			Body: ioutil.NopCloser(
				jsonpipe.Encode(
					map[string]string{"version": "2.0.2"},
				),
			),
		}, nil
	})
	h.Env.ParseAPIClient = &parsecli.ParseAPIClient{APIClient: &parse.Client{Transport: ht}}
	u := new(updateCmd)

	latestVersion, err := u.latestVersion(h.Env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, latestVersion, "2.0.2")

	downloadURL, err := u.getDownloadURL(h.Env)
	ensure.StringContains(t,
		downloadURL, "https://github.com/ParsePlatform/parse-cli/releases/download/release_2.0.2")
}
Пример #20
0
func TestDBCRUD(t *testing.T) {
	db := newTestDB(t, "TestDBGet", nil)
	defer db.Close()

	var (
		givenKey  = []byte("hello")
		givenVal1 = []byte("world1")
		givenVal2 = []byte("world2")
		wo        = NewDefaultWriteOptions()
		ro        = NewDefaultReadOptions()
	)

	// create
	ensure.Nil(t, db.Put(wo, givenKey, givenVal1))

	// retrieve
	v1, err := db.Get(ro, givenKey)
	defer v1.Free()
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v1.Data(), givenVal1)

	// update
	ensure.Nil(t, db.Put(wo, givenKey, givenVal2))
	v2, err := db.Get(ro, givenKey)
	defer v2.Free()
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v2.Data(), givenVal2)

	// delete
	ensure.Nil(t, db.Delete(wo, givenKey))
	v3, err := db.Get(ro, givenKey)
	ensure.Nil(t, err)
	ensure.True(t, v3.Data() == nil)
}
Пример #21
0
func TestConfigureAcessToken(t *testing.T) {
	t.Parallel()

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

	c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
	h.env.In = ioutil.NopCloser(strings.NewReader("token\n"))
	ensure.Nil(t, c.accountKey(h.env))
	ensure.DeepEqual(
		t,
		h.Out.String(),
		`
Input your account key or press enter to generate a new one.
Account Key: Successfully stored credentials.
`)
	h.env.In = ioutil.NopCloser(strings.NewReader("email\ninvalid\n"))
	ensure.Err(t, c.accountKey(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, the account key you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new account key.
`,
	)
}
Пример #22
0
func TestServeCombinedURLWithExt(t *testing.T) {
	contents := [][]byte{
		[]byte("foo"),
		[]byte("bar"),
	}
	var count int
	h := Handler{
		Path: "/",
		Box: funcBox(func(name string) ([]byte, error) {
			defer func() { count++ }()
			return contents[count], nil
		}),
	}
	v, err := h.URL("n1.js", "n2")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v, "/W1sibjEuanMiLCJhY2JkMThkYiJdLFsibjIiLCIzN2I1MWQxOSJdXQ.js")
	w := httptest.NewRecorder()
	r := &http.Request{
		URL: &url.URL{
			Path: v,
		},
	}
	h.ServeHTTP(w, r)
	ensure.DeepEqual(t, w.Code, http.StatusOK)
	ensure.DeepEqual(t, w.Body.String(), "foobar")
	ensure.DeepEqual(t, w.Header(), http.Header{
		"Content-Length": []string{"6"},
		"Cache-Control":  []string{cacheControl},
		"Content-Type":   []string{"application/javascript"},
	})
}
Пример #23
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"},
	)
}
Пример #24
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(), "")
}
Пример #25
0
func TestGetProjectRoot(t *testing.T) {
	t.Parallel()
	h := NewHarness(t)
	h.MakeEmptyRoot()
	defer h.Stop()

	ensure.Nil(t, os.Mkdir(filepath.Join(h.Env.Root, "parse"), 0755))
	ensure.Nil(t, os.Mkdir(filepath.Join(h.Env.Root, "parse", "config"), 0755))
	f, err := os.Create(filepath.Join(h.Env.Root, "parse", LegacyConfigFile))
	ensure.Nil(t, err)
	defer f.Close()
	ensure.Nil(t, os.Mkdir(filepath.Join(h.Env.Root, "parse", "cloud"), 0755))
	ensure.Nil(t, os.Mkdir(filepath.Join(h.Env.Root, "parse", "public"), 0755))
	ensure.Nil(t, os.MkdirAll(filepath.Join(h.Env.Root, "parse", "cloud", "other", "config"), 0755))

	ensure.DeepEqual(t, GetLegacyProjectRoot(h.Env, h.Env.Root), h.Env.Root)

	ensure.DeepEqual(t, GetLegacyProjectRoot(h.Env, filepath.Join(h.Env.Root, "parse", "config")), filepath.Join(h.Env.Root, "parse"))

	ensure.DeepEqual(t, GetLegacyProjectRoot(h.Env, filepath.Join(h.Env.Root, "parse", "cloud")), filepath.Join(h.Env.Root, "parse"))

	ensure.DeepEqual(t, GetLegacyProjectRoot(h.Env, filepath.Join(h.Env.Root, "parse", "public")), filepath.Join(h.Env.Root, "parse"))

	ensure.DeepEqual(t, GetLegacyProjectRoot(h.Env, filepath.Join(h.Env.Root, "parse", "cloud", "other")), filepath.Join(h.Env.Root, "parse"))
}
Пример #26
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), "{}")

}
Пример #27
0
func NewTokenHarness(t testing.TB) *Harness {
	h := NewHarness(t)
	ht := TransportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/accountkey")
		ensure.DeepEqual(t, r.Method, "POST")

		key := &struct {
			AccountKey string `json:"accountKey"`
		}{}
		ensure.Nil(t, json.NewDecoder(ioutil.NopCloser(r.Body)).Decode(key))

		if key.AccountKey != "token" {
			return &http.Response{
				StatusCode: http.StatusUnauthorized,
				Body:       ioutil.NopCloser(strings.NewReader(`{"error": "incorrect token"}`)),
			}, nil
		}

		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(`{"email": "email"}`)),
		}, nil
	})
	h.Env.ParseAPIClient = &ParseAPIClient{APIClient: &parse.Client{Transport: ht}}
	return h
}
Пример #28
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)
}
Пример #29
0
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(), "")
}
Пример #30
0
func TestSum(t *testing.T) {
	t.Parallel()
	ensure.DeepEqual(t, stats.Sum([]float64{}), 0.0)
	ensure.DeepEqual(t, stats.Sum([]float64{1}), 1.0)
	ensure.DeepEqual(t, stats.Sum([]float64{1, 2}), 3.0)
	ensure.DeepEqual(t, stats.Sum([]float64{1, 2, 3}), 6.0)
}