Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add extra_headers option to http method call #5753

Merged
merged 2 commits into from
Feb 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions datadog_checks_base/datadog_checks/base/utils/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,14 +302,21 @@ def _request(self, method, url, options):
if persist is None:
persist = self.persist_connections

new_options = self.populate_options(options)
AlexandreYang marked this conversation as resolved.
Show resolved Hide resolved

extra_headers = options.pop('extra_headers', None)
if extra_headers is not None:
new_options['headers'] = new_options['headers'].copy()
new_options['headers'].update(extra_headers)

with ExitStack() as stack:
for hook in self.request_hooks:
stack.enter_context(hook())

if persist:
return getattr(self.session, method)(url, **self.populate_options(options))
return getattr(self.session, method)(url, **new_options)
else:
return getattr(requests, method)(url, **self.populate_options(options))
return getattr(requests, method)(url, **new_options)

def populate_options(self, options):
# Avoid needless dictionary update if there are no options
Expand Down
24 changes: 24 additions & 0 deletions datadog_checks_base/tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,30 @@ def test_config_extra_headers_string_values(self):

assert http.options['headers'] == {'User-Agent': 'Datadog Agent/0.0.0', 'answer': '42'}

def test_extra_headers_on_http_method_call(self):
instance = {'extra_headers': {'answer': 42}}
init_config = {}
http = RequestsWrapper(instance, init_config)

extra_headers = {"foo": "bar"}
with mock.patch("requests.get") as get:
http.get("http://example.com/hello", extra_headers=extra_headers)

expected_options = {'foo': 'bar', 'User-Agent': 'Datadog Agent/0.0.0', 'answer': '42'}
get.assert_called_with(
"http://example.com/hello",
headers=expected_options,
auth=None,
cert=None,
proxies=None,
timeout=(10.0, 10.0),
verify=True,
)

# make sure the original headers are not modified
assert http.options['headers'] == {'User-Agent': 'Datadog Agent/0.0.0', 'answer': '42'}
assert extra_headers == {"foo": "bar"}


class TestVerify:
def test_config_default(self):
Expand Down