def _cs_request(self, url, method, **kwargs): # Check that certain things are called correctly if method in ['GET', 'DELETE']: assert 'body' not in kwargs elif method == 'PUT': assert 'body' in kwargs # Call the method args = urlparse.parse_qsl(urlparse.urlparse(url)[4]) kwargs.update(args) munged_url = url.rsplit('?', 1)[0] munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_') munged_url = munged_url.replace('-', '_') callback = "%s_%s" % (method.lower(), munged_url) if not hasattr(self, callback): raise AssertionError('Called unknown API method: %s %s, ' 'expected fakes method name: %s' % (method, url, callback)) # Note the call self.callstack.append((method, url, kwargs.get('body', None))) status, headers, body = getattr(self, callback)(**kwargs) r = utils.TestResponse({ "status_code": status, "text": body, "headers": headers, }) return r, body if hasattr(status, 'items'): return utils.TestResponse(status), body else: return utils.TestResponse({"status": status}), body
def test_authenticate_success(self): cs = client.Client("username", "password", "project_id", "auth_url") management_url = 'https://localhost/v2.1/443470' auth_response = utils.TestResponse({ 'status_code': 204, 'headers': { 'x-server-management-url': management_url, 'x-auth-token': '1b751d74-de0c-46ae-84f0-915744b582d1', }, }) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): cs.client.authenticate() headers = { 'Accept': 'application/json', 'X-Auth-User': '******', 'X-Auth-Key': 'password', 'X-Auth-Project-Id': 'project_id', 'User-Agent': cs.client.USER_AGENT } mock_request.assert_called_with("GET", cs.client.auth_url, headers=headers, **self.TEST_REQUEST_BASE) self.assertEqual(auth_response.headers['x-server-management-url'], cs.client.management_url) self.assertEqual(auth_response.headers['x-auth-token'], cs.client.auth_token) test_auth_call()
def mock_http_request(resp=None): """Mock an HTTP Request.""" if not resp: resp = { "access": { "token": { "expires": "12345", "id": "FAKE_ID", "tenant": { "id": "FAKE_TENANT_ID", } }, "serviceCatalog": [ { "type": "sds", "endpoints": [ { "region": "RegionOne", "adminURL": "http://localhost:8774/v1.1", "internalURL": "http://localhost:8774/v1.1", "publicURL": "http://localhost:8774/v1.1/", }, ], }, ], }, } auth_response = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp), }) return mock.Mock(return_value=(auth_response))
def test_authenticate_failure(self): cs = client.Client("username", "password", "project_id", "auth_url") auth_response = utils.TestResponse({"status_code": 401}) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.Unauthorized, cs.client.authenticate) test_auth_call()
def test_authenticate_failure(self): cs = client.Client("username", "password", "project_id", "http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.Unauthorized, cs.client.authenticate) test_auth_call()
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import mock import requests from sdsclient import client from sdsclient import exceptions from sdsclient.tests import utils fake_response = utils.TestResponse({ "status_code": 200, "text": '{"hi": "there"}', }) fake_response_empty = utils.TestResponse({ "status_code": 200, "text": '{"access": {}}' }) mock_request = mock.Mock(return_value=(fake_response)) mock_request_empty = mock.Mock(return_value=(fake_response_empty)) bad_400_response = utils.TestResponse({ "status_code": 400, "text": '{"error": {"message": "n/a", "details": "Terrible!"}}',
def test_authenticate_tenant_id(self): cs = client.Client("username", "password", auth_url="http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): cs.client.authenticate() headers = { 'User-Agent': cs.client.USER_AGENT, 'Content-Type': 'application/json', 'Accept': 'application/json', } body = { 'auth': { 'passwordCredentials': { 'username': cs.client.user, 'password': cs.client.password, }, 'tenantId': cs.client.tenant_id, }, } token_url = cs.client.auth_url + "/tokens" mock_request.assert_called_with("POST", token_url, headers=headers, data=json.dumps(body), allow_redirects=True, **self.TEST_REQUEST_BASE) endpoints = resp["access"]["serviceCatalog"][0]['endpoints'] public_url = endpoints[0]["publicURL"].rstrip('/') self.assertEqual(public_url, cs.client.management_url) token_id = resp["access"]["token"]["id"] self.assertEqual(token_id, cs.client.auth_token) tenant_id = resp["access"]["token"]["tenant"]["id"] self.assertEqual(tenant_id, cs.client.tenant_id) test_auth_call()
def test_auth_redirect(self): cs = client.Client("username", "password", "project_id", "http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): cs.client.authenticate() headers = { 'User-Agent': cs.client.USER_AGENT, 'Content-Type': 'application/json', 'Accept': 'application/json', } body = { 'auth': { 'passwordCredentials': { 'username': cs.client.user, 'password': cs.client.password, }, 'tenantName': cs.client.projectid, }, } token_url = cs.client.auth_url + "/tokens" mock_request.assert_called_with("POST", token_url, headers=headers, data=json.dumps(body), allow_redirects=True, **self.TEST_REQUEST_BASE) resp = dict_correct_response endpoints = resp["access"]["serviceCatalog"][0]['endpoints'] public_url = endpoints[0]["publicURL"].rstrip('/') self.assertEqual(public_url, cs.client.management_url) token_id = resp["access"]["token"]["id"] self.assertEqual(token_id, cs.client.auth_token) test_auth_call()