Created
September 30, 2019 15:41
-
-
Save vianhanif/f67eb97bc9300ebc45fd3b66f612e2e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package handlers_test | |
import ( | |
"bytes" | |
"context" | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"net/http/httptest" | |
"reflect" | |
"testing" | |
"time" | |
"github.com/go-chi/chi" | |
"github.com/payfazz/payfazz-cashback/config" | |
"github.com/payfazz/payfazz-cashback/internal/app" | |
"github.com/payfazz/payfazz-cashback/internal/disbursement" | |
"github.com/payfazz/payfazz-cashback/internal/httpserver/handlers" | |
"github.com/payfazz/payfazz-cashback/internal/httpserver/middleware" | |
"github.com/payfazz/payfazz-cashback/internal/test" | |
) | |
var a *app.App | |
var ctx context.Context | |
func init() { | |
ctx = context.TODO() | |
a = test.GetApp(ctx) | |
} | |
func TestPagination(t *testing.T) { | |
offset, limit := handlers.OnPagination([]string{"1"}, []string{"10"}) | |
if limit != 10 { | |
t.Fatal("limit is not 10") | |
} | |
if offset != 0 { | |
t.Fatal("offset is not 0") | |
} | |
offset, limit = handlers.OnPagination([]string{"2"}, []string{"10"}) | |
if offset != 10 { | |
t.Fatal("offset is not 10") | |
} | |
offset, limit = handlers.OnPagination([]string{"1"}, []string{"20"}) | |
if limit != 20 { | |
t.Fatal("limit is not 20") | |
} | |
} | |
func TestCreateCashback(t *testing.T) { | |
mcPostBody := map[string]interface{}{ | |
"userId": 1, | |
"type": "bonus", | |
"typeId": "1", | |
"description": "", | |
"metadata": json.RawMessage("{}"), | |
} | |
body, _ := json.Marshal(mcPostBody) | |
handler := handlerFunc(middleware.Private(a.Config), handlers.CreateCashback()) | |
req := private(a.Config)(httpRequestor( | |
"/private/v1/cashbacks", | |
"POST", | |
handler, | |
body, | |
)) | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &handlers.CashbackResponse{} | |
err := json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if data.CashbackID == "" { | |
t.Error("cashbackId is not generated") | |
} | |
} | |
func TestInvalidMetadata(t *testing.T) { | |
postBody := map[string]interface{}{ | |
"userId": 2, | |
"type": "bonus", | |
"typeId": "2", | |
"description": "", | |
"metadata": "invalid", | |
} | |
body, _ := json.Marshal(postBody) | |
handler := handlerFunc(middleware.Private(a.Config), handlers.CreateCashback()) | |
req := private(a.Config)(httpRequestor( | |
"/private/v1/cashbacks", | |
"POST", | |
handler, | |
body, | |
)) | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusBadRequest { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) | |
} | |
} | |
func TestViewCashbackByCashbackId(t *testing.T) { | |
record := test.FakeCashback(1, 1000, disbursement.TypeCashback) | |
_, err := a.Services.Cashback.Create(context.TODO(), record) | |
if err != nil { | |
t.Fatal(err) | |
} | |
rctx := chi.NewRouteContext() | |
rctx.URLParams.Add("cashbackId", record.CashbackID) | |
ctx := context.WithValue(context.TODO(), chi.RouteCtxKey, rctx) | |
handler := handlerFunc(middleware.Private(a.Config), handlers.GetCashback()) | |
req := private(a.Config)(httpRequestor( | |
fmt.Sprintf("/private/v1/cashbacks/%s", record.CashbackID), | |
"GET", | |
handler, | |
nil, | |
)) | |
res := httpWriter() | |
handler.ServeHTTP(res, req.WithContext(ctx)) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &handlers.CashbackResponse{} | |
err = json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if data.CashbackID == "" { | |
t.Error("cashback id not found") | |
} | |
} | |
func TestNotFoundCashback(t *testing.T) { | |
rctx := chi.NewRouteContext() | |
rctx.URLParams.Add("cashbackId", "empty") | |
ctx := context.WithValue(context.TODO(), chi.RouteCtxKey, rctx) | |
handler := handlerFunc(middleware.Private(a.Config), handlers.GetCashback()) | |
req := private(a.Config)(httpRequestor( | |
"/private/v1/cashbacks/empty", | |
"GET", | |
handler, | |
nil, | |
)) | |
res := httpWriter() | |
handler.ServeHTTP(res, req.WithContext(ctx)) | |
status := res.Code | |
if status != http.StatusBadRequest { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) | |
} | |
} | |
func TestSumCashback(t *testing.T) { | |
record := test.FakeCashback(1, 1000, disbursement.TypeCashback) | |
_, err := a.Services.Cashback.Create(context.TODO(), record) | |
if err != nil { | |
t.Fatal(err) | |
} | |
err = a.Clients.Redis.Set("session:token", fmt.Sprintf(`{"userId": %d}`, record.UserID), 0).Err() | |
if err != nil { | |
t.Fatal(err) | |
} | |
handler := handlerFunc(middleware.PayfazzAuthenticator(), handlers.SumCashback()) | |
req := payfazzAuth(httpRequestor( | |
"/v1/cashbacks/sum", | |
"GET", | |
handler, | |
nil, | |
)) | |
query := req.URL.Query() | |
query.Add("type", record.Type) | |
query.Add("fromDate", time.Now().Format("2006-01-02")) | |
query.Add("toDate", time.Now().AddDate(0, 1, 0).Format("2006-01-02")) | |
req.URL.RawQuery = query.Encode() | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &handlers.SumResponse{} | |
err = json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if data.UserID == 0 { | |
t.Error("userId not found") | |
} | |
} | |
func TestSumCashbackWithoutDateRange(t *testing.T) { | |
record := test.FakeCashback(1, 1000, disbursement.TypeCashback) | |
_, err := a.Services.Cashback.Create(context.TODO(), record) | |
if err != nil { | |
t.Fatal(err) | |
} | |
err = a.Clients.Redis.Set("session:token", fmt.Sprintf(`{"userId": %d}`, record.UserID), 0).Err() | |
if err != nil { | |
t.Fatal(err) | |
} | |
handler := handlerFunc(middleware.PayfazzAuthenticator(), handlers.SumCashback()) | |
req := payfazzAuth(httpRequestor( | |
"/v1/cashbacks/sum", | |
"GET", | |
handler, | |
nil, | |
)) | |
query := req.URL.Query() | |
query.Add("type", record.Type) | |
req.URL.RawQuery = query.Encode() | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &handlers.SumResponse{} | |
err = json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if data.UserID == 0 { | |
t.Error("userId not found") | |
} | |
} | |
func TestListCashbackWithFilters(t *testing.T) { | |
record := test.FakeCashback(1, 1000, disbursement.TypeCashback) | |
_, err := a.Services.Cashback.Create(context.TODO(), record) | |
if err != nil { | |
t.Fatal(err) | |
} | |
err = a.Clients.Redis.Set("session:token", fmt.Sprintf(`{"userId": %d}`, record.UserID), 0).Err() | |
if err != nil { | |
t.Fatal(err) | |
} | |
handler := handlerFunc(middleware.PayfazzAuthenticator(), handlers.ListCashback()) | |
req := payfazzAuth(httpRequestor( | |
"/v1/cashbacks", | |
"GET", | |
handler, | |
nil, | |
)) | |
query := req.URL.Query() | |
query.Add("status", "pending") | |
query.Add("fromDate", time.Now().Format("2006-01-02")) | |
query.Add("toDate", time.Now().AddDate(0, 1, 0).Format("2006-01-02")) | |
req.URL.RawQuery = query.Encode() | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &[]handlers.CashbackResponse{} | |
err = json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if len(*data) < 1 { | |
t.Error(*data) | |
} | |
} | |
func TestListCashbackWithoutDateRange(t *testing.T) { | |
record := test.FakeCashback(1, 1000, disbursement.TypeCashback) | |
_, err := a.Services.Cashback.Create(context.TODO(), record) | |
if err != nil { | |
t.Fatal(err) | |
} | |
err = a.Clients.Redis.Set("session:token", fmt.Sprintf(`{"userId": %d}`, record.UserID), 0).Err() | |
if err != nil { | |
t.Fatal(err) | |
} | |
handler := handlerFunc(middleware.PayfazzAuthenticator(), handlers.ListCashback()) | |
req := payfazzAuth(httpRequestor( | |
"/v1/cashbacks", | |
"GET", | |
handler, | |
nil, | |
)) | |
query := req.URL.Query() | |
query.Add("status", "pending") | |
req.URL.RawQuery = query.Encode() | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &[]handlers.CashbackResponse{} | |
err = json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if len(*data) < 1 { | |
t.Error(*data) | |
} | |
} | |
func TestListCashbackDataNotFound(t *testing.T) { | |
err := a.Clients.Redis.Set("session:token", `{"userId": 10}`, 0).Err() | |
if err != nil { | |
t.Fatal(err) | |
} | |
handler := handlerFunc(middleware.PayfazzAuthenticator(), handlers.ListCashback()) | |
req := payfazzAuth(httpRequestor( | |
"/v1/cashbacks", | |
"GET", | |
handler, | |
nil, | |
)) | |
query := req.URL.Query() | |
query.Add("type", disbursement.TypeCommision) | |
req.URL.RawQuery = query.Encode() | |
res := httpWriter() | |
handler.ServeHTTP(res, req) | |
status := res.Code | |
if status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) | |
} | |
data := &[]handlers.CashbackResponse{} | |
err = json.NewDecoder(res.Body).Decode(data) | |
if err != nil { | |
t.Error("error decoding body response") | |
} | |
if reflect.TypeOf(*data).Kind() != reflect.Slice { | |
t.Error("response should return empty array") | |
} | |
} | |
func httpRequestor(path, method string, handler http.Handler, body []byte) *http.Request { | |
return httptest.NewRequest(method, path, bytes.NewReader(body)) | |
} | |
func httpWriter() *httptest.ResponseRecorder { | |
return httptest.NewRecorder() | |
} | |
func handlerFunc(middleware func(next http.Handler) http.Handler, h http.HandlerFunc) http.Handler { | |
return app.InjectorMiddleware(a)(middleware(http.HandlerFunc(h))) | |
} | |
func payfazzAuth(req *http.Request) *http.Request { | |
req.Header.Add("Content-Type", "application/json") | |
req.Header.Add("X-Access-Token", "token") | |
return req | |
} | |
func private(config *config.Config) func(req *http.Request) *http.Request { | |
return func(req *http.Request) *http.Request { | |
req.Header.Add("Content-Type", "application/json") | |
req.Header.Add("Authorization", fmt.Sprintf(`Bearer %s`, config.PrivateToken)) | |
return req | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment