test

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: MIT Imports: 12 Imported by: 0

README

Testing Utilities

tests

This package provides a set of utilities for testing Go applications in the Dracory ecosystem. It includes tools for setting up test environments, managing test databases, and testing HTTP endpoints.

Key Components

Test Configuration

The test_config.go file provides utilities for setting up test environments:

  • TestConfig: A struct that contains configuration options for setting up a test environment
  • DefaultTestConfig(): Returns a default test configuration suitable for most test cases
  • SetupTestEnvironment(): Configures environment variables for testing
  • CleanupTestEnvironment(): Cleans up environment variables after testing
Test Database

The test_db.go file provides utilities for setting up and managing test databases:

  • NewTestDB(): Creates a new test database connection (defaults to in-memory SQLite)
  • CloseTestDB(): Safely closes a test database connection
  • ExecuteSQL(): Executes SQL statements on the database
  • CreateTestTable(): Creates test tables in the database
  • DropTestTable(): Drops test tables from the database

Note: NewTestDB requires the selected SQL driver to be registered. When using the default SQLite configuration, add a blank import for a compatible SQLite driver (for example, _ "modernc.org/sqlite") in your test code or main package.

Test HTTP

The test_http.go file provides utilities for testing HTTP endpoints:

  • TestHTTPRequest: A struct for building test HTTP requests
  • TestHTTPServer: A wrapper around httptest.Server for testing HTTP servers
  • Helper methods for executing HTTP requests and handling responses
Test Key

The test_key.go file provides a utility for generating test keys:

  • TestKey(): Generates a consistent hash based on database configuration

Usage Examples

Setting Up a Test Environment
import (
    "testing"

    testutils "github.com/dracory/test"
)

func TestSomething(t *testing.T) {
    // Create and customize a test configuration
    config := testutils.DefaultTestConfig()
    config.AppName = "My Test App"

    // Set up the test environment
    testutils.SetupTestEnvironment(config)

    // Run your tests...

    // Clean up the test environment
    testutils.CleanupTestEnvironment(config)
}
Using the Test Database
import (
    "testing"

    _ "modernc.org/sqlite"
    testutils "github.com/dracory/test"
)

func TestWithDatabase(t *testing.T) {
    // Create a test database
    db, err := testutils.NewTestDB(nil) // Uses default in-memory SQLite
    if err != nil {
        t.Fatalf("Failed to create test database: %v", err)
    }
    defer testutils.CloseTestDB(db)

    // Create a test table
    err = testutils.CreateTestTable(db, "users", "id INTEGER PRIMARY KEY, name TEXT, email TEXT")
    if err != nil {
        t.Fatalf("Failed to create test table: %v", err)
    }

    // Execute SQL
    err = testutils.ExecuteSQLWithArgs(db, "INSERT INTO users (name, email) VALUES (?, ?)", "Test User", "[email protected]")
    if err != nil {
        t.Fatalf("Failed to insert test data: %v", err)
    }

    // Run your tests with the database...
}
Testing HTTP Endpoints
import (
    "net/http"
    "testing"

    testutils "github.com/dracory/test"
)

func TestHTTPEndpoint(t *testing.T) {
    // Create a test handler
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("Hello, world!"))
    })

    // Create a request
    req := testutils.NewTestHTTPRequest("GET", "/hello").
        WithHeader("X-Test", "test-value")

    // Execute the request
    resp := req.Execute(handler)

    // Check the response
    if resp.Code != http.StatusOK {
        t.Errorf("Expected status code %d, got %d", http.StatusOK, resp.Code)
    }

    if resp.Body.String() != "Hello, world!" {
        t.Errorf("Expected body %q, got %q", "Hello, world!", resp.Body.String())
    }
}

Best Practices

  1. Always clean up resources after tests (close database connections, clean up environment variables)
  2. Use in-memory SQLite for tests to avoid external dependencies
  3. Use real database connections and stores instead of mocks
  4. Keep tests isolated and independent
  5. Use the provided utilities to simplify test setup and teardown

Documentation

Index

Constants

View Source
const (
	EnvDevelopment = "development"
	EnvLocal       = "local"
	EnvProduction  = "production"
	EnvStaging     = "staging"
	EnvTesting     = "testing"
)

Environment constants

Variables

This section is empty.

Functions

func CallEndpoint

func CallEndpoint(method string, f func(w http.ResponseWriter, r *http.Request), options NewRequestOptions) (body string, response *http.Response, err error)

func CallMiddleware

func CallMiddleware(method string, middleware func(next http.Handler) http.Handler, next func(w http.ResponseWriter, r *http.Request), options NewRequestOptions) (body string, response *http.Response, err error)

func CallStringEndpoint

func CallStringEndpoint(method string, f func(w http.ResponseWriter, r *http.Request) string, options NewRequestOptions) (body string, response *http.Response, err error)

func CleanupTestEnvironment

func CleanupTestEnvironment(config *TestConfig)

CleanupTestEnvironment unsets all environment variables set by SetupTestEnvironment

func CloseTestDB

func CloseTestDB(db *sql.DB) error

CloseTestDB safely closes a test database connection

func CreateTestTable

func CreateTestTable(db *sql.DB, tableName string, schema string) error

CreateTestTable creates a test table in the database

func DropTestTable

func DropTestTable(db *sql.DB, tableName string) error

DropTestTable drops a test table from the database

func ExecuteSQL

func ExecuteSQL(db *sql.DB, sql string) error

ExecuteSQL executes a SQL statement on the database

func ExecuteSQLWithArgs

func ExecuteSQLWithArgs(db *sql.DB, sql string, args ...interface{}) error

ExecuteSQLWithArgs executes a SQL statement with arguments on the database

func NewRequest

