Coder Social home page Coder Social logo

jmartin82 / mmock Goto Github PK

View Code? Open in Web Editor NEW
660.0 660.0 80.0 1.87 MB

Mmock is an HTTP mocking application for testing and fast prototyping

License: MIT License

Go 87.48% CSS 0.38% HTML 6.24% JavaScript 5.11% Makefile 0.38% Shell 0.15% Dockerfile 0.26%
golang http httpmock mock prototyping stubbing

mmock's People

Contributors

alfonsfoubert avatar colin-teamcmp avatar danhnguyen123 avatar daroot avatar dependabot[bot] avatar dmitriyminer avatar eslamabdelkader avatar estermaja-teamcmp avatar ggrebert avatar hmoragrega avatar inabajunmr avatar jaimelopez avatar jdietrich-tc avatar jmartin82 avatar jmartinmad avatar jmc-signaturit avatar joel-44 avatar lovromazgon avatar marclop avatar marcoreni avatar mavimo avatar mcintyre94 avatar mikesir87 avatar mrgleam avatar nekroze avatar radovskyb avatar rosspatil avatar rubencougil avatar spheromak avatar vtrifonov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mmock's Issues

Get `internal` packages back into public scope

Hi,

I'm thinking about integrating mmock in our testing and CI/CD framework and to launch the mmock server (dispatcher) in-process.

As far as I like the refactoring introduced in 97bd768 it prevents reusing the project in external code since the most relevant packages are internal.

Any chance to have these internal packages back in a public scope?

Cheers, steirico

Question: how can i define multiple values of one query parameter

---
request:
  method: "GET"
  path: "/v1/endpoint"
  queryStringParameters:
    param1:
      - "value1"
      - "value2"
response: ...

Log:
2022/05/13 22:21:49 Discarding mock: get_something.yaml[0] Reason: Query string not match. Actual: param1: value1, Expected: param1: value1, param1: value2

Getting a timeout

docker run -v $HOME/desktop/sandbox/mmock/config -p 8082:8082 -p 8083:8083 jordimartin/mmock

Above is the line I'm using to launch mmock with the config files provided in this repo for testing. This is what I'm seeing when it is launched:

