Update service rest class to handle new fields and updated dao

This commit is contained in:
Martyn Inglis
2016-02-19 15:53:45 +00:00
parent 5bfae689c2
commit 1a136885c3
2 changed files with 397 additions and 378 deletions

View File

@@ -1,93 +1,122 @@
from datetime import datetime from datetime import datetime
from flask import (jsonify, request, abort) from flask import (jsonify, request)
from sqlalchemy.exc import DataError from sqlalchemy.exc import DataError
from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import NoResultFound
from app.dao import DAOException from app.dao import DAOException
from app.dao.users_dao import get_model_users
from app.dao.services_dao import ( from app.dao.services_dao import (
save_model_service, get_model_services, delete_model_service) dao_fetch_service_by_id_and_user,
dao_fetch_service_by_id,
dao_fetch_all_services,
dao_create_service,
dao_update_service,
dao_fetch_all_services_by_user
)
from app.dao.templates_dao import ( from app.dao.templates_dao import (
save_model_template, get_model_templates, delete_model_template) save_model_template,
from app.dao.api_key_dao import (save_model_api_key, get_model_api_keys, get_unsigned_secret) get_model_templates,
delete_model_template
)
from app.dao.api_key_dao import (
save_model_api_key,
get_model_api_keys,
get_unsigned_secret
)
from app.models import ApiKey from app.models import ApiKey
from app.schemas import ( from app.schemas import (
services_schema, service_schema, template_schema, templates_schema, services_schema,
api_keys_schema, service_schema_load_json, template_schema_load_json) service_schema,
templates_schema,
api_keys_schema,
template_schema_load_json,
template_schema
)
from flask import Blueprint from flask import Blueprint
service = Blueprint('service', __name__) service = Blueprint('service', __name__)
from app.errors import register_errors from app.errors import register_errors
register_errors(service) register_errors(service)
@service.route('', methods=['GET'])
def get_services():
user_id = request.args.get('user_id', None)
if user_id:
services = dao_fetch_all_services_by_user(user_id)
else:
services = dao_fetch_all_services()
data, errors = services_schema.dump(services)
return jsonify(data=data)
@service.route('/<service_id>', methods=['GET'])
def get_service_by_id(service_id):
user_id = request.args.get('user_id', None)
if user_id:
fetched = dao_fetch_service_by_id_and_user(service_id, user_id)
else:
fetched = dao_fetch_service_by_id(service_id)
if not fetched:
return jsonify(result="error", message="not found"), 404
data, errors = service_schema.dump(fetched)
return jsonify(data=data)
@service.route('', methods=['POST']) @service.route('', methods=['POST'])
def create_service(): def create_service():
# TODO what exceptions get passed from schema parsing? data = request.get_json()
service, errors = service_schema.load(request.get_json())
if not data.get('user_id', None):
return jsonify(result="error", message={'user_id': ['Missing data for required field.']}), 400
user = get_model_users(data['user_id'])
if not user:
return jsonify(result="error", message={'user_id': ['not found']}), 400
request.get_json().pop('user_id', None)
valid_service, errors = service_schema.load(request.get_json())
if errors: if errors:
return jsonify(result="error", message=errors), 400 return jsonify(result="error", message=errors), 400
# I believe service is already added to the session but just needs a
# db.session.commit dao_create_service(valid_service, user)
try: return jsonify(data=service_schema.dump(valid_service).data), 201
save_model_service(service)
except DAOException as e:
return jsonify(result="error", message=str(e)), 500
return jsonify(data=service_schema.dump(service).data), 201
@service.route('/<service_id>', methods=['PUT', 'DELETE']) @service.route('/<service_id>', methods=['POST'])
def update_service(service_id): def update_service(service_id):
try: fetched_service = dao_fetch_service_by_id(service_id)
service = get_model_services(service_id=service_id) if not fetched_service:
except DataError: return jsonify(result="error", message="not found"), 404
return jsonify(result="error", message="Invalid service id"), 400
except NoResultFound:
return jsonify(result="error", message="Service not found"), 404
if request.method == 'DELETE':
status_code = 202
delete_model_service(service)
else:
status_code = 200
update_dict, errors = service_schema_load_json.load(request.get_json())
if errors:
return jsonify(result="error", message=errors), 400
try:
save_model_service(service, update_dict=update_dict)
except DAOException as e:
return jsonify(result="error", message=str(e)), 500
return jsonify(data=service_schema.dump(service).data), status_code
current_data = dict(service_schema.dump(fetched_service).data.items())
current_data.update(request.get_json())
@service.route('/<service_id>', methods=['GET']) update_dict, errors = service_schema.load(current_data)
@service.route('', methods=['GET']) if errors:
def get_service(service_id=None): return jsonify(result="error", message=errors), 400
user_id = request.args.get('user_id', None) dao_update_service(update_dict)
try: return jsonify(data=service_schema.dump(fetched_service).data), 200
services = get_model_services(service_id=service_id, user_id=user_id)
except DataError:
return jsonify(result="error", message="Invalid service id"), 400
except NoResultFound:
return jsonify(result="error", message="Service not found"), 404
data, errors = services_schema.dump(services) if isinstance(services, list) else service_schema.dump(services)
return jsonify(data=data)
@service.route('/<service_id>/api-key', methods=['POST']) @service.route('/<service_id>/api-key', methods=['POST'])
def renew_api_key(service_id=None): def renew_api_key(service_id=None):
try: fetched_service = dao_fetch_service_by_id(service_id=service_id)
service = get_model_services(service_id=service_id) if not fetched_service:
except DataError:
return jsonify(result="error", message="Invalid service id"), 400
except NoResultFound:
return jsonify(result="error", message="Service not found"), 404 return jsonify(result="error", message="Service not found"), 404
try: try:
# create a new one # create a new one
# TODO: what validation should be done here? # TODO: what validation should be done here?
secret_name = request.get_json()['name'] secret_name = request.get_json()['name']
key = ApiKey(service=service, name=secret_name) key = ApiKey(service=fetched_service, name=secret_name)
save_model_api_key(key) save_model_api_key(key)
except DAOException as e: except DAOException as e:
return jsonify(result='error', message=str(e)), 500 return jsonify(result='error', message=str(e)), 500
@@ -112,7 +141,7 @@ def revoke_api_key(service_id, api_key_id):
@service.route('/<service_id>/api-keys/<int:key_id>', methods=['GET']) @service.route('/<service_id>/api-keys/<int:key_id>', methods=['GET'])
def get_api_keys(service_id, key_id=None): def get_api_keys(service_id, key_id=None):
try: try:
service = get_model_services(service_id=service_id) service = dao_fetch_service_by_id(service_id=service_id)
except DataError: except DataError:
return jsonify(result="error", message="Invalid service id"), 400 return jsonify(result="error", message="Invalid service id"), 400
except NoResultFound: except NoResultFound:
@@ -133,16 +162,13 @@ def get_api_keys(service_id, key_id=None):
@service.route('/<service_id>/template', methods=['POST']) @service.route('/<service_id>/template', methods=['POST'])
def create_template(service_id): def create_template(service_id):
try: fetched_service = dao_fetch_service_by_id(service_id=service_id)
service = get_model_services(service_id=service_id) if not fetched_service:
except DataError:
return jsonify(result="error", message="Invalid service id"), 400
except NoResultFound:
return jsonify(result="error", message="Service not found"), 404 return jsonify(result="error", message="Service not found"), 404
template, errors = template_schema.load(request.get_json()) template, errors = template_schema.load(request.get_json())
if errors: if errors:
return jsonify(result="error", message=errors), 400 return jsonify(result="error", message=errors), 400
template.service = service template.service = fetched_service
# I believe service is already added to the session but just needs a # I believe service is already added to the session but just needs a
# db.session.commit # db.session.commit
save_model_template(template) save_model_template(template)
@@ -151,11 +177,8 @@ def create_template(service_id):
@service.route('/<service_id>/template/<int:template_id>', methods=['PUT', 'DELETE']) @service.route('/<service_id>/template/<int:template_id>', methods=['PUT', 'DELETE'])
def update_template(service_id, template_id): def update_template(service_id, template_id):
try: fetched_service = dao_fetch_service_by_id(service_id=service_id)
service = get_model_services(service_id=service_id) if not fetched_service:
except DataError:
return jsonify(result="error", message="Invalid service id"), 400
except NoResultFound:
return jsonify(result="error", message="Service not found"), 404 return jsonify(result="error", message="Service not found"), 404
try: try:
template = get_model_templates(template_id=template_id) template = get_model_templates(template_id=template_id)

View File

@@ -1,352 +1,348 @@
import json import json
import uuid import uuid
from collections import Set
from flask import url_for from flask import url_for
from app.dao.services_dao import save_model_service
from app.models import (Service, ApiKey, Template) from app.dao.users_dao import save_model_user
from app.models import User, Template, Service
from tests import create_authorization_header from tests import create_authorization_header
from tests.app.conftest import sample_user as create_sample_user
from tests.app.conftest import sample_service as create_sample_service
def test_get_service_list(notify_api, notify_db, notify_db_session, sample_service): def test_get_service_list(notify_api, service_factory):
"""
Tests GET endpoint '/' to retrieve entire service list.
"""
with notify_api.test_request_context(): with notify_api.test_request_context():
with notify_api.test_client() as client: with notify_api.test_client() as client:
auth_header = create_authorization_header(path=url_for('service.get_service'), service_factory.get('one')
method='GET') service_factory.get('two')
response = client.get(url_for('service.get_service'), service_factory.get('three')
headers=[auth_header])
auth_header = create_authorization_header(
path='/service',
method='GET'
)
response = client.get(
'/service',
headers=[auth_header]
)
assert response.status_code == 200 assert response.status_code == 200
json_resp = json.loads(response.get_data(as_text=True)) json_resp = json.loads(response.get_data(as_text=True))
# TODO assert correct json returned assert len(json_resp['data']) == 3
assert len(json_resp['data']) == 1 assert json_resp['data'][0]['name'] == 'one'
assert json_resp['data'][0]['name'] == sample_service.name assert json_resp['data'][1]['name'] == 'two'
assert json_resp['data'][0]['id'] == str(sample_service.id) assert json_resp['data'][2]['name'] == 'three'
def test_get_service(notify_api, notify_db, notify_db_session, sample_service): def test_get_service_list_by_user(notify_api, service_factory, sample_user):
"""
Tests GET endpoint '/<service_id>' to retrieve a single service.
"""
with notify_api.test_request_context(): with notify_api.test_request_context():
with notify_api.test_client() as client: with notify_api.test_client() as client:
auth_header = create_authorization_header(path=url_for('service.get_service', service_id=sample_service.id), service_factory.get('one', sample_user)
method='GET') service_factory.get('two', sample_user)
resp = client.get(url_for('service.get_service', service_factory.get('three', sample_user)
service_id=sample_service.id),
headers=[auth_header]) auth_header = create_authorization_header(
path='/service',
method='GET'
)
response = client.get(
'/service?user_id='.format(sample_user.id),
headers=[auth_header]
)
json_resp = json.loads(response.get_data(as_text=True))
assert response.status_code == 200
assert len(json_resp['data']) == 3
assert json_resp['data'][0]['name'] == 'one'
assert json_resp['data'][1]['name'] == 'two'
assert json_resp['data'][2]['name'] == 'three'
def test_get_service_list_by_user_should_return_empty_list_if_no_services(notify_api, service_factory, sample_user):
with notify_api.test_request_context():
with notify_api.test_client() as client:
new_user = User(
name='Test User',
email_address='new_user@digital.cabinet-office.gov.uk',
password='password',
mobile_number='+447700900986'
)
save_model_user(new_user)
service_factory.get('one', sample_user)
service_factory.get('two', sample_user)
service_factory.get('three', sample_user)
auth_header = create_authorization_header(
path='/service',
method='GET'
)
response = client.get(
'/service?user_id={}'.format(new_user.id),
headers=[auth_header]
)
json_resp = json.loads(response.get_data(as_text=True))
assert response.status_code == 200
assert len(json_resp['data']) == 0
def test_get_service_list_should_return_empty_list_if_no_services(notify_api, notify_db):
with notify_api.test_request_context():
with notify_api.test_client() as client:
auth_header = create_authorization_header(
path='/service',
method='GET'
)
response = client.get(
'/service',
headers=[auth_header]
)
assert response.status_code == 200
json_resp = json.loads(response.get_data(as_text=True))
assert len(json_resp['data']) == 0
def test_get_service_by_id(notify_api, sample_service):
with notify_api.test_request_context():
with notify_api.test_client() as client:
auth_header = create_authorization_header(
path='/service/{}'.format(sample_service.id),
method='GET'
)
resp = client.get(
'/service/{}'.format(sample_service.id),
headers=[auth_header]
)
assert resp.status_code == 200 assert resp.status_code == 200
json_resp = json.loads(resp.get_data(as_text=True)) json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['data']['name'] == sample_service.name assert json_resp['data']['name'] == sample_service.name
assert json_resp['data']['id'] == str(sample_service.id) assert json_resp['data']['id'] == str(sample_service.id)
def test_get_service_for_user(notify_api, notify_db, notify_db_session, sample_service): def test_get_service_by_id_should_404_if_no_service(notify_api, notify_db):
second_user = create_sample_user(notify_db, notify_db_session, 'an@other.gov.uk') with notify_api.test_request_context():
create_sample_service(notify_db, notify_db_session, service_name='Second Service', user=second_user) with notify_api.test_client() as client:
create_sample_service(notify_db, notify_db_session, service_name='Another Service', user=sample_service.users[0]) service_id = str(uuid.uuid4())
auth_header = create_authorization_header(
path='/service/{}'.format(service_id),
method='GET'
)
resp = client.get(
'/service/{}'.format(service_id),
headers=[auth_header]
)
assert resp.status_code == 404
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['result'] == 'error'
assert json_resp['message'] == 'not found'
def test_get_service_by_id_and_user(notify_api, service_factory, sample_user):
with notify_api.test_request_context():
with notify_api.test_client() as client:
service = service_factory.get('new service', sample_user)
auth_header = create_authorization_header(
path='/service/{}'.format(service.id),
method='GET'
)
resp = client.get(
'/service/{}?user_id={}'.format(service.id, sample_user.id),
headers=[auth_header]
)
assert resp.status_code == 200
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['data']['name'] == service.name
assert json_resp['data']['id'] == str(service.id)
def test_get_service_by_id_should_404_if_no_service_for_user(notify_api, sample_user):
with notify_api.test_request_context():
with notify_api.test_client() as client:
service_id = str(uuid.uuid4())
auth_header = create_authorization_header(
path='/service/{}'.format(service_id),
method='GET'
)
resp = client.get(
'/service/{}?user_id={}'.format(service_id, sample_user.id),
headers=[auth_header]
)
assert resp.status_code == 404
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['result'] == 'error'
assert json_resp['message'] == 'not found'
def test_create_service(notify_api, sample_user):
with notify_api.test_request_context():
with notify_api.test_client() as client:
data = {
'email_from': 'service',
'name': 'created service',
'user_id': sample_user.id,
'limit': 1000,
'restricted': False,
'active': False}
auth_header = create_authorization_header(
path='/service',
method='POST',
request_body=json.dumps(data)
)
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(
'/service',
data=json.dumps(data),
headers=headers)
json_resp = json.loads(resp.get_data(as_text=True))
assert resp.status_code == 201
assert json_resp['data']['id']
assert json_resp['data']['name'] == 'created service'
auth_header_fetch = create_authorization_header(
path='/service/{}'.format(json_resp['data']['id']),
method='GET'
)
resp = client.get(
'/service/{}?user_id={}'.format(json_resp['data']['id'], sample_user.id),
headers=[auth_header_fetch]
)
assert resp.status_code == 200
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['data']['name'] == 'created service'
def test_should_not_create_service_with_missing_user_id_field(notify_api):
with notify_api.test_request_context():
with notify_api.test_client() as client:
data = {
'email_from': 'service',
'name': 'created service',
'limit': 1000,
'restricted': False,
'active': False
}
auth_header = create_authorization_header(
path='/service',
method='POST',
request_body=json.dumps(data)
)
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(
'/service',
data=json.dumps(data),
headers=headers)
json_resp = json.loads(resp.get_data(as_text=True))
assert resp.status_code == 400
assert json_resp['result'] == 'error'
assert 'Missing data for required field.' in json_resp['message']['user_id']
def test_should_not_create_service_with_missing_if_user_id_is_not_in_database(notify_api, notify_db):
with notify_api.test_request_context():
with notify_api.test_client() as client:
data = {
'email_from': 'service',
'user_id': 1234,
'name': 'created service',
'limit': 1000,
'restricted': False,
'active': False
}
auth_header = create_authorization_header(
path='/service',
method='POST',
request_body=json.dumps(data)
)
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(
'/service',
data=json.dumps(data),
headers=headers)
json_resp = json.loads(resp.get_data(as_text=True))
assert resp.status_code == 400
assert json_resp['result'] == 'error'
assert 'not found' in json_resp['message']['user_id']
def test_should_not_create_service_with_missing_if_missing_data(notify_api, sample_user):
with notify_api.test_request_context():
with notify_api.test_client() as client:
data = {
'user_id': sample_user.id
}
auth_header = create_authorization_header(
path='/service',
method='POST',
request_body=json.dumps(data)
)
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(
'/service',
data=json.dumps(data),
headers=headers)
json_resp = json.loads(resp.get_data(as_text=True))
assert resp.status_code == 400
assert json_resp['result'] == 'error'
assert 'Missing data for required field.' in json_resp['message']['name']
assert 'Missing data for required field.' in json_resp['message']['active']
assert 'Missing data for required field.' in json_resp['message']['limit']
assert 'Missing data for required field.' in json_resp['message']['restricted']
assert 'Missing data for required field.' in json_resp['message']['email_from']
def test_update_service(notify_api, sample_service):
with notify_api.test_request_context(): with notify_api.test_request_context():
with notify_api.test_client() as client: with notify_api.test_client() as client:
auth_header = create_authorization_header( auth_header = create_authorization_header(
path='/service', path='/service/{}'.format(sample_service.id),
method='GET') method='GET'
resp = client.get('/service?user_id={}'.format(sample_service.users[0].id), )
headers=[auth_header]) resp = client.get(
'/service/{}'.format(sample_service.id),
headers=[auth_header]
)
json_resp = json.loads(resp.get_data(as_text=True))
assert resp.status_code == 200 assert resp.status_code == 200
json_resp = json.loads(resp.get_data(as_text=True)) assert json_resp['data']['name'] == sample_service.name
assert len(json_resp['data']) == 2
print(x for x in json_resp['data'])
assert 'Another Service' in [x.get('name') for x in json_resp['data']]
assert 'Sample service' in [x.get('name') for x in json_resp['data']]
assert 'Second Service' not in [x.get('name') for x in json_resp['data']]
def test_post_service(notify_api, notify_db, notify_db_session, sample_user):
"""
Tests POST endpoint '/' to create a service.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
assert Service.query.count() == 0
data = { data = {
'name': 'created service', 'name': 'updated service name'
'users': [sample_user.id], }
'limit': 1000,
'restricted': False, auth_header = create_authorization_header(
'active': False} path='/service/{}'.format(sample_service.id),
auth_header = create_authorization_header(path=url_for('service.create_service'), method='POST',
method='POST', request_body=json.dumps(data)
request_body=json.dumps(data)) )
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post( resp = client.post(
url_for('service.create_service'), '/service/{}'.format(sample_service.id),
data=json.dumps(data), data=json.dumps(data),
headers=headers) headers=[('Content-Type', 'application/json'), auth_header]
assert resp.status_code == 201 )
service = Service.query.filter_by(name='created service').first() result = json.loads(resp.get_data(as_text=True))
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['data']['name'] == service.name
assert json_resp['data']['limit'] == service.limit
def test_post_service_multiple_users(notify_api, notify_db, notify_db_session, sample_user):
"""
Tests POST endpoint '/' to create a service with multiple users.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
another_user = create_sample_user(
notify_db,
notify_db_session,
"new@digital.cabinet-office.gov.uk")
assert Service.query.count() == 0
data = {
'name': 'created service',
'users': [sample_user.id, another_user.id],
'limit': 1000,
'restricted': False,
'active': False}
auth_header = create_authorization_header(path=url_for('service.create_service'),
method='POST',
request_body=json.dumps(data))
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(
url_for('service.create_service'),
data=json.dumps(data),
headers=headers)
assert resp.status_code == 201
service = Service.query.filter_by(name='created service').first()
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['data']['name'] == service.name
assert json_resp['data']['limit'] == service.limit
assert len(service.users) == 2
def test_post_service_without_users_attribute(notify_api, notify_db, notify_db_session):
"""
Tests POST endpoint '/' to create a service without 'users' attribute.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
assert Service.query.count() == 0
data = {
'name': 'created service',
'limit': 1000,
'restricted': False,
'active': False}
auth_header = create_authorization_header(path=url_for('service.create_service'),
method='POST',
request_body=json.dumps(data))
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(
url_for('service.create_service'),
data=json.dumps(data),
headers=headers)
assert resp.status_code == 500
assert Service.query.count() == 0
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['message'] == '{"users": ["Missing data for required attribute"]}'
def test_put_service(notify_api, notify_db, notify_db_session, sample_service):
"""
Tests PUT endpoint '/<service_id>' to edit a service.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
assert Service.query.count() == 1
new_name = 'updated service'
data = {
'name': new_name,
'users': [sample_service.users[0].id],
'limit': 1000,
'restricted': False,
'active': False}
auth_header = create_authorization_header(path=url_for('service.update_service',
service_id=sample_service.id),
method='PUT',
request_body=json.dumps(data))
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.put(
url_for('service.update_service', service_id=sample_service.id),
data=json.dumps(data),
headers=headers)
assert Service.query.count() == 1
assert resp.status_code == 200 assert resp.status_code == 200
updated_service = Service.query.get(sample_service.id) assert result['data']['name'] == 'updated service name'
json_resp = json.loads(resp.get_data(as_text=True))
assert json_resp['data']['name'] == updated_service.name
assert json_resp['data']['limit'] == updated_service.limit
assert updated_service.name == new_name
def test_put_service_not_exists(notify_api, notify_db, notify_db_session, sample_service): def test_update_service_should_404_if_id_is_invalid(notify_api, notify_db):
"""
Tests PUT endpoint '/<service_id>' service doesn't exist.
"""
with notify_api.test_request_context(): with notify_api.test_request_context():
with notify_api.test_client() as client: with notify_api.test_client() as client:
sample_user = sample_service.users[0]
new_name = 'updated service'
data = { data = {
'name': new_name, 'name': 'updated service name'
'users': [sample_user.id], }
'limit': 1000,
'restricted': False,
'active': False}
missing_service_id = uuid.uuid4() missing_service_id = uuid.uuid4()
auth_header = create_authorization_header(path=url_for('service.update_service',
service_id=missing_service_id), auth_header = create_authorization_header(
method='PUT', path='/service/{}'.format(missing_service_id),
request_body=json.dumps(data)) method='POST',
resp = client.put( request_body=json.dumps(data)
url_for('service.update_service', service_id=missing_service_id), )
resp = client.post(
'/service/{}'.format(missing_service_id),
data=json.dumps(data), data=json.dumps(data),
headers=[('Content-Type', 'application/json'), auth_header]) headers=[('Content-Type', 'application/json'), auth_header]
)
assert resp.status_code == 404 assert resp.status_code == 404
assert Service.query.first().name == sample_service.name
assert Service.query.first().name != new_name
def test_put_service_add_user(notify_api, notify_db, notify_db_session, sample_service):
"""
Tests PUT endpoint '/<service_id>' add user to the service.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
assert Service.query.count() == 1
another_user = create_sample_user(
notify_db,
notify_db_session,
"new@digital.cabinet-office.gov.uk")
new_name = 'updated service'
sample_user = sample_service.users[0]
data = {
'name': new_name,
'users': [sample_user.id, another_user.id],
'limit': 1000,
'restricted': False,
'active': False}
auth_header = create_authorization_header(path=url_for('service.update_service',
service_id=sample_service.id),
method='PUT',
request_body=json.dumps(data))
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.put(
url_for('service.update_service', service_id=sample_service.id),
data=json.dumps(data),
headers=headers)
assert Service.query.count() == 1
assert resp.status_code == 200
updated_service = Service.query.get(sample_service.id)
json_resp = json.loads(resp.get_data(as_text=True))
assert len(json_resp['data']['users']) == 2
assert sample_user.id in json_resp['data']['users']
assert another_user.id in json_resp['data']['users']
assert len(updated_service.users) == 2
assert set(updated_service.users) == set([sample_user, another_user])
def test_put_service_remove_user(notify_api, notify_db, notify_db_session, sample_service):
"""
Tests PUT endpoint '/<service_id>' add user to the service.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
sample_user = sample_service.users[0]
another_user = create_sample_user(
notify_db,
notify_db_session,
"new@digital.cabinet-office.gov.uk")
data = {
'name': sample_service.name,
'users': [sample_user, another_user],
'limit': sample_service.limit,
'restricted': sample_service.restricted,
'active': sample_service.active}
save_model_service(sample_service, update_dict=data)
assert Service.query.count() == 1
data['users'] = [another_user.id]
auth_header = create_authorization_header(path=url_for('service.update_service',
service_id=sample_service.id),
method='PUT',
request_body=json.dumps(data))
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.put(
url_for('service.update_service', service_id=sample_service.id),
data=json.dumps(data),
headers=headers)
assert Service.query.count() == 1
assert resp.status_code == 200
updated_service = Service.query.get(sample_service.id)
json_resp = json.loads(resp.get_data(as_text=True))
assert len(json_resp['data']['users']) == 1
assert sample_user.id not in json_resp['data']['users']
assert another_user.id in json_resp['data']['users']
assert sample_user not in updated_service.users
assert another_user in updated_service.users
def test_delete_service(notify_api, notify_db, notify_db_session, sample_service):
"""
Tests DELETE endpoint '/<service_id>' delete service.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
auth_header = create_authorization_header(path=url_for('service.update_service',
service_id=sample_service.id),
method='DELETE')
resp = client.delete(
url_for('service.update_service', service_id=sample_service.id),
headers=[('Content-Type', 'application/json'), auth_header])
assert resp.status_code == 202
json_resp = json.loads(resp.get_data(as_text=True))
json_resp['data']['name'] == sample_service.name
assert Service.query.count() == 0
def test_delete_service_not_exists(notify_api, notify_db, notify_db_session, sample_service):
"""
Tests DELETE endpoint '/<service_id>' delete service doesn't exist.
"""
with notify_api.test_request_context():
with notify_api.test_client() as client:
assert Service.query.count() == 1
missing_service_id = uuid.uuid4()
auth_header = create_authorization_header(path=url_for('service.update_service',
service_id=missing_service_id),
method='DELETE')
resp = client.delete(
url_for('service.update_service', service_id=missing_service_id),
headers=[('Content-Type', 'application/json'), auth_header])
assert resp.status_code == 404
assert Service.query.count() == 1
def test_create_service_should_create_new_service_for_user(notify_api, notify_db, notify_db_session, sample_user):
with notify_api.test_request_context():
with notify_api.test_client() as client:
assert Service.query.count() == 0
data = {
'name': 'created service',
'users': [sample_user.id],
'limit': 1000,
'restricted': False,
'active': False}
auth_header = create_authorization_header(path=url_for('service.create_service'),
method='POST',
request_body=json.dumps(data))
headers = [('Content-Type', 'application/json'), auth_header]
resp = client.post(url_for('service.create_service'),
data=json.dumps(data),
headers=headers)
assert resp.status_code == 201
assert Service.query.count() == 1
def test_create_template(notify_api, notify_db, notify_db_session, sample_service): def test_create_template(notify_api, notify_db, notify_db_session, sample_service):