Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
format_data.return_value = "formatted"
request = ClientRequest('GET', '/')
request.add_formdata()
assert request.files == {}
request = ClientRequest('GET', '/')
request.add_formdata({'Test':'Data'})
assert request.files == {'Test':'formatted'}
request = ClientRequest('GET', '/')
request.headers = {'Content-Type':'1234'}
request.add_formdata({'1':'1', '2':'2'})
assert request.files == {'1':'formatted', '2':'formatted'}
request = ClientRequest('GET', '/')
request.headers = {'Content-Type':'1234'}
request.add_formdata({'1':'1', '2':None})
assert request.files == {'1':'formatted'}
request = ClientRequest('GET', '/')
request.headers = {'Content-Type':'application/x-www-form-urlencoded'}
request.add_formdata({'1':'1', '2':'2'})
assert request.files is None
assert request.data == {'1':'1', '2':'2'}
request = ClientRequest('GET', '/')
request.headers = {'Content-Type':'application/x-www-form-urlencoded'}
request.add_formdata({'1':'1', '2':None})
assert request.files is None
assert request.data == {'1':'1'}
def test_no_log(mock_http_logger):
universal_request = ClientRequest('GET', 'http://127.0.0.1/')
request = Request(universal_request)
http_logger = HTTPLogger()
response = Response(request, ClientResponse(universal_request, None))
# By default, no log handler for HTTP
http_logger.on_request(request)
mock_http_logger.debug.assert_not_called()
http_logger.on_response(request, response)
mock_http_logger.debug.assert_not_called()
mock_http_logger.reset_mock()
# I can enable it per request
http_logger.on_request(request, **{"enable_http_logger": True})
assert mock_http_logger.debug.call_count >= 1
http_logger.on_response(request, response, **{"enable_http_logger": True})
assert mock_http_logger.debug.call_count >= 1
def test_user_agent():
with mock.patch.dict('os.environ', {'AZURE_HTTP_USER_AGENT': "mytools"}):
policy = UserAgentPolicy()
assert policy.user_agent.endswith("mytools")
request = ClientRequest('GET', 'http://127.0.0.1/')
policy.on_request(Request(request))
assert request.headers["user-agent"].endswith("mytools")
def _create_request_message(self, http_method, location_id, route_values=None,
query_parameters=None):
location = self._get_resource_location(location_id)
if location is None:
raise ValueError('API resource location ' + location_id + ' is not registered on '
+ self.config.base_url + '.')
if route_values is None:
route_values = {}
route_values['area'] = location.area
route_values['resource'] = location.resource_name
route_template = self._remove_optional_route_parameters(location.route_template,
route_values)
logger.debug('Route template: %s', location.route_template)
url = self._client.format_url(route_template, **route_values)
request = ClientRequest(method=http_method, url=self._client.format_url(url))
if query_parameters:
request.format_parameters(query_parameters)
return request
def get_vsts_info(self, relative_remote_url):
url = self._client.format_url(relative_remote_url.rstrip('/') + '/vsts/info')
request = ClientRequest(method='GET', url=url)
headers = {'Accept': 'application/json'}
if self._suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
if self._force_msa_pass_through:
headers['X-VSS-ForceMsaPassThrough'] = 'true'
response = self._send_request(request, headers)
return self._deserialize('VstsInfo', response)
def get_vsts_info(self, relative_remote_url):
url = self._client.format_url(relative_remote_url.rstrip('/') + '/vsts/info')
request = ClientRequest(method='GET', url=url)
headers = {'Accept': 'application/json'}
if self._suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
if self._force_msa_pass_through:
headers['X-VSS-ForceMsaPassThrough'] = 'true'
response = self._send_request(request, headers)
return self._deserialize('VstsInfo', response)
def _request(self, method, url, params, headers, content, form_content):
# type: (str, str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
"""Create ClientRequest object.
:param str url: URL for the request.
:param dict params: URL query parameters.
:param dict headers: Headers
:param dict form_content: Form content
"""
request = ClientRequest(method, self.format_url(url))
if params:
request.format_parameters(params)
if headers:
request.headers.update(headers)
# All requests should contain a Accept.
# This should be done by Autorest, but wasn't in old Autorest
# Force it for now, but might deprecate it later.
if "Accept" not in request.headers:
_LOGGER.debug("Accept header absent and forced to application/json")
request.headers['Accept'] = 'application/json'
if content is not None:
request.add_content(content)
def get_vsts_info_by_remote_url(remote_url, credentials, suppress_fedauth_redirect=True):
request = ClientRequest(method='GET', url=remote_url.rstrip('/') + '/vsts/info')
headers = {'Accept': 'application/json'}
if suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
git_client = GitClient(base_url=remote_url, creds=credentials)
response = git_client._send_request(request, headers)
return git_client._deserialize('VstsInfo', response)
# Next check for options cached on disk
if not all_host_types and OPTIONS_FILE_CACHE[self.normalized_url]:
try:
logger.debug('File cache hit for options on: %s', self.normalized_url)
self._locations = self._base_deserialize.deserialize_data(OPTIONS_FILE_CACHE[self.normalized_url],
'[ApiResourceLocation]')
return self._locations
except DeserializationError as ex:
logger.debug(ex, exc_info=True)
else:
logger.debug('File cache miss for options on: %s', self.normalized_url)
# Last resort, make the call to the server
options_uri = self._combine_url(self.config.base_url, '_apis')
request = ClientRequest(method='OPTIONS', url=self._client.format_url(options_uri))
if all_host_types:
query_parameters = {'allHostTypes': True}
request.format_parameters(query_parameters)
headers = {'Accept': 'application/json'}
if self._suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
if self._force_msa_pass_through:
headers['X-VSS-ForceMsaPassThrough'] = 'true'
response = self._send_request(request, headers=headers)
wrapper = self._base_deserialize('VssJsonCollectionWrapper', response)
if wrapper is None:
raise VstsClientRequestError("Failed to retrieve resource locations from: {}".format(options_uri))
collection = wrapper.value
returned_locations = self._base_deserialize('[ApiResourceLocation]',
collection)
if all_host_types:
# Next check for options cached on disk
if not all_host_types and OPTIONS_FILE_CACHE[self.normalized_url]:
try:
logger.debug('File cache hit for options on: %s', self.normalized_url)
self._locations = self._base_deserialize.deserialize_data(OPTIONS_FILE_CACHE[self.normalized_url],
'[ApiResourceLocation]')
return self._locations
except DeserializationError as ex:
logger.debug(ex, exc_info=True)
else:
logger.debug('File cache miss for options on: %s', self.normalized_url)
# Last resort, make the call to the server
options_uri = self._combine_url(self.config.base_url, '_apis')
request = ClientRequest(method='OPTIONS', url=self._client.format_url(options_uri))
if all_host_types:
query_parameters = {'allHostTypes': True}
request.format_parameters(query_parameters)
headers = {'Accept': 'application/json'}
if self._suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
if self._force_msa_pass_through:
headers['X-VSS-ForceMsaPassThrough'] = 'true'
response = self._send_request(request, headers=headers)
wrapper = self._base_deserialize('VssJsonCollectionWrapper', response)
if wrapper is None:
raise AzureDevOpsClientRequestError("Failed to retrieve resource locations from: {}".format(options_uri))
collection = wrapper.value
returned_locations = self._base_deserialize('[ApiResourceLocation]',
collection)
if all_host_types: