Skip to content

Commit

Permalink
Refactor config and increase test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
voltgizerz committed Jun 30, 2024
1 parent a211e7b commit 7f64444
Show file tree
Hide file tree
Showing 8 changed files with 247 additions and 25 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
This project provides simple REST APIs for Point of Sale (POS) software.

## Built With
- Go 1.21.3 or higher
- Fiber
- Go 1.21.3
- MySQL
- JWT Auth
- Goose
- Fiber
- JWT Authentication
- DB Migration Goose

## How to Run the Project

Expand Down
12 changes: 9 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@ import (
"github.com/voltgizerz/POS-restaurant/pkg/logger"
)

const (
ConfigPathDevelopment = "./config/yml/config.development.yml"
ConfigPathProduction = "./config/yml/config.production.yml"
)

type (
MainConfig struct {
App `yaml:"app"`
API `yaml:"api"`
Database `yaml:"database"`
}
)

type (
App struct {
Name string `yaml:"name" env-required:"true"`
Version string `yaml:"version" env-required:"true"`
Expand Down Expand Up @@ -60,10 +67,9 @@ func NewConfig() *MainConfig {
}

func getConfigPATH() string {
cfgPath := ConfigPathDevelopment
if env.IsProduction() {
cfgPath = ConfigPathPorduction
return ConfigPathProduction
}

return cfgPath
return ConfigPathDevelopment
}
2 changes: 1 addition & 1 deletion config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func Test_getConfigPATH(t *testing.T) {
{
name: "Production mode",
isProduction: true,
want: ConfigPathPorduction,
want: ConfigPathProduction,
},
}
for _, tt := range tests {
Expand Down
6 changes: 0 additions & 6 deletions config/const.go

This file was deleted.

4 changes: 2 additions & 2 deletions internal/app/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ func (s *Server) initUserRoutes(group fiber.Router) {

// initUserRoutes initializes user-related routes.
func (s *Server) initMenuRoutes(group fiber.Router) {
menuRoutes := group.Group("/menu")
menuRoutes.Post("/", s.menuHandler.AddMenu, s.jwtMiddleware.AuthorizeAccess())
menuRoutes := group.Group("/menus", )
menuRoutes.Post("", s.menuHandler.AddMenu, s.jwtMiddleware.AuthorizeAccess())
menuRoutes.Delete("/user/:user_id", s.menuHandler.UpdateActiveMenuBatchByUserID, s.jwtMiddleware.AuthorizeAccess())
menuRoutes.Delete("/:menu_id", s.menuHandler.UpdateActiveMenuByMenuID, s.jwtMiddleware.AuthorizeAccess())
menuRoutes.Patch("/:menu_id", s.menuHandler.UpdateMenuByMenuID, s.jwtMiddleware.AuthorizeAccess())
Expand Down
125 changes: 125 additions & 0 deletions internal/app/auth/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package auth

import (
"context"
"reflect"
"testing"

"github.com/voltgizerz/POS-restaurant/internal/app/constants"
)

func TestGetUserLoginFromCtx(t *testing.T) {
type args struct {
ctx context.Context
}
tests := []struct {
name string
args args
want *Auth
wantErr bool
expectedErr string
}{
{
name: "Valid context",
args: args{ctx: context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(context.Background(), constants.CTXKeyUserID, float64(1)),
constants.CTXKeyUsername, "testuser"),
constants.CTXKeyRoleID, float64(2)),
constants.CTXKeyIsActive, true),
constants.CTXKeyRequestID, "request123")},
want: &Auth{
UserID: 1,
Username: "testuser",
RoleID: 2,
IsUserActive: true,
RequestID: "request123",
},
wantErr: false,
},
{
name: "Missing userID",
args: args{ctx: context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(context.Background(), constants.CTXKeyUsername, "testuser"),
constants.CTXKeyRoleID, float64(2)),
constants.CTXKeyIsActive, true),
constants.CTXKeyRequestID, "request123")},
want: nil,
wantErr: true,
expectedErr: "user ID not found in context",
},
{
name: "Missing username",
args: args{ctx: context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(context.Background(), constants.CTXKeyUserID, float64(1)),
constants.CTXKeyRoleID, float64(2)),
constants.CTXKeyIsActive, true),
constants.CTXKeyRequestID, "request123")},
want: nil,
wantErr: true,
expectedErr: "username not found in context",
},
{
name: "Missing roleID",
args: args{ctx: context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(context.Background(), constants.CTXKeyUserID, float64(1)),
constants.CTXKeyUsername, "testuser"),
constants.CTXKeyIsActive, true),
constants.CTXKeyRequestID, "request123")},
want: nil,
wantErr: true,
expectedErr: "role ID not found in context",
},
{
name: "Missing isUserActive",
args: args{ctx: context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(context.Background(), constants.CTXKeyUserID, float64(1)),
constants.CTXKeyUsername, "testuser"),
constants.CTXKeyRoleID, float64(2)),
constants.CTXKeyRequestID, "request123")},
want: nil,
wantErr: true,
expectedErr: "active status not found in context",
},
{
name: "Missing requestID",
args: args{ctx: context.WithValue(
context.WithValue(
context.WithValue(
context.WithValue(context.Background(), constants.CTXKeyUserID, float64(1)),
constants.CTXKeyUsername, "testuser"),
constants.CTXKeyRoleID, float64(2)),
constants.CTXKeyIsActive, true)},
want: nil,
wantErr: true,
expectedErr: "request ID not found in context",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := GetUserLoginFromCtx(tt.args.ctx)
if (err != nil) != tt.wantErr {
t.Errorf("GetUserLoginFromCtx() error = %v, wantErr %v", err, tt.wantErr)
return
}
if err != nil && err.Error() != tt.expectedErr {
t.Errorf("GetUserLoginFromCtx() error = %v, expectedErr %v", err, tt.expectedErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("GetUserLoginFromCtx() = %v, want %v", got, tt.want)
}
})
}
}
95 changes: 95 additions & 0 deletions internal/utils/bcrypt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package utils

