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
26 changes: 26 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ jobs:
with:
ruby-version: ${{ matrix.ruby_version }}
bundler-cache: true
# TEMP: load libpact_ffi 0.5.13-rc.1 (YOU54F/pact-reference fork prerelease),
# fetched by the YOU54F/pact-ruby-ffi PR branch's download script, through
# pact-ffi's DEBUG_TARGET override (revert before merge)
- name: Use pact_ffi 0.5.13-rc.1 from YOU54F/pact-ruby-ffi
shell: bash
run: |
git clone --depth 1 --branch fix/repeated-headers-rfc9110 https://github.com/YOU54F/pact-ruby-ffi.git ../pact-ruby-ffi
cd ../pact-ruby-ffi
ruby script/download_libs.rb
echo "DEBUG_TARGET=$(ruby -r ./lib/pact/detect_os -e 'print File.expand_path(DetectOS.get_bin_path)')" >> "$GITHUB_ENV"
- name: Check loaded pact_ffi version
shell: bash
run: bundle exec ruby -e 'require "pact/ffi"; v = PactFfi.version; puts "DEBUG_TARGET=#{ENV["DEBUG_TARGET"]} pact_ffi=#{v}"; abort "expected pact_ffi 0.5.13-rc.1" unless v == "0.5.13-rc.1"'
- uses: pact-foundation/pact-cli@575a793b515ad65718cfb81198b3a4634dc8f72d # main
- run: pact plugin install --yes https://github.com/mefellows/pact-matt-plugin/releases/tag/v0.1.1
- run: pact plugin install --yes avro --version 0.1.3
Expand Down Expand Up @@ -53,6 +66,19 @@ jobs:
with:
ruby-version: ${{ matrix.ruby_version }}
bundler-cache: true
# TEMP: load libpact_ffi 0.5.13-rc.1 (YOU54F/pact-reference fork prerelease),
# fetched by the YOU54F/pact-ruby-ffi PR branch's download script, through
# pact-ffi's DEBUG_TARGET override (revert before merge)
- name: Use pact_ffi 0.5.13-rc.1 from YOU54F/pact-ruby-ffi
shell: bash
run: |
git clone --depth 1 --branch fix/repeated-headers-rfc9110 https://github.com/YOU54F/pact-ruby-ffi.git ../pact-ruby-ffi
cd ../pact-ruby-ffi
ruby script/download_libs.rb
echo "DEBUG_TARGET=$(ruby -r ./lib/pact/detect_os -e 'print File.expand_path(DetectOS.get_bin_path)')" >> "$GITHUB_ENV"
- name: Check loaded pact_ffi version
shell: bash
run: bundle exec ruby -e 'require "pact/ffi"; v = PactFfi.version; puts "DEBUG_TARGET=#{ENV["DEBUG_TARGET"]} pact_ffi=#{v}"; abort "expected pact_ffi 0.5.13-rc.1" unless v == "0.5.13-rc.1"'
- uses: pact-foundation/pact-cli@575a793b515ad65718cfb81198b3a4634dc8f72d # main
- run: pact plugin install --yes https://github.com/mefellows/pact-matt-plugin/releases/tag/v0.1.1
- run: "bundle exec appraisal install"
Expand Down
43 changes: 27 additions & 16 deletions lib/pact/consumer/http_interaction_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ def with_request(method: nil, path: nil, query: {}, headers: {}, body: nil)
end
end

InteractionContents.basic(headers).each_pair do |key, value_item|
PactFfi.with_header_v2(pact_interaction, interaction_part, key.to_s, 0, format_value(value_item))
end
add_headers(interaction_part, headers)

if body
PactFfi.with_body(pact_interaction, interaction_part, "application/json", format_value(InteractionContents.basic(body).value))
Expand All @@ -101,9 +99,7 @@ def will_respond_with(status: nil, headers: {}, body: nil)
interaction_part = PactFfi::FfiInteractionPart["INTERACTION_PART_RESPONSE"]
PactFfi.response_status(pact_interaction, status)

InteractionContents.basic(headers).each_pair do |key, value_item|
PactFfi.with_header_v2(pact_interaction, interaction_part, key.to_s, 0, format_value(value_item))
end
add_headers(interaction_part, headers)

if body
PactFfi.with_body(pact_interaction, interaction_part, "application/json", format_value(InteractionContents.basic(body).value))
Expand All @@ -128,17 +124,20 @@ def execute(&block)
yield(mock_server)

ensure
if mock_server.matched?
mock_server.write_pacts!(pact_config.pact_dir)
else
msg = mismatches_error_msg(mock_server)
raise InteractionMismatchesError.new(msg)
begin
if mock_server.matched?
mock_server.write_pacts!(pact_config.pact_dir)
else
msg = mismatches_error_msg(mock_server)
raise InteractionMismatchesError.new(msg)
end
ensure
@used = true
mock_server&.cleanup
# Reset the pact handle to allow for a new interaction to be built
# without previous interactions being included, also after a mismatch
@pact_config.reset_pact
end
@used = true
mock_server&.cleanup
# Reset the pact handle to allow for a new interaction to be built
# without previous interactions being included
@pact_config.reset_pact
end

private
Expand All @@ -162,6 +161,18 @@ def init_pact
handle
end

# Registers each header with pactffi_with_header_v2. An Array value is a repeated header
# (RFC 9110 §5.3): each element, a literal or a matcher, is registered at its own index,
# so a matcher can be set per value. An empty Array is passed through unchanged.
def add_headers(interaction_part, headers)
InteractionContents.basic(headers).each_pair do |key, value_item|
values = value_item.is_a?(Array) && value_item.any? ? value_item : [value_item]
values.each_with_index do |value, index|
PactFfi.with_header_v2(pact_interaction, interaction_part, key.to_s, index, format_value(value))
end
end
end

def format_value(obj)
return obj if obj.is_a?(String)

Expand Down
40 changes: 40 additions & 0 deletions spec/lib/consumer/http_interaction_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,44 @@
end.to raise_error(described_class::InteractionBuilderError, /value is required/)
end
end

describe 'headers' do
let(:request_part) { PactFfi::FfiInteractionPart['INTERACTION_PART_REQUEST'] }
let(:response_part) { PactFfi::FfiInteractionPart['INTERACTION_PART_RESPONSE'] }

before { allow(PactFfi).to receive(:with_header_v2).and_call_original }

it 'registers a single value at index 0' do
subject.with_request(method: :get, path: '/', headers: { 'X-Request' => 'a' })

expect(PactFfi).to have_received(:with_header_v2).with(anything, request_part, 'X-Request', 0, 'a').once
end

it 'registers each request header array element at its own index' do
subject.with_request(method: :get, path: '/', headers: { 'X-Request' => %w[a b] })

expect(PactFfi).to have_received(:with_header_v2).with(anything, request_part, 'X-Request', 0, 'a').ordered
expect(PactFfi).to have_received(:with_header_v2).with(anything, request_part, 'X-Request', 1, 'b').ordered
end

it 'serialises each matcher in a request header array at its own index' do
subject.with_request(method: :get, path: '/', headers: {
'X-Request' => [Pact::Matchers::V2::Regex.new(/^first-\d+$/, 'first-1'), 'b']
})

expect(PactFfi).to have_received(:with_header_v2)
.with(anything, request_part, 'X-Request', 0, satisfy { |v| JSON.parse(v)['pact:matcher:type'] == 'regex' })
expect(PactFfi).to have_received(:with_header_v2).with(anything, request_part, 'X-Request', 1, 'b')
end

it 'registers each response header array element at its own index' do
subject.will_respond_with(status: 200, headers: {
'X-Response' => ['a', Pact::Matchers::V2::Regex.new(/^first-\d+$/, 'first-1')]
})

expect(PactFfi).to have_received(:with_header_v2).with(anything, response_part, 'X-Response', 0, 'a')
expect(PactFfi).to have_received(:with_header_v2)
.with(anything, response_part, 'X-Response', 1, satisfy { |v| JSON.parse(v)['pact:matcher:type'] == 'regex' })
end
end
end
123 changes: 123 additions & 0 deletions spec/pact/providers/repeated-headers/http_repeated_headers_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# frozen_string_literal: true

require 'pact/rspec'
require 'socket'
require 'tmpdir'

# Repeated HTTP headers (RFC 9110 §5.3, pact-reference#568 / #584).
#
# An Array header value declares one expected value per index. Requests are written over a
# raw TCP socket so every field line reaches the mock server as its own line (HTTP clients
# merge, reorder or reject repeated header lines).
#
# Some of these cases (e.g. H2, one comma-separated field line) need a pact_ffi that
# includes pact-reference#584.
RSpec.describe 'PactProviders::RepeatedHeaders', :pact do
pact_dir = Dir.mktmpdir('pact-repeated-headers')

has_http_pact_between 'pact-ruby-repeated-headers-consumer', 'pact-ruby-repeated-headers-provider', opts: {
pact_specification: 'V3',
pact_dir: pact_dir
}

after(:context) { FileUtils.rm_rf(pact_dir) }

# Sends GET /headers with one `header` field line per entry in field_lines.
# Returns [status, response header field lines].
def send_raw(port, header, field_lines)
socket = TCPSocket.new('127.0.0.1', port)
request = +"GET /headers HTTP/1.1\r\nHost: 127.0.0.1:#{port}\r\n"
field_lines.each { |line| request << "#{header}: #{line}\r\n" }
request << "Connection: close\r\n\r\n"
socket.write(request)
response = socket.read
socket.close
head = response.split("\r\n\r\n", 2).first.split("\r\n")
[head.first.split[1].to_i, head.drop(1)]
end

def repeated_request(header, values)
new_interaction
.upon_receiving("a request with a repeated #{header} header")
.with_request(method: :get, path: '/headers', headers: { header => values })
.will_respond_with(status: 200)
end

context 'with repeated request headers' do
it 'H1: matches values sent on separate field lines' do
repeated_request('X-Request', %w[a b]).execute do |mock_server|
expect(send_raw(mock_server.port, 'X-Request', %w[a b]).first).to eq(200)
end
end

it 'H2: matches values sent as one comma-separated field line' do
repeated_request('X-Request', %w[a b]).execute do |mock_server|
expect(send_raw(mock_server.port, 'X-Request', ['a, b']).first).to eq(200)
end
end

it 'H4: does not match a single-value header sent as one comma-separated field line' do
expect do
repeated_request('Content-Type', ['text/plain', 'text/html']).execute do |mock_server|
expect(send_raw(mock_server.port, 'Content-Type', ['text/plain, text/html']).first).not_to eq(200)
end
end.to raise_error(Pact::Consumer::HttpInteractionBuilder::InteractionMismatchesError)
end

it 'H6a: applies one matcher per index' do
values = [match_regex(/^first-\d+$/, 'first-1'), match_regex(/^first-\d+$/, 'first-2')]
repeated_request('X-Request', values).execute do |mock_server|
expect(send_raw(mock_server.port, 'X-Request', %w[first-42 first-99]).first).to eq(200)
end
end

it 'applies a different matcher at each index' do
values = [match_regex(/^first-\d+$/, 'first-1'), match_regex(/^second-\d+$/, 'second-1')]
repeated_request('X-Request', values).execute do |mock_server|
expect(send_raw(mock_server.port, 'X-Request', %w[first-42 second-99]).first).to eq(200)
end
end

it 'rejects values that do not match the matcher at their index' do
values = [match_regex(/^first-\d+$/, 'first-1'), match_regex(/^second-\d+$/, 'second-1')]
expect do
repeated_request('X-Request', values).execute do |mock_server|
expect(send_raw(mock_server.port, 'X-Request', %w[second-99 first-42]).first).not_to eq(200)
end
end.to raise_error(Pact::Consumer::HttpInteractionBuilder::InteractionMismatchesError)
end

it 'mixes literals and matchers' do
values = ['a', match_regex(/^second-\d+$/, 'second-1')]
repeated_request('X-Request', values).execute do |mock_server|
expect(send_raw(mock_server.port, 'X-Request', %w[a second-99]).first).to eq(200)
end
end

it 'H8b: matches Link values sent as one field line' do
links = ['<https://a.example/x,y>; rel="a"', '<https://b.example/>; rel="b"']
repeated_request('Link', links).execute do |mock_server|
expect(send_raw(mock_server.port, 'Link', [links.join(', ')]).first).to eq(200)
end
end
end

context 'with repeated response headers' do
it 'returns one value per index, including the example of a matcher' do
new_interaction
.upon_receiving('a request for a response with a repeated header')
.with_request(method: :get, path: '/headers')
.will_respond_with(status: 200, headers: {
'X-Response' => ['a', match_regex(/^second-\d+$/, 'second-1')]
})
.execute do |mock_server|
status, header_lines = send_raw(mock_server.port, 'X-Other', [])
values = header_lines.grep(/\Ax-response:/i)
.flat_map { |line| line.split(':', 2).last.split(',').map(&:strip) }

expect(status).to eq(200)
expect(values).to eq(%w[a second-1])
end
end
end
end
Loading