MMock v 2.0.2

		.---. .---.
               :     : o   :    me want request!
           _..-:   o :     :-.._    /
       .-''  '  `---' `---' "   ``-.
     .'   "   '  "  .    "  . '  "  `.
    :   '.---.,,.,...,.,.,.,..---.  ' ;
    `. " `.                     .' " .'
     `.  '`.                   .' ' .'
      `.    `-._           _.-' "  .'  .----.
        `. "    '"--...--"'  . ' .'  .'  o   `.
        .'`-._'    " .     " _.-'`. :       o  :
      .'      ```--.....--'''    ' `:_ o       :
    .'    "     '         "     "   ; `.;";";";'
   ;         '       "       '     . ; .' ; ; ;
  ;     '         '       '   "    .'      .-'
  '  "     "   '      "           "    _.-'
 

   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v3.2.1
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on 172.17.0.2:8082
2017/06/30 18:53:47 Getting external IP
2017/06/30 18:53:47 HTTP Server running at 172.17.0.2:8083
2017/06/30 18:53:47 HTTPS Server running at 172.17.0.2:8084
2017/06/30 18:53:47 Console running at 172.17.0.2:8082
2017/06/30 18:53:47 File monitor started

However, when I ping these endpoints I get a timeout/server unable to send response.

I know this is a vague question, but I'm unsure of where I went wrong (the absolute path is where the json files are and the correct docker image is being served), so any help would be appreciated. Thanks for a great api testing tool.

Multiple call to a fake function returns identical result

Hi there,

I noticed that calling, let's say, fake.Int(1000) multiple time gives me multiple time the exact same result in the context of a request, instead of different values. Is that the expected behaviour?

Example:

response:
  body: |
    {
      "number1": {{fake.Int(1000)}},
      "number2": {{fake.Int(1000)}},
       "number3": {{fake.Int(1000)}}
    }

I'm calling this route and get the result:

{
  "number1": 278,
  "number2": 278,
  "number3": 278
}

I would expect each call of the function to be randomized.

Match request header names and values with globs

It would be useful to have glob matching for headers also.

To match something having header with any value.

request:
  method: GET
  path: /echo
  headers:
    User-Agent:
      - "*"

Or partial value glob match:

request:
  method: GET
  path: /echo
  headers:
    User-Agent:
      - "curl/*"

It would also be useful to be able to glob match headers:

request:
  method: GET
  path: /echo
  headers:
    "Company-Custom-Header-*":
      - "*"

Multiple requests in single yaml file

YAML format can hold several documents in a single file; It would be convenient if the config file could hold multiple requests through

--- # First request
request: ...
response: ...
--- # Second request
request: ...
response: ...

It's more convenient to keep requests for a single test together in a single file.

Return 500 error instead 404 in case config errors

Hi there. Today I try to use mmoke first time. All going ok with first file. But my second file seems to be ignored, I get 404:

description: Use this for test if mock works
request:
    method: GET
    path: /test

response:
    statusCode: 200,
    body: I'm here!

Yes, I know - the comma after 200 must be deleted. All because the file was originally in json format, then I transform it to yaml & forgot to remove one comma. But can't see that mistake for a hour 🥲

Maybe better to return error with message file xxx can't be processed due to syntax error(s)? Or, as another (may be better) solution, add one more tab in web interface with accepted & ignored files.

PS. I used docker image, not the command line tool.

Feature Request: Support mocking an API that makes a HTTP request after some delay

I'm opening this issue as a feature request because it'd be really useful, would appreciate feedback on whether this could be an appropriate extension.

I'd like to use mmock to mock an API where the contract is:

  • Respond with HTTP 202 Accepted
  • At some point later, make an API request to a given URL

The specific use case here is around APIs orchestrated by AWS step functions. Without giving too much specific detail, part of the request to my API includes a 'token', and my API eventually calls some URL with its response and that token.

In order to integration test the entire step function, it'd be ideal to mock that API using mmock, so that when the step function calls it, it will after a short time receive a mocked response with the token it passed in.

The flow I'm proposing is something like:

Request (includes token=XYZ header) -> mmock
mmock -> Mocked 202 response
(some short delay)
Mocked response (includes token=XYZ) -> some URL


As a speculative design proposal, I'd like to be able to define a request like:

---
request:
  method: POST
  path: "/hello"
response:
  statusCode: 202
  headers:
    Content-Type:
    - application/json
  body: '{}'
callback:
  url: http://callbackApi:3000
  delay: 500 // (milliseconds)
  headers:
    Content-Type:
    - application/json
  body: '{"token": "{{request.header.token}}", "success": true, "response": "{{fake.Digits}}"}'

When mmock receives a POST to /hello, it'd respond with the 202, and then after 500ms make an API request to http://callbackApi:3000 with the headers + body I specified (which importantly can include request variables).

Do you think this would potentially be an appropriate use case to extend mmock to support?

Command not found mmock

Hello.
I tried to install mmock via docs

go get github.com/jmartin82/mmock
mmock -h

image

But on step 2 error
mmock command not found

How to install and launch mmock in Ubuntu 16.04?

image

Control delay in example JSON produces an error

Using /config/delay.json I encounter:

2020/05/01 07:07:16 Invalid mock format in: /config/delay.json Err: json: cannot unmarshal string into Go struct field Control.delay of type int

Updated:

    "control": {
        "delay": "400ms"
    }

to:

    "control": {
        "delay": 4
    }

Fixes the issue.

Unable to proxy request to https enpoint with selfsigned certificate

Any chances for help with that kind of error:

2017/02/28 16:15:24 http: panic serving 127.0.0.1:54820: Get https://path.abexample.net:44444/example/v1/test: x509: certificate is valid for *.ab*.net, not path.abexample.net
goroutine 67 [running]:
net/http.(*conn).serve.func1(0xc8202faa00)
	/usr/lib/go-1.6/src/net/http/server.go:1389 +0xc1
panic(0x8626c0, 0xc820325950)
	/usr/lib/go-1.6/src/runtime/panic.go:443 +0x4e9
github.com/jmartin82/mmock/proxy.(*Proxy).MakeRequest(0xc8204db980, 0x0, 0x0, 0xc8203c477d, 0x3, 0xc8203c83e0, 0x11, 0x0, 0x0, 0x0, ...)
	/home/test/go_path/src/github.com/jmartin82/mmock/proxy/proxy.go:31 +0x528
github.com/jmartin82/mmock/server.(*Dispatcher).ServeHTTP(0xc82001e6c0, 0x7fd062a1e1e0, 0xc82001a1a0, 0xc820308460)
	/home/test/go_path/src/github.com/jmartin82/mmock/server/dispatcher.go:67 +0x55f
net/http.serverHandler.ServeHTTP(0xc820092680, 0x7fd062a1e1e0, 0xc82001a1a0, 0xc820308460)
	/usr/lib/go-1.6/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc8202faa00)
	/usr/lib/go-1.6/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
	/usr/lib/go-1.6/src/net/http/server.go:2137 +0x44e

Is there a switch that i can use it to turn of certificate verification?

Invalid JSON is returned when using request.body."key" and multi-line strings

If I have a mock like this:

---
request:
  method: POST
  path: /test
response:
  statusCode: 201
  headers:
    Content-Type:
      - "application/json"
  body: >
    {
      "message": "{{request.body.message}}"
    }

And POST a JSON string like this:

{
  "message": "hello\nworld"
}

mmock will then return an invalid JSON string using a new-line instead of an escaped JSON string with \n. Unfortunately that is not valid JSON. E.g.

{
  "message": "hello
world"
}

When comparing json request bodies, comparison should be json specific

Currently when comparing bodies, json is treated as a simple string. As a result, parameter order or extra spacing can cause matching to fail. For example, the following request bodies should all match, but do not:

{"name":"bob","age":30"}
{
  "name":"bob",
  "age":30
}
{
  "age":30,
  "name":"bob"
}
{
  "name": "bob",
  "age":30
}

Password protected TLS key file

I want to run mmock (in a container) using a custom cert but the .key file needs to be encrypted.

How can I specify the key password to mmock?

Typo in mmock/config/crud/users-get.json

typo in

"body": "{\"id\":\"{{request.path.userid}}\",\"name\":\"Leanne Graham\",\"username\":\"Bret\",\"email\": \"[email protected]\",\"address\":{\"street\": \"Kulas Light\",\"suite\": \"Apt. 556\",\"city\": \"Gwenborough\",\"zipcode\": \"92998-3874\"}}}"

Must be:
"body": "{"id":"{{request.path.userid}}","name":"Leanne Graham","username":"Bret","email": "[email protected]","address":{"street": "Kulas Light","suite": "Apt. 556","city": "Gwenborough","zipcode": "92998-3874"}}"

Remove 1 brace in the end

Mapping API set incorrect control delay value

Hi,

I'm running the currently latest version (3.1.5) of MMock from Docker hub and trying to add a mock template using the mapping API. The endpoint returns 201 created and I can see that the template has been added to the config folder but the mock is not shown in the Web Console and when I inspect the logs I see that the value for the delay property is incorrect.

Example

curl -i -X POST -H "Content-Type:application/json" -d "{\"request\": { \"method\": \"GET\", \"path\": \"/\" }, \"response\": { \"statusCode\": 200, \"body\": \"{}\" }}" "http://localhost:8082/api/mapping/test.json"

Response

HTTP/1.1 201 Created
Content-Type: application/json; charset=UTF-8
Date: Mon, 13 Mar 2023 10:43:05 GMT
Content-Length: 21

{"result":"created"}

Logs

2023/03/13 10:43:05 Invalid mock format in: /config/test.json Err: invalid value for delay, got: map[string]interface {}
2023/03/13 10:43:05 Error invalid value for delay, got: map[string]interface {}. Loading config: /test.json

Template

{
  "URI": "",
  "description": "",
  "request": {
    "scheme": "",
    "host": "",
    "port": "",
    "method": "GET",
    "path": "/",
    "queryStringParameters": null,
    "fragment": "",
    "headers": null,
    "cookies": null,
    "body": ""
  },
  "response": {
    "statusCode": 200,
    "headers": null,
    "cookies": null,
    "body": "{}"
  },
  "callback": {
    "delay": {
      "Duration": 0
    },
    "method": "",
    "url": "",
    "headers": null,
    "cookies": null,
    "body": "",
    "timeout": {
      "Duration": 0
    }
  },
  "control": {
    "priority": 0,
    "delay": {
      "Duration": 0
    },
    "crazy": false,
    "scenario": {
      "name": "",
      "requiredState": null,
      "newState": ""
    },
    "proxyBaseURL": "",
    "webHookURL": ""
  }

Parallel execution

Hi, we have mmock deployed to a server. We use it to run our tests against it. When 2 test executions run in parallel, we started to see flakiness. This is basically because they share the same state and mess up with each other.

Do you have any suggestion to support parallel execution with state management?

Read json response from a file.

I have a file with large json. I would like to be able to read the file from file path instead of pasting the entire response json in config.

Mappings update API broken by v2.7.7

I have an integration test that uses mmock to update a mapping using PUT /api/mapping/:url. In v2.7.7 this test fails, because the update API doesn't seem to work any more for YAML files.

Repro example, using httpie

This is my config file, note it returns a statusCode 200

$ cat bulk-email.yml
---
    request:
      method: POST
      path: "/"
    response:
      statusCode: 200
      headers:
        Content-Type:
        - application/json
      body: '{}'

In one of my tests I want to modify it to return a statusCode 500

# start the Dockerfile with my config
$ docker run -v ${PWD}:/config -p 8082:8082 -p 8083:8083 jordimartin/mmock:v2.7.7
...
2020/03/19 10:15:22 Loading config file: /config/bulk-email.yml
...

# get my mapping using the API, all good
$ http ":8082/api/mapping/bulk-email.yml[0]"
HTTP/1.1 200 OK
Content-Length: 445
Content-Type: application/json; charset=UTF-8
Date: Thu, 19 Mar 2020 10:19:21 GMT

{
    "URI": "bulk-email.yml[0]",
    "control": {
        "crazy": false,
        "delay": 0,
        "priority": 0,
        "proxyBaseURL": "",
        "scenario": {
            "name": "",
            "newState": "",
            "requiredState": null
        },
        "webHookURL": ""
    },
    "description": "",
    "request": {
        "body": "",
        "cookies": null,
        "fragment": "",
        "headers": null,
        "host": "",
        "method": "POST",
        "path": "/",
        "port": "",
        "queryStringParameters": null,
        "scheme": ""
    },
    "response": {
        "body": "{}",
        "cookies": null,
        "headers": {
            "Content-Type": [
                "application/json"
            ]
        },
        "statusCode": 200
    }
}

# replace the statusCode from 200 to 500
$ http ":8082/api/mapping/bulk-email.yml[0]" -b | sed "s/200/500/" > newMapping

$ cat newMapping
{"URI":"bulk-email.yml[0]","description":"","request":{"scheme":"","host":"","port":"","method":"POST","path":"/","queryStringParameters":null,"fragment":"","headers":null,"cookies":null,"body":""},"response":{"statusCode":500,"headers":{"Content-Type":["application/json"]},"cookies":null,"body":"{}"},"control":{"priority":0,"delay":0,"crazy":false,"scenario":{"name":"","requiredState":null,"newState":""},"proxyBaseURL":"","webHookURL":""}}

$ http put ":8082/api/mapping/bulk-email.yml[0]" < newMapping
HTTP/1.1 200 OK
Content-Length: 21
Content-Type: application/json; charset=UTF-8
Date: Thu, 19 Mar 2020 10:26:02 GMT

{
    "result": "updated"
}

# get the mapping again
$ http ":8082/api/mapping/bulk-email.yml[0]" -b
{
    "URI": "bulk-email.yml[0]",
    "control": {
        "crazy": false,
        "delay": 0,
        "priority": 0,
        "proxyBaseURL": "",
        "scenario": {
            "name": "",
            "newState": "",
            "requiredState": null
        },
        "webHookURL": ""
    },
    "description": "",
    "request": {
        "body": "",
        "cookies": null,
        "fragment": "",
        "headers": null,
        "host": "",
        "method": "POST",
        "path": "/",
        "port": "",
        "queryStringParameters": null,
        "scheme": ""
    },
    "response": {
        "body": "{}",
        "cookies": null,
        "headers": {
            "Content-Type": [
                "application/json"
            ]
        },
        "statusCode": 200
    }
}

Note the statusCode in the final get has gone back to 200 - the 500 hasn't been saved correctly.

I think the issue is to do with the mapping from a url back to a file, with the new support for multiple routes in one yaml file. In the directory I've mapped in as a volume, I have a new file bulk-email.yml[0].

# my original file is untouched
$ cat bulk-email.yml
---
    request:
      method: POST
      path: "/"
    response:
      statusCode: 200
      headers:
        Content-Type:
        - application/json
      body: '{}'
 
# the new one has the statusCode                                                                                                                                                                                                $ cat "bulk-email.yml[0]"
{
  "URI": "bulk-email.yml[0]",
  "description": "",
  "request": {
    "scheme": "",
    "host": "",
    "port": "",
    "method": "POST",
    "path": "/",
    "queryStringParameters": null,
    "fragment": "",
    "headers": null,
    "cookies": null,
    "body": ""
  },
  "response": {
    "statusCode": 500,
    "headers": {
      "Content-Type": [
        "application/json"
      ]
    },
    "cookies": null,
    "body": "{}"
  },
  "control": {
    "priority": 0,
    "delay": 0,
    "crazy": false,
    "scenario": {
      "name": "",
      "requiredState": null,
      "newState": ""
    },
    "proxyBaseURL": "",
    "webHookURL": ""
  }
}%

So I have two files both controlling the same / route, one returning a statusCode 200 (the original one), and one a 500 (the intended replacement).

In v2.7.6 this use case worked, with the original bulk-email.yml file's contents being replaced with what's now put into bulk-email.yml[0]. The above repro works on v2.7.6, but the URL is :8082/api/mapping/bulk-email.yml, the [0] is a change required for v2.7.7

Add Proxy mode

Hello @jmartin82

It will be great feature - proxy mode

What I expect

run mmock in proxy mode
mmock -h --proxy-url=https://httpbin.org

write simple config file


request:
  path: /get/
  method: GET
response:
  statusCode: 202
  body: "It is from mmock"

Then, request to localhost:8083/get/
wil return mock response It is from mmock

request to localhost:8083/post/
will return real response from https://httpbin.org/post ( proxy-url + path )
something like this

{
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "application/json",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-US,en;q=0.9,ru;q=0.8",
    "Content-Length": "0",
    "Host": "httpbin.org",
    "Origin": "https://httpbin.org",
    "Referer": "https://httpbin.org/",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"
  },
  "json": null,
  "origin": "62.76.12.111, 62.76.12.111",
  "url": "https://httpbin.org/post"
}

Main goal
that dont need mock whole service ( REST API)
It is very useful for QA, for testing some new code that uses only one request. And developer needs to mmock response or statusCode or something else

Get all requested headers or a specific requested header

I would like to be able to just like the body be able to get requested headers in the response body.

For example:

request:
  method: GET
  path: /echo
response:
  statusCode: 200
  headers:
    Content-Type:
      - "application/json"
  body: >
    {
      "headers": "{{request.headers}}"
    }

Or to utilize specific headers:

request:
  method: GET
  path: /echo
response:
  statusCode: 200
  headers:
    Content-Type:
      - "application/json"
  body: >
    {
      "headers": "{{request.headers.User-Agent}}"
    }

This can be useful for various different testing purposes. My current use case is to check if a proxy adds/removes certain headers.

Question: Ordering with partial matches

I was wondering if there is a way to enforce the ordering of path matches.

I have the following configuration:
health-check.yaml

request:
  method: GET
  path: "/health-check"
response:
  statusCode: 200
  headers:
    Content-Type:
      - application/json
  body: |
    {
      "type": "health-check",
      "request.hostname": "{{request.hostname}}",
      "request.path": "{{request.path}}",
      "request.url": "{{request.url}}"
    }

And a fallback
default.yaml

---
request:
  method: GET
  path: "/*"
response:
  statusCode: 200
  headers:
    Content-Type:
      - application/json
  body: |
    {
      "request.hostname": "{{request.hostname}}",
      "request.path": "{{request.path}}",
      "request.url": "{{request.url}}"
    }

When I make a request:
curl http://0.0.0.0:8083/health-check

I would expect to get:

{
  "type": "health-check",
  "request.hostname": "0.0.0.0",
  "request.path": "/health-check",
  "request.url": "http://0.0.0.0:8083/health-check"
}

Instead - I randomly get the default response. Other times I get the health check response. The output from the docker container looks like this:

2022/03/14 09:04:43 New request: GET /health-check
2022/03/14 09:04:43 Definition match found: true. Name : health-check.yaml
2022/03/14 09:04:43 New request: GET /health-check
2022/03/14 09:04:43 Definition match found: true. Name : default.yaml
2

Is this expected? Is these an option to control the match ordering explicitly?

Disable default stat collection. Update README.

I noticed the CLI switch -server-statistics having a default value true. Though you are collecting anonymous stats, its a dark pattern to leave this switch enabled by default.

Any privacy concerned user will definitely be caught by surprise.

  1. There is no prominent mention in the README that stats are collected by mmock by default. Though there is a mention of statistics in the Contributors it doesn't convey that the tool collects anonymous stats.
  2. The CLI switches listed in the README don't feature this flag (perhaps not updated). I happened to find this switch only after running the tool with -h; after which I began to inspect rest of the code.

I know this is a very subjective issue. You are entitled to your PoV. But, my request to you is:

  1. Please disable this switch by default.
  2. Please display information in a very prominent location in the README about mmock's statistic collection, the actual data collected and what can the user do to enable/disable it.

Please let me know your views. Please also let me know if you'd like a PR for this change. TIA.

Reading an array of json as a body payload fails

When having the body payload as an array of json objects this error is happening:
"Err: json: cannot unmarshal array into Go value of type definition.Mock".

For example this would fail:

[{"name":"bob","age":35"} , {"name":"john","age":30"}]

v3.0.3 disappeared from Docker Hub

I'm using v3.1.5 now since it was fixed #140

But it looks like you removed v3.0.3 from docker hub that it was the one that I was using before, just letting you know

[Feature Request] Parse external streams (file.contents at least) for variable tags

Hi,
I think it would be useful to parse external files for variable tags.
This way it would be possible to have the response contents outside the mock definition files and still be able to populate it with fake data.

If this is already possible, I can't seem to find how to do it.

An example:

MMock definition:

request:
  method: GET
  path: "/"
response:
  statusCode: 200
  headers:
    Content-Type:
    - application/json
  body: "{{file.contents(test_payload.json)}}"

test_payload.json:

{"test": "{{fake.Brand}}"}

response:

{"test": "Zoozzy"}

Right now this is the response:

{"test": "{{fake.Brand}}"}

Match request without parameters

Hey 👋 First of all, thanks for all this amazing work that you're doing!

I'm using MMock for automated tests. So far it worked pretty well. But currently, I'm facing this issue:

I have two API calls that I need to mock:
/api/help_center
/api/help_center?link_id=1234

They return different content with link_id and without it. And I need to test both cases.

When I'm mocking like this:

request:
  method: GET
  path: "/api/help_center"
  queryStringParameters:
     link_id:
       - null

it doesn't match because clients are not sending nil/null as a parameter (most network libraries omit them if they are nil)

If I'm mocking without queryStringParameters then MMock simply uses one mock for ALL the requests no matter it contains link_id or not.

Can you please clarify if that's possible or not?

Variable `request.url` does not seem to work

Using:

request:
  method: GET
  path: /echo
response:
  statusCode: 200
  headers:
    Content-Type:
      - "application/json"
  body: >
    {
      "url": "{{request.url}}",
    }

I get:

$ curl -v -XPOST localhost:8083/echo
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8083 (#0)
> POST /echo HTTP/1.1
> Host: localhost:8083
> User-Agent: curl/7.54.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Thu, 10 Aug 2017 09:17:05 GMT
< Content-Length: 32
<
{
  "url": "{{request.url}}",
}
* Connection #0 to host localhost left intact

Incorrect platform issue

The latest images have been built with linux/arm64 where the previous images were built with linux/amd64. The latest version (v3.1) images never reach a healthy state in my environment, even when I specify the platform as linux/arm64.

Definition match not found

I am trying to run the samples provided. The docker image runs and the server respond but no matches are ever found. The console shows a 404 for even the /hello sample.

2019/10/17 19:02:57 Definition match found: false. Name :

I am running the call using:

docker run -v "C:\Users\lapellan\source\repos\mmock\config" -p 8082:8082 -p 8083:8083 jordimartin/mmock

mappings API needs some love

File definitions seem to be ok, but working with API is almost impossible. Simple example:

docker run --rm -p 8082:8082 -p 8083:8083 jordimartin/mmock`
> curl -d '{"request": {"method": "GET", "path": "/foo"}, "response": {"statusCode": 200}}' -X POST http://localhost:8082/api/mapping/foo 
> {"result":"created"}

Is it really created?

2020/07/02 22:38:08 Changes detected in mock definitions  DIRECTORY "config" WRITE [/config]
2020/07/02 22:38:08 Error Not valid config reader found. Loading config: /foo

I don't speak go to troubleshoot this but let's try something very naive:

> curl -d '{"request": {"method": "GET", "path": "/foo"}, "response": {"statusCode": 200}}' -X POST http://localhost:8082/api/mapping/foo.json
> {"result":"created"}

Logs:

2020/07/02 22:39:22 Loading config file: /config/foo.json
2020/07/02 22:39:22 Invalid mock format in: /config/foo.json Err: invalid value for delay, got: map[string]interface {}
2020/07/02 22:39:22 Error invalid value for delay, got: map[string]interface {}. Loading config: /foo.json

I don't think swagger.json even mentiones this endpoint BTW.

I thought you should know

mmock on Windows 10 host: View and Edit buttons in the Console Mapping Tab return 404 Not Found

MMock v 2.0.2
Windows 10
go version go1.10.1 windows/amd64

Hi,
First attempt with Mmock today, I have installed via go and created a config directory.

I run the command
mmock -config-path "mmock-config"

The console runs at 10.128.3.102:8082, but the View and Edit buttons in the mapping tab return 404:
GET http://10.128.3.102:8082/api/mapping//hello.json 404 (Not Found)