import (
"testing"
"golang.org/x/crypto/bcrypt"
)

func TestHashPassword(t *testing.T) {
type args struct {
password string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "Valid Password",
args: args{password: "mysecretpassword"},
wantErr: false,
},
{
name: "Empty Password",
args: args{password: ""},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HashPassword(tt.args.password)
if (err != nil) != tt.wantErr {
t.Errorf("HashPassword() error = %v, wantErr %v", err, tt.wantErr)
return
}
// Check if the hashed password can be verified with the original password
if err := bcrypt.CompareHashAndPassword([]byte(got), []byte(tt.args.password)); err != nil {
t.Errorf("Hashed password does not match the original password: %v", err)
}
})
}
}

func TestVerifyPassword(t *testing.T) {
type args struct {
password string
hash string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "Correct Password",
args: args{
password: "mysecretpassword",
hash: func() string {
hash, _ := HashPassword("mysecretpassword")
return hash
}(),
},
wantErr: false,
},
{
name: "Incorrect Password",
args: args{
password: "wrongpassword",
hash: func() string {
hash, _ := HashPassword("mysecretpassword")
return hash
}(),
},
wantErr: true,
},
{
name: "Empty Password",
args: args{
password: "",
hash: func() string {
hash, _ := HashPassword("")
return hash
}(),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := VerifyPassword(tt.args.password, tt.args.hash)
if (err != nil) != tt.wantErr {
t.Errorf("VerifyPassword() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
20 changes: 11 additions & 9 deletions pkg/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import (
)

const (
GO_ENV_KEY = "GO_ENV"
GoEnvKey = "GO_ENV"
EnvProduction = "production"
EnvDevelopment = "development"
)

// LoadENV - load env file.
Expand All @@ -19,27 +21,27 @@ func LoadENV() {
}

func IsDevelopment() bool {
val, ok := os.LookupEnv(GO_ENV_KEY)
val, ok := os.LookupEnv(GoEnvKey)
if !ok {
logger.LogStdErr.Fatalf("%s not set\n", GO_ENV_KEY)
logger.LogStdErr.Fatalf("%s not set\n", GoEnvKey)
}

return val == "development"
return val == EnvDevelopment
}

func IsProduction() bool {
val, ok := os.LookupEnv(GO_ENV_KEY)
val, ok := os.LookupEnv(GoEnvKey)
if !ok {
logger.LogStdErr.Fatalf("%s not set\n", GO_ENV_KEY)
logger.LogStdErr.Fatalf("%s not set\n", GoEnvKey)
}

return val == "production"
return val == EnvProduction
}

func GetENV() string {
val, ok := os.LookupEnv(GO_ENV_KEY)
val, ok := os.LookupEnv(GoEnvKey)
if !ok {
logger.LogStdErr.Fatalf("%s not set\n", GO_ENV_KEY)
logger.LogStdErr.Fatalf("%s not set\n", GoEnvKey)
}

return val
Expand Down

0 comments on commit 7f64444

Please sign in to comment.