Ejemplo n.º 1
0
func TestListAll(t *testing.T) {
	presetData := []Order{
		Order{1468248039, 100, -100, "USD"},
		Order{1468248040, -50, 51, "USD"},
		Order{1468248041, 100, -100, "JPY"},
		Order{1468248042, -50, 51, "JPY"},
	}
	h, token, mgr := makeListAll(presetData)
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/listall", "", `{"token":"`+token+`"}`)

	if err != nil {
		t.Fatalf("unexpected error occured when testing listall: %s", err)
	}

	if resp.Code != http.StatusOK {
		t.Fatalf("unexpected error occured when testing listall with status code %d: %s", resp.Code, resp.Body.String())
	}

	var orders []Order
	if resp.Body == nil {
		t.Fatal(resp)
	}
	if err := json.Unmarshal(resp.Body.Bytes(), &orders); err != nil {
		t.Fatalf("cannot encode returned data from listall: %s", err)
	}

	msgs := validateOrders(presetData, orders)
	for _, msg := range msgs {
		t.Errorf("listall: %s", msg)
	}
}
Ejemplo n.º 2
0
func TestAuthWrongPin(t *testing.T) {
	fake := FakeAuthenticator("123456")
	h := &auth{fake}

	cases := []struct {
		in  string
		msg string
	}{
		{`{"pin":"654321"}`, "auth: sent wrong pin, expect 400, got %d"},
		{`{}`, "auth: sent no pin, expect 400, got %d"},
		{`"123456"`, "auth: sent wrong format, expect 400, got %d"},
	}

	for _, c := range cases {
		resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/auth", "", c.in)

		if err != nil {
			t.Fatalf("unexpected error occured when testing auth: %s", err)
		}

		if resp.Code != http.StatusBadRequest {
			t.Errorf(c.msg, resp.Code)
		}
	}
}
Ejemplo n.º 3
0
func TestPadEditAclCoop(t *testing.T) {
	sess := session(pc().SF, t)
	sess.Login(peAclCoop)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("While loging in as coop: %s", err)
	}
	param := map[string]interface{}{
		"title":      peAclPad.Title,
		"content":    peAclPad.Title,
		"tags":       peAclPad.Tags,
		"cooperator": []int{peAclCoop.ID + 1},
		"version":    peAclPad.Version,
	}
	resp, err := jsonapi.HandlerTest(pc().Edit).PostJSON(peAclURI, sess.Cookie(), param)
	if err != nil {
		t.Fatalf("Error occured when testing edit ACL with coop: %s", err)
	}

	if !testResult(resp.Body, false) {
		t.Errorf("Edit cooperators success with coop: %s", resp.Body.String())
	}

	if !testData(3, resp.Body, "code") {
		t.Errorf("Expect error code 3 when edit cooperators with coop, got response %s", resp.Body.String())
	}
}
Ejemplo n.º 4
0
func TestListNotJSON(t *testing.T) {
	h, _, mgr := makeList([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/list", "", ``)

	if err != nil {
		t.Fatalf("unexpected error occured when testing list: %s", err)
	}

	if resp.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status code %d for bad request: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 5
0
func TestListAllNotJSON(t *testing.T) {
	h, _, mgr := makeListAll([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/listall", "", `1234`)

	if err != nil {
		t.Fatalf("unexpected error occured when testing listall: %s", err)
	}

	if resp.Code != http.StatusBadRequest {
		t.Fatalf("expected listall return bad request when not sending json, got %d: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 6
0
func TestListAllWrongToken(t *testing.T) {
	h, _, mgr := makeListAll([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/listall", "", `{"token":"1234"}`)

	if err != nil {
		t.Fatalf("unexpected error occured when testing listall: %s", err)
	}

	if resp.Code != http.StatusForbidden {
		t.Fatalf("expected listall return forbidden when wrong token, got %d: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 7
0
func TestPadVersionMismatch(t *testing.T) {
	pad, err := model.NewPad(db, pvTestUser.ID, "pm version", "test pm version", nil, nil)
	if err != nil {
		t.Fatalf("Cannot create pad for version testing: %s", err)
	}
	sess := session(pc().SF, t)
	sess.Login(pvTestUser)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("Failed to login for testing version: %s", err)
	}
	cookie := sess.Cookie()
	uri := fmt.Sprintf("/api/edit/%d", pad.ID)
	param := map[string]interface{}{
		"title":   "pm version modified",
		"content": "content",
		"version": pad.Version + 1,
	}

	fn := func() {
		resp, err := jsonapi.HandlerTest(pc().Edit).PostJSON(uri, cookie, param)
		if err != nil {
			t.Fatalf("Cannot run /api/edit for version test: %s", err)
		}

		if !testResult(resp.Body, false) {
			t.Errorf("Version (%d) mismatch but pad is updates: %s", param["version"].(int), resp.Body.String())
		}
		code, ok := testHasData(resp.Body, "code")
		if !ok {
			t.Errorf("Not returning code wher version mismatch: %s", resp.Body.String())
		}
		var c int
		switch v := code.(type) {
		case float32, float64:
			c = int(reflect.ValueOf(v).Float())
		case int64, int32, int16, int8, int:
			c = int(reflect.ValueOf(v).Int())
		default:
			t.Fatalf("Returned code is not integer: %#v", code)
		}
		if c != 5 {
			t.Errorf("Error code is not 5: %d", c)
		}
	}

	fn()
	param["version"] = pad.Version - 1
	fn()
}
Ejemplo n.º 8
0
func TestAddNoData(t *testing.T) {
	h, token, mgr := makeAdd([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/add", "", `{"token":"`+token+`"}`)

	if err != nil {
		t.Fatalf("unexpected error occured when testing add: %s", err)
	}

	if resp.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status code %d for bas request: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 9
0
func TestAddOK(t *testing.T) {
	h, token, mgr := makeAdd([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post(
		"/api/add",
		"",
		`{"data":{"when":1468248043,"foreign":100,"local":-100,"code":"AUD"},"token":"`+token+`"}`,
	)

	if err != nil {
		t.Fatalf("unexpected error occured when testing add: %s", err)
	}

	if resp.Code != http.StatusOK {
		t.Fatalf("unexpected error occured when testing add with status code %d: %s", resp.Code, resp.Body.String())
	}

	if resp.Body == nil {
		t.Fatal(resp)
	}

	if str := strings.TrimSpace(resp.Body.String()); str != "null" {
		t.Errorf("add: returned non-null result: '%s'", str)
	}

	qstr := `SELECT * FROM orders`
	rows := mgr.Query(Order{}, qstr)
	expect := []Order{
		Order{1468248043, 100, -100, "AUD"},
	}

	var orders []Order
	for rows.Next() {
		var o Order
		rows.Scan(&o)
		orders = append(orders, o)
	}

	if err := rows.Err(); err != nil {
		t.Fatalf("add: error reading records from db: %s", err)
	}

	msgs := validateOrders(expect, orders)
	for _, msg := range msgs {
		t.Errorf("add: %s", msg)
	}
}
Ejemplo n.º 10
0
func TestAddWrongToken(t *testing.T) {
	h, _, mgr := makeAdd([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post(
		"/api/add",
		"",
		`{"data":{"when":1468248043,"foreign":100,"local":-100,"code":"AUD"},"token":"1234"}`,
	)

	if err != nil {
		t.Fatalf("unexpected error occured when testing add: %s", err)
	}

	if resp.Code != http.StatusForbidden {
		t.Fatalf("expect add return forbidden when wrong token, got %d: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 11
0
func TestAuthOK(t *testing.T) {
	fake := FakeAuthenticator("123456")
	h := &auth{fake}

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/auth", "", `{"pin":"123456"}`)

	if err != nil {
		t.Fatalf("unexpected error occured when testing auth: %s", err)
	}

	if resp.Code != http.StatusOK {
		t.Fatalf("auth: sent correct pin but got http status %d", resp.Code)
	}

	if resp.Body == nil {
		t.Fatal("auth: got 200 OK, but no token")
	}
}
Ejemplo n.º 12
0
func TestListWrongToken(t *testing.T) {
	h, _, mgr := makeList([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post(
		"/api/list",
		"",
		`{"code":"USD","token":"1234"}`,
	)

	if err != nil {
		t.Fatalf("unexpected error occured when testing list: %s", err)
	}

	if resp.Code != http.StatusForbidden {
		t.Fatalf("unexpected status code %d for forbidden: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 13
0
func TestPadDelAclNoLogin(t *testing.T) {
	resp, err := jsonapi.HandlerTest(pc().Delete).Get(pdAclURI, "")
	if err != nil {
		t.Fatalf("Error occured while testing pad delete ACL without login: %s", err)
	}

	if !testResult(resp.Body, false) {
		t.Errorf("Delete success without login: %s", resp.Body.String())
	}

	code, ok := testHasData(resp.Body, "code")
	if !ok {
		t.Errorf("Error code not found in deletion without login: %s", resp.Body.String())
	}
	if !eqInt(1, code) {
		t.Errorf("Expected error code is 1 when delete without login, got %d", code)
	}
}
Ejemplo n.º 14
0
func TestPads(t *testing.T) {
	p, err := model.NewPad(db, padTestUser.ID, "list pad", "test list pad", []string{}, []int{})
	if err != nil {
		t.Fatalf("Cannot create pad for testing list: %s", err)
	}

	resp, err := jsonapi.HandlerTest(pc().List).Get("/api/pads", "")
	if err != nil {
		t.Fatalf("While getting response of /api/pads: %s", err)
	}

	if !testResult(resp.Body, true) {
		t.Fatalf("/api/pads resurns an error: %s", resp.Body.String())
	}
	if !testArrayHas(p.ID, resp.Body) {
		t.Fatalf("Cannot find pad#%d in response of /api/pads: %s", p.ID, resp.Body.String())
	}
}
Ejemplo n.º 15
0
func realTestEdit(t *testing.T, pid int, tags []string, coops []int, cookie string) {
	pad, err := model.LoadPad(pid)
	if err != nil {
		t.Fatalf("Cannot load pad to edit: %s", err)
	}
	t.Logf("Test pad modification with tags %#v and coops %#v", tags, coops)
	ts := tags
	if tags == nil {
		ts = []string{}
	}
	c := coops
	if coops == nil {
		c = []int{}
	}
	randomTitle := fmt.Sprintf("randomTitle-%d", rand.Int())
	uri := fmt.Sprintf("/api/edit/%d", pad.ID)
	param := map[string]interface{}{
		"title":      randomTitle,
		"content":    pad.Content,
		"tags":       tags,
		"cooperator": coops,
		"version":    pad.Version,
	}

	resp, err := jsonapi.HandlerTest(pc().Edit).PostJSON(uri, cookie, param)
	if err != nil {
		t.Fatalf("Cannot save pad modification to db: %s", err)
	}
	if !testResult(resp.Body, true) {
		t.Errorf("/apd/edit returns false: %s", resp.Body.String())
	}
	actual, err := model.LoadPad(pad.ID)
	if err != nil {
		t.Fatalf("Cannot load just updated pad#%d: %s", pad.ID, err)
	}
	if !reflect.DeepEqual(actual.Tags, ts) {
		t.Errorf("Expected tags %v, got %v", tags, pad.Tags)
	}
	if !reflect.DeepEqual(actual.Cooperators, c) {
		t.Errorf("Expected coops %v, got %v", coops, pad.Cooperators)
	}

}
Ejemplo n.º 16
0
func TestPad(t *testing.T) {
	p, err := model.NewPad(db, padTestUser.ID, "pad", "test pad", []string{}, []int{})
	if err != nil {
		t.Fatalf("Cannot create pad for later testing: %s", err)
	}

	resp, err := jsonapi.HandlerTest(pc().View).Get(fmt.Sprintf("/api/pad/%d", p.ID), "")
	if err != nil {
		t.Fatalf("While getting response of /api/pad/%d: %s", p.ID, err)
	}

	if !testResult(resp.Body, true) {
		t.Fatalf("/api/pad/%d returns an error: %s", p.ID, resp.Body.String())
	}

	if !testData(p.ID, resp.Body, "id") {
		t.Fatalf("/api/pad/%d returns wrong data: %s", p.ID, resp.Body.String())
	}
}
Ejemplo n.º 17
0
func TestPadEditAclNoLogin(t *testing.T) {
	param := map[string]interface{}{
		"title":      peAclPad.Title,
		"content":    peAclPad.Title,
		"tags":       peAclPad.Tags,
		"cooperator": peAclPad.Cooperators,
	}
	resp, err := jsonapi.HandlerTest(pc().Edit).PostJSON(peAclURI, "", param)
	if err != nil {
		t.Fatalf("Error occured when testing edit ACL without login: %s", err)
	}

	if !testResult(resp.Body, false) {
		t.Errorf("Edit success while no user logged in!: %s", resp.Body.String())
	}

	if !testData(1, resp.Body, "code") {
		t.Errorf("Expect error code 1 when edit without login, got response %s", resp.Body.String())
	}
}
Ejemplo n.º 18
0
func TestListAllEmpty(t *testing.T) {
	h, token, mgr := makeListAll([]Order{})
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post("/api/listall", "", `{"token":"`+token+`"}`)

	if err != nil {
		t.Fatalf("unexpected error occured when testing listall: %s", err)
	}

	if resp.Code != http.StatusOK {
		t.Fatalf("unexpected error occured when testing listall with status code %d: %s", resp.Code, resp.Body.String())
	}

	if resp.Body == nil {
		t.Fatal(resp)
	}
	if str := strings.TrimSpace(resp.Body.String()); str != "[]" {
		t.Errorf("listall: not returning empty array: '%s'", str)
	}
}
Ejemplo n.º 19
0
func TestAddDuplicated(t *testing.T) {
	presetData := []Order{
		Order{1468248039, 100, -100, "USD"},
	}
	h, token, mgr := makeAdd(presetData)
	defer mgr.Connection().Close()

	resp, err := jsonapi.HandlerTest(jsonapi.APIHandler(h.Handle).Handler).Post(
		"/api/add",
		"",
		`{"data":{"when":1468248039,"foreign":100,"local":-100,"code":"USD"},"token":"`+token+`"}`,
	)

	if err != nil {
		t.Fatalf("unexpected error occured when testing add: %s", err)
	}

	if resp.Code != http.StatusInternalServerError {
		t.Fatalf("unexpected status code %d for duplicated record: %s", resp.Code, resp.Body.String())
	}
}
Ejemplo n.º 20
0
func TestDeletePad(t *testing.T) {
	sess := session(pc().SF, t)
	sess.Login(pmTestUser)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("Failed to login for deleting pad: %s", err)
	}
	cookie := sess.Cookie()
	pad, err := model.NewPad(db, pmTestUser.ID, "pm del", "test pm del", nil, nil)
	if err != nil {
		t.Fatalf("Cannot create pad for later deletion: %s", err)
	}

	resp, err := jsonapi.HandlerTest(pc().Delete).Get(fmt.Sprintf("/api/delete/%d", pad.ID), cookie)
	if err != nil {
		t.Fatalf("Error occured when delete pad: %s", err)
	}

	if !testResult(resp.Body, true) {
		t.Errorf("Failed to delete pad#%d: returned %s", pad.ID, resp.Body.String())
	}
}
Ejemplo n.º 21
0
func TestPadDelAclCoop(t *testing.T) {
	sess := session(pc().SF, t)
	sess.Login(pdAclCoop)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("Failed to login with coop when test delete ACL: %s", err)
	}
	resp, err := jsonapi.HandlerTest(pc().Delete).Get(pdAclURI, sess.Cookie())
	if err != nil {
		t.Fatalf("Error occured while testing pad delete ACL with coop: %s", err)
	}

	if !testResult(resp.Body, false) {
		t.Errorf("Delete success with coop: %s", resp.Body.String())
	}

	code, ok := testHasData(resp.Body, "code")
	if !ok {
		t.Errorf("Error code not found in deletion with coop: %s", resp.Body.String())
	}
	if !eqInt(3, code) {
		t.Errorf("Expected error code is 3 when delete with coop, got %d", code)
	}
}
Ejemplo n.º 22
0
func TestValidEditor(t *testing.T) {
	cfg := map[string]string{
		"RedisAddr":    ":6379",
		"SessSecret":   "1234567890",
		"SessName":     "mdpadtest",
		"ValidEditors": "*****@*****.**",
	}
	pc := &Pad{db, sf, cfg}

	u, err := model.NewUser("invalid editor", "*****@*****.**", "https://patrolavia.com/logo128.png")
	if err != nil {
		t.Fatalf("Cannot create invalid user to test valid editor: %s", err)
	}
	vu, err := model.NewUser("valid editor", "*****@*****.**", "https://patrolavia.com/logo128.png")
	if err != nil {
		t.Fatalf("Cannot create valid user to test valid editor: %s", err)
	}

	sess := session(sf, t)
	sess.Login(u)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("Cannot login as invalid editor: %s", err)
	}

	pad := map[string]interface{}{
		"title":   "invalid edit",
		"content": "test invalid edit",
	}

	resp, err := jsonapi.HandlerTest(pc.Create).PostJSON("/api/create", sess.Cookie(), pad)
	if err != nil {
		t.Fatalf("Failed to get response of creating pad with invalid editor: %s", err)
	}

	if !testResult(resp.Body, false) {
		t.Errorf("api call should fail when invalid editor tries to create pad: %s", resp.Body.String())
	}

	if !testData(3, resp.Body, "code") {
		t.Errorf("api call should return errcode 1 when invalid editor tries to create pad: %s", resp.Body.String())
	}

	sess.Login(vu)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("Cannot login as valid editor: %s", err)
	}

	resp, err = jsonapi.HandlerTest(pc.Create).PostJSON("/api/create", sess.Cookie(), pad)
	if err != nil {
		t.Fatalf("Failed to get response of creating pad with invalid editor: %s", err)
	}

	if !testResult(resp.Body, true) {
		t.Errorf("api call should be ok when valid editor tries to create pad: %s", resp.Body.String())
	}

	if !testData(0, resp.Body, "code") {
		t.Errorf("api call should return errcode 0 when valid editor tries to create pad: %s", resp.Body.String())
	}
}
Ejemplo n.º 23
0
func realTestCreate(t *testing.T, tags []string, coops []int) {
	t.Logf("Test pad creation with tags %v and coops %v", tags, coops)
	randomString := rand.Int()
	randomTitle := fmt.Sprintf("pm create-%d", randomString)
	param := map[string]interface{}{
		"title":      randomTitle,
		"content":    fmt.Sprintf("test pm create-%d", randomString),
		"tags":       tags,
		"cooperator": coops,
	}
	sess := session(pc().SF, t)
	sess.Login(pmTestUser)
	sess.Save()
	if err := sess.Err(); err != nil {
		t.Fatalf("Failed to login for creating pad: %s", err)
	}
	cookie := sess.Cookie()

	resp, err := jsonapi.HandlerTest(pc().Create).PostJSON("/api/create", cookie, param)
	if err != nil {
		t.Fatalf("While getting response of pad creation: %s", err)
	}

	if !testResult(resp.Body, true) {
		t.Fatalf("Returns error when creating pad: %s", resp.Body.String())
	}

	data, ok := testHasData(resp.Body, "id")
	if !ok {
		t.Fatalf("No pad returned from creating pad: %s", resp.Body.String())
	}

	var pid int
	switch v := data.(type) {
	case float64, float32:
		pid = int(reflect.ValueOf(v).Float())
	case int64, int32, int16, int8, int:
		pid = int(reflect.ValueOf(v).Int())
	default:
		t.Fatalf("returned pid is not integer: %#v", data)
	}

	pad, err := model.LoadPad(pid)
	if err != nil {
		t.Fatalf("Failed to save created pad into db: %s", err)
	}
	if pad.Title != randomTitle {
		t.Errorf("Expected title [%s], got [%s]", randomTitle, pad.Title)
	}
	ts := tags
	if tags == nil {
		ts = []string{}
	}
	if !reflect.DeepEqual(pad.Tags, ts) {
		t.Errorf("Expected tags %v, got %v", tags, pad.Tags)
	}
	c := coops
	if coops == nil {
		c = []int{}
	}
	if !reflect.DeepEqual(pad.Cooperators, c) {
		t.Errorf("Expected coops %v, got %v", coops, pad.Cooperators)
	}
}