In the config directory I have the following basic sample:

hello.json

{
	"request": {
		"method": "GET",
		"path": "/hello/*"
	},
	"response": {
		"statusCode": 200,
		"headers": {
			"Content-Type":["application/json"]
		},
		"body": "{\"hello\": \"{{request.query.name}}, my name is {{fake.FirstName}}\"}"
	}
}

Additionally, where is the actual http server running by default, I'd assumed on a Port on 127.0.0.1 but the terminal output does not specify:

2018/04/24 17:34:11 Getting external IP
2018/04/24 17:34:11 File monitor started
2018/04/24 17:34:11 HTTP Server running at 10.128.3.102:8083
2018/04/24 17:34:11 HTTPS Server running at 10.128.3.102:8084
2018/04/24 17:34:11 Console running at 10.128.3.102:8082
2018/04/24 17:34:11 TLS certificates not found, impossible to start the TLS server.

I am genuinely excited about the possibilities for our team using your tool, hopefully with a little help perhaps I could do a little getting started guide for complete noobs like me (first time using Go too!)

mmock 404 errors

Question: is it possible to work with date/time?

I need to do some date/time manipulations in response, for example add/subtract time period to/from current datetime. And echo result in a specific format (such as Y-m-d H:i:s or D, d M Y H:i:s \G\M\T). Is it possible?

Feature Request - support parsing of `request.path`

Unlike the body for example, we can't do intensive parsing of the path. The .regex() and .concat() methods don't work on the path.

The :value part of the path also cannot be limited to specific values, so you can't simultaneously get a particular part of path while limiting which values match.

As an example, I have a config like this:

request:
  method: POST|PUT
  path: "/api/v1/method/create*/resource"

I want to match create*, so create or create-thing or create-other would be valid for that part of the path.

In the response, I want to reference that component, or part of it. I'd like to use regex maybe:

response:
  statusCode: 200
  headers:
    Content-Type:
      - application/json
  body: 'A request to create {{request.path.regex(/create-([^/]*)/)}} has been received.'

However that doesn't work.

If I instead do:

request:
  method: POST|PUT
  path: "/api/v1/method/:method/resource"

then I guess I can do:

response:
  statusCode: 200
  headers:
    Content-Type:
      - application/json
  body: 'A request to {{request.path.method}} has been received.'

Which is something.. but not quite the same, as I can't do any string manipulation on it.

But even worse, is that the config will match paths I don't want it to match, like /api/v1/method/delete/resource.

It seems that my only option is hardcoding the possible permutations of paths I want to match into multiple configs, with a lot of duplication and slightly different responses. The data I need isn't in the body of the request, so it seems like I'm stuck.

