Search code examples
wiremock

How to get last n characters from a form request field in wiremock response template?


I have a wiremock stub like below

{
   "id":"86c2bb75-6de5-48aa-9c14-3cfc2483d12b",
   "name":"v1_payment_methods",
   "request":{
      "url":"/stripe/v1/payment_methods",
      "method":"POST",
      "bodyPatterns":[
         {
            "equalTo":"type=card&card[cvc]=890&card[number]=4242424242424242&card[exp_month]=1&card[exp_year]=2043",
            "caseInsensitive":false
         }
      ]
   },
   "response":{
      "status":200,
      "body":"{\n  \"id\": \"pm_{{randomValue length=24 type='ALPHANUMERIC'}}\",\n  \"object\": \"payment_method\",\n  \"billing_details\": {\n    \"address\": {\n      \"city\": null,\n      \"country\": null,\n      \"line1\": null,\n      \"line2\": null,\n      \"postal_code\": null,\n      \"state\": null\n    },\n    \"email\": null,\n    \"name\": null,\n    \"phone\": null\n  },\n  \"card\": {\n    \"brand\": \"visa\",\n    \"checks\": {\n      \"address_line1_check\": null,\n      \"address_postal_code_check\": null,\n      \"cvc_check\": \"unchecked\"\n    },\n    \"country\": \"US\",\n    \"exp_month\": {{formData request.body 'form' urlDecode=true}}{{lookup form 'card[exp_month]'}},\n    \"exp_year\": {{formData request.body 'form' urlDecode=true}}{{lookup form 'card[exp_year]'}},\n    \"fingerprint\": \"{{randomValue length=16 type='ALPHANUMERIC'}}\",\n    \"funding\": \"credit\",\n    \"generated_from\": null,\n    {\"last4\": \"4242\",\n    \"networks\": {\n      \"available\": [\n        \"visa\"\n      ],\n      \"preferred\": null\n    },\n    \"three_d_secure_usage\": {\n      \"supported\": true\n    },\n    \"wallet\": null\n  },\n  \"created\": {{now format='unix'}},\n  \"customer\": null,\n  \"livemode\": false,\n  \"metadata\": {},\n  \"type\": \"{{formData request.body 'form' urlDecode=true}}{{form.type}}\"\n}",
      "transformers":[
         "response-template"
      ]
   },
   "uuid":"86c2bb75-6de5-48aa-9c14-3cfc2483d12b",
   "persistent":true,
   "insertionIndex":7
}

In the response body last4 I want to get the last 4 characters from card[number] field in request body. Can someone let me know how can I do this?

Wiremock version

     <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock-jre8-standalone</artifactId>
        <version>2.35.0</version>
      </dependency>

Solution

  • I decided to use regexExtract

    {{#assign 'last4'}}{{formData request.body 'form' urlDecode=true}}{{lookup form 'card[number]'}}{{/assign}}\"last4\": \"{{regexExtract last4 '.{4}$'}}\"