Mmock is an HTTP mocking application for testing and fast prototyping
Mmock is a testing and fast prototyping tool for developers:
Easy and fast HTTP mock server.
Built with Go - Mmock runs without installation on multiple platforms.
Mock definition file example:
{
"request": {
"method": "GET",
"path": "/hello/*"
},
"response": {
"statusCode": 200,
"headers": {
"Content-Type":["application/json"]
},
"body": "{\"hello\": \"{{request.query.name}}, my name is {{fake.FirstName}}\"}"
}
}
Or
---
request:
method: GET
path: "/hello/*"
response:
statusCode: 200
headers:
Content-Type:
- application/json
body: '{"hello": "{{request.query.name}}, my name is {{fake.FirstName}}"}'
You can see more complex examples here.
Either:
Run it from Docker using the provided Dockerfile
or from Docker Hub
docker image pull jordimartin/mmock
docker run -v YOUR_ABS_PATH:/config -p 8082:8082 -p 8083:8083 jordimartin/mmock
Or run mmock locally from the command line. (Requires Go 1.8 at least)
go get github.com/jmartin82/mmock/...
mmock -h
To configure Mmock, use command line flags described in help.
Usage of ./mmock:
-config-path string
Mocks definition folder (default "execution_pathconfig")
-console
Console enabled (true/false) (default true)
-console-ip string
Console server IP (default "public_ip")
-console-port int
Console server Port (default 8082)
-request-storage-capacity int
Request storage capacity (0 = infinite) (default 100)
-results-per-page uint
Number of results per page (default 25)
-server-ip string
Mock server IP (default "public_ip")
-server-port int
Mock server Port (default 8083)
-server-statistics
Mock server sends anonymous statistics (default true)
-server-tls-port int
Mock server TLS Port (default 8084)
-tls-path string
TLS config folder (server.crt and server.key should be inside) (default "execution_path/tls")
The default logging level is INFO, but you can change it by setting the environment variable LOG_LEVEL to one of the following:
Mock definition:
{
"description": "Some text that describes the intended usage of the current configuration",
"request": {
"host": "example.com",
"method": "GET|POST|PUT|PATCH|...",
"path": "/your/path/:variable",
"queryStringParameters": {
"name": ["value"],
"name": ["value", "value"]
},
"headers": {
"name": ["value"]
},
"cookies": {
"name": "value"
},
"body": "Expected Body"
},
"response": {
"statusCode": "int (2xx,4xx,5xx,xxx)",
"headers": {
"name": ["value"]
},
"cookies": {
"name": "value"
},
"body": "Response body"
},
"callback": {
"method": "GET|POST|PUT|PATCH|...",
"url": "http://your-callback/",
"delay": "string (response delay in s,ms)",
"headers": {
"name": ["value"]
},
"body": "Response body"
},
"control": {
"scenario": {
"name": "string (scenario name)",
"requiredState": [
"not_started (default state)",
"another_state_name"
],
"newState": "new_stat_neme"
},
"proxyBaseURL": "string (original URL endpoint)",
"delay": "string (response delay in s,ms)",
"crazy": "bool (return random 5xx)",
"priority": "int (matching priority)",
"webHookURL" : "string (URL endpoint)"
}
}
A core feature of Mmock is the ability to return canned HTTP responses for requests matching criteria.
In case of queryStringParameters, headers and cookies, the request can be matched only if all defined keys in mock will be present with the exact or glob value.
Glob matching is available for:
Query strings and headers support also global matches (*) in the header/parameter name. For example:
"headers": {
"Custom-Header-*": [
"partial val*"
]
}
Regexp matching is available for:
See https://pkg.go.dev/regexp/syntax for regexp syntax
This is used to have mmock make an API request after receiving the mocked request.
You can use variable data in response. The variables will be defined as tags like this {{nameVar}}
Request data: Use them if you want to add request data in your response.
You can extract information from the request body too, using a dot notation path:
application/json
, application/xml
and application/x-www-form-urlencoded
requests)application/json
, application/xml
requests)Quick overview of the path syntax available to extract values form the request: https://github.com/tidwall/gjson#path-syntax
You can also use "regex" and "concat" commands to complement GJson query:
application/json
, application/xml
requests)application/json
, application/xml
requests)application/json
, application/xml
requests)Example request data:
{
"email": "[email protected]",
"age": 4,
"uuid":"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
"discarded": "do not return"
}
Example config mock data:
{
"email": "{{request.body.email.regex((\@gmail.com))}}",
"age": {{request.body.age}},
"uuid": "{{request.body.uuid.regex(\b([0-9a-zA-Z]{4})\b).concat(-878787)}}",
"discarded": "{{request.body.discarded.concat(, Please!)}}"
}
Example response data:
{
"email": "",
"age": 4,
"uuid": "2307-878787",
"discarded": "do not return, Please!"
}
External streams: Perfect for embedding big payloads or getting data from another service.
Fake data: Useful to provide a more rich and random response.
With the scenarios you can simulate a stateful service. It's useful to create test doubles.
A scenario is a state machine and you can assign an arbitrarily state.
When mmock recieve a new request and there is an scenario defined in the matching mock, mmock checks if the mock is valid for the current state. Also a new scenario state can be set after the mock match.
By default all scenarios has the state "not_started" until some mock triggers a new one.
Example of REST services using scenarios:
+---------------------------------------------------------------------------------------------+
| |
| GET /user POST /user GET /user |
| StatusCode: 404 StatusCode: 201 StatusCode: 200 |
| |
| +-------------------------+ +---------------------------+ +-------------------------+ |
| | | | | | | |
| | requiredState:created +-> | requiredState:not_started +-> | requiredState: created | |
| | | | newState: created | | | |
| | | | | | | |
| +-------------------------+ +---------------------------+ +-------------------------+ |
| |
+---------------------------------------------------------------------------------------------+
Working examples here
MMock uses the Open API Specification (OAI, formerly known as Swagger) to describe its APIs. Our OAI specification schema is hosted at /swagger.json and serves as the canonical definition and comprehensive declaration of all available endpoints.
The OAI specification makes writing client applications easier by: auto-generating boilerplate code (like data object classes) and dealing with authentication and error handling.
You can find a comprehensive set of open tools for the OAI specification at: https://github.com/swagger-api.
The Mmock records the incoming requests in memory (last 100 by default). This makes it possible to verify that a request matching a specific pattern was received, and also to fetch the requests details.
Title : Get all requests.
URL : /api/request/all
Method : GET
Response Codes: Success (200 OK)
Title : Get all matched requests with any mock.
URL : /api/request/matched
Method : GET
Response Codes: Success (200 OK)
Title : Clean all recorded request.
URL : /api/request/reset
Method : GET
Response Codes: Success (200 OK)
Title : Reset all requests that match with an specific pattern.
URL : /api/request/reset_match
Method : POST
Data Params:
Like stubbing this call also uses the same DSL to filter and query requests.
{
"host": "example.com",
"method": "GET|POST|PUT|PATCH|... (Mandatory)",
"path": "/your/path/:variable (Mandatory)",
"queryStringParameters": {
"name": ["value"],
"name": ["value", "value"]
},
"headers": {
"name": ["value"]
},
"cookies": {
"name": "value"
},
"body": "Expected Body"
}
Response Codes: Success (200 OK)
Title : Get all non matched requests.
URL : /api/request/unmatched
Method : GET
Response Codes: Success (200 OK)
Title : Get all requests that match with an specific pattern.
URL : /api/request/verify
Method : POST
Data Params:
Like stubbing this call also uses the same DSL to filter and query requests.
{
"host": "example.com",
"method": "GET|POST|PUT|PATCH|... (Mandatory)",
"path": "/your/path/:variable (Mandatory)",
"queryStringParameters": {
"name": ["value"],
"name": ["value", "value"]
},
"headers": {
"name": ["value"]
},
"cookies": {
"name": "value"
},
"body": "Expected Body"
}
Response Codes: Success (200 OK)
Title : Get all active scenarios.
URL : /api/scenarios
Method : GET
Response Codes: Success (200 OK)
Title : Clean all scenarios status and pause state.
URL : /api/scenarios/reset_all
Method : GET
Response Codes: Success (200 OK)
Title : Manually progress a scenario state machine to the given state.
URL : /api/scenarios/set/:scenario/:state
Method : PUT
Response Codes: Success (200 OK)
Title : Pause prevents all scenarios state machines from progressing to a new state.
URL : /api/scenarios/pause
Method : PUT
Response Codes: Success (200 OK)
Title : Allow scenarios state machines to continue.
URL : /api/scenarios/unpause
Method : PUT
Response Codes: Success (200 OK)
You can manage remotely your stub mappings whenever you need with this simple API:
Title : Get all mock definitions.
URL : /api/mapping
Method : GET
Response Codes: Success (200 OK)
Title : Create new mock definition.
URL : /api/mapping/:uri
Method : POST
Response Codes: Success (201 OK)
Title : Get mock definition.
URL : /api/mapping/:uri
Method : GET
Response Codes: Success (200 OK)
Title : Update mock definition.
URL : /api/mapping/:uri
Method : PUT
Response Codes: Success (200 OK)
Title : Delete mock definition.
URL : /api/mapping/:uri
Method : DELETE
Response Codes: Success (200 OK)
)
Also there is a real time endpoint available through WebSockets that broadcast all requests.
Title : Get all requests.
URL : /echo
All endpoints have the same output format:
[
{
"time": 1486563983,
"request": {
"host": "192.168.20.209",
"method": "GET",
"path": "/hello",
"queryStringParameters": {},
"headers": {
"Accept": [
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
]
},
"cookies": {},
"body": ""
},
"response": {
"statusCode": 200,
"headers": null,
"cookies": {
"visit": "true"
},
"body": "Hello world!"
},
"result": {
"match": true,
"errors": null
}
}
]
Mmock is collecting anonymous statistics about the usage of the following actions:
Source code: /statistics/statistics.go
requests.mock
: Mocks served (number)requests.console
: Web console usage (number)requests.verify
: Verify requests (number)feature.scenario
: Mocks with scenario feature served (number)feature.proxy
: Mocks with proxy feature served (number)You can always disable this behavior adding the following flag -server-statistics=false
As of version 3.0.0, Mmock is available as a Go module. Therefore a Go version capable of understanding /vN suffixed imports is required:
1.9.7+ 1.10.3+ 1.11+
If you make any changes, please run go fmt ./...
before submitting a pull request.
Copyright © 2016 - 2020, Jordi Martín (http://jordi.io)
Released under MIT license, see LICENSE for details.