Use request headers in mock body?

Would it be possible to add to the body Variable Tags something that can extract values from the request headers, similar to the request.path."key" tag?

Hoping to read a user ID from a request header and use it in the response body.

Incorrect install section via Docker

Hi
Install section is incorrect
Current:

go get github.com/jmartin82/mmock
docker build -t mmock/mmock .
docker run -v YOUR_ABS_PATH:/config -p 8082:8082 -p 8083:8083  mmock/mmock

Why
No need
go get github.com/jmartin82/mmock
Error on docker build -t mmock/mmock .
no such file or directory

Actual

  1. sudo docker image pull jordimartin/mmock
  2. sudo docker run -v YOUR_ABS_PATH:/config -p 8082:8082 -p 8083:8083 jordimartin/mmock

thats all

image

Partial match and unordered match of request body

I want to match bodies with at least a set of specific key-value pairs in either a JSON-encoded or www-form-urlencoded body.

This is a probably insecure example but:
if Content-Type is application/json and the body is { "username": "*", "password": "*" } then i respond with 200. Any valid json string specifying the username and password would ideally match that, but instead it has to match exactly, spaces and all.
So the order of the fields shouldn't matter either e.g.:
{ "password": "*", "username": "*" } should be 200 too.

So then I could then match on just the username too for example, and say password required if there's at least some valid string with a username.
So I could match { "username": "*" } or {"username" :"*"} or any other valid json string to return something like password required.

