help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
go-rest-api
/
internal
/
handlers
RSK World
go-rest-api
Go REST API - Enterprise-grade REST API with JWT Authentication + PostgreSQL + Redis Caching + Docker + Comprehensive Testing + Educational Design
handlers
  • api_handler.go1.4 KB
  • auth_handler.go4.4 KB
  • auth_handler_test.go4.6 KB
  • category_handler.go5.2 KB
  • product_handler.go8.8 KB
  • upload_handler.go5 KB
auth_handler_test.go
internal/handlers/auth_handler_test.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package handlers

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/rskworld/go-rest-api/internal/config"
	"github.com/rskworld/go-rest-api/internal/database"
	"github.com/rskworld/go-rest-api/internal/models"
	"github.com/stretchr/testify/assert"
	"golang.org/x/crypto/bcrypt"
)

func setupAuthTest(t *testing.T) (*gin.Engine, *config.Config) {
	gin.SetMode(gin.TestMode)

	// Setup test database
	cfg := &config.Config{
		DBHost:     "localhost",
		DBUser:     "postgres",
		DBPassword: "postgres",
		DBName:     "testdb",
		DBPort:     "5432",
		JWTSecret:  "testsecret",
	}

	// For testing, we'll use an in-memory database approach
	// In a real scenario, you'd set up a test database

	r := gin.New()
	return r, cfg
}

func TestRegister(t *testing.T) {
	r, cfg := setupAuthTest(t)

	authHandler := NewAuthHandler(cfg)

	r.POST("/register", authHandler.Register)

	tests := []struct {
		name           string
		requestBody    RegisterRequest
		expectedStatus int
		expectError    bool
	}{
		{
			name: "Valid registration",
			requestBody: RegisterRequest{
				Name:     "Test User",
				Email:    "test@example.com",
				Password: "password123",
			},
			expectedStatus: http.StatusCreated,
			expectError:    false,
		},
		{
			name: "Invalid email",
			requestBody: RegisterRequest{
				Name:     "Test User",
				Email:    "invalid-email",
				Password: "password123",
			},
			expectedStatus: http.StatusBadRequest,
			expectError:    true,
		},
		{
			name: "Password too short",
			requestBody: RegisterRequest{
				Name:     "Test User",
				Email:    "test@example.com",
				Password: "123",
			},
			expectedStatus: http.StatusBadRequest,
			expectError:    true,
		},
		{
			name: "Missing name",
			requestBody: RegisterRequest{
				Email:    "test@example.com",
				Password: "password123",
			},
			expectedStatus: http.StatusBadRequest,
			expectError:    true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			jsonBody, _ := json.Marshal(tt.requestBody)
			req, _ := http.NewRequest("POST", "/register", bytes.NewBuffer(jsonBody))
			req.Header.Set("Content-Type", "application/json")

			w := httptest.NewRecorder()
			r.ServeHTTP(w, req)

			assert.Equal(t, tt.expectedStatus, w.Code)

			var response map[string]interface{}
			json.Unmarshal(w.Body.Bytes(), &response)

			if tt.expectError {
				assert.Equal(t, "error", response["status"])
			} else {
				assert.Equal(t, "success", response["status"])
			}
		})
	}
}

func TestLogin(t *testing.T) {
	r, cfg := setupAuthTest(t)

	// Create a test user in the database
	hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password123"), bcrypt.DefaultCost)
	testUser := models.User{
		Name:     "Test User",
		Email:    "test@example.com",
		Password: string(hashedPassword),
		Role:     "user",
		IsActive: true,
	}

	// This would normally save to database
	// For this test, we'll mock the database interaction

	authHandler := NewAuthHandler(cfg)

	r.POST("/login", authHandler.Login)

	tests := []struct {
		name           string
		requestBody    AuthRequest
		expectedStatus int
		expectError    bool
	}{
		{
			name: "Valid login",
			requestBody: AuthRequest{
				Email:    "test@example.com",
				Password: "password123",
			},
			expectedStatus: http.StatusOK,
			expectError:    false,
		},
		{
			name: "Invalid email",
			requestBody: AuthRequest{
				Email:    "invalid@example.com",
				Password: "password123",
			},
			expectedStatus: http.StatusUnauthorized,
			expectError:    true,
		},
		{
			name: "Wrong password",
			requestBody: AuthRequest{
				Email:    "test@example.com",
				Password: "wrongpassword",
			},
			expectedStatus: http.StatusUnauthorized,
			expectError:    true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			jsonBody, _ := json.Marshal(tt.requestBody)
			req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(jsonBody))
			req.Header.Set("Content-Type", "application/json")

			w := httptest.NewRecorder()
			r.ServeHTTP(w, req)

			assert.Equal(t, tt.expectedStatus, w.Code)

			var response map[string]interface{}
			json.Unmarshal(w.Body.Bytes(), &response)

			if tt.expectError {
				assert.Equal(t, "error", response["status"])
			} else {
				assert.Equal(t, "success", response["status"])
				assert.Contains(t, response["data"], "token")
			}
		})
	}
}
199 lines•4.6 KB
go

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer