<commit_before>require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))

RSpec.describe HTTParty::Request do
  before do
    @request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml)
  end

  describe "::NON_RAILS_QUERY_STRING_NORMALIZER" do
    let(:normalizer) { HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER }

    it "doesn't modify strings" do
      query_string = normalizer["foo=bar&foo=baz"]
      expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz")
    end

    context "when the query is an array" do
      it "doesn't include brackets" do
        query_string = normalizer[{page: 1, foo: %w(bar baz)}]
        expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz&page=1")
      end

      it "URI encodes array values" do
        query_string = normalizer[{people: ["<NAME>", "<NAME>", "Tim & Jon"], page: 1, xyzzy: 3}]
        expect(query_string).to eq("page=1&people=Otis%20Redding&people=Bob%20Marley&people=Tim%20%26%20Jon&xyzzy=3")
      end
    end

    context "when the query is a hash" do
      it "correctly handles nil values" do
        query_string = normalizer[{page: 1, per_page: nil}]
        expect(query_string).to eq("page=1&per_page")
      end
    end
  end

  describe "initialization" do
    it "sets parser to HTTParty::Parser" do
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
      expect(request.parser).to eq(HTTParty::Parser)
    end

    it "sets parser to the optional parser" do
      my_parser = lambda {}
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', parser: my_parser)
      expect(request.parser).to eq(my_parser)
    end

    it "sets connection_adapter to HTTPParty::ConnectionAdapter" do
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
      expect(request.connection_adapter).to eq(HTTParty::ConnectionAdapter)
    end

    it "sets connection_adapter to the optional connection_adapter" do
      my_adapter = lambda {}
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', connection_adapter: my_adapter)
      expect(request.connection_adapter).to eq(my_adapter)
    end

    context "when using a query string" do
      context "and it has an empty array" do
        it "sets correct query string" do
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [] })

          expect(request.uri).to eq(URI.parse("http://google.com/?fake_array[]="))
        end
      end

      context "when sending an array with only one element" do
        it "sets correct query" do
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [1] })

          expect(request.uri).to eq(URI.parse("http://google.com/?fake_array[]=1"))
        end
      end
    end

    context "when basic authentication credentials provided in uri" do
      context "when basic auth options wasn't set explicitly" do
        it "sets basic auth from uri" do
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@<EMAIL>')
          expect(request.options[:basic_auth]).to eq({username: 'user1', password: '<PASSWORD>'})
        end
      end

      context "when basic auth options was set explicitly" do
        it "uses basic auth from url anyway" do
          basic_auth = {username: 'user2', password: '<PASSWORD>'}
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@<EMAIL>', basic_auth: basic_auth)
          expect(request.options[:basic_auth]).to eq({username: 'user1', password: '<PASSWORD>'})
        end
      end
    end
  end

  describe "#format" do
    context "request yet to be made" do
      it "returns format option" do
        request = HTTParty::Request.new 'get', '/', format: :xml
        expect(request.format).to eq(:xml)
      end

      it "returns nil format" do
        request = HTTParty::Request.new 'get', '/'
        expect(request.format).to be_nil
      end
    end

    context "request has been made" do
      it "returns format option" do
        request = HTTParty::Request.new 'get', '/', format: :xml
        request.last_response = double
        expect(request.format).to eq(:xml)
      end

      it "returns the content-type from the last response when the option is not set" do
        request = HTTParty::Request.new 'get', '/'
        response = double
        expect(response).to receive(:[]).with('content-type').and_return('text/json')
        request.last_response = response
        expect(request.format).to eq(:json)
      end
    end
  end

  context "options" do
    it "should use basic auth when configured" do
      @request.options[:basic_auth] = {username: 'foobar', password: '<PASSWORD>'}
      @request.send(:setup_raw_request)
      expect(@request.instance_variable_get(:@raw_request)['authorization']).not_to be_nil
    end

    context 'digest_auth' do 
      before do 
        response_sequence = [
          {status: ['401', 'Unauthorized' ], 
            www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
            set_cookie: 'custom-cookie=1234567', 
          },
          {status: ['200', 'OK']}
        ]      
        FakeWeb.register_uri(:get, "http://api.foo.com/v1",
                            response_sequence)
      end 

      it 'should not send credentials more than once' do
        response_sequence = [
          {status: ['401', 'Unauthorized' ], 
            www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
            set_cookie: 'custom-cookie=1234567', 
          },
          {status: ['401', 'Unauthorized' ], 
            www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
            set_cookie: 'custom-cookie=1234567', 
          },      
          {status: ['404', 'Not found']}
        ]      
        FakeWeb.register_uri(:get, "http://api.foo.com/v1",
                            response_sequence)

        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform { |v| }
        expect(response.code).to eq(401)

        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request['Authorization']).not_to be_nil                    
      end 

      it 'should not be used when configured and the response is 200' do
        FakeWeb.register_uri(:get, "http://api.foo.com/v1",
          status: 200)
        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform { |v| }
        expect(response.code).to eq(200)


        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request['Authorization']).to be_nil
      end

      it "should be used when configured and the response is 401" do
        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform { |v| }
        expect(response.code).to eq(200)

        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request['Authorization']).not_to be_nil
      end

      it 'should maintain cookies returned from a 401 response' do
        require 'pry'

        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform {|v|}
        expect(response.code).to eq(200)
        
        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request.get_fields('cookie')).to eql ["custom-cookie=1234567"]
      end

      it 'should merge cookies from request and a 401 response' do
        <commit_msg>Remove accidental 'require'<commit_after>require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))

