Below is my wiremock mock json. I would like to cr...
# general
v
Below is my wiremock mock json. I would like to create a random uuid and assign it in a variable and use the same value in headers and body of the response section. Is it possible ?
Copy code
{
    "request": {
        "method": "POST",
        "urlPattern": {{url_match_pattern}}
    },
    "response": {
        "status": 200,
        "headers": {
            "Content-Type": "application/json",
            "request-id" : "{{#assign 'ID'}}{{randomValue type='UUID'}}{{/assign}}{{ID}}"
        },
        "jsonBody": {
            "request_id": "{{ID}}"
        }
    }
}
wiremock startup logs:
Copy code
port:                         8080
enable-browser-proxying:      false
disable-banner:               false
no-request-journal:           false
verbose:                      true

extensions:                   response-template,webhook
@Dirk Bolte: any pointers or suggestions ?
@Lee Turner @Tom
l
I might be wrong but I have a feeling that the context of the handlebars assign doesn't span the headers and the body. I couldn't get that to work in the tests I ran anyway. The solution could be the state extension as per our conversation here - https://wiremock-community.slack.com/archives/C03NAEH5LVA/p1709682557284889
👍 1
v
ok.. got it
thanks @Lee Turner
👍 1
d
sorry for the late reply. I'm not too familiar with WireMock internals in that area. From what understand from an extension point of view, you can assume that for every template, this is parsed individually. You can't assume that this is one scope they are executed in. The response template gets the model for the request passed in. From what I see, if you have two lines like your
request_id
line in there, they will be executed in isolation. If you want to use the same ID mutiple times, you need to built a whole JSON with handlebars (different use case, but maybe it transports the idea: https://github.com/wiremock/wiremock-state-extension/blob/develop/src/test/resourc[…]mplateHelperProviderExtensionTest/list_with_filled_default.json ) .
Looking at com.
github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer#transform
, the model for headers gets the response body passed in, so you can access it there.
v
Thanks @Dirk Bolte
But i see that using extension itis easier and better control and also keeping a future extension.
d
You might also write your own: there’s a hook to extend the model that is passed in. Haven’t tried it though: https://wiremock.org/docs/extensibility/adding-template-model-data/
When recording a state via the listeners, this is done as last step before actually sending the response. So whatever you store in the state won’t be available when building the response or headers.
If you check https://wiremock.org/docs/extensibility/listening-for-serve-events/, the state extension uses the beforeResponseSent event.