diff --git a/rapyuta_io/rio_client.py b/rapyuta_io/rio_client.py index 317de96a..19503d65 100644 --- a/rapyuta_io/rio_client.py +++ b/rapyuta_io/rio_client.py @@ -2,38 +2,23 @@ from __future__ import absolute_import import json -import jsonschema import os import six from rapyuta_io.clients import DeviceManagerClient, _ParamserverClient -from rapyuta_io.clients.build import Build, BuildStatus from rapyuta_io.clients.catalog_client import CatalogClient from rapyuta_io.clients.core_api_client import CoreAPIClient -from rapyuta_io.clients.deployment import Deployment from rapyuta_io.clients.device import Device -from rapyuta_io.clients.metrics import QueryMetricsRequest, MetricOperation, \ - MetricFunction, QueryMetricsResponse, \ - ListMetricsRequest, ListTagKeysRequest, \ - Metric, Tags, ListTagValuesRequest -from rapyuta_io.clients.native_network import NativeNetwork -from rapyuta_io.clients.package import Package -from rapyuta_io.clients.package import Runtime, ROSDistro, RestartPolicy -from rapyuta_io.clients.persistent_volumes import VolumeInstance -from rapyuta_io.clients.project import Project -from rapyuta_io.clients.rip_client import RIPClient, AuthTokenLevel -from rapyuta_io.clients.rosbag import ROSBagJob, ROSBagJobStatus, ROSBagBlob, \ - ROSBagBlobStatus -from rapyuta_io.clients.routed_network import RoutedNetwork, Parameters -from rapyuta_io.clients.secret import Secret +from rapyuta_io.clients.metrics import ListMetricsRequest, ListTagKeysRequest, ListTagValuesRequest, Metric, \ + MetricFunction, MetricOperation, QueryMetricsRequest, QueryMetricsResponse, Tags +from rapyuta_io.clients.rip_client import AuthTokenLevel, RIPClient +from rapyuta_io.clients.rosbag import ROSBagBlob, ROSBagBlobStatus, ROSBagJob, ROSBagJobStatus from rapyuta_io.clients.user_group import UserGroup from rapyuta_io.utils import InvalidAuthTokenException, \ InvalidParameterException -from rapyuta_io.utils import to_objdict -from rapyuta_io.utils.settings import VOLUME_PACKAGE_ID, default_host_config -from rapyuta_io.utils.utils import get_api_response_data, valid_list_elements -from rapyuta_io.clients.validation_schema import UPDATE_DEPLOYMENT_SCHEMA +from rapyuta_io.utils.settings import default_host_config +from rapyuta_io.utils.utils import valid_list_elements class Client(object): @@ -127,6 +112,36 @@ def set_project(self, project_guid): self._dmClient.set_project(project_guid) self._paramserver_client.set_project(project_guid) + def get_authenticated_user(self): + """ + Get details for authenticated User. + + :rtype: :py:class:`~rapyuta_io.clients.project.User` + + Following example demonstrates how to get authenticated user details. + + >>> from rapyuta_io import Client + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> user = client.get_authenticated_user() + + """ + return self._core_api_client.get_user() + + def get_user_organizations(self): + """ + Get list of organizations that a user is part of. + + :rtype: list(:py:class:`~rapyuta_io.clients.organization.Organization`) + + Following example demonstrates how to get the list of organizations that a user is part of. + + >>> from rapyuta_io import Client + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> organizations = client.get_user_organizations() + + """ + return self._core_api_client.get_user_organizations() + def get_all_devices(self, online_device=False, arch_list=None, retry_limit=0, device_name=None): """ Get all the devices @@ -799,3 +814,108 @@ def list_tag_values(self, list_tag_values_request): response = self._core_api_client.list_tag_values(list_tag_values_request) return response.get('tags_values', []) + + def list_usergroups(self, org_guid): + """ + List usergroups in an organization + + :param org_guid: Organization GUID + :type org_guid: str + :return: A list of all Usergroups in the organization + :rtype: list(:py:class:`~rapyuta_io.clients.user_group.UserGroup`) + + Following example demonstrates how to list usergroups + + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> user = self._core_api_client.get_user() + >>> organization_guid = user.organization.guid + >>> client.list_usergroups(organization_guid) + + """ + return self._core_api_client.list_usergroups(org_guid) + + def get_usergroup(self, org_guid, group_guid): + """ + Get usergroup using its GUID + + :param org_guid: Organization GUID + :type org_guid: str + :param group_guid: Usergroup GUID + :type group_guid: str + :return: A usergroup + :rtype: :py:class:`~rapyuta_io.clients.user_group.UserGroup` + + Following example demonstrates how to fetch a usergroup using its GUID + + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> user = self._core_api_client.get_user() + >>> organization_guid = user.organization.guid + >>> client.get_usergroup(organization_guid, 'group-guid') + + """ + return self._core_api_client.get_usergroup(org_guid, group_guid) + + def delete_usergroup(self, org_guid, group_guid): + """ + Delete usergroup using its GUID + + :param org_guid: Organization GUID + :type org_guid: str + :param group_guid: Usergroup GUID + :type group_guid: str + + Following example demonstrates how to delete a usergroup using its GUID + + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> user = self._core_api_client.get_user() + >>> organization_guid = user.organization.guid + >>> client.delete_usergroup(organization_guid, 'group-guid') + + """ + return self._core_api_client.delete_usergroup(org_guid, group_guid) + + def create_usergroup(self, org_guid, usergroup): + """ + Create usergroup in organization + + :param org_guid: Organization GUID + :type org_guid: str + :param usergroup: usergroup object + :type usergroup: py:class:`~rapyuta_io.clients.user_group.UserGroup` + :return: Usergroup object + :rtype: :py:class:`~rapyuta_io.clients.user_group.UserGroup` + + Following example demonstrates how to create usergroup in an organization + + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> user = self._core_api_client.get_user() + >>> organization_guid = user.organization.guid + >>> usergroup = UserGroup(name='test-usergroup', description='test-description', creator=user.guid) + >>> usergroup = client.create_usergroup(organization_guid, usergroup) + + """ + return self._core_api_client.create_usergroup(org_guid, usergroup) + + def update_usergroup(self, org_guid, group_guid, usergroup): + """ + Update usergroup in organization + + :param org_guid: Organization GUID + :type org_guid: str + :param group_guid: Usergroup GUID + :type group_guid: str + :param usergroup: Usergroup object + :type usergroup: py:class:`~rapyuta_io.clients.user_group.UserGroup` + :return: Usergroup object + :rtype: :py:class:`~rapyuta_io.clients.user_group.UserGroup` + + Following example demonstrates how to update usergroup + + >>> client = Client(auth_token='auth_token', project='project_guid') + >>> user = self._core_api_client.get_user() + >>> organization_guid = user.organization.guid + >>> usergroup = UserGroup(name='test-usergroup-updated', description='test-description-updated', creator=user.guid) + >>> usergroup = client.update_usergroup(organization_guid, 'group-guid', usergroup) + + """ + return self._core_api_client.update_usergroup(org_guid, group_guid, usergroup) diff --git a/tests/build_test.py b/tests/build_test.py deleted file mode 100644 index 15737a03..00000000 --- a/tests/build_test.py +++ /dev/null @@ -1,867 +0,0 @@ -from __future__ import absolute_import -import requests -import unittest -import json -from mock import patch, Mock, MagicMock, call -from rapyuta_io.clients.build import Build, BuildStatus, SimulationOptions, BuildOptions, CatkinOption, GithubWebhook -from rapyuta_io.clients.buildoperation import BuildOperation, BuildOperationInfo -from tests.utils.client import get_client, remove_auth_token, headers -from rapyuta_io.utils.error import InvalidParameterException, ResourceNotFoundError -from tests.utils.build_responses import BUILD_CREATE_SUCCESS, BUILD_GET_SUCCESS, BUILD_GET_SUCCESS_WITH_BUILD_REQUESTS,\ - BUILD_LIST_SUCCESS, BUILD_NOT_FOUND, TRIGGER_BUILD_RESPONSE, \ - ROLLBACK_BUILD_RESPONSE, BUILD_GUID_NOT_FOUND, BUILD_IN_PROGRESS_ERROR -from requests import Response -from six.moves import map -from rapyuta_io.utils.partials import PartialMixin - - -class BuildTest(unittest.TestCase): - - def test_create_build_invalid_build_type(self): - expected_err_msg = 'build must be non-empty and of type rapyuta_io.clients.build.Build' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build('invalid-build-type') - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_strategy_type(self): - expected_err_msg = 'StrategyType must be one of rapyuta_io.clients.package.StrategyType' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'invalid', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'melodic')) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_ros_distro(self): - expected_err_msg = 'rosDistro must be one of rapyuta_io.clients.package.ROSDistro' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'invalid', True)) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_architecture(self): - expected_err_msg = 'Architecture must be one of rapyuta_io.clients.device_manager.DeviceArch' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'invalid', 'melodic')) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_build_name_absent(self): - expected_err_msg = 'buildName must be a non-empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'melodic')) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_repository_absent(self): - expected_err_msg = 'repository must be a valid non-empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', None, 'amd64', 'melodic')) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_simulation_option(self): - expected_err_msg = 'simulation must be a boolean' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', None, 'amd64', 'melodic', simulationOptions=SimulationOptions(1))) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_catkin_options(self): - expected_err_msg = 'catkinOptions must be an instance of list' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', None, 'amd64', rosDistro='melodic', buildOptions=BuildOptions(catkinOptions={}))) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_only_docker_push_secret(self): - expected_err_msg = 'both dockerPushRepository and dockerPushSecret must be present' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/example', 'amd64', - isRos=False, dockerPushSecret='secret-guid')) - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_create_build_invalid_only_docker_push_repository(self): - expected_err_msg = 'both dockerPushRepository and dockerPushSecret must be present' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/example', 'amd64', - isRos=False, dockerPushRepository='docker.io/example/example')) - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_create_build_invalid_trigger_name(self): - expected_err_msg = 'triggerName must be a non-empty string' - client = get_client() - invalid_trigger_name = 1 - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/example', 'amd64', - isRos=False, dockerPushSecret='secret-guid', triggerName=invalid_trigger_name, - dockerPushRepository='docker.io/example/example')) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_tag_name(self): - expected_err_msg = 'tagName must be a non-empty string' - client = get_client() - invalid_tag_name = 1 - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/example', 'amd64', - isRos=False, dockerPushSecret='secret-guid', tagName=invalid_tag_name, - dockerPushRepository='docker.io/example/example')) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_invalid_only_tag_name_with_no_docker_push_secret(self): - expected_err_msg = 'cannot use tagName without dockerPushSecret' - client = get_client() - test_tag_name = 'test_tag_name' - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/example', 'amd64', - isRos=False, tagName=test_tag_name)) - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_create_build_operation_info_with_invalid_trigger_name(self): - expected_err_msg = 'triggerName must be a non-empty string' - inavlid_trigger_name = 1 - with self.assertRaises(InvalidParameterException) as e: - BuildOperationInfo('build-guid', triggerName=inavlid_trigger_name, tagName='tag-name') - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_operation_info_with_invalid_tag_name(self): - expected_err_msg = 'tagName must be a non-empty string' - inavlid_tag_name = 1 - with self.assertRaises(InvalidParameterException) as e: - BuildOperationInfo('build-guid', triggerName='trigger_name', tagName=inavlid_tag_name) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_build_operation_info_with_invalid_webhook(self): - expected_err_msg = 'buildWebhooks must be a list of rapyuta_io.clients.build.GithubWebhook' - inavlid_webhook = 1 - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_build(Build('test_build', 'Source', 'https://github.com/example', 'amd64', - isRos=False, dockerPushSecret='secret-guid', - dockerPushRepository='docker.io/example/example', - buildWebhooks = inavlid_webhook)) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_create_build_noetic_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Source", - "repository": "https://github.com/rapyuta-robotics/io_tutorials.git", - "architecture": "amd64", - "rosDistro": "noetic", - "isRos": True - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - mock_create_build = Mock() - mock_create_build.text = BUILD_CREATE_SUCCESS - mock_create_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_build] - client = get_client() - build = client.create_build( - Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'noetic', True), False) - mock_request.assert_called_once_with(headers=headers, - json=expected_payload, - method='POST', - url=expected_url, - params=None) - self.assertEqual(build.get('guid'), 'build-guid') - self.assertEqual(build.get('buildName'), 'test_build') - self.assertTrue(build.is_partial) - - @patch('requests.request') - def test_create_build_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Source", - "repository": "https://github.com/rapyuta-robotics/io_tutorials.git", - "architecture": "amd64", - "rosDistro": "melodic", - "isRos": True - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - mock_create_build = Mock() - mock_create_build.text = BUILD_CREATE_SUCCESS - mock_create_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_build] - client = get_client() - build = client.create_build( - Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'melodic', True), False) - mock_request.assert_called_once_with(headers=headers, - json=expected_payload, - method='POST', - url=expected_url, - params=None) - self.assertEqual(build.get('guid'), 'build-guid') - self.assertEqual(build.get('buildName'), 'test_build') - self.assertTrue(build.is_partial) - - @patch('requests.request') - def test_create_build_with_push_pull_secrets_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Docker", - "repository": "https://github.com/rapyuta-robotics/io_tutorials.git", - "architecture": "amd64", - "isRos": False, - "dockerPullSecrets": ["secret-guid"], - "dockerPushSecret": "secret-guid", - "dockerPushRepository": "docker.io/example/example" - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - mock_create_build = Mock() - mock_create_build.text = BUILD_CREATE_SUCCESS - mock_create_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_build] - client = get_client() - build = client.create_build( - Build('test_build', 'Docker', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', isRos=False, dockerPushSecret='secret-guid', - dockerPushRepository='docker.io/example/example', dockerPullSecret='secret-guid'), False) - mock_request.assert_called_once_with(headers=headers, - json=expected_payload, - method='POST', - url=expected_url, - params=None) - self.assertEqual(build.get('guid'), 'build-guid') - self.assertEqual(build.get('buildName'), 'test_build') - - @patch('requests.request') - def test_create_build_with_trigger_name_tag_name_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Docker", - "repository": "https://github.com/rapyuta-robotics/io_tutorials.git", - "architecture": "amd64", - "isRos": False, - "dockerPullSecrets": ["secret-guid"], - "dockerPushSecret": "secret-guid", - "dockerPushRepository": "docker.io/example/example", - "triggerName": "test-trigger-name", - "tagName": "test-tag-name" - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - mock_create_build = Mock() - mock_create_build.text = BUILD_CREATE_SUCCESS - mock_create_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_build] - client = get_client() - build = client.create_build( - Build('test_build', 'Docker', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', isRos=False, dockerPushSecret='secret-guid', - dockerPushRepository='docker.io/example/example', dockerPullSecret='secret-guid', - triggerName='test-trigger-name', tagName='test-tag-name'), False) - mock_request.assert_called_once_with(headers=headers, - json=expected_payload, - method='POST', - url=expected_url, - params=None) - self.assertEqual(build.get('guid'), 'build-guid') - self.assertEqual(build.get('buildName'), 'test_build') - - @patch('requests.request') - def test_create_build_with_refresh_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Source", - "repository": "https://github.com/rapyuta-robotics/io_tutorials.git", - "architecture": "amd64", - "rosDistro": "melodic", - "isRos": True - } - get_build_response = MagicMock(spec=Response) - get_build_response.text = BUILD_GET_SUCCESS - get_build_response.status_code = requests.codes.OK - mock_create_build = Mock() - mock_create_build.text = BUILD_CREATE_SUCCESS - mock_create_build.status_code = requests.codes.OK - mock_request.side_effect = [get_build_response, mock_create_build] - client = get_client() - build = client.create_build( - Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'melodic', True)) - self.assertEqual(mock_request.call_count, 2) - self.assertEqual(build.get('guid'), 'build-guid') - self.assertEqual(build.get('buildName'), 'test_build') - self.assertFalse(build.is_partial) - - @patch('requests.request') - def test_create_build_with_webhook_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Source", - "repository": "https://github.com/rapyuta-robotics/io_tutorials.git", - "architecture": "amd64", - "rosDistro": "melodic", - "isRos": True, - "buildWebhooks": [ - { - "webhookType": "githubWorkflow", - "accessToken": "fake_access_token", - "workflowName": "fake.yaml" - } - ] - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - expected_get_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/build-guid' - mock_create_build = Mock() - mock_create_build.text = BUILD_CREATE_SUCCESS - mock_create_build.status_code = requests.codes.OK - mock_get_build = Mock() - mock_get_build.text = BUILD_GET_SUCCESS_WITH_BUILD_REQUESTS - mock_get_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_build, mock_get_build] - webhooks = [GithubWebhook(workflowName='fake.yaml', accessToken='fake_access_token')] - client = get_client() - created_build = client.create_build( - Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', - 'amd64', 'melodic', True, buildWebhooks=webhooks), False) - build = client.get_build('build-guid', include_build_requests=True) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_get_url, method='GET', params={'include_build_requests': True}), - ]) - self.assertEqual(created_build.get('guid'), 'build-guid') - self.assertEqual(created_build.get('buildName'), 'test_build') - self.assertEqual(build.buildRequests[0]['buildWebhooks'][0]['webhookType'], 'githubWorkflow') - self.assertEqual(build.buildRequests[0]['buildWebhooks'][0]['accessToken'], 'fake_access_token') - self.assertEqual(build.buildRequests[0]['buildWebhooks'][0]['workflowName'], 'fake.yaml') - self.assertEqual(build.buildRequests[0]['buildWebhooks'][0]['repositoryUrl'], 'https://github.com/rapyuta-robotics/io_tutorials.git') - - @patch('requests.request') - def test_get_build_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/{}'.format('build-guid') - mock_get_build = Mock() - mock_get_build.text = BUILD_GET_SUCCESS - mock_get_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_build] - client = get_client() - build = client.get_build('build-guid') - remove_auth_token(build) - delattr(build, 'dockerPullSecret') - expected_response = json.loads(BUILD_GET_SUCCESS) - expected_response[PartialMixin.PARTIAL_ATTR] = False - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='GET', - params=None) - self.assertEqual(build.get('guid'), 'build-guid') - self.assertEqual(build.get('buildName'), 'test_build') - self.assertEqual(build.to_dict(), expected_response) - self.assertFalse(build.is_partial) - - @patch('requests.request') - def test_get_build_with_guid_not_found(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/{}'.format('build-guid') - expected_err_msg = "build guid not found" - mock_get_build = Mock() - mock_get_build.text = BUILD_NOT_FOUND - mock_get_build.status_code = requests.codes.NOT_FOUND - mock_request.side_effect = [mock_get_build] - client = get_client() - with self.assertRaises(ResourceNotFoundError) as e: - client.get_build('build-guid') - self.assertEqual(str(e.exception), expected_err_msg) - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params=None) - - @patch('requests.request') - def test_get_build_with_query_params(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/{}'.format('build-guid') - expected_query_params = {'include_build_requests': True} - mock_get_build = Mock() - mock_get_build.text = BUILD_GET_SUCCESS_WITH_BUILD_REQUESTS - mock_get_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_build] - client = get_client() - build = client.get_build('build-guid', include_build_requests=True) - remove_auth_token(build) - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params=expected_query_params) - self.assertFalse(build.is_partial) - - @patch('requests.request') - def test_list_build_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - - mock_list_build = Mock() - mock_list_build.text = BUILD_LIST_SUCCESS - mock_list_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_build] - client = get_client() - builds = client.list_builds() - list(map(remove_auth_token, builds)) - list(map(lambda build: delattr(build, 'dockerPullSecret'), builds)) - expected_response = json.loads(BUILD_LIST_SUCCESS) - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params=None) - self.assertListEqual(builds, expected_response) - for build in builds: - self.assertTrue(build.is_partial) - - @patch('requests.request') - def test_build_refresh_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - - mock_list_build = Mock() - mock_list_build.text = BUILD_LIST_SUCCESS - mock_list_build.status_code = requests.codes.OK - mock_get_build = Mock() - mock_get_build.text = BUILD_GET_SUCCESS - mock_get_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_build, mock_get_build] - - client = get_client() - builds = client.list_builds() - build = builds[0] - self.assertTrue(build.is_partial) - builds[0].refresh() - - self.assertFalse(build.is_partial) - remove_auth_token(build) - expected_response = json.loads(BUILD_GET_SUCCESS) - expected_response[PartialMixin.PARTIAL_ATTR] = False - expected_response['dockerPullSecret'] = '' - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params=None), - call(headers=headers, json=None, url=expected_url+'/build-guid', method='GET', params={}), - ]) - self.assertEqual(build, expected_response) - - @patch('requests.request') - def test_list_builds_with_query_params_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build' - expected_query_params = {'status': ['Complete', 'BuildInProgress']} - mock_list_build = Mock() - mock_list_build.text = BUILD_LIST_SUCCESS - mock_list_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_build] - statuses = [BuildStatus.COMPLETE, BuildStatus.BUILD_IN_PROGRESS] - client = get_client() - builds = client.list_builds(statuses=statuses) - list(map(remove_auth_token, builds)) - list(map(lambda build: delattr(build, 'dockerPullSecret'), builds)) - expected_response = json.loads(BUILD_LIST_SUCCESS) - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params=expected_query_params) - self.assertListEqual(builds, expected_response) - for build in builds: - self.assertTrue(build.is_partial) - - def test_list_builds_with_invalid_statuses_type(self): - expected_err_msg = 'statuses must be an instance of list' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.list_builds(statuses={}) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_list_builds_with_invalid_status_value(self): - expected_err_msg = 'status must be of rapyuta_io.clients.build.BuildStatus' - client = get_client() - statuses = ['invalid-status'] - with self.assertRaises(InvalidParameterException) as e: - client.list_builds(statuses=statuses) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Source", - "architecture": "amd64", - "isRos": True, - "rosDistro": "melodic", - "repository": "https://github.com/rapyuta-robotics", - "contextDir": "contextDir", - "branch": "master", - "buildOptions": { - "catkinOptions": [ - { - "rosPkgs": "listener", - "cmakeArgs": None, - "makeArgs": None, - "blacklist": None, - "catkinMakeArgs": None - } - ] - }, - "secret": "test-secret" - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/{}'.format('build-guid') - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - setattr(build, '_host', 'https://gacatalog.apps.okd4v2.prod.rapyuta.io') - setattr(build, 'guid', 'build-guid') - setattr(build, '_auth_token', 'Bearer test_auth_token') - setattr(build, '_project', 'test_project') - mock_update_build = Mock() - mock_update_build.text = 'null' - mock_update_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_update_build] - build.buildInfo.repository = 'https://github.com/rapyuta-robotics' - build.buildInfo.branch = 'master' - build.buildInfo.contextDir = 'contextDir' - build.buildInfo.buildOptions = BuildOptions(catkinOptions=[CatkinOption(rosPkgs='listener')]) - build.secret = 'test-secret' - build.save() - mock_request.assert_called_with(headers=headers, json=expected_payload, - url=expected_url, method='PUT', params={}) - - @patch('requests.request') - def test_update_build_with_webhook_success(self, mock_request): - expected_payload = { - "buildName": "test_build", - "strategyType": "Source", - "architecture": "amd64", - "isRos": True, - "rosDistro": "melodic", - "repository": "https://github.com/rapyuta-robotics", - "contextDir": "contextDir", - "branch": "master", - "buildOptions": { - "catkinOptions": [ - { - "rosPkgs": "listener", - "cmakeArgs": None, - "makeArgs": None, - "blacklist": None, - "catkinMakeArgs": None - } - ] - }, - "secret": "test-secret", - "buildWebhooks": [ - { - "webhookType": "githubWorkflow", - "accessToken": "fake_access_token", - "workflowName": "fake.yaml" - } - ] - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/{}'.format('build-guid') - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - setattr(build, '_host', 'https://gacatalog.apps.okd4v2.prod.rapyuta.io') - setattr(build, 'guid', 'build-guid') - setattr(build, '_auth_token', 'Bearer test_auth_token') - setattr(build, '_project', 'test_project') - mock_update_build = Mock() - mock_update_build.text = 'null' - mock_update_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_update_build] - build.buildInfo.repository = 'https://github.com/rapyuta-robotics' - build.buildInfo.branch = 'master' - build.buildInfo.contextDir = 'contextDir' - build.buildInfo.buildOptions = BuildOptions(catkinOptions=[CatkinOption(rosPkgs='listener')]) - build.secret = 'test-secret' - build.buildWebhooks = [GithubWebhook(workflowName='fake.yaml', accessToken='fake_access_token')] - build.save() - mock_request.assert_called_with(headers=headers, json=expected_payload, - url=expected_url, method='PUT', params={}) - - @patch('requests.request') - def test_update_build_invalid_secret(self, mock_request): - expected_err_msg = 'secret must be a string' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.secret = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_docker_pull_secret(self, mock_request): - expected_err_msg = 'dockerPullSecret must be a string' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.dockerPullSecret = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_docker_push_repository(self, mock_request): - expected_err_msg = 'dockerPushRepository must be a string' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.dockerPushRepository = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_repository(self, mock_request): - expected_err_msg = 'repository must be a valid non-empty string' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.buildInfo.repository = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_branch(self, mock_request): - expected_err_msg = 'branch must be a valid non-empty string' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.buildInfo.branch = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_docker_file_path_usage_for_source_strategyType(self, mock_request): - expected_err_msg = 'cannot use dockerFilePath for source strategyType' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.buildInfo.dockerFilePath = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_context_directory(self, mock_request): - expected_err_msg = 'contextDir must be a string' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.buildInfo.contextDir = 1 - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_webhook(self, mock_request): - expected_err_msg = 'buildWebhooks must be a list of rapyuta_io.clients.build.GithubWebhook' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.buildWebhooks = '' - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_update_build_invalid_webhook_workflow(self, mock_request): - expected_err_msg = 'workflowName must be present and should be of string type' - build = Build('test_build', 'Source', 'https://github.com/rapyuta-robotics/io_tutorials.git', 'amd64', - 'melodic', True) - with self.assertRaises(InvalidParameterException) as e: - build.buildWebhooks = [GithubWebhook(workflowName='', accessToken='fake_access_token')] - build.save() - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_delete_build_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/{}'.format('build-guid') - get_build_response = MagicMock(spec=Response) - get_build_response.text = BUILD_GET_SUCCESS - get_build_response.status_code = requests.codes.OK - mock_delete_build = Mock() - mock_delete_build.text = None - mock_delete_build.status_code = requests.codes.OK - mock_request.side_effect = [get_build_response, mock_delete_build] - client = get_client() - client.delete_build('build-guid') - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='DELETE', params=None) - - @patch('requests.request') - def test_delete_build_build_not_found(self, mock_request): - expected_err_msg = 'build guid not found' - get_build_response = MagicMock(spec=Response) - get_build_response.text = BUILD_GET_SUCCESS - get_build_response.status_code = requests.codes.OK - mock_delete_build = Mock() - mock_delete_build.text = BUILD_NOT_FOUND - mock_delete_build.status_code = requests.codes.NOT_FOUND - mock_request.side_effect = [get_build_response, mock_delete_build] - client = get_client() - build = client.get_build('build-guid') - with self.assertRaises(ResourceNotFoundError) as e: - build.delete() - self.assertEqual(str(e.exception), expected_err_msg) - - def test_trigger_build_invalid_build_operation_info_type(self): - expected_err_msg = 'buildOperationInfo must be an instance of list' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.trigger_build(BuildOperation(buildOperationInfo={})) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_trigger_build_invalid_build_guid(self): - expected_err_msg = 'buildGuid must be a non-empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - build_op_info = [BuildOperationInfo("")] - req = BuildOperation(build_op_info) - client.trigger_build(BuildOperation(req)) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_trigger_build_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/trigger' - get_build_response = json.loads(BUILD_GET_SUCCESS) - mock_trigger_build = Mock() - mock_trigger_build.text = TRIGGER_BUILD_RESPONSE - mock_trigger_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_trigger_build] - trigger_request = BuildOperation([BuildOperationInfo('build-guid')]) - client = get_client() - trigger_response = client.trigger_build(trigger_request) - mock_request.assert_called_once_with(headers=headers, json=trigger_request, - url=expected_url, method='PUT', params=None) - self.assertEqual(get_build_response['buildGeneration'] + 1, - trigger_response['buildOperationResponse'][0]['buildGenerationNumber']) - - @patch('requests.request') - def test_trigger_build_success_with_trigger_name(self, mock_request): - expected_payload = { - "buildOperationInfo": [ - { - "buildGUID": "build-guid", - "triggerName": "trigger-name" - } - ] - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/trigger' - get_build_response = json.loads(BUILD_GET_SUCCESS) - mock_trigger_build = Mock() - mock_trigger_build.text = TRIGGER_BUILD_RESPONSE - mock_trigger_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_trigger_build] - trigger_request = BuildOperation([BuildOperationInfo('build-guid', triggerName='trigger-name')]) - client = get_client() - trigger_response = client.trigger_build(trigger_request) - mock_request.assert_called_once_with(headers=headers, json=expected_payload, - url=expected_url, method='PUT', params=None) - self.assertEqual(get_build_response['buildGeneration'] + 1, - trigger_response['buildOperationResponse'][0]['buildGenerationNumber']) - - @patch('requests.request') - def test_trigger_build_success_with_tag_name(self, mock_request): - expected_payload = { - "buildOperationInfo": [ - { - "buildGUID": "build-guid", - "tagName": "tag-name" - } - ] - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/trigger' - get_build_response = json.loads(BUILD_GET_SUCCESS) - mock_trigger_build = Mock() - mock_trigger_build.text = TRIGGER_BUILD_RESPONSE - mock_trigger_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_trigger_build] - trigger_request = BuildOperation([BuildOperationInfo('build-guid', tagName='tag-name')]) - client = get_client() - trigger_response = client.trigger_build(trigger_request) - mock_request.assert_called_once_with(headers=headers, json=expected_payload, - url=expected_url, method='PUT', params=None) - self.assertEqual(get_build_response['buildGeneration'] + 1, - trigger_response['buildOperationResponse'][0]['buildGenerationNumber']) - - @patch('requests.request') - def test_trigger_build_build_in_progress_error(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/trigger' - expected_err_msg = "build is in BuildInProgress state" - mock_trigger_build = Mock() - mock_trigger_build.text = BUILD_IN_PROGRESS_ERROR - mock_trigger_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_trigger_build] - trigger_request = BuildOperation([BuildOperationInfo('build-guid')]) - client = get_client() - trigger_response = client.trigger_build(trigger_request) - mock_request.assert_called_once_with(headers=headers, json=trigger_request, - url=expected_url, method='PUT', params=None) - self.assertEqual(trigger_response['buildOperationResponse'][0]['error'], expected_err_msg) - - @patch('requests.request') - def test_trigger_build_guid_not_found(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/trigger' - expected_err_msg = "build guid not found" - mock_trigger_build = Mock() - mock_trigger_build.text = BUILD_GUID_NOT_FOUND - mock_trigger_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_trigger_build] - trigger_request = BuildOperation([BuildOperationInfo('build-guid-1')]) - client = get_client() - trigger_response = client.trigger_build(trigger_request) - mock_request.assert_called_once_with(headers=headers, json=trigger_request, - url=expected_url, method='PUT', params=None) - self.assertEqual(trigger_response['buildOperationResponse'][0]['error'], expected_err_msg) - - @patch('requests.request') - def test_rollback_build_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/rollback' - get_build_response = json.loads(BUILD_GET_SUCCESS) - mock_rollback_build = Mock() - mock_rollback_build.text = ROLLBACK_BUILD_RESPONSE - mock_rollback_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_rollback_build] - rollback_request = BuildOperation([BuildOperationInfo('build-guid', 1)]) - client = get_client() - rollback_response = client.rollback_build(rollback_request) - mock_request.assert_called_once_with(headers=headers, json=rollback_request, - url=expected_url, method='PUT', params=None) - self.assertEqual(get_build_response['buildGeneration'], - rollback_response['buildOperationResponse'][0]['buildGenerationNumber']) - - @patch('requests.request') - def test_rollback_build_build_in_progress_error(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/rollback' - expected_err_msg = "build is in BuildInProgress state" - mock_rollback_build = Mock() - mock_rollback_build.text = BUILD_IN_PROGRESS_ERROR - mock_rollback_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_rollback_build] - rollback_request = BuildOperation([BuildOperationInfo('build-guid', 1)]) - client = get_client() - rollback_response = client.rollback_build(rollback_request) - mock_request.assert_called_once_with(headers=headers, json=rollback_request, - url=expected_url, method='PUT', params=None) - self.assertEqual(rollback_response['buildOperationResponse'][0]['error'], expected_err_msg) - - @patch('requests.request') - def test_rollback_build_guid_not_found(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/build/operation/rollback' - expected_err_msg = "build guid not found" - mock_rollback_build = Mock() - mock_rollback_build.text = BUILD_GUID_NOT_FOUND - mock_rollback_build.status_code = requests.codes.OK - mock_request.side_effect = [mock_rollback_build] - rollback_request = BuildOperation([BuildOperationInfo('build-guid-1', 1)]) - client = get_client() - rollback_response = client.rollback_build(rollback_request) - mock_request.assert_called_once_with(headers=headers, json=rollback_request, - url=expected_url, method='PUT', params=None) - self.assertEqual(rollback_response['buildOperationResponse'][0]['error'], expected_err_msg) - - @patch('requests.request') - def test_rollback_build_invalid_build_gen_number(self, mock_request): - expected_err_msg = 'build generation number must be an integer and greater than 0' - get_build_response = MagicMock(spec=Response) - get_build_response.text = BUILD_GET_SUCCESS - get_build_response.status_code = requests.codes.OK - mock_request.side_effect = [get_build_response] - build = get_client().get_build('build-guid') - with self.assertRaises(InvalidParameterException) as e: - build.rollback(-1) - self.assertEqual(str(e.exception), expected_err_msg) diff --git a/tests/client_get_package_test.py b/tests/client_get_package_test.py deleted file mode 100644 index a99c819f..00000000 --- a/tests/client_get_package_test.py +++ /dev/null @@ -1,221 +0,0 @@ -# encoding: utf-8 -from __future__ import absolute_import -import requests -import unittest - -from mock import patch, Mock -from requests import Response - -from rapyuta_io.clients.package import Package -from rapyuta_io.clients.persistent_volumes import PersistentVolumes -from rapyuta_io.clients.plan import Plan -from rapyuta_io.utils.error import APIError, PackageNotFound, PlanNotFound, InternalServerError,\ - InvalidParameterException -from tests.utils.client import get_client -from tests.utils.package_responses import PACKAGE_OK_VALIDATE, PACKAGES_LIST, PERSISTENT_VOLUME_INFO - - -class ClientPackageTests(unittest.TestCase): - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_package_ok(self, rest_mock, response): - response.text = PACKAGE_OK_VALIDATE - response.status_code = requests.codes.OK - rest_mock.return_value = response - client = get_client() - pkg = client.get_package('test_package_id') - rest_mock.assert_called_once() - self.assertIsInstance(pkg, Package) - self.assertEqual(pkg.packageId, 'test_package_id') - self.assertEqual(pkg.packageName, 'test-1.0') - self.assertEqual(pkg._auth_token, 'Bearer test_auth_token') - self.assertFalse(pkg.is_partial) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_package_no_plan(self, rest_mock, response): - response.text = PACKAGE_OK_VALIDATE - response.status_code = requests.codes.OK - rest_mock.return_value = response - client = get_client() - pkg = client.get_package('my_package') - with self.assertRaises(PlanNotFound): - pkg.get_plan_by_id('test_plan_id') - rest_mock.assert_called_once() - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_package_no_pkg_info(self, rest_mock, response): - response.text = '{}' - response.status_code = requests.codes.OK - rest_mock.return_value = response - client = get_client() - with self.assertRaises(APIError): - client.get_package('test_package_id') - rest_mock.assert_called_once() - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_package_no_service_id(self, rest_mock, response): - response.text = '{}' - response.status_code = requests.codes.NOT_FOUND - rest_mock.return_value = response - client = get_client() - with self.assertRaises(PackageNotFound): - client.get_package('test_package_id') - rest_mock.assert_called_once() - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_package_api_error(self, rest_mock, response): - response.text = '{}' - response.status_code = requests.codes.INTERNAL_SERVER_ERROR - rest_mock.return_value = response - client = get_client() - with self.assertRaises(InternalServerError): - client.get_package('test_package_id') - rest_mock.assert_called_once() - - def test_get_all_packages_failure_invalid_filter_name(self): - invalid_filter_name = 25 - expected_err_msg = 'name must be a string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.get_all_packages(name=invalid_filter_name) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_get_all_packages_failure_invalid_filter_version(self): - invalid_filter_version = 1.0 - expected_err_msg = 'version must be a string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.get_all_packages(version=invalid_filter_version) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_all_packages_success_no_filter_parameters(self, rest_mock, response): - response.text = PACKAGES_LIST - response.status_code = requests.codes.OK - rest_mock.return_value = response - rest_mock.side_effect = [response] - client = get_client() - pkg_list = client.get_all_packages() - rest_mock.assert_called_once() - self.assertEqual(len(pkg_list), 2) - for pkg in pkg_list: - self.assertIsInstance(pkg, Package, 'pkg should be instance of Package class') - self.assertTrue(pkg.is_partial) - self.assertEqual(pkg_list[0].packageName, 'test_package') - self.assertEqual(pkg_list[0].packageId, 'package_id') - - @patch('requests.request') - def test_get_all_packages_success_filter_name_only(self, rest_mock): - filter_name = 'test' - all_packages = Mock() - all_packages.text = PACKAGES_LIST - all_packages.status_code = requests.codes.OK - rest_mock.side_effect = [all_packages] - client = get_client() - pkgs = client.get_all_packages(name=filter_name) - self.assertEqual(rest_mock.call_count, 1) - self.assertEqual(len(pkgs), 1) - for pkg in pkgs: - self.assertIsInstance(pkg, Package, 'pkg should be instance of Package class') - self.assertTrue(pkg.is_partial) - self.assertIn(filter_name, pkgs[0].packageName) - - @patch('requests.request') - def test_get_all_packages_success_filter_version_only(self, rest_mock): - filter_version = 'v1.0' - all_packages = Mock() - all_packages.text = PACKAGES_LIST - all_packages.status_code = requests.codes.OK - rest_mock.side_effect = [all_packages] - client = get_client() - pkgs = client.get_all_packages(version=filter_version) - self.assertEqual(rest_mock.call_count, 1) - self.assertEqual(len(pkgs), 2) - for pkg in pkgs: - self.assertIsInstance(pkg, Package, 'pkg should be instance of Package class') - self.assertTrue(pkg.is_partial) - self.assertEqual(filter_version, pkgs[0].packageVersion) - - @patch('requests.request') - def test_get_all_packages_success_filter_name_filter_version(self, rest_mock): - filter_version = 'v1.0' - filter_name = 'test' - all_packages = Mock() - all_packages.text = PACKAGES_LIST - all_packages.status_code = requests.codes.OK - rest_mock.side_effect = [all_packages] - client = get_client() - pkgs = client.get_all_packages(name=filter_name, version=filter_version) - self.assertEqual(rest_mock.call_count, 1) - self.assertEqual(len(pkgs), 1) - for pkg in pkgs: - self.assertIsInstance(pkg, Package, 'pkg should be instance of Package class') - self.assertTrue(pkg.is_partial) - self.assertIn(filter_name, pkgs[0].packageName) - self.assertEqual(filter_version, pkgs[0].packageVersion) - - @patch('requests.request') - def test_get_all_packages_success_no_data_filter_name_filter_version(self, rest_mock): - filter_version = 'v1.1' - filter_name = 'test' - all_packages = Mock() - all_packages.text = PACKAGES_LIST - all_packages.status_code = requests.codes.OK - rest_mock.side_effect = [all_packages] - client = get_client() - pkgs = client.get_all_packages(name=filter_name, version=filter_version) - self.assertEqual(rest_mock.call_count, 1) - self.assertEqual(len(pkgs), 0) - - @patch('requests.request') - def test_package_refresh_ok(self, rest_mock): - package_list = Mock() - package_list.text = PACKAGES_LIST - package_list.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE - get_package.status_code = requests.codes.OK - rest_mock.side_effect = [package_list, get_package] - client = get_client() - pkg_list = client.get_all_packages() - pkg = pkg_list[0] - self.assertTrue(pkg.is_partial) - pkg.refresh() - self.assertFalse(pkg.is_partial) - self.assertIsInstance(pkg, Package, 'pkg should be instance of Package class') - self.assertEqual(pkg_list[0].packageName, 'test-1.0') - self.assertEqual(pkg_list[0].packageId, 'pkg-xlhpyvigqoorhnomeryjfjqx') - self.assertEqual(rest_mock.call_count, 2) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_all_packages_api_error(self, rest_mock, response): - response.text = {} - response.status_code = requests.codes.INTERNAL_SERVER_ERROR - rest_mock.return_value = response - client = get_client() - with self.assertRaises(InternalServerError): - client.get_all_packages() - rest_mock.assert_called_once() - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_persistent_volume_ok(self, rest_mock, response): - response.text = PERSISTENT_VOLUME_INFO - response.status_code = requests.codes.OK - rest_mock.return_value = response - client = get_client() - persistent_volume = client.get_persistent_volume() - self.assertIsInstance(persistent_volume, PersistentVolumes, - 'object should be instance of PersitentVolumes class') - self.assertEqual(persistent_volume.packageId, 'io-public-persistent-volume') - self.assertEqual(persistent_volume.packageName, 'Rapyuta IO Persistent Volume') - for plan in persistent_volume.plans: - self.assertIsInstance(plan, Plan, 'Object should be instance of class Plan') - rest_mock.assert_called_once() diff --git a/tests/deployment_test.py b/tests/deployment_test.py deleted file mode 100644 index 8d2f9f61..00000000 --- a/tests/deployment_test.py +++ /dev/null @@ -1,232 +0,0 @@ -from __future__ import absolute_import -import requests -import unittest -import json - -from mock import Mock, patch, MagicMock, call -from requests import Response - -from rapyuta_io import DeploymentPhaseConstants -from rapyuta_io.utils import InternalServerError, RetriesExhausted, InvalidParameterException -from rapyuta_io.utils.rest_client import HttpMethod -from sdk_test.util import get_manifest_file -from tests.utils.client import get_client, headers -from tests.utils.package_responses import DEPLOYMENT_INFO, \ - DEPLOYMENT_STATUS_RUNNING, DEPLOYMENT_BINDING_OK, DEPLOYMENT_LIST, DEPLOYMENT_STATUS_PENDING, \ - DEPLOYMENT_STATUS_RUNNING_PHASE_PROVISIONING, UPDATE_DEPLOYMENT - - -class DeploymentTest(unittest.TestCase): - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_package_bindable(self, rest_mock, deployment_info_rseponse): - deployment_info_rseponse.text = DEPLOYMENT_INFO - deployment_info_rseponse.status_code = requests.codes.OK - binding_response = deployment_info_rseponse() - binding_response.text = DEPLOYMENT_BINDING_OK - binding_response.status_code = requests.codes.OK - rest_mock.side_effect = [deployment_info_rseponse, binding_response] - client = get_client() - deployment = client.get_deployment('deploment_id') - binding_result = deployment.get_service_binding('binding_id') - self.assertIsNotNone(binding_result, 'binding response should not be empty') - self.assertIn('credentials', binding_result, 'Credentials should not be empty') - self.assertEqual(rest_mock.call_count, 2) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_get_deployment_status_ok(self, rest_mock, deployment_info_response): - deployment_info_response.text = DEPLOYMENT_INFO - deployment_info_response.status_code = requests.codes.OK - deployment_status_response = deployment_info_response() - deployment_status_response.text = DEPLOYMENT_STATUS_RUNNING - deployment_status_response.status_code = requests.codes.OK - rest_mock.side_effect = [deployment_info_response, deployment_status_response] - client = get_client() - deployment = client.get_deployment('deployment_id') - self.assertFalse(deployment.is_partial) - deployment_status = deployment.get_status() - self.assertEqual(deployment_status.packageId, 'package_id') - self.assertEqual(deployment_status.planId, 'test-plan') - self.assertEqual(deployment_status.status, 'Running') - self.assertEqual(deployment_status.phase, 'Succeeded') - self.assertEqual(rest_mock.call_count, 2) - - @patch('requests.request') - def test_poll_deployment_till_ready_ok(self, mock_request): - deployment_info_response = MagicMock(spec=Response) - deployment_info_response.text = DEPLOYMENT_INFO - deployment_info_response.status_code = requests.codes.OK - first_deployment_status_response = MagicMock(spec=Response) - first_deployment_status_response.text = DEPLOYMENT_STATUS_PENDING - first_deployment_status_response.status_code = requests.codes.OK - second_deployment_status_response = MagicMock(spec=Response) - second_deployment_status_response.text = DEPLOYMENT_STATUS_RUNNING - second_deployment_status_response.status_code = requests.codes.OK - mock_request.side_effect = [deployment_info_response, first_deployment_status_response, - second_deployment_status_response] - deployment = get_client().get_deployment('deployment_id') - deployment_status = deployment.poll_deployment_till_ready(retry_count=2, sleep_interval=0) - - self.assertEqual(deployment_status.packageId, 'package_id') - self.assertEqual(deployment_status.planId, 'test-plan') - self.assertEqual(deployment_status.status, 'Running') - self.assertEqual(deployment_status.phase, 'Succeeded') - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_poll_deployment_till_ready_retries_exhausted(self, mock_request): - deployment_info_response = MagicMock(spec=Response) - deployment_info_response.text = DEPLOYMENT_INFO - deployment_info_response.status_code = requests.codes.OK - first_deployment_status_response = MagicMock(spec=Response) - first_deployment_status_response.text = DEPLOYMENT_STATUS_PENDING - first_deployment_status_response.status_code = requests.codes.OK - second_deployment_status_response = MagicMock(spec=Response) - second_deployment_status_response.text = DEPLOYMENT_STATUS_RUNNING_PHASE_PROVISIONING - second_deployment_status_response.status_code = requests.codes.OK - mock_request.side_effect = [deployment_info_response, first_deployment_status_response, - second_deployment_status_response] - - deployment = get_client().get_deployment('deployment_id') - regexp = 'Retries exhausted: Tried 2 times with 0s interval. Deployment: phase=Provisioning status=Running' + \ - ' errors=None' - with self.assertRaisesRegex(RetriesExhausted, regexp): - deployment.poll_deployment_till_ready(retry_count=2, sleep_interval=0) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_package_deprovision_api_error(self, rest_mock, deployment_info_response): - deployment_info_response.text = DEPLOYMENT_INFO - deployment_info_response.status_code = requests.codes.OK - deprovision_response = deployment_info_response() - deprovision_response.status_code = requests.codes.INTERNAL_SERVER_ERROR - rest_mock.side_effect = [deployment_info_response, deprovision_response] - client = get_client() - deployment = client.get_deployment('deployment_id') - with self.assertRaises(InternalServerError): - deployment.deprovision() - self.assertEqual(rest_mock.call_count, 2) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_package_bindable_api_error(self, rest_mock, deployment_info_response): - deployment_info_response.text = DEPLOYMENT_INFO - deployment_info_response.status_code = requests.codes.OK - binding_response = deployment_info_response() - binding_response.status_code = requests.codes.INTERNAL_SERVER_ERROR - rest_mock.side_effect = [deployment_info_response, binding_response] - client = get_client() - deployment = client.get_deployment('deployment_id') - with self.assertRaises(InternalServerError): - deployment.get_service_binding() - self.assertEqual(rest_mock.call_count, 2) - - @patch('requests.Response', spec=Response) - @patch('rapyuta_io.utils.rest_client.RestClient.execute') - def test_deployment_status_api_error(self, rest_mock, deployment_info_response): - deployment_info_response.text = DEPLOYMENT_INFO - deployment_info_response.status_code = requests.codes.OK - deployment_status_response = deployment_info_response() - deployment_status_response.status_code = requests.codes.INTERNAL_SERVER_ERROR - rest_mock.side_effect = [deployment_info_response, deployment_status_response] - client = get_client() - deployment = client.get_deployment('deployment_id') - with self.assertRaises(InternalServerError): - deployment.get_status() - self.assertEqual(rest_mock.call_count, 2) - - @patch('rapyuta_io.clients.catalog_client.CatalogClient._execute') - def test_get_deployment_list_ok(self, catalog_mock_execute): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - expected_query_param = {'phase': ['Succeeded', 'Provisioning']} - catalog_mock_execute.return_value = MagicMock() - catalog_mock_execute.return_value.status_code = 200 - catalog_mock_execute.return_value.text = DEPLOYMENT_LIST - phases = [DeploymentPhaseConstants.SUCCEEDED, DeploymentPhaseConstants.PROVISIONING] - deployments = get_client().get_all_deployments(phases=phases) - - catalog_mock_execute.assert_called_once_with(expected_url, HttpMethod.GET, 0, - query_params=expected_query_param) - for dep in deployments: - self.assertTrue(dep.is_partial) - - @patch('rapyuta_io.clients.catalog_client.CatalogClient._execute') - def test_get_deployment_list_without_query_param(self, catalog_mock_execute): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - catalog_mock_execute.return_value = MagicMock() - catalog_mock_execute.return_value.status_code = 200 - catalog_mock_execute.return_value.text = DEPLOYMENT_LIST - get_client().get_all_deployments() - catalog_mock_execute.assert_called_once_with(expected_url, HttpMethod.GET, 0, query_params={}) - - @patch('rapyuta_io.clients.catalog_client.CatalogClient._execute') - def test_get_deployment_list_with_phase_query_param(self, catalog_mock_execute): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - expected_query_param = {'phase': ['Succeeded', 'Provisioning']} - catalog_mock_execute.return_value = MagicMock() - catalog_mock_execute.return_value.status_code = 200 - catalog_mock_execute.return_value.text = DEPLOYMENT_LIST - get_client().get_all_deployments(phases=[DeploymentPhaseConstants.SUCCEEDED, DeploymentPhaseConstants.PROVISIONING]) - catalog_mock_execute.assert_called_once_with(expected_url, HttpMethod.GET, 0, query_params=expected_query_param) - - @patch('requests.request') - def test_get_bad_request_error_with_invalid_device_id(self, mock_request): - expected_err_msg = 'invalid deviceID' - with self.assertRaises(InvalidParameterException) as e: - get_client().get_all_deployments(device_id=1234) - - self.assertEqual(str(e.exception), expected_err_msg) - self.assertEqual(mock_request.call_count, 0) - - @patch('requests.request') - def test_get_filtered_deployment_list_with_valid_device_id(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - expected_query_param = {'device_uid': 'test-device-id'} - client = get_client() - mock_get_filtered_deployment = Mock() - mock_get_filtered_deployment.status_code = 200 - mock_get_filtered_deployment.text = DEPLOYMENT_LIST - mock_request.side_effect = [mock_get_filtered_deployment] - client.get_all_deployments(device_id='test-device-id') - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='GET', - params=expected_query_param) - self.assertEqual(mock_get_filtered_deployment.status_code, 200) - - @patch('requests.request') - def test_deployment_refresh_ok(self, mock_request): - deployment_list = Mock() - deployment_list.text = DEPLOYMENT_LIST - deployment_list.status_code = requests.codes.OK - get_deployment = Mock() - get_deployment.text = DEPLOYMENT_STATUS_RUNNING - get_deployment.status_code = requests.codes.OK - mock_request.side_effect = [deployment_list, get_deployment] - - client = get_client() - deployments = client.get_all_deployments() - self.assertTrue(deployments[0].is_partial) - deployments[0].refresh() - self.assertFalse(deployments[0].is_partial) - self.assertEqual(deployments[0].packageId, 'package_id') - self.assertEqual(deployments[0].planId, 'test-plan') - self.assertEqual(deployments[0].status, 'Running') - self.assertEqual(deployments[0].phase, 'Succeeded') - self.assertEqual(mock_request.call_count, 2) - - @patch('rapyuta_io.clients.catalog_client.CatalogClient._execute') - def test_update_deployment_success(self, catalog_mock_execute): - catalog_mock_execute.return_value = MagicMock() - catalog_mock_execute.return_value.status_code = 200 - catalog_mock_execute.return_value.text = UPDATE_DEPLOYMENT - payload = json.loads(UPDATE_DEPLOYMENT) - get_client().update_deployment(payload, 0) - catalog_mock_execute.assert_has_calls([call( - 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/v2/service_instances/dep-xyiwwwfongcfhpkhqlohtbee', - HttpMethod.PATCH, 0, - payload=payload)]) diff --git a/tests/native_network_test.py b/tests/native_network_test.py deleted file mode 100644 index 85141a5f..00000000 --- a/tests/native_network_test.py +++ /dev/null @@ -1,536 +0,0 @@ -from __future__ import absolute_import -import unittest -import requests -from mock import patch, Mock, call -from rapyuta_io.utils import ResourceNotFoundError - -from rapyuta_io.utils.error import InvalidParameterException -from tests.utils.client import get_client, headers, add_auth_token -from rapyuta_io.clients.package import Runtime, ROSDistro, Device -from rapyuta_io.clients.native_network import NativeNetwork, Parameters -from tests.utils.native_network_responses import NATIVE_NETWORK_CREATE_SUCCESS, NATIVE_NETWORK_LIST_SUCCESS, \ - NATIVE_NETWORK_GET_SUCCESS, NATIVE_NETWORK_FAILURE, NATIVE_NETWORK_NOT_FOUND -from rapyuta_io.clients.common_models import Limits - -class NativeNetworkTests(unittest.TestCase): - def setUp(self): - native_network = { - "ID": 1, - "name": "native_network_name", - "guid": "net-guid", - "ownerProject": "project-id", - "creator": "creator-id", - "runtime": "cloud", - "rosDistro": "kinetic", - "internalDeploymentGUID": "dep-id", - "internalDeploymentStatus": { - "phase": "Succeeded", - "status": "Running" - }, - "parameters": { - "limits": { - "cpu": 1, - "memory": 4096 - } - } - } - self.native_network = NativeNetwork.deserialize(native_network) - add_auth_token(self.native_network) - - def test_create_native_network_name_empty(self): - expected_err_msg = 'name must be a non-empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network(NativeNetwork('', Runtime.CLOUD, ROSDistro.KINETIC)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_invalid_name(self): - expected_err_msg = 'name must be a non-empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network(NativeNetwork(1, Runtime.CLOUD, ROSDistro.KINETIC)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_noetic_device_err(self): - with self.assertRaises(InvalidParameterException) as e: - NativeNetwork('native_network_name', Runtime.DEVICE, ROSDistro.NOETIC) - self.assertEqual(str(e.exception), 'device runtime does not support noetic ros_distro yet') - - def test_create_native_network_invalid_runtime(self): - expected_err_msg = 'runtime must be one of rapyuta_io.clients.package.Runtime' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network(NativeNetwork('native_network_name', 'invalid_runtime', ROSDistro.KINETIC)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_invalid_rosdistro(self): - expected_err_msg = 'ros_distro must be one of rapyuta_io.clients.package.ROSDistro' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network(NativeNetwork('native_network_name', Runtime.CLOUD, 'invalid rosdistro')) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_invalid_parameters(self): - expected_err_msg = 'parameters must be of type rapyuta_io.clients.native_network.Parameters' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network(NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.MELODIC, - 'invalid_parameters')) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_parameters_invalid_device(self): - expected_err_msg = 'device must be of type rapyuta_io.clients.device.Device' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - parameters = Parameters(device='device', network_interface='lo') - client.create_native_network( - NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_parameters_empty_device_uuid(self): - expected_err_msg = 'uuid field must be present in rapyuta_io.clients.device.Device object' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - device = Device('dev-name') - device.uuid = '' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='lo') - client.create_native_network( - NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_parameters_empty_ip_interfaces(self): - expected_err_msg = 'ip_interfaces field must be present in rapyuta_io.clients.device.Device object' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - device = Device('dev-name') - device.uuid = 'random' - parameters = Parameters(device=device, network_interface='lo') - client.create_native_network( - NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_parameters_invalid_network_interface(self): - expected_err_msg = 'NETWORK_INTERFACE should be in [\'lo\']' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - device = Device('dev-name') - device.uuid = 'random' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='docker0') - client.create_native_network( - NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_parameters_invalid_restart_policy(self): - expected_err_msg = 'RestartPolicy must be one of rapyuta_io.clients.package.RestartPolicy' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - device = Device('dev-name') - device.uuid = 'random' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='lo', restart_policy='') - client.create_native_network( - NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_no_parameters(self): - expected_err_msg = 'parameters must be present for device runtime' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network( - NativeNetwork('native_network_name', Runtime.DEVICE, ROSDistro.MELODIC, None)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_no_device_id(self): - expected_err_msg = 'device_id field must be present in rapyuta_io.clients.' \ - 'native_network.Parameters object for device runtime' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - device = Device('dev-name') - device.uuid = 'random' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='lo') - parameters.device_id = '' - client.create_native_network( - NativeNetwork('native_network_name', Runtime.DEVICE, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_device_runtime_no_network_interface(self): - expected_err_msg = 'network_interface must be present in rapyuta_io.clients.' \ - 'native_network.Parameters object for device runtime' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - device = Device('dev-name') - device.uuid = 'random' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='lo') - parameters.network_interface = '' - client.create_native_network( - NativeNetwork('native_network_name', Runtime.DEVICE, ROSDistro.MELODIC, parameters)) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_native_network_object_invalid_native_network_payload_object(self): - expected_err_msg = 'native_network must be non-empty and of type ' \ - 'rapyuta_io.clients.native_network.NativeNetwork' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_native_network(1) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_create_noetic_native_network_success(self, mock_request): - expected_payload = { - "name": "native_network_name", - "runtime": 'cloud', - "rosDistro": 'noetic' - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_create_native_network = Mock() - mock_create_native_network.text = NATIVE_NETWORK_CREATE_SUCCESS - mock_create_native_network.status_code = requests.codes.OK - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_native_network, mock_get_native_network] - - client = get_client() - native_network_parameters = None - native_network_payload = NativeNetwork("native_network_name", Runtime.CLOUD, ROSDistro.NOETIC, - native_network_parameters) - native_network_response = client.create_native_network(native_network_payload) - print(headers, expected_payload, expected_url, 'POST', None) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-guid', method='GET', params=None) - ]) - self.assertEqual(native_network_response.guid, 'net-guid') - self.assertEqual(native_network_response.name, 'native_network_name') - self.assertFalse(native_network_response.is_partial) - - @patch('requests.request') - def test_create_native_network_success(self, mock_request): - expected_payload = { - "name": "native_network_name", - "runtime": 'cloud', - "rosDistro": 'kinetic', - "parameters": {"limits": {"cpu": 1, "memory": 1024}} - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_create_native_network = Mock() - mock_create_native_network.text = NATIVE_NETWORK_CREATE_SUCCESS - mock_create_native_network.status_code = requests.codes.OK - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_native_network, mock_get_native_network] - - client = get_client() - native_network_parameters = Parameters(limits=Limits(1,1024)) - native_network_payload = NativeNetwork("native_network_name", Runtime.CLOUD, ROSDistro.KINETIC, - native_network_parameters) - native_network_response = client.create_native_network(native_network_payload) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-guid', method='GET', params=None) - ]) - self.assertEqual(native_network_response.guid, 'net-guid') - self.assertEqual(native_network_response.name, 'native_network_name') - self.assertFalse(native_network_response.is_partial) - - @patch('requests.request') - def test_create_native_network_success_without_parameters(self, mock_request): - expected_payload = { - "name": "native_network_name", - "runtime": 'cloud', - "rosDistro": 'kinetic' - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_create_native_network = Mock() - mock_create_native_network.text = NATIVE_NETWORK_CREATE_SUCCESS - mock_create_native_network.status_code = requests.codes.OK - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_native_network, mock_get_native_network] - - client = get_client() - native_network_payload = NativeNetwork("native_network_name", Runtime.CLOUD, ROSDistro.KINETIC) - native_network_response = client.create_native_network(native_network_payload) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-guid', method='GET', params=None) - ]) - self.assertEqual(native_network_response.guid, 'net-guid') - self.assertEqual(native_network_response.name, 'native_network_name') - - @patch('requests.request') - def test_create_device_native_network_success(self, mock_request): - expected_payload = { - "name": "native_network_name", - "runtime": 'device', - "rosDistro": 'melodic', - "parameters": {"device_id": "random", "NETWORK_INTERFACE": "lo"} - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_create_native_network = Mock() - mock_create_native_network.text = NATIVE_NETWORK_CREATE_SUCCESS - mock_create_native_network.status_code = requests.codes.OK - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_native_network, mock_get_native_network] - - client = get_client() - device = Device('dev-name') - device.uuid = 'random' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='lo') - native_network_payload = NativeNetwork("native_network_name", Runtime.DEVICE, ROSDistro.MELODIC, - parameters) - native_network_response = client.create_native_network(native_network_payload) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-guid', method='GET', params=None) - ]) - self.assertEqual(native_network_response.guid, 'net-guid') - self.assertEqual(native_network_response.name, 'native_network_name') - self.assertFalse(native_network_response.is_partial) - - def test_get_native_network_invalid_guid(self): - expected_err_msg = 'guid needs to be a non empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.get_native_network(None) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_get_native_network_guid_empty(self): - expected_err_msg = 'guid needs to be a non empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.get_native_network('') - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_get_native_network_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork/{}'.format('net-guid') - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_native_network] - - client = get_client() - native_network = client.get_native_network('net-guid') - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='GET', - params=None) - self.assertEqual(native_network.name, 'native_network_name') - self.assertEqual(native_network.runtime, 'cloud') - self.assertEqual(native_network.ros_distro, 'kinetic') - self.assertEqual(native_network.parameters.limits.cpu, 1) - self.assertEqual(native_network.parameters.limits.memory, 4096) - self.assertEqual(native_network.updated_at, '2021-02-05T13:16:08.736362Z') - self.assertEqual(native_network.guid, 'net-guid') - self.assertEqual(native_network.owner_project, 'project-id') - self.assertEqual(native_network.creator, 'creator-id') - self.assertEqual(native_network.internal_deployment_guid, 'dep-id') - self.assertEqual(native_network.internal_deployment_status.phase, 'Succeeded') - self.assertFalse(native_network.is_partial) - - @patch('requests.request') - def test_list_native_network_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_list_native_network = Mock() - mock_list_native_network.text = NATIVE_NETWORK_LIST_SUCCESS - mock_list_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_native_network] - - client = get_client() - native_network_list = client.list_native_networks() - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='GET', - params=None) - self.assertEqual(native_network_list[0].name, 'native_network_name') - self.assertEqual(native_network_list[0].runtime, 'cloud') - self.assertEqual(native_network_list[0].ros_distro, 'kinetic') - self.assertEqual(native_network_list[0].parameters.limits.cpu, 1) - self.assertEqual(native_network_list[0].parameters.limits.memory, 4096) - self.assertEqual(native_network_list[0].updated_at, '2021-02-05T13:16:08.736362Z') - self.assertEqual(native_network_list[0].guid, 'net-guid') - self.assertEqual(native_network_list[0].owner_project, 'project-id') - self.assertEqual(native_network_list[0].creator, 'creator-id') - self.assertEqual(native_network_list[0].internal_deployment_guid, 'dep-id') - self.assertEqual(native_network_list[0].internal_deployment_status.phase, 'Succeeded') - for net in native_network_list: - self.assertTrue(net.is_partial) - - @patch('requests.request') - def test_native_network_refresh_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_list_native_network = Mock() - mock_list_native_network.text = NATIVE_NETWORK_LIST_SUCCESS - mock_list_native_network.status_code = requests.codes.OK - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_native_network, mock_get_native_network] - - client = get_client() - native_network_list = client.list_native_networks() - self.assertTrue(native_network_list[0].is_partial) - native_network_list[0].refresh() - self.assertFalse(native_network_list[0].is_partial) - - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params=None), - call(headers=headers, json=None, url=expected_url + '/net-guid', method='GET', params={}), - ]) - self.assertEqual(native_network_list[0].name, 'native_network_name') - self.assertEqual(native_network_list[0].runtime, 'cloud') - self.assertEqual(native_network_list[0].ros_distro, 'kinetic') - self.assertEqual(native_network_list[0].parameters.limits.cpu, 1) - self.assertEqual(native_network_list[0].parameters.limits.memory, 4096) - self.assertEqual(native_network_list[0].updated_at, '2021-02-05T13:16:08.736362Z') - self.assertEqual(native_network_list[0].guid, 'net-guid') - self.assertEqual(native_network_list[0].owner_project, 'project-id') - self.assertEqual(native_network_list[0].creator, 'creator-id') - self.assertEqual(native_network_list[0].internal_deployment_guid, 'dep-id') - self.assertEqual(native_network_list[0].internal_deployment_status.phase, 'Succeeded') - self.assertEqual(native_network_list[0].internal_deployment_status.status, 'Running') - - def test_delete_native_network_invalid_guid(self): - expected_err_msg = 'guid needs to be a non empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.delete_native_network(None) - self.assertEqual(str(e.exception), expected_err_msg) - - def test_delete_native_network_guid_empty(self): - expected_err_msg = 'guid needs to be a non empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.delete_native_network('') - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_delete_native_network_not_found(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork/{}'.format('net-guid') - mock_delete_native_network = Mock() - mock_delete_native_network.text = NATIVE_NETWORK_NOT_FOUND - mock_delete_native_network.status_code = requests.codes.NOT_FOUND - mock_request.side_effect = [mock_delete_native_network] - client = get_client() - with self.assertRaises(ResourceNotFoundError) as e: - client.delete_native_network('net-guid') - mock_request.assert_called_once_with(headers=headers, url=expected_url, json=None, - method='DELETE', params=None) - self.assertEqual(str(e.exception), 'native network not found in db') - - @patch('requests.request') - def test_delete_native_network_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork/{}'.format('net-guid') - mock_delete_native_network = Mock() - mock_delete_native_network.text = 'null' - mock_delete_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_delete_native_network] - - client = get_client() - client.delete_native_network('net-guid') - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='DELETE', - params=None) - - @patch('requests.request') - def test_delete_native_network_success_with_native_network_object(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork/{}'.format('net-guid') - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_native_network.status_code = requests.codes.OK - mock_delete_native_network = Mock() - mock_delete_native_network.text = 'null' - mock_delete_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_native_network, mock_delete_native_network] - - client = get_client() - native_network = client.get_native_network('net-guid') - native_network.delete() - mock_request.assert_called_with(headers=headers, - json=None, - url=expected_url, - method='DELETE', - params={}) - self.assertEqual(mock_request.call_count, 2) - - @patch('requests.request') - def test_get_status_native_network_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork/{}'.format('net-guid') - internal_deployment_status_expected = self.native_network.internal_deployment_status - - mock_get_status_native_network = Mock() - mock_get_status_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_get_status_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_status_native_network] - - internal_deployment_status_actual = self.native_network.get_status() - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='GET', - params={}) - self.assertEqual(internal_deployment_status_expected.phase, internal_deployment_status_actual.phase) - self.assertEqual(internal_deployment_status_expected.status, internal_deployment_status_actual.status) - - @patch('requests.request') - def test_create_native_network_failure(self, mock_request): - expected_payload = { - "name": "native_network_name", - "runtime": 'cloud', - "rosDistro": 'kinetic' - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork' - mock_create_native_network = Mock() - mock_create_native_network.text = NATIVE_NETWORK_FAILURE - mock_create_native_network.status_code = requests.codes.OK - mock_get_native_network = Mock() - mock_get_native_network.text = NATIVE_NETWORK_FAILURE - mock_get_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_native_network, mock_get_native_network] - - mock_request.side_effect = [mock_create_native_network, mock_get_native_network] - - client = get_client() - native_network_payload = NativeNetwork("native_network_name", Runtime.CLOUD, ROSDistro.KINETIC) - native_network_response = client.create_native_network(native_network_payload) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-guid', method='GET', params=None) - ]) - self.assertEqual(native_network_response.internal_deployment_status.error_code[0], "DEP_E209") - self.assertEqual(native_network_response.internal_deployment_status.phase, "Failed to start") - - @patch('requests.request') - def test_poll_native_network_till_ready(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/nativenetwork/{}'.format('net-guid') - internal_deployment_status_expected = self.native_network.internal_deployment_status - - mock_poll_native_network = Mock() - mock_poll_native_network.text = NATIVE_NETWORK_GET_SUCCESS - mock_poll_native_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_poll_native_network] - - internal_deployment_status_actual = self.native_network.poll_native_network_till_ready() - mock_request.assert_called_once_with(headers=headers, - json=None, - url=expected_url, - method='GET', - params={}) - self.assertEqual(internal_deployment_status_expected.phase, - internal_deployment_status_actual.internal_deployment_status.phase) - self.assertEqual(internal_deployment_status_expected.status, - internal_deployment_status_actual.internal_deployment_status.status) diff --git a/tests/package_test.py b/tests/package_test.py deleted file mode 100644 index a20819af..00000000 --- a/tests/package_test.py +++ /dev/null @@ -1,1741 +0,0 @@ -# encoding: utf-8 -from __future__ import absolute_import - -import unittest -from copy import deepcopy - -import requests -from mock import patch, MagicMock, Mock -from requests import Response - -from rapyuta_io import DeviceStatus, DeploymentPhaseConstants -from rapyuta_io.clients.device import Device -from rapyuta_io.clients.native_network import NativeNetwork, Parameters -from rapyuta_io.clients.package import RestartPolicy, Runtime, ROSDistro, ExecutableMount -from rapyuta_io.clients.rosbag import ROSBagJob, ROSBagOptions, UploadOptions -from rapyuta_io.clients.routed_network import RoutedNetwork -from rapyuta_io.utils import InternalServerError -from rapyuta_io.utils.error import OperationNotAllowedError, PlanNotFound, \ - InvalidParameterException, ParameterMissingException, DuplicateAliasException, \ - ConflictError, BadRequestError, ResourceNotFoundError -from rapyuta_io.utils.rest_client import HttpMethod -from tests.utils.client import get_client, headers -from tests.utils.device_respones import DEVICE_INFO, CONFIG_VARIABLES, DOCKER_CONFIG_VARIABLES, \ - DOCKER_DEVICE, DOCKER_EMPTY_ROSBAG_CONFIG_VARIABLES, GET_DOCKERCOMPOSE_DEVICE_SUCCESS, \ - DOCKER_CONFIG_VARIABLE_WITH_ROSBAG_VARIABLES, PREINSTALLED_DEVICE_WITH_NEW_RUNTIME -from .utils.package_responses import PACKAGE_OK_VALIDATE, PACKAGE_OK_VALIDATE_DEVICE, \ - DEPLOYMENT_INFO, PACKAGE_OK_NO_VALIDATE, DEPLOYMENT_STATUS_RUNNING, DEPLOYMENT_STATUS_STOPPED, \ - PROVISION_OK, DEPLOYMENT_LIST, CREATE_PACKAGE, MANIFEST, PACKAGE_OK_VALIDATE_DEVICE_DOCKER, \ - PACKAGE_NOT_FOUND, PACKAGE_OK_NON_ROS_VALIDATE, PACKAGES_LIST, PACKAGE_OK_VALIDATE_ROSBAG_JOB, \ - DEPLOYMENT_INFO_ROSBAG_JOB, PACKAGE_OK_VALIDATE_DEVICE_ROSBAG_JOB, DEPLOYMENT_INFO_DEVICE_ROSBAG_JOB,\ - GET_VOLUME_INSTANCE_OK - -from .utils.scoped_targeted_responses import SCOPED_TARGETED_PACKAGE, CAN_BE_TARGETED, \ - SCOPED_TARGETABLE_DEPEPNDANT_DEPLOY, SCOPED_CLOUD_PACKAGE -from .utils.static_route_responses import STATIC_ROUTE_RESPONSE - - -class PackageTests(unittest.TestCase): - - @patch('requests.request') - def test_package_provision_on_device_ok(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - device.status = DeviceStatus.OFFLINE - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - ignore_device_config = ['ros_workspace'] - provision_config.add_device('ros-talker', device, ignore_device_config) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - deployment = pkg.provision('test_deployment_name', provision_config) - # this is not scoped or targeted - self.assertNotIn("bridge_params", - provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 5) - - @patch('requests.request') - def test_package_provision_on_device_with_set_comonent_alias_false_ok(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - ignore_device_config = ['ros_workspace'] - provision_config.add_device('ros-talker', device, ignore_device_config, set_component_alias=False) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'ros-talker') - deployment = pkg.provision('test_deployment_name', provision_config) - # this is not scoped or targeted - self.assertNotIn("bridge_params", - provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 5) - - @patch('requests.request') - def test_package_provision_with_rosbag_preinstalled_device(self, mock_request): - expected_err = 'ROSBag on Device does not support Preinstalled devices' - get_device = Mock() - get_device.status_code = requests.codes.OK - get_device.text = DEVICE_INFO - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - ignore_device_config = ['ros_workspace'] - provision_config.add_device('ros-talker', device, ignore_device_config) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - provision_config.add_rosbag_job('ros-talker', ROSBagJob('test-job', ROSBagOptions(all_topics=True))) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - with self.assertRaises(InvalidParameterException) as e: - pkg.provision('test_deployment_name', provision_config) - - self.assertEqual(str(e.exception), expected_err) - - @patch('requests.request') - def test_package_provision_with_rosbag_device_without_rosbag_mount_path(self, mock_request): - expected_err = 'This device does not have ROSBag components installed. Please re-onboard the device to use ROSBag features' - get_device = Mock() - get_device.text = DOCKER_DEVICE - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = DOCKER_CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - provision_config.add_rosbag_job('ros-talker', ROSBagJob('test-job', ROSBagOptions(all_topics=True))) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - with self.assertRaises(InvalidParameterException) as e: - pkg.provision('test_deployment_name', provision_config) - - self.assertEqual(str(e.exception), expected_err) - - @patch('requests.request') - def test_package_provision_with_rosbag_device_with_empty_rosbag_mount_path(self, mock_request): - expected_err = 'This device does not have ROSBag components installed. Please re-onboard the device to use ROSBag features' - get_device = Mock() - get_device.text = DOCKER_DEVICE - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = DOCKER_EMPTY_ROSBAG_CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - provision_config.add_rosbag_job('ros-talker', ROSBagJob('test-job', ROSBagOptions(all_topics=True))) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - with self.assertRaises(InvalidParameterException) as e: - pkg.provision('test_deployment_name', provision_config) - - self.assertEqual(str(e.exception), expected_err) - - @patch('requests.request') - def test_package_provision_on_cloud_ok(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE - get_package.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_package, provision, deployment_info] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_provision_on_cloud_with_rosbag_job_ok(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_ROSBAG_JOB - get_package.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO_ROSBAG_JOB - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_package, provision, deployment_info] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 3) - self.assertEqual( - deployment.provisionContext.component_context['gpzxcgjynhulepjjcyglgepl'].ros_bag_job_defs[0].name, 'rbag') - self.assertEqual( - deployment.provisionContext.component_context['gpzxcgjynhulepjjcyglgepl'].ros_bag_job_defs[ - 0].recordOptions.topics, ['/telemetry']) - - @patch('requests.request') - def test_package_provision_on_device_with_rosbag_job_ok(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_ROSBAG_JOB - get_package.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - get_device = Mock() - get_device.text = GET_DOCKERCOMPOSE_DEVICE_SUCCESS - get_device.status_code = requests.codes.OK - get_device_configs = Mock() - get_device_configs.text = DOCKER_CONFIG_VARIABLE_WITH_ROSBAG_VARIABLES - get_device_configs.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO_DEVICE_ROSBAG_JOB - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_device, get_device_configs, provision, deployment_info] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - device = client.get_device('test_device_id') - provision_config.add_device('ros-talker', device=device, ignore_device_config=['ros_workspace'], - set_component_alias=False) - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 5) - self.assertEqual( - deployment.provisionContext.component_context['gpzxcgjynhulepjjcyglgepl'].ros_bag_job_defs[0].name, 'rbag') - self.assertEqual( - deployment.provisionContext.component_context['gpzxcgjynhulepjjcyglgepl'].ros_bag_job_defs[ - 0].recordOptions.topics, ['/telemetry']) - self.assertEqual( - deployment.provisionContext.component_context['gpzxcgjynhulepjjcyglgepl'].ros_bag_job_defs[ - 0].uploadOptions.maxUploadRate, 1048576) - - @patch('requests.request') - def test_package_provision_plan_not_found_failure(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - with self.assertRaises(PlanNotFound): - pkg.get_provision_configuration('test-plan1') - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_provision_empty_ros_workspace_failure(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException): - provision_config.add_device('ros-talker', device) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_add_device_remove_ros_workspace_docker_device(self, rest_mock): - component_id = "jakmybngjupwdjjdqztmcrjq" - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package_response.status_code = requests.codes.OK - get_device_response = MagicMock() - get_device_response.text = DOCKER_DEVICE - get_device_response.status_code = requests.codes.OK - config_variable_response = MagicMock() - config_variable_response.text = DOCKER_CONFIG_VARIABLES - config_variable_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_device_response, get_package_response, config_variable_response] - client = get_client() - device = client.get_device('test_device_id') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device) - self.assertTrue('ros_workspace' not in provision_config.parameters.get(component_id), - 'ros_workspace should be present for docker runtime') - - @patch('requests.request') - def test_package_provision_empty_add_label_failure(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(ParameterMissingException): - provision_config.add_label('', '') - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_provision_empty_deployment_name(self, rest_mock): - mock_response = MagicMock() - mock_response.text = PACKAGE_OK_VALIDATE - mock_response.status_code = 200 - rest_mock.return_value = mock_response - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - pkg.provision('', provision_config) - self.assertEqual("deployment_name must be a non-empty string", str(e.exception)) - self.assertEqual(rest_mock.call_count, 1) - - @patch('requests.request') - def test_package_provision_incorrect_provision_configuration_type(self, rest_mock): - mock_response = MagicMock() - mock_response.text = PACKAGE_OK_VALIDATE - mock_response.status_code = 200 - rest_mock.return_value = mock_response - client = get_client() - pkg = client.get_package('my_package') - with self.assertRaises(InvalidParameterException) as e: - pkg.provision('dep1', '') - self.assertEqual("provision_configuration must be of type ProvisionConfiguration", str(e.exception)) - self.assertEqual(rest_mock.call_count, 1) - - @patch('requests.request') - def test_package_provision_component_not_mapped_with_device_failure(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = 200 - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(OperationNotAllowedError): - pkg.provision('test_deployment_name', provision_config) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_provision_api_error(self, mock_request): - response = Mock() - response.text = PACKAGE_OK_VALIDATE - response.status_code = 200 - response2 = response() - response2.status_code = 500 - mock_request.side_effect = [response, response2] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InternalServerError): - pkg.provision('test_package_name', provision_config) - self.assertEqual(mock_request.call_count, 2) - - @patch('requests.request') - def test_package_provision_component_parameter_empty_component_name_failure(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_NO_VALIDATE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException): - provision_config.add_parameter('', 'invalid-value', 123) - - @patch('requests.request') - def test_package_provision_component_parameter_empty_failure(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_NO_VALIDATE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - ignore_device_config = ['ros_workspace'] - provision_config.add_device('ros-talker', device, ignore_device_config) - with self.assertRaises(InvalidParameterException): - pkg.provision('test_deployment_name', provision_config) - self.assertEqual(mock_request.call_count, 3) - - def test_create_executable_mount_invalid_executable_name(self): - with self.assertRaises(InvalidParameterException) as e: - mount = ExecutableMount(1, '/mountPath', '/subPath') - self.assertEqual("exec_name must be a non-empty string", str(e.exception)) - - def test_create_executable_mount_invalid_mount_path(self): - with self.assertRaises(InvalidParameterException) as e: - mount = ExecutableMount('exec-name', 1, '/subPath') - self.assertEqual("mount_path must be a non-empty string", str(e.exception)) - - def test_create_executable_mount_invalid_sub_path(self): - with self.assertRaises(InvalidParameterException) as e: - mount = ExecutableMount('exec-name', '/mountPath', 1) - self.assertEqual("sub_path must be a non-empty string", str(e.exception)) - - @patch('requests.request') - def test_provision_config_add_mount_volume_both_mount_path_and_executable_mounts_none_error(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - get_volume_instance = Mock() - get_volume_instance.text = GET_VOLUME_INSTANCE_OK - get_volume_instance.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_volume_instance, get_volume_instance] - client = get_client() - pkg = client.get_package('my_package') - volume_instance = client.get_volume_instance('test-id') - prov_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', volume=volume_instance, mount_path=None, executable_mounts=None) - self.assertEqual("One of mount_path or executable_mounts should be present", str(e.exception)) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_provision_config_add_mount_volume_invalid_executable_mounts(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - get_volume_instance = Mock() - get_volume_instance.text = GET_VOLUME_INSTANCE_OK - get_volume_instance.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_volume_instance, get_volume_instance] - client = get_client() - pkg = client.get_package('my_package') - volume_instance = client.get_volume_instance('test-id') - prov_config = pkg.get_provision_configuration('test-plan') - executable_mounts = ["invalid mount"] - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', volume=volume_instance, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual("executable_mounts must be a list of rapyuta_io.clients.package.ExecutableMount", str(e.exception)) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_add_mount_volume_to_provision_config_ok(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - get_volume_instance = Mock() - get_volume_instance.text = GET_VOLUME_INSTANCE_OK - get_volume_instance.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_volume_instance, get_volume_instance] - client = get_client() - pkg = client.get_package('my_package') - volume_instance = client.get_volume_instance('test-id') - prov_config = pkg.get_provision_configuration('test-plan') - executable_mounts = [ExecutableMount(exec_name='ros-talker', mount_path='/test_path', sub_path='data')] - prov_config.mount_volume('ros-talker', volume=volume_instance, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual( - prov_config.context['dependentDeployments'][0]['config']['mountPaths']['ros-talker']['mountPath'], - '/test_path') - self.assertEqual( - prov_config.context['dependentDeployments'][0]['config']['mountPaths']['ros-talker']['subPath'], 'data') - - @patch('requests.request') - def test_package_add_volume_to_provision_config_both_present(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - prov_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', volume='random', device='random', mount_path=None, executable_mounts=None) - self.assertEqual("both volume and device parameter cannot be present", str(e.exception)) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_add_volume_to_provision_config_both_absent(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - prov_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', mount_path=None, executable_mounts=None) - self.assertEqual("either a volume or device parameter must be present", str(e.exception)) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_invalid_volume(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - prov_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', volume='invalid', mount_path=None, executable_mounts=None) - self.assertEqual("volume must be of type rapyuta_io.clients.persistent_volumes.VolumeInstance", str(e.exception)) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_invalid_device(self, mock_request): - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('my_package') - prov_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', device='invalid', mount_path=None, executable_mounts=None) - self.assertEqual("device must be of type Device", str(e.exception)) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_invalid_exec_mount(self, mock_request): - get_device = Mock() - get_device.text = DOCKER_DEVICE - get_device.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = DOCKER_CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_device, config_variable] - client = get_client() - pkg = client.get_package('my_package') - device = client.get_device('test-dev') - prov_config = pkg.get_provision_configuration('test-plan') - prov_config.add_device('ros-talker', device, ['ros_workspace']) - executable_mounts = ["invalid"] - with self.assertRaises(InvalidParameterException) as e: - prov_config.mount_volume('ros-talker', device=device, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual("executable_mounts must be a list of rapyuta_io.clients.package.ExecutableMount", str(e.exception)) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_preinstalled_runtime(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_device, config_variable] - client = get_client() - pkg = client.get_package('my_package') - device = client.get_device('test-dev') - prov_config = pkg.get_provision_configuration('test-plan') - prov_config.add_device('ros-talker', device, ['ros_workspace']) - executable_mounts = [ExecutableMount(exec_name='ros-talker', mount_path='/test_path', sub_path='/data')] - with self.assertRaises(OperationNotAllowedError) as e: - prov_config.mount_volume('ros-talker', device=device, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual("Device must be a dockercompose device", str(e.exception)) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_with_new_preinstalled_runtime(self, mock_request): - get_device = Mock() - get_device.text = PREINSTALLED_DEVICE_WITH_NEW_RUNTIME - get_device.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_device, config_variable] - client = get_client() - pkg = client.get_package('my_package') - device = client.get_device('test-dev') - prov_config = pkg.get_provision_configuration('test-plan') - prov_config.add_device('ros-talker', device, ['ros_workspace']) - executable_mounts = [ExecutableMount(exec_name='ros-talker', mount_path='/test_path', sub_path='/data')] - with self.assertRaises(OperationNotAllowedError) as e: - prov_config.mount_volume('ros-talker', device=device, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual("Device must be a dockercompose device", str(e.exception)) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_not_added_device(self, mock_request): - get_device = Mock() - get_device.text = DOCKER_DEVICE - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_device] - client = get_client() - pkg = client.get_package('my_package') - device = client.get_device('test-dev') - prov_config = pkg.get_provision_configuration('test-plan') - executable_mounts = [ExecutableMount(exec_name='ros-talker', mount_path='/test_path', sub_path='/data')] - with self.assertRaises(OperationNotAllowedError) as e: - prov_config.mount_volume('ros-talker', device=device, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual("Device must be added to the component", str(e.exception)) - self.assertEqual(mock_request.call_count, 2) - - @patch('requests.request') - def test_package_add_device_volume_to_provision_config_ok(self, mock_request): - get_device = Mock() - get_device.text = DOCKER_DEVICE - get_device.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = DOCKER_CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE_DOCKER - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package, get_device, config_variable] - client = get_client() - pkg = client.get_package('my_package') - device = client.get_device('test-dev') - device.status = DeviceStatus.OFFLINE.value - prov_config = pkg.get_provision_configuration('test-plan') - prov_config.add_device('ros-talker', device, ['ros_workspace']) - executable_mounts = [ExecutableMount(exec_name='ros-talker', mount_path='/test_path', sub_path='/data')] - prov_config.mount_volume('ros-talker', device=device, mount_path=None, executable_mounts=executable_mounts) - self.assertEqual( - prov_config.context['diskMountInfo'][0]['diskResourceId'], - device.deviceId) - self.assertEqual( - prov_config.context['diskMountInfo'][0]['config']['mountPaths']['ros-talker']['mountPath'], - '/test_path') - self.assertEqual( - prov_config.context['diskMountInfo'][0]['config']['mountPaths']['ros-talker']['subPath'], '/data') - - @patch('requests.request') - def test_package_provision_dependent_deployment_ok(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - deployment_status = Mock() - deployment_status.text = DEPLOYMENT_STATUS_RUNNING - deployment_status.status_code = requests.codes.OK - provision = Mock() - provision.text = '''{"operation": "deployment_id"}''' - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = 200 - mock_request.side_effect = [get_device, get_package, config_variable, deployment_status, - deployment_status, provision, deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device, ['ros_workspace']) - dep_deployment = client.get_deployment('deployment_id') - provision_config.add_dependent_deployment(dep_deployment) - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 7) - self.assertFalse(deployment.is_partial) - - @patch('requests.request') - def test_package_provision_dependent_deployment_with_partial_package_and_deployment_ok(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - all_packages = Mock() - all_packages.text = PACKAGES_LIST - all_packages.status_code = requests.codes.OK - get_package1 = Mock() - get_package1.text = PACKAGE_OK_VALIDATE_DEVICE - get_package1.status_code = requests.codes.OK - get_package2 = Mock() - get_package2.text = PACKAGE_OK_VALIDATE_DEVICE - get_package2.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - all_deployments = Mock() - all_deployments.text = DEPLOYMENT_LIST - all_deployments.status_code = requests.codes.OK - deployment_status = Mock() - deployment_status.text = DEPLOYMENT_STATUS_RUNNING - deployment_status.status_code = requests.codes.OK - provision = Mock() - provision.text = '''{"operation": "deployment_id"}''' - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = 200 - mock_request.side_effect = [get_device, all_packages, get_package1, config_variable, all_deployments, - deployment_status, get_package2, provision, deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkgs = client.get_all_packages() - partial_pkg = deepcopy(pkgs[0]) - self.assertTrue(pkgs[0].is_partial) - provision_config = pkgs[0].get_provision_configuration('test-plan') - self.assertFalse(pkgs[0].is_partial) - provision_config.add_device('ros-talker', device, ['ros_workspace']) - deployments = client.get_all_deployments() - self.assertTrue(deployments[0].is_partial) - provision_config.add_dependent_deployment(deployments[0]) - self.assertTrue(partial_pkg.is_partial) - deployment = partial_pkg.provision('test_deployment_name', provision_config) - self.assertFalse(partial_pkg.is_partial) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 9) - self.assertFalse(deployments[0].is_partial) - - @patch('requests.request') - def test_provision_dependent_deployment_failure(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - deployment_status = Mock() - deployment_status.text = DEPLOYMENT_STATUS_STOPPED - deployment_status.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, - deployment_status, deployment_status] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device, ['ros_workspace']) - dep_deployment = client.get_deployment('deployment_id') - with self.assertRaises(OperationNotAllowedError): - provision_config.add_dependent_deployment(dep_deployment) - self.assertEqual(mock_request.call_count, 5) - - @patch('requests.request') - def test_package_provision_with_same_provision_configuration_failed(self, rest_mock): - get_device_response = MagicMock() - get_device_response.text = DEVICE_INFO - get_device_response.status_code = requests.codes.OK - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE_DEVICE - get_package_response.status_code = requests.codes.OK - config_variable_response = MagicMock() - config_variable_response.text = CONFIG_VARIABLES - config_variable_response.status_code = requests.codes.OK - provision_response = MagicMock() - provision_response.text = '''{"operation": "deployment_id"}''' - provision_response.status_code = requests.codes.OK - deployment_info = MagicMock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = 200 - rest_mock.side_effect = [get_device_response, get_package_response, - config_variable_response, provision_response, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device, ['ros_workspace']) - deployment = pkg.provision('test_deployment_name-1', provision_config) - self.assertTrue(deployment.deploymentId) - with self.assertRaises(InvalidParameterException) as e: - pkg.provision('test_deployment_name-2', provision_config) - self.assertEqual("cannot reuse this ProvisionConfiguration for provisioning", str(e.exception)) - self.assertEqual(rest_mock.call_count, 5) - - @patch('requests.request') - def test_scoped_package_provision_defaulting(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = SCOPED_TARGETED_PACKAGE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - ignore_device_config = ['ros_workspace'] - provision_config.add_device('devicepong', device, ignore_device_config) - self.assertEqual(provision_config.parameters["dev-comp"]["bridge_params"]["alias"], 'D239-Device') - self.assertEqual(provision_config.parameters["cloud-comp"]["bridge_params"]["alias"], 'cloudping') - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 5) - - @patch('requests.request') - def test_scoped_package_provision_clash(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = SCOPED_TARGETED_PACKAGE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, provision, - deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - ignore_device_config = ['ros_workspace'] - provision_config.add_device('devicepong', device, ignore_device_config) - provision_config.validate() - provision_config.set_component_alias("cloudping", "samename") - provision_config.set_component_alias("devicepong", "samename") - with self.assertRaises(DuplicateAliasException): - pkg.provision('test_deployment_name', provision_config) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_scoped_package_provision_empty_component_name(self, mock_request): - expected_err = "component_name must be a non-empty string" - get_package = MagicMock() - get_package.text = SCOPED_CLOUD_PACKAGE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - provision_config.validate() - with self.assertRaises(InvalidParameterException) as e: - provision_config.set_component_alias("", "samename") - self.assertEqual(str(e.exception), expected_err) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_scoped_package_provision_invalid_component_name(self, mock_request): - expected_err = "component_name must be a non-empty string" - get_package = MagicMock() - get_package.text = SCOPED_CLOUD_PACKAGE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - provision_config.validate() - with self.assertRaises(InvalidParameterException) as e: - provision_config.set_component_alias(True, "samename") - self.assertEqual(str(e.exception), expected_err) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_scoped_package_provision_invalid_alias(self, mock_request): - expected_err = "alias must be a string" - get_package = MagicMock() - get_package.text = SCOPED_CLOUD_PACKAGE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - provision_config.validate() - with self.assertRaises(InvalidParameterException) as e: - provision_config.set_component_alias("cloudping", True) - self.assertEqual(str(e.exception), expected_err) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_scoped_package_provision_invalid_ros_namespace_flag(self, mock_request): - expected_err = "set_ros_namespace must be a boolean" - get_package = MagicMock() - get_package.text = SCOPED_CLOUD_PACKAGE - get_package.status_code = requests.codes.OK - mock_request.side_effect = [get_package] - client = get_client() - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - provision_config.validate() - with self.assertRaises(InvalidParameterException) as e: - provision_config.set_component_alias("cloudping", "alias", "true") - self.assertEqual(str(e.exception), expected_err) - self.assertEqual(mock_request.call_count, 1) - - @patch('requests.request') - def test_scoped_package_provision_on_cloud_ok(self, mock_request): - get_package = Mock() - get_package.text = SCOPED_CLOUD_PACKAGE - get_package.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = SCOPED_TARGETABLE_DEPEPNDANT_DEPLOY - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_package, provision, deployment_info] - client = get_client() - pkg = client.get_package('C2DPingMaxST2') - provision_config = pkg.get_provision_configuration('basicplan') - provision_config.validate() - provision_config.set_component_alias("cloudping", "parent", True) - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(deployment.parameters.sszyzwycqdgsnmgezoyaqydy.bridge_params.alias, "parent") - self.assertEqual(deployment.parameters.sszyzwycqdgsnmgezoyaqydy.bridge_params.setROSNamespace, True) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_canbetargeted_ok(self, mock_request): - get_package = Mock() - get_package.text = CAN_BE_TARGETED - get_package.status_code = requests.codes.OK - provision = Mock() - provision.text = PROVISION_OK - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = DEPLOYMENT_INFO - deployment_info.status_code = requests.codes.OK - mock_request.side_effect = [get_package, provision, deployment_info] - client = get_client() - pkg = client.get_package('canbetargeted') - provision_config = pkg.get_provision_configuration('basicplan') - self.assertEqual(provision_config.parameters["compid"]["bridge_params"]["alias"], 'comp') - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 3) - - @patch('requests.request') - def test_package_provision_normal_package_dependent_deployment_with_scoped_and_targeted(self, mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - deployment_status = Mock() - deployment_status.text = SCOPED_TARGETABLE_DEPEPNDANT_DEPLOY - deployment_status.status_code = requests.codes.OK - provision = Mock() - provision.text = '''{"operation": "deployment_id"}''' - provision.status_code = requests.codes.OK - deployment_info = Mock() - deployment_info.text = SCOPED_TARGETABLE_DEPEPNDANT_DEPLOY - deployment_info.status_code = 200 - mock_request.side_effect = [get_device, get_package, config_variable, - deployment_status, deployment_status, provision, deployment_info] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device, ['ros_workspace']) - dep_deployment = client.get_deployment('deployment_id') - provision_config.add_dependent_deployment(dep_deployment) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - deployment = pkg.provision('test_deployment_name', provision_config) - self.assertTrue(deployment.deploymentId) - self.assertEqual(mock_request.call_count, 7) - - @patch('requests.request') - def test_package_provision_normal_package_dependent_deployment_with_scoped_and_targeted_alias_clash(self, - mock_request): - get_device = Mock() - get_device.text = DEVICE_INFO - get_device.status_code = requests.codes.OK - get_package = Mock() - get_package.text = PACKAGE_OK_VALIDATE_DEVICE - get_package.status_code = requests.codes.OK - config_variable = Mock() - config_variable.text = CONFIG_VARIABLES - config_variable.status_code = requests.codes.OK - dep_deployment_info = Mock() - dep_deployment_info.text = SCOPED_TARGETABLE_DEPEPNDANT_DEPLOY - dep_deployment_info.status_code = requests.codes.OK - deployment_status = Mock() - deployment_status.text = SCOPED_TARGETABLE_DEPEPNDANT_DEPLOY - deployment_status.status_code = requests.codes.OK - provision = Mock() - provision.text = '''{"operation": "deployment_id"}''' - provision.status_code = requests.codes.OK - mock_request.side_effect = [get_device, get_package, config_variable, dep_deployment_info, - deployment_status, provision] - client = get_client() - device = client.get_device('test_device_id') - self.assertIsInstance(device, Device, 'Object should be an instance of class Device') - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_device('ros-talker', device, ['ros_workspace']) - dep_deployment = client.get_deployment('deployment_id') - provision_config.add_dependent_deployment(dep_deployment) - self.assertEqual(provision_config.parameters["jakmybngjupwdjjdqztmcrjq"]["bridge_params"]["alias"], - 'D239-Device') - provision_config.set_component_alias("ros-talker", "parent") - with self.assertRaises(DuplicateAliasException): - pkg.provision('test_deployment_name', provision_config) - self.assertEqual(mock_request.call_count, 5) - - @patch('rapyuta_io.clients.provision_client.ProvisionClient._execute_api') - @patch('requests.request') - def test_package_deployments_without_phase(self, mock_rest_client, mock_execute): - mock_get_package = Mock() - mock_get_package.text = SCOPED_TARGETED_PACKAGE - mock_get_package.status_code = requests.codes.OK - mock_rest_client.side_effect = [mock_get_package] - mock_execute.return_value = MagicMock() - mock_execute.return_value.status_code = 200 - mock_execute.return_value.text = DEPLOYMENT_LIST - client = get_client() - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - package = client.get_package('pkg-abcdefg') - deployments = package.deployments() - mock_execute.assert_called_once_with(expected_url, HttpMethod.GET, - query_params={'package_uid': 'pkg-abcdefg'}, retry_limit=0) - for deployment in deployments: - self.assertTrue(deployment.is_partial) - - @patch('rapyuta_io.clients.provision_client.ProvisionClient._execute_api') - @patch('requests.request') - def test_package_deployments_with_phase(self, mock_rest_client, mock_execute): - get_package = Mock() - get_package.text = SCOPED_TARGETED_PACKAGE - get_package.status_code = requests.codes.OK - mock_rest_client.side_effect = [get_package] - mock_execute.return_value = MagicMock() - mock_execute.return_value.status_code = 200 - mock_execute.return_value.text = DEPLOYMENT_LIST - client = get_client() - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - package = client.get_package('pkg-abcdefg') - deployments = package.deployments(phases=[DeploymentPhaseConstants.SUCCEEDED, DeploymentPhaseConstants.PROVISIONING]) - mock_execute.assert_called_once_with(expected_url, HttpMethod.GET, - query_params={'package_uid': 'pkg-abcdefg', 'phase': - [DeploymentPhaseConstants.SUCCEEDED.value, - DeploymentPhaseConstants.PROVISIONING.value]}, - retry_limit=0) - for deployment in deployments: - self.assertTrue(deployment.is_partial) - - @patch('rapyuta_io.clients.provision_client.ProvisionClient._execute_api') - @patch('requests.request') - def test_package_deployments_with_phase_and_retry(self, mock_rest_client, mock_execute): - get_package = Mock() - get_package.text = SCOPED_TARGETED_PACKAGE - get_package.status_code = requests.codes.OK - mock_rest_client.side_effect = [get_package] - mock_execute.return_value = MagicMock() - mock_execute.return_value.status_code = 200 - mock_execute.return_value.text = DEPLOYMENT_LIST - client = get_client() - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/deployment/list' - package = client.get_package('pkg-abcdefg') - package.deployments(phases=[DeploymentPhaseConstants.SUCCEEDED, DeploymentPhaseConstants.PROVISIONING], - retry_limit=2) - mock_execute.assert_called_once_with(expected_url, HttpMethod.GET, - query_params={'package_uid': 'pkg-abcdefg', 'phase': - [DeploymentPhaseConstants.SUCCEEDED.value, - DeploymentPhaseConstants.PROVISIONING.value]}, - retry_limit=2) - - @patch('requests.request') - def test_create_package(self, mock_request): - mock_response = MagicMock(spec=Response) - mock_response.text = CREATE_PACKAGE - mock_response.status_code = requests.codes.OK - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/add' - mock_request.return_value = mock_response - get_client().create_package(MANIFEST) - mock_request.assert_called_once_with(headers=headers, - json=MANIFEST, - method='POST', - url=expected_url, - params=None) - - @patch('requests.request') - def test_create_package_package_with_same_exists(self, mock_request): - mock_response = MagicMock(spec=Response) - mock_response.text = CREATE_PACKAGE - mock_response.status_code = requests.codes.CONFLICT - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/add' - mock_request.return_value = mock_response - with self.assertRaises(ConflictError): - get_client().create_package(MANIFEST) - mock_request.assert_called_once_with(headers=headers, - json=MANIFEST, - method='POST', - url=expected_url, - params=None) - - @patch('requests.request') - def test_create_package_package_with_bad_request(self, mock_request): - mock_response = MagicMock(spec=Response) - mock_response.text = CREATE_PACKAGE - mock_response.status_code = requests.codes.BAD_REQUEST - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/add' - mock_request.return_value = mock_response - with self.assertRaises(BadRequestError): - get_client().create_package(MANIFEST) - mock_request.assert_called_once_with(headers=headers, - json=MANIFEST, - method='POST', - url=expected_url, - params=None) - - @patch('rapyuta_io.rio_client.Client._get_manifest_from_file') - @patch('requests.request') - def test_create_package_from_manifest(self, mock_request, mock_get_manifest_path): - mock_response = MagicMock() - mock_response.text = CREATE_PACKAGE - mock_response.status_code = requests.codes.OK - mock_request.return_value = mock_response - mock_get_manifest_path.return_value = MANIFEST - manifest_filepath = '/path/to/listener.json' - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/add' - get_client().create_package_from_manifest(manifest_filepath) - mock_request.assert_called_once_with(headers=headers, - json=MANIFEST, - method='POST', - url=expected_url, - params=None) - mock_get_manifest_path.assert_called_once_with(manifest_filepath) - - @patch('rapyuta_io.rio_client.Client._get_manifest_from_file') - @patch('requests.request') - def test_create_package_from_manifest_package_with_same_exists(self, mock_request, - mock_get_manifest_path): - mock_response = MagicMock() - mock_response.text = CREATE_PACKAGE - mock_response.status_code = requests.codes.CONFLICT - mock_request.return_value = mock_response - mock_get_manifest_path.return_value = MANIFEST - manifest_filepath = '/path/to/listener.json' - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/add' - with self.assertRaises(ConflictError): - get_client().create_package_from_manifest(manifest_filepath) - mock_request.assert_called_once_with(headers=headers, - json=MANIFEST, - method='POST', - url=expected_url, - params=None) - mock_get_manifest_path.assert_called_once_with(manifest_filepath) - - @patch('rapyuta_io.rio_client.Client._get_manifest_from_file') - @patch('requests.request') - def test_create_package_from_manifest_package_with_bad_request(self, mock_request, - mock_get_manifest_path): - mock_response = MagicMock() - mock_response.text = CREATE_PACKAGE - mock_response.status_code = requests.codes.BAD_REQUEST - mock_request.return_value = mock_response - mock_get_manifest_path.return_value = MANIFEST - manifest_filepath = '/path/to/listener.json' - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/add' - with self.assertRaises(BadRequestError): - get_client().create_package_from_manifest(manifest_filepath) - mock_request.assert_called_once_with(headers=headers, - json=MANIFEST, - method='POST', - url=expected_url, - params=None) - mock_get_manifest_path.assert_called_once_with(manifest_filepath) - - @patch('requests.request') - def test_add_rosbag_job_success(self, rest_mock): - component_id = 'jakmybngjupwdjjdqztmcrjq' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - rosbag_options = ROSBagOptions(all_topics=True) - job = ROSBagJob(name='job', rosbag_options=rosbag_options) - provision_config.add_rosbag_job('ros-talker', job) - self.assertEqual(provision_config['context']['component_context'][component_id] - ['ros_bag_job_defs'][0]['name'], job.name) - self.assertEqual(provision_config['context']['component_context'][component_id] - ['ros_bag_job_defs'][0]['recordOptions'], rosbag_options.serialize()) - - @patch('requests.request') - def test_add_rosbag_job_invalid_rosbag_job(self, rest_mock): - expected_err = 'rosbag_job needs to a ROSBagJob object' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - provision_config.add_rosbag_job('ros-talker', 'invalid') - - self.assertEqual(str(e.exception), expected_err) - - @patch('requests.request') - def test_add_rosbag_job_to_device_component(self, rest_mock): - component_id = 'jakmybngjupwdjjdqztmcrjq' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE_DEVICE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - job = ROSBagJob(name='job', rosbag_options=ROSBagOptions(all_topics=True), - upload_options=UploadOptions()) - provision_config.add_rosbag_job('ros-talker', job) - self.assertEqual(provision_config['context']['component_context'][component_id] - ['ros_bag_job_defs'][0]['name'], job.name) - self.assertEqual(provision_config['context']['component_context'][component_id] - ['ros_bag_job_defs'][0]['recordOptions'], job.rosbag_options.serialize()) - self.assertEqual(provision_config['context']['component_context'][component_id] - ['ros_bag_job_defs'][0]['uploadOptions'], job.upload_options.serialize()) - - @patch('requests.request') - def test_add_rosbag_jobs_with_same_name(self, rest_mock): - expected_err = 'rosbag job with same name already exists' - component_id = 'jakmybngjupwdjjdqztmcrjq' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE_DEVICE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - job1 = ROSBagJob(name='job', rosbag_options=ROSBagOptions(all_topics=True), - upload_options=UploadOptions()) - provision_config.add_rosbag_job('ros-talker', job1) - job2 = ROSBagJob(name='job', rosbag_options=ROSBagOptions(all_topics=True), - upload_options=UploadOptions()) - with self.assertRaises(OperationNotAllowedError) as e: - provision_config.add_rosbag_job('ros-talker', job2) - self.assertEqual(str(e.exception), expected_err) - - @patch('requests.request') - def test_add_rosbag_job_to_non_ros_component(self, rest_mock): - expected_err = 'rosbag job is only supported for ros components' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_NON_ROS_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - job = ROSBagJob(name='job', rosbag_options=ROSBagOptions(all_topics=True)) - with self.assertRaises(OperationNotAllowedError) as e: - provision_config.add_rosbag_job('ros-talker', job) - - self.assertEqual(str(e.exception), expected_err) - - @patch('requests.request') - def test_remove_rosbag_job_from_device_component(self, rest_mock): - component_id = 'jakmybngjupwdjjdqztmcrjq' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE_ROSBAG_JOB - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - self.assertEqual(provision_config.plan.components.components[0].rosBagJobDefs[0].name, 'rbag') - provision_config.remove_rosbag_job('ros-talker', 'rbag') - self.assertEqual(len(provision_config['context']['component_context'][component_id]['rosBagJobDefs']), 0) - - @patch('requests.request') - def test_add_restart_policy_success(self, rest_mock): - component_id = 'jakmybngjupwdjjdqztmcrjq' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_NO_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_restart_policy('ros-talker', RestartPolicy.Always) - self.assertEqual(provision_config['context']['component_context'][component_id] - ['component_override']['restart_policy'], - RestartPolicy.Always.value) - - @patch('requests.request') - def test_add_routed_networks_to_provision_config_invalid_routed_network(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = str('invalid object') - - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - provision_config.add_routed_networks([routed_network]) - self.assertEqual(str(e.exception), 'routed networks must be of type RoutedNetwork') - - @patch('requests.request') - def test_add_routed_network_invalid_routed_network(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - provision_config.add_routed_network('invalid', 'lo') - self.assertEqual(str(e.exception), - 'routed networks must be of type RoutedNetwork') - - @patch('requests.request') - def test_add_routed_network_cloud_runtime_with_network_interface(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'cloud'}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(OperationNotAllowedError) as e: - provision_config.add_routed_network(routed_network, 'docker0') - self.assertEqual(str(e.exception), - 'cloud routed network does not bind to network interface') - - @patch('requests.request') - def test_add_routed_network_to_provision_config_device_runtime(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'device', - 'parameters': {'NETWORK_INTERFACE': 'lo'}}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_routed_network(routed_network, 'docker0') - self.assertEqual(provision_config['context']['routedNetworks'], - [{'bindParameters': {'NETWORK_INTERFACE': 'docker0'}, 'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_routed_network_to_provision_config_device(self, rest_mock): - ''' - adding network interface to device routed network which is already present - ''' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'device', - 'parameters': {'NETWORK_INTERFACE': 'lo'}}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config['context']['routedNetworks'] = [{'guid': 'test-network-id'}] - self.assertEqual(provision_config['context']['routedNetworks'], - [{'guid': 'test-network-id'}]) - provision_config.add_routed_network(routed_network, 'docker0') - self.assertEqual(provision_config['context']['routedNetworks'], - [{'bindParameters': {'NETWORK_INTERFACE': 'docker0'}, 'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_routed_network_to_provision_config_cloud(self, rest_mock): - ''' - adding network interface to cloud routed network which is already added - ''' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'device'}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config['context']['routedNetworks'] = [{'guid': 'test-network-id'}] - self.assertEqual(provision_config['context']['routedNetworks'], - [{'guid': 'test-network-id'}]) - provision_config.add_routed_network(routed_network) - self.assertEqual(provision_config['context']['routedNetworks'], - [{'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_routed_network_to_provision_config_device_runtime_with_diff_interface(self, rest_mock): - ''' - The network interface value gets updated each time you call the function - ''' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'device', - 'parameters': {'NETWORK_INTERFACE': 'lo'}}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_routed_network(routed_network, 'docker0') - self.assertEqual(provision_config['context']['routedNetworks'], - [{'bindParameters': {'NETWORK_INTERFACE': 'docker0'}, 'guid': 'test-network-id'}]) - provision_config.add_routed_network(routed_network, 'lo') - self.assertEqual(provision_config['context']['routedNetworks'], - [{'bindParameters': {'NETWORK_INTERFACE': 'lo'}, 'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_routed_network_to_provision_config_cloud_runtime(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'cloud'}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_routed_network(routed_network) - self.assertEqual(provision_config['context']['routedNetworks'], - [{'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_routed_networks_to_provision_config(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - routed_network = RoutedNetwork({'guid': 'test-network-id', 'runtime': 'cloud'}) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_routed_networks([routed_network]) - self.assertEqual(provision_config['context']['routedNetworks'], [{'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_native_networks_invalid_native_network(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - native_network = str('invalid object') - - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - provision_config.add_native_networks([native_network]) - self.assertEqual(str(e.exception), 'native network must be of type NativeNetwork') - - @patch('requests.request') - def test_add_native_network_invalid_native_network(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException) as e: - provision_config.add_native_network('invalid native_network','lo') - self.assertEqual(str(e.exception), - 'native network must be of type NativeNetwork') - - @patch('requests.request') - def test_add_native_network_cloud_runtime_with_network_interface(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - native_network = NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.KINETIC) - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(OperationNotAllowedError) as e: - provision_config.add_native_network(native_network, 'docker0') - self.assertEqual(str(e.exception), - 'cloud native network does not bind to network interface') - - @patch('requests.request') - def test_add_native_networks_to_provision_config_cloud_success(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - native_network = NativeNetwork('native_network_name', Runtime.CLOUD, ROSDistro.KINETIC) - native_network.guid = 'test-network-id' - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_native_networks([native_network]) - self.assertEqual(provision_config['context']['nativeNetworks'], [{'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_native_networks_to_provision_config_device_success(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - device = Device('dev-name') - device.uuid = 'random' - device.ip_interfaces = {'lo': '0.0.0.0'} - parameters = Parameters(device=device, network_interface='lo') - native_network = NativeNetwork('native_network_name', Runtime.DEVICE, ROSDistro.KINETIC, parameters) - native_network.guid = 'test-network-id' - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_native_network(native_network, 'lo') - self.assertEqual(provision_config['context']['nativeNetworks'], - [{'bindParameters': {'NETWORK_INTERFACE': 'lo'}, 'guid': 'test-network-id'}]) - provision_config.add_native_network(native_network, 'docker0') - self.assertEqual(provision_config['context']['nativeNetworks'], - [{'bindParameters': {'NETWORK_INTERFACE': 'docker0'}, 'guid': 'test-network-id'}]) - - @patch('requests.request') - def test_add_static_route(self, rest_mock): - endpoint_name = 'test' - static_route_name = 'test_route' - component_id = 'jakmybngjupwdjjdqztmcrjq' - component_name = 'ros-talker' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_NO_VALIDATE - get_package_response.status_code = requests.codes.OK - static_route_response = MagicMock() - static_route_response.text = STATIC_ROUTE_RESPONSE - static_route_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response, static_route_response] - client = get_client() - pkg = client.get_package('my_package') - static_route = client.create_static_route(static_route_name) - provision_config = pkg.get_provision_configuration('test-plan') - provision_config.add_static_route(component_name, endpoint_name, static_route) - self.assertEqual( - provision_config['context']['component_context'][component_id]['static_route_config'][endpoint_name], - static_route.guid) - - @patch('requests.request') - def test_add_static_route_with_type_error(self, rest_mock): - endpoint_name = 'test' - component_name = 'ros-talker' - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_NO_VALIDATE - get_package_response.status_code = requests.codes.OK - static_route_response = MagicMock() - static_route_response.text = STATIC_ROUTE_RESPONSE - static_route_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response, static_route_response] - client = get_client() - pkg = client.get_package('my_package') - static_route = {'key': 'not a static route'} - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(TypeError): - provision_config.add_static_route(component_name, endpoint_name, static_route) - - @patch('requests.request') - def test_get_static_route_by_name_name_not_found(self, rest_mock): - static_route_response = MagicMock() - static_route_response.text = None - static_route_response.status_code = requests.codes.NOT_FOUND - rest_mock.side_effect = [static_route_response] - client = get_client() - sr = client.get_static_route_by_name('test') - self.assertIsNone(sr) - - @patch('requests.request') - def test_delete_static_route_failure_invalid_route_guid(self, rest_mock): - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/staticroute/delete' - expected_payload = {'guid': 'invalid-route-guid'} - static_route_response = MagicMock() - static_route_response.text = '{"success":false,"error":"unable to find the resource from db: record not found"}' - static_route_response.status_code = requests.codes.NOT_FOUND - rest_mock.side_effect = [static_route_response] - client = get_client() - expected_err_msg = 'unable to find the resource from db: record not found' - with self.assertRaises(ResourceNotFoundError) as e: - client.delete_static_route('invalid-route-guid') - rest_mock.assert_called_once_with(headers=headers, json=expected_payload, url=expected_url, method='DELETE', - params={}) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_delete_static_route_success_valid_route_guid(self, rest_mock): - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/staticroute/delete' - expected_payload = {'guid': 'valid-route-guid'} - static_route_response = MagicMock() - static_route_response.text = '{"success":true,"error":""}' - static_route_response.status_code = requests.codes.OK - rest_mock.side_effect = [static_route_response] - client = get_client() - client.delete_static_route('valid-route-guid') - rest_mock.assert_called_once_with(headers=headers, json=expected_payload, url=expected_url, method='DELETE', - params={}) - - @patch('requests.request') - def test_add_restart_policy_invalid_policy(self, rest_mock): - get_package_response = MagicMock() - get_package_response.text = PACKAGE_OK_NO_VALIDATE - get_package_response.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response] - client = get_client() - pkg = client.get_package('my_package') - provision_config = pkg.get_provision_configuration('test-plan') - with self.assertRaises(InvalidParameterException): - provision_config.add_restart_policy('ros-talker', 'forever') - - @patch('requests.request') - def test_delete_package_success(self, rest_mock): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/delete?package_uid={}'.format('pkg-guid') - mock_delete_package = Mock() - mock_delete_package.text = 'null' - mock_delete_package.status_code = requests.codes.OK - rest_mock.side_effect = [mock_delete_package] - client = get_client() - client.delete_package('pkg-guid') - rest_mock.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='DELETE', - params=None) - - @patch('requests.request') - def test_delete_package_with_package_object_success(self, rest_mock): - get_package_response = MagicMock(spec=Response) - get_package_response.text = PACKAGE_OK_VALIDATE - get_package_response.status_code = requests.codes.OK - mock_delete_package = Mock() - mock_delete_package.text = 'null' - mock_delete_package.status_code = requests.codes.OK - rest_mock.side_effect = [get_package_response, mock_delete_package] - client = get_client() - pkg = client.get_package('pkg-guid') - pkg.delete() - - @patch('requests.request') - def test_delete_package_invalid_package_id(self, rest_mock): - mock_delete_package = Mock() - mock_delete_package.status_code = requests.codes.UNPROCESSABLE_ENTITY - rest_mock.side_effect = [mock_delete_package] - client = get_client() - expected_err_msg = 'package_id must be a non-empty string' - with self.assertRaises(InvalidParameterException) as e: - client.delete_package(123) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_delete_package_package_not_found(self, rest_mock): - mock_delete_package = Mock() - mock_delete_package.text = PACKAGE_NOT_FOUND - mock_delete_package.status_code = requests.codes.NOT_FOUND - rest_mock.side_effect = [mock_delete_package] - client = get_client() - with self.assertRaises(ResourceNotFoundError) as e: - client.delete_package('pkg-guid') - expected_err_msg = 'Package not found' - self.assertEqual(str(e.exception), expected_err_msg) diff --git a/tests/persistent_volume_test.py b/tests/persistent_volume_test.py deleted file mode 100644 index 37dccbb1..00000000 --- a/tests/persistent_volume_test.py +++ /dev/null @@ -1,147 +0,0 @@ -from __future__ import absolute_import -import requests -import unittest - -from mock import patch, MagicMock, Mock, call, ANY -from requests import Response - -from rapyuta_io import DeploymentPhaseConstants, DiskType -from rapyuta_io.clients.persistent_volumes import DiskCapacity -from rapyuta_io.utils import InvalidParameterException -from rapyuta_io.utils.rest_client import HttpMethod -from tests.utils.client import get_client, headers -from tests.utils.package_responses import DEPLOYMENT_LIST -from tests.utils.persistent_volume_responses import GET_PACKAGE_SUCCESS, PROVISION_CLIENT_SUCCESS, \ - GET_VOLUME_INSTANCE_SUCCESS, GET_DISK_SUCCESS, GET_DISK_LIST_SUCCESS -from tests.utils.scoped_targeted_responses import SCOPED_TARGETED_PACKAGE - -PERSISTENT_VOLUME = 'io-public-persistent-volume' - - -class PersistentVolumeTest(unittest.TestCase): - - @patch('requests.request') - def test_get_volume_deployments_without_phase(self, mock_request): - expected_url_get_package = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/status?' \ - 'package_uid=io-public-persistent-volume' - expected_url_list_disk = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/disk' - expected_get_volume_instance = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceinstance/dep-lblpkngqrhdrefhvnvulaioq' - mock_get_package = Mock() - mock_get_package.text = GET_PACKAGE_SUCCESS - mock_get_package.status_code = requests.codes.OK - - mock_list_disk = Mock() - mock_list_disk.status_code = 200 - mock_list_disk.text = GET_DISK_LIST_SUCCESS - mock_get_volume_instance = Mock() - mock_get_volume_instance.status_code = 200 - mock_get_volume_instance.text = GET_VOLUME_INSTANCE_SUCCESS - mock_request.side_effect = [mock_get_package, mock_list_disk, mock_get_volume_instance] - client = get_client() - - volume = client.get_persistent_volume() - volume_instances = volume.get_all_volume_instances() - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url_get_package, method='GET', params=None), - call(headers=headers, json=None, url=expected_url_list_disk, method='GET', params={}), - call(headers=headers, json=None, url=expected_get_volume_instance, method='GET', params=None), - ]) - for vol in volume_instances: - self.assertTrue(vol.is_partial) - self.assertEqual(vol['name'], 'test-volume') - self.assertEqual(vol['parameters']['io-pv']['capacity'], 32) - self.assertEqual(vol['parameters']['io-pv']['diskType'], DiskType.SSD.value) - - @patch('requests.request') - def test_get_volume_deployments_with_phase(self, mock_request): - expected_url_get_package = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/status?' \ - 'package_uid=io-public-persistent-volume' - expected_url_list_disk = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/disk' - expected_get_volume_instance = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceinstance/dep-lblpkngqrhdrefhvnvulaioq' - mock_get_package = Mock() - mock_get_package.text = GET_PACKAGE_SUCCESS - mock_get_package.status_code = requests.codes.OK - - mock_list_disk = Mock() - mock_list_disk.status_code = 200 - mock_list_disk.text = GET_DISK_LIST_SUCCESS - mock_get_volume_instance = Mock() - mock_get_volume_instance.status_code = 200 - mock_get_volume_instance.text = GET_VOLUME_INSTANCE_SUCCESS - mock_request.side_effect = [mock_get_package, mock_list_disk, mock_get_volume_instance] - client = get_client() - - volume = client.get_persistent_volume() - volume_instances = volume.get_all_volume_instances(phases=['In Progress']) - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url_get_package, method='GET', params=None), - call(headers=headers, json=None, url=expected_url_list_disk, method='GET', params={}), - call(headers=headers, json=None, url=expected_get_volume_instance, method='GET', params=None), - ]) - for vol in volume_instances: - self.assertTrue(vol.is_partial) - self.assertEqual(vol['name'], 'test-volume') - self.assertEqual(vol['parameters']['io-pv']['capacity'], 32) - self.assertEqual(vol['parameters']['io-pv']['diskType'], DiskType.SSD.value) - - @patch('requests.request') - def test_create_volume_instance_invalid_disk_type(self, mock_request): - expected_err_msg = 'disk_type must be of rapyuta_io.clients.persistent_volumes.DiskType' - mock_get_package = Mock() - mock_get_package.text = GET_PACKAGE_SUCCESS - mock_get_package.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_package] - client = get_client() - persistent_volume = client.get_persistent_volume() - with self.assertRaises(InvalidParameterException) as e: - persistent_volume.create_volume_instance(name='test-volume', capacity=DiskCapacity.GiB_32, - disk_type='invalid_disk_type') - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_create_volume_instance_invalid_disk_capacity(self, mock_request): - expected_err_msg = 'capacity must be one of rapyuta_io.clients.persistent_volumes.DiskCapacity' - mock_get_package = Mock() - mock_get_package.text = GET_PACKAGE_SUCCESS - mock_get_package.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_package] - client = get_client() - persistent_volume = client.get_persistent_volume() - with self.assertRaises(InvalidParameterException) as e: - persistent_volume.create_volume_instance(name='test-volume', capacity='invalid_capacity', - disk_type=DiskType.SSD) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_create_volume_instance_with_integer_capacity_success(self, mock_request): - expected_url_create_disk = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/disk' - expected_url_get_disk = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/disk/disk-guid' - expected_url_provision_client = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceinstance/dep-guid' - expected_url_get_package = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/serviceclass/status?' \ - 'package_uid=io-public-persistent-volume' - mock_get_package = Mock() - mock_get_package.text = GET_PACKAGE_SUCCESS - mock_get_package.status_code = requests.codes.OK - mock_client_provision = Mock() - mock_client_provision.text = PROVISION_CLIENT_SUCCESS - mock_client_provision.status_code = requests.codes.OK - mock_client_get_disk = Mock() - mock_client_get_disk.text = GET_DISK_SUCCESS - mock_client_get_disk.status_code = requests.codes.OK - mock_get_volume_instance = Mock() - mock_get_volume_instance.text = GET_VOLUME_INSTANCE_SUCCESS - mock_get_volume_instance.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_package, mock_client_provision, mock_client_get_disk, mock_get_volume_instance] - client = get_client() - persistent_volume = client.get_persistent_volume() - volume_instance = persistent_volume.create_volume_instance(name='test-volume', capacity=32, - disk_type=DiskType.SSD) - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url_get_package, method='GET', params=None), - call(headers=headers, json=ANY, url=expected_url_create_disk, method='POST', params=None), - call(headers=headers, json=None, url=expected_url_get_disk, method='GET', params=None), - call(headers=headers, json=None, url=expected_url_provision_client, method='GET', params=None) - ]) - self.assertEqual(volume_instance['name'], 'test-volume') - self.assertEqual(volume_instance['parameters']['io-pv']['capacity'], 32) - self.assertEqual(volume_instance['parameters']['io-pv']['diskType'], DiskType.SSD.value) diff --git a/tests/project_test.py b/tests/project_test.py deleted file mode 100644 index 0ccc8a29..00000000 --- a/tests/project_test.py +++ /dev/null @@ -1,345 +0,0 @@ -from __future__ import absolute_import -import requests -import unittest - -from mock import patch, call, Mock - -from rapyuta_io.clients.project import Project -from rapyuta_io.utils import InvalidParameterException, InternalServerError -from tests.utils.client import get_client, headers, AUTH_TOKEN -from tests.utils.projects_responses import PROJECT_CREATE_SUCCESS, PROJECT_GET_SUCCESS, PROJECT_LIST_SUCCESS, \ - PROJECT_CREATE_INVITED_ORG_SUCCESS - - -class ProjectTests(unittest.TestCase): - def test_bad_names_length(self): - expected_err_msg = 'length of name must be between 3 and 15 characters' - with self.assertRaises(InvalidParameterException) as e: - Project('a') - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_names_type(self): - expected_err_msg = 'name must be a string' - with self.assertRaises(InvalidParameterException) as e: - Project(name=123) - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_names_invalid_characters(self): - expected_err_msg = 'name can have alphabets, numbers or - only' - with self.assertRaises(InvalidParameterException) as e: - Project('4@#1$') - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_create_project_invalid_project_type(self): - expected_err_msg = 'project must be non-empty and of type rapyuta_io.clients.project.Project' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_project('invalid-project-type') - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_project_invalid_organization_id(self): - expected_err_msg = 'organization_guid needs to a non empty string' - with self.assertRaises(InvalidParameterException) as e: - Project('test-project', 1) - self.assertEqual(expected_err_msg, str(e.exception)) - - @patch('requests.request') - def test_create_project_success(self, mock_request): - project = Project('test-project') - client = get_client() - expected_payload = {'name': 'test-project'} - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/create' - mock_project = Mock() - mock_project.text = PROJECT_CREATE_SUCCESS - mock_project.status_code = requests.codes.OK - mock_request.side_effect = [mock_project] - result = client.create_project(project) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params={}), - ]) - self.assertIsInstance(result, Project) - self.assertTrue(hasattr(result, 'guid')) - - @patch('requests.request') - def test_create_project_in_invited_organization_success(self, mock_request): - project = Project('test-project', 'invited-org-guid') - client = get_client() - expected_payload = {'name': 'test-project', 'organization': {'guid': 'invited-org-guid'}} - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/create' - mock_project = Mock() - mock_project.text = PROJECT_CREATE_INVITED_ORG_SUCCESS - mock_project.status_code = requests.codes.OK - mock_request.side_effect = [mock_project] - result = client.create_project(project) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params={}), - ]) - self.assertIsInstance(result, Project) - self.assertTrue(hasattr(result, 'guid')) - self.assertEqual(result.name, 'test-project') - self.assertEqual(len(result.users), 2) - self.assertEqual(result.organization.guid, 'invited-org-guid') - - @patch('requests.request') - def test_create_project_server_error(self, mock_request): - project = Project('test-project') - client = get_client() - expected_payload = {'name': 'test-project'} - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/create' - mock_project = Mock() - mock_project.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_project] - with self.assertRaises(InternalServerError) as e: - client.create_project(project) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params={}), - ]) - - @patch('requests.request') - def test_get_project_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/project-guid/get' - mock_project = Mock() - mock_project.status_code = requests.codes.OK - mock_project.text = PROJECT_GET_SUCCESS - mock_request.side_effect = [mock_project] - result = client.get_project('project-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}) - ]) - self.assertIsInstance(result, Project) - self.assertTrue(hasattr(result, 'guid')) - - @patch('rapyuta_io.utils.rest_client.DEFAULT_RETRY_COUNT', 0) - @patch('requests.request') - def test_get_project_server_error(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/project-guid/get' - mock_project = Mock() - mock_project.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_project] - with self.assertRaises(InternalServerError): - client.get_project('project-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}) - ]) - - @patch('requests.request') - def test_list_projects_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/list' - mock_projects = Mock() - mock_projects.status_code = requests.codes.OK - mock_projects.text = PROJECT_LIST_SUCCESS - mock_request.side_effect = [mock_projects] - proj_list = client.list_projects() - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}) - ]) - self.assertIsInstance(proj_list, list) - for proj in proj_list: - self.assertIsInstance(proj, Project) - self.assertTrue(hasattr(proj, 'guid')) - self.assertTrue(hasattr(proj, 'organization')) - self.assertEqual(proj.organization.name, 'temp-org') - - @patch('rapyuta_io.utils.rest_client.DEFAULT_RETRY_COUNT', 0) - @patch('requests.request') - def test_list_projects_server_error(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/list' - mock_projects = Mock() - mock_projects.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_projects] - with self.assertRaises(InternalServerError): - client.list_projects() - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}) - ]) - - @patch('requests.request') - def test_delete_project_from_client_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/delete' - expected_payload = {'guid': 'project-guid'} - mock_project = Mock() - mock_project.status_code = requests.codes.OK - mock_project.text = '{"success": true, "error": ""}' - mock_request.side_effect = [mock_project] - client.delete_project('project-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_delete_project_from_client_no_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/delete' - expected_payload = {'guid': 'project-guid'} - mock_project = Mock() - mock_project.status_code = requests.codes.OK - mock_project.text = '{"success": false, "error": ""}' - mock_request.side_effect = [mock_project] - result = client.delete_project('project-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - self.assertFalse(result) - - @patch('requests.request') - def test_delete_project_from_client_sever_error(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/delete' - expected_payload = {'guid': 'project-guid'} - mock_project = Mock() - mock_project.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_project] - with self.assertRaises(InternalServerError): - client.delete_project('project-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_delete_method_success(self, mock_request): - proj = Project('test-project') - setattr(proj, '_core_api_host', 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io') - setattr(proj, '_auth_token', 'Bearer ' + AUTH_TOKEN) - setattr(proj, 'guid', 'test_project') - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/delete' - expected_payload = {'guid': 'test_project'} - mock_project = Mock() - mock_project.status_code = requests.codes.OK - mock_project.text = '{"success": true, "error": ""}' - mock_request.side_effect = [mock_project] - proj.delete() - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_delete_method_server_error(self, mock_request): - proj = Project('test-project') - setattr(proj, '_core_api_host', 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io') - setattr(proj, '_auth_token', 'Bearer ' + AUTH_TOKEN) - setattr(proj, 'guid', 'test_project') - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/delete' - expected_payload = {'guid': 'test_project'} - mock_project = Mock() - mock_project.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_project] - with self.assertRaises(InternalServerError): - proj.delete() - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - def test_delete_local_project_error(self): - proj = Project('test-project') - expected_err_msg = 'Project must be created first' - with self.assertRaises(InvalidParameterException) as e: - proj.delete() - self.assertEqual(expected_err_msg, str(e.exception)) - - @patch('requests.request') - def test_add_user_to_project_no_success(self, mock_request): - client = get_client() - dummy_project_guid = 'dummy-project-guid' - user_guid = 'user-guid' - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/{}/adduser'.format( - dummy_project_guid) - expected_payload = {'userGUID': user_guid} - mock_add_user_to_project = Mock() - mock_add_user_to_project.status_code = requests.codes.OK - mock_add_user_to_project.text = '{"success": false, "error": "project not found"}' - mock_request.side_effect = [mock_add_user_to_project] - client.add_user_to_project(project_guid=dummy_project_guid, user_guid=user_guid) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='PUT', params={}) - ]) - - @patch('requests.request') - def test_add_user_to_project_server_error(self, mock_request): - client = get_client() - project_guid = 'project-guid' - user_guid = 'user-guid' - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/{}/adduser'.format( - project_guid) - expected_payload = {'userGUID': user_guid} - mock_add_user_to_project = Mock() - mock_add_user_to_project.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_add_user_to_project] - with self.assertRaises(InternalServerError): - client.add_user_to_project(project_guid=project_guid, user_guid=user_guid) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='PUT', params={}) - ]) - - @patch('requests.request') - def test_add_user_to_project_success(self, mock_request): - client = get_client() - project_guid = 'project-guid' - user_guid = 'user-guid' - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/{}/adduser'.format( - project_guid) - expected_payload = {'userGUID': user_guid} - mock_add_user_to_project = Mock() - mock_add_user_to_project.status_code = requests.codes.OK - mock_add_user_to_project.text = '{"success": true, "error": ""}' - mock_request.side_effect = [mock_add_user_to_project] - client.add_user_to_project(project_guid=project_guid, user_guid=user_guid) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='PUT', params={}) - ]) - - @patch('requests.request') - def test_remove_user_from_project_no_success(self, mock_request): - client = get_client() - dummy_project_guid = 'dummy-project-guid' - user_guid = 'user-guid' - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/{}/removeuser'.format( - dummy_project_guid) - expected_payload = {'userGUID': user_guid} - mock_remove_user_from_project = Mock() - mock_remove_user_from_project.status_code = requests.codes.OK - mock_remove_user_from_project.text = '{"success": false, "error": "project not found"}' - mock_request.side_effect = [mock_remove_user_from_project] - client.remove_user_from_project(project_guid=dummy_project_guid, user_guid=user_guid) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_remove_user_from_project_server_error(self, mock_request): - client = get_client() - project_guid = 'project-guid' - user_guid = 'user-guid' - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/{}/removeuser'.format( - project_guid) - expected_payload = {'userGUID': user_guid} - mock_remove_user_from_project = Mock() - mock_remove_user_from_project.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_remove_user_from_project] - with self.assertRaises(InternalServerError): - client.remove_user_from_project(project_guid=project_guid, user_guid=user_guid) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_remove_user_from_project_success(self, mock_request): - client = get_client() - project_guid = 'project-guid' - user_guid = 'user-guid' - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/project/{}/removeuser'.format( - project_guid) - expected_payload = {'userGUID': user_guid} - mock_remove_user_from_project = Mock() - mock_remove_user_from_project.status_code = requests.codes.OK - mock_remove_user_from_project.text = '{"success": true, "error": ""}' - mock_request.side_effect = [mock_remove_user_from_project] - client.remove_user_from_project(project_guid=project_guid, user_guid=user_guid) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) diff --git a/tests/routed_network_test.py b/tests/routed_network_test.py deleted file mode 100644 index 67706f03..00000000 --- a/tests/routed_network_test.py +++ /dev/null @@ -1,420 +0,0 @@ -from __future__ import absolute_import -import requests -import unittest -import json -from mock import patch, Mock, call -from rapyuta_io.clients.routed_network import RoutedNetwork, Parameters -from rapyuta_io.clients.package import ROSDistro -from rapyuta_io.clients.device import Device -from rapyuta_io.utils import to_objdict, ResourceNotFoundError -from rapyuta_io.utils.error import InvalidParameterException -from rapyuta_io.utils.partials import PartialMixin - -from tests.utils.client import get_client, remove_auth_token, add_auth_token, headers -from tests.utils.routed_networks_responses import ROUTED_NETWORK_CREATE_SUCCESS, ROUTED_NETWORK_GET_SUCCESS, \ - ROUTED_NETWORK_LIST_SUCCESS, ROUTED_NETWORK_NOT_FOUND -from six.moves import map -from rapyuta_io.clients.common_models import Limits - -class RoutedNetworkTest(unittest.TestCase): - - def setUp(self): - routed_network = { - "name": "test-network", - "guid": "net-testguid", - "internalDeploymentStatus": { - "error_code": [], - "phase": "Succeeded", - "status": "Running" - }, - } - self.routed_network = RoutedNetwork(to_objdict(routed_network)) - add_auth_token(self.routed_network) - - def test_create_cloud_routed_network_invalid_distro(self): - expected_err_msg = 'ROSDistro must be one of rapyuta_io.clients.package.ROSDistro' - - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_cloud_routed_network('test-network', 'invalid-distro', - True) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_cloud_routed_network_invalid_parameters(self): - expected_err_msg = 'parameters must be of type rapyuta_io.clients.routed_network.Parameters' - - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_cloud_routed_network('test-network', ROSDistro.KINETIC, - True, 'invalid parameters') - - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_create_device_noetic_routed_network_success(self, mock_request): - expected_payload = { - 'name': 'test-network', - 'runtime': 'device', - 'rosDistro': 'noetic', - 'shared': True, - 'parameters': { - 'NETWORK_INTERFACE': 'lo', - 'restart_policy': 'always', - 'device_id': 'test-device-id' - }, - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_create_network = Mock() - mock_create_network.text = ROUTED_NETWORK_CREATE_SUCCESS - mock_create_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network] - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network, mock_get_network] - - client = get_client() - device = Device._deserialize({'uuid': 'test-device-id', 'ip_interfaces': {'lo': 'ip'}, - 'config_variables': [], 'labels': [], 'deployments': []}) - routed_network = client.create_device_routed_network('test-network', ROSDistro.NOETIC, True, device, 'lo') - - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-testguid', method='GET', params=None) - ]) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertFalse(routed_network.is_partial) - - @patch('requests.request') - def test_create_device_routed_network_success(self, mock_request): - expected_payload = { - 'name': 'test-network', - 'runtime': 'device', - 'rosDistro': 'kinetic', - 'shared': True, - 'parameters': { - 'NETWORK_INTERFACE': 'lo', - 'restart_policy': 'always', - 'device_id': 'test-device-id' - }, - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_create_network = Mock() - mock_create_network.text = ROUTED_NETWORK_CREATE_SUCCESS - mock_create_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network] - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network, mock_get_network] - - client = get_client() - device = Device._deserialize({'uuid': 'test-device-id', 'ip_interfaces': {'lo': 'ip'}, - 'config_variables': [], 'labels': [], 'deployments': []}) - routed_network = client.create_device_routed_network('test-network', ROSDistro.KINETIC, True, device, 'lo') - - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-testguid', method='GET', params=None) - ]) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertFalse(routed_network.is_partial) - - def test_create_device_routed_network_invalid_distro(self): - expected_err_msg = 'ROSDistro must be one of rapyuta_io.clients.package.ROSDistro' - - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_device_routed_network('test-network', 'invalid-distro', - True, None, None) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_device_routed_network_without_device(self): - expected_err_msg = 'device must be of type rapyuta_io.clients.device.Device' - - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.create_device_routed_network('test-network', ROSDistro.KINETIC, - True, None, None) - - self.assertEqual(str(e.exception), expected_err_msg) - - def test_create_routed_network_without_network_interface(self): - expected_err_msg = 'NETWORK_INTERFACE should be in [\'wlp4s0\']' - - client = get_client() - device = Device._deserialize({'uuid': 'test-device-id', 'ip_interfaces': {'wlp4s0': 'ip'}, - 'config_variables': [], 'labels': [], 'deployments': []}) - with self.assertRaises(InvalidParameterException) as e: - client.create_device_routed_network('test-network', ROSDistro.KINETIC, - True, device, 'lo') - - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_create_cloud_noetic_routed_network_success(self, mock_request): - expected_payload = { - 'name': 'test-network', - 'runtime': 'cloud', - 'rosDistro': 'noetic', - 'shared': True, - 'parameters': { - }, - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_create_network = Mock() - mock_create_network.text = ROUTED_NETWORK_CREATE_SUCCESS - mock_create_network.status_code = requests.codes.OK - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network, mock_get_network] - client = get_client() - routed_network = client.create_cloud_routed_network('test-network', ROSDistro.NOETIC, - True) - - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-testguid', method='GET', params=None) - ]) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertFalse(routed_network.is_partial) - - @patch('requests.request') - def test_create_cloud_routed_network_success(self, mock_request): - expected_payload = { - 'name': 'test-network', - 'runtime': 'cloud', - 'rosDistro': 'kinetic', - 'shared': True, - 'parameters': { - }, - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_create_network = Mock() - mock_create_network.text = ROUTED_NETWORK_CREATE_SUCCESS - mock_create_network.status_code = requests.codes.OK - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network, mock_get_network] - client = get_client() - routed_network = client.create_cloud_routed_network('test-network', ROSDistro.KINETIC, - True) - - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-testguid', method='GET', params=None) - ]) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertFalse(routed_network.is_partial) - - @patch('requests.request') - def test_create_cloud_routed_network_with_parameters_success(self, mock_request): - expected_payload = { - 'name': 'test-network', - 'runtime': 'cloud', - 'rosDistro': 'kinetic', - 'shared': True, - 'parameters': {'limits': {'cpu': 1, 'memory': 1024}}, - } - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_create_network = Mock() - mock_create_network.text = ROUTED_NETWORK_CREATE_SUCCESS - mock_create_network.status_code = requests.codes.OK - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_create_network, mock_get_network] - client = get_client() - routed_network = client.create_cloud_routed_network('test-network', ROSDistro.KINETIC, - True, Parameters(limits=Limits(1, 1024))) - - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-testguid', method='GET', params=None) - ]) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertFalse(routed_network.is_partial) - - @patch('requests.request') - def test_get_routed_network(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format('net-testguid') - - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_network] - client = get_client() - routed_network = client.get_routed_network('net-testguid') - remove_auth_token(routed_network) - expected_response = json.loads(ROUTED_NETWORK_GET_SUCCESS) - expected_response['phase'] = "Succeeded" - expected_response["error_code"] = [] - expected_response["status"] = "Running" - expected_response[PartialMixin.PARTIAL_ATTR] = False - - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params=None) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertEqual(routed_network.to_dict(), expected_response) - self.assertFalse(routed_network.is_partial) - - @patch('requests.request') - def test_list_routed_network(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_list_network = Mock() - mock_list_network.text = ROUTED_NETWORK_LIST_SUCCESS - mock_list_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_network] - client = get_client() - routed_networks = client.get_all_routed_networks() - list(map(remove_auth_token, routed_networks)) - expected_response = json.loads(ROUTED_NETWORK_LIST_SUCCESS) - expected_response[0]['phase'] = "Succeeded" - expected_response[0]["error_code"] = [] - - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params=None) - self.assertEqual([routed_networks[0].to_dict()], expected_response) - for net in routed_networks: - self.assertTrue(net.is_partial) - - @patch('requests.request') - def test_routed_network_refresh(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork' - - mock_list_network = Mock() - mock_list_network.text = ROUTED_NETWORK_LIST_SUCCESS - mock_list_network.status_code = requests.codes.OK - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_list_network, mock_get_network] - expected_response = json.loads(ROUTED_NETWORK_GET_SUCCESS) - expected_response['phase'] = "Succeeded" - expected_response["error_code"] = [] - expected_response[PartialMixin.PARTIAL_ATTR] = False - - client = get_client() - routed_networks = client.get_all_routed_networks() - routed_network = routed_networks[0] - self.assertTrue(routed_network.is_partial) - routed_network.refresh() - remove_auth_token(routed_network) - - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params=None), - call(headers=headers, json=None, url=expected_url + '/' + 'net-testguid', method='GET', params={}), - ]) - self.assertFalse(routed_network.is_partial) - self.assertEqual(routed_network.guid, 'net-testguid') - self.assertEqual(routed_network.name, 'test-network') - self.assertEqual(routed_network.to_dict(), expected_response) - - def test_delete_routed_network_invalid_guid(self): - expected_err_msg = 'guid needs to be a non empty string' - client = get_client() - with self.assertRaises(InvalidParameterException) as e: - client.delete_routed_network(123) - self.assertEqual(str(e.exception), expected_err_msg) - - @patch('requests.request') - def test_delete_routed_network_not_found(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format('network-guid') - mock_delete_network = Mock() - mock_delete_network.text = ROUTED_NETWORK_NOT_FOUND - mock_delete_network.status_code = requests.codes.NOT_FOUND - mock_request.side_effect = [mock_delete_network] - client = get_client() - with self.assertRaises(ResourceNotFoundError) as e: - client.delete_routed_network('network-guid') - mock_request.assert_called_once_with(headers=headers, url=expected_url, json=None, - method='DELETE', params=None) - self.assertEqual(str(e.exception), 'routed network not found in db') - - @patch('requests.request') - def test_delete_routed_network_success(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format('network-guid') - mock_delete_network = Mock() - mock_delete_network.text = 'null' - mock_delete_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_delete_network] - client = get_client() - client.delete_routed_network('network-guid') - mock_request.assert_called_once_with(headers=headers, url=expected_url, json=None, - method='DELETE', params=None) - - @patch('requests.request') - def test_delete_routed_network_success_with_routed_network_object(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format(self.routed_network.guid) - - mock_delete_network = Mock() - mock_delete_network.text = 'null' - mock_delete_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_delete_network] - self.routed_network.delete() - - mock_request.assert_called_once_with(headers=headers, url=expected_url, json=None, - method='DELETE', params={}) - - @patch('requests.request') - def test_get_status_routed_network(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format(self.routed_network.guid) - expected_result = self.routed_network.internalDeploymentStatus - expected_result.errors = [expected_result.error_code] - mock_delete_network = Mock() - mock_delete_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_delete_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_delete_network] - deployment_status = self.routed_network.get_status() - - mock_request.assert_called_once() - self.assertEqual(mock_request.call_args_list[0][1]['url'], expected_url) - self.assertEqual(mock_request.call_args_list[0][1]['method'], 'GET') - self.assertEqual(deployment_status, expected_result) - - @patch('requests.request') - def test_get_status_routed_network(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format(self.routed_network.guid) - expected_result = self.routed_network.internalDeploymentStatus - expected_result.errors = expected_result.error_code - mock_delete_network = Mock() - mock_delete_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_delete_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_delete_network] - deployment_status = self.routed_network.get_status() - - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params={}) - self.assertEqual(deployment_status, expected_result) - - @patch('requests.request') - def test_poll_till_ready_routed_network(self, mock_request): - expected_url = 'https://gacatalog.apps.okd4v2.prod.rapyuta.io/routednetwork/{}'.format(self.routed_network.guid) - expected_result = self.routed_network.internalDeploymentStatus - expected_result.errors = expected_result.error_code - - mock_get_network = Mock() - mock_get_network.text = ROUTED_NETWORK_GET_SUCCESS - mock_get_network.status_code = requests.codes.OK - mock_request.side_effect = [mock_get_network] - deployment_status = self.routed_network.get_status() - - mock_request.assert_called_once_with(headers=headers, json=None, - url=expected_url, method='GET', params={}) - self.assertEqual(deployment_status, expected_result) diff --git a/tests/secret_test.py b/tests/secret_test.py deleted file mode 100644 index 505e0d1e..00000000 --- a/tests/secret_test.py +++ /dev/null @@ -1,352 +0,0 @@ -from __future__ import absolute_import -import base64 -from http.client import INTERNAL_SERVER_ERROR -import requests -import unittest - -from mock import Mock, call, patch - -from rapyuta_io.clients.secret import SecretType, \ - SecretConfigDocker, DOCKER_HUB_REGISTRY, Secret -from rapyuta_io.utils import InvalidParameterException, InternalServerError, ResourceNotFoundError -from tests.utils.client import get_client, headers, AUTH_TOKEN -from tests.utils.secrets_responses import SECRET_CREATE_SUCCESS, SECRET_LIST_SUCCESS, SECRET_UPDATE_SUCCESS - - -class SecretConfigTests(unittest.TestCase): - def test_bad_secret_config_docker_empty_username(self): - expected_err_msg = 'username cannot be empty' - with self.assertRaises(InvalidParameterException) as e: - SecretConfigDocker(username='', password='password', email='test@example.com') - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_secret_config_docker_empty_password(self): - expected_err_msg = 'password cannot be empty' - with self.assertRaises(InvalidParameterException) as e: - SecretConfigDocker(username='username', password='', email='test@example.com') - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_secret_config_docker_empty_email(self): - expected_err_msg = 'email cannot be empty' - with self.assertRaises(InvalidParameterException) as e: - SecretConfigDocker(username='username', password='password', email='') - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_secret_config_docker_empty_registry(self): - expected_err_msg = 'registry cannot be empty' - with self.assertRaises(InvalidParameterException) as e: - SecretConfigDocker(username='username', password='password', email='test@example.com', registry='') - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_secret_config_docker_default_registry(self): - secret_config = SecretConfigDocker(username='username', password='password', email='test@example.com') - docker_config = '{"https://index.docker.io/v1/": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - expected_serialize = {'.dockercfg': base64.b64encode(docker_config.encode()).decode()} - self.assertEqual('username', secret_config.username) - self.assertEqual('password', secret_config.password) - self.assertEqual('test@example.com', secret_config.email) - self.assertEqual(DOCKER_HUB_REGISTRY, secret_config.registry) - self.assertEqual(SecretType.DOCKER, secret_config.get_type()) - self.assertEqual(expected_serialize, secret_config.serialize()) - - def test_secret_config_docker_private_registry(self): - secret_config = SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io') - docker_config = '{"quay.io": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - expected_serialize = {'.dockercfg': base64.b64encode(docker_config.encode()).decode()} - self.assertEqual('username', secret_config.username) - self.assertEqual('password', secret_config.password) - self.assertEqual('test@example.com', secret_config.email) - self.assertEqual('quay.io', secret_config.registry) - self.assertEqual(SecretType.DOCKER, secret_config.get_type()) - self.assertEqual(expected_serialize, secret_config.serialize()) - - -class SecretTests(unittest.TestCase): - def test_bad_secret_name_length(self): - expected_err_msg = 'length of name must be between 3 and 253 characters' - with self.assertRaises(InvalidParameterException) as e: - Secret(name='a' * 300, secret_config=SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_secret_name_pattern(self): - expected_err_msg = 'name must consist of lower case alphanumeric characters or - and must start and end with ' \ - 'an alphanumeric character' - with self.assertRaises(InvalidParameterException) as e: - Secret(name='-SECRET-', secret_config=SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - self.assertEqual(expected_err_msg, str(e.exception)) - - def test_bad_secret_name_type(self): - expected_err_msg = 'name must be a string' - with self.assertRaises(InvalidParameterException) as e: - Secret(name=123, secret_config=SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - self.assertEqual(expected_err_msg, str(e.exception)) - - @patch('requests.request') - def test_create_secret_internal_server_error(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - docker_config = '{"quay.io": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - client = get_client() - expected_payload = { - 'type': str(SecretType.DOCKER), - 'data': {'.dockercfg': base64.b64encode(docker_config.encode()).decode()}, - 'name': 'test-secret' - } - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/create' - mock_secret = Mock() - mock_secret.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_secret] - with self.assertRaises(InternalServerError) as e: - client.create_secret(secret) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params={}), - ]) - - @patch('requests.request') - def test_create_secret_success(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - docker_config = '{"quay.io": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - client = get_client() - expected_payload = { - 'type': str(SecretType.DOCKER), - 'data': {'.dockercfg': base64.b64encode(docker_config.encode()).decode()}, - 'name': 'test-secret' - } - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/create' - mock_secret = Mock() - mock_secret.text = SECRET_CREATE_SUCCESS - mock_secret.status_code = requests.codes.OK - mock_request.side_effect = [mock_secret] - result = client.create_secret(secret) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='POST', params={}), - ]) - self.assertIsInstance(result, Secret) - - @patch('rapyuta_io.utils.rest_client.DEFAULT_RETRY_COUNT', 0) - @patch('requests.request') - def test_get_secret_internal_server_error(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/secret-guid/get' - mock_secret = Mock() - mock_secret.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_secret] - with self.assertRaises(InternalServerError): - client.get_secret('secret-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}), - ]) - - @patch('requests.request') - def test_get_secret_not_found(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/secret-guid/get' - mock_secret = Mock() - mock_secret.status_code = requests.codes.NOT_FOUND - mock_request.side_effect = [mock_secret] - with self.assertRaises(ResourceNotFoundError): - client.get_secret('secret-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}), - ]) - - @patch('requests.request') - def test_get_secret_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/secret-guid/get' - mock_secret = Mock() - mock_secret.text = SECRET_CREATE_SUCCESS - mock_secret.status_code = requests.codes.OK - mock_request.side_effect = [mock_secret] - result = client.get_secret('secret-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}), - ]) - self.assertIsInstance(result, Secret) - - @patch('rapyuta_io.utils.rest_client.DEFAULT_RETRY_COUNT', 0) - @patch('requests.request') - def test_list_secret_internal_server_error(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/list' - mock_secrets = Mock() - mock_secrets.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_secrets] - with self.assertRaises(InternalServerError): - client.list_secrets() - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}) - ]) - - @patch('requests.request') - def test_list_secret_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/list' - mock_secrets = Mock() - mock_secrets.status_code = requests.codes.OK - mock_secrets.text = SECRET_LIST_SUCCESS - mock_request.side_effect = [mock_secrets] - secret_list = client.list_secrets() - mock_request.assert_has_calls([ - call(headers=headers, json=None, url=expected_url, method='GET', params={}) - ]) - self.assertIsInstance(secret_list, list) - for secret in secret_list: - self.assertIsInstance(secret, Secret) - - @patch('requests.request') - def test_delete_secret_internal_server_error(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/delete' - expected_payload = {'guid': 'secret-guid'} - mock_secret = Mock() - mock_secret.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_secret] - with self.assertRaises(InternalServerError): - client.delete_secret('secret-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_delete_secret_no_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/delete' - expected_payload = {'guid': 'secret-guid'} - mock_secret = Mock() - mock_secret.status_code = requests.codes.OK - mock_secret.text = '{"success": false, "error": ""}' - mock_request.side_effect = [mock_secret] - result = client.delete_secret('secret-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - self.assertFalse(result) - - @patch('requests.request') - def test_delete_secret_success(self, mock_request): - client = get_client() - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/delete' - expected_payload = {'guid': 'secret-guid'} - mock_secret = Mock() - mock_secret.status_code = requests.codes.OK - mock_secret.text = '{"success": true, "error": ""}' - mock_request.side_effect = [mock_secret] - client.delete_secret('secret-guid') - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_delete_method_internal_server_error(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com')) - setattr(secret, '_core_api_host', 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io') - setattr(secret, '_auth_token', 'Bearer ' + AUTH_TOKEN) - setattr(secret, '_project', 'test_project') - setattr(secret, 'guid', 'secret-guid') - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/delete' - expected_payload = {'guid': 'secret-guid'} - mock_secret = Mock() - mock_secret.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_secret] - with self.assertRaises(InternalServerError): - secret.delete() - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - def test_delete_method_invalid_parameter(self): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com')) - expected_err_msg = 'Secret must be created first' - setattr(secret, 'guid', 'secret-guid') - with self.assertRaises(InvalidParameterException) as e: - secret.delete() - self.assertEqual(expected_err_msg, str(e.exception)) - - @patch('requests.request') - def test_delete_method_success(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - setattr(secret, '_core_api_host', 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io') - setattr(secret, '_auth_token', 'Bearer ' + AUTH_TOKEN) - setattr(secret, '_project', 'test_project') - setattr(secret, 'guid', 'secret-guid') - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/delete' - expected_payload = {'guid': 'secret-guid'} - mock_secret = Mock() - mock_secret.status_code = requests.codes.OK - mock_secret.text = '{"success": true, "error":""}' - mock_request.side_effect = [mock_secret] - secret.delete() - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='DELETE', params={}) - ]) - - @patch('requests.request') - def test_update_method_success(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - docker_config = '{"quay.io": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - client = get_client() - expected_payload = { - 'type': str(SecretType.DOCKER), - 'data': {'.dockercfg': base64.b64encode(docker_config.encode()).decode()}, - 'name': 'test-secret' - } - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/secret-guid/update' - mock_secret = Mock() - mock_secret.text = SECRET_UPDATE_SUCCESS - mock_secret.status_code = requests.codes.OK - mock_request.side_effect = [mock_secret] - result = client.update_secret('secret-guid', secret) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='PUT', params={}), - ]) - self.assertIsInstance(result, Secret) - - @patch('requests.request') - def test_update_method_internal_server_error(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - docker_config = '{"quay.io": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - client = get_client() - expected_payload = { - 'type': str(SecretType.DOCKER), - 'data': {'.dockercfg': base64.b64encode(docker_config.encode()).decode()}, - 'name': 'test-secret' - } - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/secret-guid/update' - mock_secret = Mock() - mock_secret.status_code = requests.codes.INTERNAL_SERVER_ERROR - mock_request.side_effect = [mock_secret] - with self.assertRaises(InternalServerError) as e: - client.update_secret("secret-guid", secret) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='PUT', params={}), - ]) - - @patch('requests.request') - def test_update_method_not_found_error(self, mock_request): - secret = Secret('test-secret', SecretConfigDocker(username='username', password='password', email='test@example.com', - registry='quay.io')) - docker_config = '{"quay.io": {"username": "username", "password": "password", "email": "test@example.com", "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="}}' - client = get_client() - expected_payload = { - 'type': str(SecretType.DOCKER), - 'data': {'.dockercfg': base64.b64encode(docker_config.encode()).decode()}, - 'name': 'test-secret' - } - expected_url = 'https://gaapiserver.apps.okd4v2.prod.rapyuta.io/api/secret/secret-guid/update' - mock_secret = Mock() - mock_secret.status_code = requests.codes.NOT_FOUND - mock_request.side_effect = [mock_secret] - with self.assertRaises(ResourceNotFoundError) as e: - client.update_secret("secret-guid", secret) - mock_request.assert_has_calls([ - call(headers=headers, json=expected_payload, url=expected_url, method='PUT', params={}), - ]) \ No newline at end of file