Mockchaos is a Go library for creating mock HTTP and gRPC servers with configurable latencies, status codes, and responses. It's designed for chaos engineering, integration testing, and simulating real-world API behavior in development environments.
- 🚀 HTTP & gRPC Mocking: Create mock servers for both HTTP REST APIs and gRPC services
- ⏱️ Latency Simulation: Configure random latencies to simulate network delays
- 🎲 Randomized Responses: Randomly select from multiple status codes and latencies
- 📝 JSON Configuration: Define mocks using simple JSON files
- 🧪 Test Utilities: Built-in test helpers for integration testing
- 🐳 Standalone Servers: Run as standalone servers for Kubernetes deployments
- 🔄 Dynamic gRPC: Automatically register services from
.protofiles
go get github.com/nawafswe/mockchaosMockchaos is ideal for:
- Integration Testing: Test your services against mock dependencies with realistic latencies
- Chaos Engineering: Simulate network delays, errors, and failures
- Local Development: Replace external services with mocks during development
- CI/CD Pipelines: Run integration tests without depending on external services
- Kubernetes Deployments: Deploy mock servers as sidecars or standalone services
package mytest
import (
"net/http"
"testing"
"time"
"github.com/nawafswe/mockchaos/core/http"
"github.com/nawafswe/mockchaos/httptest"
)
func TestMyService(t *testing.T) {
handlers := []http.Handler{
{
Path: "/api/users",
Method: http.MethodGet,
Response: []byte(`{"id": 1, "name": "Alice"}`),
Statuses: []int{200, 500}, // Randomly returns 200 or 500
Latencies: []time.Duration{100 * time.Millisecond, 200 * time.Millisecond},
Headers: map[string]string{"Content-Type": "application/json"},
},
}
svc := httptest.NewServer(t, handlers...)
defer svc.Close()
// Use svc.URL() to make requests to the mock server
resp, err := http.Get(svc.URL() + "/api/users")
// ...
}package main
import (
"log"
"os"
"github.com/nawafswe/mockchaos/core/http"
)
func main() {
content, err := os.ReadFile("mocks/handlers.json")
if err != nil {
log.Fatal(err)
}
handlers, err := http.ParseHandlers(content)
if err != nil {
log.Fatal(err)
}
handler := http.NewHTTPHandler(handlers...)
// Use with your HTTP server
}[
{
"path": "/api/v1/users",
"method": "GET",
"response": {
"id": 1,
"name": "Alice"
},
"statuses": [200, 500],
"latencies": ["100ms", "200ms", "500ms"],
"headers": {
"Content-Type": "application/json"
}
}
]See examples/grpctest/grpc_test.go for a complete example:
package grpctest
import (
"context"
"testing"
"time"
"github.com/nawafswe/mockchaos/grpctest"
"google.golang.org/grpc"
"your-service/proto"
)
func TestMyGRPCService(t *testing.T) {
svc := grpctest.NewServer(t, func(server *grpc.Server) {
proto.RegisterMyServiceServer(server, &myMockServer{})
})
defer svc.Close()
client := proto.NewMyServiceClient(svc.Client)
resp, err := client.GetData(context.Background(), &proto.GetDataRequest{})
// ...
}[
{
"service": "orders.OrderService",
"method": "GetOrder",
"response_proto_type": "orders.GetOrderResponse",
"response": {
"order": {
"orderId": "123",
"status": "PENDING",
"grandTotal": 29.99
}
},
"status_codes": [0, 13],
"latencies": ["100ms", "300ms"],
"error_message": "mock internal error"
}
]gRPC Status Codes: Use numeric codes (0=OK, 13=INTERNAL, 14=UNAVAILABLE, etc.)
Mockchaos supports random latency simulation to mimic real-world network conditions:
- Multiple Latencies: Provide an array of durations
- Random Selection: Each request randomly selects one latency from the array
- Applied Before Response: The latency is applied before sending the response
// Single latency (always the same)
Latencies: []time.Duration{100 * time.Millisecond}
// Multiple latencies (randomly selected)
Latencies: []time.Duration{
50 * time.Millisecond,
100 * time.Millisecond,
200 * time.Millisecond,
500 * time.Millisecond,
}
// In JSON format
"latencies": ["50ms", "100ms", "200ms", "500ms"]- Chaos Engineering: Test how your service handles variable latencies
- Timeout Testing: Verify timeout handling with high latencies
- Performance Testing: Simulate slow dependencies
- Realistic Testing: Mimic real-world network conditions
Mockchaos includes a CLI tool for running standalone mock servers:
go install github.com/nawafswe/mockchaos/cmd/mockchaos@latestmockchaos \
-mock_server=http-svc \
-http_port=8080 \
-mocks_path=./http-mocksmockchaos \
-mock_server=grpc-svc \
-grpc_port=50051 \
-grpc_proto_dir=./protos \
-mocks_path=./grpc-mocks/orders-mock_server: Service type (http-svcorgrpc-svc)-http_port: HTTP server port (default: 8080)-grpc_port: gRPC server port (default: 50051)-grpc_proto_dir: Directory containing.protofiles (required for gRPC)-mocks_path: Directory containing JSON mock files (required)
The mocks_path directory is recursively scanned for all .json files, which are automatically loaded and combined.
See examples/k8s/app.yaml for a complete Kubernetes deployment example.
- Multiple Services: Host multiple gRPC or HTTP services with different mock paths to isolate services and resources (e.g., deploy separate gRPC services for restaurants and orders)
apiVersion: apps/v1
kind: Deployment
metadata:
name: http-mockserver
spec:
template:
spec:
containers:
- name: http
image: your-image
command: ["/bin/sh", "-c"]
args:
- |
./bin/mockchaos \
-mock_server=http-svc \
-http_port=8080 \
-mocks_path=./http-mockscore/http: Core HTTP mocking functionalitycore/grpc: Core gRPC mocking functionalityhttptest: Test utilities for HTTP mockinggrpctest: Test utilities for gRPC mockinghttp: Standalone HTTP server implementationgrpc: Standalone gRPC server implementationcmd/mockchaos: CLI tool for running standalone servers
See the examples/ directory for complete working examples:
examples/httptest/: HTTP integration test example with latency simulation and JSON configurationexamples/grpctest/: gRPC integration test example with latency simulationexamples/k8s/: Kubernetes deployment configuration
HTTP Example:
cd examples/httptest
go test -vgRPC Example:
cd examples/grpctest
go generate # Generate protobuf files
go test -v- Matching: Exact match on HTTP method and path
- Status Codes: Randomly selected from the
statusesarray - Latencies: Randomly selected from the
latenciesarray (if provided) - No Match: Returns
404 Not Foundwith{"error": "Not found"}
- Service Registration: Automatically registers services from
.protofiles - Status Codes: Randomly selected from the
status_codesarray - Latencies: Randomly selected from the
latenciesarray (if provided) - No Match: Returns
Unimplementedstatus error
Contributions are welcome! Please see our Contributing Guide for details on how to contribute.
See LICENSE file for details.