Skip to content

Commit

Permalink
Tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mukulmantosh committed Oct 22, 2023
1 parent b3fe52e commit 6f2389f
Show file tree
Hide file tree
Showing 4 changed files with 274 additions and 2 deletions.
24 changes: 22 additions & 2 deletions internal/server/cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,33 @@ package server

import (
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/mukulmantosh/go-ecommerce-app/internal/generic/common_errors"
"github.com/mukulmantosh/go-ecommerce-app/internal/models"
"net/http"
"os"
)

func ParseJWTToken(tokenString string) (*models.CustomJWTClaims, error) {
// Parse the JWT token with custom claims
token, err := jwt.ParseWithClaims(tokenString, &models.CustomJWTClaims{}, func(token *jwt.Token) (interface{}, error) {
// Replace this with your own secret key or public key (if using asymmetric signing)
return []byte(os.Getenv("JWT_SECRET")), nil
})

if err != nil {
return nil, err
}

if claims, ok := token.Claims.(*models.CustomJWTClaims); ok && token.Valid {
return claims, nil
}

return nil, fmt.Errorf("invalid token")
}

func (s *EchoServer) CreateNewCart(ctx echo.Context) error {
cart := new(models.Cart)
if err := ctx.Bind(cart); err != nil {
Expand All @@ -32,7 +52,8 @@ func (s *EchoServer) CreateNewCart(ctx echo.Context) error {
func (s *EchoServer) AddItemToCart(ctx echo.Context) error {
product := new(models.ProductParams)
user := ctx.Get("user").(*jwt.Token)
claims := user.Claims.(*models.CustomJWTClaims)
//claims := user.Claims.(*models.CustomJWTClaims)
claims, err := ParseJWTToken(user.Raw)
userId := claims.UserID

if err := ctx.Bind(product); err != nil {
Expand All @@ -43,7 +64,6 @@ func (s *EchoServer) AddItemToCart(ctx echo.Context) error {
return ctx.JSON(http.StatusBadRequest,
map[string]any{"message": "Missing Product ID!"})
}

cartData, cartExist, err := s.DB.GetCartInfoByUserID(ctx.Request().Context(), userId)
if err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type Server interface {
abstract.UserAddress
abstract.Login
abstract.Category
abstract.Cart
}

type EchoServer struct {
Expand Down
187 changes: 187 additions & 0 deletions internal/tests/cart/add_items_to_cart_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package cart

import (
"encoding/json"
"github.com/go-faker/faker/v4"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/mukulmantosh/go-ecommerce-app/internal/models"
"github.com/mukulmantosh/go-ecommerce-app/internal/server"
"github.com/mukulmantosh/go-ecommerce-app/internal/tests"
"github.com/mukulmantosh/go-ecommerce-app/internal/utils"
"github.com/stretchr/testify/assert"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)

func TestAddItemsToCart(t *testing.T) {
testDB, _ := tests.Setup()
type FakeUser struct {
Username string `json:"username" faker:"username"`
Password string `json:"password" faker:"word,unique"`
FirstName string `json:"first_name" faker:"first_name"`
LastName string `json:"last_name" faker:"last_name"`
}

type FakeCategory struct {
Name string `json:"name" faker:"word,unique"`
Description string `json:"description" faker:"word,unique"`
}

type FakeProduct struct {
Name string `json:"name"`
Description string `json:"description"`
Price float64 `json:"price"`
CategoryID string `json:"category_id"`
}

type CategoryDataObj struct {
CreatedAt string `json:"CreatedAt"`
UpdatedAt string `json:"UpdatedAt"`
DeletedAt string `json:"DeletedAt"`
ID string `json:"ID"`
Name string `json:"name"`
Description string `json:"description"`
Product []models.Product `json:"product"`
}

type LoginResponse struct {
Message string `json:"message"`
Token string `json:"token"`
}

type ProductDataForCart struct {
ProductID string `json:"productID"`
}

t.Run("add items to cart", func(t *testing.T) {
var customUser FakeUser
_ = faker.FakeData(&customUser)
out, _ := json.Marshal(&customUser)
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/user", strings.NewReader(string(out)))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

var service = server.NewServer(testDB)
// Assertions
if assert.NoError(t, service.AddUser(c)) {
assert.Equal(t, http.StatusCreated, rec.Code)
}

var customCategory FakeCategory
_ = faker.FakeData(&customCategory)
out, _ = json.Marshal(&customCategory)
req = httptest.NewRequest(http.MethodPost, "/category", strings.NewReader(string(out)))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)

if assert.NoError(t, service.AddCategory(c)) {
assert.Equal(t, http.StatusCreated, rec.Code)
}

var newCategoryResp CategoryDataObj
data, _ := io.ReadAll(rec.Body)
err := json.Unmarshal(data, &newCategoryResp)
if err != nil {
t.Error(err)
}
categoryId := newCategoryResp.ID

addProduct := FakeProduct{
Name: "IPhone 15",
Description: "IPhone 15, the latest available phone from Apple",
Price: 3500.00,
CategoryID: categoryId,
}

AddProductJSON, err := utils.StructToJSON(addProduct)
if err != nil {
t.Error(err.Error())
}

newReq := httptest.NewRequest(http.MethodPost, "/products", strings.NewReader(AddProductJSON))
newReq.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
newRec := httptest.NewRecorder()
getContext := e.NewContext(newReq, newRec)
if assert.NoError(t, service.AddProduct(getContext)) {
assert.Equal(t, http.StatusCreated, newRec.Code)
}

type ProductInfo struct {
CreatedAt string `json:"CreatedAt"`
UpdatedAt string `json:"UpdatedAt"`
DeletedAt string `json:"DeletedAt"`
ID string `json:"ID"`
Name string `json:"name"`
Description string `json:"description"`
Price float64 `json:"price"`
CategoryID string `json:"category_id"`
}

var newProductResp ProductInfo
data, _ = io.ReadAll(newRec.Body)
err = json.Unmarshal(data, &newProductResp)
if err != nil {
t.Error(err)
}
productId := newProductResp.ID

//User Login
type UserLogin struct {
Username string `json:"username"`
Password string `json:"password"`
}
userLoginInfo := UserLogin{Username: customUser.Username, Password: customUser.Password}
userLoginJSON, err := utils.StructToJSON(userLoginInfo)
if err != nil {
t.Error(err.Error())
}
newReq = httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(userLoginJSON))
newReq.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
newRec = httptest.NewRecorder()
loginContext := e.NewContext(newReq, newRec)
// Assertions
if assert.NoError(t, service.UserLogin(loginContext)) {
assert.Equal(t, http.StatusOK, newRec.Code)
}

ProductJSON, err := utils.StructToJSON(ProductDataForCart{ProductID: productId})
if err != nil {
t.Error(err.Error())
}

var LoginResp LoginResponse
data, _ = io.ReadAll(newRec.Body)
err = json.Unmarshal(data, &LoginResp)
if err != nil {
t.Error(err)
}
AuthToken := LoginResp.Token
// Parse Token
parsedToken, err := jwt.Parse(AuthToken, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET")), nil
})

newCartReq := httptest.NewRequest(http.MethodPost, "/cart/", strings.NewReader(ProductJSON))
newCartReq.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
newCartRec := httptest.NewRecorder()
cartContext := e.NewContext(newCartReq, newCartRec)
cartContext.Set("user", parsedToken)
// Assertions
if assert.NoError(t, service.AddItemToCart(cartContext)) {
assert.Equal(t, http.StatusCreated, newCartRec.Code)
assert.Equal(t, "{\"message\":\"Item Added to Cart!\"}\n", newCartRec.Body.String())

}

defer tests.Teardown(testDB)
})

}
64 changes: 64 additions & 0 deletions internal/tests/login/user_login_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package login

import (
"encoding/json"
"github.com/go-faker/faker/v4"
"github.com/labstack/echo/v4"
"github.com/mukulmantosh/go-ecommerce-app/internal/server"
"github.com/mukulmantosh/go-ecommerce-app/internal/tests"
"github.com/mukulmantosh/go-ecommerce-app/internal/utils"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func TestUserLogin(t *testing.T) {
testDB, _ := tests.Setup()
type FakeUser struct {
Username string `json:"username" faker:"username"`
Password string `json:"password" faker:"word,unique"`
FirstName string `json:"first_name" faker:"first_name"`
LastName string `json:"last_name" faker:"last_name"`
}
type UserLogin struct {
Username string `json:"username"`
Password string `json:"password"`
}

t.Run("should return JWT token for a valid user", func(t *testing.T) {

var customUser FakeUser
_ = faker.FakeData(&customUser)
out, _ := json.Marshal(&customUser)
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/user", strings.NewReader(string(out)))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

var service = server.NewServer(testDB)
// Assertions
if assert.NoError(t, service.AddUser(c)) {
assert.Equal(t, http.StatusCreated, rec.Code)
}

userLoginInfo := UserLogin{Username: customUser.Username, Password: customUser.Password}
userLoginJSON, err := utils.StructToJSON(userLoginInfo)
if err != nil {
t.Error(err.Error())
}
newReq := httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(userLoginJSON))
newReq.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
newRec := httptest.NewRecorder()
loginContext := e.NewContext(newReq, newRec)
// Assertions
if assert.NoError(t, service.UserLogin(loginContext)) {
assert.Equal(t, http.StatusOK, newRec.Code)
}

tests.Teardown(testDB)
})

}

0 comments on commit 6f2389f

Please sign in to comment.