You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pact匹配规则中min与max无法同时生效,如何校验数组元素数量范围?

How to Enforce Both Min and Max Array Length in Pact's Matching Rules

Great question—this is a common gotcha with Pact's matching rules, especially when you're first figuring out how to combine length constraints for arrays. Let's break down why your previous attempts didn't work and how to fix it.

Why Your Previous Approaches Failed

  • Combining min and max without specifying the match type: When you wrote "$.body": { "min": 1, "max": 2 }, Pact didn't recognize you were targeting an array specifically. Without a match property defining the field type (like "array" or "arrayLike"), Pact only prioritizes one constraint (usually min here) and ignores the other.
  • Duplicate keys in the matching rules object: JSON doesn't allow duplicate top-level keys in an object. When you added two separate "$.body" entries, the second one overwrote the first entirely—so only the max rule took effect.

The Correct Solution

To enforce both a minimum and maximum array length, you need to:

  1. Explicitly declare the target field is an array using the match property
  2. Include both min and max constraints in the same rule object

Here's a working example for an array at $.body:

"matchingRules": {
  "$.body": {
    "match": "array",
    "min": 1,
    "max": 2
  }
}

If your array has structured elements you also want to validate (not just length), use "arrayLike" instead and add matchers for the elements:

"matchingRules": {
  "$.body": {
    "match": "arrayLike",
    "min": 1,
    "max": 2,
    "matchers": [
      {
        "$": {
          "match": "type" // Validates each element is the correct type (e.g., object)
        }
      }
    ]
  }
}

How This Works

  • The "match": "array" (or "arrayLike") tells Pact that $.body must be an array.
  • The min and max properties work together to enforce the array has between 1 and 2 elements, inclusive.
  • Pact will now fail verification if the array has fewer than 1 element (violating min) or more than 2 elements (violating max).

内容的提问来源于stack exchange,提问作者Oliver Sanftleben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:03:32