testutil

package
v0.0.0-...-fb81f76 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetupTestDB

func SetupTestDB(t *testing.T, models ...interface{}) (*gorm.DB, func())

SetupTestDB Quickly Creates a Minimal Test Database

Applicable scenario: Only the database is required, other components are not needed.

Usage:

db, cleanup := testutil.SetupTestDB(t, &model.User{})
defer cleanup()

Types

type CLITestContext

type CLITestContext struct {
	Logger    *zap.Logger
	DBManager *database.Manager
	DBHelper  *DBHelper
}

CLI Test Context Encapsulate basic components required for CLI tests

func MustNewCLITestContext

func MustNewCLITestContext(t *testing.T, opts CLITestOptions) (*CLITestContext, func())

MustNewCLITestContext Create CLI test context (fatal on failure)

func NewCLITestContext

func NewCLITestContext(t *testing.T, opts CLITestOptions) (*CLITestContext, func())

NewCLITestContext creates a CLI test context (one-stop initialization)

Usage:

func TestMain(m *testing.M) {

// 1. Create test context (auto-complete all initialization)

ctx, cleanup := testutil.NewCLITestContext(t, testutil.CLITestOptions{
    AutoMigrate: []interface{}{&model.User{}},
})
defer cleanup()

// 2. Use DBManager to create Service

userRepo := user.NewRepositoryImpl(ctx.DBManager.DB("master"))
userService := user.NewService(userRepo)

// 3. Run tests

    code := m.Run()
    os.Exit(code)
}

Advantages: - Automatically create Logger, DBManager, AutoMigrate - Default use of SQLite in-memory database (fast, isolated) - Provide a cleanup function to automatically clean up resources

type CLITestOptions

type CLITestOptions struct {
	// AutoMigrate list of models for automatic migration
	AutoMigrate []interface{}

	// DBConfig custom database configuration (optional, defaults to an in-memory SQLite database)
	DBConfig map[string]database.Config

	// Logger custom logger (optional, default uses Development Logger)
	Logger *zap.Logger

	// SetupFunc custom initialization function (optional, called after basic initialization)
	// For creating services, handlers, etc. in the business layer
	SetupFunc func(*CLITestContext) error
}

CLITestOptions CLI test options

type DBHelper

type DBHelper struct {
	DB *gorm.DB
}

DBHelper database test utility

func NewDBHelper

func NewDBHelper(db *gorm.DB) *DBHelper

NewDBHelper Create database helper utility

func (*DBHelper) Count

func (h *DBHelper) Count(tableName string) (int64, error)

Count Statistic record count (excluding soft-deleted records)

func (*DBHelper) CountWhere

func (h *DBHelper) CountWhere(tableName string, where string, args ...interface{}) (int64, error)

CountWhere count records that meet the condition

func (*DBHelper) DeleteAll

func (h *DBHelper) DeleteAll(tableName string) error

DeleteAll deletes all data in the table (does not reset auto-increment ID)

func (*DBHelper) Exists

func (h *DBHelper) Exists(tableName string, where string, args ...interface{}) (bool, error)

Exists Check if record exists

func (*DBHelper) FindAll

func (h *DBHelper) FindAll(dest interface{}, tableName string) error

FindAll query all records

func (*DBHelper) FindOne

func (h *DBHelper) FindOne(dest interface{}, where string, args ...interface{}) error

FindOne query for a single record

func (*DBHelper) Seed

func (h *DBHelper) Seed(data interface{}) error

Seed insert seed data

func (*DBHelper) SeedMultiple

func (h *DBHelper) SeedMultiple(data interface{}) error

SeedMultiple batch insert seed data

func (*DBHelper) TruncateTable

func (h *DBHelper) TruncateTable(tableName string) error

TruncateTable truncate table data (retain auto-increment ID)

func (*DBHelper) TruncateTables

func (h *DBHelper) TruncateTables(tableNames ...string) error

TruncateTables truncate multiple tables

type RequestBuilder

type RequestBuilder struct {
	// contains filtered or unexported fields
}

RequestBuilder HTTP request builder

func DELETE

func DELETE(path string) *RequestBuilder

DELETE create DELETE request

func GET

func GET(path string) *RequestBuilder

Create GET request

func NewRequest

func NewRequest(method, path string) *RequestBuilder

NewRequest creates request builder

func PATCH

func PATCH(path string) *RequestBuilder

Create a PATCH request

func POST

func POST(path string) *RequestBuilder

Create POST request

func PUT

func PUT(path string) *RequestBuilder

English: PUT create PUT request

func (*RequestBuilder) Do

func (rb *RequestBuilder) Do(engine *gin.Engine) *ResponseHelper

Execute request

func (*RequestBuilder) WithHeader

func (rb *RequestBuilder) WithHeader(key, value string) *RequestBuilder

WithHeader set Header

func (*RequestBuilder) WithJSON

func (rb *RequestBuilder) WithJSON(body interface{}) *RequestBuilder

WithJSON sets the JSON Body

func (*RequestBuilder) WithQuery

func (rb *RequestBuilder) WithQuery(key, value string) *RequestBuilder

WithQuery sets the Query parameters

func (*RequestBuilder) WithTraceID

func (rb *RequestBuilder) WithTraceID(traceID string) *RequestBuilder

Set TraceID

type ResponseHelper

type ResponseHelper struct {
	Recorder *httptest.ResponseRecorder
}

ResponseHelper Response utility

func (*ResponseHelper) Body

func (rh *ResponseHelper) Body() string

Body Retrieve response body

func (*ResponseHelper) Header

func (rh *ResponseHelper) Header(key string) string

Get response headers

func (*ResponseHelper) JSON

func (rh *ResponseHelper) JSON(v interface{}) error

Parse the JSON response

func (*ResponseHelper) Status

func (rh *ResponseHelper) Status() int

Get status code

type TestApp

type TestApp interface {
	// RunNonBlocking Start the application non-blockingly (fully start but do not wait for shutdown signal)
	RunNonBlocking() error

	// GetHTTPServer obtain HTTP server (for testing)
	GetHTTPServer() interface {
		GetEngine() *gin.Engine
	}

	// GetDBManager Obtain database manager
	GetDBManager() *database.Manager

	// GetRedisManager Get Redis manager
	GetRedisManager() *redis.Manager

	// Shut down application
	Shutdown()
}

TestApp interface testing Any application that implements this interface can be used for testing

type TestServer

type TestServer struct {
	Engine *gin.Engine
	DB     *database.Manager
	Redis  *redis.Manager
}

TestServer test server Encapsulate the complete application instance for integration testing

func MustNewTestServer

func MustNewTestServer(t *testing.T, app TestApp) *TestServer

MustNewTestServer Create a test server (panic on failure)

func NewTestServer

func NewTestServer(app TestApp) (*TestServer, error)

Create test server (elegant version)

Usage:

// 1. Create application instance

userApp := app.NewWithConfig(configPath)

// 2. Register components and callbacks

userApp.RegisterComponents(...)
userApp.SetupCallbacks(...)

// 3. Create test server (automatically calls RunNonBlocking)

server, err := testutil.NewTestServer(userApp)

Advantages: - Reuse the complete logic of Application.Run() - The startup process for the test environment is identical to that of the production environment code is concise and easy to maintain

func (*TestServer) Close

func (ts *TestServer) Close() error

Close the test server

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL