### Install Unimock Go Client Source: https://github.com/bmcszk/unimock/blob/master/docs/client.md Use 'go get' to install the Unimock Go client library. This command fetches and installs the specified package. ```bash go get github.com/bmcszk/unimock/pkg/client ``` -------------------------------- ### Run Unimock Example Source: https://github.com/bmcszk/unimock/blob/master/examples/library/README.md Execute the example using the Go run command. This starts a mock server on port 8081. ```bash go run . ``` -------------------------------- ### Test Environment Configuration Example Source: https://github.com/bmcszk/unimock/blob/master/docs/testing-guidelines.md Shows how to define test-specific environment variables in a .env.test file and load them during test setup. ```dotenv # .env.test TEST_DB_URL=postgres://test:test@localhost:5433/testdb TEST_SQS_QUEUE_URL=http://localhost:4566/000000000000/test-queue TEST_SERVICE_ADDRESS=http://localhost:18082 ``` ```go // Test setup with environment loading func newParts(t *testing.T) (*parts, *parts, *parts) { t.Helper() var envs config.Environment // Load test-specific environment err := godotenv.Load(".env.test") assert.NoError(t, err, "load test config") err = env.Parse(&envs) assert.NoError(t, err, "parse test config") // Continue with test setup... } ``` -------------------------------- ### Start Tilt Development Environment Source: https://github.com/bmcszk/unimock/blob/master/docs/deployment.md Run this command to start the local development environment with Tilt. It automates cluster creation, image building, deployment, and live reload setup. ```bash make tilt-run ``` -------------------------------- ### Install and Run Unimock Binary from Source Source: https://github.com/bmcszk/unimock/blob/master/docs/deployment.md Instructions for installing the Unimock binary by cloning the repository and building it locally. This method is useful for development or when direct Go installation is not preferred. ```bash # Install from source git clone https://github.com/bmcszk/unimock.git cd unimock make build ./unimock ``` -------------------------------- ### Unimock Installation Methods Source: https://github.com/bmcszk/unimock/blob/master/README.md Overview of different methods to install and run Unimock, including Docker, Helm, local build, and as a Go library. ```markdown | Method | Command | Use Case | |--------|---------|----------| | **Docker** | `docker run -p 8080:8080 ghcr.io/bmcszk/unimock` | Quick testing | | **Helm (Registry)** | `helm install unimock oci://ghcr.io/bmcszk/charts/unimock` | Production | | **Local Build** | `make build && ./unimock` | Development | | **Go Library** | `import "github.com/bmcszk/unimock/pkg"` | Embed in apps | ``` -------------------------------- ### Quick Start: Unimock Go Client Usage Source: https://github.com/bmcszk/unimock/blob/master/docs/client.md Demonstrates creating a client, performing a POST request to store data, and a GET request to retrieve it. Assumes the Unimock server is running on localhost:8080. ```go package main import ( "context" "fmt" "log" "github.com/bmcszk/unimock/pkg/client" ) func main() { // Create client (uses localhost:8080 if URL is empty) c, err := client.NewClient("http://localhost:8080") if err != nil { log.Fatal(err) } ctx := context.Background() // Store data via POST headers := map[string]string{"Content-Type": "application/json"} data := `{"id": "123", "name": "John Doe", "email": "john@example.com"}` resp, err := c.Post(ctx, "/api/users", headers, []byte(data)) if err != nil { log.Fatal(err) } fmt.Printf("Created: %d\n", resp.StatusCode) // Retrieve data via GET resp, err = c.Get(ctx, "/api/users/123", nil) if err != nil { log.Fatal(err) } fmt.Printf("Retrieved: %s\n", string(resp.Body)) } ``` -------------------------------- ### Install Unimock Go Package Source: https://github.com/bmcszk/unimock/blob/master/docs/library.md Use 'go get' to install the Unimock package for use in your Go projects. ```bash go get github.com/bmcszk/unimock/pkg ``` -------------------------------- ### Install Unimock Binary with Go Source: https://github.com/bmcszk/unimock/blob/master/docs/deployment.md Install the Unimock standalone binary using the Go toolchain. This is a convenient way to get the latest version for direct command-line usage. ```bash # Install with Go go install github.com/bmcszk/unimock@latest unimock ``` -------------------------------- ### Environment Configuration Example Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md Shows example environment variables for database, SQS, and service addresses, along with Go code to load and parse these configurations using godotenv. ```text // .env.test TEST_DB_URL=postgres://test:test@localhost:5433/testdb TEST_SQS_QUEUE_URL=http://localhost:4566/000000000000/test-queue TEST_SERVICE_ADDRESS=http://localhost:18082 ``` ```go // Test setup with environment loading func newParts(t *testing.T) (*parts, *parts, *parts) { t.Helper() var envs config.Environment // Load test-specific environment err := godotenv.Load(".env.test") assert.NoError(t, err, "load test config") err = env.Parse(&envs) assert.NoError(t, err, "parse test config") // Continue with test setup... } ``` -------------------------------- ### Unimock Quick Reference - GET Test Source: https://github.com/bmcszk/unimock/blob/master/README.md Example of how to test a GET request to the Unimock server using curl. ```bash curl :8080/api/users/1 ``` -------------------------------- ### Unimock Configuration for Practical Example Source: https://github.com/bmcszk/unimock/blob/master/prds/strict_path_matching/strict_path_matching_prd.md This YAML configuration is used for a practical example comparing strict and flexible path matching behaviors. ```yaml sections: regular_users: path_pattern: "/users/*" strict_path: false body_id_paths: ["/id"] admin_users: path_pattern: "/admin/users/*" strict_path: true body_id_paths: ["/id"] ``` -------------------------------- ### Start Embedded Unimock Server in Go Source: https://github.com/bmcszk/unimock/blob/master/docs/deployment.md This Go code snippet demonstrates how to initialize and start an embedded Unimock server. Ensure you have the necessary imports and mock configuration defined. ```go import "github.com/bmcszk/unimock/pkg" // Start embedded server server, err := pkg.NewServer( pkg.WithPort(8080), pkg.WithMockConfig(mockConfig), ) if err != nil { log.Fatal(err) } go server.ListenAndServe() ``` -------------------------------- ### Implement Clean Test Setup Separation in Go Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md Shows the correct pattern for separating test setup from test logic using a fluent interface. This improves readability and maintainability. ```go // GOOD: Clean setup separation func TestVideoProcessing(t *testing.T) { given, when, then := newParts(t) given. setupVideoProcessingEnvironment().and(). uploadTestVideo() when. startVideoProcessing() then. videoProcessedSuccessfully().and(). assetsCreated() } func (p *parts) setupVideoProcessingEnvironment() *parts { // All complex setup encapsulated in helper method p.db = setupDatabase(p.T, "test-config.sql") p.sqsClient = setupSQS(p.T) p.s3Client = setupS3(p.T) p.videoProcessor = NewVideoProcessor(p.db, p.sqsClient, p.s3Client) return p } ``` -------------------------------- ### Install Unimock from Local Chart Source: https://github.com/bmcszk/unimock/blob/master/docs/deployment.md Install Unimock from a local chart directory after cloning the repository. Supports default installation or installation with custom values. ```bash # Clone repository git clone https://github.com/bmcszk/unimock.git cd unimock # Install with defaults helm install my-unimock ./helm/unimock # Install with custom values helm install my-unimock ./helm/unimock -f my-values.yaml ``` -------------------------------- ### Install Unimock Helm Chart from Source Source: https://github.com/bmcszk/unimock/blob/master/helm/unimock/README.md Clone the Unimock repository and install the Helm chart directly from the local source files. This is an alternative to installing from a published repository. ```bash git clone https://github.com/bmcszk/unimock.git cd unimock/helm helm install my-unimock ./unimock ``` -------------------------------- ### Valid Fixture File Syntax Examples Source: https://github.com/bmcszk/unimock/blob/master/CLAUDE.md Illustrates valid syntax for loading fixture files, including space after '<' and immediate '@' after '<'. ```text "< file" - VALID (space after <) "<@ file" - VALID (@ immediately after <, space after @) ``` -------------------------------- ### Troubleshoot Unimock Pod Startup Source: https://github.com/bmcszk/unimock/blob/master/helm/unimock/README.md If a Unimock pod fails to start, check resource limits and pull secrets. Use `kubectl describe pod` to get detailed information about the pod's status and events. ```bash kubectl describe pod -l app.kubernetes.io/name=unimock ``` -------------------------------- ### Start Unimock with Unified Config Source: https://github.com/bmcszk/unimock/blob/master/docs/scenarios.md Commands to start the Unimock service using a unified configuration file, either directly or via Docker. ```bash # Using unified config file unimock # Using Docker with unified config docker run -p 8080:8080 \ -v $(pwd)/config.yaml:/etc/unimock/config.yaml \ ghcr.io/bmcszk/unimock:latest ``` -------------------------------- ### Simplified Unified Configuration Scenario Source: https://github.com/bmcszk/unimock/blob/master/docs/scenarios.md A minimal example of a scenario defined in a unified configuration file, focusing on a GET request for a specific user. ```yaml sections: users: path_pattern: "/api/users/*" body_id_paths: ["/id"] scenarios: - uuid: "example-user-001" method: "GET" path: "/api/users/123" status_code: 200 content_type: "application/json" data: | { "id": "123", "name": "John Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Anti-Pattern: Complex Test Setup Source: https://github.com/bmcszk/unimock/blob/master/docs/testing-guidelines.md Demonstrates a test where setup logic is intertwined with test execution and assertions, making it hard to read and maintain. ```go // Bad: Test setup mixed with test logic func TestBadExample(t *testing.T) { // Complex setup mixed in db, err := sqlx.Connect("postgres", "postgres://test:test@localhost:5433/testdb") if err != nil { t.Fatal(err) } httpClient := &http.Client{} sqsClient := setupSQSClient() // Test logic buried in setup resp, err := httpClient.Post("http://localhost:8080/videos", "application/json", bytes.NewReader(data)) if err != nil { t.Fatal(err) } // Assertions mixed with setup if resp.StatusCode != 201 { t.Errorf("expected 201, got %d", resp.StatusCode) } } ``` -------------------------------- ### Install Unimock from Registry Source: https://github.com/bmcszk/unimock/blob/master/docs/deployment.md Install the latest or a specific version of Unimock from the GitHub Container Registry using Helm. Custom values can be applied using a YAML file. ```bash # Install latest version from GitHub Container Registry helm install unimock oci://ghcr.io/bmcszk/charts/unimock # Install specific version helm install unimock oci://ghcr.io/bmcszk/charts/unimock --version 1.2.0 # Install with custom values helm install unimock oci://ghcr.io/bmcszk/charts/unimock -f my-values.yaml ``` -------------------------------- ### Run Unimock with Docker and Test Source: https://github.com/bmcszk/unimock/blob/master/README.md Quickly start Unimock using Docker and test its functionality with sample curl commands. ```bash # 1. Run with Docker docker run -p 8080:8080 ghcr.io/bmcszk/unimock:latest # 2. Test it curl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"id": "123", "name": "John Doe"}' curl http://localhost:8080/api/users/123 ``` -------------------------------- ### Correct: Single Given Chain Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md Demonstrates the correct fluent chaining pattern where all setup steps are chained within a single 'given' statement. This ensures proper test state management and atomic setup. ```go // ✅ CORRECT: Single given chain func TestComplexSetup(t *testing.T) { given, when, then := newParts(t) given. setupDatabase().and(). createTestData().and(). configureServices() when. executeAction() then. verifyResult() } ``` -------------------------------- ### E2E Test Workflow Example Source: https://github.com/bmcszk/unimock/blob/master/docs/testing-guidelines.md Demonstrates a complete user journey test in an E2E scenario. Assumes Docker Compose services are running and connects to them via localhost. ```go package e2e_test import ( "testing" "net/http" ) func TestWorkflow_CompleteUserJourney(t *testing.T) { // given - assumes docker-compose.test.yml services are running client := &http.Client{} userData := buildUserData() // when - connect to containerized services response := makeRequest(client, "POST", "http://localhost:18081/api/register", userData) // then assert.Equal(t, http.StatusCreated, response.StatusCode) // Continue workflow testing with external service connections... } ``` -------------------------------- ### Test File Structure Example Source: https://github.com/bmcszk/unimock/blob/master/docs/testing-guidelines.md Illustrates a recommended directory structure for organizing end-to-end tests, separating test data, templates, configuration, and test logic. ```directory test/ ├── e2e/ │ ├── assets/ # Test data files │ │ └── test-video.mp4 │ ├── templates/ # Template files for test data │ │ ├── asset_event.json │ │ └── encode_task_event.json │ ├── .env.test # Test environment configuration │ ├── docker-compose.test.yml │ ├── e2e_test.go # Main test scenarios (readable workflows) │ ├── e2e_parts_test.go # Test helpers and fluent interface │ └── e2e_checks_test.go # Asynchronous check implementation ``` -------------------------------- ### Given/When/Then Structure for Complex Workflow Test Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md Demonstrates the use of all three Given/When/Then parts for tests requiring setup and configuration. ```go func TestComplexWorkflow(t *testing.T) { given, when, then := newParts(t) given. setupTestData().and(). configureServices() when. executeWorkflow() then. verifyExpectedResult().and(). noError() } ``` -------------------------------- ### JSON with Arrays for Order Items Source: https://github.com/bmcszk/unimock/blob/master/docs/examples.md This example demonstrates creating an order resource that includes an array of items, each with its own details like product, price, and quantity. ```bash curl -X POST http://localhost:8080/api/orders \ -H "Content-Type: application/json" \ -d '{ "id": "order789", "customer": "John Doe", "items": [ {"id": "item1", "product": "Laptop", "price": 1200, "quantity": 1}, {"id": "item2", "product": "Mouse", "price": 25, "quantity": 2} ], "total": 1250 }' ``` -------------------------------- ### Unimock Quick Reference - POST Test Source: https://github.com/bmcszk/unimock/blob/master/README.md Example of how to test a POST request to the Unimock server using curl. ```bash curl -X POST :8080/api/users -d '{"id":"1"}' ``` -------------------------------- ### Standard Integration Test Example Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md This Go code demonstrates a typical structure for a standard integration test before migration. It focuses on direct function calls and assertions. ```go // BEFORE: Standard integration test func TestUserService_CreateUser(t *testing.T) { db := setupTestDatabase(t) defer db.Close() service := NewUserService(db) user := &User{Name: "Test User", Email: "test@example.com"} created, err := service.CreateUser(user) assert.NoError(t, err) assert.Equal(t, user.Name, created.Name) assert.NotZero(t, created.ID) } ``` -------------------------------- ### Correct: Single Given Method (No Chaining) Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md Illustrates a correct scenario for a single 'given' statement when no further chaining is required. This is suitable for simpler setup configurations. ```go // ✅ CORRECT: Single given method (when no chaining needed) func TestSimpleSetup(t *testing.T) { given, when, then := newParts(t) given. unifiedConfigFile() when. a_get_request_is_made_to("/api/resource") then. the_response_is_successful() } ``` -------------------------------- ### Setup Test Data Helper Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md A helper function to set up test data. It marks itself as a test helper using `t.Helper()`. ```go func setupTestData(t *testing.T) TestData { t.Helper() data := TestData{ Field1: "value1", Field2: "value2", } return data } ``` -------------------------------- ### Invalid Fixture File Syntax Examples Source: https://github.com/bmcszk/unimock/blob/master/CLAUDE.md Shows invalid syntax for fixture file loading that will result in fallback to literal string data. ```text " %d\n", scenario.Method, scenario.Path, scenario.StatusCode) ``` ``` -------------------------------- ### Get a Scenario Source: https://github.com/bmcszk/unimock/blob/master/docs/technical_endpoints.md Retrieves a specific test scenario by its UUID. ```APIDOC ## GET /_uni/scenarios/{uuid} ### Description Retrieves a specific test scenario using its unique identifier (UUID). ### Method GET ### Endpoint /_uni/scenarios/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - The unique identifier of the scenario to retrieve. ### Response #### Success Response (200) - **uuid** (string) - Unique identifier for the scenario. - **method** (string) - HTTP method. - **path** (string) - API path. - **status_code** (integer) - HTTP status code. - **content_type** (string) - Content type of the response. - **location** (string) - Location header returned (if provided). - **headers** (object) - Additional response headers returned (if provided). - **data** (string) - Response body data returned (if provided). ### Response Example { "uuid": "550e8400-e29b-41d4-a716-446655440000", "method": "GET", "path": "/api/users/123", "status_code": 200, "content_type": "application/json", "data": "{\"id\":\"123\",\"name\":\"John Doe\"}" } ``` -------------------------------- ### Get Specific Scenario Source: https://github.com/bmcszk/unimock/blob/master/docs/scenarios.md Retrieve the details of a particular scenario by its unique identifier. ```bash curl http://localhost:8080/_uni/scenarios/user-not-found ``` -------------------------------- ### Get comments from a specific review Source: https://github.com/bmcszk/unimock/blob/master/docs/pr-guidelines.md Fetches comments associated with a particular review on a pull request. ```bash gh api repos/:owner/:repo/pulls/:pr_number/reviews/:review_id/comments ``` -------------------------------- ### Create a Mock Scenario in Go Source: https://github.com/bmcszk/unimock/blob/master/docs/client.md Shows how to define and create a new scenario for mocking API responses. Ensure the `model` package is imported. ```go import "github.com/bmcszk/unimock/pkg/model" scenario := model.Scenario{ UUID: "user-not-found", // Optional, auto-generated if empty Method: "GET", Path: "/api/users/999", StatusCode: 404, ContentType: "application/json", Data: `{"error": "User not found", "code": "USER_NOT_FOUND"}`, } err := client.CreateScenario(ctx, scenario) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Server Health Status Source: https://github.com/bmcszk/unimock/blob/master/docs/technical_endpoints.md Use this endpoint to check the current status and uptime of the Unimock server. ```bash curl -X GET http://localhost:8080/_uni/health ``` -------------------------------- ### Get all reviews for a PR Source: https://github.com/bmcszk/unimock/blob/master/docs/pr-guidelines.md Retrieves all reviews submitted for a specific pull request using the GitHub API. ```bash gh api repos/:owner/:repo/pulls/:pr_number/reviews ``` -------------------------------- ### Configure Server via Environment Variables Source: https://github.com/bmcszk/unimock/blob/master/docs/library.md Use environment variables for production-ready Unimock server configuration. This allows for flexible deployment-time settings. ```go // Production-ready configuration serverConfig := config.FromEnv() // Allows deployment-time configuration via: // UNIMOCK_PORT=8080 // UNIMOCK_LOG_LEVEL=info // UNIMOCK_CONFIG=/etc/unimock/config.yaml ``` -------------------------------- ### Get a Specific Scenario by UUID in Go Source: https://github.com/bmcszk/unimock/blob/master/docs/client.md Retrieves a single mock scenario using its unique identifier (UUID). ```go // Get specific scenario by UUID scenario, err := client.GetScenario(ctx, "user-not-found") if err != nil { log.Fatal(err) } fmt.Printf("Scenario: %s %s -> %d\n", scenario.Method, scenario.Path, scenario.StatusCode) ``` -------------------------------- ### Integration Testing with File-based Configuration Source: https://github.com/bmcszk/unimock/blob/master/docs/library.md Shows how to perform integration tests using Unimock with configurations loaded from temporary YAML files. It includes creating a temporary file, configuring the server, and loading the configuration. ```go func TestWithConfigFiles(t *testing.T) { // Create temporary config file configFile := createTempConfig(t, ` sections: users: path_pattern: "/api/users/*" body_id_paths: - "/id" return_body: true `) defer os.Remove(configFile) // Create server config pointing to file serverConfig := &config.ServerConfig{ Port: "0", LogLevel: "error", ConfigPath: configFile, } // Load mock config from file uniConfig, err := config.LoadFromYAML(serverConfig.ConfigPath) require.NoError(t, err) // Create and test server server, err := pkg.NewServer(serverConfig, uniConfig) require.NoError(t, err) // ... test operations } func createTempConfig(t *testing.T, content string) string { file, err := os.CreateTemp("", "unimock-test-*.yaml") require.NoError(t, err) _, err = file.WriteString(content) require.NoError(t, err) err = file.Close() require.NoError(t, err) return file.Name() } ``` -------------------------------- ### Get general PR comments Source: https://github.com/bmcszk/unimock/blob/master/docs/pr-guidelines.md Retrieves all general comments made on a pull request, excluding those within specific reviews. ```bash gh api repos/:owner/:repo/pulls/:pr_number/comments ``` -------------------------------- ### Implement Graceful Server Shutdown Source: https://github.com/bmcszk/unimock/blob/master/docs/library.md Start the Unimock server and handle interrupt signals for a graceful shutdown with a configurable timeout. ```go import ( "context" "log" "os" "os/signal" "syscall" "time" ) func main() { server, err := pkg.NewServer(serverConfig, uniConfig) if err != nil { log.Fatal(err) } // Start server in background go func() { log.Printf("Starting server on %s", server.Addr) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatal("Server error:", err) } }() // Wait for interrupt signal quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down server...") // Graceful shutdown with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := server.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } log.Println("Server exited") } ``` -------------------------------- ### Setting up Test Environment with GoDotEnv Source: https://github.com/bmcszk/unimock/blob/master/docs/fluent-testing.md Loads test-specific environment variables from a .env.test file and initializes a TestEnvironment struct with necessary configuration values. ```go // Separate test configs with environment-specific behavior func setupTestEnvironment(t *testing.T) *TestEnvironment { t.Helper() // Load test-specific config err := godotenv.Load(".env.test") require.NoError(t, err, "load test environment") env := &TestEnvironment{ DBURL: os.Getenv("TEST_DB_URL"), SQSQueue: os.Getenv("TEST_SQS_QUEUE_URL"), ServiceAddr: os.Getenv("TEST_SERVICE_ADDRESS"), } return env } ``` -------------------------------- ### Load Configuration from YAML Source: https://github.com/bmcszk/unimock/blob/master/docs/library.md Loads mock configuration from a specified YAML file. Use this for standard configuration loading. ```go import ( "github.com/bmcszk/unimock/pkg/config" ) func loadFromYAML() (*config.UniConfig, error) { // Load mock configuration from YAML file return config.LoadFromYAML("config.yaml") } ``` ```go import ( "github.com/bmcszk/unimock/pkg/config" ) func loadUnifiedFromYAML() (*config.UnifiedConfig, error) { // Load unified configuration (sections + scenarios) from YAML file return config.LoadUnifiedFromYAML("config.yaml") } ```