| Crates.io | mockforge-sdk |
| lib.rs | mockforge-sdk |
| version | 0.3.20 |
| created_at | 2025-10-29 16:55:58.458087+00 |
| updated_at | 2025-12-31 14:11:03.358124+00 |
| description | Developer SDK for embedding MockForge in tests and applications |
| homepage | https://mockforge.dev |
| repository | https://github.com/SaaSy-Solutions/mockforge |
| max_upload_size | |
| id | 1906947 |
| size | 432,319 |
MockForge is a comprehensive mocking framework for APIs, gRPC services, and WebSockets. It provides a unified interface for creating, managing, and deploying mock servers across different protocols with advanced data generation capabilities.
MockForge is built on five foundational pillars that guide every feature: [Reality], [Contracts], [DevX], [Cloud], and [AI]. These pillars ensure MockForge delivers a cohesive, powerful mocking experience that scales from solo developers to enterprise teams.
See the complete Pillars documentation for detailed information about each pillar, feature mappings, and examples. All changelog entries are tagged with these pillars to make it clear what each release invests in.
| Feature | MockForge | WireMock | MockServer | Mockoon |
|---|---|---|---|---|
| Language | Rust | Java | Java/JavaScript | JavaScript |
| Multi-Language SDKs | β Rust, Node.js, Python, Go, Java, .NET | β οΈ Java native, clients for others | β οΈ Java/JS native, clients for others | β οΈ JS native, clients for others |
| Performance | β‘ High (native Rust) | Medium | Medium | Medium |
| HTTP/REST | β Full | β Full | β Full | β Full |
| gRPC Native | β Full + HTTP Bridge | β No | β No | β οΈ Limited |
| WebSocket | β Scripted Replay + JSONPath | β No | β οΈ Basic | β No |
| GraphQL | β Yes | β οΈ Via HTTP | β οΈ Via HTTP | β Yes |
| Kafka | β Full Mock Broker | β No | β No | β No |
| MQTT | β Full Broker (3.1.1 & 5.0) | β No | β No | β No |
| AMQP/RabbitMQ | β Full Broker (0.9.1) | β No | β No | β No |
| SMTP | β Full Email Server | β No | β No | β No |
| FTP | β Full File Transfer | β No | β No | β No |
| TCP | β Raw TCP Mocking | β No | β No | β No |
| Client Generation | β React, Vue, Angular, Svelte | β No | β No | β No |
| TLS/mTLS | β HTTPS + Mutual TLS | β οΈ TLS only | β οΈ TLS only | β οΈ TLS only |
| Admin UI | β Modern React UI | β οΈ Basic | β Yes | β Desktop App |
| Data Generation | β Advanced (Faker + RAG) | β οΈ Basic | β οΈ Basic | β οΈ Templates |
| AI-Driven Mocking | β LLM-powered generation | β No | β No | β No |
| Data Drift | β Evolving mock data | β No | β No | β No |
| AI Event Streams | β Narrative-driven WebSocket | β No | β No | β No |
| Plugin System | β WASM-based | β οΈ Java extensions | β οΈ JavaScript | β No |
| E2E Encryption | β Built-in (AES-256/ChaCha20) | β No | β οΈ TLS only | β οΈ TLS only |
| Workspace Sync | β Git integration + file watching | β No | β No | β οΈ Cloud sync (Pro) |
| Cross-Endpoint Validation | β Referential integrity checks | β No | β No | β No |
| OpenAPI Support | β Full + Auto-generation | β Yes | β Yes | β Yes |
| Template Expansion | β Advanced (faker, time, UUIDs) | β οΈ Basic | β οΈ Basic | β Handlebars |
| Deployment | Binary, Docker, Cargo | JAR, Docker, Maven | JAR/NPM, Docker | Desktop, NPM, Docker |
| Stateful Mocking | β Yes | β Yes | β Yes | β Yes |
| Request Matching | β JSONPath, Regex, Schema | β Yes | β Yes | β Yes |
| Latency Simulation | β Configurable profiles | β Yes | β Yes | β Yes |
| Fault Injection | β Yes | β Yes | β Yes | β Yes |
| CLI Tool | β Full-featured | β Yes | β Yes | β Yes |
| License | MIT/Apache-2.0 | Apache-2.0 | Apache-2.0 | MIT |
MockForge provides native SDKs for multiple programming languages, enabling developers to embed mock servers directly in their test suites regardless of their technology stack.
Rust:
let mut server = MockServer::new().port(3000).start().await?;
server.stub_response("GET", "/api/users/{id}", json!({"id": 123})).await?;
Node.js:
const server = await MockServer.start({ port: 3000 });
await server.stubResponse('GET', '/api/users/123', { id: 123 });
Python:
with MockServer(port=3000) as server:
server.stub_response('GET', '/api/users/123', {'id': 123})
See SDK Documentation for complete examples and Ecosystem & Use Cases Guide for detailed comparisons with WireMock.
MockForge supports a wide range of use cases, from unit testing to service virtualization:
Embed mock servers directly in test suites across all supported languages. No separate server process required for most SDKs.
Test complex multi-service interactions with stateful mocking and multi-protocol support (HTTP, gRPC, WebSocket).
Replace external dependencies with mocks using proxy mode and record/replay workflows. Capture real API behavior and replay it later.
Create local development environments without backend dependencies. Share mock configurations across teams with workspace synchronization.
Simulate network failures, timeouts, and slow responses with built-in latency and fault injection. Test application resilience under various failure conditions.
Generate realistic mocks from API specifications (OpenAPI, GraphQL, gRPC) before implementation. Enable parallel development with schema-driven mock generation.
For detailed use case examples and code samples, see Ecosystem & Use Cases Guide.
All major features listed in this README are implemented and functional in v1.0, with the following clarification:
All commands, options, and features documented in each protocol section (HTTP, gRPC, WebSocket, GraphQL, Plugins, Data Generation) have been verified to work as described.
mockforge plugin install https://github.com/user/plugin#v1.0.0For comprehensive documentation, tutorials, and guides:
The documentation covers:
Install the MockForge VS Code Extension to enhance your development workflow:
mockforge.yaml files with inline error reportingSee the VS Code Extension README for detailed features and usage.
New to MockForge? Follow our Golden Path Guide β - the fastest way from zero to integrated mock API in under 10 minutes.
Prefer a quick API? Try our 5-Minute Tutorial to create your first mock API.
Need help? Check the FAQ or Troubleshooting Guide.
# Install from crates.io
cargo install mockforge-cli
# Or build from source
git clone https://github.com/SaaSy-Solutions/mockforge.git
cd mockforge
make setup
make build
make install
For faster typing, you can set up command aliases:
# Run the setup script
./scripts/setup-aliases.sh
# Or manually add to your ~/.bashrc or ~/.zshrc:
alias mf='mockforge'
alias mf-serve='mockforge serve'
alias mf-wizard='mockforge wizard'
Then use mf instead of mockforge:
mf wizard # Interactive setup wizard
mf serve # Start mock server
mf init . # Initialize project
MockForge comes with comprehensive examples to get you started quickly:
# Run with the included examples
make run-example
# Or use the configuration file
cargo run -p mockforge-cli -- serve --config demo-config.yaml
# Or run manually with environment variables
MOCKFORGE_WS_REPLAY_FILE=examples/ws-demo.jsonl \
MOCKFORGE_RESPONSE_TEMPLATE_EXPAND=true \
cargo run -p mockforge-cli -- serve --spec examples/openapi-demo.json --admin
MockForge supports multiple API specification formats for generating mocks and clients:
.proto files# Generate mocks from OpenAPI spec
mockforge generate --spec api.json --output ./generated
# Serve with OpenAPI spec
mockforge serve --spec api.yaml --admin
# Import OpenAPI spec and generate mocks
mockforge import openapi ./specs/api.yaml --output mocks.json
Example OpenAPI 3.0 Specification:
{
"openapi": "3.0.0",
"info": {
"title": "User Management API",
"version": "1.0.0",
"description": "API for managing users"
},
"servers": [
{
"url": "https://api.example.com/v1"
}
],
"paths": {
"/users": {
"get": {
"summary": "List users",
"responses": {
"200": {
"description": "List of users",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/User"
}
}
}
}
}
}
},
"post": {
"summary": "Create user",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/User"
}
}
}
},
"responses": {
"201": {
"description": "User created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/User"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"User": {
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
}
}
}
}
}
}
# Serve with GraphQL schema
mockforge serve --graphql schema.graphql --graphql-port 4000
# Generate from GraphQL schema
mockforge generate --spec schema.graphql --output ./generated
Example GraphQL Schema:
type Query {
users: [User!]!
user(id: ID!): User
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
}
type User {
id: ID!
name: String!
email: String!
createdAt: DateTime!
}
input CreateUserInput {
name: String!
email: String!
}
input UpdateUserInput {
name: String
email: String
}
scalar DateTime
# Serve with proto files
mockforge serve --grpc-port 50051
# Proto files are discovered from configured directories
MockForge provides comprehensive validation with detailed error messages:
Example validation output:
$ mockforge generate --spec invalid-api.json
Invalid OpenAPI specification:
Missing 'info' section in OpenAPI 3.x spec (at /info). Hint: Add an 'info' section with 'title' and 'version' fields
Missing or empty 'info.title' field (at /info/title). Hint: Add 'title' field to the 'info' section
'paths' object cannot be empty. At least one endpoint is required (at /paths). Hint: Add at least one path definition
Fix the validation errors above and try again
Validation Features:
While MockForge can detect and validate Swagger 2.0 specifications, full parsing requires OpenAPI 3.x format. Use conversion tools:
# Using swagger2openapi (Node.js)
npx swagger2openapi swagger.json -o openapi.json
# Or use online converter
# https://editor.swagger.io/
See examples/README.md for detailed documentation on the example files.
MockForge can also be run using Docker for easy deployment:
# Using Docker Compose (recommended)
make docker-compose-up
# Or using Docker directly
make docker-build && make docker-run
# Build the image
docker build -t mockforge .
# Run with examples
docker run -p 3000:3000 -p 3001:3001 -p 50051:50051 -p 9080:9080 \
-v $(pwd)/examples:/app/examples:ro \
-e MOCKFORGE_ADMIN_ENABLED=true \
-e MOCKFORGE_HTTP_OPENAPI_SPEC=examples/openapi-demo.json \
mockforge
See DOCKER.md for comprehensive Docker documentation and deployment options.
MockForge now supports generating client code for multiple frontend frameworks from your OpenAPI specifications. This enables seamless integration with your existing applications and reduces development time.
# Generate React client
mockforge client generate --spec examples/user-management-api.json --framework react --output ./generated
# Generate Vue client
mockforge client generate --spec examples/user-management-api.json --framework vue --output ./generated
# Generate Angular client
mockforge client generate --spec examples/user-management-api.json --framework angular --output ./generated
# Generate Svelte client
mockforge client generate --spec examples/user-management-api.json --framework svelte --output ./generated
Complete example applications are available in the examples/ directory:
react-demo/ - React application with generated hooksvue-demo/ - Vue 3 application with generated composablesangular-demo/ - Angular 17 application with generated servicessvelte-demo/ - SvelteKit application with generated storesEach demo includes:
All generated clients include:
// React
const { data: users, loading, error } = useGetUsers();
// Vue
const { data, loading, error } = useGetUsers();
// Angular
this.userService.getUsers().subscribe({
next: (users) => this.users = users,
error: (error) => this.error = error
});
// Svelte
const usersStore = createGetUsersStore();
usersStore.subscribe(state => {
users = state.data;
loading = state.loading;
});
See examples/README.md for detailed documentation on all framework examples.
# Build the project
cargo build
# Start all mock servers with Admin UI (separate port)
cargo run -p mockforge-cli -- serve --admin --admin-port 9080
# Start with custom configuration
cargo run -p mockforge-cli -- serve --config config.yaml --admin
# Generate test data
cargo run -p mockforge-cli -- data template user --rows 50 --output users.json
# Start Admin UI only (standalone server)
cargo run -p mockforge-cli -- admin --port 9080
# Start workspace synchronization daemon
cargo run -p mockforge-cli -- sync start --directory ./workspace-sync
# Access Admin Interface
- Standalone Admin: http://localhost:9080/
- Admin embedded under HTTP (when configured): http://localhost:3000/admin/
# Quick development setup with environment variables
MOCKFORGE_ADMIN_ENABLED=true MOCKFORGE_HTTP_PORT=3000 cargo run -p mockforge-cli -- serve
MockForge supports AI-powered mock generation for intelligent, evolving data. Perfect for realistic testing!
# Install Ollama (one-time setup)
curl https://ollama.ai/install.sh | sh
ollama pull llama2
# Start MockForge with AI enabled
cargo run -p mockforge-cli -- serve \
--ai-enabled \
--rag-provider ollama \
--rag-model llama2 \
--config examples/ai/intelligent-customer-api.yaml
# Start with OpenAI
export MOCKFORGE_RAG_API_KEY=sk-your-api-key
cargo run -p mockforge-cli -- serve \
--ai-enabled \
--rag-provider openai \
--rag-model gpt-3.5-turbo \
--config examples/ai/intelligent-customer-api.yaml
# Test intelligent mock generation
cargo run -p mockforge-cli -- test-ai intelligent-mock \
--prompt "Generate realistic customer data for a SaaS platform" \
--rag-provider ollama
# Test data drift simulation
cargo run -p mockforge-cli -- test-ai drift \
--initial-data examples/order.json \
--iterations 10
# Test AI event stream generation
cargo run -p mockforge-cli -- test-ai event-stream \
--narrative "Simulate 5 minutes of live stock market data" \
--event-count 20 \
--rag-provider ollama
responses:
- name: "AI Customer Response"
status_code: 200
intelligent:
mode: intelligent
prompt: "Generate realistic customer data for a retail SaaS API"
schema:
type: object
properties:
id: { type: string }
name: { type: string }
email: { type: string }
drift:
enabled: true
request_based: true
rules:
- field: tier
strategy: state_machine
states: [bronze, silver, gold, platinum]
π Learn More: See docs/AI_DRIVEN_MOCKING.md for complete AI features documentation.
curl http://localhost:3000/ping
MockForge includes a fully functional SMTP server for testing email workflows:
# Start SMTP server
mockforge serve --smtp --smtp-port 1025
# Send test email with Python
python3 << EOF
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = 'Test Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.set_content('This is a test email.')
with smtplib.SMTP('localhost', 1025) as server:
server.send_message(msg)
print("Email sent successfully!")
EOF
# Or use command-line tools
swaks --to recipient@example.com \
--from sender@example.com \
--server localhost:1025 \
--body "Test email"
smtp:
enabled: true
port: 1025
hostname: "mockforge-smtp"
fixtures_dir: "./fixtures/smtp"
enable_mailbox: true
max_mailbox_messages: 1000
See SMTP documentation for complete guide.
MockForge supports scripted WebSocket interactions with template expansion and conditional responses.
# Set the replay file environment variable
export MOCKFORGE_WS_REPLAY_FILE=examples/ws-demo.jsonl
# Start the WebSocket server
cargo run -p mockforge-cli -- serve --ws-port 3001
Using Node.js:
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:3001/ws');
ws.on('open', () => {
console.log('Connected! Sending CLIENT_READY...');
ws.send('CLIENT_READY');
});
ws.on('message', (data) => {
console.log('Received:', data.toString());
// Auto-respond to expected prompts
if (data.toString().includes('ACK')) {
ws.send('ACK');
}
if (data.toString().includes('CONFIRMED')) {
ws.send('CONFIRMED');
}
});
ws.on('close', () => console.log('Connection closed'));
Using websocat:
websocat ws://localhost:3001/ws
# Then type: CLIENT_READY
# The server will respond with scripted messages
Using wscat:
wscat -c ws://localhost:3001/ws
# Then type: CLIENT_READY
Browser Console:
const ws = new WebSocket('ws://localhost:3001/ws');
ws.onopen = () => ws.send('CLIENT_READY');
ws.onmessage = (event) => console.log('Received:', event.data);
MockForge supports JSONPath queries for sophisticated WebSocket message matching:
[
{"waitFor": "^CLIENT_READY$", "text": "Welcome!"},
{"waitFor": "$.type", "text": "Type received"},
{"waitFor": "$.user.id", "text": "User authenticated"},
{"waitFor": "$.order.status", "text": "Order status updated"}
]
JSONPath Examples:
$.type - Wait for any message with a type property$.user.id - Wait for messages with user ID$.order.status - Wait for order status updates$.items[0].name - Wait for first item nameJSON Message Testing:
const ws = new WebSocket('ws://localhost:3001/ws');
// Send JSON messages that match JSONPath patterns
ws.onopen = () => {
ws.send(JSON.stringify({type: 'login'})); // Matches $.type
ws.send(JSON.stringify({user: {id: '123'}})); // Matches $.user.id
ws.send(JSON.stringify({order: {status: 'paid'}})); // Matches $.order.status
};
ws.onmessage = (event) => console.log('Response:', event.data);
See examples/README-websocket-jsonpath.md for complete documentation.
WebSocket replay files use JSON Lines format with the following structure:
{"ts":0,"dir":"out","text":"HELLO {{uuid}}","waitFor":"^CLIENT_READY$"}
{"ts":10,"dir":"out","text":"{\\"type\\":\\"welcome\\",\\"sessionId\\":\\"{{uuid}}\\"}"}
{"ts":20,"dir":"out","text":"{\\"type\\":\\"data\\",\\"value\\":\\"{{randInt 1 100}}\\"}","waitFor":"^ACK$"}
ts: Timestamp in milliseconds for message timingdir: Direction ("in" for received, "out" for sent)text: Message content (supports template expansion)waitFor: Optional regex pattern to wait for before sendingWebSocket messages support the same template expansion as HTTP responses:
{{uuid}} β Random UUID{{now}} β Current timestamp{{now+1h}} β Future timestamp{{randInt 1 100}} β Random integergrpcurl -plaintext -proto crates/mockforge-grpc/proto/gretter.proto -d '{"name":"Ray"}' localhost:50051 mockforge.greeter.Greeter/SayHello
MockForge now includes an advanced HTTP Bridge that automatically converts gRPC services to REST APIs, eliminating the need for separate gRPC and HTTP implementations.
.proto files and creates REST endpoints for all gRPC services# Start gRPC server with HTTP bridge
cargo run -p mockforge-cli -- serve --config config.dev.yaml --admin
The bridge will automatically:
/api/{service}/{method}/api/docs/api/healthgRPC Service:
service UserService {
rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
rpc GetUser(GetUserRequest) returns (GetUserResponse);
}
HTTP Bridge Endpoints:
# Create user (POST)
curl -X POST http://localhost:3000/api/userservice/createuser \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}'
# Get user (POST - gRPC semantics)
curl -X POST http://localhost:3000/api/userservice/getuser \
-H "Content-Type: application/json" \
-d '{"user_id": "123"}'
Response:
{
"success": true,
"data": {
"user_id": "123",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2025-01-01T00:00:00Z"
},
"error": null,
"metadata": {
"x-mockforge-service": "userservice",
"x-mockforge-method": "createuser"
}
}
Enable the HTTP bridge by modifying your config:
grpc:
dynamic:
enabled: true
proto_dir: "proto" # Directory containing .proto files
enable_reflection: true # Enable gRPC reflection
http_bridge:
enabled: true # Enable HTTP bridge
base_path: "/api" # Base path for REST endpoints
enable_cors: true # Enable CORS
timeout_seconds: 30 # Request timeout
Or via environment variables:
export MOCKFORGE_GRPC_DYNAMIC_ENABLED=true
export MOCKFORGE_GRPC_HTTP_BRIDGE_ENABLED=true
export MOCKFORGE_GRPC_PROTO_DIR=proto
GET /api/health - Health checkGET /api/stats - Request statistics and metricsGET /api/services - List available gRPC servicesGET /api/docs - OpenAPI 3.0 documentation/api/{service}/{method} - Automatically generated REST endpointsFor gRPC streaming methods, the bridge provides:
# Server streaming endpoint
curl -N http://localhost:3000/api/chat/streammessages \
-H "Content-Type: application/json" \
-d '{"topic": "tech"}'
Returns server-sent events:
data: {"event_type":"message","data":{"text":"Hello!"},"metadata":{}}
event: message
data: {"event_type":"message","data":{"text":"How can I help?"},"metadata":{}}
event: message
The bridge auto-generates comprehensive OpenAPI documentation:
# Access interactive API docs
open http://localhost:3000/api/docs
# Get OpenAPI JSON spec
curl http://localhost:3000/api/docs
Features:
MockForge provides first-class support for async and event-driven protocols, enabling comprehensive testing of message-driven architectures, pub/sub systems, and event-driven microservices.
# Start all protocols (Kafka, MQTT, AMQP enabled by default)
mockforge serve
# Override ports
mockforge serve --kafka-port 9092 --mqtt-port 1883 --amqp-port 5672
# Or use dedicated commands
mockforge kafka serve --port 9092
mockforge mqtt publish --topic "sensors/temp" --payload '{"temp": 22.5}'
mockforge amqp serve --port 5672
Features:
Example: Using with Python
from confluent_kafka import Producer, Consumer
# Producer
producer = Producer({'bootstrap.servers': 'localhost:9092'})
producer.produce('orders', key='order-123', value='{"total": 99.99}')
producer.flush()
# Consumer
consumer = Consumer({
'bootstrap.servers': 'localhost:9092',
'group.id': 'my-group',
'auto.offset.reset': 'earliest'
})
consumer.subscribe(['orders'])
Fixture-Based Testing:
Create fixtures/kafka/orders.yaml:
- identifier: "order-created"
topic: "orders.created"
key_pattern: "order-{{uuid}}"
value_template:
order_id: "{{uuid}}"
customer_id: "customer-{{faker.int 1000 9999}}"
total: "{{faker.float 10.0 1000.0 | round 2}}"
status: "pending"
created_at: "{{now}}"
auto_produce:
enabled: true
rate_per_second: 10 # Generate 10 orders/second
Features:
+, #)Example: Using with JavaScript
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://localhost:1883');
// Publish
client.publish('sensors/temperature', JSON.stringify({ temp: 22.5 }), { qos: 1 });
// Subscribe
client.subscribe('sensors/#');
client.on('message', (topic, message) => {
console.log(`${topic}: ${message.toString()}`);
});
Features:
Example: Using with Python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Declare and bind
channel.exchange_declare(exchange='orders', exchange_type='topic')
channel.queue_declare(queue='order.processing')
channel.queue_bind(exchange='orders', queue='order.processing', routing_key='order.created')
# Publish
channel.basic_publish(exchange='orders', routing_key='order.created',
body='{"order_id": "123"}')
Auto-Production:
auto_produce:
enabled: true
rate_per_second: 100
duration_seconds: 0 # 0 = infinite
Template Engine:
value_template:
id: "{{uuid}}"
customer_name: "{{faker.name}}"
amount: "{{faker.float 10.0 1000.0 | round 2}}"
created_at: "{{now}}"
status: "{{faker.randomChoice ['pending', 'processing', 'completed']}}"
Metrics & Monitoring:
curl http://localhost:9080/__mockforge/metrics
# Example metrics
kafka_messages_produced_total 12345
mqtt_messages_published_total 5678
amqp_messages_published_total 9012
kafka:
enabled: true
port: 9092
auto_create_topics: true
default_partitions: 3
fixtures_dir: "./fixtures/kafka"
mqtt:
enabled: true
port: 1883
max_connections: 1000
keep_alive_secs: 60
fixtures_dir: "./fixtures/mqtt"
amqp:
enabled: true
port: 5672
max_connections: 1000
heartbeat_interval: 60
fixtures_dir: "./fixtures/amqp"
π For detailed documentation, see ASYNC_PROTOCOLS.md
MockForge includes powerful synthetic data generation capabilities:
# Generate user data using built-in templates
cargo run -p mockforge-cli -- data template user --rows 100 --output users.json
# Generate product data
cargo run -p mockforge-cli -- data template product --rows 50 --format csv --output products.csv
# Generate data from JSON schema
cargo run -p mockforge-cli -- data schema schema.json --rows 200 --output custom_data.json
# Enable RAG mode for enhanced data generation
cargo run -p mockforge-cli -- data template user --rows 100 --rag --output users.json
echo -e '{"name":"one"}\n{"name":"two"}' | grpcurl -plaintext -proto crates/mockforge-grpc/proto/gretter.proto -d @ localhost:50051 mockforge.greeter.Greeter/SayHelloClientStream
echo -e '{"name":"first"}\n{"name":"second"}' | grpcurl -plaintext -proto crates/mockforge-grpc/proto/gretter.proto -d @ localhost:50051 mockforge.greeter.Greeter/Chat

MockForge ships a built-in Admin UI that can run as either:
--admin is used): http://localhost:9080/.http://localhost:3000/admin/ when admin.mount_path: "/admin" is configured.The Admin UI provides:
Note: Role-based authentication (Admin/Viewer access control) is planned for v1.1. The frontend UI components are ready, but backend JWT/OAuth authentication is not yet implemented in v1.0. The Admin UI is currently accessible without authentication.
You can embed the Admin UI under the HTTP server instead of running it on a separate port. This is handy when you want a single endpoint to expose mocks and admin controls.
admin:
enabled: true
mount_path: "/admin"
export MOCKFORGE_ADMIN_ENABLED=true
export MOCKFORGE_ADMIN_MOUNT_PATH=/admin
cargo run -p mockforge-cli -- serve
Notes:
/admin/admin.css).mount_path (or unset env) and run with --admin --admin-port 9080.You can control how the Admin UI runs via flags on serve:
# Force embedded mode (default mount at /admin)
cargo run -p mockforge-cli -- serve --admin-embed
# Embedded with explicit mount
cargo run -p mockforge-cli -- serve --admin-embed --admin-mount-path /tools
# Force standalone mode on port 9080 (overrides embed)
cargo run -p mockforge-cli -- serve --admin --admin-standalone --admin-port 9080
# Disable Admin APIs (UI loads but __mockforge/* endpoints are absent)
cargo run -p mockforge-cli -- serve --admin-embed --disable-admin-api
# Equivalent env-based control
export MOCKFORGE_ADMIN_ENABLED=true
export MOCKFORGE_ADMIN_MOUNT_PATH=/admin
export MOCKFORGE_ADMIN_API_ENABLED=false
cargo run -p mockforge-cli -- serve
Admin API endpoints are namespaced under __mockforge:
GET /__mockforge/dashboardGET /__mockforge/healthGET /__mockforge/logsGET /__mockforge/metricsGET /__mockforge/fixturesPOST /__mockforge/config/*/admin):
GET /admin/__mockforge/dashboardGET /admin/__mockforge/healthMockForge supports flexible configuration through YAML or JSON files:
# Initialize a new configuration
mockforge init my-project
# Validate your configuration
mockforge config validate
# Use a configuration file
cargo run -p mockforge-cli -- serve --config my-config.yaml
π Complete Configuration Template - Fully documented template with all available options
Override any configuration setting with environment variables:
# Server ports
export MOCKFORGE_HTTP_PORT=9080
export MOCKFORGE_WS_PORT=8081
export MOCKFORGE_GRPC_PORT=9090
export MOCKFORGE_ADMIN_PORT=9091
# Enable features
export MOCKFORGE_ADMIN_ENABLED=true
export MOCKFORGE_LATENCY_ENABLED=true
# Logging
export MOCKFORGE_LOG_LEVEL=debug
# Clone the repository
git clone https://github.com/SaaSy-Solutions/mockforge.git
cd mockforge
# Set up development environment (installs all tools and hooks)
make setup
# Build the project
make build
# Run all tests
make test
# Run all quality checks
make check-all
# Start development mode with file watching
make dev
# Format code
make fmt
# Run lints
make clippy
# Run security audit
make audit
# Generate documentation
make doc
# Build user docs
make book
mockforge/
βββ crates/ # Workspace crates
β βββ mockforge-cli/ # Command-line interface
β βββ mockforge-core/ # Shared logic (routing, validation, latency, proxy)
β βββ mockforge-http/ # HTTP mocking library
β βββ mockforge-ws/ # WebSocket mocking library
β βββ mockforge-grpc/ # gRPC mocking library
β βββ mockforge-data/ # Synthetic data generation (faker + RAG)
β βββ mockforge-ui/ # Admin UI (Axum routes + static assets)
βββ config.example.yaml # Configuration example
βββ docs/ # Project documentation
βββ book/ # mdBook documentation
βββ examples/ # Example configurations and test files
βββ tools/ # Development tools
βββ scripts/ # Setup and utility scripts
βββ .github/ # GitHub Actions and templates
βββ tools/ # Development utilities
We welcome contributions! Please see our Contributing Guide for details.
This project uses automated releases with cargo-release:
# Patch release (bug fixes)
make release-patch
# Minor release (new features)
make release-minor
# Major release (breaking changes)
make release-major
Challenge: A fintech company needed to develop and test 15+ microservices that communicate via gRPC, REST, and WebSocket protocols. Waiting for all services to be ready blocked parallel development.
Solution: MockForge provided:
Results:
Challenge: An e-commerce platform integrated with 8 external payment, shipping, and inventory APIs. Testing was expensive, slow, and unpredictable due to rate limits and sandbox limitations.
Solution: MockForge enabled:
Results:
Challenge: A mobile team needed to test iOS and Android apps against a backend API that was constantly evolving. The backend team couldn't provide stable test environments.
Solution: MockForge provided:
Results:
Challenge: A healthcare company was migrating from a monolithic SOAP API to microservices-based REST APIs. They needed to run both systems in parallel during the 18-month transition.
Solution: MockForge acted as:
Results:
Challenge: A SaaS platform needed to performance test their client application under various backend conditions (slow responses, partial failures, high load).
Solution: MockForge delivered:
Results:
MockForge includes comprehensive performance benchmarks using Criterion.rs to measure and track performance across releases.
Template Rendering
{{name}}{{user.address.city}}{{#each items}}JSON Schema Validation
OpenAPI Spec Parsing
Data Generation
Memory Profiling
# Run all benchmarks
cargo bench
# Run specific benchmark suite
cargo bench --bench core_benchmarks
# Run benchmarks with specific filter
cargo bench template
# Generate detailed HTML reports
cargo bench -- --save-baseline main
Typical performance metrics on modern hardware (AMD Ryzen 9 / Intel i9):
| Operation | Throughput | Latency |
|---|---|---|
| Simple template rendering | ~500K ops/sec | ~2 Β΅s |
| Complex template rendering | ~100K ops/sec | ~10 Β΅s |
| JSON schema validation (simple) | ~1M ops/sec | ~1 Β΅s |
| JSON schema validation (complex) | ~200K ops/sec | ~5 Β΅s |
| OpenAPI spec parsing (small) | ~10K ops/sec | ~100 Β΅s |
| OpenAPI spec parsing (large) | ~500 ops/sec | ~2 ms |
| Data generation (single record) | ~50K ops/sec | ~20 Β΅s |
Note: Results vary based on hardware, spec complexity, and system load. Run benchmarks on your target hardware for accurate metrics.
Benchmarks are run automatically in CI/CD:
View the latest benchmark results in our GitHub Actions.
π For detailed performance characteristics and current benchmark results, see Performance Benchmarks Documentation.
| Issue | Quick Fix |
|---|---|
| Server won't start | lsof -i :3000 β mockforge serve --http-port 3001 |
| Template variables not working | mockforge serve --response-template-expand |
| Validation too strict | mockforge serve --validation warn |
| Admin UI not loading | mockforge serve --admin --admin-port 9080 |
| Docker port conflicts | docker run -p 3001:3000 mockforge |
| Docker permission issues | sudo chown -R 1000:1000 fixtures/ (Linux) |
See the complete troubleshooting guide for detailed solutions.
When reporting issues, please include:
mockforge --version)RUST_LOG=debug mockforge serve)Licensed under either of:
at your option.
You can control request/response validation via CLI, environment, or config.
Environment:
MOCKFORGE_REQUEST_VALIDATION=off|warn|enforce (default: enforce)
MOCKFORGE_AGGREGATE_ERRORS=true|false (default: true)
MOCKFORGE_RESPONSE_VALIDATION=true|false (default: false)
MOCKFORGE_RESPONSE_TEMPLATE_EXPAND=true|false (default: false)
example bodies) expand tokens:
{{uuid}} β random UUID v4{{now}} β RFC3339 timestamp{{nowΒ±And|Nh|Nm|Ns}} β timestamp offset by days/hours/minutes/seconds, e.g., {{now+2h}}, {{now-30m}}{{rand.int}} β random integer{{rand.float}} β random float{{randInt 10 99}}, {{rand.int -5 5}}{{faker.uuid}}, {{faker.email}}, {{faker.name}}, {{faker.address}}, {{faker.phone}}, {{faker.company}}, {{faker.url}}, {{faker.ip}}, {{faker.color}}, {{faker.word}}, {{faker.sentence}}, {{faker.paragraph}}MOCKFORGE_FAKE_TOKENS=false to disable faker token expansion (uuid/now/rand tokens still expand).MOCKFORGE_VALIDATION_STATUS=400|422 (default: 400)
CLI (serve):
--validation off|warn|enforce--aggregate-errors--validate-responsesConfig (config.yaml):
http:
request_validation: "enforce" # off|warn|enforce
aggregate_validation_errors: true
validate_responses: false
skip_admin_validation: true
validation_overrides:
"POST /users/{id}": "warn"
"GET /internal/health": "off"
When aggregation is enabled, 400 responses include both a flat errors list and a details array with structured items:
{
"error": "request validation failed",
"details": [
{ "path": "query.q", "code": "type", "message": "query.q: expected number, got \"abc\"", "value": "abc" }
]
}