diff --git a/docs/consumer.md b/docs/consumer.md index 15024819..e241887f 100644 --- a/docs/consumer.md +++ b/docs/consumer.md @@ -104,6 +104,13 @@ _NOTE: Some matchers are only compatible with the V3 interface, and must not be | `DateGenerated` | V3 | Matches a cross platform formatted date, and generates a current date during verification | | `TimeGenerated` | V3 | Matches a cross platform formatted date, and generates a current time during verification | | `DateTimeGenerated` | V3 | Matches a cross platform formatted datetime, and generates a current datetime during verification | +| `Null{}` | V3 | Matches only null values. | +| `AnyOf(matchers...)` | V3 | Matches if at least one of the matchers matches (rules combined with OR). The first matcher provides the example. See [Combining matchers with OR](#combining-matchers-with-or). | +| `OrNull(matcher)` | V3 | Matches the given matcher, or null. Shorthand for `AnyOf(matcher, Null{})`. | +| `LikeOrNull(content)` | V3 | Matches a value of the same type as `content`, or null. | +| `IntegerOrNull(example)` | V3 | Matches an integer, or null. | +| `DecimalOrNull(example)` | V3 | Matches a decimal, or null. | +| `RegexOrNull(example, regex)` | V3 | Matches a string matching `regex`, or null. | #### Match common formats @@ -120,6 +127,57 @@ _NOTE: Some matchers are only compatible with the V3 interface, and must not be | `IPv6Address()` | V2 | Match string containing IP6 formatted address | | `UUID()` | V2 | Match strings containing UUIDs | +#### Combining matchers with OR + +`AnyOf` lets several matchers apply to the same field, header or query parameter, so that a value matches if +_any one_ of them matches. A common use is a value that may be `null`: + +```go + body := Map{ + // "Fred", any other string, or null + "name": LikeOrNull("Fred"), + // digits, lower case letters, or null + "code": AnyOf(Regex("123", `^\d+$`), Regex("abc", `^[a-z]+$`), Null{}), + // null, or an object whose "number" is an integer + "address": LikeOrNull(map[string]any{ + "street": Like("Main St"), + "number": Integer(42), + }), + } +``` + +Matchers nested in the example (like `number` above) still apply to its children when the value is not `null`. +`AnyOf` also works for headers and query parameters, e.g. +`Query("status", AnyOf(Regex("active", "^active$"), Regex("pending", "^pending$")))`. + +The `name` field is sent to pact_ffi as: + +```json +{ + "pact:matcher:type": [{ "pact:matcher:type": "type" }, { "pact:matcher:type": "null" }], + "pact:matcher:combine": "OR", + "value": "Fred" +} +``` + +and is written to the pact file as `{"combine": "OR", "matchers": [{"match": "type"}, {"match": "null"}]}`. + +Things to be aware of: + +- **Only the example is exercised in the consumer test.** In a response, the mock server always returns the first + matcher's example, so your consumer code is never tested against the other alternatives (for example, how it + handles `null`). They are recorded in the pact and checked during provider verification. Consider a separate + interaction for each shape your consumer must actually handle. +- Each alternative must be a matcher that describes a matching rule (`Like`, `Regex`, `Integer`, `Null{}`, ...), + not a plain `S`/`String` or a `StructMatcher`; otherwise marshalling the matcher fails. +- Matchers like `Like` compare against the example, so `LikeOrNull` on an object accepts an object of the same + shape, or null. +- Put all the alternatives in one `AnyOf` (nested `AnyOf`s are flattened for you). Don't wrap another matcher in the + example of an OR group: its rules would be replaced by the OR group. +- Requires a version of pact_ffi that supports `pact:matcher:combine` + ([pact-foundation/pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601)), + i.e. pact_ffi `TODO: version`. Older versions do not understand `pact:matcher:combine`, so requests that should match will not. + #### Nesting Matchers Matchers may be nested in other objects. Here is a more complex example that shows how 3 common matchers can be used together: diff --git a/examples/consumer_or_test.go b/examples/consumer_or_test.go new file mode 100644 index 00000000..391fbd55 --- /dev/null +++ b/examples/consumer_or_test.go @@ -0,0 +1,202 @@ +//go:build consumer + +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/pact-foundation/pact-go/v2/consumer" + "github.com/pact-foundation/pact-go/v2/log" + "github.com/pact-foundation/pact-go/v2/matchers" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var ( + AnyOf = matchers.AnyOf + LikeOrNull = matchers.LikeOrNull + RegexOrNull = matchers.RegexOrNull +) + +// orRequest is what the consumer under test sends to the mock provider. +type orRequest struct { + header string + query string + body string +} + +// The example values: what the first alternative of each matcher describes. +var orExampleRequest = orRequest{ + header: "123", + query: "active", + body: `{"name": "Fred", "nickname": "Freddo", "address": {"street": "Main St", "number": 42}}`, +} + +// TestConsumerV4AnyOf shows matching rules combined with OR: the mock server +// accepts a value that matches any one of the alternatives. +func TestConsumerV4AnyOf(t *testing.T) { + require.NoError(t, log.SetLogLevel("INFO")) + + tests := map[string]struct { + request orRequest + wantErr bool + }{ + "the example values match": { + request: orExampleRequest, + }, + "the other alternatives match": { + request: orRequest{ + header: "abc", + query: "pending", + body: `{"name": null, "nickname": null, "address": null}`, + }, + }, + "a string that is neither a string nor null fails": { + request: orRequest{ + header: orExampleRequest.header, + query: orExampleRequest.query, + body: `{"name": 42, "nickname": "Freddo", "address": null}`, + }, + wantErr: true, + }, + "rules nested in the object example still apply": { + request: orRequest{ + header: orExampleRequest.header, + query: orExampleRequest.query, + body: `{"name": "Fred", "nickname": "Freddo", "address": {"street": "Main St", "number": "42"}}`, + }, + wantErr: true, + }, + "a header matching no alternative fails": { + request: orRequest{ + header: "ABC!", + query: orExampleRequest.query, + body: orExampleRequest.body, + }, + wantErr: true, + }, + "a query parameter matching no alternative fails": { + request: orRequest{ + header: orExampleRequest.header, + query: "deleted", + body: orExampleRequest.body, + }, + wantErr: true, + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + pactDir := t.TempDir() + err := anyOfInteraction(t, pactDir).ExecuteTest(t, orTest(tt.request)) + if tt.wantErr { + assert.Error(t, err) + return + } + require.NoError(t, err) + assertPactCombinesWithOR(t, pactDir) + }) + } +} + +func anyOfInteraction(t *testing.T, pactDir string) *consumer.V4InteractionWithResponse { + t.Helper() + + mockProvider, err := consumer.NewV4Pact(consumer.MockHTTPProviderConfig{ + Consumer: "PactGoV4AnyOfConsumer", + Provider: "V4AnyOfProvider", + Host: "127.0.0.1", + PactDir: pactDir, + }) + require.NoError(t, err) + + return mockProvider. + AddInteraction(). + UponReceiving("A request using matchers combined with OR"). + WithRequest("POST", "/users", func(b *consumer.V4RequestBuilder) { + b. + Header("Content-Type", S("application/json")). + Header("X-Id", AnyOf(Regex("123", `^\d+$`), Regex("abc", `^[a-z]+$`))). + Query("status", AnyOf(Regex("active", "^active$"), Regex("pending", "^pending$"))). + JSONBody(Map{ + "name": LikeOrNull("Fred"), + "nickname": RegexOrNull("Freddo", `^\w+$`), + // Null or an object: the rules inside the example still + // apply to its children when it is not null. + "address": LikeOrNull(map[string]any{ + "street": Like("Main St"), + "number": Integer(42), + }), + }) + }). + WillRespondWith(200) +} + +func orTest(r orRequest) func(config consumer.MockServerConfig) error { + return func(config consumer.MockServerConfig) error { + req := &http.Request{ + Method: http.MethodPost, + URL: &url.URL{ + Host: fmt.Sprintf("%s:%d", config.Host, config.Port), + Scheme: "http", + Path: "/users", + RawQuery: url.Values{"status": {r.query}}.Encode(), + }, + Body: io.NopCloser(strings.NewReader(r.body)), + Header: make(http.Header), + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Id", r.header) + + res, err := http.DefaultClient.Do(req) + if err != nil { + return fmt.Errorf("calling the mock provider: %w", err) + } + defer func() { _ = res.Body.Close() }() + + if res.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status %d", res.StatusCode) + } + return nil + } +} + +// assertPactCombinesWithOR checks the pact file records the OR rule lists. +func assertPactCombinesWithOR(t *testing.T, pactDir string) { + t.Helper() + + raw, err := os.ReadFile(filepath.Join(pactDir, "PactGoV4AnyOfConsumer-V4AnyOfProvider.json")) //nolint:gosec // pactDir is the test's own temp dir + require.NoError(t, err) + + var pact struct { + Interactions []struct { + Request struct { + MatchingRules map[string]map[string]json.RawMessage `json:"matchingRules"` + } `json:"request"` + } `json:"interactions"` + } + require.NoError(t, json.Unmarshal(raw, &pact)) + require.Len(t, pact.Interactions, 1) + rules := pact.Interactions[0].Request.MatchingRules + + assert.JSONEq(t, `{"combine": "OR", "matchers": [{"match": "type"}, {"match": "null"}]}`, + string(rules["body"]["$.name"])) + assert.JSONEq(t, `{"combine": "OR", "matchers": [{"match": "regex", "regex": "^\\w+$"}, {"match": "null"}]}`, + string(rules["body"]["$.nickname"])) + assert.JSONEq(t, `{"combine": "OR", "matchers": [{"match": "type"}, {"match": "null"}]}`, + string(rules["body"]["$.address"])) + assert.JSONEq(t, `{"combine": "AND", "matchers": [{"match": "integer"}]}`, + string(rules["body"]["$.address.number"])) + assert.JSONEq(t, `{"combine": "OR", "matchers": [{"match": "regex", "regex": "^\\d+$"}, {"match": "regex", "regex": "^[a-z]+$"}]}`, + string(rules["header"]["X-Id"])) + assert.JSONEq(t, `{"combine": "OR", "matchers": [{"match": "regex", "regex": "^active$"}, {"match": "regex", "regex": "^pending$"}]}`, + string(rules["query"]["status"])) +} diff --git a/installer/installer.go b/installer/installer.go index a2e7140f..8bd9a1c8 100644 --- a/installer/installer.go +++ b/installer/installer.go @@ -377,8 +377,8 @@ func checkMusl() bool { return false } -// download template structure: "https://github.com/pact-foundation/pact-reference/releases/download/RELEASE-vVERSION/RELEASE-TARGET.ARCHIVE_EXTENSION" -var downloadTemplate = "https://github.com/pact-foundation/pact-reference/releases/download/%s-v%s/%s-%s.%s" +// download template structure: "https://github.com/YOU54F/pact-reference/releases/download/RELEASE-vVERSION/RELEASE-TARGET.ARCHIVE_EXTENSION" +var downloadTemplate = "https://github.com/YOU54F/pact-reference/releases/download/%s-v%s/%s-%s.%s" var supportedOSes = map[string]string{ "darwin": macos, @@ -435,14 +435,14 @@ var packages = map[string]packageInfo{ FFIPackage: { libName: ffiLibBaseName, releaseName: "pact_ffi", - version: "0.5.12", + version: "0.5.13-or.1", // Pin to the shipped FFI minor. The bindings in this release reference // symbols specific to this libpact_ffi minor, and past minors have both // added and removed symbols, so a wider range lets a mismatched-but-in-range // library already on disk pass CheckPackageInstall and skip reinstalling, // which then fails at link/load time with undefined FFI symbols. Bump this // in lockstep with version above. - semverRange: ">= 0.5.12, < 0.6.0", + semverRange: ">= 0.5.13-or.1", // hashicorp go-version rejects a prerelease against "< 0.6.0" }, } diff --git a/installer/installer_test.go b/installer/installer_test.go index 0976c1ce..b4fb9584 100644 --- a/installer/installer_test.go +++ b/installer/installer_test.go @@ -49,9 +49,9 @@ func TestInstallerDownloader(t *testing.T) { pkg: FFIPackage, want: func() string { if checkMusl() { - return fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-unknown-linux-musl.tar.xz", packages[FFIPackage].version) + return fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-unknown-linux-musl.tar.xz", packages[FFIPackage].version) } - return fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-unknown-linux-gnu.tar.xz", packages[FFIPackage].version) + return fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-unknown-linux-gnu.tar.xz", packages[FFIPackage].version) }(), test: Installer{ os: linux, @@ -63,9 +63,9 @@ func TestInstallerDownloader(t *testing.T) { pkg: FFIPackage, want: func() string { if checkMusl() { - return fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-unknown-linux-musl.tar.xz", packages[FFIPackage].version) + return fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-unknown-linux-musl.tar.xz", packages[FFIPackage].version) } - return fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-unknown-linux-gnu.tar.xz", packages[FFIPackage].version) + return fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-unknown-linux-gnu.tar.xz", packages[FFIPackage].version) }(), test: Installer{ os: linux, @@ -75,7 +75,7 @@ func TestInstallerDownloader(t *testing.T) { { name: "ffi lib - macos x86_64", pkg: FFIPackage, - want: fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-apple-darwin.tar.xz", packages[FFIPackage].version), + want: fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-apple-darwin.tar.xz", packages[FFIPackage].version), test: Installer{ os: macos, arch: x86_64, @@ -84,7 +84,7 @@ func TestInstallerDownloader(t *testing.T) { { name: "ffi lib - macos arm64", pkg: FFIPackage, - want: fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-apple-darwin.tar.xz", packages[FFIPackage].version), + want: fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-apple-darwin.tar.xz", packages[FFIPackage].version), test: Installer{ os: macos, arch: aarch64, @@ -93,7 +93,7 @@ func TestInstallerDownloader(t *testing.T) { { name: "ffi lib - windows aarch64", pkg: FFIPackage, - want: fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-pc-windows-msvc.zip", packages[FFIPackage].version), + want: fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-aarch64-pc-windows-msvc.zip", packages[FFIPackage].version), test: Installer{ os: windows, arch: aarch64, @@ -102,7 +102,7 @@ func TestInstallerDownloader(t *testing.T) { { name: "ffi lib - windows x86_64", pkg: FFIPackage, - want: fmt.Sprintf("https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-pc-windows-msvc.zip", packages[FFIPackage].version), + want: fmt.Sprintf("https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v%s/pact_ffi-x86_64-pc-windows-msvc.zip", packages[FFIPackage].version), test: Installer{ os: windows, arch: x86_64, diff --git a/matchers/matcher_or.go b/matchers/matcher_or.go new file mode 100644 index 00000000..eb81dcca --- /dev/null +++ b/matchers/matcher_or.go @@ -0,0 +1,190 @@ +package matchers + +import ( + "encoding/json" + "errors" + "fmt" +) + +// combineOR is the pact:matcher:combine value that makes at least one of the +// rules in a pact:matcher:type array apply (rather than all of them, AND). +const combineOR = "OR" + +// matcherTypeKey is the integration JSON key naming a matcher's kind. +const matcherTypeKey = "pact:matcher:type" + +// errNoMatchers is returned when AnyOf is marshalled without any alternatives. +var errNoMatchers = errors.New("AnyOf requires at least one matcher") + +// errNotARule is returned when an AnyOf alternative does not encode a +// matching rule (for example a plain String or a StructMatcher). +var errNotARule = errors.New("AnyOf alternative is not a matching rule") + +// anyOf combines several matchers for the same path with OR logic. +type anyOf struct { + Matchers []Matcher +} + +// GetValue returns the example of the first alternative. +func (a anyOf) GetValue() any { + if len(a.Matchers) == 0 { + return nil + } + return a.Matchers[0].GetValue() +} + +// MarshalJSON encodes a as a single integration JSON matcher whose +// pact:matcher:type is the flattened list of alternatives, combined with OR, +// and whose value is the example of the first alternative. +// +// Fields here are emitted in a fixed order, keeping pact:matcher:type first: +// the key order is contract-visible in pact files another party consumes. +func (a anyOf) MarshalJSON() ([]byte, error) { + if len(a.Matchers) == 0 { + return nil, errNoMatchers + } + + rules, err := a.rules() + if err != nil { + return nil, err + } + + value, err := exampleOf(a.Matchers[0]) + if err != nil { + return nil, err + } + + //nolint:wrapcheck // encoding/json wraps a MarshalJSON failure in a + // *json.MarshalerError recording the type and the original error, so an extra + // prefix here would be doubled up in the message the caller finally sees. + return json.Marshal(struct { + Type []map[string]json.RawMessage `json:"pact:matcher:type"` + Combine string `json:"pact:matcher:combine"` + Value json.RawMessage `json:"value"` + }{rules, combineOR, value}) +} + +func (a anyOf) isMatcher() {} + +// rules returns the matching rule of each alternative, without its example, +// flattening any nested AnyOf so that all the alternatives end up in the one +// list (the FFI replaces, rather than merges, an OR group nested in the value). +func (a anyOf) rules() ([]map[string]json.RawMessage, error) { + rules := make([]map[string]json.RawMessage, 0, len(a.Matchers)) + for idx, m := range a.Matchers { + if nested, ok := m.(anyOf); ok { + nestedRules, err := nested.rules() + if err != nil { + return nil, err + } + rules = append(rules, nestedRules...) + continue + } + + fields, err := marshalToFields(m) + if err != nil { + return nil, err + } + if _, ok := fields[matcherTypeKey]; !ok { + return nil, fmt.Errorf("%w: alternative %d (%T)", errNotARule, idx, m) + } + + // The example and specification belong to the combined matcher, not to + // each rule in the list. + delete(fields, "value") + delete(fields, "pact:specification") + delete(fields, "specification") + rules = append(rules, fields) + } + return rules, nil +} + +// exampleOf returns the JSON example of m, keeping any matchers nested inside +// it so that rules for child paths still apply. +func exampleOf(m Matcher) (json.RawMessage, error) { + if nested, ok := m.(anyOf); ok { + if len(nested.Matchers) == 0 { + return nil, errNoMatchers + } + return exampleOf(nested.Matchers[0]) + } + + fields, err := marshalToFields(m) + if err != nil { + return nil, err + } + if value, ok := fields["value"]; ok { + return value, nil + } + + //nolint:wrapcheck // see MarshalJSON above. + return json.Marshal(m.GetValue()) +} + +// marshalToFields encodes m and splits the resulting JSON object into its +// top level fields. Matchers that do not encode to an object yield no fields. +func marshalToFields(m Matcher) (map[string]json.RawMessage, error) { + raw, err := json.Marshal(m) + if err != nil { + //nolint:wrapcheck // see MarshalJSON above. + return nil, err + } + + fields := map[string]json.RawMessage{} + if len(raw) == 0 || raw[0] != '{' { + return fields, nil + } + err = json.Unmarshal(raw, &fields) + if err != nil { + //nolint:wrapcheck // see MarshalJSON above. + return nil, err + } + return fields, nil +} + +// AnyOf matches a value if at least one of the given matchers matches it +// (the matching rules are combined with OR). +// +// The first matcher provides the example used in the consumer test, including +// any matchers nested inside an object example. The other alternatives only +// contribute their matching rule: they are recorded in the pact file and +// applied during provider verification, but are never exercised against your +// consumer code. +// +// Each alternative must be a matcher that encodes a matching rule (Like, +// Regex, Integer, Null, ...), not a plain String or StructMatcher. Nested +// AnyOf matchers are flattened into the one list of alternatives. +// +// Requires a pact_ffi version that supports pact:matcher:combine +// (pact-foundation/pact-reference#601). +// +// TODO: replace with the released pact_ffi version once available. +func AnyOf(matchers ...Matcher) Matcher { + return anyOf{Matchers: matchers} +} + +// OrNull matches a value that matches m, or is null. The example is m's +// example. +func OrNull(m Matcher) Matcher { + return AnyOf(m, Null{}) +} + +// LikeOrNull matches a value of the same type as content, or null. +func LikeOrNull(content any) Matcher { + return OrNull(Like(content)) +} + +// IntegerOrNull matches an integer, or null. +func IntegerOrNull(example int) Matcher { + return OrNull(Integer(example)) +} + +// DecimalOrNull matches a decimal, or null. +func DecimalOrNull(example float64) Matcher { + return OrNull(Decimal(example)) +} + +// RegexOrNull matches a string matching regex, or null. +func RegexOrNull(example string, regex string) Matcher { + return OrNull(Regex(example, regex)) +} diff --git a/matchers/matcher_or_test.go b/matchers/matcher_or_test.go new file mode 100644 index 00000000..092e0c27 --- /dev/null +++ b/matchers/matcher_or_test.go @@ -0,0 +1,137 @@ +package matchers + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func marshalString(t *testing.T, m Matcher) string { + t.Helper() + b, err := json.Marshal(m) + require.NoError(t, err) + return string(b) +} + +func TestMatcher_AnyOfTypeOrNull(t *testing.T) { + assert.JSONEq(t, `{ + "pact:matcher:type": [ + {"pact:matcher:type": "type"}, + {"pact:matcher:type": "null"} + ], + "pact:matcher:combine": "OR", + "value": "Fred" + }`, marshalString(t, AnyOf(Like("Fred"), Null{}))) +} + +func TestMatcher_AnyOfKeepsRuleAttributes(t *testing.T) { + assert.JSONEq(t, `{ + "pact:matcher:type": [ + {"pact:matcher:type": "regex", "regex": "^\\d+$"}, + {"pact:matcher:type": "integer"}, + {"pact:matcher:type": "type", "min": 1} + ], + "pact:matcher:combine": "OR", + "value": "100" + }`, marshalString(t, AnyOf(Regex("100", `^\d+$`), Integer(5), EachLike("x", 1)))) +} + +func TestMatcher_AnyOfKeyOrder(t *testing.T) { + // pact:matcher:type first, as with the other matchers. + assert.Regexp(t, `^\{"pact:matcher:type":\[`, marshalString(t, AnyOf(Like("Fred"), Null{}))) +} + +func TestMatcher_AnyOfFlattensNested(t *testing.T) { + assert.JSONEq(t, `{ + "pact:matcher:type": [ + {"pact:matcher:type": "integer"}, + {"pact:matcher:type": "null"}, + {"pact:matcher:type": "regex", "regex": "^\\d+$"} + ], + "pact:matcher:combine": "OR", + "value": 42 + }`, marshalString(t, AnyOf(IntegerOrNull(42), Regex("1", `^\d+$`)))) +} + +func TestMatcher_AnyOfNullOrObjectKeepsNestedMatchers(t *testing.T) { + m := LikeOrNull(map[string]any{ + "street": "Main St", + "number": Integer(42), + }) + assert.JSONEq(t, `{ + "pact:matcher:type": [ + {"pact:matcher:type": "type"}, + {"pact:matcher:type": "null"} + ], + "pact:matcher:combine": "OR", + "value": { + "street": "Main St", + "number": {"specification": "3.0.0", "pact:matcher:type": "integer", "value": 42} + } + }`, marshalString(t, m)) +} + +func TestMatcher_AnyOfNullFirstHasNullExample(t *testing.T) { + assert.JSONEq(t, `{ + "pact:matcher:type": [ + {"pact:matcher:type": "null"}, + {"pact:matcher:type": "type"} + ], + "pact:matcher:combine": "OR", + "value": null + }`, marshalString(t, AnyOf(Null{}, Like("Fred")))) + assert.Nil(t, AnyOf(Null{}, Like("Fred")).GetValue()) +} + +func TestMatcher_AnyOfInsideBody(t *testing.T) { + body := map[string]any{"name": LikeOrNull("Fred")} + b, err := json.Marshal(body) + require.NoError(t, err) + assert.JSONEq(t, `{"name": { + "pact:matcher:type": [{"pact:matcher:type": "type"}, {"pact:matcher:type": "null"}], + "pact:matcher:combine": "OR", + "value": "Fred" + }}`, string(b)) +} + +func TestMatcher_OrNullHelpers(t *testing.T) { + tests := map[string]struct { + matcher Matcher + rule string + value string + }{ + "LikeOrNull": {LikeOrNull("Fred"), `{"pact:matcher:type":"type"}`, `"Fred"`}, + "IntegerOrNull": {IntegerOrNull(7), `{"pact:matcher:type":"integer"}`, `7`}, + "DecimalOrNull": {DecimalOrNull(1.5), `{"pact:matcher:type":"decimal"}`, `1.5`}, + "RegexOrNull": {RegexOrNull("abc", `\w+`), `{"pact:matcher:type":"regex","regex":"\\w+"}`, `"abc"`}, + "OrNull": {OrNull(Includes("ell")), `{"pact:matcher:type":"include"}`, `"ell"`}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + assert.JSONEq(t, `{ + "pact:matcher:type": [`+tt.rule+`, {"pact:matcher:type": "null"}], + "pact:matcher:combine": "OR", + "value": `+tt.value+` + }`, marshalString(t, tt.matcher)) + }) + } +} + +func TestMatcher_AnyOfGetValue(t *testing.T) { + assert.Equal(t, "Fred", AnyOf(Like("Fred"), Null{}).GetValue()) + assert.Equal(t, 42, IntegerOrNull(42).GetValue()) + assert.Nil(t, AnyOf().GetValue()) +} + +func TestMatcher_AnyOfErrors(t *testing.T) { + _, err := json.Marshal(AnyOf()) + require.ErrorIs(t, err, errNoMatchers) + + _, err = json.Marshal(AnyOf(Like("x"), String("y"))) + require.ErrorIs(t, err, errNotARule) + + _, err = json.Marshal(AnyOf(Like("x"), StructMatcher{"a": Like(1)})) + require.ErrorIs(t, err, errNotARule) +}