From 9edeeb92ccea0ffc5dbfcdaae276e82a62e5b8f4 Mon Sep 17 00:00:00 2001 From: Felix Fernando Wijaya Date: Sat, 22 Jun 2024 18:57:58 +0700 Subject: [PATCH 1/4] Add unit test repo --- go.mod | 1 + go.sum | 3 + .../app/repository/user_repository_test.go | 105 +++++++++++++++++- 3 files changed, 106 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 077811f..98188c3 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( require ( filippo.io/edwards25519 v1.1.0 // indirect + github.com/DATA-DOG/go-sqlmock v1.5.2 // indirect github.com/HdrHistogram/hdrhistogram-go v1.1.2 // indirect github.com/andybalholm/brotli v1.1.0 // indirect github.com/gofiber/utils/v2 v2.0.0-beta.4 // indirect diff --git a/go.sum b/go.sum index e6b5fba..df8aa6b 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,8 @@ filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4 github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak= github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= +github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM= github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= @@ -38,6 +40,7 @@ github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE= github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= diff --git a/internal/app/repository/user_repository_test.go b/internal/app/repository/user_repository_test.go index 02a5522..fa1bda3 100644 --- a/internal/app/repository/user_repository_test.go +++ b/internal/app/repository/user_repository_test.go @@ -2,9 +2,13 @@ package repository import ( "context" + "database/sql" + "errors" "reflect" "testing" + "github.com/DATA-DOG/go-sqlmock" + "github.com/jmoiron/sqlx" "github.com/voltgizerz/POS-restaurant/internal/app/entity" ) @@ -13,6 +17,101 @@ func TestUserRepository_GetUserByEmail(t *testing.T) { ctx context.Context email string } + tests := []struct { + name string + r *UserRepository + args args + want *entity.UserORM + wantErr bool + mockFunc func(mock sqlmock.Sqlmock) + }{ + { + name: "SUCCESS - GetUserByEmail", + args: args{ + + ctx: context.Background(), + email: "mock@email.com", + }, + want: &entity.UserORM{ + ID: 1, + }, + wantErr: false, + mockFunc: func(mock sqlmock.Sqlmock) { + mock.ExpectQuery(queryGetEmailSame). + WithArgs("mock@email.com"). + WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) + }, + }, + { + name: "ERROR - On GetUserByEmail", + args: args{ + ctx: context.Background(), + email: "mock@email.com", + }, + want: nil, + wantErr: true, + mockFunc: func(mock sqlmock.Sqlmock) { + mock.ExpectQuery(queryGetEmailSame). + WithArgs("mock@email.com"). + WillReturnError(errors.New("some error")) + }, + }, + { + name: "ERROR - On GetUserByEmail got NoRows", + args: args{ + ctx: context.Background(), + email: "mock@email.com", + }, + want: &entity.UserORM{}, + wantErr: false, + mockFunc: func(mock sqlmock.Sqlmock) { + mock.ExpectQuery(queryGetEmailSame). + WithArgs("mock@email.com"). + WillReturnError(sql.ErrNoRows) + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dbMock, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("error creating mock database: %v", err) + } + defer dbMock.Close() + + // Initialize UserRepository with the mock DB + tt.r = &UserRepository{ + MasterDB: sqlx.NewDb(dbMock, "sqlmock"), + } + + // Call the mock function to set expectations + tt.mockFunc(mock) + + // Call the method under test + got, err := tt.r.GetUserByEmail(tt.args.ctx, tt.args.email) + if (err != nil) != tt.wantErr { + t.Errorf("UserRepository.GetUserByEmail() error = %v, wantErr %v", err, tt.wantErr) + return + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("UserRepository.GetUserByEmail() = %v, want %v", got, tt.want) + } + + // Ensure all expectations were met + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("there were unfulfilled expectations: %s", err) + } + }) + } +} + +func TestUserRepository_GetUserByUsernameAndPassword(t *testing.T) { + type args struct { + ctx context.Context + username string + hashPassword string + } tests := []struct { name string r *UserRepository @@ -24,13 +123,13 @@ func TestUserRepository_GetUserByEmail(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := tt.r.GetUserByEmail(tt.args.ctx, tt.args.email) + got, err := tt.r.GetUserByUsernameAndPassword(tt.args.ctx, tt.args.username, tt.args.hashPassword) if (err != nil) != tt.wantErr { - t.Errorf("UserRepository.GetUserByEmail() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("UserRepository.GetUserByUsernameAndPassword() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("UserRepository.GetUserByEmail() = %v, want %v", got, tt.want) + t.Errorf("UserRepository.GetUserByUsernameAndPassword() = %v, want %v", got, tt.want) } }) } From 08e163db8777b4259f615fe41fed2be473268c89 Mon Sep 17 00:00:00 2001 From: Felix Fernando Wijaya Date: Sat, 22 Jun 2024 20:16:10 +0700 Subject: [PATCH 2/4] Add db migration for users --- Makefile | 11 ++++ database/dump/dump-db_pos-202406091310.sql | 66 ------------------- .../20240622125106_add_users_table.sql | 19 ++++++ 3 files changed, 30 insertions(+), 66 deletions(-) delete mode 100644 database/dump/dump-db_pos-202406091310.sql create mode 100644 database/migrations/20240622125106_add_users_table.sql diff --git a/Makefile b/Makefile index 613e843..adb6c2c 100644 --- a/Makefile +++ b/Makefile @@ -25,3 +25,14 @@ mock-gen: changelog-gen: @auto-changelog + +# Target to apply migrations +up: + goose -dir=./database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" up + +# Target to reset migrations (if needed) +down: + goose -dir=./database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" down + +status: + goose -dir=./database/migrations mysql "root@tcp(localhost:3306)/db_pos?parseTime=true" status diff --git a/database/dump/dump-db_pos-202406091310.sql b/database/dump/dump-db_pos-202406091310.sql deleted file mode 100644 index 96dc5f7..0000000 --- a/database/dump/dump-db_pos-202406091310.sql +++ /dev/null @@ -1,66 +0,0 @@ --- phpMyAdmin SQL Dump --- version 5.2.0 --- https://www.phpmyadmin.net/ --- --- Host: localhost:3306 --- Generation Time: Jun 14, 2024 at 09:19 AM --- Server version: 5.7.33 --- PHP Version: 8.2.11 - -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -START TRANSACTION; -SET time_zone = "+00:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Database: `db_pos` --- - --- -------------------------------------------------------- - --- --- Table structure for table `users` --- - -CREATE TABLE `users` ( - `id` bigint(20) NOT NULL, - `name` varchar(255) DEFAULT NULL, - `username` varchar(255) DEFAULT NULL, - `email` varchar(255) DEFAULT NULL, - `password_hashed` varchar(528) DEFAULT NULL, - `is_active` tinyint(1) NOT NULL, - `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `role_id` int(100) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - - --- --- Indexes for dumped tables --- - --- --- Indexes for table `users` --- -ALTER TABLE `users` - ADD PRIMARY KEY (`id`); - --- --- AUTO_INCREMENT for dumped tables --- - --- --- AUTO_INCREMENT for table `users` --- -ALTER TABLE `users` - MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; -COMMIT; - -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/database/migrations/20240622125106_add_users_table.sql b/database/migrations/20240622125106_add_users_table.sql new file mode 100644 index 0000000..85c9a56 --- /dev/null +++ b/database/migrations/20240622125106_add_users_table.sql @@ -0,0 +1,19 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE `users` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `username` varchar(255) DEFAULT NULL, + `email` varchar(255) DEFAULT NULL, + `password_hashed` varchar(528) DEFAULT NULL, + `is_active` tinyint(1) NOT NULL, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE `users`; +-- +goose StatementEnd From 98f77cfcb6e5c7103f6f1de38216089cbd51eb6d Mon Sep 17 00:00:00 2001 From: Felix Fernando Wijaya Date: Sat, 22 Jun 2024 21:11:21 +0700 Subject: [PATCH 3/4] Add validator struct --- go.mod | 9 ++++++++- go.sum | 14 ++++++++++++++ internal/app/api/handler/request.go | 4 ++-- internal/app/api/handler/user_handler.go | 9 +++++++-- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 98188c3..7608ec7 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,10 @@ module github.com/voltgizerz/POS-restaurant go 1.21.3 require ( + github.com/DATA-DOG/go-sqlmock v1.5.2 github.com/antonfisher/nested-logrus-formatter v1.3.1 github.com/go-playground/assert/v2 v2.2.0 + github.com/go-playground/validator/v10 v10.22.0 github.com/go-sql-driver/mysql v1.8.1 github.com/gofiber/fiber/v3 v3.0.0-beta.2 github.com/ilyakaznacheev/cleanenv v1.5.0 @@ -15,12 +17,15 @@ require ( require ( filippo.io/edwards25519 v1.1.0 // indirect - github.com/DATA-DOG/go-sqlmock v1.5.2 // indirect github.com/HdrHistogram/hdrhistogram-go v1.1.2 // indirect github.com/andybalholm/brotli v1.1.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect github.com/gofiber/utils/v2 v2.0.0-beta.4 // indirect github.com/google/uuid v1.6.0 // indirect github.com/klauspost/compress v1.17.8 // indirect + github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect @@ -31,7 +36,9 @@ require ( github.com/valyala/fasthttp v1.54.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect go.uber.org/atomic v1.11.0 // indirect + golang.org/x/net v0.23.0 // indirect golang.org/x/sys v0.21.0 // indirect + golang.org/x/text v0.16.0 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect ) diff --git a/go.sum b/go.sum index df8aa6b..cb0dbef 100644 --- a/go.sum +++ b/go.sum @@ -18,9 +18,17 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.0 h1:k6HsTZ0sTnROkhS//R0O+55JgM8C4Bx7ia+JlgcnOao= +github.com/go-playground/validator/v10 v10.22.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/gofiber/fiber/v3 v3.0.0-beta.2 h1:mVVgt8PTaHGup3NGl/+7U7nEoZaXJ5OComV4E+HpAao= @@ -47,6 +55,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -103,6 +113,8 @@ golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCc golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -113,6 +125,8 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= diff --git a/internal/app/api/handler/request.go b/internal/app/api/handler/request.go index 7bfc875..7f5f08e 100644 --- a/internal/app/api/handler/request.go +++ b/internal/app/api/handler/request.go @@ -2,8 +2,8 @@ package handler type ( loginRequest struct { - Username string `json:"username"` - Password string `json:"password"` + Username string `json:"username" validate:"required"` + Password string `json:"password" validate:"required"` } registerRequest struct { diff --git a/internal/app/api/handler/user_handler.go b/internal/app/api/handler/user_handler.go index f839fb6..e6d0be6 100644 --- a/internal/app/api/handler/user_handler.go +++ b/internal/app/api/handler/user_handler.go @@ -3,8 +3,10 @@ package handler import ( "database/sql" + "github.com/go-playground/validator/v10" "github.com/gofiber/fiber/v3" "github.com/opentracing/opentracing-go" + "github.com/voltgizerz/POS-restaurant/internal/app/constants" "github.com/voltgizerz/POS-restaurant/internal/app/entity" "github.com/voltgizerz/POS-restaurant/internal/app/interactor" @@ -33,8 +35,11 @@ func (h *UserHandler) Login(c fiber.Ctx) error { return sendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgInvalidUsernameAndPassword) } - if req.Username == "" || req.Password == "" { - return sendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgUsernameOrPasswordRequired) + err = validator.New().StructCtx(ctx, req) + if err != nil { + validationErrors := err.(validator.ValidationErrors) + + return sendErrorResp(c, fiber.StatusBadRequest, validationErrors.Error()) } userLoginData, err := h.userService.Login(ctx, req.Username, req.Password) From 643695ab76a2c4b9798fae63480fa947560bd40e Mon Sep 17 00:00:00 2001 From: Felix Fernando Wijaya Date: Sat, 22 Jun 2024 21:24:47 +0700 Subject: [PATCH 4/4] Init test on handler --- internal/app/api/handler/init_test.go | 45 +++++++++++++++++++ internal/app/api/handler/user_handler_test.go | 37 +++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 internal/app/api/handler/init_test.go create mode 100644 internal/app/api/handler/user_handler_test.go diff --git a/internal/app/api/handler/init_test.go b/internal/app/api/handler/init_test.go new file mode 100644 index 0000000..4d0453d --- /dev/null +++ b/internal/app/api/handler/init_test.go @@ -0,0 +1,45 @@ +package handler + +import ( + "os" + "testing" + + "go.uber.org/mock/gomock" + + "github.com/voltgizerz/POS-restaurant/internal/app/mocks" + "github.com/voltgizerz/POS-restaurant/pkg/logger" +) + +func TestMain(m *testing.M) { + // Setup code (if any) + // ... + logger.Init() + // Run the tests + m.Run() +} + +type MockObject struct { + MockUserRepo *mocks.MockIUserRepository + MockAuthService *mocks.MockIAuth + MockUserService *mocks.MockIUserService +} + +func NewMock(t *testing.T) (*gomock.Controller, *MockObject) { + setTestENV() + ctrl := gomock.NewController(t) + mockUserRepo := mocks.NewMockIUserRepository(ctrl) + mockAuthService := mocks.NewMockIAuth(ctrl) + mockUserService := mocks.NewMockIUserService(ctrl) + + mockObj := &MockObject{ + MockUserRepo: mockUserRepo, + MockAuthService: mockAuthService, + MockUserService: mockUserService, + } + + return ctrl, mockObj +} + +func setTestENV() { + os.Setenv("GO_ENV", "unit_test") +} diff --git a/internal/app/api/handler/user_handler_test.go b/internal/app/api/handler/user_handler_test.go new file mode 100644 index 0000000..50d733c --- /dev/null +++ b/internal/app/api/handler/user_handler_test.go @@ -0,0 +1,37 @@ +package handler + +import ( + "testing" + + "github.com/gofiber/fiber/v3" +) + +func TestUserHandler_Login(t *testing.T) { + type args struct { + c fiber.Ctx + } + tests := []struct { + name string + args args + wantErr bool + setup func(mockObj *MockObject) + }{{}} + for _, tt := range tests { + ctrl, mockObj := NewMock(t) + if tt.setup != nil { + tt.setup(mockObj) + } + defer ctrl.Finish() + + userHandler := &UserHandler{ + authService: mockObj.MockAuthService, + userService: mockObj.MockUserService, + } + + t.Run(tt.name, func(t *testing.T) { + if err := userHandler.Login(tt.args.c); (err != nil) != tt.wantErr { + t.Errorf("UserHandler.Login() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +}