Skip to content

Commit

Permalink
DST-540/unit tests (#27)
Browse files Browse the repository at this point in the history
* Adding tests

* Unit tests for some views

* adding more tests

* Licence not license

* Adding tests

* add business views tests

* Updating tests

* Change submodule url to use ssh

---------

Co-authored-by: Morgan Rees <[email protected]>
  • Loading branch information
morganmaerees and Morgan Rees authored Aug 9, 2024
1 parent 9512661 commit c3bbe31
Show file tree
Hide file tree
Showing 19 changed files with 1,233 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .gitmodules
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[submodule "django_app/sanctions_regimes"]
path = django_app/sanctions_regimes
url = https://github.com/uktrade/sanctions-regimes.git
url = git@github.com:uktrade/sanctions-regimes.git
35 changes: 25 additions & 10 deletions django_app/apply_for_a_licence/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class Meta:
widgets = {
"who_do_you_want_the_licence_to_cover": forms.RadioSelect,
}
error_messages = {"who_do_you_want_the_licence_to_cover": {"required": "Select who you want the licence to cover"}}

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -136,7 +137,11 @@ class EmailVerifyForm(BaseForm):

email_verification_code = forms.CharField(
label="Enter the 6 digit security code",
error_messages={"required": "Enter the 6 digit security code we sent to your email"},
error_messages={
"required": "Enter the 6 digit security code we sent to your email",
"expired": "The code you entered is no longer valid. New code sent",
"invalid": "Code is incorrect. Enter the 6 digit security code we sent to your email",
},
)

def clean_email_verification_code(self) -> str:
Expand All @@ -159,7 +164,14 @@ def clean_email_verification_code(self) -> str:
# check if the user has submitted the verify code within the specified timeframe
allowed_lapse = verification_objects.date_created + timedelta(seconds=verify_timeout_seconds)
if allowed_lapse < now():
raise forms.ValidationError("The code you entered is no longer valid. Please verify your email again")
time_code_sent = verification_objects.date_created

# 15 minutes ago, show a ‘code has expired’ error message and send the user a new code
# 2 hours ago, show an ‘incorrect security code’ message, even if the code was correct
if time_code_sent > (now() - timedelta(hours=2)):
raise forms.ValidationError(self.fields["email_verification_code"].error_messages["expired"], code="expired")
else:
raise forms.ValidationError(self.fields["email_verification_code"].error_messages["invalid"], code="invalid")

verification_objects.verified = True
verification_objects.save()
Expand Down Expand Up @@ -358,7 +370,7 @@ class ManualCompaniesHouseInputForm(BaseForm):
),
widget=forms.RadioSelect,
error_messages={
"required": "Select if the address of the business you would like the license for is in the UK, or outside the UK"
"required": "Select if the address of the business you would like the licence for is in the UK, or outside the UK"
},
)

Expand Down Expand Up @@ -485,7 +497,11 @@ class Meta:
"nationality_and_location": "What is the individual's nationality and location?",
}
help_texts = {"nationality_and_location": "Hint text"}
error_messages = {"first_name": {"required": "Enter your first name"}, "last_name": {"required": "Enter your last name"}}
error_messages = {
"first_name": {"required": "Enter your first name"},
"last_name": {"required": "Enter your last name"},
"nationality_and_location": {"required": "Enter your nationality and location"},
}

def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -632,12 +648,8 @@ class Meta(BaseBusinessDetailsForm.Meta):
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, **kwargs)

# all fields on this form are optional. Except if it's a non-UK user, then we need the country at least
for _, field in self.fields.items():
field.required = False

if not self.is_uk_address:
self.fields["country"].required = True
self.fields["town_or_city"].required = True
self.fields["address_line_1"].required = True

self.helper.layout = Layout(
Field.text("town_or_city", field_width=Fluid.ONE_THIRD),
Expand Down Expand Up @@ -811,6 +823,9 @@ class Meta(BaseBusinessDetailsForm.Meta):
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, **kwargs)

self.fields["town_or_city"].required = True
self.fields["address_line_1"].required = True

