def test_create_service_and_history_is_transactional(sample_user): assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0 service = Service(name=None, email_from="email_from", message_limit=1000, restricted=False, created_by=sample_user) with pytest.raises(IntegrityError) as excinfo: dao_create_service(service, sample_user) assert 'column "name" violates not-null constraint' in str(excinfo.value) assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0
def test_save_api_key_should_not_create_new_service_history(sample_service): from app.models import Service assert Service.query.count() == 1 assert Service.get_history_model().query.count() == 1 api_key = ApiKey(**{'service': sample_service, 'name': sample_service.name, 'created_by': sample_service.created_by, 'key_type': KEY_TYPE_NORMAL}) save_model_api_key(api_key) assert Service.get_history_model().query.count() == 1
def delete_service_and_all_associated_db_objects(service): def _delete_commit(query): query.delete() db.session.commit() _delete_commit(NotificationStatistics.query.filter_by(service=service)) _delete_commit(TemplateStatistics.query.filter_by(service=service)) _delete_commit(ProviderStatistics.query.filter_by(service=service)) _delete_commit(InvitedUser.query.filter_by(service=service)) _delete_commit(Permission.query.filter_by(service=service)) _delete_commit(ApiKey.query.filter_by(service=service)) _delete_commit(ApiKey.get_history_model().query.filter_by(service_id=service.id)) _delete_commit(NotificationHistory.query.filter_by(service=service)) _delete_commit(Notification.query.filter_by(service=service)) _delete_commit(Job.query.filter_by(service=service)) _delete_commit(Template.query.filter_by(service=service)) _delete_commit(TemplateHistory.query.filter_by(service_id=service.id)) verify_codes = VerifyCode.query.join(User).filter(User.id.in_([x.id for x in service.users])) list(map(db.session.delete, verify_codes)) db.session.commit() users = [x for x in service.users] map(service.users.remove, users) [service.users.remove(x) for x in users] _delete_commit(Service.get_history_model().query.filter_by(id=service.id)) db.session.delete(service) db.session.commit() list(map(db.session.delete, users)) db.session.commit()
def test_create_service_and_history_is_transactional(notify_db_session): user = create_user() assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0 service = Service(name=None, email_from="email_from", message_limit=1000, restricted=False, created_by=user) with pytest.raises(IntegrityError) as excinfo: dao_create_service(service, user) assert 'column "name" violates not-null constraint' in str(excinfo.value) assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0
def test_delete_service_and_associated_objects( notify_db, notify_db_session, sample_user, sample_service, sample_email_code, sample_sms_code, sample_template, sample_email_template, sample_api_key, sample_job, sample_notification, sample_invited_user, sample_permission, sample_provider_statistics, ): delete_service_and_all_associated_db_objects(sample_service) assert NotificationStatistics.query.count() == 0 assert TemplateStatistics.query.count() == 0 assert ProviderStatistics.query.count() == 0 assert VerifyCode.query.count() == 0 assert ApiKey.query.count() == 0 assert ApiKey.get_history_model().query.count() == 0 assert Template.query.count() == 0 assert TemplateHistory.query.count() == 0 assert Job.query.count() == 0 assert Notification.query.count() == 0 assert Permission.query.count() == 0 assert User.query.count() == 0 assert InvitedUser.query.count() == 0 assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0
def delete_service_and_all_associated_db_objects(service): def _delete_commit(query): query.delete(synchronize_session=False) db.session.commit() subq = db.session.query(Template.id).filter_by(service=service).subquery() _delete_commit( TemplateRedacted.query.filter(TemplateRedacted.template_id.in_(subq))) _delete_commit(ServiceSmsSender.query.filter_by(service=service)) _delete_commit(InvitedUser.query.filter_by(service=service)) _delete_commit(Permission.query.filter_by(service=service)) _delete_commit(NotificationHistory.query.filter_by(service=service)) _delete_commit(Notification.query.filter_by(service=service)) _delete_commit(Job.query.filter_by(service=service)) _delete_commit(Template.query.filter_by(service=service)) _delete_commit(TemplateHistory.query.filter_by(service_id=service.id)) _delete_commit(ServicePermission.query.filter_by(service_id=service.id)) _delete_commit(ApiKey.query.filter_by(service=service)) _delete_commit( ApiKey.get_history_model().query.filter_by(service_id=service.id)) _delete_commit(AnnualBilling.query.filter_by(service_id=service.id)) verify_codes = VerifyCode.query.join(User).filter( User.id.in_([x.id for x in service.users])) list(map(db.session.delete, verify_codes)) db.session.commit() users = [x for x in service.users] map(service.users.remove, users) [service.users.remove(x) for x in users] _delete_commit(Service.get_history_model().query.filter_by(id=service.id)) db.session.delete(service) db.session.commit() list(map(db.session.delete, users)) db.session.commit()
def post(self, jwt): data = [] if request.is_json and request.get_json(silent=True) is not None: try: post_data = request.get_json() service_name = post_data.get('service_name') warning_str = "" critical_str = "" if service_name is None: return jsonify(error=True, msg="Missing service name required field.") services = Service.get_by_description(service_name) if services is None: return jsonify(error=True) else: for service in services: warning_str = str(service.warning) critical_str = service.critical break data.append({ "warning": warning_str, "critical": critical_str }) except Exception as e: return jsonify(error=True, msg=str(e)) return jsonify(data=data)
def dao_fetch_service_creator(service_id: uuid.UUID) -> User: service_history = Service.get_history_model() query = (User.query.join(service_history, User.id == service_history.created_by_id).filter( service_history.id == service_id, service_history.version == 1).one()) return query
def test_should_reject_notification_if_job_id_not_on_service(notify_api, notify_db, notify_db_session, notify_config): service = Service( id=1000, name="unrelated service", created_at=datetime.now(), active=True, restricted=True, limit=100 ) job = Job(id=1000, name="job test", created_at=datetime.now()) job.service = service db.session.add(service) db.session.add(job) db.session.commit() response = notify_api.test_client().post( '/sms/notification', headers={ 'Authorization': 'Bearer 1234' }, data=json.dumps({ "notification": { "to": "+441234512345", "message": "Some message", "jobId": 1000 } }), content_type='application/json' ) data = json.loads(response.get_data()) assert response.status_code == 400 assert data['error'] == 'Invalid job id for these credentials'
def test_create_service_with_organisation(notify_db_session): user = create_user(email='*****@*****.**') organisation = create_organisation(name='Some local authority', organisation_type='other', domains=['local-authority.gov.uk']) assert Service.query.count() == 0 service = Service(name="service_name", email_from="email_from", message_limit=1000, restricted=False, organisation_type='some-org-type', created_by=user) dao_create_service(service, user) assert Service.query.count() == 1 service_db = Service.query.one() organisation = Organisation.query.get(organisation.id) assert service_db.name == "service_name" assert service_db.id == service.id assert service_db.email_from == 'email_from' assert service_db.research_mode is False assert service_db.prefix_sms is False assert service.active is True assert user in service_db.users assert service_db.organisation_type == 'other' assert service_db.crown is None assert not service.letter_branding assert service.organisation_id == organisation.id assert service.organisation == organisation
def get_service_history(service_id): from app.models import (Service, ApiKey, TemplateHistory) from app.schemas import (service_history_schema, api_key_history_schema, template_history_schema) service_history = Service.get_history_model().query.filter_by( id=service_id).all() service_data = service_history_schema.dump(service_history, many=True).data api_key_history = ApiKey.get_history_model().query.filter_by( service_id=service_id).all() api_keys_data = api_key_history_schema.dump(api_key_history, many=True).data template_history = TemplateHistory.query.filter_by( service_id=service_id).all() template_data, errors = template_history_schema.dump(template_history, many=True) data = { 'service_history': service_data, 'api_key_history': api_keys_data, 'template_history': template_data, 'events': [] } return jsonify(data=data)
def notify_service(notify_db, notify_db_session): user = create_user() service = Service.query.get(current_app.config["NOTIFY_SERVICE_ID"]) if not service: service = Service( name="Notify Service", message_limit=1000, restricted=False, email_from="notify.service", created_by=user, prefix_sms=False, ) dao_create_service( service=service, service_id=current_app.config["NOTIFY_SERVICE_ID"], user=user, ) data = { "service": service, "email_address": "*****@*****.**", "is_default": True, } reply_to = ServiceEmailReplyTo(**data) db.session.add(reply_to) db.session.commit() return service, user
def test_delete_service_and_associated_objects(notify_db_session): user = create_user() service = create_service(user=user, service_permissions=None) create_user_code(user=user, code='somecode', code_type='email') create_user_code(user=user, code='somecode', code_type='sms') template = create_template(service=service) api_key = create_api_key(service=service) create_notification(template=template, api_key=api_key) create_invited_user(service=service) assert ServicePermission.query.count() == len(( SMS_TYPE, EMAIL_TYPE, INTERNATIONAL_SMS_TYPE, )) delete_service_and_all_associated_db_objects(service) assert VerifyCode.query.count() == 0 assert ApiKey.query.count() == 0 assert ApiKey.get_history_model().query.count() == 0 assert Template.query.count() == 0 assert TemplateHistory.query.count() == 0 assert Job.query.count() == 0 assert Notification.query.count() == 0 assert Permission.query.count() == 0 assert User.query.count() == 0 assert InvitedUser.query.count() == 0 assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0 assert ServicePermission.query.count() == 0
def test_save_api_key_should_not_create_new_service_history(sample_service): from app.models import Service assert Service.query.count() == 1 assert Service.get_history_model().query.count() == 1 api_key = ApiKey( **{ 'service': sample_service, 'name': sample_service.name, 'created_by': sample_service.created_by, 'key_type': KEY_TYPE_NORMAL }) save_model_api_key(api_key) assert Service.get_history_model().query.count() == 1
def test_create_nhs_service_get_default_branding_based_on_email_address( notify_db_session, branding_name_to_create, expected_branding, email_address, organisation_type, ): user = create_user(email=email_address) letter_branding = create_letter_branding(name=branding_name_to_create) email_branding = create_email_branding(name=branding_name_to_create) service = Service( name="service_name", email_from="email_from", message_limit=1000, restricted=False, organisation_type=organisation_type, created_by=user, ) dao_create_service(service, user) service_db = Service.query.one() if expected_branding: assert service_db.letter_branding == letter_branding assert service_db.email_branding == email_branding else: assert service_db.letter_branding is None assert service_db.email_branding is None
def test_add_existing_user_to_another_service_doesnot_change_old_permissions(notify_db_session): user = create_user() service_one = Service(name="service_one", email_from="service_one", message_limit=1000, restricted=False, created_by=user) dao_create_service(service_one, user) assert user.id == service_one.users[0].id test_user_permissions = Permission.query.filter_by(service=service_one, user=user).all() assert len(test_user_permissions) == 8 other_user = User( name='Other Test User', email_address='*****@*****.**', password='******', mobile_number='+447700900987' ) save_model_user(other_user, validated_email_access=True) service_two = Service(name="service_two", email_from="service_two", message_limit=1000, restricted=False, created_by=other_user) dao_create_service(service_two, other_user) assert other_user.id == service_two.users[0].id other_user_permissions = Permission.query.filter_by(service=service_two, user=other_user).all() assert len(other_user_permissions) == 8 other_user_service_one_permissions = Permission.query.filter_by(service=service_one, user=other_user).all() assert len(other_user_service_one_permissions) == 0 # adding the other_user to service_one should leave all other_user permissions on service_two intact permissions = [] for p in ['send_emails', 'send_texts', 'send_letters']: permissions.append(Permission(permission=p)) dao_add_user_to_service(service_one, other_user, permissions=permissions) other_user_service_one_permissions = Permission.query.filter_by(service=service_one, user=other_user).all() assert len(other_user_service_one_permissions) == 3 other_user_service_two_permissions = Permission.query.filter_by(service=service_two, user=other_user).all() assert len(other_user_service_two_permissions) == 8
def test_view_all(self): """Test if view all works""" res1 = Service("maintenance", "request descriptions", "location", "1") res1.add() res2 = Service("maintenance", "request descriptions", "location", "1") res2.add() res = self.request.view_all() count = len(res) self.assertEqual(count, 2)
def create_service(user=None, service_name="Sample service", service_id=None, restricted=False, count_as_live=True, service_permissions=[EMAIL_TYPE, SMS_TYPE], research_mode=False, active=True, email_from=None, prefix_sms=True, message_limit=1000, organisation_type='central', check_if_service_exists=False, go_live_user=None, go_live_at=None, crown=True, organisation=None): if check_if_service_exists: service = Service.query.filter_by(name=service_name).first() if (not check_if_service_exists) or (check_if_service_exists and not service): service = Service( name=service_name, message_limit=message_limit, restricted=restricted, email_from=email_from if email_from else service_name.lower().replace(' ', '.'), created_by=user if user else create_user( email='{}@digital.cabinet-office.gov.uk'.format(uuid.uuid4())), prefix_sms=prefix_sms, organisation_type=organisation_type, go_live_user=go_live_user, go_live_at=go_live_at, crown=crown) dao_create_service(service, service.created_by, service_id, service_permissions=service_permissions) service.active = active service.research_mode = research_mode service.count_as_live = count_as_live else: if user and user not in service.users: dao_add_user_to_service(service, user) return service
def test_live_dos_service_is_not_deleted(self, search_api_client, live_dos_framework): dos = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists').first() with mock.patch.object(Service, "serialize"): service = Service(status='published', framework=dos) delete_service_from_index(service) assert search_api_client.delete.called is False
def setup(self): super(BaseBriefResponseTest, self).setup() self.supplier_ids = self.setup_dummy_suppliers(2) supplier_frameworks = [ SupplierFramework(supplier_id=supplier_id, framework_id=5) for supplier_id in self.supplier_ids ] brief = Brief(data=example_listings.brief_data().example(), status='live', framework_id=5, lot=Lot.query.get(5)) service = Service( service_id='1234560987654321', data={'locations': [brief.data['location']]}, status='published', framework_id=5, lot_id=5, supplier_id=0, ) specialist_brief = Brief(data=example_listings.brief_data().example(), status='live', framework_id=5, lot=Lot.query.get(6)) specialist_service = Service( service_id='1234560987654322', data={ 'developerLocations': [specialist_brief.data['location']], 'developerPriceMin': "0", 'developerPriceMax': "1000" }, status='published', framework_id=5, lot_id=6, supplier_id=0, ) db.session.add_all( [service, specialist_service, brief, specialist_brief] + supplier_frameworks) db.session.commit() self.brief_id = brief.id self.specialist_brief_id = specialist_brief.id
def test_expired_g_cloud_6_service_is_not_deleted(self, search_api_client, expired_g6_framework): g6 = Framework.query.filter(Framework.slug == 'g-cloud-6').first() with mock.patch.object(Service, "serialize"): service = Service(status='published', framework=g6) delete_service_from_index(service) assert search_api_client.delete.called is False
def test_update_service_permission_creates_a_history_record_with_current_data(notify_db_session): user = create_user() assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0 service = Service(name="service_name", email_from="email_from", message_limit=1000, restricted=False, created_by=user) dao_create_service(service, user, service_permissions=[ SMS_TYPE, EMAIL_TYPE, INTERNATIONAL_SMS_TYPE, ]) service.permissions.append(ServicePermission(service_id=service.id, permission='letter')) dao_update_service(service) assert Service.query.count() == 1 assert Service.get_history_model().query.count() == 2 service_from_db = Service.query.first() assert service_from_db.version == 2 _assert_service_permissions(service.permissions, ( SMS_TYPE, EMAIL_TYPE, INTERNATIONAL_SMS_TYPE, LETTER_TYPE, )) permission = [p for p in service.permissions if p.permission == 'sms'][0] service.permissions.remove(permission) dao_update_service(service) assert Service.query.count() == 1 assert Service.get_history_model().query.count() == 3 service_from_db = Service.query.first() assert service_from_db.version == 3 _assert_service_permissions(service.permissions, ( EMAIL_TYPE, INTERNATIONAL_SMS_TYPE, LETTER_TYPE, )) history = Service.get_history_model().query.filter_by(name='service_name').order_by('version').all() assert len(history) == 3 assert history[2].version == 3
def test_live_dos_published_service_is_not_indexed(self, index_object, live_dos_framework): dos = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists').first() with mock.patch.object(Service, "serialize"): service = Service(status='published', framework=dos) index_service(service) assert not index_object.called
def test_cannot_create_two_services_with_same_email_from(notify_db_session): user = create_user() assert Service.query.count() == 0 service1 = Service(name="service_name1", email_from="email_from", message_limit=1000, restricted=False, created_by=user) service2 = Service(name="service_name2", email_from="email_from", message_limit=1000, restricted=False, created_by=user) with pytest.raises(IntegrityError) as excinfo: dao_create_service(service1, user) dao_create_service(service2, user) assert 'duplicate key value violates unique constraint "services_email_from_key"' in str(excinfo.value)
def test_expired_g_cloud_6_published_service_is_not_indexed(self, index_object, expired_g6_framework): g6 = Framework.query.filter(Framework.slug == 'g-cloud-6').first() with mock.patch.object(Service, "serialize"): service = Service(status='published', framework=g6) index_service(service) assert not index_object.called
def test_live_g_cloud_8_enabled_service_is_not_indexed( self, index_object, live_g8_framework): g8 = Framework.query.filter(Framework.slug == 'g-cloud-8').first() with mock.patch.object(Service, "serialize"): service = Service(status='enabled', framework=g8) index_service(service) assert not index_object.called
def test_can_create_two_services_with_same_email_from(notify_db_session): user = create_user() assert Service.query.count() == 0 service1 = Service(name="service_name1", email_from="email_from", message_limit=1000, restricted=False, created_by=user) service2 = Service(name="service_name2", email_from="email_from", message_limit=1000, restricted=False, created_by=user) try: dao_create_service(service1, user) dao_create_service(service2, user) except IntegrityError: pytest.fail("Could not create two services with same email from")
def draft_service(request, app, supplier_framework): with app.app_context(): supplier_id = Supplier.query.filter( Supplier.supplier_id == supplier_framework['supplierId']).first() framework = Framework.query.filter( Framework.slug == supplier_framework['frameworkSlug']).first() lot = Lot.query.filter(Lot.slug == 'digital-specialists').first() fl_query = {'framework_id': framework.id, 'lot_id': lot.id} fl = FrameworkLot(**fl_query) ds = DraftService( framework=framework, lot=lot, service_id="1234567890", supplier=supplier_id, data={}, status='submitted', updated_at=datetime.now(), created_at=datetime.now(), lot_one_service_limit=lot.one_service_limit, ) db.session.add(fl) db.session.add(ds) db.session.commit() def teardown(): with app.app_context(): FrameworkLot.query.filter(*[ getattr(FrameworkLot, k) == v for k, v in fl_query.items() ]).delete(synchronize_session=False) Service.query.filter( Service.service_id == ds.service_id).delete( synchronize_session=False) DraftService.query.filter( DraftService.service_id == ds.service_id).delete( synchronize_session=False) db.session.commit() request.addfinalizer(teardown) with mock.patch('app.models.main.url_for', autospec=lambda i, **values: 'test.url/test'): Service.create_from_draft(ds, 'enabled') return ds.serialize()
def notify_db_session(request): meta = MetaData(bind=db.engine, reflect=True) # Set up dummy org, with a service and a job org = Organisation(id=1234, name="org test") token = Token(id=1234, token="1234", type='admin') service = Service( id=1234, name="service test", created_at=datetime.utcnow(), token=token, active=True, restricted=False, limit=100 ) job = Job(id=1234, name="job test", created_at=datetime.utcnow(), service=service) notification = Notification( id=1234, to="phone-number", message="this is a message", job=job, status="created", method="sms", created_at=datetime.utcnow() ) # Setup a dummy user for tests user = User( id=1234, email_address="*****@*****.**", mobile_number="+449999234234", password=generate_password_hash('valid-password'), active=True, created_at=datetime.utcnow(), updated_at=datetime.utcnow(), password_changed_at=datetime.utcnow(), role='admin' ) service.users.append(user) db.session.add(token) db.session.add(org) db.session.add(service) db.session.add(notification) db.session.add(job) db.session.add(user) db.session.commit() def teardown(): db.session.remove() for tbl in reversed(meta.sorted_tables): db.engine.execute(tbl.delete()) request.addfinalizer(teardown)
def test_deactivating_service_creates_history(archived_service): ServiceHistory = Service.get_history_model() history = ServiceHistory.query.filter_by( id=archived_service.id ).order_by( ServiceHistory.version.desc() ).first() assert history.version == 2 assert history.active is False
def test_deactivating_service_creates_history(deactivated_service): ServiceHistory = Service.get_history_model() history = ServiceHistory.query.filter_by( id=deactivated_service.id ).order_by( ServiceHistory.version.desc() ).first() assert history.version == 2 assert history.active is False
def add_service(): form = ServiceForm() if form.validate_on_submit(): service = Service(name=form.name.data, description=form.description.data) db.session.add(service) db.session.commit() flash('données enregistrées') return redirect(url_for('admin.service')) return render_template('admin/service/add_service.html', form=form)
def test_expired_g_cloud_6_published_service_is_not_indexed( self, search_api_client, expired_g6_framework): with self.app.app_context(): g6 = Framework.query.filter(Framework.slug == 'g-cloud-6').first() with mock.patch.object(Service, "serialize") as serialize_mock: service = Service(status='published', framework=g6) index_service(service) assert not search_api_client.index.called
def test_live_g_cloud_8_enabled_service_is_not_indexed( self, search_api_client, live_g8_framework): with self.app.app_context(): g8 = Framework.query.filter(Framework.slug == 'g-cloud-8').first() with mock.patch.object(Service, "serialize") as serialize_mock: service = Service(status='enabled', framework=g8) index_service(service) assert not search_api_client.index.called
def insert_service(listing, service_id, lot_id, framework_id): db.session.add( Service(service_id=service_id, supplier_code=1, updated_at=now, status='published', created_at=now, lot_id=lot_id, framework_id=framework_id, data=listing))
def post(self): user = User.logged_in_user() if user: payload = request.json or {} comment = payload.get('comment') post_key = payload.get('key') author = Node.get_by_id(user.id) post = Node.get_by_id(post_key) comment_node = Service.create_comment(author, comment, post) return {'status': 'success', 'node': comment_node.__dict__, 'message': 'Successfully posted the comment'} else: return {'status': 'error', 'message': 'Please login first.'}
def test_create_service_creates_a_history_record_with_current_data(sample_user): assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0 service = Service( name="service_name", email_from="email_from", message_limit=1000, restricted=False, created_by=sample_user ) dao_create_service(service, sample_user) assert Service.query.count() == 1 assert Service.get_history_model().query.count() == 1 service_from_db = Service.query.first() service_history = Service.get_history_model().query.first() assert service_from_db.id == service_history.id assert service_from_db.name == service_history.name assert service_from_db.version == 1 assert service_from_db.version == service_history.version assert sample_user.id == service_history.created_by_id assert service_from_db.created_by.id == service_history.created_by_id assert service_from_db.branding == BRANDING_GOVUK assert service_history.branding == BRANDING_GOVUK
def post(self): payload = request.json or {} print '*' * 100 print "JSON", request.json print payload print '*' * 100 name, email, password = payload.get('name'), payload.get('email'), payload.get('password') node = Service.registerProfile(name, email, password) if node: return {'status': 'success', 'node': node.__dict__, "message": "Successfully registered with email: " + email} else: return {'status': 'error', 'node': None, 'message': 'Unable to register at this moment'}
def create_service(): service_from_request = get_json_from_request('service') validation_result, validation_errors = valid_service_submission(service_from_request) if not validation_result: return jsonify( error="Invalid JSON", error_details=validation_errors ), 400 user = User.query.get(service_from_request['userId']) if not user: return jsonify( error="failed to create service - invalid user" ), 400 try: token = Token(token=uuid4(), type='client') db.session.add(token) db.session.flush() service = Service( name=service_from_request['name'], created_at=datetime.utcnow(), token_id=token.id, active=True, restricted=True, limit=current_app.config['MAX_SERVICE_LIMIT'] ) service.users.append(user) db.session.add(service) db.session.commit() return jsonify( service=service.serialize() ), 201 except IntegrityError as e: print(e.orig) db.session.rollback() abort(400, "failed to create service")
def draft_service(request, app, supplier_framework): with app.app_context(): supplier_id = Supplier.query.filter(Supplier.supplier_id == supplier_framework['supplierId']).first() framework = Framework.query.filter(Framework.slug == supplier_framework['frameworkSlug']).first() lot = Lot.query.filter(Lot.slug == 'digital-specialists').first() fl_query = { 'framework_id': framework.id, 'lot_id': lot.id } fl = FrameworkLot(**fl_query) ds = DraftService( framework=framework, lot=lot, service_id="1234567890", supplier=supplier_id, data={}, status='submitted', updated_at=datetime.now(), created_at=datetime.now() ) db.session.add(fl) db.session.add(ds) db.session.commit() def teardown(): with app.app_context(): FrameworkLot.query.filter( *[getattr(FrameworkLot, k) == v for k, v in fl_query.items()] ).delete(synchronize_session=False) Service.query.filter(Service.service_id == ds.service_id).delete(synchronize_session=False) DraftService.query.filter(DraftService.service_id == ds.service_id).delete(synchronize_session=False) db.session.commit() request.addfinalizer(teardown) with mock.patch('app.models.main.url_for', autospec=lambda i, **values: 'test.url/test'): Service.create_from_draft(ds, 'enabled') return ds.serialize()
def test_update_service_creates_a_history_record_with_current_data(sample_user): assert Service.query.count() == 0 assert Service.get_history_model().query.count() == 0 service = Service( name="service_name", email_from="email_from", message_limit=1000, restricted=False, created_by=sample_user ) dao_create_service(service, sample_user) assert Service.query.count() == 1 assert Service.query.first().version == 1 assert Service.get_history_model().query.count() == 1 service.name = "updated_service_name" dao_update_service(service) assert Service.query.count() == 1 assert Service.get_history_model().query.count() == 2 service_from_db = Service.query.first() assert service_from_db.version == 2 assert Service.get_history_model().query.filter_by(name="service_name").one().version == 1 assert Service.get_history_model().query.filter_by(name="updated_service_name").one().version == 2
def test_invalid_service_status(self): service = Service() with assert_raises(ValidationError): service.status = 'invalid'