func NewRequest(method string, url string, opts NewRequestOptions) (*http.Request, error)

NewRequest creates a new Request for testing, but adds RequestURI as the default imlemented in GoLang does not add the RequestURI and leaves it to the end user to implement

func NewTestDB

func NewTestDB(config *DBConfig) (*sql.DB, error)

NewTestDB creates a new test database connection By default, it creates an in-memory SQLite database

func SetupTestEnvironment

func SetupTestEnvironment(config *TestConfig)

SetupTestEnvironment configures the environment variables for testing based on the provided configuration

func StringResponse

func StringResponse(w http.ResponseWriter, r *http.Request, body string)

StringResponse - responds with the string body

func TestKey

func TestKey(dbDriver, dbHost, dbPort, dbName, dbUser, dbPass string) string

TestKey is a pseudo secret test key used for testing specific unit cases where a secret key is required but not available in the testing environment. It generates a consistent hash based on the provided database configuration.

Types

type DBConfig

type DBConfig struct {
	Driver   string
	Host     string
	Port     string
	Database string
	Username string
	Password string
}

DBConfig contains configuration for test database

func DefaultDBConfig

func DefaultDBConfig() *DBConfig

DefaultDBConfig returns a default SQLite in-memory database configuration. To use the default SQLite driver, ensure you import a compatible driver package (for example, via a blank import in your test setup) before calling NewTestDB.

type NewRequestOptions

type NewRequestOptions struct {
	// Body use this to set the request body
	Body string

	// Context allows setting the request context.
	Context map[any]any

	// ContentType allows setting the Content-Type header
	ContentType string

	// Headers allows setting the request headers
	Headers map[string]string

	// GetValues use this to set the GET values, it will be converted to url.Values
	// and set as the request query
	// Deprecated: use QueryValues
	GetValues urlpkg.Values

	// PostValues use this to set the POST values, it will be converted to url.Values
	// and set as the request body, with Content-Type: application/x-www-form-urlencoded
	// Deprecated: use FormValues
	PostValues urlpkg.Values

	// JSONData sets the request body as application/json.
	// If set, Body and FormValues will be ignored.
	JSONData any

	// QueryParams sets the URL query parameters.
	QueryParams urlpkg.Values

	// FormValues sets the request body as application/x-www-form-urlencoded.
	// If set, Body and JSONData will be ignored.
	FormValues urlpkg.Values
}

NewRequest options for the new request

type StringHandler

type StringHandler func(w http.ResponseWriter, r *http.Request) string

func (StringHandler) ServeHTTP

func (h StringHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type TestConfig

type TestConfig struct {
	// Application settings
	AppName string
	AppURL  string
	AppEnv  string

	// Database settings
	DbDriver   string
	DbHost     string
	DbPort     string
	DbDatabase string
	DbUsername string
	DbPassword string

	// Server settings
	ServerHost string
	ServerPort string

	// Mail settings
	MailDriver   string
	MailHost     string
	MailPort     string
	MailUsername string
	MailPassword string
	EmailFrom    string
	EmailName    string

	// Security settings
	EnvEncryptionKey string
	VaultKey         string

	// Additional settings can be added as needed
	AdditionalEnvVars map[string]string
}

TestConfig contains configuration options for setting up a test environment

func DefaultTestConfig

func DefaultTestConfig() *TestConfig

DefaultTestConfig returns a default test configuration suitable for most test cases

type TestHTTPRequest

type TestHTTPRequest struct {
	Method  string
	Path    string
	Body    io.Reader
	Headers map[string]string
}

TestHTTPRequest represents a test HTTP request

func NewTestHTTPRequest

func NewTestHTTPRequest(method, path string) *TestHTTPRequest

NewTestHTTPRequest creates a new test HTTP request

func (*TestHTTPRequest) Execute

func (r *TestHTTPRequest) Execute(handler http.Handler) *httptest.ResponseRecorder

Execute executes the request against the provided handler

func (*TestHTTPRequest) WithBody

func (r *TestHTTPRequest) WithBody(body string) *TestHTTPRequest

WithBody sets the request body

func (*TestHTTPRequest) WithFormBody

func (r *TestHTTPRequest) WithFormBody(formBody string) *TestHTTPRequest

WithFormBody sets the request body as form data and adds the appropriate content type header

func (*TestHTTPRequest) WithHeader

func (r *TestHTTPRequest) WithHeader(key, value string) *TestHTTPRequest

WithHeader adds a header to the request

func (*TestHTTPRequest) WithJSONBody

func (r *TestHTTPRequest) WithJSONBody(jsonBody string) *TestHTTPRequest

WithJSONBody sets the request body as JSON and adds the appropriate content type header

type TestHTTPServer

type TestHTTPServer struct {
	Server *httptest.Server
}

TestHTTPServer is a wrapper around httptest.Server for testing HTTP servers

func NewTestHTTPServer

func NewTestHTTPServer(handler http.Handler) *TestHTTPServer

NewTestHTTPServer creates a new test HTTP server with the provided handler

func (*TestHTTPServer) Close

func (s *TestHTTPServer) Close()

Close closes the test server

func (*TestHTTPServer) Do

func (s *TestHTTPServer) Do(req *http.Request) (*http.Response, error)

Do performs a custom request to the test server

func (*TestHTTPServer) Get

func (s *TestHTTPServer) Get(path string) (*http.Response, error)

Get performs a GET request to the test server

func (*TestHTTPServer) Post

func (s *TestHTTPServer) Post(path string, contentType string, body io.Reader) (*http.Response, error)

Post performs a POST request to the test server

func (*TestHTTPServer) URL

func (s *TestHTTPServer) URL() string

URL returns the base URL of the test server

Jump to

Keyboard shortcuts

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