if self.is_uk_address:
address_layout = Fieldset(
Field.text("country", field_width=Fluid.ONE_HALF),
Expand Down
4 changes: 2 additions & 2 deletions django_app/apply_for_a_licence/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ class ApplicationType(BaseModelID):
who_do_you_want_the_licence_to_cover = models.CharField(
max_length=255,
choices=choices.WhoDoYouWantTheLicenceToCoverChoices.choices,
blank=True,
null=True,
blank=False,
null=False,
)
label = models.CharField()
start_date = models.DateField(blank=True, null=True)
Expand Down
2 changes: 1 addition & 1 deletion django_app/config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@

LOGIN_URL = reverse_lazy("authbroker_client:login")
# TODO: update when viewing portal is created
LOGIN_REDIRECT_URL = reverse_lazy("view_a_suspected_breach:landing")
LOGIN_REDIRECT_URL = reverse_lazy("view_a_licence:landing")
else:
LOGIN_URL = "/admin/login"

Expand Down
3 changes: 2 additions & 1 deletion django_app/core/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.conf import settings
from django.contrib import admin
from django.urls import include, path

from .views import cookie_views
from .views.base_views import RedirectBaseDomainView

Expand All @@ -10,7 +11,7 @@
path("pingdom/", include("healthcheck.urls")),
path("throw_error/", lambda x: 1 / 0),
path("admin/", admin.site.urls),
path("apply-for-a-license/", include("apply_for_a_licence.urls")),
path("apply-for-a-licence/", include("apply_for_a_licence.urls")),
path("cookies_consent", cookie_views.CookiesConsentView.as_view(), name="cookies_consent"),
path("hide_cookies", cookie_views.HideCookiesView.as_view(), name="hide_cookies"),
]
Expand Down
13 changes: 5 additions & 8 deletions django_app/core/views/base_views.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
from django.urls import reverse

from apply_for_a_licence.utils import get_dirty_form_data
from django.http import HttpRequest, HttpResponse, Http404
from core.sites import is_apply_for_a_licence_site, is_view_a_licence_site
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views.generic import FormView, RedirectView
from django_ratelimit.exceptions import Ratelimited

from core.sites import is_apply_for_a_licence_site, is_view_a_licence_site


class BaseFormView(FormView):
template_name = "core/base_form_step.html"
Expand Down Expand Up @@ -72,18 +70,17 @@ def rate_limited_view(request: HttpRequest, exception: Ratelimited) -> HttpRespo


class RedirectBaseDomainView(RedirectView):
"""Redirects base url visits to either apply-for-a-license or view-a-license default view"""
"""Redirects base url visits to either apply-for-a-licence or view-a-licence default view"""

@property
def url(self) -> str:
if is_apply_for_a_licence_site(self.request.site):
return reverse("start")
elif is_view_a_licence_site(self.request.site):
# if users are not accessing a specific page in view-a-license - raise a 404
# if users are not accessing a specific page in view-a-licence - raise a 404
# unless they are staff, in which case take them to the manage users page
if self.request.user.is_staff:
return "/"
else:
raise Http404()
return ""

22 changes: 22 additions & 0 deletions django_app/utils/s3.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Any, List

from core.document_storage import PermanentDocumentStorage, TemporaryDocumentStorage
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase
from django.core.cache import cache
from django.http import HttpRequest
from django.urls import reverse
from storages.backends.s3boto3 import S3Boto3Storage

Expand Down Expand Up @@ -73,3 +75,23 @@ def get_user_uploaded_files(session: SessionBase) -> List[str]:
cache_keys = list(cache.iter_keys(f"{session.session_key}*"))
uploaded_files = [file_name for key, file_name in cache.get_many(cache_keys).items()]
return uploaded_files


def store_documents_in_s3(request: HttpRequest, licence_id: str) -> None:
"""
Copies documents from the default temporary storage to permanent storage on s3
"""
temporary_storage_bucket = TemporaryDocumentStorage()
permanent_storage_bucket = PermanentDocumentStorage()

if session_files := get_all_session_files(temporary_storage_bucket, request.session):
for object_key in session_files.keys():
permanent_storage_bucket.bucket.meta.client.copy(
CopySource={
"Bucket": settings.TEMPORARY_S3_BUCKET_NAME,
"Key": f"{request.session.session_key}/{object_key}",
},
Bucket=settings.PERMANENT_S3_BUCKET_NAME,
Key=f"{licence_id}/{object_key}",
SourceClient=temporary_storage_bucket.bucket.meta.client,
)
6 changes: 3 additions & 3 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def test(context: Any) -> None:


@task
def unit_tests(context: Any) -> None:
def unittests(context: Any) -> None:
context.run("pipenv run pytest tests/test_unit")


Expand All @@ -21,13 +21,13 @@ def frontend_tests(context: Any) -> None:
@task
def makemigrations(context: Any) -> None:
print("Running manage.py makemigrations")
context.run(f"pipenv run python django_app/manage.py makemigrations")
context.run("pipenv run python django_app/manage.py makemigrations")


@task
def migrate(context: Any) -> None:
print("Running manage.py migrate")
base_command = f"pipenv run python django_app/manage.py migrate"
base_command = "pipenv run python django_app/manage.py migrate"
context.run(base_command)


Expand Down
Empty file.
Loading

0 comments on commit c3bbe31

Please sign in to comment.