コード例 #1
0
func TestWithdrawalList(t *testing.T) {
	Convey("Given withdrawal list controller", t, func() {
		handler := WithdrawalList(mockGetWithdrawals(nil, fmt.Errorf("")), nil, nil)

		Convey("When get withdrawal list with invalid limit", func() {
			route := "/withdrawals"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route+"?limit=3i", nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 400", func() {
				So(resp.Code, ShouldEqual, 400)
			})
		})

		Convey("When get withdrawal list", func() {
			route := "/withdrawals"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given withdrawal list controller with correct dependencies injected", t, func() {
		getWithdrawals := mockGetWithdrawals([]models.Withdrawal{{}}, nil)
		handler := WithdrawalList(getWithdrawals, func(int64) (int64, error) { return 0, nil }, func(tx string) string { return tx })

		Convey("When get withdrawal list", func() {
			route := "/withdrawals"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route+"?until=1234567890", nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #2
0
ファイル: reward_test.go プロジェクト: solefaucet/sole-server
func TestRewardList(t *testing.T) {
	Convey("Given reward list handler", t, func() {
		handler := RewardList(mockGetRewardIncomes(nil, fmt.Errorf("")), nil)

		Convey("When get reward list with invalid limit", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route+"?limit=3i", nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 400", func() {
				So(resp.Code, ShouldEqual, 400)
			})
		})

		Convey("When get reward list with errored handler", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given reward list handler", t, func() {
		handler := RewardList(mockGetRewardIncomes(nil, nil), func(int64) (int64, error) { return 0, nil })

		Convey("When get reward list", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, http.StatusOK)
			})
		})
	})
}
コード例 #3
0
ファイル: user_test.go プロジェクト: solefaucet/sole-server
func TestGetReferees(t *testing.T) {
	Convey("Given referee list handler with errored dependency", t, func() {
		handler := RefereeList(mockGetReferees(nil, fmt.Errorf("")), nil)

		Convey("When get reward list with invalid offset", func() {
			route := "/users/referees"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route+"?offset=3i", nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 400", func() {
				So(resp.Code, ShouldEqual, 400)
			})
		})

		Convey("When get referee list", func() {
			route := "/users/referees"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given referee list controller with correct dependencies injected", t, func() {
		handler := RefereeList(mockGetReferees(nil, nil), func(int64) (int64, error) { return 0, nil })

		Convey("When get referee list", func() {
			route := "/users/referees"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #4
0
func TestWebsocket(t *testing.T) {
	Convey("Given a webserver with websocket controller", t, func() {
		handler := Websocket(
			mockGetUsersOnline(1),
			mockGetLatestIncomes([]interface{}{123.456, "hello"}),
			mockBroadcast(),
			mockPutConn(),
		)

		Convey("When websocket connect", func() {
			route := "/websocket"
			_, _, r := gin.CreateTestContext()
			r.GET(route, handler)
			server := httptest.NewServer(r)

			conn, resp, _ := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+route, nil)

			Convey("Response code should be 101", func() {
				So(resp.StatusCode, ShouldEqual, 101)
			})

			m := models.WebsocketMessage{}
			conn.ReadJSON(&m)
			Convey("Receive data through websocket should resemble", func() {
				So(m, ShouldResemble, models.WebsocketMessage{
					UsersOnline:   2,
					LatestIncomes: []interface{}{123.456, "hello"},
				})
			})

			Reset(func() {
				server.Close()
				conn.Close()
			})
		})
	})

	Convey("Given websocket controller", t, func() {
		handler := Websocket(nil, nil, nil, nil)

		Convey("HTTP connect", func() {
			route := "/websocket"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 400", func() {
				So(resp.Code, ShouldEqual, 400)
			})
		})
	})
}
コード例 #5
0
ファイル: main_test.go プロジェクト: kevineaton/go-esperanto
func Test_GetAll(t *testing.T) {
	phrases := loadPhrasebook()
	c, w, _ := gin.CreateTestContext()
	GetAllWords(c, phrases)
	assert.Equal(t, w.Code, 200)
	assert.NotEqual(t, w.Body.String(), "")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}
コード例 #6
0
ファイル: main_test.go プロジェクト: kevineaton/go-esperanto
func Test_Post_Not_Authorized(t *testing.T) {
	c, w, _ := gin.CreateTestContext()
	c.Set("Authenticated", false)
	phrases := loadPhrasebook()
	SaveNewPair(c, phrases)
	assert.Equal(t, w.Code, 401)
	assert.NotEqual(t, w.Body.String(), "")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}
コード例 #7
0
ファイル: user_test.go プロジェクト: solefaucet/sole-server
func TestGetUserInfo(t *testing.T) {
	Convey("Given get user info controller with errored getUserByID dependency", t, func() {
		getUserByID := mockGetUserByID(models.User{}, errors.ErrNotFound)
		handler := UserInfo(getUserByID)

		Convey("When get user info", func() {
			route := "/users"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given get user info controller with correctly dependencies injected", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		handler := UserInfo(getUserByID)

		Convey("When get user info", func() {
			route := "/users"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #8
0
ファイル: middleware_test.go プロジェクト: thedodd/api
func TestRequestIDSetsExpectedHeader(t *testing.T) {
	context, _, _ := gin.CreateTestContext()

	RequestID(context)
	header := context.Writer.Header().Get("X-Request-ID")

	length := len(header)
	if length != 36 { // Length of UUID4.
		t.Errorf("Length of ID should be 36; got %d", length)
		t.Fail()
	}
}
コード例 #9
0
func TestLogout(t *testing.T) {
	Convey("Given Logout controller with errored logout dependency", t, func() {
		handler := Logout(mockDeleteAuthToken(fmt.Errorf("")))

		Convey("When logout", func() {
			route := "/auth_tokens"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.DELETE(route, handler)
			req, _ := http.NewRequest("DELETE", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given Logout controller", t, func() {
		handler := Logout(mockDeleteAuthToken(nil))

		Convey("When logout", func() {
			route := "/auth_tokens"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.DELETE(route, handler)
			req, _ := http.NewRequest("DELETE", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #10
0
func TestRegisterCaptcha(t *testing.T) {
	Convey("Given errored register captcha handler", t, func() {
		getCaptchaID := func() string { return "" }
		registerCaptcha := func() (string, error) { return "", fmt.Errorf("") }
		handler := RegisterCaptcha(registerCaptcha, getCaptchaID)

		Convey("When request register captcha", func() {
			route := "/captcha"
			_, resp, r := gin.CreateTestContext()
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response status code should be 503", func() {
				So(resp.Code, ShouldEqual, 503)
			})
		})
	})

	Convey("Given error free register captcha handler", t, func() {
		getCaptchaID := func() string { return "" }
		registerCaptcha := func() (string, error) { return "", nil }
		handler := RegisterCaptcha(registerCaptcha, getCaptchaID)

		Convey("When request register captcha", func() {
			route := "/captcha"
			_, resp, r := gin.CreateTestContext()
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response status code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #11
0
ファイル: middleware_test.go プロジェクト: thedodd/api
//////////////////////////
// Tests for RequestID. //
//////////////////////////
func TestRequestIDSetsExpectedRequestID(t *testing.T) {
	context, _, _ := gin.CreateTestContext()

	RequestID(context)
	value, exists := context.Get("request_id")

	if !exists {
		t.Error("Key is expected to exist.")
		t.Fail()
	}

	length := len(value.(string))
	if length != 36 { // Length of UUID4.
		t.Errorf("Length of ID should be 36; got %d", length)
		t.Fail()
	}
}
コード例 #12
0
func TestRequestVerifyEmail(t *testing.T) {
	Convey("Given request verify email controller with errored getUserByID dependency", t, func() {
		getUserByID := mockGetUserByID(models.User{}, fmt.Errorf(""))
		handler := RequestVerifyEmail(getUserByID, nil, nil, nil, "", "")

		Convey("When request verify email", func() {
			route := "/sessions"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given request verify email controller with user last sent email within one hour", t, func() {
		getUserByID := mockGetUserByID(models.User{EmailSentAt: time.Now().Add(-29 * time.Minute)}, nil)
		handler := RequestVerifyEmail(getUserByID, nil, nil, nil, "", "")

		Convey("When request verify email", func() {
			route := "/sessions"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 429", func() {
				So(resp.Code, ShouldEqual, http.StatusTooManyRequests)
			})
		})
	})

	Convey("Given request verify email controller with errored upsertSession dependency", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		upsertSession := mockUpsertSession(fmt.Errorf(""))
		handler := RequestVerifyEmail(getUserByID, upsertSession, nil, nil, "", "")

		Convey("When request verify email", func() {
			route := "/sessions"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given request verify email controller with errored sendEmail dependency", t, func() {
		getUserByID := mockGetUserByID(models.User{Email: "*****@*****.**"}, nil)
		upsertSession := mockUpsertSession(nil)
		sendEmail := mockSendEmail(fmt.Errorf(""))
		tmpl := template.Must(template.New("template").Parse(`email: {{.email}} token: {{.token}}`))
		handler := RequestVerifyEmail(getUserByID, upsertSession, sendEmail, tmpl, "", "")

		Convey("When request verify email", func() {
			route := "/sessions"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given request verify email controller with correct dependencies injected", t, func() {
		getUserByID := mockGetUserByID(models.User{Email: "*****@*****.**"}, nil)
		upsertSession := mockUpsertSession(nil)
		sendEmail := mockSendEmail(nil)
		tmpl := template.Must(template.New("template").Parse(`email: {{.email}} token: {{.token}}`))
		handler := RequestVerifyEmail(getUserByID, upsertSession, sendEmail, tmpl, "", "")

		Convey("When request verify email", func() {
			route := "/sessions"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #13
0
ファイル: user_test.go プロジェクト: solefaucet/sole-server
func TestSignup(t *testing.T) {
	requestDataJSON := func(email string) []byte {
		raw, _ := json.Marshal(map[string]interface{}{
			"email":      email,
			"address":    "address",
			"referer_id": 2,
		})
		return raw
	}

	testdata := []struct {
		when            string
		requestData     []byte
		code            int
		getUserByID     dependencyGetUserByID
		createUser      dependencyCreateUser
		validateAddress func(string) (bool, error)
	}{
		{
			"invalid json data",
			[]byte("huhu"),
			400,
			nil,
			nil,
			nil,
		},
		{
			"invalid email",
			requestDataJSON(invalidEmail),
			400,
			nil,
			nil,
			nil,
		},
		{
			"invalid address",
			requestDataJSON(validEmail),
			400,
			nil,
			nil,
			func(string) (bool, error) { return false, nil },
		},
		{
			"duplicate email",
			requestDataJSON(validEmail),
			409,
			mockGetUserByID(models.User{}, nil),
			mockCreateUser(errors.ErrDuplicatedEmail),
			func(string) (bool, error) { return true, nil },
		},
		{
			"valid email, but create user unknown error",
			requestDataJSON(validEmail),
			500,
			mockGetUserByID(models.User{}, nil),
			mockCreateUser(fmt.Errorf("")),
			func(string) (bool, error) { return true, nil },
		},
		{
			"valid email",
			requestDataJSON(validEmail),
			200,
			mockGetUserByID(models.User{}, nil),
			mockCreateUser(nil),
			func(string) (bool, error) { return true, nil },
		},
	}

	for _, v := range testdata {
		Convey("Given Signup controller", t, func() {
			handler := Signup(v.validateAddress, v.createUser, v.getUserByID)

			Convey(fmt.Sprintf("When request with %s", v.when), func() {
				route := "/users"
				_, resp, r := gin.CreateTestContext()
				r.POST(route, handler)
				req, _ := http.NewRequest("POST", route, bytes.NewBuffer(v.requestData))
				r.ServeHTTP(resp, req)

				Convey(fmt.Sprintf("Response code should be equal to %d", v.code), func() {
					So(resp.Code, ShouldEqual, v.code)
				})
			})
		})
	}
}
コード例 #14
0
func TestLogin(t *testing.T) {
	requestDataJSON := func(email string) []byte {
		raw, _ := json.Marshal(map[string]interface{}{
			"email": email,
		})
		return raw
	}

	testdata := []struct {
		when            string
		requestData     []byte
		code            int
		getUserByEmail  dependencyGetUserByEmail
		createAuthToken dependencyCreateAuthToken
	}{
		{
			"invalid json data",
			[]byte("huhu"),
			400,
			nil,
			nil,
		},
		{
			"invalid email",
			requestDataJSON(invalidEmail),
			400,
			nil,
			nil,
		},
		{
			"banned user",
			requestDataJSON(validEmail),
			403,
			mockGetUserByEmail(models.User{Status: models.UserStatusBanned}, nil),
			nil,
		},
		{
			"non existing email",
			requestDataJSON(validEmail),
			404,
			mockGetUserByEmail(models.User{}, errors.ErrNotFound),
			nil,
		},
		{
			"valid email, unknown error",
			requestDataJSON(validEmail),
			500,
			mockGetUserByEmail(models.User{}, fmt.Errorf("")),
			nil,
		},
		{
			"valid existing email, but unknown error",
			requestDataJSON(validEmail),
			500,
			mockGetUserByEmail(models.User{}, nil),
			mockCreateAuthToken(fmt.Errorf("")),
		},
		{
			"valid existing email",
			requestDataJSON(validEmail),
			201,
			mockGetUserByEmail(models.User{}, nil),
			mockCreateAuthToken(nil),
		},
	}

	for _, v := range testdata {
		Convey("Given Login controller", t, func() {
			handler := Login(v.getUserByEmail, v.createAuthToken)

			Convey(fmt.Sprintf("When request with %s", v.when), func() {
				route := "/auth_tokens"
				_, resp, r := gin.CreateTestContext()
				r.POST(route, handler)
				req, _ := http.NewRequest("POST", route, bytes.NewBuffer(v.requestData))
				r.ServeHTTP(resp, req)

				Convey(fmt.Sprintf("Response code should be equal to %d", v.code), func() {
					So(resp.Code, ShouldEqual, v.code)
				})
			})
		})
	}
}
コード例 #15
0
func TestSuperrewardsCallback(t *testing.T) {
	Convey("Given superrewards callback handler with invalid parameters", t, func() {
		handler := SuperrewardsCallback("", nil, nil, nil, nil, nil)

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 400", func() {
				So(resp.Code, ShouldEqual, 400)
			})
		})
	})

	Convey("Given superrewards callback handler with invalid signature", t, func() {
		handler := SuperrewardsCallback("secret", nil, nil, nil, nil, nil)
		query := "id=id&uid=1&new=13.2&sig=4b2ae6c496"

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s?%s", route, query), nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 403", func() {
				So(resp.Code, ShouldEqual, 403)
			})
		})
	})

	Convey("Given superrewards callback handler with errored getUserByID", t, func() {
		getUserByID := mockGetUserByID(models.User{}, fmt.Errorf(""))
		handler := SuperrewardsCallback("secret", getUserByID, nil, nil, nil, nil)
		query := "id=id&uid=1&new=13.2&sig=4b2ae6c496f862b258e8b6b9d3242257"

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s?%s", route, query), nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given superrewards callback handler with non-err-not-found errored getNumberOfSuperrewardsOffers", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		getNumberOfSuperrewardsOffers := mockGetNumberOfSuperrewardsOffers(0, fmt.Errorf(""))
		handler := SuperrewardsCallback("secret", getUserByID, getNumberOfSuperrewardsOffers, nil, nil, nil)
		query := "id=id&uid=1&new=13.2&sig=4b2ae6c496f862b258e8b6b9d3242257"

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s?%s", route, query), nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given superrewards callback handler with getNumberOfSuperrewardsOffers returning nil error", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		getNumberOfSuperrewardsOffers := mockGetNumberOfSuperrewardsOffers(2, nil)
		handler := SuperrewardsCallback("secret", getUserByID, getNumberOfSuperrewardsOffers, nil, nil, nil)
		query := "id=id&uid=1&new=13.2&sig=4b2ae6c496f862b258e8b6b9d3242257"

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s?%s", route, query), nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})

			Convey("Response body should be 1", func() {
				So(resp.Body.String(), ShouldEqual, "1")
			})
		})
	})

	Convey("Given superrewards callback handler without superrewards offers and errored createSuperrewardsIncome", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		getNumberOfSuperrewardsOffers := mockGetNumberOfSuperrewardsOffers(0, nil)
		getSystemConfig := mockGetSystemConfig(models.Config{})
		createSuperrewardsIncome := mockCreateSuperrewardsIncome(fmt.Errorf(""))
		handler := SuperrewardsCallback("secret", getUserByID, getNumberOfSuperrewardsOffers, getSystemConfig, createSuperrewardsIncome, nil)
		query := "id=id&uid=1&new=13.2&sig=4b2ae6c496f862b258e8b6b9d3242257"

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s?%s", route, query), nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given superrewards callback handler without superrewards offers and correct createSuperrewardsIncome", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		getNumberOfSuperrewardsOffers := mockGetNumberOfSuperrewardsOffers(0, nil)
		getSystemConfig := mockGetSystemConfig(models.Config{})
		createSuperrewardsIncome := mockCreateSuperrewardsIncome(nil)
		handler := SuperrewardsCallback("secret", getUserByID, getNumberOfSuperrewardsOffers, getSystemConfig, createSuperrewardsIncome, func([]byte) {})
		query := "id=id&uid=1&new=13.2&sig=4b2ae6c496f862b258e8b6b9d3242257"

		Convey("When callback", func() {
			route := "/callback"
			_, resp, r := gin.CreateTestContext()
			r.GET(route, handler)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s?%s", route, query), nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #16
0
ファイル: reward_test.go プロジェクト: solefaucet/sole-server
func TestGetReward(t *testing.T) {
	Convey("Given get reward controller with errored getUserByID dependency", t, func() {
		getUserByID := mockGetUserByID(models.User{}, fmt.Errorf(""))
		handler := GetReward(getUserByID, nil, nil, nil, nil, nil, nil)

		Convey("When get reward", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given get reward controller with not valid last_rewarded", t, func() {
		getUserByID := mockGetUserByID(models.User{RewardedAt: time.Now(), RewardInterval: 5}, nil)
		handler := GetReward(getUserByID, nil, nil, nil, nil, nil, nil)

		Convey("When get reward", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 429", func() {
				So(resp.Code, ShouldEqual, statusCodeTooManyRequests)
			})
		})
	})

	Convey("Given get reward controller with errored createRewardIncome dependency", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		getLatestTotalReward := mockGetLatestTotalReward(models.TotalReward{CreatedAt: time.Now(), Total: 11})
		getSystemConfig := mockGetSystemConfig(models.Config{TotalRewardThreshold: 10, RefererRewardRate: 10})
		getRewardRatesByType := mockGetRewardRatesByType([]models.RewardRate{
			{Weight: 1, Min: 1, Max: 10},
			{Weight: 2, Min: 11, Max: 20},
			{Weight: 3, Min: 21, Max: 30},
		})
		createRewardIncome := mockCreateRewardIncome(fmt.Errorf(""))
		handler := GetReward(getUserByID, getLatestTotalReward, getSystemConfig, getRewardRatesByType, createRewardIncome, nil, nil)

		Convey("When get reward", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given get reward controller with everything correctly configured", t, func() {
		getUserByID := mockGetUserByID(models.User{}, nil)
		getLatestTotalReward := mockGetLatestTotalReward(models.TotalReward{CreatedAt: time.Now().UTC(), Total: 11})
		getSystemConfig := mockGetSystemConfig(models.Config{TotalRewardThreshold: 10, RefererRewardRate: 10})
		getRewardRatesByType := mockGetRewardRatesByType([]models.RewardRate{
			{Weight: 1, Min: 1, Max: 10},
			{Weight: 2, Min: 11, Max: 20},
			{Weight: 3, Min: 21, Max: 30},
		})
		createRewardIncome := mockCreateRewardIncome(nil)
		insertIncome := mockInsertIncome()
		broadcast := mockBroadcast()
		handler := GetReward(getUserByID,
			getLatestTotalReward,
			getSystemConfig,
			getRewardRatesByType,
			createRewardIncome,
			insertIncome,
			broadcast,
		)

		Convey("When get reward", func() {
			route := "/incomes/rewards"
			_, resp, r := gin.CreateTestContext()
			r.Use(func(c *gin.Context) {
				c.Set("auth_token", models.AuthToken{})
			})
			r.POST(route, handler)
			req, _ := http.NewRequest("POST", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}
コード例 #17
0
ファイル: user_test.go プロジェクト: solefaucet/sole-server
func TestVerifyEmail(t *testing.T) {
	Convey("Given verify email controller with expired session and errored getSessionByToken dependency", t, func() {
		getSessionByToken := mockGetSessionByToken(models.Session{}, fmt.Errorf(""))
		handler := VerifyEmail(getSessionByToken, nil, nil)

		Convey("When verify email", func() {
			route := "/users/1/status"
			_, resp, r := gin.CreateTestContext()
			r.PUT(route, handler)
			req, _ := http.NewRequest("PUT", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, http.StatusInternalServerError)
			})
		})
	})

	Convey("Given verify email controller with expired session and getSessionByToken dependency", t, func() {
		getSessionByToken := mockGetSessionByToken(models.Session{}, nil)
		handler := VerifyEmail(getSessionByToken, nil, nil)

		Convey("When verify email", func() {
			route := "/users/1/status"
			_, resp, r := gin.CreateTestContext()
			r.PUT(route, handler)
			req, _ := http.NewRequest("PUT", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 401", func() {
				So(resp.Code, ShouldEqual, 401)
			})
		})
	})

	Convey("Given verify email controller with errored getUserByID dependency", t, func() {
		getSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)
		getUserByID := mockGetUserByID(models.User{}, fmt.Errorf(""))
		handler := VerifyEmail(getSessionByToken, getUserByID, nil)

		Convey("When verify email", func() {
			route := "/users/1/status"
			_, resp, r := gin.CreateTestContext()
			r.PUT(route, handler)
			req, _ := http.NewRequest("PUT", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given verify email controller with banned user status", t, func() {
		getSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)
		getUserByID := mockGetUserByID(models.User{Status: models.UserStatusBanned}, nil)
		handler := VerifyEmail(getSessionByToken, getUserByID, nil)

		Convey("When verify email", func() {
			route := "/users/1/status"
			_, resp, r := gin.CreateTestContext()
			r.PUT(route, handler)
			req, _ := http.NewRequest("PUT", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 403", func() {
				So(resp.Code, ShouldEqual, 403)
			})
		})
	})

	Convey("Given verify email controller with errored updateUser dependency", t, func() {
		getSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)
		getUserByID := mockGetUserByID(models.User{}, nil)
		updateUserStatus := mockUpdateUserStatus(fmt.Errorf(""))
		handler := VerifyEmail(getSessionByToken, getUserByID, updateUserStatus)

		Convey("When verify email", func() {
			route := "/users/1/status"
			_, resp, r := gin.CreateTestContext()
			r.PUT(route, handler)
			req, _ := http.NewRequest("PUT", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 500", func() {
				So(resp.Code, ShouldEqual, 500)
			})
		})
	})

	Convey("Given verify email controller with correct dependencies injected", t, func() {
		getSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)
		getUserByID := mockGetUserByID(models.User{}, nil)
		updateUserStatus := mockUpdateUserStatus(nil)
		handler := VerifyEmail(getSessionByToken, getUserByID, updateUserStatus)

		Convey("When verify email", func() {
			route := "/users/1/status"
			_, resp, r := gin.CreateTestContext()
			r.PUT(route, handler)
			req, _ := http.NewRequest("PUT", route, nil)
			r.ServeHTTP(resp, req)

			Convey("Response code should be 200", func() {
				So(resp.Code, ShouldEqual, 200)
			})
		})
	})
}