How to use headers method of WebMock Package

Best Webmock_ruby code snippet using WebMock.headers

curb_adapter.rb

Source:curb_adapter.rb Github

copy

Full Screen

...20 end21 # Borrowed from Patron:22 # http://github.com/toland/patron/blob/master/lib/patron/response.rb23 def self.parse_header_string(header_string)24 status, headers = nil, {}25 header_string.split(/\r\n/).each do |header|26 if header =~ %r|^HTTP/1.[01] \d\d\d (.*)|27 status = $128 else29 parts = header.split(':', 2)30 unless parts.empty?31 parts[1].strip! unless parts[1].nil?32 if headers.has_key?(parts[0])33 headers[parts[0]] = [headers[parts[0]]] unless headers[parts[0]].kind_of? Array34 headers[parts[0]] << parts[1]35 else36 headers[parts[0]] = parts[1]37 end38 end39 end40 end41 return status, headers42 end43 end44 end45 end46 module Curl47 class WebMockCurlEasy < Curl::Easy48 def curb_or_webmock49 request_signature = build_request_signature50 WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)51 if webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)52 build_curb_response(webmock_response)53 WebMock::CallbackRegistry.invoke_callbacks(54 {lib: :curb}, request_signature, webmock_response)55 invoke_curb_callbacks56 true57 elsif WebMock.net_connect_allowed?(request_signature.uri)58 res = yield59 if WebMock::CallbackRegistry.any_callbacks?60 webmock_response = build_webmock_response61 WebMock::CallbackRegistry.invoke_callbacks(62 {lib: :curb, real_request: true}, request_signature,63 webmock_response)64 end65 res66 else67 raise WebMock::NetConnectNotAllowedError.new(request_signature)68 end69 end70 def build_request_signature71 method = @webmock_method.to_s.downcase.to_sym72 uri = WebMock::Util::URI.heuristic_parse(self.url)73 uri.path = uri.normalized_path.gsub("[^:]//","/")74 headers = headers_as_hash(self.headers).merge(basic_auth_headers)75 request_body = case method76 when :post, :patch77 self.post_body || @post_body78 when :put79 @put_data80 else81 nil82 end83 if defined?( @on_debug )84 @on_debug.call("Trying 127.0.0.1...\r\n", 0)85 @on_debug.call('Connected to ' + uri.hostname + "\r\n", 0)86 @debug_method = method.upcase87 @debug_path = uri.path88 @debug_host = uri.hostname89 http_request = ["#{@debug_method} #{@debug_path} HTTP/1.1"]90 http_request << "Host: #{uri.hostname}"91 headers.each do |name, value|92 http_request << "#{name}: #{value}"93 end94 @on_debug.call(http_request.join("\r\n") + "\r\n\r\n", 2)95 if request_body96 @on_debug.call(request_body + "\r\n", 4)97 @on_debug.call(98 "upload completely sent off: #{request_body.bytesize}"\99 " out of #{request_body.bytesize} bytes\r\n", 0100 )101 end102 end103 request_signature = WebMock::RequestSignature.new(104 method,105 uri.to_s,106 body: request_body,107 headers: headers108 )109 request_signature110 end111 def headers_as_hash(headers)112 if headers.is_a?(Array)113 headers.inject({}) {|hash, header|114 name, value = header.split(":").map(&:strip)115 hash[name] = value116 hash117 }118 else119 headers120 end121 end122 def basic_auth_headers123 if self.username124 {'Authorization' => WebMock::Util::Headers.basic_auth_header(self.username, self.password)}125 else126 {}127 end128 end129 def build_curb_response(webmock_response)130 raise Curl::Err::TimeoutError if webmock_response.should_timeout131 webmock_response.raise_error_if_any132 @body_str = webmock_response.body133 @response_code = webmock_response.status[0]134 @header_str = "HTTP/1.1 #{webmock_response.status[0]} #{webmock_response.status[1]}\r\n".dup135 @on_debug.call(@header_str, 1) if defined?( @on_debug )136 if webmock_response.headers137 @header_str << webmock_response.headers.map do |k,v|138 header = "#{k}: #{v.is_a?(Array) ? v.join(", ") : v}"139 @on_debug.call(header + "\r\n", 1) if defined?( @on_debug )140 header141 end.join("\r\n")142 @on_debug.call("\r\n", 1) if defined?( @on_debug )143 location = webmock_response.headers['Location']144 if self.follow_location? && location145 @last_effective_url = location146 webmock_follow_location(location)147 end148 @content_type = webmock_response.headers["Content-Type"]149 @transfer_encoding = webmock_response.headers["Transfer-Encoding"]150 end151 @last_effective_url ||= self.url152 end153 def webmock_follow_location(location)154 first_url = self.url155 self.url = location156 curb_or_webmock do157 send( :http, {'method' => @webmock_method} )158 end159 self.url = first_url160 end161 def invoke_curb_callbacks162 @on_progress.call(0.0,1.0,0.0,1.0) if defined?( @on_progress )163 self.header_str.lines.each { |header_line| @on_header.call header_line } if defined?( @on_header )164 if defined?( @on_body )165 if chunked_response?166 self.body_str.each do |chunk|167 @on_body.call(chunk)168 end169 else170 @on_body.call(self.body_str)171 end172 end173 @on_complete.call(self) if defined?( @on_complete )174 case response_code175 when 200..299176 @on_success.call(self) if defined?( @on_success )177 when 400..499178 @on_missing.call(self, self.response_code) if defined?( @on_missing )179 when 500..599180 @on_failure.call(self, self.response_code) if defined?( @on_failure )181 end182 end183 def chunked_response?184 defined?( @transfer_encoding ) && @transfer_encoding == 'chunked' && self.body_str.respond_to?(:each)185 end186 def build_webmock_response187 status, headers =188 WebMock::HttpLibAdapters::CurbAdapter.parse_header_string(self.header_str)189 if defined?( @on_debug )190 http_response = ["HTTP/1.0 #{@debug_method} #{@debug_path}"]191 headers.each do |name, value|192 http_response << "#{name}: #{value}"193 end194 http_response << self.body_str195 @on_debug.call(http_response.join("\r\n") + "\r\n", 3)196 @on_debug.call("Connection #0 to host #{@debug_host} left intact\r\n", 0)197 end198 webmock_response = WebMock::Response.new199 webmock_response.status = [self.response_code, status]200 webmock_response.body = self.body_str201 webmock_response.headers = headers202 webmock_response203 end204 ###205 ### Mocks of Curl::Easy methods below here.206 ###207 def http(method)208 @webmock_method = method209 super210 end211 %w[ get head delete ].each do |verb|212 define_method "http_#{verb}" do213 @webmock_method = verb214 super()215 end...

Full Screen

Full Screen

typhoeus_hydra_adapter.rb

Source:typhoeus_hydra_adapter.rb Github

copy

Full Screen

...42 end43 def self.build_request_signature(req)44 uri = WebMock::Util::URI.heuristic_parse(req.url)45 uri.path = uri.normalized_path.gsub("[^:]//","/")46 headers = req.options[:headers]47 if req.options[:userpwd]48 headers['Authorization'] = WebMock::Util::Headers.basic_auth_header(req.options[:userpwd])49 end50 body = req.options[:body]51 if body.is_a?(Hash)52 body = WebMock::Util::QueryMapper.values_to_query(body)53 end54 request_signature = WebMock::RequestSignature.new(55 req.options[:method] || :get,56 uri.to_s,57 body: body,58 headers: headers59 )60 req.instance_variable_set(:@__webmock_request_signature, request_signature)61 request_signature62 end63 def self.build_webmock_response(typhoeus_response)64 webmock_response = WebMock::Response.new65 webmock_response.status = [typhoeus_response.code, typhoeus_response.status_message]66 webmock_response.body = typhoeus_response.body67 webmock_response.headers = typhoeus_response.headers68 webmock_response69 end70 def self.generate_typhoeus_response(request_signature, webmock_response)71 response = if webmock_response.should_timeout72 ::Typhoeus::Response.new(73 code: 0,74 status_message: "",75 body: "",76 headers: {},77 return_code: :operation_timedout78 )79 else80 ::Typhoeus::Response.new(81 code: webmock_response.status[0],82 status_message: webmock_response.status[1],83 body: webmock_response.body,84 headers: webmock_response.headers,85 effective_url: request_signature.uri86 )87 end88 response.mock = :webmock89 response90 end91 def self.request_hash(request_signature)92 hash = {}93 hash[:body] = request_signature.body94 hash[:headers] = request_signature.headers95 hash96 end97 AFTER_REQUEST_CALLBACK = Proc.new do |response|98 request = response.request99 request_signature = request.instance_variable_get(:@__webmock_request_signature)100 webmock_response =101 ::WebMock::HttpLibAdapters::TyphoeusAdapter.102 build_webmock_response(response)103 if response.mock104 WebMock::CallbackRegistry.invoke_callbacks(105 {lib: :typhoeus},106 request_signature,107 webmock_response108 )109 else110 WebMock::CallbackRegistry.invoke_callbacks(111 {lib: :typhoeus, real_request: true},112 request_signature,113 webmock_response114 )115 end116 end117 BEFORE_CALLBACK = Proc.new do |request|118 Typhoeus::Expectation.all.delete_if {|e| e.from == :webmock }119 res = true120 unless WebMock::HttpLibAdapters::TyphoeusAdapter.disabled?121 request_signature = ::WebMock::HttpLibAdapters::TyphoeusAdapter.build_request_signature(request)122 request.block_connection = false;123 ::WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)124 if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature)125 # ::WebMock::HttpLibAdapters::TyphoeusAdapter.stub_typhoeus(request_signature, webmock_response, self)126 response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(request_signature, webmock_response)127 if request.respond_to?(:on_headers)128 request.execute_headers_callbacks(response)129 end130 if request.respond_to?(:streaming?) && request.streaming?131 response.options[:response_body] = ""132 request.on_body.each { |callback| callback.call(webmock_response.body, response) }133 end134 request.finish(response)135 webmock_response.raise_error_if_any136 res = false137 elsif !WebMock.net_connect_allowed?(request_signature.uri)138 raise WebMock::NetConnectNotAllowedError.new(request_signature)139 end140 end141 res142 end...

