Exemple #1
0
 def test__get_response_Should_ReturnResponseJson_When_ResponseOk(
         self, *patches):
     mock_response = Mock(ok=True)
     mock_response.json.return_value = {'result': 'result'}
     client = RESTclient('hostname1.company.com')
     result = client.get_response(mock_response)
     self.assertEqual(result, mock_response.json.return_value)
Exemple #2
0
 def test__get_headers_Should_ReturnHeaders_When_Called(self, *patches):
     client = RESTclient('hostname1.company.com')
     result = client.get_headers()
     expected_result = {
         'Content-Type': 'application/json',
     }
     self.assertEqual(result, expected_result)
Exemple #3
0
 def test__get_response_Should_ReturnResponseText_When_ResponseJsonRaisesValueError(
         self, *patches):
     mock_response = Mock(ok=True, text='response text')
     mock_response.json.side_effect = [ValueError('No JSON')]
     client = RESTclient('hostname1.company.com')
     result = client.get_response(mock_response)
     self.assertEqual(result, 'response text')
Exemple #4
0
 def test__get_arguments_Should_SetVerifyToCabundle_When_VerifyIsNone(
         self, *patches):
     client = RESTclient('hostname1.company.com')
     endpoint = '/endpoint'
     kwargs = {'verify': None}
     result = client.get_arguments(endpoint, kwargs)
     self.assertEqual(result['verify'], client.cabundle)
Exemple #5
0
 def test__request_handler_Should_CallFunctionWithKwargs_When_Kwargs(
         self, get_headers, *patches):
     get_headers.return_value = {'h1': 'v1'}
     mock_function = Mock(__name__='mocked method')
     client = RESTclient('hostname1.company.com')
     decorated_function = RESTclient.request_handler(mock_function)
     object1 = b''
     decorated_function(client,
                        '/rest/endpoint',
                        kwarg1='kwarg1',
                        kwarg2='kwarg2',
                        kwarg3=object1,
                        verify=False)
     expected_kwargs = {
         'headers': {
             'h1': 'v1'
         },
         'verify': False,
         'address': 'https://hostname1.company.com/rest/endpoint',
         'kwarg1': 'kwarg1',
         'kwarg2': 'kwarg2',
         'kwarg3': object1
     }
     _, kwargs = mock_function.call_args_list[0]
     self.assertEqual(kwargs, expected_kwargs)
Exemple #6
0
 def test__get_arguments_Should_SetAddress_When_Called(self, *patches):
     client = RESTclient('hostname1.company.com')
     endpoint = '/endpoint'
     kwargs = {}
     result = client.get_arguments(endpoint, kwargs)
     expected_result = 'https://hostname1.company.com/endpoint'
     self.assertEqual(result['address'], expected_result)
Exemple #7
0
 def test__get_error_message_Should_ReturnExpected_When_ResponseJson(
         self, *patches):
     client = RESTclient('hostname1.company.com')
     response_mock = Mock()
     response_mock.json.return_value = 'json value'
     result = client.get_error_message(response_mock)
     self.assertEqual(result, response_mock.json.return_value)
Exemple #8
0
 def test__get_Should_CallRequestsGet_When_Called(self, requests, *patches):
     client = RESTclient('hostname1.company.com')
     client.get('/rest/endpoint')
     requests_get_call = call('https://hostname1.company.com/rest/endpoint',
                              headers={'Content-Type': 'application/json'},
                              verify=client.cabundle)
     self.assertTrue(requests_get_call in requests.get.mock_calls)
Exemple #9
0
 def test__get_arguments_Should_NotSetVerify_When_VerifyIsSet(
         self, *patches):
     client = RESTclient('hostname1.company.com')
     endpoint = '/endpoint'
     kwargs = {'verify': False}
     result = client.get_arguments(endpoint, kwargs)
     self.assertFalse(result['verify'])
Exemple #10
0
 def test__get_error_message_ShouldReturnExpected_When_ResponseJsonValueError(
         self, *patches):
     client = RESTclient('hostname1.company.com')
     response_mock = Mock()
     response_mock.json.side_effect = ValueError()
     response_mock.text = 'text error'
     result = client.get_error_message(response_mock)
     self.assertEqual(result, response_mock.text)
Exemple #11
0
 def test__request_handler_Should_NotCallFunctionAndReturnNone_When_FunctionSetsNoop(
         self, *patches):
     mock_function = Mock(__name__='mocked method')
     client = RESTclient('hostname1.company.com')
     decorated_function = RESTclient.request_handler(mock_function)
     result = decorated_function(client, '/rest/endpoint', noop=True)
     self.assertIsNone(result)
     self.assertFalse(mock_function.called)
Exemple #12
0
 def test__request_handler_Should_CallFunctionAndReturnResult_When_FunctionDoesNotSetNoop(
         self, *patches):
     mock_function = Mock(__name__='mocked method')
     client = RESTclient('hostname1.company.com')
     decorated_function = RESTclient.request_handler(mock_function)
     result = decorated_function(client, '/rest/endpoint')
     self.assertTrue(mock_function.called)
     self.assertEqual(result, 'result')
Exemple #13
0
 def test__get_arguments_Should_UpdatedHeaders_When_HeadersSpecified(
         self, *patches):
     client = RESTclient('hostname1.company.com')
     endpoint = '/endpoint'
     kwargs = {'headers': {'h2': 'v2'}}
     result = client.get_arguments(endpoint, kwargs)
     expected_result = {'h1': 'v1', 'h2': 'v2'}
     self.assertEqual(result['headers'], expected_result)
Exemple #14
0
 def test__get_headers_Should_ReturnHeaders_When_ApiKey(self, *patches):
     client = RESTclient('hostname1.company.com', api_key='some-api-key')
     result = client.get_headers()
     expected_result = {
         'Content-Type': 'application/json',
         'x-api-key': 'some-api-key'
     }
     self.assertEqual(result, expected_result)
Exemple #15
0
 def test__delete_Should_CallRequestsDelete_When_Called(
         self, requests, *patches):
     client = RESTclient('hostname1.company.com')
     client.delete('/rest/endpoint')
     requests_delete_call = call(
         'https://hostname1.company.com/rest/endpoint',
         headers={'Content-Type': 'application/json'},
         verify=client.cabundle)
     self.assertEqual(requests.delete.mock_calls[0], requests_delete_call)
Exemple #16
0
 def test__log_request_Should_CallLogger_When_JsonNotSerializable(
         self, logger_patch, redact_patch, *patches):
     redact_patch.return_value = '--redacted-arguments--'
     client = RESTclient('hostname1.company.com', bearer_token='token')
     arguments = {'address': '--address--', 'data': Mock()}
     client.log_request('GET', arguments, True)
     debug_call = call(
         '\nGET: --address-- NOOP: True\n"--redacted-arguments--"')
     self.assertTrue(debug_call in logger_patch.debug.mock_calls)
Exemple #17
0
 def test__get_headers_Should_ReturnHeaders_When_BearerToken(
         self, *patches):
     client = RESTclient('hostname1.company.com', bearer_token='token')
     result = client.get_headers()
     expected_result = {
         'Content-Type': 'application/json',
         'Authorization': 'Bearer token'
     }
     self.assertEqual(result, expected_result)
Exemple #18
0
 def test__request_handler_Should_CallFunctionWithArgs_When_Args(
         self, *patches):
     mock_function = Mock(__name__='mocked method')
     client = RESTclient('hostname1.company.com')
     decorated_function = RESTclient.request_handler(mock_function)
     decorated_function(client, '/rest/endpoint', k1='arg1', k2='arg2')
     expected_args = (client, '/rest/endpoint')
     args, _ = mock_function.call_args_list[0]
     self.assertEqual(args, expected_args)
Exemple #19
0
    def test__log_request_Should_CallLogger_When_JsonSerializable(
            self, logger_patch, redact_patch, *patches):
        arguments = {'address': '--address--', 'data': 'data'}
        redact_patch.return_value = arguments
        client = RESTclient('hostname1.company.com', bearer_token='token')

        client.log_request('GET', arguments, True)
        debug_call = call(
            '\nGET: --address-- NOOP: True\n{\n  "address": "--address--",\n  "data": "data"\n}'
        )
        self.assertTrue(debug_call in logger_patch.debug.mock_calls)
Exemple #20
0
 def test__put_Should_CallRequestsPut_When_Called(self, requests, *patches):
     client = RESTclient('hostname1.company.com')
     requests_data = {'arg1': 'val1', 'arg2': 'val2'}
     client.put('/rest/endpoint', json=requests_data)
     requests_put_call = call('https://hostname1.company.com/rest/endpoint',
                              headers={'Content-Type': 'application/json'},
                              json={
                                  'arg1': 'val1',
                                  'arg2': 'val2'
                              },
                              verify=client.cabundle)
     self.assertTrue(requests_put_call in requests.put.mock_calls)
