How to use body_from method of Header Package

Best Vcr_ruby code snippet using Header.body_from

structs.rb

Source:structs.rb Github

copy

Full Screen

...18 klass.extend ClassMethods19 end20 # @private21 module ClassMethods22 def body_from(hash_or_string)23 # ...24 return hash_or_string unless hash_or_string.is_a?(Hash)25 hash = hash_or_string26 if hash.has_key?('base64_string')27 string = Base64.decode64(hash['base64_string'])28 force_encode_string(string, hash['encoding'])29 else30 try_encode_string(hash['string'], hash['encoding'])31 end32 end33 if "".respond_to?(:encoding)34 def force_encode_string(string, encoding)35 return string unless encoding36 string.force_encoding(encoding)37 end38 def try_encode_string(string, encoding)39 return string if encoding.nil? || string.encoding.name == encoding40 # ASCII-8BIT just means binary, so encoding to it is nonsensical41 # and yet "\u00f6".encode("ASCII-8BIT") raises an error.42 # Instead, we'll force encode it (essentially just tagging it as binary)43 return string.force_encoding(encoding) if encoding == "ASCII-8BIT"44 string.encode(encoding)45 rescue EncodingError => e46 struct_type = name.split('::').last.downcase47 warn "VCR: got `#{e.class.name}: #{e.message}` while trying to encode the #{string.encoding.name} " +48 "#{struct_type} body to the original body encoding (#{encoding}). Consider using the " +49 "`:preserve_exact_body_bytes` option to work around this."50 return string51 end52 else53 def force_encode_string(string, encoding)54 string55 end56 def try_encode_string(string, encoding)57 string58 end59 end60 end61 def initialize(*args)62 super63 if body && !body.is_a?(String)64 raise ArgumentError, "#{self.class} initialized with an invalid body: #{body.inspect}."65 end66 # Ensure that the body is a raw string, in case the string instance67 # has been subclassed or extended with additional instance variables68 # or attributes, so that it is serialized to YAML as a raw string.69 # This is needed for rest-client. See this ticket for more info:70 # http://github.com/myronmarston/vcr/issues/471 self.body = String.new(body.to_s)72 end73 private74 def serializable_body75 if VCR.configuration.preserve_exact_body_bytes_for?(self)76 base_body_hash(body).merge('base64_string' => Base64.encode64(body))77 else78 base_body_hash(body).merge('string' => body)79 end80 end81 if ''.respond_to?(:encoding)82 def base_body_hash(body)83 { 'encoding' => body.encoding.name }84 end85 else86 def base_body_hash(body)87 { }88 end89 end90 end91 # @private92 module Header93 def initialize(*args)94 super95 normalize_headers96 end97 private98 def normalize_headers99 new_headers = {}100 @normalized_header_keys = Hash.new {|h,k| k }101 headers.each do |k, v|102 val_array = case v103 when Array then v104 when nil then []105 else [v]106 end107 new_headers[String.new(k)] = convert_to_raw_strings(val_array)108 @normalized_header_keys[k.downcase] = k109 end if headers110 self.headers = new_headers111 end112 def header_key(key)113 key = @normalized_header_keys[key.downcase]114 key if headers.has_key? key115 end116 def get_header(key)117 key = header_key(key)118 headers[key] if key119 end120 def edit_header(key, value = nil)121 if key = header_key(key)122 value ||= yield headers[key]123 headers[key] = Array(value)124 end125 end126 def delete_header(key)127 if key = header_key(key)128 @normalized_header_keys.delete key.downcase129 headers.delete key130 end131 end132 def convert_to_raw_strings(array)133 # Ensure the values are raw strings.134 # Apparently for Paperclip uploads to S3, headers135 # get serialized with some extra stuff which leads136 # to a seg fault. See this issue for more info:137 # https://github.com/myronmarston/vcr/issues#issue/39138 array.map do |v|139 case v140 when String; String.new(v)141 when Array; convert_to_raw_strings(v)142 else v143 end144 end145 end146 end147 end148 # @private149 module OrderedHashSerializer150 def each151 @ordered_keys.each do |key|152 yield key, self[key]153 end154 end155 if RUBY_VERSION.to_f > 1.8156 # 1.9+ hashes are already ordered.157 def self.apply_to(*args); end158 else159 def self.apply_to(hash, keys)160 hash.instance_variable_set(:@ordered_keys, keys)161 hash.extend self162 end163 end164 end165 # The request of an {HTTPInteraction}.166 #167 # @attr [Symbol] method the HTTP method (i.e. :head, :options, :get, :post, :put, :patch or :delete)168 # @attr [String] uri the request URI169 # @attr [String, nil] body the request body170 # @attr [Hash{String => Array<String>}] headers the request headers171 class Request < Struct.new(:method, :uri, :body, :headers)172 include Normalizers::Header173 include Normalizers::Body174 def initialize(*args)175 skip_port_stripping = false176 if args.last == :skip_port_stripping177 skip_port_stripping = true178 args.pop179 end180 super(*args)181 self.method = self.method.to_s.downcase.to_sym if self.method182 self.uri = without_standard_port(self.uri) unless skip_port_stripping183 end184 # Builds a serializable hash from the request data.185 #186 # @return [Hash] hash that represents this request and can be easily187 # serialized.188 # @see Request.from_hash189 def to_hash190 {191 'method' => method.to_s,192 'uri' => uri,193 'body' => serializable_body,194 'headers' => headers195 }.tap { |h| OrderedHashSerializer.apply_to(h, members) }196 end197 # Constructs a new instance from a hash.198 #199 # @param [Hash] hash the hash to use to construct the instance.200 # @return [Request] the request201 def self.from_hash(hash)202 method = hash['method']203 method &&= method.to_sym204 new method,205 hash['uri'],206 body_from(hash['body']),207 hash['headers'],208 :skip_port_stripping209 end210 # Parses the URI using the configured `uri_parser`.211 #212 # @return [#schema, #host, #port, #path, #query] A parsed URI object.213 def parsed_uri214 VCR.configuration.uri_parser.parse(uri)215 end216 @@object_method = Object.instance_method(:method)217 def method(*args)218 return super if args.empty?219 @@object_method.bind(self).call(*args)220 end221 # Decorates a {Request} with its current type.222 class Typed < DelegateClass(self)223 # @return [Symbol] One of `:ignored`, `:stubbed`, `:recordable` or `:unhandled`.224 attr_reader :type225 # @param [Request] request the request226 # @param [Symbol] type the type. Should be one of `:ignored`, `:stubbed`, `:recordable` or `:unhandled`.227 def initialize(request, type)228 @type = type229 super(request)230 end231 # @return [Boolean] whether or not this request is being ignored232 def ignored?233 type == :ignored234 end235 # @return [Boolean] whether or not this request is being stubbed by VCR236 # @see #externally_stubbed?237 # @see #stubbed?238 def stubbed_by_vcr?239 type == :stubbed_by_vcr240 end241 # @return [Boolean] whether or not this request is being stubbed by an242 # external library (such as WebMock or FakeWeb).243 # @see #stubbed_by_vcr?244 # @see #stubbed?245 def externally_stubbed?246 type == :externally_stubbed247 end248 # @return [Boolean] whether or not this request will be recorded.249 def recordable?250 type == :recordable251 end252 # @return [Boolean] whether or not VCR knows how to handle this request.253 def unhandled?254 type == :unhandled255 end256 # @return [Boolean] whether or not this request will be made for real.257 # @note VCR allows `:ignored` and `:recordable` requests to be made for real.258 def real?259 ignored? || recordable?260 end261 # @return [Boolean] whether or not this request will be stubbed.262 # It may be stubbed by an external library or by VCR.263 # @see #stubbed_by_vcr?264 # @see #externally_stubbed?265 def stubbed?266 stubbed_by_vcr? || externally_stubbed?267 end268 undef method269 end270 # Provides fiber-awareness for the {VCR::Configuration#around_http_request} hook.271 class FiberAware < DelegateClass(Typed)272 # Yields the fiber so the request can proceed.273 #274 # @return [VCR::Response] the response from the request275 def proceed276 Fiber.yield277 end278 # Builds a proc that allows the request to proceed when called.279 # This allows you to treat the request as a proc and pass it on280 # to a method that yields (at which point the request will proceed).281 #282 # @return [Proc] the proc283 def to_proc284 lambda { proceed }285 end286 undef method287 end288 private289 def without_standard_port(uri)290 return uri if uri.nil?291 u = parsed_uri292 return uri unless [['http', 80], ['https', 443]].include?([u.scheme, u.port])293 u.port = nil294 u.to_s295 end296 end297 # The response of an {HTTPInteraction}.298 #299 # @attr [ResponseStatus] status the status of the response300 # @attr [Hash{String => Array<String>}] headers the response headers301 # @attr [String] body the response body302 # @attr [nil, String] http_version the HTTP version303 class Response < Struct.new(:status, :headers, :body, :http_version)304 include Normalizers::Header305 include Normalizers::Body306 # Builds a serializable hash from the response data.307 #308 # @return [Hash] hash that represents this response309 # and can be easily serialized.310 # @see Response.from_hash311 def to_hash312 {313 'status' => status.to_hash,314 'headers' => headers,315 'body' => serializable_body,316 'http_version' => http_version317 }.tap { |h| OrderedHashSerializer.apply_to(h, members) }318 end319 # Constructs a new instance from a hash.320 #321 # @param [Hash] hash the hash to use to construct the instance.322 # @return [Response] the response323 def self.from_hash(hash)324 new ResponseStatus.from_hash(hash.fetch('status', {})),325 hash['headers'],326 body_from(hash['body']),327 hash['http_version']328 end329 # Updates the Content-Length response header so that it is330 # accurate for the response body.331 def update_content_length_header332 edit_header('Content-Length') { body ? body.bytesize.to_s : '0' }333 end334 # The type of encoding.335 #336 # @return [String] encoding type337 def content_encoding338 enc = get_header('Content-Encoding') and enc.first339 end340 # Checks if the type of encoding is one of "gzip" or "deflate"....

