merge master

This commit is contained in:
venusbb
2017-08-11 09:36:05 +01:00
29 changed files with 863 additions and 150 deletions
@@ -15,24 +15,40 @@
} }
&-switch { &-switch {
@include core-16; @include core-16;
text-align: right; text-align: right;
position: absolute; position: absolute;
top: 0; top: 0;
right: 0; right: 0;
padding: 13px 0 9px 15px; padding: 13px 0 9px 15px;
&:focus {
outline: none;
border-bottom: 4px solid $yellow;
border-left: 10px solid $yellow;
border-right: 3px solid $yellow;
right: -3px;
color: $text-colour;
}
} }
} }
li { li {
@include core-19; @include core-19;
margin: 10px 0 0 0; margin: 0;
list-style-type: none; list-style-type: none;
} }
a { a {
display: block;
padding: 5px 0;
position: relative;
top: 5px;
&:link, &:link,
&:visited { &:visited {
text-decoration: none; text-decoration: none;
@@ -43,6 +59,10 @@
text-decoration: underline; text-decoration: underline;
} }
&:focus {
color: $text-colour;
}
} }
} }
+9
View File
@@ -85,8 +85,11 @@ class Config(object):
r"assembly\.wales", r"assembly\.wales",
r"cjsm\.net", r"cjsm\.net",
r"cqc\.org\.uk", r"cqc\.org\.uk",
r"bl\.uk",
] ]
LOGO_UPLOAD_BUCKET_NAME = 'public-logos-local'
class Development(Config): class Development(Config):
DEBUG = True DEBUG = True
@@ -94,6 +97,7 @@ class Development(Config):
SESSION_PROTECTION = None SESSION_PROTECTION = None
STATSD_ENABLED = False STATSD_ENABLED = False
CSV_UPLOAD_BUCKET_NAME = 'development-notifications-csv-upload' CSV_UPLOAD_BUCKET_NAME = 'development-notifications-csv-upload'
LOGO_UPLOAD_BUCKET_NAME = 'public-logos-tools'
class Test(Development): class Test(Development):
@@ -102,6 +106,7 @@ class Test(Development):
STATSD_ENABLED = True STATSD_ENABLED = True
WTF_CSRF_ENABLED = False WTF_CSRF_ENABLED = False
CSV_UPLOAD_BUCKET_NAME = 'test-notifications-csv-upload' CSV_UPLOAD_BUCKET_NAME = 'test-notifications-csv-upload'
LOGO_UPLOAD_BUCKET_NAME = 'public-logos-test'
NOTIFY_ENVIRONMENT = 'test' NOTIFY_ENVIRONMENT = 'test'
TEMPLATE_PREVIEW_API_HOST = 'http://localhost:9999' TEMPLATE_PREVIEW_API_HOST = 'http://localhost:9999'
@@ -111,6 +116,7 @@ class Preview(Config):
HEADER_COLOUR = '#F499BE' # $baby-pink HEADER_COLOUR = '#F499BE' # $baby-pink
STATSD_ENABLED = True STATSD_ENABLED = True
CSV_UPLOAD_BUCKET_NAME = 'preview-notifications-csv-upload' CSV_UPLOAD_BUCKET_NAME = 'preview-notifications-csv-upload'
LOGO_UPLOAD_BUCKET_NAME = 'public-logos-preview'
NOTIFY_ENVIRONMENT = 'preview' NOTIFY_ENVIRONMENT = 'preview'
@@ -120,6 +126,7 @@ class Staging(Config):
HEADER_COLOUR = '#6F72AF' # $mauve HEADER_COLOUR = '#6F72AF' # $mauve
STATSD_ENABLED = True STATSD_ENABLED = True
CSV_UPLOAD_BUCKET_NAME = 'staging-notify-csv-upload' CSV_UPLOAD_BUCKET_NAME = 'staging-notify-csv-upload'
LOGO_UPLOAD_BUCKET_NAME = 'public-logos-staging'
NOTIFY_ENVIRONMENT = 'staging' NOTIFY_ENVIRONMENT = 'staging'
@@ -129,6 +136,7 @@ class Live(Config):
HTTP_PROTOCOL = 'https' HTTP_PROTOCOL = 'https'
STATSD_ENABLED = True STATSD_ENABLED = True
CSV_UPLOAD_BUCKET_NAME = 'live-notifications-csv-upload' CSV_UPLOAD_BUCKET_NAME = 'live-notifications-csv-upload'
LOGO_UPLOAD_BUCKET_NAME = 'public-logos-production'
NOTIFY_ENVIRONMENT = 'live' NOTIFY_ENVIRONMENT = 'live'
@@ -142,6 +150,7 @@ class Sandbox(CloudFoundryConfig):
HEADER_COLOUR = '#F499BE' # $baby-pink HEADER_COLOUR = '#F499BE' # $baby-pink
STATSD_ENABLED = True STATSD_ENABLED = True
CSV_UPLOAD_BUCKET_NAME = 'cf-sandbox-notifications-csv-upload' CSV_UPLOAD_BUCKET_NAME = 'cf-sandbox-notifications-csv-upload'
LOGO_UPLOAD_BUCKET_NAME = 'cf-sandbox-notifications-logo-upload'
NOTIFY_ENVIRONMENT = 'sandbox' NOTIFY_ENVIRONMENT = 'sandbox'
+1
View File
@@ -28,6 +28,7 @@ from app.main.views import (
providers, providers,
platform_admin, platform_admin,
letter_jobs, letter_jobs,
organisations,
conversation, conversation,
notifications, notifications,
inbound_number inbound_number
+25 -37
View File
@@ -3,6 +3,7 @@ import pytz
from flask_wtf import FlaskForm as Form from flask_wtf import FlaskForm as Form
from datetime import datetime, timedelta from datetime import datetime, timedelta
from notifications_utils.recipients import ( from notifications_utils.recipients import (
validate_phone_number, validate_phone_number,
InvalidPhoneError InvalidPhoneError
@@ -25,6 +26,7 @@ from wtforms import (
SelectField) SelectField)
from wtforms.fields.html5 import EmailField, TelField, SearchField from wtforms.fields.html5 import EmailField, TelField, SearchField
from wtforms.validators import (DataRequired, Email, Length, Regexp, Optional) from wtforms.validators import (DataRequired, Email, Length, Regexp, Optional)
from flask_wtf.file import FileField as FileField_wtf, FileAllowed
from app.main.validators import (Blacklist, CsvFileValidator, ValidGovEmail, NoCommasInPlaceHolders, OnlyGSMCharacters) from app.main.validators import (Blacklist, CsvFileValidator, ValidGovEmail, NoCommasInPlaceHolders, OnlyGSMCharacters)
@@ -210,38 +212,8 @@ class TextNotReceivedForm(Form):
mobile_number = mobile_number() mobile_number = mobile_number()
class AddServiceForm(Form):
def __init__(self, names_func, *args, **kwargs):
"""
Keyword arguments:
names_func -- Returns a list of unique service_names already registered
on the system.
"""
self._names_func = names_func
super(AddServiceForm, self).__init__(*args, **kwargs)
name = StringField(
'Service name',
validators=[
DataRequired(message='Cant be empty')
]
)
def validate_name(self, a):
from app.utils import email_safe
# make sure the email_from will be unique to all services
if email_safe(a.data) in self._names_func():
raise ValidationError('This service name is already in use')
class ServiceNameForm(Form): class ServiceNameForm(Form):
def __init__(self, names_func, *args, **kwargs): def __init__(self, *args, **kwargs):
"""
Keyword arguments:
names_func -- Returns a list of unique service_names already registered
on the system.
"""
self._names_func = names_func
super(ServiceNameForm, self).__init__(*args, **kwargs) super(ServiceNameForm, self).__init__(*args, **kwargs)
name = StringField( name = StringField(
@@ -250,12 +222,6 @@ class ServiceNameForm(Form):
DataRequired(message='Cant be empty') DataRequired(message='Cant be empty')
]) ])
def validate_name(self, a):
from app.utils import email_safe
# make sure the email_from will be unique to all services
if email_safe(a.data) in self._names_func():
raise ValidationError('This service name is already in use')
class ConfirmPasswordForm(Form): class ConfirmPasswordForm(Form):
def __init__(self, validate_password_func, *args, **kwargs): def __init__(self, validate_password_func, *args, **kwargs):
@@ -559,6 +525,28 @@ class ServiceBrandingOrg(Form):
) )
class ServiceSelectOrg(Form):
def __init__(self, organisations=[], *args, **kwargs):
self.organisation.choices = organisations
super(ServiceSelectOrg, self).__init__(*args, **kwargs)
organisation = RadioField(
'Organisation',
validators=[
DataRequired()
]
)
class ServiceManageOrg(Form):
name = StringField('Name')
colour = StringField('Colour', render_kw={'onkeyup': 'update_colour_span()', 'onblur': 'update_colour_span()'})
file = FileField_wtf('Upload a PNG logo', validators=[FileAllowed(['png'], 'PNG Images only!')])
class LetterBranding(Form): class LetterBranding(Form):
def __init__(self, choices=[], *args, **kwargs): def __init__(self, choices=[], *args, **kwargs):
+102
View File
@@ -0,0 +1,102 @@
import uuid
import botocore
from boto3 import resource
from flask import current_app
from notifications_utils.s3 import s3upload as utils_s3upload
FILE_LOCATION_STRUCTURE = 'service-{}-notify/{}.csv'
TEMP_TAG = 'temp-{user_id}_'
LOGO_LOCATION_STRUCTURE = '{temp}{unique_id}-{filename}'
def get_s3_object(bucket_name, filename):
s3 = resource('s3')
return s3.Object(bucket_name, filename)
def delete_s3_object(filename):
bucket_name = current_app.config['LOGO_UPLOAD_BUCKET_NAME']
get_s3_object(bucket_name, filename).delete()
def rename_s3_object(old_name, new_name):
bucket_name = current_app.config['LOGO_UPLOAD_BUCKET_NAME']
get_s3_object(bucket_name, new_name).copy_from(
CopySource='{}/{}'.format(bucket_name, old_name))
delete_s3_object(old_name)
def get_s3_objects_filter_by_prefix(prefix):
bucket_name = current_app.config['LOGO_UPLOAD_BUCKET_NAME']
s3 = resource('s3')
return s3.Bucket(bucket_name).objects.filter(Prefix=prefix)
def get_temp_truncated_filename(filename, user_id):
return filename[len(TEMP_TAG.format(user_id=user_id)):]
def s3upload(service_id, filedata, region):
upload_id = str(uuid.uuid4())
upload_file_name = FILE_LOCATION_STRUCTURE.format(service_id, upload_id)
utils_s3upload(filedata=filedata['data'],
region=region,
bucket_name=current_app.config['CSV_UPLOAD_BUCKET_NAME'],
file_location=upload_file_name)
return upload_id
def s3download(service_id, upload_id):
contents = ''
try:
bucket_name = current_app.config['CSV_UPLOAD_BUCKET_NAME']
upload_file_name = FILE_LOCATION_STRUCTURE.format(service_id, upload_id)
key = get_s3_object(bucket_name, upload_file_name)
contents = key.get()['Body'].read().decode('utf-8')
except botocore.exceptions.ClientError as e:
current_app.logger.error("Unable to download s3 file {}".format(
FILE_LOCATION_STRUCTURE.format(service_id, upload_id)))
raise e
return contents
def upload_logo(filename, filedata, region, user_id):
upload_file_name = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id),
unique_id=str(uuid.uuid4()),
filename=filename
)
bucket_name = current_app.config['LOGO_UPLOAD_BUCKET_NAME']
utils_s3upload(
filedata=filedata,
region=region,
bucket_name=bucket_name,
file_location=upload_file_name,
content_type='image/png'
)
return upload_file_name
def persist_logo(filename, user_id):
if filename.startswith(TEMP_TAG.format(user_id=user_id)):
persisted_filename = get_temp_truncated_filename(
filename=filename, user_id=user_id)
else:
return filename
rename_s3_object(filename, persisted_filename)
return persisted_filename
def delete_temp_files_created_by(user_id):
for obj in get_s3_objects_filter_by_prefix(TEMP_TAG.format(user_id=user_id)):
delete_s3_object(obj.key)
def delete_temp_file(filename):
if not filename.startswith(TEMP_TAG[:5]):
raise ValueError('Not a temp file: {}'.format(filename))
delete_s3_object(filename)
-32
View File
@@ -1,32 +0,0 @@
import uuid
import botocore
from boto3 import resource
from flask import current_app
from notifications_utils.s3 import s3upload as utils_s3upload
FILE_LOCATION_STRUCTURE = 'service-{}-notify/{}.csv'
def s3upload(service_id, filedata, region):
upload_id = str(uuid.uuid4())
upload_file_name = FILE_LOCATION_STRUCTURE.format(service_id, upload_id)
utils_s3upload(filedata=filedata['data'],
region=region,
bucket_name=current_app.config['CSV_UPLOAD_BUCKET_NAME'],
file_location=upload_file_name)
return upload_id
def s3download(service_id, upload_id):
contents = ''
try:
s3 = resource('s3')
bucket_name = current_app.config['CSV_UPLOAD_BUCKET_NAME']
upload_file_name = FILE_LOCATION_STRUCTURE.format(service_id, upload_id)
key = s3.Object(bucket_name, upload_file_name)
contents = key.get()['Body'].read().decode('utf-8')
except botocore.exceptions.ClientError as e:
current_app.logger.error("Unable to download s3 file {}".format(
FILE_LOCATION_STRUCTURE.format(service_id, upload_id)))
raise e
return contents
+34 -20
View File
@@ -10,11 +10,11 @@ from flask_login import (
current_user, current_user,
login_required login_required
) )
from notifications_python_client.errors import HTTPError
from werkzeug.exceptions import abort from werkzeug.exceptions import abort
from app.main import main from app.main import main
from app.main.forms import AddServiceForm from app.main.forms import ServiceNameForm
from app.notify_client.models import InvitedUser from app.notify_client.models import InvitedUser
from app import ( from app import (
@@ -39,14 +39,32 @@ def _add_invited_user_to_service(invited_user):
return service_id return service_id
def _create_service(service_name, email_from): def _create_service(service_name, email_from, form):
service_id = service_api_client.create_service(service_name=service_name, try:
message_limit=current_app.config['DEFAULT_SERVICE_LIMIT'], service_id = service_api_client.create_service(service_name=service_name,
restricted=True, message_limit=current_app.config['DEFAULT_SERVICE_LIMIT'],
user_id=session['user_id'], restricted=True,
email_from=email_from) user_id=session['user_id'],
session['service_id'] = service_id email_from=email_from)
return service_id session['service_id'] = service_id
return service_id, None
except HTTPError as e:
if e.status_code == 400 and e.message['name']:
form.name.errors.append("This service name is already in use")
return None, e
else:
raise e
def _create_example_template(service_id):
example_sms_template = service_api_client.create_service_template(
'Example text message template',
'sms',
'Hey ((name)), Im trying out Notify. Today is ((day of week)) and my favourite colour is ((colour)).',
service_id,
process_type='priority',
)
return example_sms_template
@main.route("/add-service", methods=['GET', 'POST']) @main.route("/add-service", methods=['GET', 'POST'])
@@ -60,24 +78,20 @@ def add_service():
if not is_gov_user(current_user.email_address): if not is_gov_user(current_user.email_address):
abort(403) abort(403)
form = AddServiceForm(service_api_client.find_all_service_email_from) form = ServiceNameForm()
heading = 'Which service do you want to set up notifications for?' heading = 'Which service do you want to set up notifications for?'
if form.validate_on_submit(): if form.validate_on_submit():
email_from = email_safe(form.name.data) email_from = email_safe(form.name.data)
service_name = form.name.data service_name = form.name.data
service_id = _create_service(service_name, email_from)
if (len(service_api_client.get_active_services({'user_id': session['user_id']}).get('data', [])) > 1): service_id, error = _create_service(service_name, email_from, form)
if error:
return render_template('views/add-service.html', form=form, heading=heading)
if len(service_api_client.get_active_services({'user_id': session['user_id']}).get('data', [])) > 1:
return redirect(url_for('main.service_dashboard', service_id=service_id)) return redirect(url_for('main.service_dashboard', service_id=service_id))
example_sms_template = service_api_client.create_service_template( example_sms_template = _create_example_template(service_id)
'Example text message template',
'sms',
'Hey ((name)), Im trying out Notify. Today is ((day of week)) and my favourite colour is ((colour)).',
service_id,
process_type='priority',
)
return redirect(url_for( return redirect(url_for(
'main.start_tour', 'main.start_tour',
+97
View File
@@ -0,0 +1,97 @@
from flask import current_app, redirect, render_template, session, url_for, request
from flask_login import login_required
from app import organisations_client
from app.main import main
from app.main.forms import (
ServiceSelectOrg,
ServiceManageOrg)
from app.utils import user_has_permissions, get_cdn_domain
from app.main.s3_client import (
TEMP_TAG,
upload_logo,
delete_temp_file,
delete_temp_files_created_by,
persist_logo
)
from app.main.views.service_settings import get_branding_as_value_and_label, get_branding_as_dict
@main.route("/organisations", methods=['GET', 'POST'])
@main.route("/organisations/<organisation_id>", methods=['GET', 'POST'])
@login_required
@user_has_permissions(admin_override=True)
def organisations(organisation_id=None):
orgs = organisations_client.get_organisations()
form = ServiceSelectOrg()
form.organisation.choices = get_branding_as_value_and_label(orgs) + [('None', 'Create a new organisation')]
if form.validate_on_submit():
if form.organisation.data != 'None':
session['organisation'] = [o for o in orgs if o['id'] == form.organisation.data][0]
elif session.get('organisation'):
del session['organisation']
return redirect(url_for('.manage_org'))
form.organisation.data = organisation_id if organisation_id in [o['id'] for o in orgs] else 'None'
return render_template(
'views/organisations/select-org.html',
form=form,
branding_dict=get_branding_as_dict(orgs),
organisation_id=organisation_id
)
@main.route("/organisations/manage", methods=['GET', 'POST'])
@main.route("/organisations/manage/<logo>", methods=['GET', 'POST'])
@login_required
@user_has_permissions(admin_override=True)
def manage_org(logo=None):
form = ServiceManageOrg()
org = session.get("organisation")
logo = logo if logo else org.get('logo') if org else None
if form.validate_on_submit():
if form.file.data:
upload_filename = upload_logo(
form.file.data.filename,
form.file.data,
current_app.config['AWS_REGION'],
user_id=session["user_id"]
)
if logo and logo.startswith(TEMP_TAG.format(user_id=session['user_id'])):
delete_temp_file(logo)
return redirect(
url_for('.manage_org', logo=upload_filename))
logo = persist_logo(logo, session["user_id"])
delete_temp_files_created_by(session["user_id"])
if org:
organisations_client.update_organisation(
org_id=org['id'], logo=logo, name=form.name.data, colour=form.colour.data)
org_id = org['id']
else:
resp = organisations_client.create_organisation(
logo=logo, name=form.name.data, colour=form.colour.data)
org_id = resp['data']['id']
return redirect(url_for('.organisations', organisation_id=org_id))
if org:
form.name.data = org['name']
form.colour.data = org['colour']
return render_template(
'views/organisations/manage-org.html',
form=form,
organisation=org,
cdn_url=get_cdn_domain(),
logo=logo
)
+1 -1
View File
@@ -33,7 +33,7 @@ from app.main.forms import (
ChooseTimeForm, ChooseTimeForm,
get_placeholder_form_instance get_placeholder_form_instance
) )
from app.main.uploader import ( from app.main.s3_client import (
s3upload, s3upload,
s3download s3download
) )
+5 -1
View File
@@ -88,12 +88,16 @@ def service_settings(service_id):
@login_required @login_required
@user_has_permissions('manage_settings', admin_override=True) @user_has_permissions('manage_settings', admin_override=True)
def service_name_change(service_id): def service_name_change(service_id):
form = ServiceNameForm(service_api_client.find_all_service_email_from) form = ServiceNameForm()
if request.method == 'GET': if request.method == 'GET':
form.name.data = current_service.get('name') form.name.data = current_service.get('name')
if form.validate_on_submit(): if form.validate_on_submit():
unique_name = service_api_client.is_service_name_unique(form.name.data, email_safe(form.name.data))
if not unique_name:
form.name.errors.append("This service name is already in use")
return render_template('views/service-settings/name.html', form=form)
session['service_name_change'] = form.name.data session['service_name_change'] = form.name.data
return redirect(url_for('.service_name_change_confirm', service_id=service_id)) return redirect(url_for('.service_name_change_confirm', service_id=service_id))
+16
View File
@@ -19,3 +19,19 @@ class OrganisationsClient(NotifyAdminAPIClient):
def get_letter_organisations(self): def get_letter_organisations(self):
return self.get(url='/dvla_organisations') return self.get(url='/dvla_organisations')
def create_organisation(self, logo, name, colour):
data = {
"logo": logo,
"name": name,
"colour": colour
}
return self.post(url="/organisation", data=data)
def update_organisation(self, org_id, logo, name, colour):
data = {
"logo": logo,
"name": name,
"colour": colour
}
return self.post(url="/organisation/{}".format(org_id), data=data)
+7 -3
View File
@@ -216,9 +216,13 @@ class ServiceAPIClient(NotifyAdminAPIClient):
data = _attach_current_user(data) data = _attach_current_user(data)
return self.post(endpoint, data=data) return self.post(endpoint, data=data)
def find_all_service_email_from(self, user_id=None): def is_service_name_unique(self, name, email_from):
resp = self.get_services(user_id) """
return [x['email_from'] for x in resp['data']] Check that the service name or email from are unique across all services.
"""
endpoint = "/service/unique"
params = {"name": name, "email_from": email_from}
return self.get(url=endpoint, params=params)["result"]
# Temp access of service history data. Includes service and api key history # Temp access of service history data. Includes service and api key history
def get_service_history(self, service_id): def get_service_history(self, service_id):
+1 -1
View File
@@ -88,6 +88,7 @@
<ul> <ul>
<li><a href="https://status.notifications.service.gov.uk">System status</a></li> <li><a href="https://status.notifications.service.gov.uk">System status</a></li>
<li><a href="{{ url_for('main.support') }}">Support</a></li> <li><a href="{{ url_for('main.support') }}">Support</a></li>
<li><a href="https://www.gov.uk/performance/govuk-notify">Performance</a></li>
<li><a href="https://ukgovernmentdigital.slack.com/messages/govuk-notify">Chat with the Notify team</a></li> <li><a href="https://ukgovernmentdigital.slack.com/messages/govuk-notify">Chat with the Notify team</a></li>
</ul> </ul>
</div> </div>
@@ -100,7 +101,6 @@
<li><a href="{{ url_for("main.trial_mode") }}">Trial mode</a></li> <li><a href="{{ url_for("main.trial_mode") }}">Trial mode</a></li>
<li><a href="{{ url_for("main.pricing") }}">Pricing</a></li> <li><a href="{{ url_for("main.pricing") }}">Pricing</a></li>
<li><a href="{{ url_for("main.delivery_and_failure") }}">Delivery and failure</a></li> <li><a href="{{ url_for("main.delivery_and_failure") }}">Delivery and failure</a></li>
<li><a href="https://www.gov.uk/performance/govuk-notify">Performance</a></li>
</ul> </ul>
</div> </div>
<div class="column-one-third"> <div class="column-one-third">
+3 -2
View File
@@ -6,12 +6,13 @@
secondary_link=False, secondary_link=False,
secondary_link_text=None, secondary_link_text=None,
delete_link=False, delete_link=False,
delete_link_text="delete" delete_link_text="delete",
button_disabled=False
) %} ) %}
<div class="page-footer"> <div class="page-footer">
{% if button_text %} {% if button_text %}
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input type="submit" class="button{% if destructive %}-destructive{% endif %}" value="{{ button_text }}" /> <input type="submit" class="button{% if destructive %}-destructive{% endif %}" value="{{ button_text }}"{% if button_disabled %} disabled{% endif %}/>
{% endif %} {% endif %}
{% if back_link %} {% if back_link %}
<a class="page-footer-back-link" href="{{ back_link }}">{{ back_link_text }}</a> <a class="page-footer-back-link" href="{{ back_link }}">{{ back_link_text }}</a>
+9 -6
View File
@@ -79,16 +79,19 @@
{% macro branding_radios( {% macro branding_radios(
field, field,
hint=None, hint=None,
branding_dict={} branding_dict={},
show_header=True
) %} ) %}
<div class="form-group {% if field.errors %} form-group-error{% endif %}"> <div class="form-group {% if field.errors %} form-group-error{% endif %}">
<fieldset> <fieldset>
<legend class="form-label"> <legend class="form-label">
{{ field.label.text }} {% if show_header %}
{{ field.label.text }}
{% endif %}
{% if field.errors %} {% if field.errors %}
<span class="error-message"> <span class="error-message">
{{ field.errors[0] }} {{ field.errors[0] }}
</span> </span>
{% endif %} {% endif %}
</legend> </legend>
{% for value, option, checked in field.iter_choices() %} {% for value, option, checked in field.iter_choices() %}
@@ -102,7 +105,7 @@
/> />
<label class="block-label" for="{{ field.name }}-{{ loop.index }}"> <label class="block-label" for="{{ field.name }}-{{ loop.index }}">
{% if branding_dict.get(value, {}).get('colour') %} {% if branding_dict.get(value, {}).get('colour') %}
<span style="background: {{ branding_dict[value].colour }}; display: inline-block; width: 3px; height: 27px"></span> <span style="background: {{ branding_dict[value].colour }}; display: inline-block; width: 3px; height: 27px;"></span>
{% endif %} {% endif %}
{% if branding_dict.get(value, {}).get('logo') %} {% if branding_dict.get(value, {}).get('logo') %}
<img <img
@@ -0,0 +1,55 @@
{% extends "views/platform-admin/_base_template.html" %}
{% from "components/file-upload.html" import file_upload %}
{% from "components/page-footer.html" import page_footer %}
{% from "components/textbox.html" import textbox %}
{% block service_page_title %}
{{ '{} an organisations logo'.format('Update' if organisation else 'Create')}}
{% endblock %}
{% block platform_admin_content %}
<h1 class="heading-large">{{ '{} an organisations logo'.format('Update' if organisation else 'Create')}}</h1>
<div class="grid-row">
<div class="column-three-quarters">
{% if logo %}
<div id="logo-img">
<img src="https://{{ cdn_url }}/{{ logo }}"/>
</div>
{% endif %}
{{
file_upload(
form.file,
button_text='{} logo'.format('Update' if organisation else 'Upload')
) }}
<form method="post">
<div class="form-group">
<div style='margin-top:15px;'>{{textbox(form.name)}}</div>
<div>{{textbox(form.colour, width='1-4')}}
<span id='colour_span' style="background: {{ organisation.colour }}; {% if not organisation.colour %}visibility:hidden; {% endif %}border:1px black solid; width: 3px; height: 25px;position:absolute;margin-top:138px;margin-left:135px;display:block;"></span>
</div>
{{ page_footer(
'Save',
back_link=url_for('.organisations', organisation_id=organisation.id if organisation else 'None'),
back_link_text='Back to organisation selection',
button_disabled=True if not logo else False
) }}
</div>
</form>
</div>
</div>
<script type="text/javascript">
function update_colour_span() {
document.getElementById('colour_span').style.background = '';
if (document.getElementById('colour').value) {
document.getElementById('colour_span').style.visibility = 'visible';
document.getElementById('colour_span').style.background = document.getElementById('colour').value;
}
else {
document.getElementById('colour_span').style.visibility = 'hidden';
}
}
</script>
{% endblock %}
@@ -0,0 +1,26 @@
{% extends "views/platform-admin/_base_template.html" %}
{% from "components/radios.html" import radios, branding_radios %}
{% from "components/page-footer.html" import page_footer %}
{% block service_page_title %}
Select organisation
{% endblock %}
{% block platform_admin_content %}
<h1 class="heading-large">
<div>Select an organisation to update</div>
<div>or create a new organisation</div>
</h1>
<div class="grid-row">
<div class="column-three-quarters">
<form method="post">
{{ branding_radios(form.organisation, branding_dict=branding_dict, show_header=False) }}
{{ page_footer(
'Next'
) }}
</form>
</div>
</div>
{% endblock %}
@@ -16,6 +16,7 @@
('Live services', url_for('main.live_services')), ('Live services', url_for('main.live_services')),
('Trial mode services', url_for('main.trial_services')), ('Trial mode services', url_for('main.trial_services')),
('Providers', url_for('main.view_providers')), ('Providers', url_for('main.view_providers')),
('Organisations', url_for('main.organisations')),
('Letter jobs', url_for('main.letter_jobs')) ('Letter jobs', url_for('main.letter_jobs'))
] %} ] %}
<li> <li>
+2 -2
View File
@@ -117,12 +117,12 @@
<div class="grid-row bottom-gutter"> <div class="grid-row bottom-gutter">
<div class="column-half"> <div class="column-half">
<h3 class="visually-hidden">Services</h3> <h3 class="visually-hidden">Services</h3>
<div class="product-page-big-number">69</div> <div class="product-page-big-number">70</div>
services services
</div> </div>
<div class="column-half"> <div class="column-half">
<h3 class="visually-hidden">Departments</h3> <h3 class="visually-hidden">Departments</h3>
<div class="product-page-big-number">33</div> <div class="product-page-big-number">34</div>
departments departments
</div> </div>
</div> </div>
+1 -1
View File
@@ -1,5 +1,5 @@
cffi==1.10.0
ago==0.0.9 ago==0.0.9
cffi==1.10.0
Flask==0.12.2 Flask==0.12.2
Flask-Script==2.0.5 Flask-Script==2.0.5
Flask-WTF==0.14.2 Flask-WTF==0.14.2
+2 -2
View File
@@ -1,9 +1,9 @@
-r requirements.txt -r requirements.txt
pycodestyle==2.3.1 pycodestyle==2.3.1
pytest==3.2.0 pytest==3.2.1
pytest-mock==1.6.2 pytest-mock==1.6.2
pytest-cov==2.5.1 pytest-cov==2.5.1
pytest-xdist==1.18.2 pytest-xdist==1.19.0
coveralls==1.1 coveralls==1.1
moto==1.0.1 moto==1.0.1
httpretty==0.8.14 httpretty==0.8.14
-11
View File
@@ -1,11 +0,0 @@
from app.main.forms import AddServiceForm
from werkzeug.datastructures import MultiDict
def test_form_should_have_errors_when_duplicate_service_is_added(client):
def _get_form_names():
return ['some.service', 'more.names']
form = AddServiceForm(_get_form_names,
formdata=MultiDict([('name', 'some service')]))
form.validate()
assert {'name': ['This service name is already in use']} == form.errors
+95
View File
@@ -0,0 +1,95 @@
from collections import namedtuple
from unittest.mock import call
import pytest
from app.main.s3_client import (
upload_logo,
persist_logo,
delete_temp_file,
delete_temp_files_created_by,
get_temp_truncated_filename,
LOGO_LOCATION_STRUCTURE,
TEMP_TAG
)
bucket = 'test_bucket'
data = {'data': 'some_data'}
filename = 'test.png'
upload_id = 'test_uuid'
region = 'eu-west1'
@pytest.fixture
def upload_filename(fake_uuid):
return LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=fake_uuid), unique_id=upload_id, filename=filename)
def test_upload_logo_calls_correct_args(client, mocker, fake_uuid, upload_filename):
mocker.patch('uuid.uuid4', return_value=upload_id)
mocker.patch.dict('flask.current_app.config', {'LOGO_UPLOAD_BUCKET_NAME': bucket})
mocked_s3_upload = mocker.patch('app.main.s3_client.utils_s3upload')
upload_logo(filename=filename, user_id=fake_uuid, filedata=data, region=region)
assert mocked_s3_upload.called_once_with(
filedata=data,
region=region,
file_location=upload_filename,
bucket_name=bucket
)
def test_persist_logo(client, mocker, fake_uuid, upload_filename):
mocker.patch.dict('flask.current_app.config', {'LOGO_UPLOAD_BUCKET_NAME': bucket})
mocked_rename_s3_object = mocker.patch('app.main.s3_client.rename_s3_object')
persisted_filename = persist_logo(filename=upload_filename, user_id=fake_uuid)
assert mocked_rename_s3_object.called_once_with(
upload_filename, get_temp_truncated_filename(upload_filename, fake_uuid))
assert persisted_filename == get_temp_truncated_filename(upload_filename, fake_uuid)
def test_persist_logo_returns_if_not_temp(client, mocker, fake_uuid):
filename = 'logo.png'
mocker.patch.dict('flask.current_app.config', {'LOGO_UPLOAD_BUCKET_NAME': bucket})
mocked_rename_s3_object = mocker.patch('app.main.s3_client.rename_s3_object')
persisted_filename = persist_logo(filename=filename, user_id=fake_uuid)
assert not mocked_rename_s3_object.called
assert persisted_filename == filename
def test_delete_temp_files_created_by_user(client, mocker, fake_uuid):
obj = namedtuple("obj", ["key"])
objs = [obj(key='test1'), obj(key='test2')]
mocker.patch('app.main.s3_client.get_s3_objects_filter_by_prefix', return_value=objs)
mocked_delete_s3_object = mocker.patch('app.main.s3_client.delete_s3_object')
delete_temp_files_created_by(fake_uuid)
assert mocked_delete_s3_object.called_with_args(objs[0].key)
for index, arg in enumerate(mocked_delete_s3_object.call_args_list):
assert arg == call(objs[index].key)
def test_delete_single_temp_file(client, mocker, fake_uuid, upload_filename):
mocked_delete_s3_object = mocker.patch('app.main.s3_client.delete_s3_object')
delete_temp_file(upload_filename)
assert mocked_delete_s3_object.called_with_args(upload_filename)
def test_does_not_delete_non_temp_file(client, mocker, fake_uuid):
filename = 'logo.png'
mocked_delete_s3_object = mocker.patch('app.main.s3_client.delete_s3_object')
with pytest.raises(ValueError) as error:
delete_temp_file(filename)
assert mocked_delete_s3_object.called_with_args(filename)
assert str(error.value) == 'Not a temp file: {}'.format(filename)
+3 -1
View File
@@ -93,6 +93,7 @@ def _gen_mock_field(x):
'test@cjsm.net', 'test@cjsm.net',
'test@cqc.org.uk', 'test@cqc.org.uk',
'test@digital.cqc.org.uk', 'test@digital.cqc.org.uk',
'test@bl.uk',
]) ])
def test_valid_list_of_white_list_email_domains( def test_valid_list_of_white_list_email_domains(
client, client,
@@ -126,7 +127,8 @@ def test_valid_list_of_white_list_email_domains(
'test@ukpolice.uk', 'test@ukpolice.uk',
'test@police.uk.uk', 'test@police.uk.uk',
'test@police.test.uk', 'test@police.test.uk',
'test@ucds.com' 'test@ucds.com',
'test@123bl.uk',
]) ])
def test_invalid_list_of_white_list_email_domains( def test_invalid_list_of_white_list_email_domains(
client, client,
+5 -21
View File
@@ -1,6 +1,5 @@
from flask import url_for, session from flask import url_for, session
from unittest.mock import ANY
import app
from app.utils import is_gov_user from app.utils import is_gov_user
@@ -17,9 +16,7 @@ def test_non_gov_user_cannot_see_add_service_button(
def test_get_should_render_add_service_template( def test_get_should_render_add_service_template(
logged_in_client, logged_in_client
api_user_active,
mocker,
): ):
response = logged_in_client.get(url_for('main.add_service')) response = logged_in_client.get(url_for('main.add_service'))
assert response.status_code == 200 assert response.status_code == 200
@@ -29,7 +26,6 @@ def test_get_should_render_add_service_template(
def test_should_add_service_and_redirect_to_tour_when_no_services( def test_should_add_service_and_redirect_to_tour_when_no_services(
app_, app_,
logged_in_client, logged_in_client,
mocker,
mock_create_service, mock_create_service,
mock_create_service_template, mock_create_service_template,
mock_get_services_with_no_services, mock_get_services_with_no_services,
@@ -69,7 +65,6 @@ def test_should_add_service_and_redirect_to_tour_when_no_services(
def test_should_add_service_and_redirect_to_dashboard_when_existing_service( def test_should_add_service_and_redirect_to_dashboard_when_existing_service(
app_, app_,
logged_in_client, logged_in_client,
mocker,
mock_create_service, mock_create_service,
mock_create_service_template, mock_create_service_template,
mock_get_services, mock_get_services,
@@ -93,9 +88,7 @@ def test_should_add_service_and_redirect_to_dashboard_when_existing_service(
def test_should_return_form_errors_when_service_name_is_empty( def test_should_return_form_errors_when_service_name_is_empty(
logged_in_client, logged_in_client
mocker,
api_user_active,
): ):
response = logged_in_client.post(url_for('main.add_service'), data={}) response = logged_in_client.post(url_for('main.add_service'), data={})
assert response.status_code == 200 assert response.status_code == 200
@@ -104,24 +97,16 @@ def test_should_return_form_errors_when_service_name_is_empty(
def test_should_return_form_errors_with_duplicate_service_name_regardless_of_case( def test_should_return_form_errors_with_duplicate_service_name_regardless_of_case(
logged_in_client, logged_in_client,
mocker, mock_create_duplicate_service,
service_one,
api_user_active,
mock_create_service,
): ):
mocker.patch('app.service_api_client.find_all_service_email_from', response = logged_in_client.post(url_for('main.add_service'), data={'name': 'SERVICE ONE'})
return_value=['service_one', 'service.two'])
response = logged_in_client.post(url_for('main.add_service'), data={'name': 'SERVICE TWO'})
assert response.status_code == 200 assert response.status_code == 200
assert 'This service name is already in use' in response.get_data(as_text=True) assert 'This service name is already in use' in response.get_data(as_text=True)
app.service_api_client.find_all_service_email_from.assert_called_once_with()
assert not mock_create_service.called
def test_non_whitelist_user_cannot_access_create_service_page( def test_non_whitelist_user_cannot_access_create_service_page(
logged_in_client, logged_in_client,
mock_login,
mock_get_non_govuser, mock_get_non_govuser,
api_nongov_user_active, api_nongov_user_active,
): ):
@@ -132,7 +117,6 @@ def test_non_whitelist_user_cannot_access_create_service_page(
def test_non_whitelist_user_cannot_create_service( def test_non_whitelist_user_cannot_create_service(
logged_in_client, logged_in_client,
mock_login,
mock_get_non_govuser, mock_get_non_govuser,
api_nongov_user_active, api_nongov_user_active,
): ):
+264
View File
@@ -0,0 +1,264 @@
from io import BytesIO
from unittest.mock import call
from bs4 import BeautifulSoup
from flask import url_for
import pytest
from app.main.s3_client import TEMP_TAG, LOGO_LOCATION_STRUCTURE
sample_orgs = [
{'id': '1', 'name': 'org 1', 'colour': 'red', 'logo': 'logo1.png'},
{'id': '2', 'name': 'org 2', 'colour': 'orange', 'logo': 'logo2.png'},
{'id': '3', 'name': None, 'colour': None, 'logo': 'logo3.png'},
{'id': '4', 'name': 'org 4', 'colour': None, 'logo': 'logo4.png'},
{'id': '5', 'name': None, 'colour': 'blue', 'logo': 'logo5.png'},
]
@pytest.fixture
def request_get_manage_org_with_org(logged_in_platform_admin_client):
with logged_in_platform_admin_client.session_transaction() as session:
session['organisation'] = sample_orgs[0]
response = logged_in_platform_admin_client.get(
url_for('.manage_org')
)
assert response.status_code == 200
return BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
@pytest.fixture
def request_get_manage_org_without_org(logged_in_platform_admin_client):
response = logged_in_platform_admin_client.get(
url_for('.manage_org')
)
assert response.status_code == 200
return BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
def test_organisations_page_shows_full_orgs_list(logged_in_platform_admin_client, mocker):
mocker.patch('app.organisations_client.get_organisations', return_value=sample_orgs)
response = logged_in_platform_admin_client.get(
url_for('.organisations')
)
assert response.status_code == 200
page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
assert ' '.join(page.find('h1').text.split()) == "Select an organisation to update or create a new organisation"
for index, label in enumerate(page.select('div.multiple-choice > label')):
if index < len(sample_orgs):
if sample_orgs[index]['colour']:
assert 'background: {};'.format(sample_orgs[index]['colour']) in label.find('span')['style']
assert ' '.join(label.text.split()) == str(sample_orgs[index]['name'])
assert label.find('img')['src'].endswith('/' + sample_orgs[index]['logo'])
else:
assert ' '.join(label.text.split()) == 'Create a new organisation'
@pytest.mark.parametrize("org_id", [
'None', '1', '2'
])
def test_organisations_radio_default_to_just_updated_or_new_org(
logged_in_platform_admin_client, mocker, org_id):
mocker.patch('app.organisations_client.get_organisations', return_value=sample_orgs)
response = logged_in_platform_admin_client.get(
url_for('.organisations', organisation_id=org_id)
)
assert response.status_code == 200
page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
selected = [r for r in page.select('div.multiple-choice > input') if r.attrs.get('checked')][0]
assert selected["value"] == org_id
def test_organisations_post_sets_organisation_in_session_after_selecting_org(
logged_in_platform_admin_client, mocker):
mocker.patch('app.organisations_client.get_organisations', return_value=sample_orgs)
response = logged_in_platform_admin_client.post(
url_for('.organisations'),
data={'organisation': sample_orgs[0]['id']}
)
with logged_in_platform_admin_client.session_transaction() as session:
assert session['organisation'] == sample_orgs[0]
assert response.status_code == 302
assert response.location == url_for('.manage_org', _external=True)
def test_organisations_post_deletes_organisation_session_on_new_org(
logged_in_platform_admin_client, mocker):
mocker.patch('app.organisations_client.get_organisations', return_value=sample_orgs)
with logged_in_platform_admin_client.session_transaction() as session:
session['organisation'] = sample_orgs[0]
response = logged_in_platform_admin_client.post(
url_for('.organisations'),
data={'organisation': 'None'}
)
with logged_in_platform_admin_client.session_transaction() as session:
assert session.get('organisation') is None
assert response.status_code == 302
assert response.location == url_for('.manage_org', _external=True)
def test_manage_orgs_shows_correct_org_info(request_get_manage_org_with_org):
assert request_get_manage_org_with_org.select_one('#logo-img > img')['src'].endswith('/' + sample_orgs[0]['logo'])
assert request_get_manage_org_with_org.select_one('#name').attrs.get('value') == sample_orgs[0]['name']
assert request_get_manage_org_with_org.select_one('#colour').attrs.get('value') == sample_orgs[0]['colour']
def test_manage_orgs_does_not_show_data_for_new_org(request_get_manage_org_without_org):
assert request_get_manage_org_without_org.select_one('div.page-footer input.button').has_attr('disabled')
assert request_get_manage_org_without_org.select_one('#logo-img > img') is None
assert request_get_manage_org_without_org.select_one('#name').attrs.get('value') == ''
assert request_get_manage_org_without_org.select_one('#colour').attrs.get('value') == ''
def test_save_is_enabled_when_logo_is_set(request_get_manage_org_with_org):
assert request_get_manage_org_with_org.select_one('div.page-footer input.button').has_attr('disabled') is False
def test_save_is_disabled_when_logo_is_not_set(request_get_manage_org_without_org):
assert request_get_manage_org_without_org.select_one('div.page-footer input.button').has_attr('disabled')
@pytest.fixture
def request_post_manage_org_redirect(logged_in_platform_admin_client, mocker, fake_uuid):
with logged_in_platform_admin_client.session_transaction() as session:
user_id = session["user_id"]
temp_filename = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id), unique_id=fake_uuid, filename='test.png')
mocker.patch('app.main.views.organisations.upload_logo', return_value=temp_filename)
mocker.patch('app.main.views.organisations.delete_temp_file')
mocker.patch('app.main.views.organisations.delete_temp_files_created_by')
response = logged_in_platform_admin_client.post(
url_for('.manage_org'),
data={'file': (BytesIO(''.encode('utf-8')), 'test.png')},
content_type='multipart/form-data',
follow_redirects=True
)
assert response.status_code == 200
return BeautifulSoup(response.data.decode('utf-8'), 'html.parser'), temp_filename
def test_shows_temp_logo_after_uploading_logo(request_post_manage_org_redirect):
page, temp_filename = request_post_manage_org_redirect
assert page.select_one('#logo-img > img').attrs['src'].endswith(temp_filename)
def test_save_enabled_after_uploading_logo(request_post_manage_org_redirect):
page, _ = request_post_manage_org_redirect
assert not page.select_one('div.page-footer input.button').has_attr('disabled')
def test_deletes_previous_temp_logo_after_uploading_logo(logged_in_platform_admin_client, mocker, fake_uuid):
with logged_in_platform_admin_client.session_transaction() as session:
user_id = session["user_id"]
temp_old_filename = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id), unique_id=fake_uuid, filename='old_test.png')
temp_filename = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id), unique_id=fake_uuid, filename='test.png')
mocked_upload_logo = mocker.patch(
'app.main.views.organisations.upload_logo',
return_value=temp_filename
)
mocked_delete_temp_file = mocker.patch('app.main.views.organisations.delete_temp_file')
logged_in_platform_admin_client.post(
url_for('.manage_org', logo=temp_old_filename),
data={'file': (BytesIO(''.encode('utf-8')), 'test.png')},
content_type='multipart/form-data'
)
assert mocked_upload_logo.called
assert mocked_delete_temp_file.called
assert mocked_delete_temp_file.call_args == call(temp_old_filename)
def test_logo_persisted_when_organisation_saved(logged_in_platform_admin_client, mocker, fake_uuid):
with logged_in_platform_admin_client.session_transaction() as session:
user_id = session["user_id"]
temp_filename = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id), unique_id=fake_uuid, filename='test.png')
mocked_upload_logo = mocker.patch('app.main.views.organisations.upload_logo')
mocked_persist_logo = mocker.patch('app.main.views.organisations.persist_logo', return_value='test.png')
mocked_delete_temp_files_by = mocker.patch('app.main.views.organisations.delete_temp_files_created_by')
logged_in_platform_admin_client.post(
url_for('.manage_org', logo=temp_filename),
content_type='multipart/form-data'
)
assert not mocked_upload_logo.called
assert mocked_persist_logo.called
assert mocked_delete_temp_files_by.called
assert mocked_delete_temp_files_by.call_args == call(user_id)
def test_existing_organisation_updated_when_organisation_saved(logged_in_platform_admin_client, mocker, fake_uuid):
with logged_in_platform_admin_client.session_transaction() as session:
session["organisation"] = sample_orgs[0]
user_id = session["user_id"]
update_org = {'logo': 'test.png', 'colour': 'blue', 'name': 'new name'}
temp_filename = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id), unique_id=fake_uuid, filename=update_org['logo'])
mocked_update_org = mocker.patch('app.organisations_client.update_organisation')
mocker.patch('app.main.views.organisations.persist_logo', return_value=update_org['logo'])
mocker.patch('app.main.views.organisations.delete_temp_files_created_by')
logged_in_platform_admin_client.post(
url_for('.manage_org', logo=temp_filename),
content_type='multipart/form-data',
data={'colour': update_org['colour'], 'name': update_org['name'], 'cdn_url': 'https://static-logos.cdn.com'}
)
assert mocked_update_org.called
assert mocked_update_org.call_args == call(
org_id=sample_orgs[0]['id'],
logo=update_org['logo'],
name=update_org['name'],
colour=update_org['colour']
)
def test_create_new_organisation_when_organisation_saved(logged_in_platform_admin_client, mocker, fake_uuid):
with logged_in_platform_admin_client.session_transaction() as session:
user_id = session["user_id"]
new_org = {'logo': 'test.png', 'colour': 'red', 'name': 'new name'}
temp_filename = LOGO_LOCATION_STRUCTURE.format(
temp=TEMP_TAG.format(user_id=user_id), unique_id=fake_uuid, filename=new_org['logo'])
mocked_new_org = mocker.patch('app.organisations_client.create_organisation')
mocker.patch('app.main.views.organisations.persist_logo', return_value=new_org['logo'])
mocker.patch('app.main.views.organisations.delete_temp_files_created_by')
logged_in_platform_admin_client.post(
url_for('.manage_org', logo=temp_filename),
content_type='multipart/form-data',
data={'colour': new_org['colour'], 'name': new_org['name'], 'cdn_url': 'https://static-logos.cdn.com'}
)
assert mocked_new_org.called
assert mocked_new_org.call_args == call(
logo=new_org['logo'],
name=new_org['name'],
colour=new_org['colour']
)
@@ -230,10 +230,10 @@ def test_should_show_service_name(
def test_should_redirect_after_change_service_name( def test_should_redirect_after_change_service_name(
logged_in_client, logged_in_client,
service_one, service_one,
mock_update_service, mock_update_service,
mock_get_services, mock_get_services,
): ):
response = logged_in_client.post( response = logged_in_client.post(
url_for('main.service_name_change', service_id=service_one['id']), url_for('main.service_name_change', service_id=service_one['id']),
@@ -243,7 +243,7 @@ def test_should_redirect_after_change_service_name(
settings_url = url_for( settings_url = url_for(
'main.service_name_change_confirm', service_id=service_one['id'], _external=True) 'main.service_name_change_confirm', service_id=service_one['id'], _external=True)
assert settings_url == response.location assert settings_url == response.location
assert mock_get_services.called assert mock_service_name_is_unique.called
def test_show_restricted_service( def test_show_restricted_service(
@@ -315,8 +315,6 @@ def test_should_not_allow_duplicate_names(
mocker, mocker,
service_one, service_one,
): ):
mocker.patch('app.service_api_client.find_all_service_email_from',
return_value=['service_one', 'service.two'])
service_id = service_one['id'] service_id = service_one['id']
response = logged_in_client.post( response = logged_in_client.post(
url_for('main.service_name_change', service_id=service_id), url_for('main.service_name_change', service_id=service_id),
@@ -325,7 +323,7 @@ def test_should_not_allow_duplicate_names(
assert response.status_code == 200 assert response.status_code == 200
resp_data = response.get_data(as_text=True) resp_data = response.get_data(as_text=True)
assert 'This service name is already in use' in resp_data assert 'This service name is already in use' in resp_data
app.service_api_client.find_all_service_email_from.assert_called_once_with() app.service_api_client.is_service_name_unique.assert_called_once_with('SErvICE TWO', 'service.two')
def test_should_show_service_name_confirmation( def test_should_show_service_name_confirmation(
@@ -0,0 +1,50 @@
from app.notify_client.organisations_client import OrganisationsClient
def test_get_organisation(mocker, fake_uuid):
mock_get = mocker.patch('app.notify_client.organisations_client.OrganisationsClient.get')
OrganisationsClient().get_organisation(fake_uuid)
mock_get.assert_called_once_with(
url='/organisation/{}'.format(fake_uuid)
)
def test_get_organisations(mocker):
mock_get = mocker.patch('app.notify_client.organisations_client.OrganisationsClient.get')
OrganisationsClient().get_organisations()
mock_get.assert_called_once_with(
url='/organisation'
)
def test_get_letter_organisations(mocker):
mock_get = mocker.patch('app.notify_client.organisations_client.OrganisationsClient.get')
OrganisationsClient().get_letter_organisations()
mock_get.assert_called_once_with(
url='/dvla_organisations'
)
def test_create_organisations(mocker):
org_data = {'logo': 'test.png', 'name': 'test name', 'colour': 'red'}
mock_post = mocker.patch('app.notify_client.organisations_client.OrganisationsClient.post')
OrganisationsClient().create_organisation(logo=org_data['logo'], name=org_data['name'], colour=org_data['colour'])
mock_post.assert_called_once_with(
url='/organisation',
data=org_data
)
def test_update_organisations(mocker, fake_uuid):
org_data = {'logo': 'test.png', 'name': 'test name', 'colour': 'red'}
mock_post = mocker.patch('app.notify_client.organisations_client.OrganisationsClient.post')
OrganisationsClient().update_organisation(
org_id=fake_uuid, logo=org_data['logo'], name=org_data['name'], colour=org_data['colour'])
mock_post.assert_called_once_with(
url='/organisation/{}'.format(fake_uuid),
data=org_data
)
+22
View File
@@ -149,6 +149,16 @@ def mock_get_detailed_services(mocker, fake_uuid):
return mocker.patch('app.service_api_client.get_services', return_value=services) return mocker.patch('app.service_api_client.get_services', return_value=services)
@pytest.fixture(scope='function')
def mock_service_name_is_not_unique(mocker):
return mocker.patch('app.service_api_client.is_service_name_unique', return_value=False)
@pytest.fixture(scope='function')
def mock_service_name_is_unique(mocker):
return mocker.patch('app.service_api_client.is_service_name_unique', return_value=True)
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def mock_get_live_service(mocker, api_user_active): def mock_get_live_service(mocker, api_user_active):
def _get(service_id): def _get(service_id):
@@ -172,6 +182,18 @@ def mock_create_service(mocker):
'app.service_api_client.create_service', side_effect=_create) 'app.service_api_client.create_service', side_effect=_create)
@pytest.fixture(scope='function')
def mock_create_duplicate_service(mocker):
def _create(service_name, message_limit, restricted, user_id, email_from):
json_mock = Mock(return_value={'message': {'name': ["Duplicate service name '{}'".format(service_name)]}})
resp_mock = Mock(status_code=400, json=json_mock)
http_error = HTTPError(response=resp_mock, message="Default message")
raise http_error
return mocker.patch(
'app.service_api_client.create_service', side_effect=_create)
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def mock_update_service(mocker): def mock_update_service(mocker):
def _update(service_id, **kwargs): def _update(service_id, **kwargs):