From 9bb95a53ec9de328b11c8ad9e2e8a432ccae9073 Mon Sep 17 00:00:00 2001 From: Martyn Inglis Date: Mon, 22 Feb 2016 12:55:18 +0000 Subject: [PATCH] Updates to template endpoints: - moved into templates rest class - updated dao - removed delete methods - constraint on subject line --- app/__init__.py | 2 +- app/service/rest.py | 75 +-- app/template/rest.py | 98 +++- migrations/versions/0020_email_has_subject.py | 26 ++ tests/app/dao/test_templates_dao.py | 33 ++ tests/app/service/test_rest.py | 261 +---------- tests/app/template/test_rest.py | 428 ++++++++++++++++-- 7 files changed, 540 insertions(+), 383 deletions(-) create mode 100644 migrations/versions/0020_email_has_subject.py diff --git a/app/__init__.py b/app/__init__.py index be92bfe37..9b415aae3 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -48,7 +48,7 @@ def create_app(): application.register_blueprint(service_blueprint, url_prefix='/service') application.register_blueprint(user_blueprint, url_prefix='/user') - application.register_blueprint(template_blueprint, url_prefix="/template") + application.register_blueprint(template_blueprint) application.register_blueprint(status_blueprint, url_prefix='/status') application.register_blueprint(notifications_blueprint, url_prefix='/notifications') application.register_blueprint(job_blueprint) diff --git a/app/service/rest.py b/app/service/rest.py index d6cc3cadf..f12989543 100644 --- a/app/service/rest.py +++ b/app/service/rest.py @@ -1,7 +1,10 @@ import re from datetime import datetime -from flask import (jsonify, request) +from flask import ( + jsonify, + request +) from sqlalchemy.exc import DataError from sqlalchemy.orm.exc import NoResultFound from app.dao import DAOException @@ -15,11 +18,7 @@ from app.dao.services_dao import ( dao_update_service, dao_fetch_all_services_by_user ) -from app.dao.templates_dao import ( - save_model_template, - get_model_templates, - delete_model_template -) + from app.dao.api_key_dao import ( save_model_api_key, get_model_api_keys, @@ -29,10 +28,7 @@ from app.models import ApiKey from app.schemas import ( services_schema, service_schema, - templates_schema, - api_keys_schema, - template_schema_load_json, - template_schema + api_keys_schema ) from flask import Blueprint @@ -166,62 +162,3 @@ def get_api_keys(service_id, key_id=None): return jsonify(result="error", message="API key not found"), 404 return jsonify(apiKeys=api_keys_schema.dump(api_keys).data), 200 - - -@service.route('//template', methods=['POST']) -def create_template(service_id): - fetched_service = dao_fetch_service_by_id(service_id=service_id) - if not fetched_service: - return jsonify(result="error", message="Service not found"), 404 - template, errors = template_schema.load(request.get_json()) - if errors: - return jsonify(result="error", message=errors), 400 - template.service = fetched_service - # I believe service is already added to the session but just needs a - # db.session.commit - save_model_template(template) - return jsonify(data=template_schema.dump(template).data), 201 - - -@service.route('//template/', methods=['PUT', 'DELETE']) -def update_template(service_id, template_id): - fetched_service = dao_fetch_service_by_id(service_id=service_id) - if not fetched_service: - return jsonify(result="error", message="Service not found"), 404 - try: - template = get_model_templates(template_id=template_id) - except DataError: - return jsonify(result="error", message="Invalid template id"), 400 - except NoResultFound: - return jsonify(result="error", message="Template not found"), 404 - if request.method == 'DELETE': - status_code = 202 - delete_model_template(template) - else: - status_code = 200 - update_dict, errors = template_schema_load_json.load(request.get_json()) - if errors: - return jsonify(result="error", message=errors), 400 - try: - save_model_template(template, update_dict=update_dict) - except DAOException as e: - return jsonify(result="error", message=str(e)), 500 - return jsonify(data=template_schema.dump(template).data), status_code - - -@service.route('//template/', methods=['GET']) -@service.route('//template', methods=['GET']) -def get_service_template(service_id, template_id=None): - try: - templates = get_model_templates(service_id=service_id, template_id=template_id) - except DataError: - return jsonify(result="error", message="Invalid template id"), 400 - except NoResultFound: - return jsonify(result="error", message="Template not found"), 404 - if isinstance(templates, list): - data, errors = templates_schema.dump(templates) - else: - data, errors = template_schema.dump(templates) - if errors: - return jsonify(result="error", message=str(errors)) - return jsonify(data=data) diff --git a/app/template/rest.py b/app/template/rest.py index 89e728774..ebc61e572 100644 --- a/app/template/rest.py +++ b/app/template/rest.py @@ -1,36 +1,84 @@ from flask import ( Blueprint, - jsonify + jsonify, + request, + current_app +) +from sqlalchemy.exc import IntegrityError + +from app.dao.templates_dao import ( + dao_update_template, + dao_create_template, + dao_get_template_by_id_and_service_id, + dao_get_all_templates_for_service +) +from app.dao.services_dao import ( + dao_fetch_service_by_id +) +from app.schemas import ( + template_schema, + templates_schema, ) -from sqlalchemy.exc import DataError -from sqlalchemy.orm.exc import NoResultFound - -from app.dao.templates_dao import get_model_templates -from app.schemas import (template_schema, templates_schema) - -template = Blueprint('template', __name__) +template = Blueprint('template', __name__, url_prefix='/service//template') from app.errors import register_errors + register_errors(template) -# I am going to keep these for admin like operations -# Permissions should restrict who can access this endpoint -# TODO auth to be added. -@template.route('/', methods=['GET']) -@template.route('', methods=['GET']) -def get_template(template_id=None): - try: - templates = get_model_templates(template_id=template_id) - except DataError: - return jsonify(result="error", message="Invalid template id"), 400 - except NoResultFound: - return jsonify(result="error", message="Template not found"), 404 - if isinstance(templates, list): - data, errors = templates_schema.dump(templates) - else: - data, errors = template_schema.dump(templates) +@template.route('', methods=['POST']) +def create_template(service_id): + fetched_service = dao_fetch_service_by_id(service_id=service_id) + if not fetched_service: + return jsonify(result="error", message="Service not found"), 404 + + new_template, errors = template_schema.load(request.get_json()) if errors: - return jsonify(result="error", message=str(errors)) + return jsonify(result="error", message=errors), 400 + new_template.service = fetched_service + try: + dao_create_template(new_template) + except IntegrityError as ex: + current_app.logger.debug(ex) + message = "Failed to create template" + if "templates_subject_key" in str(ex): + message = 'Duplicate template subject' + return jsonify(result="error", message=message), 400 + return jsonify(result="error", message=message), 500 + + return jsonify(data=template_schema.dump(new_template).data), 201 + + +@template.route('/', methods=['POST']) +def update_template(service_id, template_id): + fetched_template = dao_get_template_by_id_and_service_id(template_id=template_id, service_id=service_id) + if not fetched_template: + return jsonify(result="error", message="Template not found"), 404 + + current_data = dict(template_schema.dump(fetched_template).data.items()) + current_data.update(request.get_json()) + + update_dict, errors = template_schema.load(current_data) + if errors: + return jsonify(result="error", message=errors), 400 + + dao_update_template(update_dict) + return jsonify(data=template_schema.dump(update_dict).data), 200 + + +@template.route('', methods=['GET']) +def get_all_templates_for_service(service_id): + templates = dao_get_all_templates_for_service(service_id=service_id) + data, errors = templates_schema.dump(templates) return jsonify(data=data) + + +@template.route('/', methods=['GET']) +def get_template_by_id_and_service_id(service_id, template_id): + fetched_template = dao_get_template_by_id_and_service_id(template_id=template_id, service_id=service_id) + if fetched_template: + data, errors = template_schema.dump(fetched_template) + return jsonify(data=data) + else: + return jsonify(result="error", message="Template not found"), 404 diff --git a/migrations/versions/0020_email_has_subject.py b/migrations/versions/0020_email_has_subject.py new file mode 100644 index 000000000..2290b83bf --- /dev/null +++ b/migrations/versions/0020_email_has_subject.py @@ -0,0 +1,26 @@ +"""empty message + +Revision ID: 0020_email_has_subject +Revises: 0019_unique_servicename +Create Date: 2016-02-18 11:45:29.102891 + +""" + +# revision identifiers, used by Alembic. +revision = '0020_email_has_subject' +down_revision = '0019_unique_servicename' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.create_check_constraint( + "ch_email_template_has_subject", + "templates", + "((template_type='email' and subject is not null) or (template_type!='email' and subject is null))" + ) + + +def downgrade(): + op.drop_constraint('ch_email_template_has_subject', 'templates', type_='check') diff --git a/tests/app/dao/test_templates_dao.py b/tests/app/dao/test_templates_dao.py index 14a9faffc..7fabefdea 100644 --- a/tests/app/dao/test_templates_dao.py +++ b/tests/app/dao/test_templates_dao.py @@ -1,3 +1,5 @@ +from sqlalchemy.orm.exc import NoResultFound +from sqlalchemy.exc import IntegrityError from app.dao.templates_dao import ( dao_create_template, dao_get_template_by_id_and_service_id, @@ -6,6 +8,7 @@ from app.dao.templates_dao import ( ) from tests.app.conftest import sample_template as create_sample_template from app.models import Template +import pytest def test_create_template(sample_service): @@ -23,6 +26,36 @@ def test_create_template(sample_service): assert dao_get_all_templates_for_service(sample_service.id)[0].name == 'Sample Template' +def test_create_email_template(sample_service): + data = { + 'name': 'Sample Template', + 'template_type': "email", + 'subject': "subject", + 'content': "Template content", + 'service': sample_service + } + template = Template(**data) + dao_create_template(template) + + assert Template.query.count() == 1 + assert len(dao_get_all_templates_for_service(sample_service.id)) == 1 + assert dao_get_all_templates_for_service(sample_service.id)[0].name == 'Sample Template' + + +def test_create_email_template_fails_if_no_subject(sample_service): + data = { + 'name': 'Sample Template', + 'template_type': "email", + 'content': "Template content", + 'service': sample_service + } + template = Template(**data) + + with pytest.raises(IntegrityError) as e: + dao_create_template(template) + assert 'new row for relation "templates" violates check constraint "ch_email_template_has_subject"' in str(e.value) + + def test_update_template(sample_service): data = { 'name': 'Sample Template', diff --git a/tests/app/service/test_rest.py b/tests/app/service/test_rest.py index 49298ebbd..324b77d2a 100644 --- a/tests/app/service/test_rest.py +++ b/tests/app/service/test_rest.py @@ -1,9 +1,8 @@ import json import uuid -from flask import url_for from app.dao.users_dao import save_model_user -from app.models import User, Template, Service +from app.models import User from tests import create_authorization_header @@ -342,261 +341,3 @@ def test_update_service_should_404_if_id_is_invalid(notify_api, notify_db): headers=[('Content-Type', 'application/json'), auth_header] ) assert resp.status_code == 404 - - -def test_create_template(notify_api, notify_db, notify_db_session, sample_service): - """ - Tests POST endpoint '//template' a template can be created - from a service. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - assert Template.query.count() == 0 - template_name = "template name" - template_type = "sms" - template_content = "This is a template" - data = { - 'name': template_name, - 'template_type': template_type, - 'content': template_content, - 'service': str(sample_service.id) - } - auth_header = create_authorization_header(path=url_for('service.create_template', - service_id=sample_service.id), - method='POST', - request_body=json.dumps(data)) - resp = client.post( - url_for('service.create_template', service_id=sample_service.id), - data=json.dumps(data), - headers=[('Content-Type', 'application/json'), auth_header]) - assert resp.status_code == 201 - assert Template.query.count() == 1 - json_resp = json.loads(resp.get_data(as_text=True)) - assert json_resp['data']['name'] == template_name - assert json_resp['data']['template_type'] == template_type - assert json_resp['data']['content'] == template_content - - -def test_create_template_service_not_exists(notify_api, notify_db, notify_db_session, sample_service): - """ - Tests POST endpoint '//template' a template can be created - from a service. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - assert Template.query.count() == 0 - template_name = "template name" - template_type = "sms" - template_content = "This is a template" - data = { - 'name': template_name, - 'template_type': template_type, - 'content': template_content, - 'service': str(sample_service.id) - } - missing_service_id = uuid.uuid4() - auth_header = create_authorization_header(path=url_for('service.create_template', - service_id=missing_service_id), - method='POST', - request_body=json.dumps(data)) - resp = client.post( - url_for('service.create_template', service_id=missing_service_id), - data=json.dumps(data), - headers=[('Content-Type', 'application/json'), auth_header]) - assert resp.status_code == 404 - assert Template.query.count() == 0 - json_resp = json.loads(resp.get_data(as_text=True)) - assert "Service not found" in json_resp['message'] - - -def test_update_template(notify_api, notify_db, notify_db_session, sample_template): - """ - Tests PUT endpoint '//template/' a template can be - updated. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - assert Template.query.count() == 1 - sample_service = Service.query.first() - old_name = sample_template.name - template_name = "new name" - template_type = "sms" - template_content = "content has been changed" - data = { - 'name': template_name, - 'template_type': template_type, - 'content': template_content, - 'service': str(sample_service.id) - } - auth_header = create_authorization_header(path=url_for('service.update_template', - service_id=sample_service.id, - template_id=sample_template.id), - method='PUT', - request_body=json.dumps(data)) - resp = client.put( - url_for('service.update_template', - service_id=sample_service.id, - template_id=sample_template.id), - data=json.dumps(data), - headers=[('Content-Type', 'application/json'), auth_header]) - assert resp.status_code == 200 - assert Template.query.count() == 1 - json_resp = json.loads(resp.get_data(as_text=True)) - assert json_resp['data']['name'] == template_name - assert json_resp['data']['template_type'] == template_type - assert json_resp['data']['content'] == template_content - assert old_name != template_name - - -def test_update_template_service_not_exists(notify_api, notify_db, notify_db_session, - sample_template): - """ - Tests PUT endpoint '//template/' a 404 if service - doesn't exist. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - assert Template.query.count() == 1 - template_name = "new name" - template_type = "sms" - template_content = "content has been changed" - data = { - 'name': template_name, - 'template_type': template_type, - 'content': template_content, - 'service': str(sample_template.service_id) - } - missing_service_id = uuid.uuid4() - auth_header = create_authorization_header(path=url_for('service.update_template', - service_id=missing_service_id, - template_id=sample_template.id), - method='PUT', - request_body=json.dumps(data)) - resp = client.put( - url_for('service.update_template', - service_id=missing_service_id, - template_id=sample_template.id), - data=json.dumps(data), - headers=[('Content-Type', 'application/json'), auth_header]) - assert resp.status_code == 404 - json_resp = json.loads(resp.get_data(as_text=True)) - assert "Service not found" in json_resp['message'] - assert template_name != sample_template.name - - -def test_update_template_template_not_exists(notify_api, notify_db, notify_db_session, - sample_template): - """ - Tests PUT endpoint '//template/' a 404 if template - doesn't exist. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - assert Template.query.count() == 1 - sample_service = Service.query.first() - template_name = "new name" - template_type = "sms" - template_content = "content has been changed" - data = { - 'name': template_name, - 'template_type': template_type, - 'content': template_content, - 'service': str(sample_service.id) - } - auth_header = create_authorization_header(path=url_for('service.update_template', - service_id=sample_service.id, - template_id="123"), - method='PUT', - request_body=json.dumps(data)) - resp = client.put( - url_for('service.update_template', - service_id=sample_service.id, - template_id="123"), - data=json.dumps(data), - headers=[('Content-Type', 'application/json'), auth_header]) - assert resp.status_code == 404 - json_resp = json.loads(resp.get_data(as_text=True)) - assert "Template not found" in json_resp['message'] - assert template_name != sample_template.name - - -def test_create_template_unicode_content(notify_api, notify_db, notify_db_session, sample_service): - """ - Tests POST endpoint '//template/' a template is - created and the content encoding is respected after saving and loading - from the db. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - assert Template.query.count() == 0 - template_name = "template name" - template_type = "sms" - template_content = 'Россия' - data = { - 'name': template_name, - 'template_type': template_type, - 'content': template_content, - 'service': str(sample_service.id) - } - auth_header = create_authorization_header(path=url_for('service.create_template', - service_id=sample_service.id), - method='POST', - request_body=json.dumps(data)) - resp = client.post( - url_for('service.create_template', service_id=sample_service.id), - data=json.dumps(data), - headers=[('Content-Type', 'application/json'), auth_header]) - assert resp.status_code == 201 - assert Template.query.count() == 1 - json_resp = json.loads(resp.get_data(as_text=True)) - assert json_resp['data']['name'] == template_name - assert json_resp['data']['template_type'] == template_type - assert json_resp['data']['content'] == template_content - - -def test_get_template_list(notify_api, notify_db, notify_db_session, sample_template): - """ - Tests GET endpoint '/' to retrieve entire template list. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - auth_header = create_authorization_header( - service_id=sample_template.service_id, - path=url_for( - 'service.get_service_template', - service_id=sample_template.service_id), - method='GET') - response = client.get( - url_for( - 'service.get_service_template', - service_id=sample_template.service_id), - headers=[auth_header]) - assert response.status_code == 200 - json_resp = json.loads(response.get_data(as_text=True)) - assert len(json_resp['data']) == 1 - assert json_resp['data'][0]['name'] == sample_template.name - assert json_resp['data'][0]['id'] == sample_template.id - - -def test_get_template(notify_api, notify_db, notify_db_session, sample_template): - """ - Tests GET endpoint '/' to retrieve a single template. - """ - with notify_api.test_request_context(): - with notify_api.test_client() as client: - auth_header = create_authorization_header( - service_id=sample_template.service_id, - path=url_for( - 'service.get_service_template', - template_id=sample_template.id, - service_id=sample_template.service_id), - method='GET') - resp = client.get(url_for( - 'service.get_service_template', - template_id=sample_template.id, - service_id=sample_template.service_id), - headers=[auth_header]) - assert resp.status_code == 200 - json_resp = json.loads(resp.get_data(as_text=True)) - assert json_resp['data']['name'] == sample_template.name - assert json_resp['data']['id'] == sample_template.id diff --git a/tests/app/template/test_rest.py b/tests/app/template/test_rest.py index 7f3330b95..fca1bc272 100644 --- a/tests/app/template/test_rest.py +++ b/tests/app/template/test_rest.py @@ -1,41 +1,413 @@ import json -from flask import url_for +import uuid from tests import create_authorization_header -def test_get_template_list(notify_api, notify_db, notify_db_session, sample_template): - """ - Tests GET endpoint '/' to retrieve entire template list. - """ +def test_should_create_a_new_sms_template_for_a_service(notify_api, sample_service): with notify_api.test_request_context(): with notify_api.test_client() as client: - auth_header = create_authorization_header(service_id=sample_template.service_id, - path=url_for('template.get_template'), - method='GET') - response = client.get(url_for('template.get_template'), - headers=[auth_header]) + data = { + 'name': 'my template', + 'template_type': 'sms', + 'content': 'template content', + 'service': str(sample_service.id) + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + assert response.status_code == 201 + json_resp = json.loads(response.get_data(as_text=True)) + assert json_resp['data']['name'] == 'my template' + assert json_resp['data']['template_type'] == 'sms' + assert json_resp['data']['content'] == 'template content' + assert json_resp['data']['service'] == str(sample_service.id) + assert json_resp['data']['id'] + assert not json_resp['data']['subject'] + + +def test_should_create_a_new_email_template_for_a_service(notify_api, sample_service): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + data = { + 'name': 'my template', + 'template_type': 'email', + 'subject': 'subject', + 'content': 'template content', + 'service': str(sample_service.id) + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + assert response.status_code == 201 + json_resp = json.loads(response.get_data(as_text=True)) + assert json_resp['data']['name'] == 'my template' + assert json_resp['data']['template_type'] == 'email' + assert json_resp['data']['content'] == 'template content' + assert json_resp['data']['service'] == str(sample_service.id) + assert json_resp['data']['subject'] == 'subject' + assert json_resp['data']['id'] + + +def test_should_be_error_if_service_does_not_exist_on_create(notify_api): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + bad_id = str(uuid.uuid4()) + data = { + 'name': 'my template', + 'template_type': 'sms', + 'content': 'template content', + 'service': bad_id + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(bad_id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template'.format(bad_id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + json_resp = json.loads(response.get_data(as_text=True)) + assert response.status_code == 404 + assert json_resp['result'] == 'error' + assert json_resp['message'] == 'Service not found' + + +def test_should_be_error_if_service_does_not_exist_on_update(notify_api): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + bad_id = str(uuid.uuid4()) + data = { + 'name': 'my template' + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template/123'.format(bad_id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template/123'.format(bad_id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + json_resp = json.loads(response.get_data(as_text=True)) + assert response.status_code == 404 + assert json_resp['result'] == 'error' + assert json_resp['message'] == 'Template not found' + + +def test_must_have_a_subject_on_an_email_template(notify_api, sample_service): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + data = { + 'name': 'my template', + 'template_type': 'email', + 'content': 'template content', + 'service': str(sample_service.id) + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + json_resp = json.loads(response.get_data(as_text=True)) + assert response.status_code == 500 + assert json_resp['result'] == 'error' + assert json_resp['message'] == 'Failed to create template' + + +def test_must_have_a_uniqe_subject_on_an_email_template(notify_api, sample_service): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + data = { + 'name': 'my template', + 'template_type': 'email', + 'subject': 'subject', + 'content': 'template content', + 'service': str(sample_service.id) + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + assert response.status_code == 201 + + data = { + 'name': 'my template', + 'template_type': 'email', + 'subject': 'subject', + 'content': 'template content', + 'service': str(sample_service.id) + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data + ) + + response = client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + assert response.status_code == 400 + json_resp = json.loads(response.get_data(as_text=True)) + assert json_resp['result'] == 'error' + assert json_resp['message'] == 'Duplicate template subject' + + +def test_should_be_able_to_update_a_template(notify_api, sample_service): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + data = { + 'name': 'my template', + 'template_type': 'email', + 'subject': 'subject', + 'content': 'template content', + 'service': str(sample_service.id) + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data + ) + + create_response = client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + assert create_response.status_code == 201 + json_resp = json.loads(create_response.get_data(as_text=True)) + assert json_resp['data']['name'] == 'my template' + data = { + 'name': 'my template has a new name' + } + data = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template/{}'.format(sample_service.id, json_resp['data']['id']), + method='POST', + request_body=data + ) + + update_response = client.post( + '/service/{}/template/{}'.format(sample_service.id, json_resp['data']['id']), + headers=[('Content-Type', 'application/json'), auth_header], + data=data + ) + + assert update_response.status_code == 200 + update_json_resp = json.loads(update_response.get_data(as_text=True)) + assert update_json_resp['data']['name'] == 'my template has a new name' + + +def test_should_be_able_to_get_all_templates_for_a_service(notify_api, sample_service): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + data = { + 'name': 'my template 1', + 'template_type': 'email', + 'subject': 'subject 1', + 'content': 'template content', + 'service': str(sample_service.id) + } + data_1 = json.dumps(data) + data = { + 'name': 'my template 2', + 'template_type': 'email', + 'subject': 'subject 2', + 'content': 'template content', + 'service': str(sample_service.id) + } + data_2 = json.dumps(data) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data_1 + ) + client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data_1 + ) + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='POST', + request_body=data_2 + ) + + client.post( + '/service/{}/template'.format(sample_service.id), + headers=[('Content-Type', 'application/json'), auth_header], + data=data_2 + ) + + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='GET' + ) + + response = client.get( + '/service/{}/template'.format(sample_service.id), + headers=[auth_header] + ) + + assert response.status_code == 200 + update_json_resp = json.loads(response.get_data(as_text=True)) + assert update_json_resp['data'][0]['name'] == 'my template 1' + assert update_json_resp['data'][1]['name'] == 'my template 2' + + +def test_should_get_only_templates_for_that_servcie(notify_api, service_factory): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + + service_1 = service_factory.get('service 1') + service_2 = service_factory.get('service 2') + + auth_header_1 = create_authorization_header( + path='/service/{}/template'.format(service_1.id), + method='GET' + ) + + response_1 = client.get( + '/service/{}/template'.format(service_1.id), + headers=[auth_header_1] + ) + + auth_header_2 = create_authorization_header( + path='/service/{}/template'.format(service_2.id), + method='GET' + ) + + response_2 = client.get( + '/service/{}/template'.format(service_2.id), + headers=[auth_header_2] + ) + + assert response_1.status_code == 200 + assert response_2.status_code == 200 + + json_resp_1 = json.loads(response_1.get_data(as_text=True)) + json_resp_2 = json.loads(response_2.get_data(as_text=True)) + + assert len(json_resp_1['data']) == 1 + assert len(json_resp_2['data']) == 1 + + data = { + 'name': 'my template 2', + 'template_type': 'email', + 'subject': 'subject 2', + 'content': 'template content', + 'service': str(service_1.id) + } + data = json.dumps(data) + create_auth_header = create_authorization_header( + path='/service/{}/template'.format(service_1.id), + method='POST', + request_body=data + ) + client.post( + '/service/{}/template'.format(service_1.id), + headers=[('Content-Type', 'application/json'), create_auth_header], + data=data + ) + + response_3 = client.get( + '/service/{}/template'.format(service_1.id), + headers=[auth_header_1] + ) + + response_4 = client.get( + '/service/{}/template'.format(service_2.id), + headers=[auth_header_2] + ) + + assert response_3.status_code == 200 + assert response_4.status_code == 200 + + json_resp_3 = json.loads(response_3.get_data(as_text=True)) + json_resp_4 = json.loads(response_4.get_data(as_text=True)) + + assert len(json_resp_3['data']) == 2 + assert len(json_resp_4['data']) == 1 + + +def test_should_return_empty_array_if_no_templates_for_service(notify_api, sample_service): + with notify_api.test_request_context(): + with notify_api.test_client() as client: + + auth_header = create_authorization_header( + path='/service/{}/template'.format(sample_service.id), + method='GET' + ) + + response = client.get( + '/service/{}/template'.format(sample_service.id), + headers=[auth_header] + ) + assert response.status_code == 200 json_resp = json.loads(response.get_data(as_text=True)) - assert len(json_resp['data']) == 1 - assert json_resp['data'][0]['name'] == sample_template.name - assert json_resp['data'][0]['id'] == sample_template.id + assert len(json_resp['data']) == 0 -def test_get_template(notify_api, notify_db, notify_db_session, sample_template): - """ - Tests GET endpoint '/' to retrieve a single template. - """ +def test_should_return_404_if_no_templates_for_service_with_id(notify_api, sample_service): with notify_api.test_request_context(): with notify_api.test_client() as client: - auth_header = create_authorization_header(service_id=sample_template.service_id, - path=url_for('template.get_template', - template_id=sample_template.id), - method='GET') - resp = client.get(url_for( - 'template.get_template', template_id=sample_template.id), - headers=[auth_header]) - assert resp.status_code == 200 - json_resp = json.loads(resp.get_data(as_text=True)) - assert json_resp['data']['name'] == sample_template.name - assert json_resp['data']['id'] == sample_template.id + + auth_header = create_authorization_header( + path='/service/{}/template/{}'.format(sample_service.id, 111), + method='GET' + ) + + response = client.get( + '/service/{}/template/{}'.format(sample_service.id, 111), + headers=[auth_header] + ) + + assert response.status_code == 404 + json_resp = json.loads(response.get_data(as_text=True)) + assert json_resp['result'] == 'error' + assert json_resp['message'] == 'Template not found'