Exemple #21
0
    def test__get_response_Should_CallResponseRaiseForStatus_When_ResponseNotOk(
            self, *patches):
        mock_response = Mock(ok=False)
        mock_response.json.return_value = {
            'message': 'error message',
            'details': 'error details'
        }
        mock_response.raise_for_status.side_effect = [
            Exception('exception occurred')
        ]

        client = RESTclient('hostname1.company.com')
        with self.assertRaises(Exception):
            client.get_response(mock_response)
Exemple #22
0
 def test__init__Should_SetAttributes_When_CabundleDoesNotExist(
         self, *patches):
     hostname = 'hostname1.company.com'
     cabundle = 'cabundle'
     client = RESTclient(hostname, cabundle=cabundle)
     self.assertEqual(client.hostname, hostname)
     self.assertFalse(client.cabundle)
Exemple #23
0
def get_codecov_client():
    """ return instance of RESTclient for codecov.io
    """
    token = getenv('CC_TOKEN_PSW')
    if not token:
        raise ValueError('CC_TOKEN_PSW environment variable must be set to token')
    return RESTclient(CODECOV_HOST, token=token, retries=[{'wait_fixed': 5000, 'stop_max_attempt_number': 3}])
Exemple #24
0
 def test__init__Should_SetAttributes_When_BearerToken(self, *patches):
     hostname = 'hostname1.company.com'
     cabundle = 'cabundle'
     bearer_token = 'token'
     client = RESTclient(hostname,
                         bearer_token=bearer_token,
                         cabundle=cabundle)
     self.assertEqual(client.bearer_token, bearer_token)
Exemple #25
0
 def test__init__Should_SetAttributes_When_CertfileCertpass(
         self, ssl_adapter_patch, *patches):
     client = RESTclient('hostname1.company.com',
                         certfile='-certfile-',
                         certpass='******')
     self.assertEqual(client.certfile, '-certfile-')
     ssl_adapter_patch.assert_called_once_with(certfile='-certfile-',
                                               certpass='******')
     self.assertEqual(client.ssl_adapter, ssl_adapter_patch.return_value)
Exemple #26
0
def get_jenkins_client():
    """ return instance of RESTclient for jenkins api
    """
    user = getenv('JN_TOKEN_USR')
    if not user:
        raise ValueError('JN_TOKEN_USR environment variable must be set to token')
    password = getenv('JN_TOKEN_PSW')
    if not password:
        raise ValueError('JN_TOKEN_PSW environment variable must be set to token')
    return RESTclient(JENKINS_HOST, user=user, password=password)
Exemple #27
0
    def test__request_handler_Should_CallFunctionAndReturnResult_When_SslAdapter(
            self, session_patch, ssl_adapter_patch, *patches):
        session_mock = Mock()
        session_patch.return_value.__enter__.return_value = session_mock

        mock_function = Mock(__name__='mocked method')
        client = RESTclient('hostname1.company.com',
                            certfile='-certfile-',
                            certpass='******')
        decorated_function = RESTclient.request_handler(mock_function)
        result = decorated_function(client, '/rest/endpoint', key='value')
        session_mock.mount.assert_called_once_with(
            'https://hostname1.company.com', ssl_adapter_patch.return_value)
        session_mock.request.assert_called_once_with(
            'mocked method',
            'https://hostname1.company.com/rest/endpoint',
            key='value',
            headers={'Content-Type': 'application/json'},
            verify='/etc/ssl/certs/ca-certificates.crt')
        self.assertEqual(result, 'result')
Exemple #28
0
 def test__init__Should_SetAttributes_When_ApiKey(self, *patches):
     hostname = 'hostname1.company.com'
     cabundle = 'cabundle'
     api_key = 'some-api-key'
     client = RESTclient(hostname, api_key=api_key, cabundle=cabundle)
     self.assertEqual(client.api_key, api_key)
Exemple #29
0
 def test__init__Should_SetUsernamePasswordAttributes_When_CalledWithUsernamePassword(
         self, *patches):
     client = RESTclient('hostname', username='******', password='******')
     self.assertEqual(client.username, 'value1')
     self.assertEqual(client.password, 'value2')
Exemple #30
0
 def test__get_headers_Should_SetAuthorizationHeader_When_UsernamePasswordAttributesExist(
         self, *patches):
     client = RESTclient('hostname', username='******', password='******')
     results = client.get_headers()
     self.assertTrue('Authorization' in results)
     self.assertTrue('Basic' in results['Authorization'])