Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions docs/consumer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down
202 changes: 202 additions & 0 deletions examples/consumer_or_test.go
Original file line number Diff line number Diff line change
@@ -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"]))
}
8 changes: 4 additions & 4 deletions installer/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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"
},
}

Expand Down
16 changes: 8 additions & 8 deletions installer/installer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
Loading
Loading