Example #1
0
 def test_debug(self):
     register_uri(PUT,
                  self.base_url + 'classes/sms',
                  status=200,
                  body=json.dumps(TestClient.RESPONSE_BASIC),
                  content_type='application/json')
     client = Client(url=self.base_url,
                     username='******',
                     password='******',
                     debug=True)
     response = client.put('classes/sms', body=TestClient.RESPONSE_BASIC)
     self.assertEqual(response, TestClient.RESPONSE_BASIC)
Example #2
0
def _get_client(arguments):
    """Get the HTTP client to the service directory

    Retrieve the default configuration for the service directory CLI and override with the command line
    options

    :param arguments CLI arguments formatted with docopt
    :return Client object to access the service directory
    """

    # Check if the user wants to override the configuration file
    config_path = arguments.get('--conf')
    if config_path == None:
        # Get the path to the default configuration
        config_path = DEFAULT_CONFIG_PATH
    # Parse the configuration file
    client_config = _get_config(config_path)

    # Override the default configuration with the options (if any) set in the command line
    for config_key in client_config.iterkeys():
        option = '--' + config_key
        if arguments.get(option) is not None:
            client_config[config_key] = arguments.get(option)

    # Check noverify option (it is not covered by the previous loop because it is set to "verify" parameter)
    if arguments.get('--noverify'):
        client_config['verify'] = False

    # Prepare tuple for client certificate (cert and key) if 2-way ssl required
    try:
        cert = client_config['cert']
        key = client_config['key']
        if not cert or not key:
            raise SdAdminLibraryException('To enable 2-way SSL, both certificate and private key must be set')
        # Verify that both files exist
        if not isfile(cert):
            raise SdAdminLibraryException('Invalid certificate path \"' + cert + '\"')
        if not isfile(key):
            raise SdAdminLibraryException('Invalid private key path \"' + key + '\"')
        # Save the certificate as a tuple (valid for "requests" library)
        del client_config['key']  # This param is not needed anymore
        client_config['cert'] = (cert, key)
    except KeyError:
        pass

    if arguments.get('--debug'):
        client_config['debug'] = True
        print('')
        print('[CLI Configuration]:')
        print(_format(client_config))

    return Client(**client_config)
 def setUp(self):
     self.base_url = 'http://sd_fake.com/sd/v1/'
     self.client = Client(url=self.base_url,
                          username='******',
                          password='******')
     self.instances = Instances(self.client)
Example #4
0
 def test_get_url(self):
     self.assertEqual('http://sd_fake.com:80/sd/v1/',
                      Client.get_url('http', 'sd_fake.com', 80, 'v1'))
Example #5
0
 def test_init(self):
     client = Client(url='http://sd_fake.com/sd/v1/')
     self.assertEqual('http://sd_fake.com/sd/v1/', client.url)
     # Check that final slash is added automatically
     client = Client(url='http://sd_fake.com/sd/v1')
     self.assertEqual('http://sd_fake.com/sd/v1/', client.url)
Example #6
0
 def setUp(self):
     self.base_url = 'http://sd_fake.com/sd/v1/'
     self.client = Client(url=self.base_url,
                          username='******',
                          password='******',
                          debug=True)
Example #7
0
class TestClient(unittest.TestCase):

    # Dictionary with a basic response
    RESPONSE_BASIC = {
        'class_name': 'sms',
        'default_version': '1.0',
        'description': 'Servicio global de sms'
    }

    # Dictionary with query parameters
    QUERY_PARAMETERS = {'environment': 'production', 'version': 'v1'}

    RESPONSE_NOT_FOUND = {
        'exceptionId': 'SVC',
        'exceptionText': 'Resourc xxx not found'
    }

    def setUp(self):
        self.base_url = 'http://sd_fake.com/sd/v1/'
        self.client = Client(url=self.base_url,
                             username='******',
                             password='******',
                             debug=True)

    def test_init(self):
        client = Client(url='http://sd_fake.com/sd/v1/')
        self.assertEqual('http://sd_fake.com/sd/v1/', client.url)
        # Check that final slash is added automatically
        client = Client(url='http://sd_fake.com/sd/v1')
        self.assertEqual('http://sd_fake.com/sd/v1/', client.url)

    def test_get_url(self):
        self.assertEqual('http://sd_fake.com:80/sd/v1/',
                         Client.get_url('http', 'sd_fake.com', 80, 'v1'))

    def test_prepare_url(self):
        self.assertEqual('http://sd_fake.com/sd/v1/',
                         self.client._prepare_url(''))
        self.assertEqual('http://sd_fake.com/sd/v1/classes/sms',
                         self.client._prepare_url('classes/sms'))
        self.assertEqual('http://sd_fake.com/sd/info',
                         self.client._prepare_url('../info'))

    @activate
    def test_invalid_response(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body='invalid json',
                     content_type='text/plain')
        self.assertRaises(SdAdminLibraryException, self.client.get,
                          'classes/sms')

    @activate
    def test_timeout(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='text/plain')

        with patch('com.tdigital.sd.admin.client.request') as req_mock:
            req_mock.side_effect = Timeout('...')
            # Send the request
            self.assertRaises(SdAdminLibraryException, self.client.get,
                              'classes/sms')

    @activate
    def test_ssl(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='text/plain')

        with patch('com.tdigital.sd.admin.client.request') as req_mock:
            req_mock.side_effect = SSLError('...')
            # Send the request
            self.assertRaises(SdAdminLibraryException, self.client.get,
                              'classes/sms')

    @activate
    def test_redirects_exception_is_raised(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='text/plain')

        with patch('com.tdigital.sd.admin.client.request') as req_mock:
            req_mock.side_effect = TooManyRedirects('...')
            # Send the request
            self.assertRaises(TooManyRedirects, self.client.get, 'classes/sms')

    def test_connection_error(self):
        # Send the request to inexistent server (not using httpretty)
        self.assertRaises(SdAdminLibraryException, self.client.get,
                          'classes/sms')

    @activate
    def test_debug(self):
        register_uri(PUT,
                     self.base_url + 'classes/sms',
                     status=200,
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')
        client = Client(url=self.base_url,
                        username='******',
                        password='******',
                        debug=True)
        response = client.put('classes/sms', body=TestClient.RESPONSE_BASIC)
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

    @activate
    def test_get_not_found(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     status=404,
                     body=json.dumps(TestClient.RESPONSE_NOT_FOUND))
        self.assertRaises(ServerException, self.client.get, 'classes/sms')

    @activate
    def test_get_no_path_no_params(self):
        register_uri(GET,
                     self.base_url,
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')
        response = self.client.get('')
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

    @activate
    def test_get_no_path_with_params(self):
        register_uri(GET,
                     self.base_url,
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')
        response = self.client.get('', TestClient.QUERY_PARAMETERS)
        self.assertEqual(response, TestClient.RESPONSE_BASIC)
        for key, value in TestClient.QUERY_PARAMETERS.iteritems():
            self.assertEqual(value, last_request().querystring[key][0])

    @activate
    def test_get_with_path_no_params(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')
        response = self.client.get('classes/sms')
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

    @activate
    def test_get_with_path_with_params(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')
        response = self.client.get('classes/sms', TestClient.QUERY_PARAMETERS)
        self.assertEqual(response, TestClient.RESPONSE_BASIC)
        for key, value in TestClient.QUERY_PARAMETERS.iteritems():
            self.assertEqual(value, last_request().querystring[key][0])

    @activate
    def test_post_with_response_body(self):
        register_uri(POST,
                     self.base_url + 'classes/sms',
                     status=201,
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')

        # Without body in request
        response = self.client.post('classes/sms')
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

        # With body in request (as a dictionary)
        response = self.client.post('classes/sms',
                                    body=TestClient.RESPONSE_BASIC)
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

        # With body in request (as a string)
        response = self.client.post('classes/sms',
                                    body=json.dumps(TestClient.RESPONSE_BASIC))
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

    @activate
    def test_post_without_response_body(self):
        register_uri(POST, self.base_url + 'classes/sms', body='', status=201)

        # Without body in request
        self.assertRaises(SdAdminLibraryException, self.client.post,
                          'classes/sms')

        # With body in request
        self.assertRaises(SdAdminLibraryException,
                          self.client.post,
                          'classes/sms',
                          body=TestClient.RESPONSE_BASIC)

    @activate
    def test_put_with_response_body(self):
        register_uri(PUT,
                     self.base_url + 'classes/sms',
                     status=200,
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='application/json')

        # Without body in request
        response = self.client.put('classes/sms')
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

        # With body in request
        response = self.client.put('classes/sms',
                                   body=TestClient.RESPONSE_BASIC)
        self.assertEqual(response, TestClient.RESPONSE_BASIC)

    @activate
    def test_put_without_response_body(self):
        register_uri(PUT, self.base_url + 'classes/sms', body='', status=200)

        # Without body in request
        self.assertRaises(SdAdminLibraryException, self.client.put,
                          'classes/sms')

        # With body in request
        self.assertRaises(SdAdminLibraryException,
                          self.client.put,
                          'classes/sms',
                          body=TestClient.RESPONSE_BASIC)

    @activate
    def test_delete(self):
        register_uri(DELETE,
                     self.base_url + 'classes/sms',
                     body='',
                     status=204)

        response = self.client.delete('classes/sms')
        self.assertIsNone(response)