Skip to content

Commit

Permalink
[rb] Support overriding User-Agent in HTTP client
Browse files Browse the repository at this point in the history
  • Loading branch information
p0deje committed May 15, 2024
1 parent 4f72e3f commit 3ec3cef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
20 changes: 17 additions & 3 deletions rb/lib/selenium/webdriver/remote/http/common.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,16 @@ class Common
CONTENT_TYPE = 'application/json'
DEFAULT_HEADERS = {
'Accept' => CONTENT_TYPE,
'Content-Type' => "#{CONTENT_TYPE}; charset=UTF-8",
'User-Agent' => "selenium/#{WebDriver::VERSION} (ruby #{Platform.os})"
'Content-Type' => "#{CONTENT_TYPE}; charset=UTF-8"
}.freeze

class << self
attr_accessor :extra_headers
attr_writer :user_agent

def user_agent
@user_agent ||= "selenium/#{WebDriver::VERSION} (ruby #{Platform.os})"
end
end

attr_writer :server_url
Expand All @@ -46,7 +50,7 @@ def close

def call(verb, url, command_hash)
url = server_url.merge(url) unless url.is_a?(URI)
headers = DEFAULT_HEADERS.merge(Common.extra_headers || {}).dup
headers = common_headers.dup
headers['Cache-Control'] = 'no-cache' if verb == :get

if command_hash
Expand All @@ -65,6 +69,16 @@ def call(verb, url, command_hash)

private

def common_headers
@common_headers ||= begin
headers = DEFAULT_HEADERS.dup
headers['User-Agent'] = Common.user_agent
headers = headers.merge(Common.extra_headers || {})

headers
end
end

def server_url
return @server_url if @server_url

Expand Down
13 changes: 12 additions & 1 deletion rb/spec/unit/selenium/webdriver/remote/http/common_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ module Http
end

after do
described_class.extra_headers = {}
described_class.extra_headers = nil
described_class.user_agent = nil
end

it 'sends non-empty body header for POST requests without command data' do
Expand Down Expand Up @@ -63,6 +64,16 @@ module Http
.with(:post, URI.parse('http://server/session'),
hash_including('Foo' => 'bar'), '{}')
end

it 'allows overriding default User-Agent' do
described_class.user_agent = 'rspec/1.0 (ruby 3.2)'

common.call(:post, 'session', nil)

expect(common).to have_received(:request)
.with(:post, URI.parse('http://server/session'),
hash_including('User-Agent' => 'rspec/1.0 (ruby 3.2)'), '{}')
end
end
end # Http
end # Remote
Expand Down

0 comments on commit 3ec3cef

Please sign in to comment.