Full Screen

Full Screen

webmock.rb

Source:webmock.rb Github

copy

Full Screen

...23 VCR::Request.new \24 webmock_request.method,25 webmock_request.uri.to_s,26 webmock_request.body,27 request_headers_for(webmock_request)28 end29 # @private30 def vcr_response_for(webmock_response)31 VCR::Response.new \32 VCR::ResponseStatus.new(*webmock_response.status),33 webmock_response.headers,34 webmock_response.body,35 nil36 end37 if defined?(::Excon)38 # @private39 def request_headers_for(webmock_request)40 return nil unless webmock_request.headers41 # WebMock hooks deeply into a Excon at a place where it manually adds a "Host"42 # header, but this isn't a header we actually care to store...43 webmock_request.headers.dup.tap do |headers|44 headers.delete("Host")45 end46 end47 else48 # @private49 def request_headers_for(webmock_request)50 webmock_request.headers51 end52 end53 def typed_request_for(webmock_request, remove = false)54 if webmock_request.instance_variables.find { |v| v.to_sym == :@__typed_vcr_request }55 meth = remove ? :remove_instance_variable : :instance_variable_get56 return webmock_request.send(meth, :@__typed_vcr_request)57 end58 warn <<-EOS.gsub(/^\s+\|/, '')59 |WARNING: There appears to be a bug in WebMock's after_request hook60 | and VCR is attempting to work around it. Some VCR features61 | may not work properly.62 EOS63 Request::Typed.new(vcr_request_for(webmock_request), :unknown)64 end65 end66 class RequestHandler < ::VCR::RequestHandler67 include Helpers68 attr_reader :request69 def initialize(request)70 @request = request71 end72 private73 def externally_stubbed?74 # prevent infinite recursion...75 VCR::LibraryHooks::WebMock.with_global_hook_disabled do76 ::WebMock.registered_request?(request)77 end78 end79 def set_typed_request_for_after_hook(*args)80 super81 request.instance_variable_set(:@__typed_vcr_request, @after_hook_typed_request)82 end83 def vcr_request84 @vcr_request ||= vcr_request_for(request)85 end86 def on_externally_stubbed_request87 # nil allows WebMock to handle the request88 nil89 end90 def on_unhandled_request91 invoke_after_request_hook(nil)92 super93 end94 def on_stubbed_by_vcr_request95 {96 :body => stubbed_response.body,97 :status => [stubbed_response.status.code.to_i, stubbed_response.status.message],98 :headers => stubbed_response.headers99 }100 end101 end102 extend Helpers103 ::WebMock.globally_stub_request do |req|104 global_hook_disabled? ? nil : RequestHandler.new(req).handle105 end106 ::WebMock.after_request(:real_requests_only => true) do |request, response|107 unless VCR.library_hooks.disabled?(:webmock)108 http_interaction = VCR::HTTPInteraction.new \109 typed_request_for(request), vcr_response_for(response)110 VCR.record_http_interaction(http_interaction)111 end112 end...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Webmock_ruby automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful