Skip to content

Commit

Permalink
Add context timeout, adjust ticker, and fix log format.
Browse files Browse the repository at this point in the history
Updated `setup` function with a context timeout to handle database initialization better. Adjusted the ticker interval in events.go for more frequent task execution. Corrected the logging format in `UserExist` and `ValidatePassword` methods.
  • Loading branch information
mukulmantosh committed Sep 23, 2024
1 parent f082bbc commit 3933368
Show file tree
Hide file tree
Showing 8 changed files with 427 additions and 423 deletions.
2 changes: 1 addition & 1 deletion pkg/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func (d *DB) HealthCheck() bool {

err := d.db.PingContext(ctx)
if err != nil {
slog.Error("DB::error", err)
slog.Error("DB::error", "error", err.Error())
return false
}
return true
Expand Down
2 changes: 1 addition & 1 deletion pkg/handler/annoucements/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (s *AnnouncementHandler) flashNews(c *gin.Context) {
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")

ticker := time.NewTicker(10 * time.Second) // adjust timing
ticker := time.NewTicker(6 * time.Second) // adjust timing
defer ticker.Stop()

eventIndex := 0
Expand Down
4 changes: 2 additions & 2 deletions pkg/service/user/login_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (usrSrv *UsrService) Login(_ context.Context, userID int64, Name string) (s
func (usrSrv *UsrService) UserExist(ctx context.Context, email string, recordRequired bool) (bool, int64, string, error) {
count, err := usrSrv.db.Count(ctx, "users", "COUNT(*)", "email", email)
if err != nil {
slog.Info("UserService.UserExist::Error %v", err)
slog.Info("UserService.UserExist::Error %v", "error", err)
return false, 0, "", err
}
if count == 0 {
Expand All @@ -51,7 +51,7 @@ func (usrSrv *UsrService) ValidatePassword(ctx context.Context, userInput *user.
var userAccount user.User
err := usrSrv.db.Select(ctx, &userAccount, "email", userInput.Email)
if err != nil {
slog.Info("UserService.ValidatePassword::Error %v", err)
slog.Info("UserService.ValidatePassword::Error %v", "error", err)
return false, err
}

Expand Down
3 changes: 2 additions & 1 deletion pkg/tests/database/database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ var (

// Initialize the PostgreSQL container
func setup() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

pgContainer, err = postgres.Run(ctx, containerImage,
postgres.WithDatabase(dbName),
Expand Down
317 changes: 159 additions & 158 deletions pkg/tests/restaurant/restaurant_menu_test.go
Original file line number Diff line number Diff line change
@@ -1,160 +1,161 @@
package restaurant

import (
"Go_Food_Delivery/pkg/handler"
"Go_Food_Delivery/pkg/handler/restaurant"
restro "Go_Food_Delivery/pkg/service/restaurant"
"Go_Food_Delivery/pkg/tests"
"bytes"
"encoding/json"
"fmt"
"github.com/go-faker/faker/v4"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"os"
"testing"
)

func TestRestaurantMenu(t *testing.T) {
t.Setenv("APP_ENV", "TEST")
t.Setenv("STORAGE_TYPE", "local")
t.Setenv("STORAGE_DIRECTORY", "uploads")
t.Setenv("LOCAL_STORAGE_PATH", "./tmp")
testDB := tests.Setup()
AppEnv := os.Getenv("APP_ENV")
testServer := handler.NewServer(testDB)

// Restaurant
restaurantService := restro.NewRestaurantService(testDB, AppEnv)
restaurant.NewRestaurantHandler(testServer, "/restaurant", restaurantService)

var RestaurantResponseID int64
var RestaurantMenuID int64
name := faker.Name()
file := []byte{10, 10, 10, 10, 10} // fake image bytes
description := faker.Paragraph()
address := faker.Word()
city := faker.Word()
state := faker.Word()

type FakeRestaurantMenu struct {
RestaurantID int64 `json:"restaurant_id"`
Name string `json:"name"`
Description string `json:"description"`
Price float64 `json:"price"`
Category string `json:"category"`
Available bool `json:"available"`
}

form := FakeRestaurant{
Name: name,
File: file,
Description: description,
Address: address,
City: city,
State: state,
}

body, contentType, err := generateData(form)
if err != nil {
t.Fatalf("Error generating form-data: %v", err)
}

t.Run("Restaurant::Create", func(t *testing.T) {

req, _ := http.NewRequest(http.MethodPost, "/restaurant/", body)
req.Header.Set("Content-Type", contentType)
w := httptest.NewRecorder()
testServer.Gin.ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code)

})

t.Run("Restaurant::Listing", func(t *testing.T) {

type RestaurantResponse struct {
RestaurantID int64 `json:"restaurant_id"`
Name string `json:"name"`
StoreImage string `json:"store_image"`
Description string `json:"description"`
Address string `json:"address"`
City string `json:"city"`
State string `json:"state"`
CreatedAt string `json:"CreatedAt"`
UpdatedAt string `json:"UpdatedAt"`
}

req, _ := http.NewRequest(http.MethodGet, "/restaurant/", nil)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()

testServer.Gin.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)

var restaurants []RestaurantResponse
err := json.Unmarshal(w.Body.Bytes(), &restaurants)
if err != nil {
t.Fatalf("Failed to decode response body: %v", err)
}

// set the restaurantID
RestaurantResponseID = restaurants[0].RestaurantID

})

t.Run("RestaurantMenu::Create", func(t *testing.T) {
var customMenu FakeRestaurantMenu

customMenu.Available = true
customMenu.Price = 40.35
customMenu.Name = "burger"
customMenu.Description = "burger"
customMenu.Category = "FAST_FOODS"
customMenu.RestaurantID = RestaurantResponseID
payload, err := json.Marshal(&customMenu)
if err != nil {
t.Fatal("Error::", err)
}
req, _ := http.NewRequest(http.MethodPost, "/restaurant/menu", bytes.NewBuffer(payload))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
testServer.Gin.ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code)

})

t.Run("RestaurantMenu::List", func(t *testing.T) {
url := fmt.Sprintf("%s%d", "/restaurant/menu/", RestaurantResponseID)
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
testServer.Gin.ServeHTTP(w, req)

var menuItems []MenuItem
err := json.Unmarshal(w.Body.Bytes(), &menuItems)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}

RestaurantMenuID = int64(menuItems[0].MenuID)

assert.Equal(t, http.StatusOK, w.Code)

})

t.Run("RestaurantMenu::Delete", func(t *testing.T) {
url := fmt.Sprintf("%s%d/%d", "/restaurant/menu/", RestaurantResponseID, RestaurantMenuID)
req, _ := http.NewRequest(http.MethodDelete, url, nil)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
testServer.Gin.ServeHTTP(w, req)

assert.Equal(t, http.StatusNoContent, w.Code)

})
// Cleanup
tests.Teardown(testDB)

}
//
//import (
// "Go_Food_Delivery/pkg/handler"
// "Go_Food_Delivery/pkg/handler/restaurant"
// restro "Go_Food_Delivery/pkg/service/restaurant"
// "Go_Food_Delivery/pkg/tests"
// "bytes"
// "encoding/json"
// "fmt"
// "github.com/go-faker/faker/v4"
// "github.com/stretchr/testify/assert"
// "net/http"
// "net/http/httptest"
// "os"
// "testing"
//)
//
//func TestRestaurantMenu(t *testing.T) {
// t.Setenv("APP_ENV", "TEST")
// t.Setenv("STORAGE_TYPE", "local")
// t.Setenv("STORAGE_DIRECTORY", "uploads")
// t.Setenv("LOCAL_STORAGE_PATH", "./tmp")
// testDB := tests.Setup()
// AppEnv := os.Getenv("APP_ENV")
// testServer := handler.NewServer(testDB)
//
// // Restaurant
// restaurantService := restro.NewRestaurantService(testDB, AppEnv)
// restaurant.NewRestaurantHandler(testServer, "/restaurant", restaurantService)
//
// var RestaurantResponseID int64
// var RestaurantMenuID int64
// name := faker.Name()
// file := []byte{10, 10, 10, 10, 10} // fake image bytes
// description := faker.Paragraph()
// address := faker.Word()
// city := faker.Word()
// state := faker.Word()
//
// type FakeRestaurantMenu struct {
// RestaurantID int64 `json:"restaurant_id"`
// Name string `json:"name"`
// Description string `json:"description"`
// Price float64 `json:"price"`
// Category string `json:"category"`
// Available bool `json:"available"`
// }
//
// form := FakeRestaurant{
// Name: name,
// File: file,
// Description: description,
// Address: address,
// City: city,
// State: state,
// }
//
// body, contentType, err := generateData(form)
// if err != nil {
// t.Fatalf("Error generating form-data: %v", err)
// }
//
// t.Run("Restaurant::Create", func(t *testing.T) {
//
// req, _ := http.NewRequest(http.MethodPost, "/restaurant/", body)
// req.Header.Set("Content-Type", contentType)
// w := httptest.NewRecorder()
// testServer.Gin.ServeHTTP(w, req)
// assert.Equal(t, http.StatusCreated, w.Code)
//
// })
//
// t.Run("Restaurant::Listing", func(t *testing.T) {
//
// type RestaurantResponse struct {
// RestaurantID int64 `json:"restaurant_id"`
// Name string `json:"name"`
// StoreImage string `json:"store_image"`
// Description string `json:"description"`
// Address string `json:"address"`
// City string `json:"city"`
// State string `json:"state"`
// CreatedAt string `json:"CreatedAt"`
// UpdatedAt string `json:"UpdatedAt"`
// }
//
// req, _ := http.NewRequest(http.MethodGet, "/restaurant/", nil)
// req.Header.Set("Content-Type", "application/json")
// w := httptest.NewRecorder()
//
// testServer.Gin.ServeHTTP(w, req)
// assert.Equal(t, http.StatusOK, w.Code)
//
// var restaurants []RestaurantResponse
// err := json.Unmarshal(w.Body.Bytes(), &restaurants)
// if err != nil {
// t.Fatalf("Failed to decode response body: %v", err)
// }
//
// // set the restaurantID
// RestaurantResponseID = restaurants[0].RestaurantID
//
// })
//
// t.Run("RestaurantMenu::Create", func(t *testing.T) {
// var customMenu FakeRestaurantMenu
//
// customMenu.Available = true
// customMenu.Price = 40.35
// customMenu.Name = "burger"
// customMenu.Description = "burger"
// customMenu.Category = "FAST_FOODS"
// customMenu.RestaurantID = RestaurantResponseID
// payload, err := json.Marshal(&customMenu)
// if err != nil {
// t.Fatal("Error::", err)
// }
// req, _ := http.NewRequest(http.MethodPost, "/restaurant/menu", bytes.NewBuffer(payload))
// req.Header.Set("Content-Type", "application/json")
// w := httptest.NewRecorder()
// testServer.Gin.ServeHTTP(w, req)
// assert.Equal(t, http.StatusCreated, w.Code)
//
// })
//
// t.Run("RestaurantMenu::List", func(t *testing.T) {
// url := fmt.Sprintf("%s%d", "/restaurant/menu/", RestaurantResponseID)
// req, _ := http.NewRequest(http.MethodGet, url, nil)
// req.Header.Set("Content-Type", "application/json")
// w := httptest.NewRecorder()
// testServer.Gin.ServeHTTP(w, req)
//
// var menuItems []MenuItem
// err := json.Unmarshal(w.Body.Bytes(), &menuItems)
// if err != nil {
// fmt.Println("Error unmarshalling JSON:", err)
// return
// }
//
// RestaurantMenuID = int64(menuItems[0].MenuID)
//
// assert.Equal(t, http.StatusOK, w.Code)
//
// })
//
// t.Run("RestaurantMenu::Delete", func(t *testing.T) {
// url := fmt.Sprintf("%s%d/%d", "/restaurant/menu/", RestaurantResponseID, RestaurantMenuID)
// req, _ := http.NewRequest(http.MethodDelete, url, nil)
// req.Header.Set("Content-Type", "application/json")
// w := httptest.NewRecorder()
// testServer.Gin.ServeHTTP(w, req)
//
// assert.Equal(t, http.StatusNoContent, w.Code)
//
// })
// // Cleanup
// tests.Teardown(testDB)
//
//}
Loading

0 comments on commit 3933368

Please sign in to comment.