And a similar behaviour for application/x-www-form-urlencoded - the order shouldn't matter in the string as long as the specified values match.

Is that kind of thing currently possible? I can't see an easy way to do it when body is just a string match.

Cannot get latest version: module contains a go.mod file, so module path should be github.com/jmartin82/mmock/v2

Background

The github.com/jmartin82/mmock uses Go modules and the current release version is v2. And it’s module path is "github.com/jmartin82/mmock", instead of "github.com/jmartin82/mmock/v2". It must comply with the specification of "Releasing Modules for v2 or higher" available in the Modules documentation. Quoting the specification:

A package that has opted in to modules must include the major version in the import path to import any v2+ modules
To preserve import compatibility, the go command requires that modules with major version v2 or later use a module path with that major version as the final element. For example, version v2.0.0 of example.com/m must instead use module path example.com/m/v2.
https://github.com/golang/go/wiki/Modules#releasing-modules-v2-or-higher

Steps to Reproduce

GO111MODULE=on, run go get targeting any version >= v2.5.1 of the jmartin82/mmock:

$ go get github.com/jmartin82/[email protected]
go: finding github.com/jmartin82/mmock v2.7.9
go: finding github.com/jmartin82/mmock v2.7.9
go get github.com/jmartin82/[email protected]: github.com/jmartin82/[email protected]: invalid version: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v2

run go get github.com/jmartin82/mmock, the version will stuck in v2.8.0:

$go get github.com/jmartin82/mmock
go: downloading github.com/jmartin82/mmock v1.0.1
go: downloading github.com/jmartin82/mmock v2.8.0+incompatible
go: github.com/jmartin82/mmock upgrade => v2.8.0+incompatible 

SO anyone using Go modules will not be able to easily use any newer version of jmartin82/mmock.

Solution

1. Kill the go.mod files, rolling back to GOPATH.

This would push them back to not being managed by Go modules (instead of incorrectly using Go modules).
Ensure compatibility for downstream module-aware projects and module-unaware projects projects

2. Fix module path to strictly follow SIV rules.

Patch the go.mod file to declare the module path as github.com/jmartin82/mmock/v2 as per the specs. And adjust all internal imports.
The downstream projects might be negatively affected in their building if they are module-unaware (Go versions older than 1.9.7 and 1.10.3; Or use third-party dependency management tools, such as: Dep, glide,govendor…).

If you don't want to break the above repos. This method can provides better backwards-compatibility.
Release a v2 or higher module through the major subdirectory strategy: Create a new v2 subdirectory (github.com/jmartin82/mmock/v2) and place a new go.mod file in that subdirectory. The module path must end with /v2. Copy or move the code into the v2 subdirectory. Update import statements within the module to also use /v2 (import "github.com/jmartin82/mmock/v2/…"). Tag the release with v2.x.y.

3. Suggest your downstream module users use hash instead of a version tag.

