Search code examples
pythonwiremock

Why python wiremock doesnt respect precision and returns numbers as string?


I am trying basic mock example on decimals using wiremock and I couldn't get it to work. And I dont see any example online either. Below is the response section of my json file

  "response": {
    "status": 200,
    "jsonBody": {
      "weekly_rate": "{{randomDecimal lower=100.00 upper=800.00 precision=2}}",
      "max_amount": "{{randomDecimal lower=5000.00 upper=20000.00 precision=2}}"
    },
    "transformers": ["response-template"]
  }

and I get this response

{
  "weekly_rate": "220.87939761296946",
  "max_amount": "8860.916637737479"
}

Two issues

  • The numbers have more than 2 decimal places so the precision is not respected.
  • The numbers are strings instead of numeric

Solution

  • This was answered on the WireMock Community Slack so posting here for completeness.

    To force the decimal value generated by the randomDecimal helper to 2 decimal places you need to combine the randomDecimal helper with the numberFormat helper:

    {{numberFormat (randomDecimal lower=100.00 upper=800.00) '###.00' 'en_GB'}}
    

    The reason the decimals are generated as strings is because the jsonBody element requires valid json to be used. Unfortunately, because the handlebars template engine uses {{ and }} this generates invalid json if you don't put quotes around them. To workaround this you can switch to the body element instead of the jsonBody element. The body element takes a string which means you can create the response without quotes around the helpers:

    "weekly_rate": {{numberFormat (randomDecimal lower=100.00 upper=800.00) '###.00' 'en_GB'}}