Full Screen

Full Screen

aggregate_failures.rb

Source:aggregate_failures.rb Github

copy

Full Screen

...63 end64 base_indent = " " * first_example.source_range.column65 replacements = [66 header_from(first_example),67 body_from(first_example, base_indent)68 ]69 last_example = nil70 loop do71 child = iter.next72 break unless oneliner?(child)73 last_example = child74 replacements << body_from(child, base_indent)75 end76 replacements << "#{base_indent}end"77 range = first_example.source_range.begin.join(78 last_example.source_range.end79 )80 replacement = replacements.join("\n")81 lambda do |corrector|82 corrector.replace(range, replacement)83 end84 end85 private86 def check_node(node)87 offenders = 088 node.children.each do |child|89 if oneliner?(child)90 offenders += 191 elsif example_node?(child)92 break if offenders > 193 offenders = 094 end95 end96 offenders < 297 end98 def oneliner?(node)99 node&.block_type? &&100 (node.source.lines.size == 1) &&101 example_node?(node)102 end103 def example_node?(node)104 method, _args, _body = *node105 _receiver, method_name, _object = *method106 EXAMPLE_BLOCKS.include?(method_name)107 end108 def header_from(node)109 method, _args, _body = *node110 _receiver, method_name, _object = *method111 method_name = :it if method_name == :its112 %(#{method_name} "works", :aggregate_failures do)113 end114 def body_from(node, base_indent = "")115 method, _args, body = *node116 body_source = method.method_name == :its ? body_from_its(method, body) : body.source117 "#{base_indent}#{indent}#{body_source}"118 end119 def body_from_its(method, body)120 subject_attribute = method.arguments.first121 expectation = body.method_name122 match = body.arguments.first.source123 if subject_attribute.array_type?124 hash_keys = subject_attribute.values.map(&:value).join(", ")125 attribute = "dig(#{hash_keys})"126 else127 attribute = subject_attribute.value128 end129 "expect(subject.#{attribute}).#{expectation} #{match}"130 end131 def indent132 @indent ||= " " * (config.for_cop("IndentationWidth")["Width"] || 2)133 end...

Full Screen

Full Screen

forwarder.rb

Source:forwarder.rb Github

copy

Full Screen

...24 # TODO: Consider moving these methods to the ProxES ES Service to enable reuse25 def perform_request(request)26 request.session['init'] = true # Initialize the session27 conn.send(request.request_method.downcase) do |req|28 body = body_from(request)29 req.body = body if body30 req.options.context = { user_id: request.session[:user_id] }31 req.url request.fullpath == '' ? URI.parse(env['REQUEST_URI']).request_uri : request.fullpath32 end33 end34 def rewrite_response(response)35 headers = (response.respond_to?(:headers) && response.headers) || normalize_headers(response.to_hash)36 body = response.body || ['']37 body = [body] unless body.respond_to?(:each)38 # Only keep certain headers.39 # See point 1 on https://www.mnot.net/blog/2011/07/11/what_proxies_must_do40 # TODO: Extend on the above41 headers.delete_if { |k, _v| !header_list.include? k.downcase }42 [response.status, headers, body]43 end44 def header_list45 [46 'date',47 'content-type',48 'cache-control'49 ]50 end51 def body_from(request)52 return if request.body.nil? || request.body.respond_to?(:read) == false53 request.body.read.tap { |_r| request.body.rewind }54 end55 def normalize_headers(headers)56 Rack::Utils::HeaderHash.new(57 headers.map do |k, v|58 [k, v.is_a?(Array) ? v.join("\n") : v]59 end.to_h60 )61 end62 end63end...

Full Screen

Full Screen

body_from

Using AI Code Generation

copy

Full Screen

1 def add_line(line)2 def add_line(line)3 @header.add_line(line) if line =~ /^From /4 @body.add_line(line) unless line =~ /^From /5 def add_line(line)6 def add_line(line)7 @header.add_line(line) if line =~ /^From /8 @body.add_line(line) unless line =~ /^From /9 def add_line(line)10 def add_line(line)11 @header.add_line(line) if line =~ /^From /12 @body.add_line(line) unless line =~ /^From /13 def add_line(line)

Full Screen

Full Screen

body_from

Using AI Code Generation

copy

Full Screen

1 def add_line(line)2 def add_line(line)3 @header.add_line(line) if line =~ /^From /4 @body.add_line(line) unless line =~ /^From /5puts h.body_from('header.txt')6 def body_from(file)

Full Screen

Full Screen

body_from

Using AI Code Generation

copy

Full Screen

1def get_body(email)2Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)3Net::POP3.start('pop.gmail.com', 995, 'user', 'password') do |pop|4 mail = Mail.read_from_string(email.pop)5 puts get_body(mail)6 def add_line(line)7 def add_line(line)8 @header.add_line(line) if line =~ /^From /9 @body.add_line(line) unless line =~ /^From /10 def add_line(line)11 def add_line(line)12 @header.add_line(line) if line =~ /^From /13 @body.add_line(line) unless line =~ /^From /14 def add_line(line)

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful