Skip to content

Commit

Permalink
Adds body and headers matching for VCR
Browse files Browse the repository at this point in the history
  • Loading branch information
petergoldstein committed Jan 22, 2023
1 parent ba9a729 commit 937926f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
5 changes: 4 additions & 1 deletion spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
require "ruby/openai"
require "vcr"

Dir[File.expand_path("spec/support/**/*.rb")].sort.each { |f| require f }

VCR.configure do |c|
c.hook_into :webmock
c.cassette_library_dir = "spec/fixtures/cassettes"
c.default_cassette_options = { record: ENV["NO_VCR"] == "true" ? :all : :new_episodes }
c.default_cassette_options = { record: ENV["NO_VCR"] == "true" ? :all : :new_episodes,
match_requests_on: [:method, :uri, VCRMultipartMatcher.new] }
c.filter_sensitive_data("<OPENAI_ACCESS_TOKEN>") { Ruby::OpenAI.configuration.access_token }
c.filter_sensitive_data("<OPENAI_ORGANIZATION_ID>") { Ruby::OpenAI.configuration.organization_id }
end
Expand Down
47 changes: 47 additions & 0 deletions spec/support/vcr_multipart_matcher.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class VCRMultipartMatcher
MULTIPART_HEADER_MATCHER = %r{^multipart/form-data; boundary=(.+)$}.freeze
BOUNDARY_SUBSTITUTION = "----MultipartBoundaryAbcD3fGhiXyz00001".freeze

def call(request1, request2)
return false unless same_content_type?(request1, request2)
unless headers_excluding_content_type(request1) == headers_excluding_content_type(request2)
return false
end

normalized_multipart_body(request1) == normalized_multipart_body(request2)
end

private

def same_content_type?(request1, request2)
content_type1 = (request1.headers["Content-Type"] || []).first.to_s
content_type2 = (request2.headers["Content-Type"] || []).first.to_s

if multipart_request?(content_type1)
multipart_request?(content_type2)
elsif multipart_request?(content_type2)
false
else
content_type1 == content_type2
end
end

def headers_excluding_content_type(request)
request.headers.except("Content-Type")
end

def normalized_multipart_body(request)
content_type = (request.headers["Content-Type"] || []).first.to_s

return request.headers unless multipart_request?(content_type)

boundary = MULTIPART_HEADER_MATCHER.match(content_type)[1]
request.body.gsub(boundary, BOUNDARY_SUBSTITUTION)
end

def multipart_request?(content_type)
return false if content_type.empty?

MULTIPART_HEADER_MATCHER.match?(content_type)
end
end

0 comments on commit 937926f

Please sign in to comment.