Warm tip: This article is reproduced from serverfault.com, please click

其他-在Wiremock的输入请求中验证/匹配JSON字段的数字而不是字符串

(其他 - Validate/Match JSON field for number and not string in the input request in Wiremock)

发布于 2020-12-26 20:36:12

我正在尝试验证amount请求中的特定json字段是否为数字而不是字符串

{
  "request": {
    "method": "POST",
    "urlPath": "/charges",
    "bodyPatterns" : [
      {"matchesJsonPath" : "$[?(@.amount =~ /^[0-9]*$/i)]"}
    ]
}

现在request1和request2正常运行,而request3失败。但是我希望request2也失败,因为它是一个字符串而不是数字,因为它是双引号。

请求1

{
    "amount": 123,
}

请求2

{
    "amount": "123",
}

要求3,

{
    "amount": "a123",
}

这可能吗?。我在Wiremock文档中看到

    Since WireMock’s matching operators all work on strings, 
the value selected by the JSONPath expression will be coerced to a string before the match is evaluated.
Questioner
firstpostcommenter
Viewed
0
firstpostcommenter 2020-12-28 17:43:56

我找到了解决方法。

根据你给出的正则表达式,我看到该amount字段不能具有负值。

因此,在matchesJsonPath中,进行虚拟检查以确保该值大于或等于零。这将确保值123将起作用,但“ 123”将引发错误

你甚至不需要使用正则表达式。

{
  "request": {
    "method": "POST",
    "urlPath": "/charges",
    "bodyPatterns" : [
      {"matchesJsonPath" : "$[?(@.amount >= 0)]"}
    ]
}