diff --git a/consumer/http.go b/consumer/http.go index e52113cc..44b558f8 100644 --- a/consumer/http.go +++ b/consumer/http.go @@ -85,6 +85,12 @@ type httpMockProvider struct { specificationVersion models.SpecificationVersion config MockHTTPProviderConfig mockserver *native.MockServer + + // running is true while the mock server for ExecuteTest is up. + running bool + // logs holds the mock server logs read so far for the most recent + // ExecuteTest. + logs strings.Builder } // MockServerConfig stores the address configuration details of the server for the current executing test @@ -113,7 +119,9 @@ func (p *httpMockProvider) ExecuteTest(t *testing.T, integrationTest func(MockSe return errors.New("error: unable to find free port, mock server will fail to start") } + p.logs.Reset() p.config.Port, err = p.mockserver.Start(fmt.Sprintf("%s:%d", p.config.Host, p.config.Port), p.config.TLS) + p.running = err == nil defer p.reset() if err != nil { //nolint:wrapcheck // MockServer.Start returns the internal/native sentinels @@ -149,6 +157,17 @@ func (p *httpMockProvider) ExecuteTest(t *testing.T, integrationTest func(MockSe return p.writePact() } +// MockServerLogs returns the logs pact_ffi wrote for the mock server of the +// most recent ExecuteTest, at the configured log level. It can be called from +// within the integration test, or once ExecuteTest has returned. +func (p *httpMockProvider) MockServerLogs() string { + if p.running { + p.logs.WriteString(p.mockserver.MockServerLogs(p.config.Port)) + } + + return p.logs.String() +} + // configure applies the defaults for any unset consumer test configuration. func (p *httpMockProvider) configure() { log.Println("[DEBUG] pact setup") @@ -185,6 +204,10 @@ func (p *httpMockProvider) configure() { // Clear state between tests. func (p *httpMockProvider) reset() { + if p.running { + p.logs.WriteString(p.mockserver.MockServerLogs(p.config.Port)) + p.running = false + } p.mockserver.CleanupMockServer(p.config.Port) p.mockserver.CleanupPlugins() p.config.Port = 0 diff --git a/consumer/http_headers_test.go b/consumer/http_headers_test.go new file mode 100644 index 00000000..04967952 --- /dev/null +++ b/consumer/http_headers_test.go @@ -0,0 +1,232 @@ +package consumer + +import ( + "bufio" + "context" + "fmt" + "net" + "net/http" + "strconv" + "strings" + "testing" + + "github.com/pact-foundation/pact-go/v2/matchers" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// repeatedHeaderCase is a request header expected with one value per index, +// and the field lines the client sends for it. +type repeatedHeaderCase struct { + name string + header string + expected []matchers.Matcher + lines []string + match bool + // rfc9110Warning, when set, is whether the mock server should log the + // pact-reference#584 deprecation warning for the request. + rfc9110Warning *bool +} + +// rfc9110WarningText is part of the deprecation warning pact_ffi logs when +// repeated header values only match when their field lines are compared one +// at a time (pact-reference#584). +const rfc9110WarningText = "RFC 9110 §5.3" + +// repeatedHeaderCases covers how the mock server matches repeated request +// headers. RFC 9110 §5.3 treats repeated field lines as one line with the +// values joined by commas, so separate lines and a single comma-joined line +// should match the same expectation. +func repeatedHeaderCases() []repeatedHeaderCase { + linkA := `; rel="a"` + linkB := `; rel="b"` + noWarning := false + + return []repeatedHeaderCase{ + { + name: "H1 separate lines", + header: "X-Request", + expected: []matchers.Matcher{S("a"), S("b")}, + lines: []string{"a", "b"}, + match: true, + }, + { + name: "H2 one comma-joined line", + header: "X-Request", + expected: []matchers.Matcher{S("a"), S("b")}, + lines: []string{"a, b"}, + match: true, + }, + { + name: "H3 values containing commas on separate lines", + header: "X-Sunset", + expected: []matchers.Matcher{S("Sat, 01 Jan 2028 00:00:00 GMT"), S("Sun, 02 Jan 2028 00:00:00 GMT")}, + lines: []string{"Sat, 01 Jan 2028 00:00:00 GMT", "Sun, 02 Jan 2028 00:00:00 GMT"}, + match: true, + }, + { + name: "H4 singleton Content-Type sent as one comma-joined line", + header: "Content-Type", + expected: []matchers.Matcher{S("text/plain"), S("text/html")}, + lines: []string{"text/plain, text/html"}, + match: false, + }, + { + name: "H5 Cache-Control sent as one comma-joined line", + header: "Cache-Control", + expected: []matchers.Matcher{S("no-cache"), S("no-store")}, + lines: []string{"no-cache, no-store"}, + match: true, + }, + { + name: "H6a regex matcher per index", + header: "X-Request", + expected: []matchers.Matcher{Regex("first-1", `^first-\d+$`), Regex("first-2", `^first-\d+$`)}, + lines: []string{"first-42", "first-99"}, + match: true, + rfc9110Warning: &noWarning, + }, + { + // Whitespace inside a quoted-string is literal (RFC 9110 §5.6.4), so + // "x, y" never equals "x , y", line by line or joined, and no + // pact-reference#584 deprecation warning is logged. + name: "H6b quoted value whitespace is literal", + header: "X-Request", + expected: []matchers.Matcher{S(`"x , y"`), S("z")}, + lines: []string{`"x, y"`, "z"}, + match: false, + rfc9110Warning: &noWarning, + }, + { + name: "H8a Link values with a comma in the URI on separate lines", + header: "Link", + expected: []matchers.Matcher{S(linkA), S(linkB)}, + lines: []string{linkA, linkB}, + match: true, + }, + { + name: "H8b Link values with a comma in the URI on one comma-joined line", + header: "Link", + expected: []matchers.Matcher{S(linkA), S(linkB)}, + lines: []string{linkA + ", " + linkB}, + match: true, + }, + } +} + +// assertRFC9110Warning checks whether logs hold the pact-reference#584 +// deprecation warning, when tt expects one way or the other. +func assertRFC9110Warning(t *testing.T, tt repeatedHeaderCase, logs string) { + t.Helper() + if tt.rfc9110Warning == nil { + return + } + if *tt.rfc9110Warning { + assert.Contains(t, logs, rfc9110WarningText) + } else { + assert.NotContains(t, logs, rfc9110WarningText) + } +} + +// sendRawHeaderLines sends GET /headers to the mock server, writing each of +// lines as its own name: value field line. The request is written by hand +// because net/http merges repeated header lines into one before sending. +func sendRawHeaderLines(msc MockServerConfig, name string, lines []string) (int, error) { + address := net.JoinHostPort(msc.Host, strconv.Itoa(msc.Port)) + var dialer net.Dialer + conn, err := dialer.DialContext(context.Background(), "tcp", address) + if err != nil { + return 0, fmt.Errorf("connecting to the mock server: %w", err) + } + defer func() { _ = conn.Close() }() + + var req strings.Builder + fmt.Fprintf(&req, "GET /headers HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n", address) + for _, line := range lines { + fmt.Fprintf(&req, "%s: %s\r\n", name, line) + } + req.WriteString("\r\n") + + _, err = conn.Write([]byte(req.String())) + if err != nil { + return 0, fmt.Errorf("writing the request: %w", err) + } + + res, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + return 0, fmt.Errorf("reading the response: %w", err) + } + defer func() { _ = res.Body.Close() }() + + return res.StatusCode, nil +} + +func TestV3HTTPRepeatedRequestHeaders(t *testing.T) { + for _, tt := range repeatedHeaderCases() { + t.Run(tt.name, func(t *testing.T) { + p, err := NewV3Pact(MockHTTPProviderConfig{ + Consumer: "consumer", + Provider: "provider", + PactDir: t.TempDir(), + }) + require.NoError(t, err) + + var status int + err = p.AddInteraction(). + UponReceiving(tt.name). + WithRequest("GET", "/headers", func(b *V3RequestBuilder) { + b.Header(tt.header, tt.expected...) + }). + WillRespondWith(200). + ExecuteTest(t, func(msc MockServerConfig) error { + var sendErr error + status, sendErr = sendRawHeaderLines(msc, tt.header, tt.lines) + return sendErr + }) + + if tt.match { + require.NoError(t, err) + assert.Equal(t, http.StatusOK, status) + } else { + require.Error(t, err) + assert.NotEqual(t, http.StatusOK, status) + } + assertRFC9110Warning(t, tt, p.MockServerLogs()) + }) + } +} + +func TestV4HTTPRepeatedRequestHeaders(t *testing.T) { + for _, tt := range repeatedHeaderCases() { + t.Run(tt.name, func(t *testing.T) { + p, err := NewV4Pact(MockHTTPProviderConfig{ + Consumer: "consumer", + Provider: "provider", + PactDir: t.TempDir(), + }) + require.NoError(t, err) + + var status int + err = p.AddInteraction(). + UponReceiving(tt.name). + WithRequest("GET", "/headers", func(b *V4RequestBuilder) { + b.Header(tt.header, tt.expected...) + }). + WillRespondWith(200). + ExecuteTest(t, func(msc MockServerConfig) error { + var sendErr error + status, sendErr = sendRawHeaderLines(msc, tt.header, tt.lines) + return sendErr + }) + + if tt.match { + require.NoError(t, err) + assert.Equal(t, http.StatusOK, status) + } else { + require.Error(t, err) + assert.NotEqual(t, http.StatusOK, status) + } + assertRFC9110Warning(t, tt, p.MockServerLogs()) + }) + } +} diff --git a/installer/installer.go b/installer/installer.go index a2e7140f..223a6ef4 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-rc.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-rc.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/internal/native/mock_server.go b/internal/native/mock_server.go index ab59b4e5..323c74db 100644 --- a/internal/native/mock_server.go +++ b/internal/native/mock_server.go @@ -6,6 +6,7 @@ package native import "C" import ( + "bytes" "crypto/tls" "crypto/x509" "encoding/json" @@ -103,20 +104,48 @@ func Init(logLevel string) { } log.Printf("[DEBUG] initialised native log level to %s (%d)", logLevel, l) - if os.Getenv("PACT_LOG_PATH") != "" { - log.Println("[DEBUG] initialised native log to log to file:", os.Getenv("PACT_LOG_PATH")) - err := logToFile(os.Getenv("PACT_LOG_PATH"), l) - if err != nil { - log.Println("[ERROR] failed to log to file:", err) - } - return + err := initLogger(l, os.Getenv("PACT_LOG_PATH")) + if err != nil { + log.Println("[ERROR] failed to initialise the native logger:", err) + } +} + +// initLogger installs the pact_ffi logger. Logs go to stdout, or to path when +// it is set, and are also kept in an in-memory buffer so that each mock +// server's logs can be read back with MockServerLogs. +func initLogger(level logLevel, path string) error { + C.pactffi_logger_init() + + sink := "stdout" + if path != "" { + sink = "file " + path + } + log.Println("[DEBUG] initialised native log to log to", sink) + + err := attachLogSink(sink, level) + if err != nil { + return err } - log.Println("[DEBUG] initialised native log to log to stdout") - err := logToStdout(l) + err = attachLogSink("buffer", level) if err != nil { - log.Println("[ERROR] failed to log to stdout:", err) + return err } + + res := C.pactffi_logger_apply() + log.Println("[DEBUG] logger_apply res", res) + + return logResultToError(int(res)) +} + +func attachLogSink(sink string, level logLevel) error { + cSink := C.CString(sink) + defer free(cSink) + + res := C.pactffi_logger_attach_sink(cSink, C.int(level)) + log.Println("[DEBUG] logger_attach_sink", sink, "res", res) + + return logResultToError(int(res)) } // MockServer is the public interface for managing the HTTP mock server. @@ -179,12 +208,32 @@ func (m *MockServer) MockServerMismatchedRequests(port int) []MismatchedRequest return res } +// MockServerLogs returns the logs the mock server on port has written since +// they were last read, and removes them from the buffer. It returns an empty +// string if there is no mock server on port. +func (m *MockServer) MockServerLogs(port int) string { + // The returned string is owned by the mock server and freed by + // pactffi_cleanup_mock_server. + logs := C.pactffi_mock_server_logs(C.int(port)) + if logs == nil { + return "" + } + + return C.GoString(logs) +} + // CleanupMockServer frees the memory from the previous mock server. func (m *MockServer) CleanupMockServer(port int) bool { if len(m.interactions) == 0 { return true } log.Println("[DEBUG] mock server cleaning up port:", port) + + // pact_ffi keeps buffered logs until they are read. Callers read the mock + // server's own logs with MockServerLogs before cleaning up; the logs written + // outside any mock server are not read, so drop them here. + drainGlobalLogBuffer() + res := C.pactffi_cleanup_mock_server(C.int(port)) return bool(res) @@ -676,75 +725,48 @@ type stringLike interface { String() string } +// stringFromInterface converts obj into the string form pact_ffi expects. +// +// Strings are passed through as given. Anything else is JSON-encoded, without +// HTML escaping, so '<', '>' and '&' reach pact_ffi as written. If the encoding +// is a JSON string (e.g. matchers.S or matchers.String, which are really just +// strings), it is decoded again so that pact_ffi receives the plain value +// rather than a quoted and escaped one. func stringFromInterface(obj any) string { switch t := obj.(type) { case string: return t default: - bytes, err := json.Marshal(obj) + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + err := enc.Encode(obj) if err != nil { panic(fmt.Sprintln("unable to marshal body to JSON:", err)) } - return quotedString(string(bytes)) - } -} - -// This fixes a quirk where certain "matchers" (e.g. matchers.S/String) are -// really just strings. However, whene we JSON encode them they get wrapped in quotes -// and the rust core sees them as plain strings, requiring then the quotes to be matched. -func quotedString(s string) string { - if s[0] == '"' && s[len(s)-1] == '"' { - return s[1 : len(s)-1] - } - return s -} - -// Experimental logging options -// func LogMessage(pkg, level, message string) { -// cPkg := C.CString(pkg) -// defer free(cPkg) - -// cLevel := C.CString(level) -// defer free(cLevel) - -// cMessage := C.CString(message) -// defer free(cMessage) - -// res := C.pactffi_log_message(cPkg, cLevel, cMessage) -// log.Println("[DEBUG] log_to_buffer res", res) -// } + encoded := bytes.TrimSuffix(buf.Bytes(), []byte("\n")) -// func logToBuffer(level logLevel) error { -// res := C.pactffi_log_to_buffer(C.int(level)) -// log.Println("[DEBUG] log_to_buffer res", res) - -// return logResultToError(int(res)) -// } - -func logToStdout(level logLevel) error { - res := C.pactffi_log_to_stdout(C.int(level)) - log.Println("[DEBUG] log_to_stdout res", res) + // Only a JSON string is decoded; json.Unmarshal would also accept + // null into a string, which must stay "null". + var s string + if len(encoded) > 0 && encoded[0] == '"' && json.Unmarshal(encoded, &s) == nil { + return s + } - return logResultToError(int(res)) + return string(encoded) + } } -func logToFile(file string, level logLevel) error { - cFile := C.CString(file) - defer free(cFile) - - res := C.pactffi_log_to_file(cFile, C.int(level)) - log.Println("[DEBUG] log_to_file res", res) - - return logResultToError(int(res)) +// drainGlobalLogBuffer empties the in-memory log buffer that collects logs +// written outside a mock server (e.g. while an interaction is being built), +// which nothing in pact-go reads. +func drainGlobalLogBuffer() { + buf := C.pactffi_fetch_log_buffer(nil) + if buf != nil { + C.pactffi_string_delete(buf) + } } -// func getLogBuffer() string { -// buf := C.pactffi_fetch_log_buffer() -// defer free(buf) - -// return C.GoString(buf) -// } - func logResultToError(res int) error { switch res { case 0: diff --git a/internal/native/mock_server_headers_test.go b/internal/native/mock_server_headers_test.go new file mode 100644 index 00000000..4edab025 --- /dev/null +++ b/internal/native/mock_server_headers_test.go @@ -0,0 +1,184 @@ +package native + +import ( + "bufio" + "context" + "fmt" + "net" + "net/http" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// sendRawHeaderLines sends GET /headers to the mock server on port, writing +// each of lines as its own name: value field line. The request is written by +// hand because net/http merges repeated header lines into one before sending, +// and these tests depend on what reaches the mock server line by line. +func sendRawHeaderLines(t *testing.T, port int, name string, lines []string) int { + t.Helper() + + address := net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + var dialer net.Dialer + conn, err := dialer.DialContext(context.Background(), "tcp", address) + require.NoError(t, err) + defer func() { _ = conn.Close() }() + + var req strings.Builder + fmt.Fprintf(&req, "GET /headers HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n", address) + for _, line := range lines { + fmt.Fprintf(&req, "%s: %s\r\n", name, line) + } + req.WriteString("\r\n") + + _, err = conn.Write([]byte(req.String())) + require.NoError(t, err) + + res, err := http.ReadResponse(bufio.NewReader(conn), nil) + require.NoError(t, err) + defer func() { _ = res.Body.Close() }() + + return res.StatusCode +} + +// regexHeader is a regex matching rule for a single header value, in the +// JSON form pactffi_with_header_v2 accepts. +func regexHeader(regex, example string) map[string]any { + return map[string]any{ + "pact:matcher:type": "regex", + "regex": regex, + "value": example, + } +} + +// TestMockServer_RepeatedRequestHeaders checks how the mock server matches a +// header that is expected with several values (one value per index) against +// the field lines a client actually sends. RFC 9110 §5.3 treats repeated field +// lines as one line with the values joined by commas, so separate lines and a +// single comma-joined line should match the same expectation. +func TestMockServer_RepeatedRequestHeaders(t *testing.T) { + linkA := `; rel="a"` + linkB := `; rel="b"` + noWarning := false + + tests := []struct { + name string + header string + expected []any + lines []string + match bool + // rfc9110Warning, when set, is whether the mock server should log the + // pact-reference#584 deprecation warning for the request. + rfc9110Warning *bool + }{ + { + name: "H1 separate lines", + header: "X-Request", + expected: []any{"a", "b"}, + lines: []string{"a", "b"}, + match: true, + }, + { + name: "H2 one comma-joined line", + header: "X-Request", + expected: []any{"a", "b"}, + lines: []string{"a, b"}, + match: true, + }, + { + name: "H3 values containing commas on separate lines", + header: "X-Sunset", + expected: []any{"Sat, 01 Jan 2028 00:00:00 GMT", "Sun, 02 Jan 2028 00:00:00 GMT"}, + lines: []string{"Sat, 01 Jan 2028 00:00:00 GMT", "Sun, 02 Jan 2028 00:00:00 GMT"}, + match: true, + }, + { + name: "H4 singleton Content-Type sent as one comma-joined line", + header: "Content-Type", + expected: []any{"text/plain", "text/html"}, + lines: []string{"text/plain, text/html"}, + match: false, + }, + { + name: "H5 Cache-Control sent as one comma-joined line", + header: "Cache-Control", + expected: []any{"no-cache", "no-store"}, + lines: []string{"no-cache, no-store"}, + match: true, + }, + { + name: "H6a regex matcher per index", + header: "X-Request", + expected: []any{ + regexHeader(`^first-\d+$`, "first-1"), + regexHeader(`^first-\d+$`, "first-2"), + }, + lines: []string{"first-42", "first-99"}, + match: true, + rfc9110Warning: &noWarning, + }, + { + // Whitespace inside a quoted-string is literal (RFC 9110 §5.6.4), so + // "x, y" never equals "x , y", line by line or joined, and no + // pact-reference#584 deprecation warning is logged. + name: "H6b quoted value whitespace is literal", + header: "X-Request", + expected: []any{`"x , y"`, "z"}, + lines: []string{`"x, y"`, "z"}, + match: false, + rfc9110Warning: &noWarning, + }, + { + name: "H8a Link values with a comma in the URI on separate lines", + header: "Link", + expected: []any{linkA, linkB}, + lines: []string{linkA, linkB}, + match: true, + }, + { + name: "H8b Link values with a comma in the URI on one comma-joined line", + header: "Link", + expected: []any{linkA, linkB}, + lines: []string{linkA + ", " + linkB}, + match: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := NewHTTPPact("consumer", "provider") + m.NewInteraction(tt.name). + UponReceiving(tt.name). + WithRequest("GET", "/headers"). + WithRequestHeaders(map[string][]any{tt.header: tt.expected}). + WithStatus(200) + + port, err := m.Start("127.0.0.1:0", false) + require.NoError(t, err) + defer m.CleanupMockServer(port) + + status := sendRawHeaderLines(t, port, tt.header, tt.lines) + mismatches := m.MockServerMismatchedRequests(port) + + if tt.match { + assert.Equal(t, http.StatusOK, status) + assert.Empty(t, mismatches) + } else { + assert.NotEqual(t, http.StatusOK, status) + assert.NotEmpty(t, mismatches) + } + + if tt.rfc9110Warning != nil { + logs := m.MockServerLogs(port) + if *tt.rfc9110Warning { + assert.Contains(t, logs, "RFC 9110 §5.3") + } else { + assert.NotContains(t, logs, "RFC 9110 §5.3") + } + } + }) + } +} diff --git a/internal/native/mock_server_test.go b/internal/native/mock_server_test.go index dca44f1f..fef21a41 100644 --- a/internal/native/mock_server_test.go +++ b/internal/native/mock_server_test.go @@ -10,6 +10,7 @@ import ( "testing" "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" "google.golang.org/protobuf/proto" @@ -285,3 +286,38 @@ func TestPluginInteraction(t *testing.T) { err = m.WritePactFile(port, tmpPactFolder) assert.NoError(t, err) } + +func TestStringFromInterface(t *testing.T) { + link := `; rel="a" & more` + + tests := []struct { + name string + in any + want string + }{ + {name: "plain string", in: link, want: link}, + {name: "matchers.S", in: matchers.S(link), want: link}, + {name: "matchers.String", in: matchers.String(link), want: link}, + {name: "matchers.S with a backslash", in: matchers.S(`a\b`), want: `a\b`}, + {name: "empty matchers.S", in: matchers.S(""), want: ""}, + {name: "number", in: 42, want: "42"}, + {name: "bool", in: true, want: "true"}, + {name: "nil", in: nil, want: "null"}, + { + name: "map", + in: map[string]any{"a": " & c"}, + want: `{"a":" & c"}`, + }, + { + name: "regex matcher", + in: matchers.Regex("first-1", `^first-\d+$`), + want: `{"pact:matcher:type":"regex","value":"first-1","regex":"^first-\\d+$"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, stringFromInterface(tt.in)) + }) + } +}