Skip to content

Commit 3ec3cef

Browse files
committed
[rb] Support overriding User-Agent in HTTP client
1 parent 4f72e3f commit 3ec3cef

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

rb/lib/selenium/webdriver/remote/http/common.rb

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,16 @@ class Common
2626
CONTENT_TYPE = 'application/json'
2727
DEFAULT_HEADERS = {
2828
'Accept' => CONTENT_TYPE,
29-
'Content-Type' => "#{CONTENT_TYPE}; charset=UTF-8",
30-
'User-Agent' => "selenium/#{WebDriver::VERSION} (ruby #{Platform.os})"
29+
'Content-Type' => "#{CONTENT_TYPE}; charset=UTF-8"
3130
}.freeze
3231

3332
class << self
3433
attr_accessor :extra_headers
34+
attr_writer :user_agent
35+
36+
def user_agent
37+
@user_agent ||= "selenium/#{WebDriver::VERSION} (ruby #{Platform.os})"
38+
end
3539
end
3640

3741
attr_writer :server_url
@@ -46,7 +50,7 @@ def close
4650

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

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

6670
private
6771

72+
def common_headers
73+
@common_headers ||= begin
74+
headers = DEFAULT_HEADERS.dup
75+
headers['User-Agent'] = Common.user_agent
76+
headers = headers.merge(Common.extra_headers || {})
77+
78+
headers
79+
end
80+
end
81+
6882
def server_url
6983
return @server_url if @server_url
7084

rb/spec/unit/selenium/webdriver/remote/http/common_spec.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ module Http
3333
end
3434

3535
after do
36-
described_class.extra_headers = {}
36+
described_class.extra_headers = nil
37+
described_class.user_agent = nil
3738
end
3839

3940
it 'sends non-empty body header for POST requests without command data' do
@@ -63,6 +64,16 @@ module Http
6364
.with(:post, URI.parse('http://server/session'),
6465
hash_including('Foo' => 'bar'), '{}')
6566
end
67+
68+
it 'allows overriding default User-Agent' do
69+
described_class.user_agent = 'rspec/1.0 (ruby 3.2)'
70+
71+
common.call(:post, 'session', nil)
72+
73+
expect(common).to have_received(:request)
74+
.with(:post, URI.parse('http://server/session'),
75+
hash_including('User-Agent' => 'rspec/1.0 (ruby 3.2)'), '{}')
76+
end
6677
end
6778
end # Http
6879
end # Remote

0 commit comments

Comments
 (0)