def choose_template_to_copy( service_id, from_service=None, from_folder=None, ): if from_service: current_user.belongs_to_service_or_403(from_service) service = Service(service_api_client.get_service(from_service)['data']) return render_template( 'views/templates/copy.html', services_templates_and_folders=TemplateList( service, template_folder_id=from_folder, user=current_user), template_folder_path=service.get_template_folder_path(from_folder), from_service=service, search_form=SearchByNameForm(), ) else: return render_template( 'views/templates/copy.html', services_templates_and_folders=TemplateLists([ Service(service) for service in user_api_client.get_services_for_user(current_user) ], user=current_user), search_form=SearchByNameForm(), )
def test_organisation_type_when_service_and_its_org_both_have_an_org_type(mocker, service_one): # service_one has an organisation_type of 'central' service = Service(service_one) org = organisation_json(organisation_type='local') mocker.patch('app.organisations_client.get_service_organisation', return_value=org) assert service.organisation_type == 'local'
def create(current_user, workspaceId, projectId): """ Create a service. Reuires login """ if request.content_type == 'application/json': post_data = request.get_json(force=True) required_keys = ['serviceType', 'serviceMeta'] if all(name in post_data for name in required_keys): service = Service(serviceType=post_data.get('serviceType'), serviceMeta=post_data.get('serviceMeta'), projectId=projectId, createdBy=current_user.email_id) service.create() # add to project project = Project.get_by_id(projectId) project.services.append(service._id) project.save() # Replcing _id with id service_obj = json.loads(service.to_json()) service_obj['id'] = service_obj['_id'] service_obj.pop('_id', None) return response_with_obj('success', 'Service created successfully', service_obj, 200) else: return response('failed', 'Required data not found in POST body.', 402) return response('failed', 'Content-type must be json', 402)
def __init__(self, app): self.app = app self.services_cfg_file_path = None self.services = {} # Find the services yaml file self.__find_services_yml_file_path() # Read the services param file with open(self.services_cfg_file_path, "r", encoding='utf8') as stream: try: services_dict = yaml.safe_load(stream) for k, v in list(services_dict.items()): v["cfg_file_path"] = self.services_cfg_file_path v["name"] = k s = Service(**v) self.services[k] = s self.app.init_success = True except yaml.YAMLError as e: self.app.logger.exception(e) self.app.logger.critical( "The app config file is not correctly formed. The initialization porcess will stop." "The following configuration file must be fixed before the application is restarted : " "{}".format(self.services_cfg_file_path) )
def load_service_before_request(): if "/static/" in request.url: _request_ctx_stack.top.service = None _request_ctx_stack.top.organisation = None # added to init None to ensure request context has None or something return if _request_ctx_stack.top is not None: _request_ctx_stack.top.service = None _request_ctx_stack.top.organisation = None # added to init None to ensure request context has None or something if request.view_args: service_id = request.view_args.get("service_id", session.get("service_id")) else: service_id = session.get("service_id") if service_id: try: _request_ctx_stack.top.service = Service( service_api_client.get_service(service_id)["data"]) except HTTPError as exc: # if service id isn't real, then 404 rather than 500ing later because we expect service to be set if exc.status_code == 404: abort(404) else: raise
def test_get_template_folders_shows_user_folders_when_user_id_passed_in( app_, mock_get_template_folders, service_one, active_user_with_permissions, mocker ): mock_get_template_folders.return_value = _get_all_folders(active_user_with_permissions) service = Service(service_one) result = service.get_template_folders(user=User(active_user_with_permissions)) assert result == [ { 'name': ["Parent 1 - invisible", "1's Visible child"], 'id': mocker.ANY, 'parent_id': None, 'users_with_permission': [active_user_with_permissions['id']] }, { 'name': ["Parent 1 - invisible", ["1's Invisible child", "1's Visible grandchild"]], 'id': mocker.ANY, 'parent_id': None, 'users_with_permission': [active_user_with_permissions['id']] }, { 'name': "Parent 2 - visible", 'id': VIS_PARENT_FOLDER_ID, 'parent_id': None, 'users_with_permission': [active_user_with_permissions['id']] }, ]
def test_get_template_folders_shows_all_folders_when_user_id_not_passed_in( mock_get_template_folders, service_one, active_user_with_permissions, mocker ): mock_get_template_folders.return_value = _get_all_folders(active_user_with_permissions) service = Service(service_one) result = service.get_template_folders() assert result == [ { 'name': "Invisible folder", 'id': mocker.ANY, 'parent_id': None, 'users_with_permission': [] }, { 'name': "Parent 1 - invisible", 'id': INV_PARENT_FOLDER_ID, 'parent_id': None, 'users_with_permission': [] }, { 'name': "Parent 2 - visible", 'id': VIS_PARENT_FOLDER_ID, 'parent_id': None, 'users_with_permission': [active_user_with_permissions['id']], } ]
def test_go_live_checklist( mocker, service_one, has_submitted_use_case, has_templates, has_team_members_status, has_accepted_tos, expected_completed, app_, ): for prop in [ "has_submitted_use_case", "has_templates", "has_team_members_status", "has_accepted_tos", ]: mocker.patch( f"app.models.service.Service.{prop}", new_callable=PropertyMock, return_value=locals()[prop], ) with app_.test_request_context(): checklist = Service(service_one).go_live_checklist assert len(checklist) == 4 assert checklist[0].keys() == set(["text", "status", "endpoint", "completed"]) assert { "text": "Add a team member who can manage settings", "status": has_team_members_status, "endpoint": "main.manage_users", "completed": expected_completed, } in checklist
def test_get_template_folders_shows_all_folders_when_user_id_not_passed_in( mock_get_template_folders, service_one, active_user_with_permissions, mocker ): mock_get_template_folders.return_value = _get_all_folders(active_user_with_permissions) service = Service(service_one) result = service.get_template_folders() assert result == [ { "name": "Invisible folder", "id": mocker.ANY, "parent_id": None, "users_with_permission": [], }, { "name": "Parent 1 - invisible", "id": INV_PARENT_FOLDER_ID, "parent_id": None, "users_with_permission": [], }, { "name": "Parent 2 - visible", "id": VIS_PARENT_FOLDER_ID, "parent_id": None, "users_with_permission": [active_user_with_permissions["id"]], }, ]
def test_organisation_type_when_services_organisation_has_no_org_type(mocker, service_one): service = Service(service_one) service._dict['organisation_id'] = ORGANISATION_ID org = organisation_json(organisation_type=None) mocker.patch('app.organisations_client.get_organisation', return_value=org) assert not org['organisation_type'] assert service.organisation_type == 'central'
def test_get_status_filters_calculates_stats(client): ret = get_status_filters(Service({'id': 'foo'}), 'sms', STATISTICS) assert {label: count for label, _option, _link, count in ret} == { 'total': 6, 'sending': 3, 'failed': 2, 'delivered': 1 }
def test_organisation_type_when_services_organisation_has_no_org_type(mocker, service_one, organisation_one): service = Service(service_one) mocker.patch( "app.organisations_client.get_service_organisation", return_value=organisation_one, ) assert not organisation_one["organisation_type"] assert service.organisation_type == "central"
def create_service(name, repository, tag): service = Service(name=name, repository=repository, tag=tag) db.session.add(service) try: db.session.commit() print('Successfully created service', name) except IntegrityError: db.session.rollback() print('Service already exists')
def test_get_status_filters_in_right_order(client): ret = get_status_filters(Service({"id": "foo"}), "sms", STATISTICS) assert [label for label, _option, _link, _count in ret] == [ "total", "sending", "delivered", "failed", ]
def add_service(self, name, repository, tag): try: service = Service(name=name, repository=repository, tag=tag) db.session.add(service) db.session.commit() return service except IntegrityError: db.session.rollback() return None
def test_has_team_members_status_no_invited_users( service_one, mock_get_invites_without_manage_permission, mock_get_users_by_service ): # 1 active with "manage_service", 1 invited without "manage_service" service = Service(service_one) assert len(service.team_members) == 2 assert len(service.invited_users) == 1 assert service.has_team_members_status is False
def test_get_status_filters_calculates_stats(client): ret = get_status_filters(Service({"id": "foo"}), "sms", STATISTICS) assert {label: count for label, _option, _link, count in ret} == { "total": 6, "sending": 3, "failed": 2, "delivered": 1, }
def create_service_info(): with open('service-info.json') as service_info_json: data = json.load(service_info_json) service_info = Service(**data) service_info.contactUrl = SERVICE_INFO_CONTACTURL service_info.environment = SERVICE_INFO_ENVIRONMENT service_info.version = SERVICE_INFO_VERSION service_info.createdAt = SERVICE_INFO_CREATEDAT service_info.updatedAt = datetime.now().strftime("%d-%m-%y") serviceInfo.service = service_info
def test_service_without_organisation_doesnt_need_org_api(mocker, service_one): mock_redis_get = mocker.patch('app.extensions.RedisClient.get') mock_get_organisation = mocker.patch('app.organisations_client.get_organisation') service = Service(service_one) service._dict['organisation'] = None assert service.organisation_id is None assert service.organisation_name is None assert isinstance(service.organisation, Organisation) assert mock_redis_get.called is False assert mock_get_organisation.called is False
def test_organisation_name_comes_from_cache(mocker, service_one): mock_redis_get = mocker.patch( 'app.extensions.RedisClient.get', return_value=b'"Borchester Council"', ) mock_get_organisation = mocker.patch('app.organisations_client.get_organisation') service = Service(service_one) service._dict['organisation'] = ORGANISATION_ID assert service.organisation_name == 'Borchester Council' mock_redis_get.assert_called_once_with(f'organisation-{ORGANISATION_ID}-name') assert mock_get_organisation.called is False
def test_active_service_can_be_modified(app_, method, user, service): api_client = NotifyAdminAPIClient() with app_.test_request_context() as request_context, app_.test_client( ) as client: client.login(user) request_context.service = Service(service) with patch.object(api_client, "request") as request: ret = getattr(api_client, method)("url", "data") assert request.called assert ret == request.return_value
def test_has_team_members_status_multiple_active_users(mocker, service_one, active_user_with_permissions): # 2 active users with "manage_service" permission mocker.patch( "app.models.user.Users.client", return_value=[ active_user_with_permissions, active_user_with_permissions, ], ) service = Service(service_one) assert len(service.active_users) == 2 assert service.has_team_members_status is True
def test_inactive_service_can_be_modified_by_platform_admin( app_, platform_admin_user, method): api_client = NotifyAdminAPIClient() with app_.test_request_context() as request_context, app_.test_client( ) as client: client.login(platform_admin_user) request_context.service = Service(service_json(active=False)) with patch.object(api_client, "request") as request: ret = getattr(api_client, method)("url", "data") assert request.called assert ret == request.return_value
def test_inactive_service_cannot_be_modified_by_normal_user( app_, api_user_active, method): api_client = NotifyAdminAPIClient() with app_.test_request_context() as request_context, app_.test_client( ) as client: client.login(api_user_active) request_context.service = Service(service_json(active=False)) with patch.object(api_client, "request") as request: with pytest.raises(werkzeug.exceptions.Forbidden): getattr(api_client, method)("url", "data") assert not request.called
def test_logging_enabled_for_admin_users(app_, platform_admin_user, method, caplog): api_client = NotifyAdminAPIClient() with app_.test_request_context() as request_context, app_.test_client( ) as client: client.login(platform_admin_user) request_context.service = Service(service_json(active=False)) with patch.object(api_client, "request") as request: ret = getattr(api_client, method)("url", "data") assert request.called assert len(caplog.records) == 1 assert ret == request.return_value
def test_organisation_name_goes_into_cache(mocker, service_one): mocker.patch( 'app.extensions.RedisClient.get', return_value=None, ) mock_redis_set = mocker.patch('app.extensions.RedisClient.set', ) mocker.patch( 'app.organisations_client.get_organisation', return_value=organisation_json(), ) service = Service(service_one) service._dict['organisation'] = ORGANISATION_ID assert service.organisation_name == 'Test Organisation' mock_redis_set.assert_called_once_with( f'organisation-{ORGANISATION_ID}-name', '"Test Organisation"', ex=604800, )
def test_get_user_template_folders_only_returns_folders_visible_to_user( app_, mock_get_template_folders, service_one, active_user_with_permissions, mocker ): mock_get_template_folders.return_value = _get_all_folders(active_user_with_permissions) service = Service(service_one) result = service.get_user_template_folders(User(active_user_with_permissions)) assert result == [ { "name": ["Parent 1 - invisible", "1's Visible child"], "id": mocker.ANY, "parent_id": None, "users_with_permission": [active_user_with_permissions["id"]], }, { "name": [ "Parent 1 - invisible", ["1's Invisible child", "1's Visible grandchild"], ], "id": mocker.ANY, "parent_id": None, "users_with_permission": [active_user_with_permissions["id"]], }, { "name": "2's Visible child", "id": mocker.ANY, "parent_id": VIS_PARENT_FOLDER_ID, "users_with_permission": [active_user_with_permissions["id"]], }, { "name": ["2's Invisible child", "2's Visible grandchild"], "id": mocker.ANY, "parent_id": VIS_PARENT_FOLDER_ID, "users_with_permission": [active_user_with_permissions["id"]], }, { "name": "Parent 2 - visible", "id": VIS_PARENT_FOLDER_ID, "parent_id": None, "users_with_permission": [active_user_with_permissions["id"]], }, ]
def publish(self, projectId, current_user, priceContract): """ Publish Bot - Triggers Billing TODO """ self.publishedOn = util.get_current_time() if not self.isPublished: self.isPublished = True ##Create a bot service serviceMeta = self.playgroundMeta serviceMeta["priceContract"] = priceContract service = Service(serviceType='bot', serviceMeta=serviceMeta, projectId=projectId, createdBy=current_user.email_id) service.create() self.publishedServiceId = service._id #add to project project = Project.get_by_id(projectId) project.services.append(service._id) project.save() self.save() else: #update service service = Service.get_by_id(self.publishedServiceId) servicePriceContract = service.serviceMeta.get( "priceContract", {}) #get exisitng price contract serviceMeta = self.playgroundMeta #copy new playground meta serviceMeta[ "priceContract"] = servicePriceContract #add priceContract to service Meta service.serviceMeta = serviceMeta #set new service meta service.save() self.save() return service._id
def test_get_user_template_folders_only_returns_folders_visible_to_user( mock_get_template_folders, service_one, active_user_with_permissions, mocker): mock_get_template_folders.return_value = _get_all_folders( active_user_with_permissions) service = Service(service_one) result = service.get_user_template_folders(active_user_with_permissions) assert result == [ { 'name': "Parent 1 - invisible / 1's Visible child", 'id': mocker.ANY, 'parent_id': None, 'users_with_permission': [active_user_with_permissions.id] }, { 'name': "Parent 1 - invisible / 1's Invisible child / 1's Visible grandchild", 'id': mocker.ANY, 'parent_id': None, 'users_with_permission': [active_user_with_permissions.id] }, { 'name': "2's Visible child", 'id': mocker.ANY, 'parent_id': VIS_PARENT_FOLDER_ID, 'users_with_permission': [active_user_with_permissions.id] }, { 'name': "2's Invisible child / 2's Visible grandchild", 'id': mocker.ANY, 'parent_id': VIS_PARENT_FOLDER_ID, 'users_with_permission': [active_user_with_permissions.id] }, { 'name': "Parent 2 - visible", 'id': VIS_PARENT_FOLDER_ID, 'parent_id': None, 'users_with_permission': [active_user_with_permissions.id] }, ]
def load_service_before_request(): if '/static/' in request.url: _request_ctx_stack.top.service = None return if _request_ctx_stack.top is not None: _request_ctx_stack.top.service = None if request.view_args: service_id = request.view_args.get('service_id', session.get('service_id')) else: service_id = session.get('service_id') if service_id: try: _request_ctx_stack.top.service = Service( service_api_client.get_service(service_id)['data'] ) except HTTPError as exc: # if service id isn't real, then 404 rather than 500ing later because we expect service to be set if exc.status_code == 404: abort(404) else: raise