If the standard rule of go modules conflicts with your development mode. Or not intended to be used as a library and does not make any guarantees about the API. So you can’t comply with the specification of "Releasing Modules for v2 or higher" available in the Modules documentation.
Regardless, since it's against one of the design choices of Go, it'll be a bit of a hack. Instead of go get github.com/jmartin82/mmock@version-tag, module users need to use this following way to get the jmartin82/mmock:
(1) Search for the tag you want (in browser)
(2) Get the commit hash for the tag you want
(3) Run go get github.com/jmartin82/mmock@commit-hash
(4) Edit the go.mod file to put a comment about which version you actually used
This will make it difficult for module users to get and upgrade jmartin82/mmock.

[*] You can see who will be affected here: [1 module user, i.e., JumboInteractiveLimited/Gandalf]
https://github.com/JumboInteractiveLimited/Gandalf/blob/master/go.mod#L9

Summary

You can make a choice to fix DM issues by balancing your own development schedules/mode against the affects on the downstream projects.

For this issue, Solution 2 can maximize your benefits and with minimal impacts to your downstream projects the ecosystem.

References

Add ability to specify arbitrary delay unit

Hello. Thank you for your project.

AFAIK, now the delay can only be specified in seconds with a minimum 1. Sometimes it's not quite handy, for example in perf tests to set such big delay.

It would be great to have the possibility to set duration as a string, like "300ms" and then parse that duration via ParseDuration instead of reading int and hardcoding * time.Second.
What do you think?

Unable to escape : (colon) in request path

This problems appears when using URNs for identifiers.
MMock considers it as a variable and cannot properly match the request path.

Example:

---
control:
  scenario:
    name: getNote
request:
  method: GET
  path: /api/v1/notes/urn:organization:notebook:eu:note:123
response:
  statusCode: 200
  headers:
    Content-Type:
      - "application/json"
  body: "It works"

This actually works because it is matching everything that starts with /api/v1/notes/urn, but if we try a request with another URN it will still return "It works". Or if we add another mock using another URN that will never be matched.

Suggestion. Allow escaping the colon char in some way:

request:
  method: GET
  path: /api/v1/notes/urn\:organization\:notebook\:eu\:note\:123

Or:

request:
  method: GET
  path: /api/v1/notes/urn::organization::notebook::eu::note::123

[Feature Request] multiple callbacks

I was attracted to this tool by the callback functionality (#110) but for our purposes (simulating the Twilio Programmable Messaging API) it would be useful to support multiple callbacks for the same request.

In Twilio's API they send you several status updates as the message progresses.

I was thinking:

{
  "request": { ... },
  "response": { ... },
  "callbacks": [ { <callback definition 1> }, { <callback definition 2>} ...]
}

Feature Request - allow request `path` to be a list of paths

It would be great if a config could match multiple paths or path patterns. That would make it possible to not duplicate a lot of config when you want to match paths that can't completely be described with a wildcard or :value component, or just want to match a few exact paths.

Examples:

request:
  method: POST|PUT
  path: 
    - "/api/v1/method/create"
    - "/api/v1/method/delete"
request:
  method: POST|PUT
  path: 
    - "/api/v1/method/create/*"
    - "/api/v1/method/delete*"

This would let the rest of sections remain the same, and possible even act differently based on path (especially in combination with #128)

Pattern * dont work in request body strings

Actual Problem:
I have simple config for POST

description: "Create Order POST"
request:
  method: POST
  path: /order/create/
  body: '{"email": "alma@alma.*", "product": "choco-cookies", "quantity" : 3}'
response:
  headers:
    Content-Type:
      - application/json
  statusCode: 200
  body: '{"status": "ok"}'

with pattern "alma@alma.*" in request body
but when I send request

{
    "scheme": "http",
    "host": "localhost",
    "port": "8083",
    "method": "POST",
    "path": "/order/create/",
    "queryStringParameters": {},
    "fragment": "",
    "headers": {
        "Accept-Encoding": [
            "gzip,deflate"
        ],
        "Connection": [
            "Keep-Alive"
        ],
        "Content-Length": [
            "71"
        ],
        "Content-Type": [
            "application/json"
        ],
        "User-Agent": [
            "Apache-HttpClient/4.5.8 (Java/11.0.3)"
        ]
    },
    "cookies": {},
    "body": "{\"email\" : \"[email protected]\", \"product\" : \"choco-cookies\", \"quantity\" : 3}"
}
Response

, mmock says Error

"uri": "OrderCreatePositive.yaml",
            "reason": "Body not match. Actual: {\"email\" : \"[email protected]\", \"product\" : \"choco-cookies\", \"quantity\" : 3}, Expected: {\"email\": \"alma@alma.*\", \"product\": \"choco-cookies\", \"quantity\" : 3}"

Expected:
Even email send like [email protected] or [email protected] or alma.alma@com the request body must match

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.