RSpec.describe HTTParty::Request do
  before do
    @request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml)
  end

  describe "::NON_RAILS_QUERY_STRING_NORMALIZER" do
    let(:normalizer) { HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER }

    it "doesn't modify strings" do
      query_string = normalizer["foo=bar&foo=baz"]
      expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz")
    end

    context "when the query is an array" do
      it "doesn't include brackets" do
        query_string = normalizer[{page: 1, foo: %w(bar baz)}]
        expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz&page=1")
      end

      it "URI encodes array values" do
        query_string = normalizer[{people: ["<NAME>", "<NAME>", "Tim & Jon"], page: 1, xyzzy: 3}]
        expect(query_string).to eq("page=1&people=Otis%20Redding&people=Bob%20Marley&people=Tim%20%26%20Jon&xyzzy=3")
      end
    end

    context "when the query is a hash" do
      it "correctly handles nil values" do
        query_string = normalizer[{page: 1, per_page: nil}]
        expect(query_string).to eq("page=1&per_page")
      end
    end
  end

  describe "initialization" do
    it "sets parser to HTTParty::Parser" do
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
      expect(request.parser).to eq(HTTParty::Parser)
    end

    it "sets parser to the optional parser" do
      my_parser = lambda {}
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', parser: my_parser)
      expect(request.parser).to eq(my_parser)
    end

    it "sets connection_adapter to HTTPParty::ConnectionAdapter" do
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
      expect(request.connection_adapter).to eq(HTTParty::ConnectionAdapter)
    end

    it "sets connection_adapter to the optional connection_adapter" do
      my_adapter = lambda {}
      request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', connection_adapter: my_adapter)
      expect(request.connection_adapter).to eq(my_adapter)
    end

    context "when using a query string" do
      context "and it has an empty array" do
        it "sets correct query string" do
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [] })

          expect(request.uri).to eq(URI.parse("http://google.com/?fake_array[]="))
        end
      end

      context "when sending an array with only one element" do
        it "sets correct query" do
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [1] })

          expect(request.uri).to eq(URI.parse("http://google.com/?fake_array[]=1"))
        end
      end
    end

    context "when basic authentication credentials provided in uri" do
      context "when basic auth options wasn't set explicitly" do
        it "sets basic auth from uri" do
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com')
          expect(request.options[:basic_auth]).to eq({username: 'user1', password: '<PASSWORD>'})
        end
      end

      context "when basic auth options was set explicitly" do
        it "uses basic auth from url anyway" do
          basic_auth = {username: 'user2', password: '<PASSWORD>'}
          request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com', basic_auth: basic_auth)
          expect(request.options[:basic_auth]).to eq({username: 'user1', password: '<PASSWORD>'})
        end
      end
    end
  end

  describe "#format" do
    context "request yet to be made" do
      it "returns format option" do
        request = HTTParty::Request.new 'get', '/', format: :xml
        expect(request.format).to eq(:xml)
      end

      it "returns nil format" do
        request = HTTParty::Request.new 'get', '/'
        expect(request.format).to be_nil
      end
    end

    context "request has been made" do
      it "returns format option" do
        request = HTTParty::Request.new 'get', '/', format: :xml
        request.last_response = double
        expect(request.format).to eq(:xml)
      end

      it "returns the content-type from the last response when the option is not set" do
        request = HTTParty::Request.new 'get', '/'
        response = double
        expect(response).to receive(:[]).with('content-type').and_return('text/json')
        request.last_response = response
        expect(request.format).to eq(:json)
      end
    end
  end

  context "options" do
    it "should use basic auth when configured" do
      @request.options[:basic_auth] = {username: 'foobar', password: '<PASSWORD>'}
      @request.send(:setup_raw_request)
      expect(@request.instance_variable_get(:@raw_request)['authorization']).not_to be_nil
    end

    context 'digest_auth' do 
      before do 
        response_sequence = [
          {status: ['401', 'Unauthorized' ], 
            www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
            set_cookie: 'custom-cookie=1234567', 
          },
          {status: ['200', 'OK']}
        ]      
        FakeWeb.register_uri(:get, "http://api.foo.com/v1",
                            response_sequence)
      end 

      it 'should not send credentials more than once' do
        response_sequence = [
          {status: ['401', 'Unauthorized' ], 
            www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
            set_cookie: 'custom-cookie=1234567', 
          },
          {status: ['401', 'Unauthorized' ], 
            www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
            set_cookie: 'custom-cookie=1234567', 
          },      
          {status: ['404', 'Not found']}
        ]      
        FakeWeb.register_uri(:get, "http://api.foo.com/v1",
                            response_sequence)

        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform { |v| }
        expect(response.code).to eq(401)

        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request['Authorization']).not_to be_nil                    
      end 

      it 'should not be used when configured and the response is 200' do
        FakeWeb.register_uri(:get, "http://api.foo.com/v1",
          status: 200)
        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform { |v| }
        expect(response.code).to eq(200)


        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request['Authorization']).to be_nil
      end

      it "should be used when configured and the response is 401" do
        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform { |v| }
        expect(response.code).to eq(200)

        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request['Authorization']).not_to be_nil
      end

      it 'should maintain cookies returned from a 401 response' do
        @request.options[:digest_auth] = {username: 'foobar', password: '<PASSWORD>'}        
        response = @request.perform {|v|}
        expect(response.code).to eq(200)
        
        raw_request = @request.instance_variable_get(:@raw_request)
        expect(raw_request.get_fields('cookie')).to eql ["custom-cookie=1234567"]
      end

      it 'should merge cookies from request and a 401 response' do
        
{'fraction_non_alphanumeric': 0.13001313896014516, 'fraction_numerical': 0.02727898392041544, 'mean_word_length': 2.859005311443747, 'pattern_counts': {'":': 2, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 10}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5083310', 'n_tokens_mistral': 5245, 'n_tokens_neox': 4849, 'n_words': 1144}