From 648e3d52302397b4aa59a32fd4d533547ef00795 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 22 Oct 2020 16:32:35 +0200 Subject: [PATCH 01/43] Add openair generator in SensitiveArea Model --- geotrek/sensitivity/models.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/geotrek/sensitivity/models.py b/geotrek/sensitivity/models.py index bb92e5ebcd..c164f2c343 100644 --- a/geotrek/sensitivity/models.py +++ b/geotrek/sensitivity/models.py @@ -15,6 +15,7 @@ from geotrek.common.mixins import (OptionalPictogramMixin, NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin) from geotrek.common.utils import intersecting, classproperty from geotrek.core.models import simplify_coords +from pyopenair.factory import wkt2openair class SportPractice(models.Model): @@ -177,6 +178,38 @@ def kml(self): line.style.linestyle.width = 4 # pixels return kml.kml() + def openair(self): + """Exports sensitivearea into OpenAir format""" + geom = self.geom + if geom.geom_type == 'Point': + geom = geom.buffer(self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, 4) + if self.species.radius: + geometry = () + for coords in geom.coords[0]: + coords += (self.species.radius, ) + geometry += (coords, ) + geom = GEOSGeometry(Polygon(geometry), srid=settings.SRID) + geom = geom.transform(4326, clone=True) # KML uses WGS84 + geom = geom.simplify(0.001, preserve_topology=True) + wkt = geom.wkt + openair = wkt2openair(wkt, self.species.name) + print('OPENAIR', openair) + return openair + + @property + def wgs84_geom(self): + geom = self.geom + if geom.geom_type == 'Point': + geom = geom.buffer(self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, 4) + if self.species.radius: + geometry = () + for coords in geom.coords[0]: + coords += (self.species.radius, ) + geometry += (coords, ) + geom = GEOSGeometry(Polygon(geometry), srid=settings.SRID) + geom = geom.transform(4326, clone=True) # KML uses WGS84 + return geom + def is_public(self): return self.published From 197e16179cb7e4334e1ce0d15d92b550c7a81b55 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 22 Oct 2020 16:33:40 +0200 Subject: [PATCH 02/43] Add OpenAir SenitiveArea view (for aerial practices) --- geotrek/sensitivity/views.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 386e29e09b..1ba1c10234 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -4,6 +4,7 @@ from django.db.models import F, Case, When from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 +from django.utils.translation import ugettext_lazy as _ from django.views.generic.detail import BaseDetailView from mapentity.views import (MapEntityCreate, MapEntityUpdate, MapEntityLayer, MapEntityList, MapEntityDetail, MapEntityDelete, MapEntityViewSet, MapEntityFormat, LastModifiedMixin) @@ -15,7 +16,7 @@ from geotrek.common.views import PublicOrReadPermMixin from .filters import SensitiveAreaFilterSet from .forms import SensitiveAreaForm, RegulatorySensitiveAreaForm -from .models import SensitiveArea, Species +from .models import SensitiveArea, Species, SportPractice from .serializers import SensitiveAreaSerializer, SensitiveAreaGeojsonSerializer if 'geotrek.trekking' in settings.INSTALLED_APPS: @@ -181,3 +182,21 @@ def render_to_response(self, context): response = HttpResponse(area.kml(), content_type='application/vnd.google-earth.kml+xml') return response + +class SensitiveAreaOpenAirDetail(LastModifiedMixin, PublicOrReadPermMixin, BaseDetailView): + queryset = SensitiveArea.objects.existing() + + def render_to_response(self, context): + area = self.get_object() + aerial_practice=SportPractice.objects.get(name='Aerien') + is_aerial = aerial_practice.species_set.filter(id=area.id).exists() + if is_aerial: + result = area.openair() + response = HttpResponse(result, content_type='application/octet-stream; charset=UTF-8') + response['Content-Disposition'] = 'inline; filename=sensitivearea_openair_' + str(area.id) + '.txt' + return response + else: + message = _('This is not an aerial area') + response = HttpResponse(message, content_type='text/plain; charset=UTF-8') + + return response From 85ae35f761f02237d033c8d0a234e3263072d388 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 22 Oct 2020 16:34:05 +0200 Subject: [PATCH 03/43] Add OpenAir SenitiveArea url (by area) --- geotrek/sensitivity/urls.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/geotrek/sensitivity/urls.py b/geotrek/sensitivity/urls.py index 9bceed8ddb..5a07794841 100644 --- a/geotrek/sensitivity/urls.py +++ b/geotrek/sensitivity/urls.py @@ -24,6 +24,8 @@ def get_queryset(self): urlpatterns = [ path('api//sensitiveareas/.kml', views.SensitiveAreaKMLDetail.as_view(), name="sensitivearea_kml_detail"), + path('api//sensitiveareas//openair', + views.SensitiveAreaOpenAirDetail.as_view(), name="sensitivearea_openair_detail"), ] if 'geotrek.trekking' in settings.INSTALLED_APPS: urlpatterns.append(path('api//treks//sensitiveareas.geojson', From e3b3957aac5e50713032c4ddaf082bd390419d14 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 26 Oct 2020 10:02:08 +0100 Subject: [PATCH 04/43] Add header comment on openair files --- geotrek/sensitivity/views.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 1ba1c10234..f54ca25690 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -1,19 +1,20 @@ import json import logging +from datetime import datetime + from django.conf import settings from django.db.models import F, Case, When from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ from django.views.generic.detail import BaseDetailView -from mapentity.views import (MapEntityCreate, MapEntityUpdate, MapEntityLayer, MapEntityList, MapEntityDetail, - MapEntityDelete, MapEntityViewSet, MapEntityFormat, LastModifiedMixin) from rest_framework import permissions as rest_permissions, viewsets from geotrek.api.v2.functions import Transform, Buffer, GeometryType, Area from geotrek.authent.decorators import same_structure_required - from geotrek.common.views import PublicOrReadPermMixin +from mapentity.views import (MapEntityCreate, MapEntityUpdate, MapEntityLayer, MapEntityList, MapEntityDetail, + MapEntityDelete, MapEntityViewSet, MapEntityFormat, LastModifiedMixin) from .filters import SensitiveAreaFilterSet from .forms import SensitiveAreaForm, RegulatorySensitiveAreaForm from .models import SensitiveArea, Species, SportPractice @@ -183,15 +184,21 @@ def render_to_response(self, context): content_type='application/vnd.google-earth.kml+xml') return response + class SensitiveAreaOpenAirDetail(LastModifiedMixin, PublicOrReadPermMixin, BaseDetailView): queryset = SensitiveArea.objects.existing() def render_to_response(self, context): area = self.get_object() - aerial_practice=SportPractice.objects.get(name='Aerien') + file_header = """* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website {scheme}://{domain} +* Usint pyopenair library (https://github.com/lpoaura/pyopenair) +* This file was created on: {timestamp} + + """.format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) + aerial_practice = SportPractice.objects.get(name='Aerien') is_aerial = aerial_practice.species_set.filter(id=area.id).exists() if is_aerial: - result = area.openair() + result = file_header + area.openair() response = HttpResponse(result, content_type='application/octet-stream; charset=UTF-8') response['Content-Disposition'] = 'inline; filename=sensitivearea_openair_' + str(area.id) + '.txt' return response From a8fbf3062876680046e549d9fd6532d9cfc31c17 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 27 Oct 2020 11:57:22 +0100 Subject: [PATCH 05/43] Add openair key to api v2 --- geotrek/api/v2/serializers.py | 13 ++++++++++++- geotrek/sensitivity/serializers.py | 6 +++++- geotrek/sensitivity/urls.py | 4 +--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/geotrek/api/v2/serializers.py b/geotrek/api/v2/serializers.py index 5006c78aa7..d0f4429f70 100644 --- a/geotrek/api/v2/serializers.py +++ b/geotrek/api/v2/serializers.py @@ -346,6 +346,7 @@ class SensitiveAreaListSerializer(DynamicFieldsMixin, serializers.ModelSerialize geometry = geo_serializers.GeometryField(read_only=True, source="geom2d_transformed", precision=7) species_id = serializers.SerializerMethodField(read_only=True) kml_url = serializers.SerializerMethodField(read_only=True) + openair_url = serializers.SerializerMethodField(read_only=True) def get_name(self, obj): return get_translation_or_dict('name', self, obj.species) @@ -371,11 +372,21 @@ def get_kml_url(self, obj): url = reverse('sensitivity:sensitivearea_kml_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) return self.context['request'].build_absolute_uri(url) + + def get_openair_url(self, obj): + aerial_practice = sensitivity_models.SportPractice.objects.get(name='Aerien') + is_aerial = aerial_practice.species_set.filter(id=obj.pk).exists() + if is_aerial: + url = reverse('sensitivity:sensitivearea_openair_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) + return self.context['request'].build_absolute_uri(url) + else: + return None + class Meta: model = sensitivity_models.SensitiveArea fields = ( 'id', 'url', 'name', 'elevation', 'description', 'period', 'contact', 'practices', 'info_url', - 'published', 'structure', 'species_id', 'kml_url', + 'published', 'structure', 'species_id', 'kml_url','openair_url', 'geometry', 'update_datetime', 'create_datetime' ) diff --git a/geotrek/sensitivity/serializers.py b/geotrek/sensitivity/serializers.py index 427336002a..45437e4f38 100644 --- a/geotrek/sensitivity/serializers.py +++ b/geotrek/sensitivity/serializers.py @@ -28,13 +28,17 @@ class Meta: class SensitiveAreaSerializer(TranslatedModelSerializer): species = SpeciesSerializer() kml_url = rest_serializers.SerializerMethodField(read_only=True) + openair_url = rest_serializers.SerializerMethodField(read_only=True) def get_kml_url(self, obj): return reverse('sensitivity:sensitivearea_kml_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) + def get_openair_url(self, obj): + return reverse('sensitivity:sensitivearea_openair_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) + class Meta: model = sensitivity_models.SensitiveArea - fields = ('id', 'species', 'description', 'contact', 'published', 'publication_date', 'kml_url') + fields = ('id', 'species', 'description', 'contact', 'published', 'publication_date', 'kml_url', 'openair_url') class SensitiveAreaGeojsonSerializer(GeoFeatureModelSerializer, SensitiveAreaSerializer): diff --git a/geotrek/sensitivity/urls.py b/geotrek/sensitivity/urls.py index 5a07794841..e2a6b793d4 100644 --- a/geotrek/sensitivity/urls.py +++ b/geotrek/sensitivity/urls.py @@ -1,10 +1,8 @@ from django.conf import settings from django.urls import path, register_converter -from mapentity.registry import registry - from geotrek.common.urls import PublishableEntityOptions, LangConverter - +from mapentity.registry import registry from . import models from . import serializers from . import views From 94e60e39ff5facf08636fb3db999fde1557167fe Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 2 Nov 2020 11:37:31 +0100 Subject: [PATCH 06/43] add SENSITIVITY_DEFAULT_ELEVATION config --- geotrek/settings/base.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/geotrek/settings/base.py b/geotrek/settings/base.py index c7989fe2a4..df5337b214 100644 --- a/geotrek/settings/base.py +++ b/geotrek/settings/base.py @@ -645,6 +645,8 @@ def api_bbox(bbox, buffer): SENSITIVITY_DEFAULT_RADIUS = 100 # meters SENSITIVE_AREA_INTERSECTION_MARGIN = 500 # meters (always used) +SENSITIVITY_DEFAULT_ELEVATION = 300 # meters, only used when to generate openair files when sport practice is "Aerial" and elevation is null + PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', # Used for extern authent From a3a54f37133a10695d6b2c50726dfabd2208d87b Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 2 Nov 2020 16:51:55 +0100 Subject: [PATCH 07/43] Fix is_aerial check --- geotrek/api/v2/serializers.py | 3 +-- geotrek/sensitivity/views.py | 9 +++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/geotrek/api/v2/serializers.py b/geotrek/api/v2/serializers.py index d0f4429f70..00e1fe6259 100644 --- a/geotrek/api/v2/serializers.py +++ b/geotrek/api/v2/serializers.py @@ -374,8 +374,7 @@ def get_kml_url(self, obj): def get_openair_url(self, obj): - aerial_practice = sensitivity_models.SportPractice.objects.get(name='Aerien') - is_aerial = aerial_practice.species_set.filter(id=obj.pk).exists() + is_aerial = obj.species.practices.filter(name='Aerien').exists() if is_aerial: url = reverse('sensitivity:sensitivearea_openair_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) return self.context['request'].build_absolute_uri(url) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index f54ca25690..4f8b3da0fa 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -191,12 +191,9 @@ class SensitiveAreaOpenAirDetail(LastModifiedMixin, PublicOrReadPermMixin, BaseD def render_to_response(self, context): area = self.get_object() file_header = """* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website {scheme}://{domain} -* Usint pyopenair library (https://github.com/lpoaura/pyopenair) -* This file was created on: {timestamp} - - """.format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) - aerial_practice = SportPractice.objects.get(name='Aerien') - is_aerial = aerial_practice.species_set.filter(id=area.id).exists() +* Using pyopenair library (https://github.com/lpoaura/pyopenair) +* This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) + is_aerial = area.species.practices.filter(name='Aerien').exists() if is_aerial: result = file_header + area.openair() response = HttpResponse(result, content_type='application/octet-stream; charset=UTF-8') From 2efbb80b7a78df58e09661b291c475d359830a88 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 2 Nov 2020 16:52:16 +0100 Subject: [PATCH 08/43] Improve OpenAir transformation --- geotrek/sensitivity/models.py | 12 ++++++++++-- geotrek/settings/base.py | 1 - 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/geotrek/sensitivity/models.py b/geotrek/sensitivity/models.py index c164f2c343..f019bc5cbd 100644 --- a/geotrek/sensitivity/models.py +++ b/geotrek/sensitivity/models.py @@ -192,8 +192,16 @@ def openair(self): geom = geom.transform(4326, clone=True) # KML uses WGS84 geom = geom.simplify(0.001, preserve_topology=True) wkt = geom.wkt - openair = wkt2openair(wkt, self.species.name) - print('OPENAIR', openair) + openair = wkt2openair( + wkt = wkt, + an = self.species.name, + ac = 'ZSM', + ah_unit='m', + ah_alti = self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, + ah_mode='AGL', + al_mode='SFC', + comment=self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')' + ) return openair @property diff --git a/geotrek/settings/base.py b/geotrek/settings/base.py index df5337b214..08f4e83a74 100644 --- a/geotrek/settings/base.py +++ b/geotrek/settings/base.py @@ -645,7 +645,6 @@ def api_bbox(bbox, buffer): SENSITIVITY_DEFAULT_RADIUS = 100 # meters SENSITIVE_AREA_INTERSECTION_MARGIN = 500 # meters (always used) -SENSITIVITY_DEFAULT_ELEVATION = 300 # meters, only used when to generate openair files when sport practice is "Aerial" and elevation is null PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', From 0f5034a5de697958fee257955b103ef441feb11b Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 2 Nov 2020 22:56:24 +0100 Subject: [PATCH 09/43] Settings to filter OpenAir sport practices --- geotrek/api/v2/serializers.py | 2 +- geotrek/sensitivity/urls.py | 2 ++ geotrek/sensitivity/views.py | 24 +++++++++++++++++++++++- geotrek/settings/base.py | 1 + 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/geotrek/api/v2/serializers.py b/geotrek/api/v2/serializers.py index 00e1fe6259..7f3783fd23 100644 --- a/geotrek/api/v2/serializers.py +++ b/geotrek/api/v2/serializers.py @@ -374,7 +374,7 @@ def get_kml_url(self, obj): def get_openair_url(self, obj): - is_aerial = obj.species.practices.filter(name='Aerien').exists() + is_aerial = obj.species.practices.filter(name__in=settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES).exists() if is_aerial: url = reverse('sensitivity:sensitivearea_openair_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) return self.context['request'].build_absolute_uri(url) diff --git a/geotrek/sensitivity/urls.py b/geotrek/sensitivity/urls.py index e2a6b793d4..6d54a6e762 100644 --- a/geotrek/sensitivity/urls.py +++ b/geotrek/sensitivity/urls.py @@ -24,6 +24,8 @@ def get_queryset(self): views.SensitiveAreaKMLDetail.as_view(), name="sensitivearea_kml_detail"), path('api//sensitiveareas//openair', views.SensitiveAreaOpenAirDetail.as_view(), name="sensitivearea_openair_detail"), + path('api//sensitiveareas/openair', + views.SensitiveAreaOpenAirList.as_view(), name="sensitivearea_openair_list"), ] if 'geotrek.trekking' in settings.INSTALLED_APPS: urlpatterns.append(path('api//treks//sensitiveareas.geojson', diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 4f8b3da0fa..8c0a265de6 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -7,6 +7,7 @@ from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ +from django.views.generic import ListView from django.views.generic.detail import BaseDetailView from rest_framework import permissions as rest_permissions, viewsets @@ -193,7 +194,8 @@ def render_to_response(self, context): file_header = """* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website {scheme}://{domain} * Using pyopenair library (https://github.com/lpoaura/pyopenair) * This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) - is_aerial = area.species.practices.filter(name='Aerien').exists() + print('QUERY', settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES) + is_aerial = area.species.practices.filter(name__in=settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES).exists() if is_aerial: result = file_header + area.openair() response = HttpResponse(result, content_type='application/octet-stream; charset=UTF-8') @@ -204,3 +206,23 @@ def render_to_response(self, context): response = HttpResponse(message, content_type='text/plain; charset=UTF-8') return response + +class SensitiveAreaOpenAirList(PublicOrReadPermMixin, ListView): + + def get_queryset(self): + aerial_practice = SportPractice.objects.filter(name__in=settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES) + return SensitiveArea.objects.filter(species__practices__in=aerial_practice) + + def render_to_response(self, context): + areas = self.get_queryset() + file_header = """* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website {scheme}://{domain} +* Using pyopenair library (https://github.com/lpoaura/pyopenair) +* This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) + airspace_list = [] + for a in areas: + airspace_list.append(a.openair()) + airspace_core = '\n'.join(airspace_list) + airspace_file = file_header + airspace_core + response = HttpResponse(airspace_file, content_type='application/octet-stream; charset=UTF-8') + response['Content-Disposition'] = 'inline; filename=sensitivearea_openair.txt' + return response diff --git a/geotrek/settings/base.py b/geotrek/settings/base.py index 08f4e83a74..a798a98eef 100644 --- a/geotrek/settings/base.py +++ b/geotrek/settings/base.py @@ -645,6 +645,7 @@ def api_bbox(bbox, buffer): SENSITIVITY_DEFAULT_RADIUS = 100 # meters SENSITIVE_AREA_INTERSECTION_MARGIN = 500 # meters (always used) +SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Aerien',] # List of Sport practices name used to filter data to export in OpenAir PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', From 65d6eed0a9acc21035edd83c7471b2e7b1fb4b42 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 9 Nov 2020 16:53:54 +0100 Subject: [PATCH 10/43] Clean code --- geotrek/sensitivity/views.py | 1 - 1 file changed, 1 deletion(-) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 8c0a265de6..aeee18a83c 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -194,7 +194,6 @@ def render_to_response(self, context): file_header = """* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website {scheme}://{domain} * Using pyopenair library (https://github.com/lpoaura/pyopenair) * This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) - print('QUERY', settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES) is_aerial = area.species.practices.filter(name__in=settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES).exists() if is_aerial: result = file_header + area.openair() From 6b49d203e39edb8284f1b006687d43b417e3a395 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 9 Nov 2020 16:54:09 +0100 Subject: [PATCH 11/43] Add Openair descr --- geotrek/sensitivity/models.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/geotrek/sensitivity/models.py b/geotrek/sensitivity/models.py index f019bc5cbd..5f8911dc39 100644 --- a/geotrek/sensitivity/models.py +++ b/geotrek/sensitivity/models.py @@ -191,6 +191,8 @@ def openair(self): geom = GEOSGeometry(Polygon(geometry), srid=settings.SRID) geom = geom.transform(4326, clone=True) # KML uses WGS84 geom = geom.simplify(0.001, preserve_topology=True) + other = {} + other['*ADescr'] = self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')' wkt = geom.wkt openair = wkt2openair( wkt = wkt, @@ -200,7 +202,8 @@ def openair(self): ah_alti = self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, ah_mode='AGL', al_mode='SFC', - comment=self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')' + comment=self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')', + other = other ) return openair From a3bbad50fde8f9aaf017d59d3b1fa924401597f4 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 10 Nov 2020 15:17:35 +0100 Subject: [PATCH 12/43] Fix new line missing --- geotrek/sensitivity/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index aeee18a83c..a0ec8d22b3 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -220,7 +220,7 @@ def render_to_response(self, context): airspace_list = [] for a in areas: airspace_list.append(a.openair()) - airspace_core = '\n'.join(airspace_list) + airspace_core = '\n\n'.join(airspace_list) airspace_file = file_header + airspace_core response = HttpResponse(airspace_file, content_type='application/octet-stream; charset=UTF-8') response['Content-Disposition'] = 'inline; filename=sensitivearea_openair.txt' From 8c291b1f29abbd253833a89bab34f80b48d4e9f5 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 10 Nov 2020 15:17:51 +0100 Subject: [PATCH 13/43] Add pyopenair lib to requirements --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 97978fe661..70a4f5ee41 100644 --- a/requirements.txt +++ b/requirements.txt @@ -100,3 +100,4 @@ xlrd==1.1.0 xmltodict==0.12.0 zipp==3.0.0 pdfimpose==1.1.0 +pyopenair==1.0.0 \ No newline at end of file From 2f01e8a2b44b8a7e4a29a18e36b5af8ebc29660c Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 11:29:48 +0200 Subject: [PATCH 14/43] feat: optionally off pagination --- geotrek/api/v2/pagination.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/geotrek/api/v2/pagination.py b/geotrek/api/v2/pagination.py index 714f4197da..670cb5549e 100644 --- a/geotrek/api/v2/pagination.py +++ b/geotrek/api/v2/pagination.py @@ -20,3 +20,17 @@ def get_paginated_response(self, data): ])) else: return super(StandardResultsSetPagination, self).get_paginated_response(data) + + def get_page_size(self): + if self.request.query_params.get('no_page_size'): + return None + else: + return 100 + + + def get_max_page_size(self): + if self.request.query_params.get('no_page_size'): + return None + else: + return 1000 + From 03d7532145644e78e656f6eee1a4ed7c614329f7 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 11:30:21 +0200 Subject: [PATCH 15/43] feat: add some info to OpenAir export --- geotrek/sensitivity/helpers.py | 39 +++++++++++++++++++++++++++++++++ geotrek/sensitivity/models.py | 40 ++++++++++++++++------------------ 2 files changed, 58 insertions(+), 21 deletions(-) create mode 100644 geotrek/sensitivity/helpers.py diff --git a/geotrek/sensitivity/helpers.py b/geotrek/sensitivity/helpers.py new file mode 100644 index 0000000000..19f0a67d95 --- /dev/null +++ b/geotrek/sensitivity/helpers.py @@ -0,0 +1,39 @@ +from datetime import date +from calendar import monthrange + + +def openair_atimes(month: int) -> str: + """Format month number to OpenAir ATime item + + :param month: [description] + :type month: [type] + :return: [description] + :rtype: [type] + """ + year=date.today().year + str_lmonth = str(monthrange(year, month)[1]).zfill(2) + str_month = str(month).zfill(2) + tpl = '"{m}": ["UTC(01/{str_month}->{str_lmonth}/{str_month})", "ANY(00:00->23:59)"]' + return tpl.format(m=str(month),str_month=str_month,str_lmonth=str_lmonth) + +def openair_atimes_concat(row) -> str: + months_fields = [ + row.species.period01, + row.species.period02, + row.species.period03, + row.species.period04, + row.species.period05, + row.species.period06, + row.species.period07, + row.species.period08, + row.species.period09, + row.species.period10, + row.species.period11, + row.species.period12, + ] + aatimes_list = [] + for i in range(12): + if months_fields[i]: + aatimes_list.append(openair_atimes(i+1)) + return '{{{{{}}}}}'.format(','.join(aatimes_list)) + diff --git a/geotrek/sensitivity/models.py b/geotrek/sensitivity/models.py index 5f8911dc39..52eb16ed48 100644 --- a/geotrek/sensitivity/models.py +++ b/geotrek/sensitivity/models.py @@ -4,7 +4,7 @@ import datetime import simplekml - +import logging from django.conf import settings from django.contrib.gis.db import models from django.contrib.gis.geos import GEOSGeometry, Polygon @@ -16,7 +16,9 @@ from geotrek.common.utils import intersecting, classproperty from geotrek.core.models import simplify_coords from pyopenair.factory import wkt2openair +from geotrek.sensitivity.helpers import openair_atimes_concat +logger = logging.getLogger("geotrek") class SportPractice(models.Model): name = models.CharField(max_length=250, verbose_name=_("Name")) @@ -183,29 +185,25 @@ def openair(self): geom = self.geom if geom.geom_type == 'Point': geom = geom.buffer(self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, 4) - if self.species.radius: - geometry = () - for coords in geom.coords[0]: - coords += (self.species.radius, ) - geometry += (coords, ) - geom = GEOSGeometry(Polygon(geometry), srid=settings.SRID) - geom = geom.transform(4326, clone=True) # KML uses WGS84 + geom = geom.transform(4326, clone=True) geom = geom.simplify(0.001, preserve_topology=True) other = {} - other['*ADescr'] = self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')' + other['*AUID'] = "GUId=! UId=! Id=(Identifiant-GeoTrek-sentivity){{{{{id}}}}}".format(id=str(self.pk)) + other['*ADescr'] = "{name} (published on {published_date})".format(name=self.species.name, published_date=self.publication_date.strftime("%d/%m/%Y")) + other['*ATimes'] = openair_atimes_concat(self) wkt = geom.wkt - openair = wkt2openair( - wkt = wkt, - an = self.species.name, - ac = 'ZSM', - ah_unit='m', - ah_alti = self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, - ah_mode='AGL', - al_mode='SFC', - comment=self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')', - other = other - ) - return openair + data = { + 'wkt' : wkt, + 'an': self.species.name, + 'ac': 'ZSM', + 'ah_unit':'m', + 'ah_alti': self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, + 'ah_mode':'AGL', + 'al_mode':'SFC', + # 'comment': self.species.name + ' (published on '+self.publication_date.strftime("%d/%m/%Y")+')', + 'other': other + } + return wkt2openair(**data) @property def wgs84_geom(self): From d41bf98954e527d55e4663749cc43c49ac0ba127 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 11:30:32 +0200 Subject: [PATCH 16/43] fix: update pyopenair deps --- requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index 70a4f5ee41..1f3a217876 100644 --- a/requirements.txt +++ b/requirements.txt @@ -65,7 +65,7 @@ netifaces==0.10.9 openapi-codec==1.3.2 paperclip==2.2.5 Pillow==7.1.2 --no-binary Pillow -pkg-resources==0.0.0 +#pkg-resources==0.0.0 psycopg2==2.8.5 --no-binary psycopg2 public==2019.4.13 pycodestyle==2.5.0 @@ -100,4 +100,4 @@ xlrd==1.1.0 xmltodict==0.12.0 zipp==3.0.0 pdfimpose==1.1.0 -pyopenair==1.0.0 \ No newline at end of file +pyopenair==1.1.0 \ No newline at end of file From 3e0bb8b70afe2c255ac059f0b3b5f8f17bb485b3 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 14:50:23 +0200 Subject: [PATCH 17/43] fix: some OpenAir export fixes --- geotrek/sensitivity/helpers.py | 8 ++--- geotrek/sensitivity/parsers.py | 2 +- requirements.txt | 60 ++++++++++++++++++---------------- 3 files changed, 37 insertions(+), 33 deletions(-) diff --git a/geotrek/sensitivity/helpers.py b/geotrek/sensitivity/helpers.py index 19f0a67d95..33da5e4f7b 100644 --- a/geotrek/sensitivity/helpers.py +++ b/geotrek/sensitivity/helpers.py @@ -5,10 +5,10 @@ def openair_atimes(month: int) -> str: """Format month number to OpenAir ATime item - :param month: [description] - :type month: [type] - :return: [description] - :rtype: [type] + :param month: Months (1-12) + :type month: int + :return: ATimes item + :rtype: str """ year=date.today().year str_lmonth = str(monthrange(year, month)[1]).zfill(2) diff --git a/geotrek/sensitivity/parsers.py b/geotrek/sensitivity/parsers.py index 5371066225..d27f8e1ee6 100644 --- a/geotrek/sensitivity/parsers.py +++ b/geotrek/sensitivity/parsers.py @@ -8,7 +8,7 @@ class BiodivParser(Parser): model = SensitiveArea label = "Biodiv'Sports" - url = 'https://biodiv-sports.fr/api/v2/sensitivearea/?format=json&bubble&period=ignore&page_size=10000' + url = 'https://biodiv-sports.fr/api/v2/sensitivearea/?format=json&bubble&period=ignore&page_size=100' eid = 'eid' separator = None delete = True diff --git a/requirements.txt b/requirements.txt index 1f3a217876..0b20476c1e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,52 +1,53 @@ amqp==2.5.2 -appy-python-3==2019.11.19 +appy==1.0.7 beautifulsoup4==4.9.0 billiard==3.6.3.0 cairocffi==0.9.0 -CairoSVG==2.4.2 +CairoSVG==2.5.1 celery==4.4.2 certifi==2019.11.28 -cffi==1.14.0 +cffi==1.14.3 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 coverage==4.5.3 -cryptography==2.8 +cryptography==3.3.2 cssselect2==0.2.2 defusedxml==0.6.0 -Django==2.2.* +Django==3.1.* django-appconf==1.0.3 -django-appypod==2.0.4 +django-appypod==2.0.7 django-celery-results==1.0.1 django-colorfield==0.3.0 django-compressor==2.4 -django-crispy-forms==1.9.0 -django-debug-toolbar==2.2 +django-crispy-forms==1.11.2 +django-debug-toolbar==3.2.1 django-embed-video==1.3.1 django-extended-choices==1.3 django-extensions==2.2.9 -django-filter==2.2.0 -django-geojson==2.11.0 -git+https://github.com/GeotrekCE/django-leaflet.git@0.19.0+geotrek7#egg=django-leaflet -django-modeltranslation==0.13.4 -django-multiselectfield==0.1.5 -django-rest-swagger==2.2.0 # TODO: deprecated, replace with drf-yasg +django-filter==2.4.0 +django-geojson==3.1.0 +django-js-asset==1.2.2 +git+https://github.com/chibisov/drf-extensions.git@19efac2ede0eef82aac4785d47a405454fb48225#egg=drf-extensions +git+https://github.com/GeotrekCE/django-leaflet.git@0.19+geotrek8#egg=django-leaflet +django-modelcluster==5.1 +django-modeltranslation==0.15.2 +django-mptt==0.11.0 django-tinymce==2.8.0 -django-weasyprint==0.5.4 -djangorestframework==3.11.0 -djangorestframework-gis==0.15 +django-weasyprint==0.5.5 +djangorestframework==3.12.2 +djangorestframework-gis==0.16 docutils==0.16 drf-dynamic-fields==0.3.1 -drf-extensions==0.5.0 +drf-yasg==1.20.0 easy-thumbnails==2.7 entrypoints==0.3 env-file==2019.4.13 -factory-boy==2.8.1 -Faker==4.0.1 +factory-boy==3.2.0 +Faker==6.0.0 +Fiona==1.8.17 flake8==3.7.9 freezegun==0.3.15 -future==0.18.2 -GDAL==2.2.4 geojson==2.3.0 gpxpy==1.4.0 gunicorn==20.0.4 @@ -54,10 +55,10 @@ html5lib==1.0.1 idna==2.8 importlib-metadata==1.5.0 itypes==1.1.0 -Jinja2==2.11.1 +Jinja2==2.11.3 kombu==4.6.8 landez==2.5.0 -lxml==4.2.1 +lxml==4.6.3 MarkupSafe==1.1.1 mbutil==0.3.0 mccabe==0.6.1 @@ -73,18 +74,21 @@ pycparser==2.19 pyflakes==2.1.1 pygal==2.4.0 pyOpenSSL==19.1.0 +pyparsing==2.4.7 Pyphen==0.9.5 python-dateutil==2.8.1 python-memcached==1.59 pytz==2019.3 raven==6.10.0 +sentry-sdk==1.0.0 rcssmin==1.0.6 redis==3.4.1 requests[security]==2.23.0 rjsmin==1.1.0 +ruamel.yaml==0.16.12 +ruamel.yaml.clib==0.2.2 simplejson==3.17.0 -simplekml==1.3.0 -six==1.14.0 +simplekml==1.3.5 sqlparse==0.3.0 text-unidecode==1.3 tif2geojson==0.1.3 @@ -94,9 +98,9 @@ urllib3==1.25.8 values==2019.4.13 venusian==1.2.0 vine==1.3.0 -WeasyPrint==51 +WeasyPrint==52.5 webencodings==0.5.1 -xlrd==1.1.0 +xlrd==1.2.0 xmltodict==0.12.0 zipp==3.0.0 pdfimpose==1.1.0 From 690b6c5d28abbead3e5705a69e8b80129b432419 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 14:57:58 +0200 Subject: [PATCH 18/43] feat: optionnally disable pagination --- geotrek/api/v2/pagination.py | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/geotrek/api/v2/pagination.py b/geotrek/api/v2/pagination.py index 670cb5549e..bd58384f3b 100644 --- a/geotrek/api/v2/pagination.py +++ b/geotrek/api/v2/pagination.py @@ -5,7 +5,7 @@ class StandardResultsSetPagination(PageNumberPagination): - page_size = 100 + page_size = 50 page_size_query_param = 'page_size' max_page_size = 1000 @@ -19,18 +19,10 @@ def get_paginated_response(self, data): ('features', data['features']) ])) else: - return super(StandardResultsSetPagination, self).get_paginated_response(data) + return super().get_paginated_response(data) - def get_page_size(self): - if self.request.query_params.get('no_page_size'): + def paginate_queryset(self, queryset, request, view=None): + if 'no_page' in request.query_params: return None - else: - return 100 - - - def get_max_page_size(self): - if self.request.query_params.get('no_page_size'): - return None - else: - return 1000 + return super().paginate_queryset(queryset, request, view) From 1994979138344456b0866fd3b6ab7fb634394719 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 14:58:27 +0200 Subject: [PATCH 19/43] fix: revert to master --- geotrek/sensitivity/parsers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/geotrek/sensitivity/parsers.py b/geotrek/sensitivity/parsers.py index d27f8e1ee6..0edbbe87f1 100644 --- a/geotrek/sensitivity/parsers.py +++ b/geotrek/sensitivity/parsers.py @@ -8,7 +8,7 @@ class BiodivParser(Parser): model = SensitiveArea label = "Biodiv'Sports" - url = 'https://biodiv-sports.fr/api/v2/sensitivearea/?format=json&bubble&period=ignore&page_size=100' + url = 'https://biodiv-sports.fr/api/v2/sensitivearea/?format=json&bubble&period=ignore' eid = 'eid' separator = None delete = True From 1ba9cb427226e868f27c1be268a4d4e947a9fcf8 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 25 May 2021 15:00:20 +0200 Subject: [PATCH 20/43] fix: restore requirements versions --- requirements.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/requirements.txt b/requirements.txt index 0b20476c1e..1f10b1debd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -64,9 +64,8 @@ mbutil==0.3.0 mccabe==0.6.1 netifaces==0.10.9 openapi-codec==1.3.2 -paperclip==2.2.5 -Pillow==7.1.2 --no-binary Pillow -#pkg-resources==0.0.0 +paperclip==2.2.6 +Pillow==8.1.1 --no-binary Pillow psycopg2==2.8.5 --no-binary psycopg2 public==2019.4.13 pycodestyle==2.5.0 From 49f71cf65d53b62c34ab2ab0372712eb2ee1b63e Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 26 Aug 2021 10:14:08 +0200 Subject: [PATCH 21/43] fix: fix codestyle E231, E261 --- geotrek/settings/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/geotrek/settings/base.py b/geotrek/settings/base.py index 92bb6b48d9..7696dc16a2 100644 --- a/geotrek/settings/base.py +++ b/geotrek/settings/base.py @@ -656,7 +656,7 @@ def api_bbox(bbox, buffer): SENSITIVITY_DEFAULT_RADIUS = 100 # meters SENSITIVE_AREA_INTERSECTION_MARGIN = 500 # meters (always used) -SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Aerien',] # List of Sport practices name used to filter data to export in OpenAir +SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Aerien', ] # List of Sport practices name used to filter data to export in OpenAir PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', From 07550c009351dbe1ab136473be9cac35a81fdf43 Mon Sep 17 00:00:00 2001 From: Fred C Date: Thu, 9 Jun 2022 16:17:18 +0200 Subject: [PATCH 22/43] fix merge --- geotrek/sensitivity/serializers.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/geotrek/sensitivity/serializers.py b/geotrek/sensitivity/serializers.py index de46567a5f..609b1b7307 100644 --- a/geotrek/sensitivity/serializers.py +++ b/geotrek/sensitivity/serializers.py @@ -38,12 +38,8 @@ class Meta: class SensitiveAreaAPISerializer(TranslatedModelSerializer): species = SpeciesSerializer() -<<<<<<< HEAD - kml_url = rest_serializers.SerializerMethodField(read_only=True) - openair_url = rest_serializers.SerializerMethodField(read_only=True) -======= kml_url = rest_serializers.SerializerMethodField() ->>>>>>> upstream/master + openair_url = rest_serializers.SerializerMethodField() def get_kml_url(self, obj): return reverse('sensitivity:sensitivearea_kml_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) From 5cb5bafece877f172dfcb1fb4b05747475ca58ed Mon Sep 17 00:00:00 2001 From: Fred C Date: Mon, 11 Jul 2022 11:29:05 +0200 Subject: [PATCH 23/43] apply .gitignore --- bulkimport/parsers.py | 1 + 1 file changed, 1 insertion(+) create mode 120000 bulkimport/parsers.py diff --git a/bulkimport/parsers.py b/bulkimport/parsers.py new file mode 120000 index 0000000000..b639482a50 --- /dev/null +++ b/bulkimport/parsers.py @@ -0,0 +1 @@ +/app/src/var/conf/parsers.py \ No newline at end of file From 681d1f62ab22c3f6b6c7653882ddd4b54f8658cb Mon Sep 17 00:00:00 2001 From: Fred C Date: Wed, 7 Dec 2022 15:04:02 +0100 Subject: [PATCH 24/43] fix tests --- geotrek/api/tests/test_v2.py | 2 +- geotrek/sensitivity/tests/factories.py | 2 +- geotrek/sensitivity/tests/test_functional.py | 4 ++++ geotrek/sensitivity/tests/test_parsers.py | 2 ++ geotrek/sensitivity/tests/test_views.py | 10 +++++++++- 5 files changed, 17 insertions(+), 3 deletions(-) diff --git a/geotrek/api/tests/test_v2.py b/geotrek/api/tests/test_v2.py index 4ed2afc389..846b99ddac 100644 --- a/geotrek/api/tests/test_v2.py +++ b/geotrek/api/tests/test_v2.py @@ -156,7 +156,7 @@ SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE = sorted([ 'id', 'contact', 'create_datetime', 'description', 'elevation', 'geometry', - 'info_url', 'kml_url', 'name', 'period', 'practices', 'published', 'species_id', + 'info_url', 'kml_url', 'openair_url', 'name', 'period', 'practices', 'published', 'species_id', 'structure', 'update_datetime', 'url' ]) diff --git a/geotrek/sensitivity/tests/factories.py b/geotrek/sensitivity/tests/factories.py index dbe4f296ba..a6d558042a 100644 --- a/geotrek/sensitivity/tests/factories.py +++ b/geotrek/sensitivity/tests/factories.py @@ -34,7 +34,7 @@ def practices(obj, create, extracted=None, **kwargs): if not extracted: practices = [ SportPracticeFactory.create(name="Practice1"), - SportPracticeFactory.create(name="Practice2") + SportPracticeFactory.create(name="Practice2"), ] for practice in practices: obj.practices.add(practice) diff --git a/geotrek/sensitivity/tests/test_functional.py b/geotrek/sensitivity/tests/test_functional.py index d4cd5495c4..3307bf3b98 100644 --- a/geotrek/sensitivity/tests/test_functional.py +++ b/geotrek/sensitivity/tests/test_functional.py @@ -19,11 +19,14 @@ class SensitiveAreaViewsTests(GeotrekAPITestCase, CommonTest): } extra_column_list = ['description', 'contact'] + def get_expected_json_attrs(self): + return { 'contact': 'toto@tata.com', 'description': 'Blabla', 'kml_url': '/api/en/sensitiveareas/{}.kml'.format(self.obj.pk), + 'openair_url': '/api/en/sensitiveareas/{}/openair'.format(self.obj.pk), 'publication_date': '2020-03-17', 'published': True, 'species': { @@ -94,6 +97,7 @@ def get_expected_json_attrs(self): 'contact': 'toto@tata.com', 'description': 'Blabla', 'kml_url': '/api/en/sensitiveareas/{}.kml'.format(self.obj.pk), + 'openair_url': '/api/en/sensitiveareas/{}/openair'.format(self.obj.pk), 'publication_date': '2020-03-17', 'published': True, 'species': { diff --git a/geotrek/sensitivity/tests/test_parsers.py b/geotrek/sensitivity/tests/test_parsers.py index cd843afb3f..3c13d0075c 100644 --- a/geotrek/sensitivity/tests/test_parsers.py +++ b/geotrek/sensitivity/tests/test_parsers.py @@ -72,6 +72,7 @@ "structure": "LPO", "species_id": 7, "kml_url": "https://biodiv-sports.fr/api/fr/sensitiveareas/46.kml", + "openair_url": "https://biodiv-sports.fr/api/fr/sensitiveareas/46/openair", "geometry": { "type": "Polygon", "coordinates": [[[3.1, 45], [3.2, 45], [3.2, 46], [3.1, 46], [3.1, 45]], @@ -102,6 +103,7 @@ "structure": "LPO", "species_id": 7, "kml_url": "https://biodiv-sports.fr/api/fr/sensitiveareas/47.kml", + "openair_url": "https://biodiv-sports.fr/api/fr/sensitiveareas/47/openair", "geometry": { "type": "MultiPolygon", "coordinates": [[[[3.1, 45], [3.2, 45], [3.2, 46], [3.1, 46], [3.1, 45]], diff --git a/geotrek/sensitivity/tests/test_views.py b/geotrek/sensitivity/tests/test_views.py index 7fafa09971..dce97e0fd1 100644 --- a/geotrek/sensitivity/tests/test_views.py +++ b/geotrek/sensitivity/tests/test_views.py @@ -2,6 +2,7 @@ from django.contrib.auth.models import User, Permission from django.test import TestCase +from django.test.utils import override_settings from geotrek.authent.tests.factories import StructureFactory, UserProfileFactory from geotrek.authent.tests.base import AuthentFixturesTest @@ -91,6 +92,7 @@ def setUp(self): "elevation": None, 'contact': 'toto@tata.com', 'kml_url': 'http://testserver/api/en/sensitiveareas/{pk}.kml'.format(pk=self.pk), + 'openair_url': 'http://testserver/api/en/sensitiveareas/{pk}/openair'.format(pk=self.pk), 'info_url': self.species.url, 'species_id': self.species.id, "name": self.species.name, @@ -122,17 +124,20 @@ def setUp(self): } self.expected_geo_result['properties']['url'] = 'http://testserver/api/v2/sensitivearea/{}/?format=geojson'.format(self.pk) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) def test_detail_sensitivearea(self): url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=self.pk) response = self.client.get(url) self.assertJSONEqual(response.content.decode(), self.expected_result) - + + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) def test_detail_sensitivearea_regulatory(self): self.sensitivearea = RegulatorySensitiveAreaFactory.create(species__period01=True) url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=self.sensitivearea.pk) response = self.client.get(url) self.assertIsNone(response.json()['species_id']) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) def test_list_sensitivearea(self): url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en' response = self.client.get(url) @@ -143,11 +148,13 @@ def test_list_sensitivearea(self): 'results': [self.expected_result], }) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) def test_geo_detail_sensitivearea(self): url = '/api/v2/sensitivearea/{pk}/?format=geojson&period=ignore&language=en'.format(pk=self.pk) response = self.client.get(url) self.assertJSONEqual(response.content.decode(), self.expected_geo_result) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) def test_geo_list_sensitivearea(self): url = '/api/v2/sensitivearea/?format=geojson&period=ignore&language=en' response = self.client.get(url) @@ -191,6 +198,7 @@ def test_multipolygon(self): response = self.client.get(url) self.assertEqual(response.json()['geometry'], expected_geom) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) def test_list_bubble_sensitivearea(self): url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en&bubble=True' response = self.client.get(url) From de928aa48553ed7455b82f5cd86d9f8c816a350d Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 2 Feb 2023 00:14:29 +0100 Subject: [PATCH 25/43] lint --- geotrek/api/tests/test_v2.py | 4 ++-- geotrek/api/v2/pagination.py | 1 - geotrek/sensitivity/helpers.py | 10 +++++----- geotrek/sensitivity/tests/test_functional.py | 3 +-- geotrek/sensitivity/tests/test_views.py | 14 +++++++------- geotrek/sensitivity/views.py | 1 + 6 files changed, 16 insertions(+), 17 deletions(-) diff --git a/geotrek/api/tests/test_v2.py b/geotrek/api/tests/test_v2.py index 9619e3a0f0..dd890fd7ed 100644 --- a/geotrek/api/tests/test_v2.py +++ b/geotrek/api/tests/test_v2.py @@ -162,8 +162,8 @@ SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE = sorted([ 'id', 'contact', 'create_datetime', 'description', 'elevation', 'geometry', - 'info_url', 'kml_url', 'openair_url', 'name', 'period', 'practices', 'provider', 'published', - 'species_id','structure', 'update_datetime', 'url', 'attachments' + 'info_url', 'kml_url', 'openair_url', 'name', 'period', 'practices', 'provider', 'published', + 'species_id', 'structure', 'update_datetime', 'url', 'attachments' ]) SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE = sorted([ diff --git a/geotrek/api/v2/pagination.py b/geotrek/api/v2/pagination.py index ec2bcb0e67..f700ed2680 100644 --- a/geotrek/api/v2/pagination.py +++ b/geotrek/api/v2/pagination.py @@ -36,4 +36,3 @@ def paginate_queryset(self, queryset, request, view=None): if 'no_page' in request.query_params: return None return super().paginate_queryset(queryset, request, view) - diff --git a/geotrek/sensitivity/helpers.py b/geotrek/sensitivity/helpers.py index 33da5e4f7b..61013f8ec3 100644 --- a/geotrek/sensitivity/helpers.py +++ b/geotrek/sensitivity/helpers.py @@ -3,18 +3,19 @@ def openair_atimes(month: int) -> str: - """Format month number to OpenAir ATime item + """Format month number to OpenAir ATime item :param month: Months (1-12) :type month: int :return: ATimes item :rtype: str """ - year=date.today().year + year = date.today().year str_lmonth = str(monthrange(year, month)[1]).zfill(2) str_month = str(month).zfill(2) tpl = '"{m}": ["UTC(01/{str_month}->{str_lmonth}/{str_month})", "ANY(00:00->23:59)"]' - return tpl.format(m=str(month),str_month=str_month,str_lmonth=str_lmonth) + return tpl.format(m=str(month), str_month=str_month, str_lmonth=str_lmonth) + def openair_atimes_concat(row) -> str: months_fields = [ @@ -34,6 +35,5 @@ def openair_atimes_concat(row) -> str: aatimes_list = [] for i in range(12): if months_fields[i]: - aatimes_list.append(openair_atimes(i+1)) + aatimes_list.append(openair_atimes(i + 1)) return '{{{{{}}}}}'.format(','.join(aatimes_list)) - diff --git a/geotrek/sensitivity/tests/test_functional.py b/geotrek/sensitivity/tests/test_functional.py index 32df397daa..19e0f07461 100644 --- a/geotrek/sensitivity/tests/test_functional.py +++ b/geotrek/sensitivity/tests/test_functional.py @@ -19,9 +19,8 @@ class SensitiveAreaViewsTests(GeotrekAPITestCase, CommonTest): } extra_column_list = ['description', 'contact'] - def get_expected_json_attrs(self): - + return { 'attachments': [], 'contact': 'toto@tata.com', diff --git a/geotrek/sensitivity/tests/test_views.py b/geotrek/sensitivity/tests/test_views.py index 1b8814174b..30e1e8b876 100644 --- a/geotrek/sensitivity/tests/test_views.py +++ b/geotrek/sensitivity/tests/test_views.py @@ -126,20 +126,20 @@ def setUp(self): } self.expected_geo_result['properties']['url'] = 'http://testserver/api/v2/sensitivearea/{}/?format=geojson'.format(self.pk) - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_detail_sensitivearea(self): url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=self.pk) response = self.client.get(url) self.assertJSONEqual(response.content.decode(), self.expected_result) - - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) + + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_detail_sensitivearea_regulatory(self): self.sensitivearea = RegulatorySensitiveAreaFactory.create(species__period01=True) url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=self.sensitivearea.pk) response = self.client.get(url) self.assertIsNone(response.json()['species_id']) - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_list_sensitivearea(self): url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en' response = self.client.get(url) @@ -150,13 +150,13 @@ def test_list_sensitivearea(self): 'results': [self.expected_result], }) - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_geo_detail_sensitivearea(self): url = '/api/v2/sensitivearea/{pk}/?format=geojson&period=ignore&language=en'.format(pk=self.pk) response = self.client.get(url) self.assertJSONEqual(response.content.decode(), self.expected_geo_result) - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_geo_list_sensitivearea(self): url = '/api/v2/sensitivearea/?format=geojson&period=ignore&language=en' response = self.client.get(url) @@ -200,7 +200,7 @@ def test_multipolygon(self): response = self.client.get(url) self.assertEqual(response.json()['geometry'], expected_geom) - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES = ['Practice1', ]) + @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_list_bubble_sensitivearea(self): url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en&bubble=True' response = self.client.get(url) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 7aaa679af8..58fc7c629b 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -206,6 +206,7 @@ def render_to_response(self, context): return response + class SensitiveAreaOpenAirList(PublicOrReadPermMixin, ListView): def get_queryset(self): From 43828885fbfdc15db580f0e4e456cfe630186cc2 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 2 Feb 2023 00:35:33 +0100 Subject: [PATCH 26/43] update requirements --- requirements.txt | 7 ++++++- setup.py | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 99a260c7fd..a77494a077 100644 --- a/requirements.txt +++ b/requirements.txt @@ -222,6 +222,7 @@ numpy==1.23.4 # via # large-image # large-image-source-vips + # shapely packaging==21.3 # via # drf-yasg @@ -261,6 +262,8 @@ pygal==3.0.0 # via geotrek (setup.py) pymemcache==3.5.2 # via geotrek (setup.py) +pyopenair==1.2.0 + # via geotrek (setup.py) pyparsing==3.0.8 # via packaging pypdf2==1.27.5 @@ -295,6 +298,8 @@ ruamel-yaml-clib==0.2.6 # via ruamel-yaml sentry-sdk==1.14.0 # via geotrek (setup.py) +shapely==2.0.1 + # via pyopenair simplekml==1.3.6 # via geotrek (setup.py) six==1.16.0 @@ -368,6 +373,6 @@ zope-interface==5.4.0 # persistent # transaction # zodb -pyopenair==1.2.0 + # The following packages are considered to be unsafe in a requirements file: # setuptools diff --git a/setup.py b/setup.py index 12c7bab160..0a12dbf876 100644 --- a/setup.py +++ b/setup.py @@ -67,6 +67,7 @@ def run(self): "weasyprint==52.5", # newer version required libpango (not available in bionic) 'django-weasyprint<2.0.0', # 2.10 require weasyprint > 53 "django-clearcache", + "pyopenair", # prod, 'gunicorn', 'sentry-sdk', From ffad600a86e6b68622399640b05596e0c924da2c Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 2 Feb 2023 00:53:33 +0100 Subject: [PATCH 27/43] reviews fixes #3349 --- geotrek/sensitivity/models.py | 2 +- geotrek/sensitivity/parsers.py | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/geotrek/sensitivity/models.py b/geotrek/sensitivity/models.py index b65229f798..f687d7dbff 100644 --- a/geotrek/sensitivity/models.py +++ b/geotrek/sensitivity/models.py @@ -21,7 +21,7 @@ from geotrek.sensitivity.helpers import openair_atimes_concat from geotrek.core.models import simplify_coords -logger = logging.getLogger("geotrek") +logger = logging.getLogger(__name__) class SportPractice(TimeStampedModelMixin, models.Model): diff --git a/geotrek/sensitivity/parsers.py b/geotrek/sensitivity/parsers.py index 91089f7d85..52507a5b8c 100644 --- a/geotrek/sensitivity/parsers.py +++ b/geotrek/sensitivity/parsers.py @@ -34,7 +34,6 @@ class BiodivParser(Parser): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - print('URL', self.url) for lang in settings.MODELTRANSLATION_LANGUAGES: self.fields['description_' + lang] = 'description.' + lang From d9e714f955887f66146e06c9f956e06b47f883fa Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 2 Feb 2023 01:04:43 +0100 Subject: [PATCH 28/43] code cleanup --- .flake8 | 3 --- bulkimport/parsers.py | 1 - 2 files changed, 4 deletions(-) delete mode 100644 .flake8 delete mode 120000 bulkimport/parsers.py diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 8e16d4dc32..0000000000 --- a/.flake8 +++ /dev/null @@ -1,3 +0,0 @@ -[flake8] -ignore = E501,W503 -exclude = geotrek/settings,conf,env diff --git a/bulkimport/parsers.py b/bulkimport/parsers.py deleted file mode 120000 index b639482a50..0000000000 --- a/bulkimport/parsers.py +++ /dev/null @@ -1 +0,0 @@ -/app/src/var/conf/parsers.py \ No newline at end of file From d4b3c055136897272736c6c0dc1a49fce294cfaa Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 2 Feb 2023 09:37:39 +0100 Subject: [PATCH 29/43] update Changelog --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e8b4eb9649..36c31cacab 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,10 @@ CHANGELOG **Improvements** - Sensitivity: Add missing attachments list to sensitive areas API +- Sensitivity: Add ``openair`` export format for aerial sensitive areas. Usage example: + + - http://pascal.bazile.free.fr/paraglidingFolder/divers/GPS/OpenAir-Format/ + - https://www.data.gouv.fr/en/datasets/cartographies-aeriennes-dediees-a-la-pratique-du-vol-libre/ 2.96.0 (2023-02-01) From 6ced9d9f9eeffc9f9567aa69b2e8ef1a6f5dcc89 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Mon, 6 Feb 2023 09:57:04 +0100 Subject: [PATCH 30/43] update changelog --- docs/changelog.rst | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 36c31cacab..665fe73a56 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,10 +8,7 @@ CHANGELOG **Improvements** - Sensitivity: Add missing attachments list to sensitive areas API -- Sensitivity: Add ``openair`` export format for aerial sensitive areas. Usage example: - - - http://pascal.bazile.free.fr/paraglidingFolder/divers/GPS/OpenAir-Format/ - - https://www.data.gouv.fr/en/datasets/cartographies-aeriennes-dediees-a-la-pratique-du-vol-libre/ +- Sensitivity: Add ``openair`` export format for aerial sensitive areas (#2372) 2.96.0 (2023-02-01) From ddaee972f6a04574c11b9b816c6161934e844319 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 31 Aug 2023 14:04:37 +0200 Subject: [PATCH 31/43] senstivearea wgs84 transform test --- geotrek/sensitivity/tests/test_models.py | 109 +++++++++++++++-------- 1 file changed, 74 insertions(+), 35 deletions(-) diff --git a/geotrek/sensitivity/tests/test_models.py b/geotrek/sensitivity/tests/test_models.py index 499e2cea79..8a1a4eac47 100644 --- a/geotrek/sensitivity/tests/test_models.py +++ b/geotrek/sensitivity/tests/test_models.py @@ -3,13 +3,13 @@ from django.test import TestCase from django.test.utils import override_settings from django.conf import settings +from django.contrib.gis.geos import GEOSGeometry from geotrek.sensitivity.tests.factories import SensitiveAreaFactory, SpeciesFactory from geotrek.trekking.tests.factories import TrekFactory class SensitiveAreaModelTest(TestCase): - def test_specific_radius(self): specie = SpeciesFactory.create(radius=50) sensitive_area = SensitiveAreaFactory.create(species=specie) @@ -21,7 +21,9 @@ def test_no_radius(self): def test_get_lang_published(self): sensitive_area = SensitiveAreaFactory.create() - self.assertEqual(sensitive_area.published_langs, list(settings.MODELTRANSLATION_LANGUAGES)) + self.assertEqual( + sensitive_area.published_langs, list(settings.MODELTRANSLATION_LANGUAGES) + ) def test_get_lang_not_published(self): sensitive_area = SensitiveAreaFactory.create() @@ -30,7 +32,8 @@ def test_get_lang_not_published(self): def test_get_extent(self): sensitive_area = SensitiveAreaFactory.create( - geom='POLYGON((700000 6600000, 700000 6600100, 700100 6600100, 700100 6600000, 700000 6600000))') + geom="POLYGON((700000 6600000, 700000 6600100, 700100 6600100, 700100 6600000, 700000 6600000))" + ) lng_min, lat_min, lng_max, lat_max = sensitive_area.extent self.assertAlmostEqual(lng_min, 3) self.assertAlmostEqual(lat_min, 46.5) @@ -40,44 +43,56 @@ def test_get_extent(self): def test_get_kml(self): species = SpeciesFactory.create(radius=5) sensitive_area = SensitiveAreaFactory.create(species=species) - self.assertIn('3.0,46.5,5.0 3.0,46.500027,5.0 3.0000391,46.500027,5.0 ' - '3.0000391,46.5,5.0 3.0,46.5,5.0', - sensitive_area.kml()) + self.assertIn( + "3.0,46.5,5.0 3.0,46.500027,5.0 3.0000391,46.500027,5.0 " + "3.0000391,46.5,5.0 3.0,46.5,5.0", + sensitive_area.kml(), + ) def test_get_kml_point(self): - sensitive_area = SensitiveAreaFactory.create(geom='POINT(700000 6600000)') + sensitive_area = SensitiveAreaFactory.create(geom="POINT(700000 6600000)") # Create a buffer around the point with 100 (settings.SENSITIVITY_DEFAULT_RADIUS) - self.assertIn('' - '3.001304,46.5,0.0 3.0012047,46.4996554,0.0 3.000922,46.4993633,0.0 ' - '3.000499,46.4991681,0.0 3.0,46.4990996,0.0 2.999501,46.4991681,0.0 ' - '2.999078,46.4993633,0.0 2.9987953,46.4996554,0.0 2.998696,46.5,0.0 ' - '2.9987953,46.5003446,0.0 2.999078,46.5006367,0.0 2.999501,46.5008319,0.0 ' - '3.0,46.5009004,0.0 3.000499,46.5008319,0.0 3.000922,46.5006367,0.0 ' - '3.0012047,46.5003446,0.0 3.001304,46.5,0.0' - '', - sensitive_area.kml()) - - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) + self.assertIn( + "" + "3.001304,46.5,0.0 3.0012047,46.4996554,0.0 3.000922,46.4993633,0.0 " + "3.000499,46.4991681,0.0 3.0,46.4990996,0.0 2.999501,46.4991681,0.0 " + "2.999078,46.4993633,0.0 2.9987953,46.4996554,0.0 2.998696,46.5,0.0 " + "2.9987953,46.5003446,0.0 2.999078,46.5006367,0.0 2.999501,46.5008319,0.0 " + "3.0,46.5009004,0.0 3.000499,46.5008319,0.0 3.000922,46.5006367,0.0 " + "3.0012047,46.5003446,0.0 3.001304,46.5,0.0" + "", + sensitive_area.kml(), + ) + + @override_settings( + SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ + "Practice1", + ] + ) @freeze_time("2020-01-01") def test_get_openair_data(self): sensitive_area = SensitiveAreaFactory.create() self.assertEqual( - 'AC ZSM\n' - 'AN Species\n' - f'*AUID GUId=! UId=! Id=(Identifiant-GeoTrek-sentivity) {sensitive_area.pk}\n' - '*ADescr Species (published on 01/01/2020)\n' + "AC ZSM\n" + "AN Species\n" + f"*AUID GUId=! UId=! Id=(Identifiant-GeoTrek-sentivity) {sensitive_area.pk}\n" + "*ADescr Species (published on 01/01/2020)\n" '*ATimes {"6": ["UTC(01/06->30/06)", "ANY(00:00->23:59)"],"7": ["UTC(01/07->31/07)", "ANY(00:00->23:59)"]}\n' - 'AH 329FT AGL\n' - 'DP 46:29:59 N 03:00:00 E\n' - 'DP 46:30:00 N 03:00:00 E', - sensitive_area.openair() + "AH 329FT AGL\n" + "DP 46:29:59 N 03:00:00 E\n" + "DP 46:30:00 N 03:00:00 E", + sensitive_area.openair(), ) - @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) + @override_settings( + SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ + "Practice1", + ] + ) def test_get_openair_data_with_radius(self): species = SpeciesFactory.create(radius=300) sensitive_area = SensitiveAreaFactory.create(species=species) - self.assertIn('AH 985FT AGL', sensitive_area.openair()) + self.assertIn("AH 985FT AGL", sensitive_area.openair()) def test_is_public(self): sensitive_area = SensitiveAreaFactory.create() @@ -85,6 +100,29 @@ def test_is_public(self): sensitive_area.published = False self.assertFalse(sensitive_area.is_public()) + def test_wgs84_geom(self): + """Test geometry transform to SRID WGS84""" + sensitive_area = SensitiveAreaFactory.create( + geom="POLYGON((" + "700000 6600000, " + "700000 6600003, " + "700003 6600003, " + "700003 6600000, " + "700000 6600000" + "))" + ) + self.assertEqual( + GEOSGeometry( + "SRID=4326;POLYGON ((" + "3 46.49999999999994, 3 46.50002701349548, " + "3.000039118674989 46.50002701348879, " + "3.000039118655609 46.49999999999324, " + "3 46.49999999999994" + "))" + ).wkt, + sensitive_area.wgs84_geom.wkt, + ) + @override_settings(SENSITIVE_AREA_INTERSECTION_MARGIN=0) def test_trek_sensitive_area(self): """ @@ -94,16 +132,17 @@ def test_trek_sensitive_area(self): SensitiveAreaFactory.create() SensitiveAreaFactory.create( geom="Polygon ((700000 6600000, 699994.87812128441873938 6600014.35493460204452276, 700021.84601664706133306" - " 6600008.61177170090377331, 700013.10642092768102884 6600028.83769322279840708, 700044.81866825232282281" - " 6600017.85077288933098316, 700030.83531510119792074 6600042.32164090406149626, 700061.79845422133803368" - " 6600043.07074910867959261, 700061.04934601683635265 6600069.78894173633307219, 700075.78180737234652042" - " 6600056.55469678994268179, 700072.53567181946709752 6600088.01724137924611568, 700092.26218787173274904" - " 6600081.27526753861457109, 700090.01486325822770596 6600097.75564803835004568, 700100 6600100, " - "700100 6600000, 700000 6600000))") + " 6600008.61177170090377331, 700013.10642092768102884 6600028.83769322279840708, 700044.81866825232282281" + " 6600017.85077288933098316, 700030.83531510119792074 6600042.32164090406149626, 700061.79845422133803368" + " 6600043.07074910867959261, 700061.04934601683635265 6600069.78894173633307219, 700075.78180737234652042" + " 6600056.55469678994268179, 700072.53567181946709752 6600088.01724137924611568, 700092.26218787173274904" + " 6600081.27526753861457109, 700090.01486325822770596 6600097.75564803835004568, 700100 6600100, " + "700100 6600000, 700000 6600000))" + ) trek = TrekFactory.create() self.assertEqual(trek.published_sensitive_areas.count(), 2) def test_geom_buffered_trigger(self): - """ Geom buffered could be created and updated in instance after creation """ + """Geom buffered could be created and updated in instance after creation""" area = SensitiveAreaFactory() self.assertIsNotNone(area.geom_buffered) From b808ff9efbb9920d139e292c4b8998e9b9ada35a Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 31 Aug 2023 16:16:14 +0200 Subject: [PATCH 32/43] senstivearea wgs84 transform test --- geotrek/sensitivity/tests/test_models.py | 37 +++++++++++++++++------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/geotrek/sensitivity/tests/test_models.py b/geotrek/sensitivity/tests/test_models.py index 8a1a4eac47..63b3bcea15 100644 --- a/geotrek/sensitivity/tests/test_models.py +++ b/geotrek/sensitivity/tests/test_models.py @@ -1,4 +1,5 @@ from freezegun import freeze_time +from difflib import SequenceMatcher from django.test import TestCase from django.test.utils import override_settings @@ -9,6 +10,19 @@ from geotrek.trekking.tests.factories import TrekFactory +def similar_string(a: str, b: str) -> float: + """compare two strings and return similarity ratio + + Args: + a (str): first value + b (str): second_value + + Returns: + float: Similarity ration + """ + return SequenceMatcher(None, a, b).ratio() + + class SensitiveAreaModelTest(TestCase): def test_specific_radius(self): specie = SpeciesFactory.create(radius=50) @@ -111,16 +125,19 @@ def test_wgs84_geom(self): "700000 6600000" "))" ) - self.assertEqual( - GEOSGeometry( - "SRID=4326;POLYGON ((" - "3 46.49999999999994, 3 46.50002701349548, " - "3.000039118674989 46.50002701348879, " - "3.000039118655609 46.49999999999324, " - "3 46.49999999999994" - "))" - ).wkt, - sensitive_area.wgs84_geom.wkt, + self.assertGreater( + similar_string( + GEOSGeometry( + "SRID=4326;POLYGON ((" + "3 46.49999999999994, 3 46.50002701349548, " + "3.000039118674989 46.50002701348879, " + "3.000039118655609 46.49999999999324, " + "3 46.49999999999994" + "))" + ).wkt, + sensitive_area.wgs84_geom.wkt, + ), + 0.9, ) @override_settings(SENSITIVE_AREA_INTERSECTION_MARGIN=0) From 1383434028e66e9ab43d83db4513a5eb7560731c Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 19 Sep 2023 14:02:26 +0200 Subject: [PATCH 33/43] test no pagination --- geotrek/api/tests/test_v2.py | 4597 ++++++++++++++++++++-------------- 1 file changed, 2786 insertions(+), 1811 deletions(-) diff --git a/geotrek/api/tests/test_v2.py b/geotrek/api/tests/test_v2.py index bfc1cf4270..a1cb9b3e28 100644 --- a/geotrek/api/tests/test_v2.py +++ b/geotrek/api/tests/test_v2.py @@ -5,8 +5,13 @@ from dateutil.relativedelta import relativedelta from django.conf import settings from django.contrib.contenttypes.models import ContentType -from django.contrib.gis.geos import (LineString, MultiLineString, MultiPoint, - Point, Polygon) +from django.contrib.gis.geos import ( + LineString, + MultiLineString, + MultiPoint, + Point, + Polygon, +) from django.contrib.gis.geos.collections import GeometryCollection from django.db import connection from django.test.testcases import TestCase @@ -22,9 +27,11 @@ from geotrek.authent.tests import factories as authent_factory from geotrek.common import models as common_models from geotrek.common.tests import factories as common_factory -from geotrek.common.utils.testdata import (get_dummy_uploaded_document, - get_dummy_uploaded_file, - get_dummy_uploaded_image) +from geotrek.common.utils.testdata import ( + get_dummy_uploaded_document, + get_dummy_uploaded_file, + get_dummy_uploaded_image, +) from geotrek.core import models as path_models from geotrek.core.tests import factories as core_factory from geotrek.feedback.tests import factories as feedback_factory @@ -47,233 +54,527 @@ from mapentity.middleware import clear_internal_user_cache -PAGINATED_JSON_STRUCTURE = sorted([ - 'count', 'next', 'previous', 'results', -]) - -PAGINATED_GEOJSON_STRUCTURE = sorted([ - 'count', 'next', 'previous', 'features', 'type' -]) - -GEOJSON_STRUCTURE = sorted([ - 'geometry', - 'type', - 'bbox', - 'properties' -]) - -TREK_PROPERTIES_GEOJSON_STRUCTURE = sorted([ - 'id', 'access', 'accessibilities', 'accessibility_advice', 'accessibility_covering', - 'accessibility_exposure', 'accessibility_level', 'accessibility_signage', 'accessibility_slope', - 'accessibility_width', 'advice', 'advised_parking', 'altimetric_profile', 'ambiance', 'arrival', 'ascent', - 'attachments', 'attachments_accessibility', 'children', 'cities', 'create_datetime', 'departure', 'departure_geom', - 'descent', 'description', 'description_teaser', 'difficulty', 'departure_city', - 'disabled_infrastructure', 'districts', 'duration', 'elevation_area_url', 'elevation_svg_url', 'gear', - 'external_id', 'gpx', 'information_desks', 'kml', 'labels', 'length_2d', - 'length_3d', 'max_elevation', 'min_elevation', 'name', 'networks', - 'next', 'parents', 'parking_location', 'pdf', 'points_reference', - 'portal', 'practice', 'previous', 'public_transport', 'provider', 'published', 'ratings', 'ratings_description', - 'reservation_system', 'reservation_id', 'route', 'second_external_id', 'source', 'structure', - 'themes', 'update_datetime', 'url', 'uuid', 'view_points', 'web_links' -]) - -PATH_PROPERTIES_GEOJSON_STRUCTURE = sorted([ - 'arrival', 'comfort', 'comments', 'departure', 'length_2d', 'length_3d', 'name', - 'networks', 'provider', 'source', 'stake', 'url', 'usages', 'uuid']) - -TOUR_PROPERTIES_GEOJSON_STRUCTURE = sorted(TREK_PROPERTIES_GEOJSON_STRUCTURE + ['count_children', 'steps']) - -POI_PROPERTIES_GEOJSON_STRUCTURE = sorted([ - 'id', 'create_datetime', 'description', 'external_id', - 'name', 'attachments', 'published', 'provider', 'type', 'type_label', 'type_pictogram', - 'update_datetime', 'url', 'uuid', 'view_points' -]) - -LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'pictogram' -]) - -TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'order', 'pictogram', 'types' -]) - -TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE = sorted([ - 'accessibility', 'approved', 'attachments', 'category', 'cities', 'contact', 'create_datetime', 'description', - 'description_teaser', 'departure_city', 'districts', 'email', 'external_id', 'geometry', 'id', 'label_accessibility', 'name', 'pdf', - 'portal', 'practical_info', 'provider', 'published', 'reservation_id', 'reservation_system', - 'source', 'structure', 'themes', 'types', 'update_datetime', 'url', 'uuid', 'website', -]) - -CITY_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'geometry', 'name', 'published' -]) - -DISTRICT_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'geometry', 'name', 'published' -]) - -ROUTE_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'route', 'pictogram' -]) - -THEME_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'label', 'pictogram' -]) - -ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'name', 'pictogram' -]) - -ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'name' -]) - -TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'name', 'website', 'title', 'description', 'facebook_id', 'facebook_image_url', 'facebook_image_height', 'facebook_image_width' -]) - -STRUCTURE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name']) - -TREK_LABEL_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'advice', 'filter', 'name', 'pictogram']) - -FILETYPE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'structure', 'type']) - -INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'label', 'pictogram' -]) - -INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'accessibility', 'description', 'email', 'label_accessibility', 'latitude', 'longitude', - 'municipality', 'name', 'phone', 'photo_url', 'provider', 'uuid', - 'postal_code', 'street', 'type', 'website' -]) - -SOURCE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'pictogram', 'website']) - -RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE = sorted(['name', 'id']) - -SITE_PROPERTIES_JSON_STRUCTURE = sorted([ - 'accessibility', 'advice', 'ambiance', 'attachments', 'children', 'cities', 'courses', 'description', 'description_teaser', 'districts', 'eid', - 'geometry', 'id', 'information_desks', 'labels', 'managers', 'name', 'orientation', 'parent', 'period', 'portal', - 'practice', 'provider', 'pdf', 'ratings', 'sector', 'source', 'structure', 'themes', 'type', 'url', 'uuid', - 'view_points', 'wind', 'web_links' -]) - -OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'sector', 'pictogram']) - -OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name']) - -SITETYPE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'practice']) - -SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'contact', 'create_datetime', 'description', 'elevation', 'geometry', - 'info_url', 'kml_url', 'openair_url', 'name', 'period', 'practices', 'provider', - 'published', 'species_id', 'structure', 'update_datetime', 'url', 'attachments', - 'rules' -]) - -SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE = sorted([ - 'id', 'name', 'period01', 'period02', 'period03', - 'period04', 'period05', 'period06', 'period07', - 'period08', 'period09', 'period10', 'period11', - 'period12', 'practices', 'radius', 'url' -]) - -COURSE_PROPERTIES_JSON_STRUCTURE = sorted([ - 'accessibility', 'advice', 'cities', 'description', 'districts', 'eid', 'equipment', 'geometry', 'height', 'id', - 'length', 'name', 'ratings', 'ratings_description', 'sites', 'structure', - 'type', 'url', 'attachments', 'max_elevation', 'min_elevation', 'parents', 'provider', - 'pdf', 'points_reference', 'children', 'duration', 'gear', 'uuid' -]) - -COURSETYPE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'practice']) - -ORGANISM_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name']) - -SERVICE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'eid', 'geometry', 'provider', 'structure', 'type', 'uuid' -]) - -SERVICE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'name', 'practices', 'pictogram' -]) - -INFRASTRUCTURE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'accessibility', 'attachments', 'condition', 'description', 'eid', 'geometry', - 'implantation_year', 'maintenance_difficulty', 'name', 'provider', 'structure', - 'type', 'usage_difficulty', 'uuid' -]) - -INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'pictogram', 'structure', 'type' -]) - -INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'structure' -]) - -INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'structure' -]) - -INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'structure' -]) - -TOURISTIC_EVENT_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'accessibility', 'approved', 'attachments', 'begin_date', 'bookable', 'booking', 'cities', 'contact', 'create_datetime', - 'description', 'description_teaser', 'districts', 'duration', 'email', 'end_date', 'external_id', 'geometry', - 'meeting_point', 'start_time', 'meeting_time', 'end_time', 'name', 'organizer', 'capacity', 'pdf', 'place', 'portal', - 'practical_info', 'provider', 'published', 'source', 'speaker', 'structure', 'target_audience', 'themes', - 'type', 'update_datetime', 'url', 'uuid', 'website', 'cancelled', 'cancellation_reason', 'participant_number' -]) - -TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'name', 'geometry' -]) - -TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label' -]) - -TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'pictogram', 'type' -]) - -SIGNAGE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'attachments', 'blades', 'code', 'condition', 'description', 'eid', - 'geometry', 'implantation_year', 'name', 'printed_elevation', 'sealing', - 'provider', 'structure', 'type', 'uuid' -]) - -SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'pictogram', 'structure' -]) - -SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label' -]) - -SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label' -]) - -SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'structure' -]) - -SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'label', 'structure' -]) - -HDVIEWPOINT_DETAIL_JSON_STRUCTURE = sorted([ - 'id', 'annotations', 'author', 'create_datetime', 'geometry', 'legend', 'license', - 'metadata_url', 'picture_tiles_url', 'poi', 'site', 'title', 'trek', 'thumbnail_url', 'update_datetime', 'uuid' -]) +PAGINATED_JSON_STRUCTURE = sorted( + [ + "count", + "next", + "previous", + "results", + ] +) + +PAGINATED_GEOJSON_STRUCTURE = sorted(["count", "next", "previous", "features", "type"]) + +GEOJSON_COLLECTION_STRUCTURE = sorted(["type", "features"]) + +GEOJSON_STRUCTURE = sorted(["geometry", "type", "bbox", "properties"]) + +TREK_PROPERTIES_GEOJSON_STRUCTURE = sorted( + [ + "id", + "access", + "accessibilities", + "accessibility_advice", + "accessibility_covering", + "accessibility_exposure", + "accessibility_level", + "accessibility_signage", + "accessibility_slope", + "accessibility_width", + "advice", + "advised_parking", + "altimetric_profile", + "ambiance", + "arrival", + "ascent", + "attachments", + "attachments_accessibility", + "children", + "cities", + "create_datetime", + "departure", + "departure_geom", + "descent", + "description", + "description_teaser", + "difficulty", + "departure_city", + "disabled_infrastructure", + "districts", + "duration", + "elevation_area_url", + "elevation_svg_url", + "gear", + "external_id", + "gpx", + "information_desks", + "kml", + "labels", + "length_2d", + "length_3d", + "max_elevation", + "min_elevation", + "name", + "networks", + "next", + "parents", + "parking_location", + "pdf", + "points_reference", + "portal", + "practice", + "previous", + "public_transport", + "provider", + "published", + "ratings", + "ratings_description", + "reservation_system", + "reservation_id", + "route", + "second_external_id", + "source", + "structure", + "themes", + "update_datetime", + "url", + "uuid", + "view_points", + "web_links", + ] +) + +PATH_PROPERTIES_GEOJSON_STRUCTURE = sorted( + [ + "arrival", + "comfort", + "comments", + "departure", + "length_2d", + "length_3d", + "name", + "networks", + "provider", + "source", + "stake", + "url", + "usages", + "uuid", + ] +) + +TOUR_PROPERTIES_GEOJSON_STRUCTURE = sorted( + TREK_PROPERTIES_GEOJSON_STRUCTURE + ["count_children", "steps"] +) + +POI_PROPERTIES_GEOJSON_STRUCTURE = sorted( + [ + "id", + "create_datetime", + "description", + "external_id", + "name", + "attachments", + "published", + "provider", + "type", + "type_label", + "type_pictogram", + "update_datetime", + "url", + "uuid", + "view_points", + ] +) + +LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "pictogram"]) + +TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE = sorted( + ["id", "label", "order", "pictogram", "types"] +) + +TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE = sorted( + [ + "accessibility", + "approved", + "attachments", + "category", + "cities", + "contact", + "create_datetime", + "description", + "description_teaser", + "departure_city", + "districts", + "email", + "external_id", + "geometry", + "id", + "label_accessibility", + "name", + "pdf", + "portal", + "practical_info", + "provider", + "published", + "reservation_id", + "reservation_system", + "source", + "structure", + "themes", + "types", + "update_datetime", + "url", + "uuid", + "website", + ] +) + +CITY_PROPERTIES_JSON_STRUCTURE = sorted(["id", "geometry", "name", "published"]) + +DISTRICT_PROPERTIES_JSON_STRUCTURE = sorted(["id", "geometry", "name", "published"]) + +ROUTE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "route", "pictogram"]) + +THEME_PROPERTIES_JSON_STRUCTURE = sorted(["id", "label", "pictogram"]) + +ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "pictogram"]) + +ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) + +TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE = sorted( + [ + "id", + "name", + "website", + "title", + "description", + "facebook_id", + "facebook_image_url", + "facebook_image_height", + "facebook_image_width", + ] +) + +STRUCTURE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) + +TREK_LABEL_PROPERTIES_JSON_STRUCTURE = sorted( + ["id", "advice", "filter", "name", "pictogram"] +) + +FILETYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "structure", "type"]) + +INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "label", "pictogram"]) + +INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE = sorted( + [ + "id", + "accessibility", + "description", + "email", + "label_accessibility", + "latitude", + "longitude", + "municipality", + "name", + "phone", + "photo_url", + "provider", + "uuid", + "postal_code", + "street", + "type", + "website", + ] +) + +SOURCE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "pictogram", "website"]) + +RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE = sorted(["name", "id"]) + +SITE_PROPERTIES_JSON_STRUCTURE = sorted( + [ + "accessibility", + "advice", + "ambiance", + "attachments", + "children", + "cities", + "courses", + "description", + "description_teaser", + "districts", + "eid", + "geometry", + "id", + "information_desks", + "labels", + "managers", + "name", + "orientation", + "parent", + "period", + "portal", + "practice", + "provider", + "pdf", + "ratings", + "sector", + "source", + "structure", + "themes", + "type", + "url", + "uuid", + "view_points", + "wind", + "web_links", + ] +) + +OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE = sorted( + ["id", "name", "sector", "pictogram"] +) + +OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) + +SITETYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "practice"]) + +SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE = sorted( + [ + "id", + "contact", + "create_datetime", + "description", + "elevation", + "geometry", + "info_url", + "kml_url", + "openair_url", + "name", + "period", + "practices", + "provider", + "published", + "species_id", + "structure", + "update_datetime", + "url", + "attachments", + "rules", + ] +) + +SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE = sorted( + [ + "id", + "name", + "period01", + "period02", + "period03", + "period04", + "period05", + "period06", + "period07", + "period08", + "period09", + "period10", + "period11", + "period12", + "practices", + "radius", + "url", + ] +) + +COURSE_PROPERTIES_JSON_STRUCTURE = sorted( + [ + "accessibility", + "advice", + "cities", + "description", + "districts", + "eid", + "equipment", + "geometry", + "height", + "id", + "length", + "name", + "ratings", + "ratings_description", + "sites", + "structure", + "type", + "url", + "attachments", + "max_elevation", + "min_elevation", + "parents", + "provider", + "pdf", + "points_reference", + "children", + "duration", + "gear", + "uuid", + ] +) + +COURSETYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "practice"]) + +ORGANISM_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) + +SERVICE_DETAIL_JSON_STRUCTURE = sorted( + ["id", "eid", "geometry", "provider", "structure", "type", "uuid"] +) + +SERVICE_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "name", "practices", "pictogram"]) + +INFRASTRUCTURE_DETAIL_JSON_STRUCTURE = sorted( + [ + "id", + "accessibility", + "attachments", + "condition", + "description", + "eid", + "geometry", + "implantation_year", + "maintenance_difficulty", + "name", + "provider", + "structure", + "type", + "usage_difficulty", + "uuid", + ] +) + +INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE = sorted( + ["id", "label", "pictogram", "structure", "type"] +) + +INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "structure"]) + +INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted( + ["id", "label", "structure"] +) + +INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted( + ["id", "label", "structure"] +) + +TOURISTIC_EVENT_DETAIL_JSON_STRUCTURE = sorted( + [ + "id", + "accessibility", + "approved", + "attachments", + "begin_date", + "bookable", + "booking", + "cities", + "contact", + "create_datetime", + "description", + "description_teaser", + "districts", + "duration", + "email", + "end_date", + "external_id", + "geometry", + "meeting_point", + "start_time", + "meeting_time", + "end_time", + "name", + "organizer", + "capacity", + "pdf", + "place", + "portal", + "practical_info", + "provider", + "published", + "source", + "speaker", + "structure", + "target_audience", + "themes", + "type", + "update_datetime", + "url", + "uuid", + "website", + "cancelled", + "cancellation_reason", + "participant_number", + ] +) + +TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE = sorted(["id", "name", "geometry"]) + +TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE = sorted(["id", "label"]) + +TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "pictogram", "type"]) + +SIGNAGE_DETAIL_JSON_STRUCTURE = sorted( + [ + "id", + "attachments", + "blades", + "code", + "condition", + "description", + "eid", + "geometry", + "implantation_year", + "name", + "printed_elevation", + "sealing", + "provider", + "structure", + "type", + "uuid", + ] +) + +SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "pictogram", "structure"]) + +SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE = sorted(["id", "label"]) + +SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE = sorted(["id", "label"]) + +SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "structure"]) + +SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "structure"]) + +HDVIEWPOINT_DETAIL_JSON_STRUCTURE = sorted( + [ + "id", + "annotations", + "author", + "create_datetime", + "geometry", + "legend", + "license", + "metadata_url", + "picture_tiles_url", + "poi", + "site", + "title", + "trek", + "thumbnail_url", + "update_datetime", + "uuid", + ] +) class BaseApiTest(TestCase): - """ Base TestCase for all API profiles """ + """Base TestCase for all API profiles""" def tearDown(self): clear_internal_user_cache() @@ -294,15 +595,20 @@ def setUpTestData(cls): cls.label = common_factory.LabelFactory(id=23) cls.path = core_factory.PathFactory.create(geom=LineString((0, 0), (0, 10))) if settings.TREKKING_TOPOLOGY_ENABLED: - cls.treks = trek_factory.TrekWithPOIsFactory.create_batch(cls.nb_treks, paths=[(cls.path, 0, 1)], - geom=cls.path.geom) + cls.treks = trek_factory.TrekWithPOIsFactory.create_batch( + cls.nb_treks, paths=[(cls.path, 0, 1)], geom=cls.path.geom + ) else: - cls.treks = trek_factory.TrekFactory.create_batch(cls.nb_treks, geom=cls.path.geom) + cls.treks = trek_factory.TrekFactory.create_batch( + cls.nb_treks, geom=cls.path.geom + ) trek_factory.POIFactory.create_batch(cls.nb_treks, geom=Point(0, 4)) trek_factory.POIFactory.create_batch(cls.nb_treks, geom=Point(0, 5)) - html_content_with_imgs = '

Some HTML content with images

' \ - 'Descent' \ - '' + html_content_with_imgs = ( + "

Some HTML content with images

" + 'Descent' + '' + ) cls.treks[0].description = html_content_with_imgs cls.treks[0].description_teaser = html_content_with_imgs cls.treks[0].ambiance = html_content_with_imgs @@ -314,25 +620,65 @@ def setUpTestData(cls): cls.treks[1].ratings.add(cls.rating2) trek_models.TrekRelationship(trek_a=cls.treks[0], trek_b=cls.treks[1]).save() cls.information_desk_type = tourism_factory.InformationDeskTypeFactory() - cls.info_desk = tourism_factory.InformationDeskFactory(type=cls.information_desk_type) + cls.info_desk = tourism_factory.InformationDeskFactory( + type=cls.information_desk_type + ) cls.treks[0].information_desks.add(cls.info_desk) - common_factory.AttachmentFactory.create(content_object=cls.treks[0], attachment_file=get_dummy_uploaded_image()) - common_factory.AttachmentFactory.create(content_object=cls.treks[0], attachment_file=get_dummy_uploaded_file()) - common_factory.AttachmentFactory.create(content_object=cls.treks[0], attachment_file=get_dummy_uploaded_document()) - common_factory.AttachmentFactory(content_object=cls.treks[0], attachment_file='', attachment_video='https://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque') - common_factory.AttachmentFactory(content_object=cls.treks[0], attachment_file='', attachment_video='', attachment_link='https://geotrek.fr/assets/img/logo.svg') - common_factory.AttachmentFactory(content_object=cls.treks[0], attachment_file='', attachment_video='', attachment_link='') + common_factory.AttachmentFactory.create( + content_object=cls.treks[0], attachment_file=get_dummy_uploaded_image() + ) + common_factory.AttachmentFactory.create( + content_object=cls.treks[0], attachment_file=get_dummy_uploaded_file() + ) + common_factory.AttachmentFactory.create( + content_object=cls.treks[0], attachment_file=get_dummy_uploaded_document() + ) + common_factory.AttachmentFactory( + content_object=cls.treks[0], + attachment_file="", + attachment_video="https://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque", + ) + common_factory.AttachmentFactory( + content_object=cls.treks[0], + attachment_file="", + attachment_video="", + attachment_link="https://geotrek.fr/assets/img/logo.svg", + ) + common_factory.AttachmentFactory( + content_object=cls.treks[0], + attachment_file="", + attachment_video="", + attachment_link="", + ) common_factory.AttachmentAccessibilityFactory(content_object=cls.treks[0]) cls.treks[3].parking_location = None - cls.treks[3].points_reference = MultiPoint([Point(0, 0), Point(1, 1)], srid=settings.SRID) + cls.treks[3].points_reference = MultiPoint( + [Point(0, 0), Point(1, 1)], srid=settings.SRID + ) cls.treks[3].save() - cls.content = tourism_factory.TouristicContentFactory.create(published=True, geom='SRID=2154;POINT(0 0)') - cls.content2 = tourism_factory.TouristicContentFactory.create(published=True, geom='SRID=2154;POINT(0 0)') - cls.event = tourism_factory.TouristicEventFactory.create(published=True, geom='SRID=2154;POINT(0 0)') - cls.city = zoning_factory.CityFactory(code='01000', geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') - cls.city2 = zoning_factory.CityFactory(code='02000', geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') - cls.district = zoning_factory.DistrictFactory(geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') - cls.district2 = zoning_factory.DistrictFactory(geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') + cls.content = tourism_factory.TouristicContentFactory.create( + published=True, geom="SRID=2154;POINT(0 0)" + ) + cls.content2 = tourism_factory.TouristicContentFactory.create( + published=True, geom="SRID=2154;POINT(0 0)" + ) + cls.event = tourism_factory.TouristicEventFactory.create( + published=True, geom="SRID=2154;POINT(0 0)" + ) + cls.city = zoning_factory.CityFactory( + code="01000", + geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))", + ) + cls.city2 = zoning_factory.CityFactory( + code="02000", + geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))", + ) + cls.district = zoning_factory.DistrictFactory( + geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))" + ) + cls.district2 = zoning_factory.DistrictFactory( + geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))" + ) cls.accessibility = trek_factory.AccessibilityFactory() cls.accessibility_level = trek_factory.AccessibilityLevelFactory() cls.route = trek_factory.RouteFactory() @@ -346,11 +692,15 @@ def setUpTestData(cls): cls.difficulty = trek_factory.DifficultyLevelFactory() cls.network = trek_factory.TrekNetworkFactory() if settings.TREKKING_TOPOLOGY_ENABLED: - cls.poi = trek_factory.POIFactory(paths=[(cls.treks[0].paths.first(), 0.5, 0.5)]) - poi_excluded = trek_factory.POIFactory(paths=[(cls.treks[0].paths.first(), 0.5, 0.5)]) + cls.poi = trek_factory.POIFactory( + paths=[(cls.treks[0].paths.first(), 0.5, 0.5)] + ) + poi_excluded = trek_factory.POIFactory( + paths=[(cls.treks[0].paths.first(), 0.5, 0.5)] + ) else: - cls.poi = trek_factory.POIFactory(geom='SRID=2154;POINT(0 5)') - poi_excluded = trek_factory.POIFactory(geom='SRID=2154;POINT(0 5)') + cls.poi = trek_factory.POIFactory(geom="SRID=2154;POINT(0 5)") + poi_excluded = trek_factory.POIFactory(geom="SRID=2154;POINT(0 5)") cls.treks[0].pois_excluded.add(poi_excluded) cls.source = common_factory.RecordSourceFactory() cls.reservation_system = common_factory.ReservationSystemFactory() @@ -365,20 +715,20 @@ def setUpTestData(cls): cls.info_desk.label_accessibility = cls.label_accessibility cls.info_desk.save() cls.content2.portal.add(cls.portal) - common_factory.FileTypeFactory.create(type='Topoguide') - cls.filetype = common_factory.FileTypeFactory.create(type='Foo') + common_factory.FileTypeFactory.create(type="Topoguide") + cls.filetype = common_factory.FileTypeFactory.create(type="Foo") cls.sensitivearea = sensitivity_factory.SensitiveAreaFactory() cls.sensitivearea_practice = sensitivity_factory.SportPracticeFactory() cls.sensitivearea_species = sensitivity_factory.SpeciesFactory() cls.parent = trek_factory.TrekFactory.create( published=True, - name='Parent', + name="Parent", route=cls.route, structure=cls.structure, reservation_system=cls.reservation_system, practice=cls.practice, difficulty=cls.difficulty, - accessibility_level=cls.accessibility_level + accessibility_level=cls.accessibility_level, ) cls.parent.accessibilities.add(cls.accessibility) cls.parent.source.add(cls.source) @@ -386,79 +736,101 @@ def setUpTestData(cls): cls.parent.networks.add(cls.network) cls.parent.save() # For unpublished treks we avoid to create new reservation system and routes - cls.parent2 = trek_factory.TrekFactory.create(published=False, name='Parent2', - reservation_system=cls.reservation_system, route=cls.route, - accessibility_level=None) - cls.child1 = trek_factory.TrekFactory.create(published=False, name='Child 1', - reservation_system=cls.reservation_system, route=cls.route, - accessibility_level=None) - cls.child2 = trek_factory.TrekFactory.create(published=True, name='Child 2', accessibility_level=None) - cls.child3 = trek_factory.TrekFactory.create(published=False, name='Child 3', - reservation_system=cls.reservation_system, route=cls.route, - accessibility_level=None) + cls.parent2 = trek_factory.TrekFactory.create( + published=False, + name="Parent2", + reservation_system=cls.reservation_system, + route=cls.route, + accessibility_level=None, + ) + cls.child1 = trek_factory.TrekFactory.create( + published=False, + name="Child 1", + reservation_system=cls.reservation_system, + route=cls.route, + accessibility_level=None, + ) + cls.child2 = trek_factory.TrekFactory.create( + published=True, name="Child 2", accessibility_level=None + ) + cls.child3 = trek_factory.TrekFactory.create( + published=False, + name="Child 3", + reservation_system=cls.reservation_system, + route=cls.route, + accessibility_level=None, + ) trek_models.TrekRelationship(trek_a=cls.parent, trek_b=cls.treks[0]).save() - trek_models.OrderedTrekChild(parent=cls.parent, child=cls.child1, order=2).save() - trek_models.OrderedTrekChild(parent=cls.parent, child=cls.child2, order=1).save() - trek_models.OrderedTrekChild(parent=cls.parent2, child=cls.child3, order=1).save() - trek_models.OrderedTrekChild(parent=cls.treks[0], child=cls.child2, order=3).save() + trek_models.OrderedTrekChild( + parent=cls.parent, child=cls.child1, order=2 + ).save() + trek_models.OrderedTrekChild( + parent=cls.parent, child=cls.child2, order=1 + ).save() + trek_models.OrderedTrekChild( + parent=cls.parent2, child=cls.child3, order=1 + ).save() + trek_models.OrderedTrekChild( + parent=cls.treks[0], child=cls.child2, order=3 + ).save() # Create a trek with a multilinestring geom cls.path2 = core_factory.PathFactory.create(geom=LineString((0, 10), (0, 20))) cls.path3 = core_factory.PathFactory.create(geom=LineString((0, 20), (0, 30))) cls.trek_multilinestring = trek_factory.TrekFactory.create( paths=[(cls.path, 0, 1), (cls.path2, 0, 1), (cls.path3, 0, 1)], - geom=MultiLineString([cls.path.geom, cls.path3.geom]) + geom=MultiLineString([cls.path.geom, cls.path3.geom]), ) cls.path2.delete() cls.trek_multilinestring.reload() cls.trek_multilinestring.published = True cls.trek_multilinestring.save() # Create a trek with a point geom - cls.trek_point = trek_factory.TrekFactory.create(paths=[(cls.path, 0, 0)], geom=Point(cls.path.geom.coords[0])) + cls.trek_point = trek_factory.TrekFactory.create( + paths=[(cls.path, 0, 0)], geom=Point(cls.path.geom.coords[0]) + ) cls.nb_treks += 4 # add parent, 1 child published and treks with a multilinestring/point geom cls.coursetype = outdoor_factory.CourseTypeFactory() cls.course = outdoor_factory.CourseFactory( - type=cls.coursetype, - points_reference=MultiPoint(Point(12, 12)) + type=cls.coursetype, points_reference=MultiPoint(Point(12, 12)) ) cls.course.pois_excluded.add(poi_excluded) cls.course.parent_sites.set([cls.site]) # create a reference point for distance filter (in 4326, Cahors city) - cls.reference_point = Point(x=1.4388656616210938, - y=44.448487178796235, srid=4326) + cls.reference_point = Point( + x=1.4388656616210938, y=44.448487178796235, srid=4326 + ) cls.service_type = trek_factory.ServiceTypeFactory() cls.service_type_2 = trek_factory.ServiceTypeFactory(published=False) cls.service1 = trek_factory.ServiceFactory() - cls.service = trek_factory.ServiceFactory( - type=cls.service_type + cls.service = trek_factory.ServiceFactory(type=cls.service_type) + cls.service_2 = trek_factory.ServiceFactory(type=cls.service_type_2) + cls.infrastructure_type = infrastructure_factory.InfrastructureTypeFactory() + cls.infrastructure_condition = ( + infrastructure_factory.InfrastructureConditionFactory() ) - cls.service_2 = trek_factory.ServiceFactory( - type=cls.service_type_2 + cls.infrastructure_usagedifficulty = ( + infrastructure_factory.InfrastructureUsageDifficultyLevelFactory() + ) + cls.infrastructure_maintenancedifficulty = ( + infrastructure_factory.InfrastructureMaintenanceDifficultyLevelFactory() ) - cls.infrastructure_type = infrastructure_factory.InfrastructureTypeFactory() - cls.infrastructure_condition = infrastructure_factory.InfrastructureConditionFactory() - cls.infrastructure_usagedifficulty = infrastructure_factory.InfrastructureUsageDifficultyLevelFactory() - cls.infrastructure_maintenancedifficulty = infrastructure_factory.InfrastructureMaintenanceDifficultyLevelFactory() cls.infrastructure = infrastructure_factory.InfrastructureFactory( type=cls.infrastructure_type, usage_difficulty=cls.infrastructure_usagedifficulty, maintenance_difficulty=cls.infrastructure_maintenancedifficulty, condition=cls.infrastructure_condition, - published=True - ) - cls.bladetype = signage_factory.BladeTypeFactory( + published=True, ) + cls.bladetype = signage_factory.BladeTypeFactory() cls.color = signage_factory.BladeColorFactory() cls.sealing = signage_factory.SealingFactory() cls.direction = signage_factory.BladeDirectionFactory() cls.bladetype = signage_factory.BladeFactory( - color=cls.color, - type=cls.bladetype, - direction=cls.direction + color=cls.color, type=cls.bladetype, direction=cls.direction ) cls.signagetype = signage_factory.SignageTypeFactory() cls.signage = signage_factory.SignageFactory( - type=cls.signagetype, - published=True + type=cls.signagetype, published=True ) cls.sector = outdoor_factory.SectorFactory() cls.outdoor_practice = outdoor_factory.PracticeFactory(sector=cls.sector) @@ -471,9 +843,7 @@ def setUpTestData(cls): cls.hdviewpoint_trek = common_factory.HDViewPointFactory( content_object=cls.treks[0] ) - cls.hdviewpoint_poi = common_factory.HDViewPointFactory( - content_object=cls.poi - ) + cls.hdviewpoint_poi = common_factory.HDViewPointFactory(content_object=cls.poi) cls.hdviewpoint_site = common_factory.HDViewPointFactory( content_object=cls.site ) @@ -481,7 +851,7 @@ def setUpTestData(cls): def check_number_elems_response(self, response, model): json_response = response.json() self.assertEqual(response.status_code, 200) - self.assertEquals(len(json_response['results']), model.objects.count()) + self.assertEquals(len(json_response["results"]), model.objects.count()) def check_structure_response(self, response, structure): json_response = response.json() @@ -489,343 +859,499 @@ def check_structure_response(self, response, structure): self.assertEquals(sorted(json_response.keys()), structure) def get_trek_list(self, params=None): - return self.client.get(reverse('apiv2:trek-list'), params) + return self.client.get(reverse("apiv2:trek-list"), params) def get_trek_detail(self, id_trek, params=None): - return self.client.get(reverse('apiv2:trek-detail', args=(id_trek,)), params) + return self.client.get(reverse("apiv2:trek-detail", args=(id_trek,)), params) def get_tour_list(self, params=None): - return self.client.get(reverse('apiv2:tour-list'), params) + return self.client.get(reverse("apiv2:tour-list"), params) def get_tour_detail(self, id_trek, params=None): - return self.client.get(reverse('apiv2:tour-detail', args=(id_trek,)), params) + return self.client.get(reverse("apiv2:tour-detail", args=(id_trek,)), params) def get_difficulties_list(self, params=None): - return self.client.get(reverse('apiv2:difficulty-list'), params) + return self.client.get(reverse("apiv2:difficulty-list"), params) def get_difficulty_detail(self, id_difficulty, params=None): - return self.client.get(reverse('apiv2:difficulty-detail', args=(id_difficulty,)), params) + return self.client.get( + reverse("apiv2:difficulty-detail", args=(id_difficulty,)), params + ) def get_practices_list(self, params=None): - return self.client.get(reverse('apiv2:practice-list'), params) + return self.client.get(reverse("apiv2:practice-list"), params) def get_practices_detail(self, id_practice, params=None): - return self.client.get(reverse('apiv2:practice-detail', args=(id_practice,)), params) + return self.client.get( + reverse("apiv2:practice-detail", args=(id_practice,)), params + ) def get_networks_list(self, params=None): - return self.client.get(reverse('apiv2:network-list'), params) + return self.client.get(reverse("apiv2:network-list"), params) def get_network_detail(self, id_network, params=None): - return self.client.get(reverse('apiv2:network-detail', args=(id_network,)), params) + return self.client.get( + reverse("apiv2:network-detail", args=(id_network,)), params + ) def get_themes_list(self, params=None): - return self.client.get(reverse('apiv2:theme-list'), params) + return self.client.get(reverse("apiv2:theme-list"), params) def get_themes_detail(self, id_theme, params=None): - return self.client.get(reverse('apiv2:theme-detail', args=(id_theme,)), params) + return self.client.get(reverse("apiv2:theme-detail", args=(id_theme,)), params) def get_city_list(self, params=None): - return self.client.get(reverse('apiv2:city-list'), params) + return self.client.get(reverse("apiv2:city-list"), params) def get_city_detail(self, id_city, params=None): - return self.client.get(reverse('apiv2:city-detail', args=(id_city,)), params) + return self.client.get(reverse("apiv2:city-detail", args=(id_city,)), params) def get_district_list(self, params=None): - return self.client.get(reverse('apiv2:district-list'), params) + return self.client.get(reverse("apiv2:district-list"), params) def get_district_detail(self, id_district, params=None): - return self.client.get(reverse('apiv2:district-detail', args=(id_district,)), params) + return self.client.get( + reverse("apiv2:district-detail", args=(id_district,)), params + ) def get_route_list(self, params=None): - return self.client.get(reverse('apiv2:route-list'), params) + return self.client.get(reverse("apiv2:route-list"), params) def get_route_detail(self, id_route, params=None): - return self.client.get(reverse('apiv2:route-detail', args=(id_route,)), params) + return self.client.get(reverse("apiv2:route-detail", args=(id_route,)), params) def get_accessibility_list(self, params=None): - return self.client.get(reverse('apiv2:accessibility-list'), params) + return self.client.get(reverse("apiv2:accessibility-list"), params) def get_accessibility_level_list(self, params=None): - return self.client.get(reverse('apiv2:accessibility-level-list'), params) + return self.client.get(reverse("apiv2:accessibility-level-list"), params) def get_accessibility_detail(self, id_accessibility, params=None): - return self.client.get(reverse('apiv2:accessibility-detail', args=(id_accessibility,)), params) + return self.client.get( + reverse("apiv2:accessibility-detail", args=(id_accessibility,)), params + ) def get_accessibility_level_detail(self, id_accessibility_level, params=None): - return self.client.get(reverse('apiv2:accessibility-level-detail', args=(id_accessibility_level,)), params) + return self.client.get( + reverse("apiv2:accessibility-level-detail", args=(id_accessibility_level,)), + params, + ) def get_portal_list(self, params=None): - return self.client.get(reverse('apiv2:portal-list'), params) + return self.client.get(reverse("apiv2:portal-list"), params) def get_portal_detail(self, id_portal, params=None): - return self.client.get(reverse('apiv2:portal-detail', args=(id_portal,)), params) + return self.client.get( + reverse("apiv2:portal-detail", args=(id_portal,)), params + ) def get_structure_list(self, params=None): - return self.client.get(reverse('apiv2:structure-list'), params) + return self.client.get(reverse("apiv2:structure-list"), params) def get_structure_detail(self, id_structure, params=None): - return self.client.get(reverse('apiv2:structure-detail', args=(id_structure,)), params) + return self.client.get( + reverse("apiv2:structure-detail", args=(id_structure,)), params + ) def get_poi_list(self, params=None): - return self.client.get(reverse('apiv2:poi-list'), params) + return self.client.get(reverse("apiv2:poi-list"), params) def get_poi_detail(self, id_poi, params=None): - return self.client.get(reverse('apiv2:poi-detail', args=(id_poi,)), params) + return self.client.get(reverse("apiv2:poi-detail", args=(id_poi,)), params) def get_poi_type(self, params=None): - return self.client.get(reverse('apiv2:poitype-list'), params) + return self.client.get(reverse("apiv2:poitype-list"), params) def get_path_list(self, params=None): - return self.client.get(reverse('apiv2:path-list'), params) + return self.client.get(reverse("apiv2:path-list"), params) def get_path_detail(self, id_path, params=None): - return self.client.get(reverse('apiv2:path-detail', args=(id_path,)), params) + return self.client.get(reverse("apiv2:path-detail", args=(id_path,)), params) def get_touristiccontentcategory_list(self, params=None): - return self.client.get(reverse('apiv2:touristiccontentcategory-list'), params) + return self.client.get(reverse("apiv2:touristiccontentcategory-list"), params) def get_touristiccontentcategory_detail(self, id_category, params=None): - return self.client.get(reverse('apiv2:touristiccontentcategory-detail', args=(id_category,)), params) + return self.client.get( + reverse("apiv2:touristiccontentcategory-detail", args=(id_category,)), + params, + ) def get_touristiccontent_list(self, params=None): - return self.client.get(reverse('apiv2:touristiccontent-list'), params) + return self.client.get(reverse("apiv2:touristiccontent-list"), params) def get_touristiccontent_detail(self, id_content, params=None): - return self.client.get(reverse('apiv2:touristiccontent-detail', args=(id_content,)), params) + return self.client.get( + reverse("apiv2:touristiccontent-detail", args=(id_content,)), params + ) def get_labelaccessibility_list(self, params=None): - return self.client.get(reverse('apiv2:labelaccessibility-list', params)) + return self.client.get(reverse("apiv2:labelaccessibility-list", params)) def get_labelaccessibility_detail(self, id_label_accessibility, params=None): - return self.client.get(reverse('apiv2:labelaccessibility-detail', args=(id_label_accessibility,)), params) + return self.client.get( + reverse("apiv2:labelaccessibility-detail", args=(id_label_accessibility,)), + params, + ) def get_label_list(self, params=None): - return self.client.get(reverse('apiv2:label-list'), params) + return self.client.get(reverse("apiv2:label-list"), params) def get_label_detail(self, id_label, params=None): - return self.client.get(reverse('apiv2:label-detail', args=(id_label,)), params) + return self.client.get(reverse("apiv2:label-detail", args=(id_label,)), params) def get_filetype_list(self, params=None): - return self.client.get(reverse('apiv2:filetype-list'), params) + return self.client.get(reverse("apiv2:filetype-list"), params) def get_filetype_detail(self, id_label, params=None): - return self.client.get(reverse('apiv2:filetype-detail', args=(id_label,)), params) + return self.client.get( + reverse("apiv2:filetype-detail", args=(id_label,)), params + ) def get_informationdesk_list(self, params=None): - return self.client.get(reverse('apiv2:informationdesk-list'), params) + return self.client.get(reverse("apiv2:informationdesk-list"), params) def get_informationdesk_detail(self, id_infodesk, params=None): - return self.client.get(reverse('apiv2:informationdesk-detail', args=(id_infodesk,)), params) + return self.client.get( + reverse("apiv2:informationdesk-detail", args=(id_infodesk,)), params + ) def get_informationdesk_type_list(self, params=None): - return self.client.get(reverse('apiv2:informationdesktype-list'), params) + return self.client.get(reverse("apiv2:informationdesktype-list"), params) def get_informationdesk_type_detail(self, id_infodesk_type, params=None): - return self.client.get(reverse('apiv2:informationdesktype-detail', args=(id_infodesk_type,)), params) + return self.client.get( + reverse("apiv2:informationdesktype-detail", args=(id_infodesk_type,)), + params, + ) def get_source_list(self, params=None): - return self.client.get(reverse('apiv2:source-list'), params) + return self.client.get(reverse("apiv2:source-list"), params) def get_source_detail(self, id_source, params=None): - return self.client.get(reverse('apiv2:source-detail', args=(id_source,)), params) + return self.client.get( + reverse("apiv2:source-detail", args=(id_source,)), params + ) def get_reservationsystem_list(self, params=None): - return self.client.get(reverse('apiv2:reservationsystem-list'), params) + return self.client.get(reverse("apiv2:reservationsystem-list"), params) def get_reservationsystem_detail(self, id_reservationsystem, params=None): - return self.client.get(reverse('apiv2:reservationsystem-detail', args=(id_reservationsystem,)), params) + return self.client.get( + reverse("apiv2:reservationsystem-detail", args=(id_reservationsystem,)), + params, + ) def get_site_list(self, params=None): - return self.client.get(reverse('apiv2:site-list'), params) + return self.client.get(reverse("apiv2:site-list"), params) def get_site_detail(self, id_site, params=None): - return self.client.get(reverse('apiv2:site-detail', args=(id_site,)), params) + return self.client.get(reverse("apiv2:site-detail", args=(id_site,)), params) def get_course_list(self, params=None): - return self.client.get(reverse('apiv2:course-list'), params) + return self.client.get(reverse("apiv2:course-list"), params) def get_course_detail(self, id_course, params=None): - return self.client.get(reverse('apiv2:course-detail', args=(id_course,)), params) + return self.client.get( + reverse("apiv2:course-detail", args=(id_course,)), params + ) def get_outdoorpractice_list(self, params=None): - return self.client.get(reverse('apiv2:outdoor-practice-list'), params) + return self.client.get(reverse("apiv2:outdoor-practice-list"), params) def get_outdoorpractice_detail(self, id_practice, params=None): - return self.client.get(reverse('apiv2:outdoor-practice-detail', args=(id_practice,)), params) + return self.client.get( + reverse("apiv2:outdoor-practice-detail", args=(id_practice,)), params + ) def get_sitetype_list(self, params=None): - return self.client.get(reverse('apiv2:sitetype-list'), params) + return self.client.get(reverse("apiv2:sitetype-list"), params) def get_sitetype_detail(self, id_type, params=None): - return self.client.get(reverse('apiv2:sitetype-detail', args=(id_type,)), params) + return self.client.get( + reverse("apiv2:sitetype-detail", args=(id_type,)), params + ) def get_sensitivearea_list(self, params=None): - return self.client.get(reverse('apiv2:sensitivearea-list'), params) + return self.client.get(reverse("apiv2:sensitivearea-list"), params) def get_sensitivearea_detail(self, id_sensitivearea, params=None): - return self.client.get(reverse('apiv2:sensitivearea-detail', args=(id_sensitivearea,)), params) + return self.client.get( + reverse("apiv2:sensitivearea-detail", args=(id_sensitivearea,)), params + ) def get_sensitiveareapractice_list(self, params=None): - return self.client.get(reverse('apiv2:sportpractice-list'), params) + return self.client.get(reverse("apiv2:sportpractice-list"), params) def get_sensitiveareapractice_detail(self, id_sensitivearea_practice, params=None): - return self.client.get(reverse('apiv2:sportpractice-detail', args=(id_sensitivearea_practice,)), params) + return self.client.get( + reverse("apiv2:sportpractice-detail", args=(id_sensitivearea_practice,)), + params, + ) def get_sensitiveareaspecies_list(self, params=None): - return self.client.get(reverse('apiv2:species-list'), params) + return self.client.get(reverse("apiv2:species-list"), params) def get_sensitiveareaspecies_detail(self, id_sensitivearea_species, params=None): - return self.client.get(reverse('apiv2:species-detail', args=(id_sensitivearea_species,)), params) + return self.client.get( + reverse("apiv2:species-detail", args=(id_sensitivearea_species,)), params + ) def get_config(self, params=None): - return self.client.get(reverse('apiv2:config', params)) + return self.client.get(reverse("apiv2:config", params)) def get_organism_list(self, params=None): - return self.client.get(reverse('apiv2:organism-list'), params) + return self.client.get(reverse("apiv2:organism-list"), params) def get_organism_detail(self, id_organism, params=None): - return self.client.get(reverse('apiv2:organism-detail', args=(id_organism,)), params) + return self.client.get( + reverse("apiv2:organism-detail", args=(id_organism,)), params + ) def get_status_list(self, params=None): - return self.client.get(reverse('apiv2:feedback-status'), params) + return self.client.get(reverse("apiv2:feedback-status"), params) def get_activity_list(self, params=None): - return self.client.get(reverse('apiv2:feedback-activity'), params) + return self.client.get(reverse("apiv2:feedback-activity"), params) def get_category_list(self, params=None): - return self.client.get(reverse('apiv2:feedback-category'), params) + return self.client.get(reverse("apiv2:feedback-category"), params) def get_magnitude_list(self, params=None): - return self.client.get(reverse('apiv2:feedback-magnitude'), params) + return self.client.get(reverse("apiv2:feedback-magnitude"), params) def get_touristicevent_list(self, params=None): - return self.client.get(reverse('apiv2:touristicevent-list'), params) + return self.client.get(reverse("apiv2:touristicevent-list"), params) def get_touristicevent_detail(self, id_touristicevent, params=None): - return self.client.get(reverse('apiv2:touristicevent-detail', args=(id_touristicevent,)), params) + return self.client.get( + reverse("apiv2:touristicevent-detail", args=(id_touristicevent,)), params + ) def get_touristiceventtype_list(self, params=None): - return self.client.get(reverse('apiv2:touristiceventtype-list'), params) + return self.client.get(reverse("apiv2:touristiceventtype-list"), params) def get_touristiceventtype_detail(self, id_touristiceventtype, params=None): - return self.client.get(reverse('apiv2:touristiceventtype-detail', args=(id_touristiceventtype,)), params) + return self.client.get( + reverse("apiv2:touristiceventtype-detail", args=(id_touristiceventtype,)), + params, + ) def get_touristiceventplace_list(self, params=None): - return self.client.get(reverse('apiv2:touristiceventplace-list'), params) + return self.client.get(reverse("apiv2:touristiceventplace-list"), params) def get_touristiceventplace_detail(self, id_touristiceventplace, params=None): - return self.client.get(reverse('apiv2:touristiceventplace-detail', args=(id_touristiceventplace,)), params) + return self.client.get( + reverse("apiv2:touristiceventplace-detail", args=(id_touristiceventplace,)), + params, + ) def get_touristiceventorganizer_list(self, params=None): - return self.client.get(reverse('apiv2:touristiceventorganizer-list'), params) + return self.client.get(reverse("apiv2:touristiceventorganizer-list"), params) - def get_touristiceventorganizer_detail(self, id_touristiceventorganizer, params=None): - return self.client.get(reverse('apiv2:touristiceventorganizer-detail', args=(id_touristiceventorganizer,)), params) + def get_touristiceventorganizer_detail( + self, id_touristiceventorganizer, params=None + ): + return self.client.get( + reverse( + "apiv2:touristiceventorganizer-detail", + args=(id_touristiceventorganizer,), + ), + params, + ) def get_servicetype_list(self, params=None): - return self.client.get(reverse('apiv2:servicetype-list'), params) + return self.client.get(reverse("apiv2:servicetype-list"), params) def get_service_list(self, params=None): - return self.client.get(reverse('apiv2:service-list'), params) + return self.client.get(reverse("apiv2:service-list"), params) def get_servicetype_detail(self, id_servicetype, params=None): - return self.client.get(reverse('apiv2:servicetype-detail', args=(id_servicetype,)), params) + return self.client.get( + reverse("apiv2:servicetype-detail", args=(id_servicetype,)), params + ) def get_service_detail(self, id_service, params=None): - return self.client.get(reverse('apiv2:service-detail', args=(id_service,)), params) + return self.client.get( + reverse("apiv2:service-detail", args=(id_service,)), params + ) def get_coursetype_list(self, params=None): - return self.client.get(reverse('apiv2:coursetype-list'), params) + return self.client.get(reverse("apiv2:coursetype-list"), params) def get_coursetype_detail(self, id_coursetype, params=None): - return self.client.get(reverse('apiv2:coursetype-detail', args=(id_coursetype,)), params) + return self.client.get( + reverse("apiv2:coursetype-detail", args=(id_coursetype,)), params + ) def get_infrastructuretype_detail(self, id_infrastructuretype, params=None): - return self.client.get(reverse('apiv2:infrastructure-type-detail', args=(id_infrastructuretype,)), params) + return self.client.get( + reverse("apiv2:infrastructure-type-detail", args=(id_infrastructuretype,)), + params, + ) def get_infrastructuretype_list(self, params=None): - return self.client.get(reverse('apiv2:infrastructure-type-list'), params) + return self.client.get(reverse("apiv2:infrastructure-type-list"), params) def get_infrastructure_list(self, params=None): - return self.client.get(reverse('apiv2:infrastructure-list'), params) + return self.client.get(reverse("apiv2:infrastructure-list"), params) def get_infrastructure_detail(self, id_infrastructure, params=None): - return self.client.get(reverse('apiv2:infrastructure-detail', args=(id_infrastructure,)), params) + return self.client.get( + reverse("apiv2:infrastructure-detail", args=(id_infrastructure,)), params + ) def get_infrastructurecondition_list(self, params=None): - return self.client.get(reverse('apiv2:infrastructure-condition-list'), params) + return self.client.get(reverse("apiv2:infrastructure-condition-list"), params) - def get_infrastructurecondition_detail(self, id_infrastructurecondition, params=None): - return self.client.get(reverse('apiv2:infrastructure-condition-detail', args=(id_infrastructurecondition,)), params) + def get_infrastructurecondition_detail( + self, id_infrastructurecondition, params=None + ): + return self.client.get( + reverse( + "apiv2:infrastructure-condition-detail", + args=(id_infrastructurecondition,), + ), + params, + ) def get_infrastructuremaintenancedifficulty_list(self, params=None): - return self.client.get(reverse('apiv2:infrastructure-maintenance-difficulty-list'), params) + return self.client.get( + reverse("apiv2:infrastructure-maintenance-difficulty-list"), params + ) - def get_infrastructuremaintenancedifficulty_detail(self, id_infrastructuremaintenancedifficulty, params=None): - return self.client.get(reverse('apiv2:infrastructure-maintenance-difficulty-detail', args=(id_infrastructuremaintenancedifficulty,)), params) + def get_infrastructuremaintenancedifficulty_detail( + self, id_infrastructuremaintenancedifficulty, params=None + ): + return self.client.get( + reverse( + "apiv2:infrastructure-maintenance-difficulty-detail", + args=(id_infrastructuremaintenancedifficulty,), + ), + params, + ) def get_infrastructureusagedifficulty_list(self, params=None): - return self.client.get(reverse('apiv2:infrastructure-usage-difficulty-list'), params) + return self.client.get( + reverse("apiv2:infrastructure-usage-difficulty-list"), params + ) - def get_infrastructureusagedifficulty_detail(self, id_infrastructureusagedifficulty, params=None): - return self.client.get(reverse('apiv2:infrastructure-usage-difficulty-detail', args=(id_infrastructureusagedifficulty,)), params) + def get_infrastructureusagedifficulty_detail( + self, id_infrastructureusagedifficulty, params=None + ): + return self.client.get( + reverse( + "apiv2:infrastructure-usage-difficulty-detail", + args=(id_infrastructureusagedifficulty,), + ), + params, + ) def get_signage_detail(self, id_signage, params=None): - return self.client.get(reverse('apiv2:signage-detail', args=(id_signage,)), params) + return self.client.get( + reverse("apiv2:signage-detail", args=(id_signage,)), params + ) def get_signage_list(self, params=None): - return self.client.get(reverse('apiv2:signage-list'), params) + return self.client.get(reverse("apiv2:signage-list"), params) def get_signagetype_list(self, params=None): - return self.client.get(reverse('apiv2:signage-type-list'), params) + return self.client.get(reverse("apiv2:signage-type-list"), params) def get_signagetype_detail(self, id_signagetype, params=None): - return self.client.get(reverse('apiv2:signage-type-detail', args=(id_signagetype,)), params) + return self.client.get( + reverse("apiv2:signage-type-detail", args=(id_signagetype,)), params + ) def get_signagebladetype_list(self, params=None): - return self.client.get(reverse('apiv2:signage-blade-type-list'), params) + return self.client.get(reverse("apiv2:signage-blade-type-list"), params) def get_signagebladetype_detail(self, id_signagebladetype, params=None): - return self.client.get(reverse('apiv2:signage-blade-type-detail', args=(id_signagebladetype,)), params) + return self.client.get( + reverse("apiv2:signage-blade-type-detail", args=(id_signagebladetype,)), + params, + ) def get_signagesealing_list(self, params=None): - return self.client.get(reverse('apiv2:signage-sealing-list'), params) + return self.client.get(reverse("apiv2:signage-sealing-list"), params) def get_signagesealing_detail(self, id_signagesealing, params=None): - return self.client.get(reverse('apiv2:signage-sealing-detail', args=(id_signagesealing,)), params) + return self.client.get( + reverse("apiv2:signage-sealing-detail", args=(id_signagesealing,)), params + ) def get_signagecolor_list(self, params=None): - return self.client.get(reverse('apiv2:signage-color-list'), params) + return self.client.get(reverse("apiv2:signage-color-list"), params) def get_signagecolor_detail(self, id_signagecolor, params=None): - return self.client.get(reverse('apiv2:signage-color-detail', args=(id_signagecolor,)), params) + return self.client.get( + reverse("apiv2:signage-color-detail", args=(id_signagecolor,)), params + ) def get_signagedirection_list(self, params=None): - return self.client.get(reverse('apiv2:signage-direction-list'), params) + return self.client.get(reverse("apiv2:signage-direction-list"), params) def get_signagedirection_detail(self, id_signagedirection, params=None): - return self.client.get(reverse('apiv2:signage-direction-detail', args=(id_signagedirection,)), params) + return self.client.get( + reverse("apiv2:signage-direction-detail", args=(id_signagedirection,)), + params, + ) def get_sector_list(self, params=None): - return self.client.get(reverse('apiv2:outdoor-sector-list'), params) + return self.client.get(reverse("apiv2:outdoor-sector-list"), params) def get_sector_detail(self, id_sector, params=None): - return self.client.get(reverse('apiv2:outdoor-sector-detail', args=(id_sector,)), params) + return self.client.get( + reverse("apiv2:outdoor-sector-detail", args=(id_sector,)), params + ) def get_hdviewpoint_list(self, params=None): - return self.client.get(reverse('apiv2:hdviewpoint-list'), params) + return self.client.get(reverse("apiv2:hdviewpoint-list"), params) def get_hdviewpoint_detail(self, id_hdviewpoint, params=None): - return self.client.get(reverse('apiv2:hdviewpoint-detail', args=(id_hdviewpoint,)), params) + return self.client.get( + reverse("apiv2:hdviewpoint-detail", args=(id_hdviewpoint,)), params + ) class APIAccessAnonymousTestCase(BaseApiTest): - """ TestCase for anonymous API profile """ + """TestCase for anonymous API profile""" def test_path_list(self): response = self.get_path_list() self.assertEqual(response.status_code, 401) + def test_no_pagination(self): + import pprint + response = self.get_trek_list({"no_page": "true"}) + self.assertEqual(response.status_code, 200) + json_response = response.json() + print(len(json_response)) + pprint(json_response) + self.assertIsInstance(json_response, list) + self.assertIsInstance(json_response[0], dict) + self.assertEqual( + len(json_response[0].get("geometry").get("coordinates")[0]), + 3, + ) + + def test_geojson_no_pagination(self): + response = self.get_trek_list({"no_page": "true", "format": "geojson"}) + self.assertEqual(response.status_code, 200) + json_response = response.json() + print(json_response) + self.assertIsInstance(json_response, dict) + self.assertEqual( + sorted(json_response.keys()), GEOJSON_COLLECTION_STRUCTURE + ) + self.assertEqual( + len(json_response.get("features")), self.nb_treks, json_response + ) + self.assertEqual( + sorted(json_response.get("features")[0].get("properties").keys()), + TREK_PROPERTIES_GEOJSON_STRUCTURE, + ) + def test_trek_list(self): response = self.get_trek_list() # test response code @@ -833,362 +1359,364 @@ def test_trek_list(self): # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), - PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) # trek count is ok - self.assertEqual(len(json_response.get('results')), self.nb_treks) + self.assertEqual(len(json_response.get("results")), self.nb_treks) # test dim 3 by default for treks - self.assertEqual(len(json_response.get('results')[0].get('geometry').get('coordinates')[0]), - 3) + self.assertEqual( + len(json_response.get("results")[0].get("geometry").get("coordinates")[0]), + 3, + ) # regenerate with geojson - response = self.get_trek_list({'format': 'geojson'}) + response = self.get_trek_list({"format": "geojson"}) json_response = response.json() # test geojson format - self.assertEqual(sorted(json_response.keys()), - PAGINATED_GEOJSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual(len(json_response.get('features')), - self.nb_treks, json_response) + self.assertEqual( + len(json_response.get("features")), self.nb_treks, json_response + ) - self.assertEqual(sorted(json_response.get('features')[0].keys()), - GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].keys()), GEOJSON_STRUCTURE + ) - self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), - TREK_PROPERTIES_GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].get("properties").keys()), + TREK_PROPERTIES_GEOJSON_STRUCTURE, + ) def test_trek_list_filters(self): - response = self.get_trek_list({ - 'duration_min': '2', - 'duration_max': '5', - 'length_min': '4', - 'length_max': '20', - 'difficulty_min': '1', - 'difficulty_max': '3', - 'ascent_min': '150', - 'ascent_max': '1000', - 'cities': '31000', - 'districts': self.district.pk, - 'structures': self.structure.pk, - 'accessibilities': self.accessibility.pk, - 'accessibility_level': self.accessibility_level.pk, - 'themes': self.theme2.pk, - 'portals': self.portal.pk, - 'labels': '23', - 'routes': '68', - 'practices': '1', - 'ratings': self.rating.pk, - 'q': 'test string', - }) + response = self.get_trek_list( + { + "duration_min": "2", + "duration_max": "5", + "length_min": "4", + "length_max": "20", + "difficulty_min": "1", + "difficulty_max": "3", + "ascent_min": "150", + "ascent_max": "1000", + "cities": "31000", + "districts": self.district.pk, + "structures": self.structure.pk, + "accessibilities": self.accessibility.pk, + "accessibility_level": self.accessibility_level.pk, + "themes": self.theme2.pk, + "portals": self.portal.pk, + "labels": "23", + "routes": "68", + "practices": "1", + "ratings": self.rating.pk, + "q": "test string", + } + ) # test response code self.assertEqual(response.status_code, 200) # json collection structure is ok json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_theme_filter(self): - response = self.get_trek_list({'themes': self.theme2.pk}) + response = self.get_trek_list({"themes": self.theme2.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'themes': 0}) + response = self.get_trek_list({"themes": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_portal_filter(self): - response = self.get_trek_list({'portals': self.portal.pk}) + response = self.get_trek_list({"portals": self.portal.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'portals': 0}) + response = self.get_trek_list({"portals": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_ids_filter(self): - response = self.get_trek_list({'ids': f"{self.treks[0].pk},{self.treks[1].pk}"}) + response = self.get_trek_list({"ids": f"{self.treks[0].pk},{self.treks[1].pk}"}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 2) + self.assertEqual(len(json_response.get("results")), 2) - response = self.get_trek_list({'ids': 99999}) + response = self.get_trek_list({"ids": 99999}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_label_filter(self): - response = self.get_trek_list({'labels': self.label.pk}) + response = self.get_trek_list({"labels": self.label.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'labels': 0}) + response = self.get_trek_list({"labels": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_labels_exclude_filter(self): - response = self.get_trek_list({'labels_exclude': self.label.pk}) + response = self.get_trek_list({"labels_exclude": self.label.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 18) + self.assertEqual(len(json_response.get("results")), 18) trek = trek_factory.TrekFactory.create() label = common_factory.LabelFactory.create() trek.labels.add(label, self.label) - response = self.get_trek_list({'labels_exclude': self.label.pk}) + response = self.get_trek_list({"labels_exclude": self.label.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 18) + self.assertEqual(len(json_response.get("results")), 18) trek = trek_factory.TrekFactory.create() label_2 = common_factory.LabelFactory.create() trek.labels.add(label, label_2) - response = self.get_trek_list({'labels_exclude': f'{self.label.pk},{label.pk}'}) + response = self.get_trek_list({"labels_exclude": f"{self.label.pk},{label.pk}"}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 18) + self.assertEqual(len(json_response.get("results")), 18) - response = self.get_trek_list({'labels_exclude': label_2.pk}) + response = self.get_trek_list({"labels_exclude": label_2.pk}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 20) + self.assertEqual(len(json_response.get("results")), 20) def test_trek_city_filter(self): path = core_factory.PathFactory.create(geom=LineString((-10, -9), (-9, -9))) - city3 = zoning_factory.CityFactory(code='03000', - geom='SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, -9 -10, -10 -10)))') + city3 = zoning_factory.CityFactory( + code="03000", + geom="SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, -9 -10, -10 -10)))", + ) if settings.TREKKING_TOPOLOGY_ENABLED: trek_factory.TrekFactory.create(paths=[(path, 0, 1)]) else: - trek_factory.TrekFactory.create(geom='SRID=2154;LINESTRING(-10 -9, -9 -9)') - response = self.get_trek_list({'cities': city3.pk}) + trek_factory.TrekFactory.create(geom="SRID=2154;LINESTRING(-10 -9, -9 -9)") + response = self.get_trek_list({"cities": city3.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'cities': 0}) + response = self.get_trek_list({"cities": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_district_filter(self): path = core_factory.PathFactory.create(geom=LineString((-10, -9), (-9, -9))) - dist3 = zoning_factory.DistrictFactory(geom='SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, ' - '-9 -10, -10 -10)))') + dist3 = zoning_factory.DistrictFactory( + geom="SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, " + "-9 -10, -10 -10)))" + ) if settings.TREKKING_TOPOLOGY_ENABLED: trek_factory.TrekFactory.create(paths=[(path, 0, 1)]) else: - trek_factory.TrekFactory.create(geom='SRID=2154;LINESTRING(-10 -9, -9 -9)') - response = self.get_trek_list({'districts': dist3.pk}) + trek_factory.TrekFactory.create(geom="SRID=2154;LINESTRING(-10 -9, -9 -9)") + response = self.get_trek_list({"districts": dist3.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'districts': 0}) + response = self.get_trek_list({"districts": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_structure_filter(self): - response = self.get_trek_list({'structures': self.structure.pk}) + response = self.get_trek_list({"structures": self.structure.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'cities': 0}) + response = self.get_trek_list({"cities": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_practice_filter(self): - response = self.get_trek_list({'practices': self.practice.pk}) + response = self.get_trek_list({"practices": self.practice.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'practices': 0}) + response = self.get_trek_list({"practices": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_accessibility_level_filter(self): - response = self.get_trek_list({'accessibility_level': self.accessibility_level.pk}) + response = self.get_trek_list( + {"accessibility_level": self.accessibility_level.pk} + ) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'accessibility_level': 0}) + response = self.get_trek_list({"accessibility_level": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_routes_filter(self): - response = self.get_trek_list({'routes': self.route.pk}) + response = self.get_trek_list({"routes": self.route.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'routes': 0}) + response = self.get_trek_list({"routes": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_ratings_filter(self): - response = self.get_trek_list({'ratings': self.rating.pk}) + response = self.get_trek_list({"ratings": self.rating.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) - response = self.get_trek_list({'ratings': 0}) + response = self.get_trek_list({"ratings": 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_version_route(self): response = self.client.get("/api/v2/version") self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, {'version': __version__}) + self.assertJSONEqual(response.content, {"version": __version__}) @override_settings(DEBUG=False) def test_handle_404_route(self): response = self.client.get("/api/v2/x") self.assertEqual(response.status_code, 404) - self.assertJSONEqual(response.content, {'page': 'does not exist'}) + self.assertJSONEqual(response.content, {"page": "does not exist"}) def test_trek_list_filter_distance(self): - """ Test Trek list is filtered by reference point distance """ - toulouse_trek_geom = LineString([ - [ - 1.4464187622070312, - 43.65147866566022 - ], - [ - 1.435432434082031, - 43.63682057801007 - ], - [ - 1.4574050903320312, - 43.62439567002734 - ], + """Test Trek list is filtered by reference point distance""" + toulouse_trek_geom = LineString( [ - 1.4426422119140625, - 43.601775746067986 + [1.4464187622070312, 43.65147866566022], + [1.435432434082031, 43.63682057801007], + [1.4574050903320312, 43.62439567002734], + [1.4426422119140625, 43.601775746067986], + [1.473541259765625, 43.58810023846608], ], - [ - 1.473541259765625, - 43.58810023846608 - ]], srid=4326) + srid=4326, + ) toulouse_trek_geom.transform(2154) path_trek = core_factory.PathFactory(geom=toulouse_trek_geom) - trek_toulouse = trek_factory.TrekFactory(paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom) + trek_toulouse = trek_factory.TrekFactory( + paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom + ) # trek is in non filtered list response = self.get_trek_list() # json collection structure is ok json_response = response.json() - ids_treks = [element['id'] for element in json_response['results']] + ids_treks = [element["id"] for element in json_response["results"]] self.assertIn(trek_toulouse.pk, ids_treks, ids_treks) # test trek is in distance filter (< 110 km) - response = self.get_trek_list({ - 'dist': '110000', - 'point': f"{self.reference_point.x},{self.reference_point.y}", - }) + response = self.get_trek_list( + { + "dist": "110000", + "point": f"{self.reference_point.x},{self.reference_point.y}", + } + ) # json collection structure is ok json_response = response.json() - ids_treks = [element['id'] for element in json_response['results']] + ids_treks = [element["id"] for element in json_response["results"]] self.assertIn(trek_toulouse.pk, ids_treks) # test trek is not in distance filter (< 50km) - response = self.get_trek_list({ - 'dist': '50000', - 'point': f"{self.reference_point.x},{self.reference_point.x}", - }) + response = self.get_trek_list( + { + "dist": "50000", + "point": f"{self.reference_point.x},{self.reference_point.x}", + } + ) # json collection structure is ok json_response = response.json() - ids_treks = [element['id'] for element in json_response['results']] + ids_treks = [element["id"] for element in json_response["results"]] self.assertNotIn(trek_toulouse.pk, ids_treks) def test_trek_list_filter_in_bbox(self): - """ Test Trek list is filtered by bbox param """ - toulouse_trek_geom = LineString([ - [ - 1.4464187622070312, - 43.65147866566022 - ], - [ - 1.435432434082031, - 43.63682057801007 - ], - [ - 1.4574050903320312, - 43.62439567002734 - ], + """Test Trek list is filtered by bbox param""" + toulouse_trek_geom = LineString( [ - 1.4426422119140625, - 43.601775746067986 + [1.4464187622070312, 43.65147866566022], + [1.435432434082031, 43.63682057801007], + [1.4574050903320312, 43.62439567002734], + [1.4426422119140625, 43.601775746067986], + [1.473541259765625, 43.58810023846608], ], - [ - 1.473541259765625, - 43.58810023846608 - ]], srid=4326) + srid=4326, + ) toulouse_trek_geom.transform(2154) path_trek = core_factory.PathFactory(geom=toulouse_trek_geom) - trek_toulouse = trek_factory.TrekFactory(paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom) + trek_toulouse = trek_factory.TrekFactory( + paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom + ) trek_toulouse.geom.buffer(10) trek_toulouse.geom.transform(4326) xmin, ymin, xmax, ymax = trek_toulouse.geom.extent # test pois is in bbox filter - response = self.get_trek_list({ - 'in_bbox': f'{xmin},{ymin},{xmax},{ymax}', - }) + response = self.get_trek_list( + { + "in_bbox": f"{xmin},{ymin},{xmax},{ymax}", + } + ) # json collection structure is ok json_response = response.json() - ids_treks = [element['id'] for element in json_response['results']] + ids_treks = [element["id"] for element in json_response["results"]] self.assertIn(trek_toulouse.pk, ids_treks) # test trek is not in distance filter (< 50km) - response = self.get_trek_list({ - 'in_bbox': f'{0.0},{0.0},{1.0},{1.0}', - }) + response = self.get_trek_list( + { + "in_bbox": f"{0.0},{0.0},{1.0},{1.0}", + } + ) # json collection structure is ok json_response = response.json() - ids_treks = [element['id'] for element in json_response['results']] + ids_treks = [element["id"] for element in json_response["results"]] self.assertNotIn(trek_toulouse.pk, ids_treks) def test_trek_list_filtered_by_near_trek(self): @@ -1201,43 +1729,51 @@ def test_trek_list_filtered_by_near_trek(self): self.assertEqual(json_response["count"], 16) def test_trek_list_filters_inexistant_zones(self): - response = self.get_trek_list({ - 'cities': '99999', - 'districts': '999', - }) + response = self.get_trek_list( + { + "cities": "99999", + "districts": "999", + } + ) # test response code self.assertEqual(response.status_code, 200) # json collection structure is ok json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_trek_city(self): - response = self.get_trek_list({'cities': self.city.pk}) - self.assertEqual(len(response.json()['results']), 17) + response = self.get_trek_list({"cities": self.city.pk}) + self.assertEqual(len(response.json()["results"]), 17) def test_trek_district(self): - response = self.get_trek_list({'districts': self.district.pk}) - self.assertEqual(len(response.json()['results']), 17) + response = self.get_trek_list({"districts": self.district.pk}) + self.assertEqual(len(response.json()["results"]), 17) def test_trek_cities(self): - response = self.get_trek_list({'cities': f"{self.city.pk},{self.city2.pk}"}) - self.assertEqual(len(response.json()['results']), 17) + response = self.get_trek_list({"cities": f"{self.city.pk},{self.city2.pk}"}) + self.assertEqual(len(response.json()["results"]), 17) def test_trek_districts(self): - response = self.get_trek_list({'districts': f"{self.district.pk},{self.district2.pk}"}) - self.assertEqual(len(response.json()['results']), 17) + response = self.get_trek_list( + {"districts": f"{self.district.pk},{self.district2.pk}"} + ) + self.assertEqual(len(response.json()["results"]), 17) def test_trek_ratings(self): - response = self.get_trek_list({'ratings': f"{self.rating.pk},{self.rating2.pk}"}) - self.assertEqual(len(response.json()['results']), 2) + response = self.get_trek_list( + {"ratings": f"{self.rating.pk},{self.rating2.pk}"} + ) + self.assertEqual(len(response.json()["results"]), 2) def test_trek_child_not_published_detail_view_ok_if_ancestor_published(self): response = self.get_trek_detail(self.child1.pk) self.assertEqual(response.status_code, 200) - def test_trek_child_not_published_detail_view_ko_if_ancestor_published_not_in_requested_language(self): - response = self.get_trek_detail(self.child1.pk, {'language': 'fr'}) + def test_trek_child_not_published_detail_view_ko_if_ancestor_published_not_in_requested_language( + self, + ): + response = self.get_trek_detail(self.child1.pk, {"language": "fr"}) self.assertEqual(response.status_code, 404) def test_trek_child_not_published_detail_view_ko_if_ancestor_not_published(self): @@ -1245,7 +1781,7 @@ def test_trek_child_not_published_detail_view_ko_if_ancestor_not_published(self) self.assertEqual(response.status_code, 404) def test_trek_child_not_published_not_in_list_view_if_ancestor_published(self): - response = self.get_trek_list({'fields': 'id'}) + response = self.get_trek_list({"fields": "id"}) self.assertNotContains(response, str(self.child1.pk)) def test_tour_list(self): @@ -1255,30 +1791,38 @@ def test_tour_list(self): # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), - PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) # trek count is ok - self.assertEqual(len(json_response.get('results')), 2) # Two parents + self.assertEqual(len(json_response.get("results")), 2) # Two parents # regenrate with geojson - response = self.get_tour_list({'format': 'geojson'}) + response = self.get_tour_list({"format": "geojson"}) json_response = response.json() # test geojson format self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual(len(json_response.get('features')), 2) + self.assertEqual(len(json_response.get("features")), 2) # test dim 3 ok - self.assertEqual(len(json_response.get('features')[0].get('geometry').get('coordinates')[0]), - 3, json_response.get('features')[0].get('geometry').get('coordinates')[0]) + self.assertEqual( + len(json_response.get("features")[0].get("geometry").get("coordinates")[0]), + 3, + json_response.get("features")[0].get("geometry").get("coordinates")[0], + ) - self.assertEqual(sorted(json_response.get('features')[0].keys()), GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].keys()), GEOJSON_STRUCTURE + ) - self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), - TOUR_PROPERTIES_GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].get("properties").keys()), + TOUR_PROPERTIES_GEOJSON_STRUCTURE, + ) - self.assertEqual(json_response.get('features')[1].get('properties').get('count_children'), 1) + self.assertEqual( + json_response.get("features")[1].get("properties").get("count_children"), 1 + ) @override_settings(ONLY_EXTERNAL_PUBLIC_PDF=True) def test_trek_external_pdf(self): @@ -1296,29 +1840,38 @@ def test_trek_detail_categories_split_practice(self): self.assertEqual(response.status_code, 200) def test_trek_detail_with_lang(self): - response = self.get_trek_list({'language': 'en'}) + response = self.get_trek_list({"language": "en"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['results'][0]['pdf'], - f'http://testserver/api/en/treks/{self.child2.pk}/child-2.pdf') + self.assertEqual( + response.json()["results"][0]["pdf"], + f"http://testserver/api/en/treks/{self.child2.pk}/child-2.pdf", + ) def test_trek_detail_img_src_are_completed_in_descriptions(self): response = self.get_trek_detail(self.treks[0].pk) self.assertEqual(response.status_code, 200) # Note that tags are sorted and the HTML format slightly changed during the "src" processing. - expected_description = '

Some HTML content with images

'\ - 'Descent'\ - '' - self.assertEqual(response.json()['description']['en'], expected_description) - self.assertEqual(response.json()['description_teaser']['en'], expected_description) - self.assertEqual(response.json()['ambiance']['en'], expected_description) + expected_description = ( + "

Some HTML content with images

" + 'Descent' + '' + ) + self.assertEqual(response.json()["description"]["en"], expected_description) + self.assertEqual( + response.json()["description_teaser"]["en"], expected_description + ) + self.assertEqual(response.json()["ambiance"]["en"], expected_description) # Same test requesting a specific language - response = self.get_trek_detail(self.treks[0].pk, params={'language': 'en'}) + response = self.get_trek_detail(self.treks[0].pk, params={"language": "en"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['description'], expected_description) - self.assertEqual(response.json()['description_teaser'], expected_description) - self.assertEqual(response.json()['ambiance'], expected_description) - self.assertEqual(response.json()['view_points'][0]['geometry'], {'type': 'Point', 'coordinates': [-1.3630812, -5.9838563]}) + self.assertEqual(response.json()["description"], expected_description) + self.assertEqual(response.json()["description_teaser"], expected_description) + self.assertEqual(response.json()["ambiance"], expected_description) + self.assertEqual( + response.json()["view_points"][0]["geometry"], + {"type": "Point", "coordinates": [-1.3630812, -5.9838563]}, + ) def test_difficulty_list(self): response = self.get_difficulties_list() @@ -1337,7 +1890,7 @@ def test_practice_detail(self): self.assertEqual(response.status_code, 200) def test_network_list(self): - response = self.get_networks_list({'portals': self.portal.pk}) + response = self.get_networks_list({"portals": self.portal.pk}) self.assertContains(response, self.network.network) def test_network_detail(self): @@ -1345,7 +1898,7 @@ def test_network_detail(self): self.assertEqual(response.status_code, 200) def test_theme_list(self): - response = self.get_themes_list({'portals': self.portal.pk}) + response = self.get_themes_list({"portals": self.portal.pk}) self.assertContains(response, self.theme.label) self.assertContains(response, self.theme3.label) @@ -1356,141 +1909,125 @@ def test_theme_list_filter_portal(self): trek.themes.add(self.theme) trek.save() # Ok because the trek is published - response = self.get_themes_list({'portals': portal2.pk}) + response = self.get_themes_list({"portals": portal2.pk}) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 1) + self.assertEqual(len(json_response.get("results")), 1) trek.published = False trek.save() # No theme should be returned because the trek is not published anymore - response = self.get_themes_list({'portals': portal2.pk}) + response = self.get_themes_list({"portals": portal2.pk}) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) trek.published = True trek.deleted = True trek.save() # No theme should be returned because the published trek on this portal is deleted - response = self.get_themes_list({'portals': portal2.pk}) + response = self.get_themes_list({"portals": portal2.pk}) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 0) + self.assertEqual(len(json_response.get("results")), 0) def test_city_list(self): - self.check_number_elems_response( - self.get_city_list(), - zoning_models.City - ) + self.check_number_elems_response(self.get_city_list(), zoning_models.City) def test_city_detail(self): self.check_structure_response( - self.get_city_detail(self.city.pk), - CITY_PROPERTIES_JSON_STRUCTURE + self.get_city_detail(self.city.pk), CITY_PROPERTIES_JSON_STRUCTURE ) def test_district_list(self): self.check_number_elems_response( - self.get_district_list(), - zoning_models.District + self.get_district_list(), zoning_models.District ) def test_district_detail(self): self.check_structure_response( self.get_district_detail(self.district.pk), - DISTRICT_PROPERTIES_JSON_STRUCTURE + DISTRICT_PROPERTIES_JSON_STRUCTURE, ) def test_route_list(self): - self.check_number_elems_response( - self.get_route_list(), - trek_models.Route - ) + self.check_number_elems_response(self.get_route_list(), trek_models.Route) def test_sector_detail(self): self.check_structure_response( self.get_sector_detail(self.sector.pk), - OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE + OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE, ) def test_sector_list(self): - self.check_number_elems_response( - self.get_sector_list(), - outdoor_models.Sector - ) + self.check_number_elems_response(self.get_sector_list(), outdoor_models.Sector) def test_hdviewpoint_detail(self): self.check_structure_response( self.get_hdviewpoint_detail(self.hdviewpoint_trek.pk), - HDVIEWPOINT_DETAIL_JSON_STRUCTURE + HDVIEWPOINT_DETAIL_JSON_STRUCTURE, ) def test_hdviewpoint_list(self): self.check_number_elems_response( - self.get_hdviewpoint_list(), - common_models.HDViewPoint + self.get_hdviewpoint_list(), common_models.HDViewPoint ) def test_route_detail(self): self.check_structure_response( - self.get_route_detail(self.route.pk), - ROUTE_PROPERTIES_JSON_STRUCTURE + self.get_route_detail(self.route.pk), ROUTE_PROPERTIES_JSON_STRUCTURE ) def test_accessibility_list(self): self.check_number_elems_response( - self.get_accessibility_list(), - trek_models.Accessibility + self.get_accessibility_list(), trek_models.Accessibility ) def test_accessibility_level_list(self): self.check_number_elems_response( - self.get_accessibility_level_list(), - trek_models.AccessibilityLevel + self.get_accessibility_level_list(), trek_models.AccessibilityLevel ) def test_accessibility_detail(self): self.check_structure_response( self.get_accessibility_detail(self.accessibility.pk), - ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE + ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE, ) def test_accessibility_level_detail(self): self.check_structure_response( self.get_accessibility_level_detail(self.accessibility_level.pk), - ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE + ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE, ) def test_theme_detail(self): self.check_structure_response( - self.get_themes_detail(self.theme2.pk), - THEME_PROPERTIES_JSON_STRUCTURE + self.get_themes_detail(self.theme2.pk), THEME_PROPERTIES_JSON_STRUCTURE ) def test_portal_list(self): self.check_number_elems_response( - self.get_portal_list(), - common_models.TargetPortal + self.get_portal_list(), common_models.TargetPortal ) def test_portal_detail(self): self.check_structure_response( self.get_portal_detail(self.portal.pk), - TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE + TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE, ) def test_structure_list(self): self.check_number_elems_response( - self.get_structure_list(), - authent_models.Structure + self.get_structure_list(), authent_models.Structure ) def test_structure_filter_list(self): - response = self.get_structure_list({'portals': self.portal.pk, 'language': 'en'}) - self.assertEquals(len(response.json()['results']), 1) + response = self.get_structure_list( + {"portals": self.portal.pk, "language": "en"} + ) + self.assertEquals(len(response.json()["results"]), 1) def test_structure_detail(self): self.check_structure_response( self.get_structure_detail(self.structure.pk), - STRUCTURE_PROPERTIES_JSON_STRUCTURE + STRUCTURE_PROPERTIES_JSON_STRUCTURE, ) def test_service_list(self): @@ -1498,72 +2035,77 @@ def test_service_list(self): json_response = response.json() self.assertEqual(response.status_code, 200) services = trek_models.Service.objects.all() - self.assertEquals(len(json_response['results']), services.count() - 1, services.filter(type__published=True).count()) + self.assertEquals( + len(json_response["results"]), + services.count() - 1, + services.filter(type__published=True).count(), + ) def test_service_detail(self): self.check_structure_response( - self.get_service_detail(self.service.pk), - SERVICE_DETAIL_JSON_STRUCTURE + self.get_service_detail(self.service.pk), SERVICE_DETAIL_JSON_STRUCTURE ) def test_infrastructure_list(self): self.check_number_elems_response( - self.get_infrastructure_list(), - infrastructure_models.Infrastructure + self.get_infrastructure_list(), infrastructure_models.Infrastructure ) def test_infrastructure_detail(self): self.check_structure_response( self.get_infrastructure_detail(self.infrastructure.pk), - INFRASTRUCTURE_DETAIL_JSON_STRUCTURE + INFRASTRUCTURE_DETAIL_JSON_STRUCTURE, ) def test_infrastructuretype_list(self): self.check_number_elems_response( - self.get_infrastructuretype_list(), - infrastructure_models.InfrastructureType + self.get_infrastructuretype_list(), infrastructure_models.InfrastructureType ) def test_infrastructuretype_detail(self): self.check_structure_response( self.get_infrastructuretype_detail(self.infrastructure_type.pk), - INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE + INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE, ) def test_infrastructurecondition_list(self): self.check_number_elems_response( self.get_infrastructurecondition_list(), - infrastructure_models.InfrastructureCondition + infrastructure_models.InfrastructureCondition, ) def test_infrastructurecondition_detail(self): self.check_structure_response( self.get_infrastructurecondition_detail(self.infrastructure_condition.pk), - INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE + INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE, ) def test_infrastructuremaintenancedifficulty_list(self): self.check_number_elems_response( self.get_infrastructuremaintenancedifficulty_list(), - infrastructure_models.InfrastructureMaintenanceDifficultyLevel + infrastructure_models.InfrastructureMaintenanceDifficultyLevel, ) def test_infrastructuremaintenancedifficulty_detail(self): self.check_structure_response( - self.get_infrastructuremaintenancedifficulty_detail(self.infrastructure_maintenancedifficulty.pk), - INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE + self.get_infrastructuremaintenancedifficulty_detail( + self.infrastructure_maintenancedifficulty.pk + ), + INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE, ) def test_infrastructureusagedifficulty_list(self): self.check_number_elems_response( self.get_infrastructureusagedifficulty_list(), - infrastructure_models.InfrastructureUsageDifficultyLevel + infrastructure_models.InfrastructureUsageDifficultyLevel, ) def test_infrastructureusagedifficulty_detail(self): self.check_structure_response( - self.get_infrastructureusagedifficulty_detail(self.infrastructure_usagedifficulty.pk), - INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE + self.get_infrastructureusagedifficulty_detail( + self.infrastructure_usagedifficulty.pk + ), + INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE, ) def test_servicetype_list(self): @@ -1571,88 +2113,85 @@ def test_servicetype_list(self): json_response = response.json() self.assertEqual(response.status_code, 200) services = trek_models.ServiceType.objects.all() - self.assertEquals(len(json_response['results']), services.count() - 1, services.filter(published=True).count()) + self.assertEquals( + len(json_response["results"]), + services.count() - 1, + services.filter(published=True).count(), + ) def test_servicetype_detail(self): self.check_structure_response( self.get_servicetype_detail(self.service_type.pk), - SERVICE_TYPE_DETAIL_JSON_STRUCTURE + SERVICE_TYPE_DETAIL_JSON_STRUCTURE, ) def test_signage_detail(self): self.check_structure_response( - self.get_signage_detail(self.signage.pk), - SIGNAGE_DETAIL_JSON_STRUCTURE + self.get_signage_detail(self.signage.pk), SIGNAGE_DETAIL_JSON_STRUCTURE ) def test_signage_list(self): self.check_number_elems_response( - self.get_signage_list(), - signage_models.Signage + self.get_signage_list(), signage_models.Signage ) def test_signagetype_list(self): self.check_number_elems_response( - self.get_signagetype_list(), - signage_models.SignageType + self.get_signagetype_list(), signage_models.SignageType ) def test_signagetype_detail(self): self.check_structure_response( self.get_signagetype_detail(self.signagetype.pk), - SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE + SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE, ) def test_signagebladetype_list(self): self.check_number_elems_response( - self.get_signagebladetype_list(), - signage_models.BladeType + self.get_signagebladetype_list(), signage_models.BladeType ) def test_signagebladetype_detail(self): self.check_structure_response( self.get_signagebladetype_detail(self.bladetype.pk), - SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE + SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE, ) def test_signagesealing_list(self): self.check_number_elems_response( - self.get_signagesealing_list(), - signage_models.Sealing + self.get_signagesealing_list(), signage_models.Sealing ) def test_signagesealing_detail(self): self.check_structure_response( self.get_signagesealing_detail(self.sealing.pk), - SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE + SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE, ) def test_signagecolor_list(self): self.check_number_elems_response( - self.get_signagecolor_list(), - signage_models.Color + self.get_signagecolor_list(), signage_models.Color ) def test_signagecolor_detail(self): self.check_structure_response( self.get_signagecolor_detail(self.color.pk), - SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE + SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE, ) def test_signagedirection_list(self): self.check_number_elems_response( - self.get_signagedirection_list(), - signage_models.Direction + self.get_signagedirection_list(), signage_models.Direction ) def test_signagedirection_detail(self): self.check_structure_response( self.get_signagedirection_detail(self.direction.pk), - SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE + SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE, ) def test_service_types_filter(self): - response = self.get_service_list({'types': self.service_type.pk}) + response = self.get_service_list({"types": self.service_type.pk}) self.assertEqual(response.json().get("count"), 1) def test_poi_list(self): @@ -1662,34 +2201,45 @@ def test_poi_list(self): # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), - PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) # trek count is ok - self.assertEqual(len(json_response.get('results')), - trek_models.POI.objects.all().count()) + self.assertEqual( + len(json_response.get("results")), trek_models.POI.objects.all().count() + ) # regenerate with geojson 3D - response = self.get_poi_list({'format': 'geojson'}) + response = self.get_poi_list({"format": "geojson"}) json_response = response.json() # test geojson format - self.assertEqual(sorted(json_response.keys()), - PAGINATED_GEOJSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual(len(json_response.get('features')), - trek_models.POI.objects.all().count()) + self.assertEqual( + len(json_response.get("features")), trek_models.POI.objects.all().count() + ) # test dim 3 - self.assertEqual(len(json_response.get('features')[0].get('geometry').get('coordinates')), - 3) + self.assertEqual( + len(json_response.get("features")[0].get("geometry").get("coordinates")), 3 + ) - self.assertEqual(sorted(json_response.get('features')[0].keys()), - GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].keys()), GEOJSON_STRUCTURE + ) - self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), - POI_PROPERTIES_GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].get("properties").keys()), + POI_PROPERTIES_GEOJSON_STRUCTURE, + ) - response = self.get_poi_list({'types': self.poi_type.pk, 'trek': self.treks[0].pk, 'sites': self.site.pk, 'courses': self.course.pk}) + response = self.get_poi_list( + { + "types": self.poi_type.pk, + "trek": self.treks[0].pk, + "sites": self.site.pk, + "courses": self.course.pk, + } + ) self.assertEqual(response.status_code, 200) def launch_tests_excluded_pois(self, obj, filter_name): @@ -1698,8 +2248,8 @@ def launch_tests_excluded_pois(self, obj, filter_name): # test response code self.assertEqual(response.status_code, 200) self.assertEqual( - len(json_response.get('results')), - trek_models.POI.objects.all().count() - 1 # 1 excluded POI + len(json_response.get("results")), + trek_models.POI.objects.all().count() - 1, # 1 excluded POI ) obj.pois_excluded.add(self.poi) obj.save() @@ -1709,32 +2259,48 @@ def launch_tests_excluded_pois(self, obj, filter_name): # test response code self.assertEqual(response.status_code, 200) self.assertEqual( - len(json_response.get('results')), - trek_models.POI.objects.all().count() - 2 # 1 excluded POI + len(json_response.get("results")), + trek_models.POI.objects.all().count() - 2, # 1 excluded POI ) def test_poi_list_filter_trek(self): - self.launch_tests_excluded_pois(self.treks[0], 'trek') + self.launch_tests_excluded_pois(self.treks[0], "trek") def test_poi_list_filter_courses(self): - self.launch_tests_excluded_pois(self.course, 'courses') + self.launch_tests_excluded_pois(self.course, "courses") def test_poi_list_filter_sites(self): - self.launch_tests_excluded_pois(self.site, 'sites') + self.launch_tests_excluded_pois(self.site, "sites") def test_poi_list_filtered_by_near_trek(self): if settings.TREKKING_TOPOLOGY_ENABLED: trek = trek_factory.TrekFactory() - trek_factory.POIFactory(paths=[(trek.paths.first(), 0.5, 0.5)], name="a POI near trek") + trek_factory.POIFactory( + paths=[(trek.paths.first(), 0.5, 0.5)], name="a POI near trek" + ) far_away_coords = [[n + 2000 for n in c] for c in trek.geom.coords] - far_away_path = core_factory.PathFactory(geom=LineString(far_away_coords, srid=settings.SRID)) - trek_factory.POIFactory(paths=[far_away_path, 0.5, 0.5], name="a POI far from trek") - near_excluded_poi = trek_factory.POIFactory(paths=[(trek.paths.first(), 0.2, 0.2)]) + far_away_path = core_factory.PathFactory( + geom=LineString(far_away_coords, srid=settings.SRID) + ) + trek_factory.POIFactory( + paths=[far_away_path, 0.5, 0.5], name="a POI far from trek" + ) + near_excluded_poi = trek_factory.POIFactory( + paths=[(trek.paths.first(), 0.2, 0.2)] + ) else: - trek = trek_factory.TrekFactory(geom=LineString(Point(500, 600), Point(550, 800), srid=settings.SRID)) - trek_factory.POIFactory(geom=Point(525, 700, srid=settings.SRID), name="a POI near trek") - trek_factory.POIFactory(geom=Point(2500, 3000, srid=settings.SRID), name="a POI far from trek") - near_excluded_poi = trek_factory.POIFactory(geom=Point(510, 620, srid=settings.SRID)) + trek = trek_factory.TrekFactory( + geom=LineString(Point(500, 600), Point(550, 800), srid=settings.SRID) + ) + trek_factory.POIFactory( + geom=Point(525, 700, srid=settings.SRID), name="a POI near trek" + ) + trek_factory.POIFactory( + geom=Point(2500, 3000, srid=settings.SRID), name="a POI far from trek" + ) + near_excluded_poi = trek_factory.POIFactory( + geom=Point(510, 620, srid=settings.SRID) + ) trek.pois_excluded.add(near_excluded_poi) for filtername in ["near_trek", "trek"]: @@ -1745,70 +2311,79 @@ def test_poi_list_filtered_by_near_trek(self): json_response = response.json() self.assertEqual(json_response["count"], 1) response_poi = json_response["results"][0] - self.assertEqual(response_poi["name"][settings.MODELTRANSLATION_DEFAULT_LANGUAGE], "a POI near trek") + self.assertEqual( + response_poi["name"][settings.MODELTRANSLATION_DEFAULT_LANGUAGE], + "a POI near trek", + ) def test_poi_list_filter_distance(self): - """ Test POI list is filtered by reference point distance """ - geom_path = LineString([(1.4464187622070312, 43.65147866566022), - (1.435432434082031, 43.63682057801007)], srid=4326) + """Test POI list is filtered by reference point distance""" + geom_path = LineString( + [ + (1.4464187622070312, 43.65147866566022), + (1.435432434082031, 43.63682057801007), + ], + srid=4326, + ) geom_path.transform(2154) pois_path = core_factory.PathFactory(geom=geom_path) - geom_point_1 = Point(x=1.4464187622070312, - y=43.65147866566022, srid=4326) + geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) geom_point_1.transform(2154) - poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], - geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, - y=43.63682057801007, srid=4326) + poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_1) + geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) geom_point_2.transform(2154) - poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], - geom=geom_point_2) + poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_2) # pois are in list is in non filtered list response = self.get_poi_list() # json collection structure is ok json_response = response.json() - ids_pois = [element['id'] for element in json_response['results']] + ids_pois = [element["id"] for element in json_response["results"]] self.assertIn(poi_1.pk, ids_pois) self.assertIn(poi_2.pk, ids_pois) # test pois is in distance filter (< 110000 km) - response = self.get_poi_list({ - 'dist': '110000', - 'point': f"{self.reference_point.x},{self.reference_point.y}", - }) + response = self.get_poi_list( + { + "dist": "110000", + "point": f"{self.reference_point.x},{self.reference_point.y}", + } + ) # json collection structure is ok json_response = response.json() - ids_pois = [element['id'] for element in json_response['results']] + ids_pois = [element["id"] for element in json_response["results"]] self.assertIn(poi_1.pk, ids_pois) self.assertIn(poi_2.pk, ids_pois) # test trek is not in distance filter (< 50km) - response = self.get_poi_list({ - 'dist': '50000', - 'point': f"{self.reference_point.x},{self.reference_point.x}", - }) + response = self.get_poi_list( + { + "dist": "50000", + "point": f"{self.reference_point.x},{self.reference_point.x}", + } + ) # json collection structure is ok json_response = response.json() - ids_pois = [element['id'] for element in json_response['results']] + ids_pois = [element["id"] for element in json_response["results"]] self.assertNotIn(poi_1.pk, ids_pois) self.assertNotIn(poi_2.pk, ids_pois) def test_poi_list_filter_in_bbox(self): - """ Test POI list is filtered by bbox param """ - geom_path = LineString([(1.4464187622070312, 43.65147866566022), - (1.435432434082031, 43.63682057801007)], srid=4326) + """Test POI list is filtered by bbox param""" + geom_path = LineString( + [ + (1.4464187622070312, 43.65147866566022), + (1.435432434082031, 43.63682057801007), + ], + srid=4326, + ) geom_path.transform(2154) pois_path = core_factory.PathFactory(geom=geom_path) - geom_point_1 = Point(x=1.4464187622070312, - y=43.65147866566022, srid=4326) + geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) geom_point_1.transform(2154) - poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], - geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, - y=43.63682057801007, srid=4326) + poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_1) + geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) geom_point_2.transform(2154) - poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], - geom=geom_point_2) + poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_2) test_bbox = LineString(geom_point_1, geom_point_2, srid=2154) test_bbox.buffer(10) @@ -1816,22 +2391,26 @@ def test_poi_list_filter_in_bbox(self): xmin, ymin, xmax, ymax = test_bbox.extent # test pois is in bbox filter - response = self.get_poi_list({ - 'in_bbox': f'{xmin},{ymin},{xmax},{ymax}', - }) + response = self.get_poi_list( + { + "in_bbox": f"{xmin},{ymin},{xmax},{ymax}", + } + ) # json collection structure is ok json_response = response.json() - ids_pois = [element['id'] for element in json_response['results']] + ids_pois = [element["id"] for element in json_response["results"]] self.assertIn(poi_1.pk, ids_pois) self.assertIn(poi_2.pk, ids_pois) # test trek is not in distance filter (< 50km) - response = self.get_poi_list({ - 'in_bbox': f'{0.0},{0.0},{1.0},{1.0}', - }) + response = self.get_poi_list( + { + "in_bbox": f"{0.0},{0.0},{1.0},{1.0}", + } + ) # json collection structure is ok json_response = response.json() - ids_pois = [element['id'] for element in json_response['results']] + ids_pois = [element["id"] for element in json_response["results"]] self.assertNotIn(poi_1.pk, ids_pois) self.assertNotIn(poi_2.pk, ids_pois) @@ -1846,7 +2425,7 @@ def test_poi_published_detail(self): def test_poi_not_published_detail_lang_en(self): id_poi = trek_factory.POIFactory.create(published_fr=True, published=False) - response = self.get_poi_detail(id_poi.pk, {'language': 'en'}) + response = self.get_poi_detail(id_poi.pk, {"language": "en"}) self.assertEqual(response.status_code, 404) def test_poi_not_published_detail(self): @@ -1857,53 +2436,52 @@ def test_poi_not_published_detail(self): def test_touristiccontentcategory_detail(self): self.check_structure_response( self.get_touristiccontentcategory_detail(self.category.pk), - TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE + TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE, ) def test_touristiccontentcategory_list(self): json_response = self.get_touristiccontentcategory_list().json() # Get two objects for the two published touristic contents - self.assertEquals(len(json_response['results']), 2) + self.assertEquals(len(json_response["results"]), 2) def test_touristiccontentcategory_list_filter(self): - response = self.get_touristiccontentcategory_list({'portals': self.portal.pk}) - self.assertEquals(len(response.json()['results']), 1) + response = self.get_touristiccontentcategory_list({"portals": self.portal.pk}) + self.assertEquals(len(response.json()["results"]), 1) def test_touristiccontent_detail(self): self.check_structure_response( self.get_touristiccontent_detail(self.content.pk), - TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE + TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE, ) @override_settings(ONLY_EXTERNAL_PUBLIC_PDF=True) def test_touristiccontent_external_pdf(self): self.check_structure_response( self.get_touristiccontent_detail(self.content.pk), - TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE + TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE, ) def test_touristiccontent_list(self): - """ Test Touristic content list access and structure """ + """Test Touristic content list access and structure""" response = self.get_touristiccontent_list() self.assertEqual(response.status_code, 200) # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), - PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) # touristiccontent count is ok - self.assertEqual(len(json_response.get('results')), - tourism_models.TouristicContent.objects.all().count()) + self.assertEqual( + len(json_response.get("results")), + tourism_models.TouristicContent.objects.all().count(), + ) def test_touristiccontent_list_filter_distance(self): - """ Test Touristic content list is filtered by reference point distance """ - geom_point_1 = Point(x=1.4464187622070312, - y=43.65147866566022, srid=4326) + """Test Touristic content list is filtered by reference point distance""" + geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) geom_point_1.transform(2154) tc_1 = tourism_factory.TouristicContentFactory(geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, - y=43.63682057801007, srid=4326) + geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) geom_point_2.transform(2154) tc_2 = tourism_factory.TouristicContentFactory(geom=geom_point_2) @@ -1911,40 +2489,42 @@ def test_touristiccontent_list_filter_distance(self): response = self.get_touristiccontent_list() self.assertEqual(response.status_code, 200) json_response = response.json() - ids = [element['id'] for element in json_response['results']] + ids = [element["id"] for element in json_response["results"]] self.assertIn(tc_1.pk, ids) self.assertIn(tc_2.pk, ids) # test present filtering < 110km - response = self.get_touristiccontent_list({ - 'dist': '110000', - 'point': f"{self.reference_point.x},{self.reference_point.y}", - }) + response = self.get_touristiccontent_list( + { + "dist": "110000", + "point": f"{self.reference_point.x},{self.reference_point.y}", + } + ) json_response = response.json() - ids = [element['id'] for element in json_response['results']] + ids = [element["id"] for element in json_response["results"]] self.assertIn(tc_1.pk, ids) self.assertIn(tc_2.pk, ids) # test present filtering < 50km - response = self.get_touristiccontent_list({ - 'dist': '50000', - 'point': f"{self.reference_point.x},{self.reference_point.y}", - }) + response = self.get_touristiccontent_list( + { + "dist": "50000", + "point": f"{self.reference_point.x},{self.reference_point.y}", + } + ) json_response = response.json() - ids = [element['id'] for element in json_response['results']] + ids = [element["id"] for element in json_response["results"]] self.assertNotIn(tc_1.pk, ids) self.assertNotIn(tc_2.pk, ids) def test_touristiccontent_list_filter_in_bbox(self): - """ Test Touristic content list is filtered by bbox """ - geom_point_1 = Point(x=1.4464187622070312, - y=43.65147866566022, srid=4326) + """Test Touristic content list is filtered by bbox""" + geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) geom_point_1.transform(2154) tc_1 = tourism_factory.TouristicContentFactory(geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, - y=43.63682057801007, srid=4326) + geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) geom_point_2.transform(2154) tc_2 = tourism_factory.TouristicContentFactory(geom=geom_point_2) @@ -1954,263 +2534,274 @@ def test_touristiccontent_list_filter_in_bbox(self): xmin, ymin, xmax, ymax = bbox.extent # test present filtering < 110km - response = self.get_touristiccontent_list({ - 'in_bbox': f"{xmin},{ymin},{xmax},{ymax}", - }) + response = self.get_touristiccontent_list( + { + "in_bbox": f"{xmin},{ymin},{xmax},{ymax}", + } + ) json_response = response.json() - ids = [element['id'] for element in json_response['results']] + ids = [element["id"] for element in json_response["results"]] self.assertIn(tc_1.pk, ids) self.assertIn(tc_2.pk, ids) # test present filtering < 50km - response = self.get_touristiccontent_list({ - 'in_bbox': f"{0.0},{0.0},{1.0},{1.0}", - }) + response = self.get_touristiccontent_list( + { + "in_bbox": f"{0.0},{0.0},{1.0},{1.0}", + } + ) json_response = response.json() - ids = [element['id'] for element in json_response['results']] + ids = [element["id"] for element in json_response["results"]] self.assertNotIn(tc_1.pk, ids) self.assertNotIn(tc_2.pk, ids) def test_touristiccontent_near_trek(self): - response = self.get_touristiccontent_list({'near_trek': self.treks[0].pk}) - self.assertEqual(len(response.json()['results']), 2) + response = self.get_touristiccontent_list({"near_trek": self.treks[0].pk}) + self.assertEqual(len(response.json()["results"]), 2) def test_touristiccontent_near_missing_trek(self): - response = self.get_touristiccontent_list({'near_trek': 42666}) - self.assertEqual(len(response.json()['results']), 0) + response = self.get_touristiccontent_list({"near_trek": 42666}) + self.assertEqual(len(response.json()["results"]), 0) def test_touristiccontent_categories(self): - response = self.get_touristiccontent_list({'categories': self.content.category.pk}) - self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list( + {"categories": self.content.category.pk} + ) + self.assertEqual(len(response.json()["results"]), 1) def test_touristiccontent_types(self): tct1 = tourism_factory.TouristicContentType1Factory() - response = self.get_touristiccontent_list({'types': self.content.type1.all()[0].pk}) - self.assertEqual(len(response.json()['results']), 1) - response = self.get_touristiccontent_list({'types': self.content.type2.all()[0].pk}) - self.assertEqual(len(response.json()['results']), 1) - response = self.get_touristiccontent_list({ - 'types': '{},{}'.format(self.content.type1.all()[0].pk, self.content.type2.all()[0].pk) - }) - self.assertEqual(len(response.json()['results']), 1) - response = self.get_touristiccontent_list({'types': '{},{}'.format(self.content.type1.all()[0].pk, tct1.pk)}) - self.assertEqual(len(response.json()['results']), 1) - response = self.get_touristiccontent_list({'types': '{},{}'.format(self.content.type2.all()[0].pk, tct1.pk)}) - self.assertEqual(len(response.json()['results']), 0) + response = self.get_touristiccontent_list( + {"types": self.content.type1.all()[0].pk} + ) + self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list( + {"types": self.content.type2.all()[0].pk} + ) + self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list( + { + "types": "{},{}".format( + self.content.type1.all()[0].pk, self.content.type2.all()[0].pk + ) + } + ) + self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list( + {"types": "{},{}".format(self.content.type1.all()[0].pk, tct1.pk)} + ) + self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list( + {"types": "{},{}".format(self.content.type2.all()[0].pk, tct1.pk)} + ) + self.assertEqual(len(response.json()["results"]), 0) def test_touristiccontent_city(self): - response = self.get_touristiccontent_list({'cities': self.city.pk}) - self.assertEqual(len(response.json()['results']), 2) + response = self.get_touristiccontent_list({"cities": self.city.pk}) + self.assertEqual(len(response.json()["results"]), 2) def test_touristiccontent_inexistant_city(self): - response = self.get_touristiccontent_list({'cities': '99999'}) - self.assertEqual(len(response.json()['results']), 0) + response = self.get_touristiccontent_list({"cities": "99999"}) + self.assertEqual(len(response.json()["results"]), 0) def test_touristiccontent_district(self): - response = self.get_touristiccontent_list({'districts': self.district.pk}) - self.assertEqual(len(response.json()['results']), 2) + response = self.get_touristiccontent_list({"districts": self.district.pk}) + self.assertEqual(len(response.json()["results"]), 2) def test_touristiccontent_inexistant_district(self): - response = self.get_touristiccontent_list({'districts': 99999}) - self.assertEqual(len(response.json()['results']), 0) + response = self.get_touristiccontent_list({"districts": 99999}) + self.assertEqual(len(response.json()["results"]), 0) def test_touristiccontent_structure(self): - response = self.get_touristiccontent_list({'structures': self.content.structure.pk}) - self.assertEqual(len(response.json()['results']), 2) + response = self.get_touristiccontent_list( + {"structures": self.content.structure.pk} + ) + self.assertEqual(len(response.json()["results"]), 2) def test_touristiccontent_theme(self): - response = self.get_touristiccontent_list({'themes': self.content.themes.all()[0].pk}) - self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list( + {"themes": self.content.themes.all()[0].pk} + ) + self.assertEqual(len(response.json()["results"]), 1) def test_touristiccontent_portal(self): - response = self.get_touristiccontent_list({'portals': self.content.portal.all()[0].pk}) - self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list( + {"portals": self.content.portal.all()[0].pk} + ) + self.assertEqual(len(response.json()["results"]), 1) def test_touristiccontent_label_accessibility(self): - response = self.get_touristiccontent_list({'labels_accessibility': self.label_accessibility.pk}) - self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list( + {"labels_accessibility": self.label_accessibility.pk} + ) + self.assertEqual(len(response.json()["results"]), 1) def test_touristiccontent_q(self): - response = self.get_touristiccontent_list({'q': 'Blah CT'}) - self.assertEqual(len(response.json()['results']), 2) + response = self.get_touristiccontent_list({"q": "Blah CT"}) + self.assertEqual(len(response.json()["results"]), 2) def test_touristiccontent_detail_with_lang(self): - response = self.get_touristiccontent_list({'language': 'en'}) + response = self.get_touristiccontent_list({"language": "en"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['results'][0]['pdf'], - f'http://testserver/api/en/touristiccontents/{self.content.pk}/touristic-content.pdf') + self.assertEqual( + response.json()["results"][0]["pdf"], + f"http://testserver/api/en/touristiccontents/{self.content.pk}/touristic-content.pdf", + ) def test_labels_accessibility_detail(self): self.check_structure_response( self.get_labelaccessibility_detail(self.label_accessibility.pk), - LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE + LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE, ) def test_labels_accessibility_list(self): self.check_number_elems_response( - self.get_labelaccessibility_list(), - tourism_models.LabelAccessibility + self.get_labelaccessibility_list(), tourism_models.LabelAccessibility ) def test_labels_list(self): - self.check_number_elems_response( - self.get_label_list(), - common_models.Label - ) + self.check_number_elems_response(self.get_label_list(), common_models.Label) def test_labels_filter_filter(self): label_1 = common_factory.LabelFactory.create(filter=False) label_2 = common_factory.LabelFactory.create(filter=True) self.treks[0].labels.add(label_1, label_2) - response = self.get_label_list({'only_filters': True}) + response = self.get_label_list({"only_filters": True}) self.assertEqual(response.json()["count"], 3) - self.assertSetEqual({result["id"] for result in response.json()["results"]}, {self.label.pk, label_2.pk, self.label_3.pk}) - response = self.get_label_list({'only_filters': False}) + self.assertSetEqual( + {result["id"] for result in response.json()["results"]}, + {self.label.pk, label_2.pk, self.label_3.pk}, + ) + response = self.get_label_list({"only_filters": False}) self.assertEqual(response.json()["results"][0]["id"], label_1.pk) self.assertEqual(response.json()["count"], 1) response = self.get_label_list() self.assertEqual(response.json()["count"], 4) - response = self.get_label_list({'only_filters': 'None'}) + response = self.get_label_list({"only_filters": "None"}) self.assertEqual(response.json()["count"], 0) def test_labels_detail(self): self.check_structure_response( - self.get_label_detail(self.label.pk), - TREK_LABEL_PROPERTIES_JSON_STRUCTURE + self.get_label_detail(self.label.pk), TREK_LABEL_PROPERTIES_JSON_STRUCTURE ) def test_filetype_detail(self): self.check_structure_response( self.get_filetype_detail(self.filetype.pk), - FILETYPE_PROPERTIES_JSON_STRUCTURE + FILETYPE_PROPERTIES_JSON_STRUCTURE, ) def test_filetype_list(self): self.check_number_elems_response( - self.get_filetype_list(), - common_models.FileType + self.get_filetype_list(), common_models.FileType ) def test_informationdesk_list(self): self.check_number_elems_response( - self.get_informationdesk_list(), - tourism_models.InformationDesk + self.get_informationdesk_list(), tourism_models.InformationDesk ) def test_informationdesk_detail(self): self.check_structure_response( self.get_informationdesk_detail(self.info_desk.pk), - INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE + INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE, ) def test_informationdesk_filter_trek(self): - response = self.get_informationdesk_list({'trek': self.treks[0].pk}) + response = self.get_informationdesk_list({"trek": self.treks[0].pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.info_desk.pk) - response = self.get_informationdesk_list({'trek': self.parent.pk}) + response = self.get_informationdesk_list({"trek": self.parent.pk}) self.assertEqual(response.json()["count"], 0) def test_infodesk_filter_type(self): - response = self.get_informationdesk_list({'types': self.information_desk_type.pk}) + response = self.get_informationdesk_list( + {"types": self.information_desk_type.pk} + ) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.info_desk.pk) def test_infodesk_filter_label_accessibility(self): - response = self.get_informationdesk_list({'labels_accessibility': self.label_accessibility.pk}) + response = self.get_informationdesk_list( + {"labels_accessibility": self.label_accessibility.pk} + ) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.info_desk.pk) def test_informationdesk_type_list(self): self.check_number_elems_response( - self.get_informationdesk_type_list(), - tourism_models.InformationDeskType + self.get_informationdesk_type_list(), tourism_models.InformationDeskType ) def test_informationdesk_type_detail(self): self.check_structure_response( self.get_informationdesk_type_detail(self.information_desk_type.pk), - INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE + INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE, ) def test_source_list(self): self.check_number_elems_response( - self.get_source_list(), - common_models.RecordSource + self.get_source_list(), common_models.RecordSource ) def test_source_detail(self): self.check_structure_response( - self.get_source_detail(self.source.pk), - SOURCE_PROPERTIES_JSON_STRUCTURE + self.get_source_detail(self.source.pk), SOURCE_PROPERTIES_JSON_STRUCTURE ) def test_reservationsystem_list(self): self.check_number_elems_response( - self.get_reservationsystem_list(), - common_models.ReservationSystem + self.get_reservationsystem_list(), common_models.ReservationSystem ) def test_reservationsystem_list_filter(self): - response = self.get_reservationsystem_list({'portals': self.portal.pk}) + response = self.get_reservationsystem_list({"portals": self.portal.pk}) # Two results : one reservationsystem associated with content2 and the other with trek[0] - self.assertEquals(len(response.json()['results']), 2) + self.assertEquals(len(response.json()["results"]), 2) def test_reservationsystem_detail(self): self.check_structure_response( self.get_reservationsystem_detail(self.reservation_system.pk), - RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE + RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE, ) def test_site_list(self): - self.check_number_elems_response( - self.get_site_list(), - outdoor_models.Site - ) + self.check_number_elems_response(self.get_site_list(), outdoor_models.Site) def test_site_detail(self): self.check_structure_response( - self.get_site_detail(self.site.pk), - SITE_PROPERTIES_JSON_STRUCTURE + self.get_site_detail(self.site.pk), SITE_PROPERTIES_JSON_STRUCTURE ) def test_site_list_filters(self): - response = self.get_site_list({ - 'q': 'test string' - }) + response = self.get_site_list({"q": "test string"}) # test response code self.assertEqual(response.status_code, 200) def test_course_list(self): - self.check_number_elems_response( - self.get_course_list(), - outdoor_models.Course - ) + self.check_number_elems_response(self.get_course_list(), outdoor_models.Course) def test_course_detail(self): self.check_structure_response( - self.get_course_detail(self.course.pk), - COURSE_PROPERTIES_JSON_STRUCTURE + self.get_course_detail(self.course.pk), COURSE_PROPERTIES_JSON_STRUCTURE ) def test_coursetype_list(self): self.check_number_elems_response( - self.get_coursetype_list(), - outdoor_models.CourseType + self.get_coursetype_list(), outdoor_models.CourseType ) def test_coursetype_detail(self): self.check_structure_response( self.get_coursetype_detail(self.coursetype.pk), - COURSETYPE_PROPERTIES_JSON_STRUCTURE + COURSETYPE_PROPERTIES_JSON_STRUCTURE, ) def test_course_list_filters(self): - response = self.get_course_list({ - 'q': 'test string' - }) + response = self.get_course_list({"q": "test string"}) # test response code self.assertEqual(response.status_code, 200) @@ -2219,40 +2810,43 @@ def test_outdoorpractice_list(self): json_response = response.json() self.assertEqual(response.status_code, 200) self.assertEquals( - len(json_response['results']), - outdoor_models.Practice.objects.filter(sites__published=True).distinct().count() + len(json_response["results"]), + outdoor_models.Practice.objects.filter(sites__published=True) + .distinct() + .count(), ) def test_outdoorpractice_detail(self): self.check_structure_response( self.get_outdoorpractice_detail(self.site.practice.pk), - OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE + OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE, ) def test_sitetype_list(self): self.check_number_elems_response( - self.get_sitetype_list(), - outdoor_models.SiteType + self.get_sitetype_list(), outdoor_models.SiteType ) def test_sitetype_detail(self): self.check_structure_response( self.get_sitetype_detail(self.site.type.pk), - SITETYPE_PROPERTIES_JSON_STRUCTURE + SITETYPE_PROPERTIES_JSON_STRUCTURE, ) def test_sensitivearea_list(self): self.check_number_elems_response( - self.get_sensitivearea_list(params={'period': 'any'}), - sensitivity_models.SensitiveArea + self.get_sensitivearea_list(params={"period": "any"}), + sensitivity_models.SensitiveArea, ) # Test filters coverage - response = self.get_sensitivearea_list({ - 'trek': self.parent.id, - 'period': "1,2,3,10,11,12", - 'structure': self.structure.id, - 'practice': self.sensitivearea_practice.id, - }) + response = self.get_sensitivearea_list( + { + "trek": self.parent.id, + "period": "1,2,3,10,11,12", + "structure": self.structure.id, + "practice": self.sensitivearea_practice.id, + } + ) self.assertEqual(response.status_code, 200) def test_sensitivearea_list_filtered_by_near_trek(self): @@ -2260,56 +2854,66 @@ def test_sensitivearea_list_filtered_by_near_trek(self): far_away_dist = settings.SENSITIVE_AREA_INTERSECTION_MARGIN * 2 trek_x = 24800 if settings.TREKKING_TOPOLOGY_ENABLED: - trek_path = core_factory.PathFactory(geom=LineString(Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID)) + trek_path = core_factory.PathFactory( + geom=LineString( + Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID + ) + ) trek = trek_factory.TrekFactory(paths=[(trek_path, 0, 1)]) else: - trek = trek_factory.TrekFactory(geom=LineString(Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID)) + trek = trek_factory.TrekFactory( + geom=LineString( + Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID + ) + ) # a sensitive area near it near_area_x1 = trek_x + nearby_dist near_area_x2 = trek_x + nearby_dist + 1000 sensitivity_factory.SensitiveAreaFactory( - geom=f'POLYGON(({near_area_x1} 7800, {near_area_x2} 7800, {near_area_x2} 7900, {near_area_x1} 7900, {near_area_x1} 7800))' + geom=f"POLYGON(({near_area_x1} 7800, {near_area_x2} 7800, {near_area_x2} 7900, {near_area_x1} 7900, {near_area_x1} 7800))" ) # a sensitive area far from it far_area_x1 = trek_x + far_away_dist far_area_x2 = trek_x + far_away_dist + 1000 sensitivity_factory.SensitiveAreaFactory( - geom=f'POLYGON(({far_area_x1} 7800, {far_area_x2} 7800, {far_area_x2} 7900, {far_area_x1} 7900, {far_area_x1} 7800))' + geom=f"POLYGON(({far_area_x1} 7800, {far_area_x2} 7800, {far_area_x2} 7900, {far_area_x1} 7900, {far_area_x1} 7800))" ) - response = self.get_sensitivearea_list({"near_trek": trek.pk, "period": "ignore"}) + response = self.get_sensitivearea_list( + {"near_trek": trek.pk, "period": "ignore"} + ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()["count"], 1) def test_sensitivearea_detail(self): self.check_structure_response( - self.get_sensitivearea_detail(self.sensitivearea.pk, params={'period': 'any'}), - SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE + self.get_sensitivearea_detail( + self.sensitivearea.pk, params={"period": "any"} + ), + SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE, ) def test_sensitivearea_practice_list(self): self.check_number_elems_response( - self.get_sensitiveareapractice_list(), - sensitivity_models.SportPractice + self.get_sensitiveareapractice_list(), sensitivity_models.SportPractice ) def test_sensitivearea_practice_detail(self): self.check_structure_response( self.get_sensitiveareapractice_detail(self.sensitivearea_practice.pk), - sorted(['name', 'id']) + sorted(["name", "id"]), ) def test_sensitivearea_species_list(self): self.check_number_elems_response( - self.get_sensitiveareaspecies_list(), - sensitivity_models.Species + self.get_sensitiveareaspecies_list(), sensitivity_models.Species ) def test_sensitivearea_species_detail(self): self.check_structure_response( self.get_sensitiveareaspecies_detail(self.sensitivearea_species.pk), - SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE + SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE, ) def test_config(self): @@ -2317,91 +2921,89 @@ def test_config(self): self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(sorted(json_response.keys()), ['bbox']) + self.assertEqual(sorted(json_response.keys()), ["bbox"]) def test_organism_list(self): self.check_number_elems_response( - self.get_organism_list(), - common_models.Organism + self.get_organism_list(), common_models.Organism ) def test_organism_detail(self): self.check_structure_response( self.get_organism_detail(self.organism.pk), - ORGANISM_PROPERTIES_JSON_STRUCTURE + ORGANISM_PROPERTIES_JSON_STRUCTURE, ) def test_sensitivearea_distance_list(self): if settings.TREKKING_TOPOLOGY_ENABLED: - p1 = core_factory.PathFactory.create(geom=LineString((605600, 6650000), (605604, 6650004), srid=2154)) + p1 = core_factory.PathFactory.create( + geom=LineString((605600, 6650000), (605604, 6650004), srid=2154) + ) trek = trek_factory.TrekFactory.create( - published=True, - name='Parent', - paths=[p1] + published=True, name="Parent", paths=[p1] ) else: - trek = trek_factory.TrekFactory.create(geom=LineString((605600, 6650000), (605604, 6650004), srid=2154)) + trek = trek_factory.TrekFactory.create( + geom=LineString((605600, 6650000), (605604, 6650004), srid=2154) + ) specy = sensitivity_factory.SpeciesFactory.create(period01=True) sensitivity_factory.SensitiveAreaFactory.create( - geom='SRID=2154;POLYGON((605600 6650000, 605600 6650004, 605604 6650004, 605604 6650000, 605600 6650000))', + geom="SRID=2154;POLYGON((605600 6650000, 605600 6650004, 605604 6650004, 605604 6650000, 605600 6650000))", species=specy, - description="Test" + description="Test", ) sensitivity_factory.SensitiveAreaFactory.create( - geom='SRID=2154;POLYGON((606001 6650501, 606001 6650505, 606005 6650505, 606005 6650501, 606001 6650501))', + geom="SRID=2154;POLYGON((606001 6650501, 606001 6650505, 606005 6650505, 606005 6650501, 606001 6650501))", species=specy, - description="Test 2" + description="Test 2", ) - response = self.get_sensitivearea_list({ - 'trek': trek.id, - 'period': '1' - }) + response = self.get_sensitivearea_list({"trek": trek.id, "period": "1"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) + self.assertEqual(response.json()["count"], 1) # validate wrong trek id returns empty list - response = self.get_sensitivearea_list({ - 'trek': 9999 - }) + response = self.get_sensitivearea_list({"trek": 9999}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 0) + self.assertEqual(response.json()["count"], 0) def test_hdviewpoint_detail_content(self): response = self.get_hdviewpoint_detail(self.hdviewpoint_trek.pk) self.assertEqual(response.status_code, 200) json_response = response.json() self.assertEqual( - json_response.get('picture_tiles_url'), - f"http://testserver/api/hdviewpoint/drf/hdviewpoints/{self.hdviewpoint_trek.pk}/tiles/%7Bz%7D/%7Bx%7D/%7By%7D.png?source=vips" + json_response.get("picture_tiles_url"), + f"http://testserver/api/hdviewpoint/drf/hdviewpoints/{self.hdviewpoint_trek.pk}/tiles/%7Bz%7D/%7Bx%7D/%7By%7D.png?source=vips", ) - json.dumps(json_response.get('annotations')) - self.assertIsNone(json_response.get('site')) - self.assertIsNone(json_response.get('poi')) - self.assertEquals(json_response.get('trek').get('uuid'), str(self.treks[0].uuid)) - self.assertEquals(json_response.get('trek').get('id'), self.treks[0].id) + json.dumps(json_response.get("annotations")) + self.assertIsNone(json_response.get("site")) + self.assertIsNone(json_response.get("poi")) + self.assertEquals( + json_response.get("trek").get("uuid"), str(self.treks[0].uuid) + ) + self.assertEquals(json_response.get("trek").get("id"), self.treks[0].id) def test_hdviewpoint_detail_content_poi(self): response = self.get_hdviewpoint_detail(self.hdviewpoint_poi.pk) self.assertEqual(response.status_code, 200) json_response = response.json() - json.dumps(json_response.get('annotations')) - self.assertIsNone(json_response.get('site')) - self.assertIsNone(json_response.get('trek')) - self.assertEquals(json_response.get('poi').get('uuid'), str(self.poi.uuid)) - self.assertEquals(json_response.get('poi').get('id'), self.poi.id) + json.dumps(json_response.get("annotations")) + self.assertIsNone(json_response.get("site")) + self.assertIsNone(json_response.get("trek")) + self.assertEquals(json_response.get("poi").get("uuid"), str(self.poi.uuid)) + self.assertEquals(json_response.get("poi").get("id"), self.poi.id) def test_hdviewpoint_detail_content_site(self): response = self.get_hdviewpoint_detail(self.hdviewpoint_site.pk) self.assertEqual(response.status_code, 200) json_response = response.json() - json.dumps(json_response.get('annotations')) - self.assertIsNone(json_response.get('poi')) - self.assertIsNone(json_response.get('trek')) - self.assertEquals(json_response.get('site').get('uuid'), str(self.site.uuid)) - self.assertEquals(json_response.get('site').get('id'), self.site.id) + json.dumps(json_response.get("annotations")) + self.assertIsNone(json_response.get("poi")) + self.assertIsNone(json_response.get("trek")) + self.assertEquals(json_response.get("site").get("uuid"), str(self.site.uuid)) + self.assertEquals(json_response.get("site").get("id"), self.site.id) class APIAccessAdministratorTestCase(BaseApiTest): - """ TestCase for administrator API profile """ + """TestCase for administrator API profile""" @classmethod def setUpTestData(cls): @@ -2414,40 +3016,61 @@ def test_path_list(self): response = self.get_path_list() self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(sorted(json_response.keys()), - PAGINATED_JSON_STRUCTURE) - self.assertEqual(len(json_response.get('results')), path_models.Path.objects.all().count()) - response = self.get_path_list({'format': 'geojson'}) + self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) + self.assertEqual( + len(json_response.get("results")), path_models.Path.objects.all().count() + ) + response = self.get_path_list({"format": "geojson"}) json_response = response.json() # test geojson format - self.assertEqual(sorted(json_response.keys()), - PAGINATED_GEOJSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual(len(json_response.get('features')), - path_models.Path.objects.all().count(), json_response) + self.assertEqual( + len(json_response.get("features")), + path_models.Path.objects.all().count(), + json_response, + ) # test dim 3 ok - self.assertEqual(len(json_response.get('features')[0].get('geometry').get('coordinates')[0]), 3) + self.assertEqual( + len(json_response.get("features")[0].get("geometry").get("coordinates")[0]), + 3, + ) - self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), - PATH_PROPERTIES_GEOJSON_STRUCTURE) + self.assertEqual( + sorted(json_response.get("features")[0].get("properties").keys()), + PATH_PROPERTIES_GEOJSON_STRUCTURE, + ) class APISwaggerTestCase(BaseApiTest): - """ TestCase API documentation """ + """TestCase API documentation""" def test_schema_fields(self): - response = self.client.get('/api/v2/', {'format': 'openapi'}) - self.assertContains(response, 'Filter by a bounding box formatted like W-lng,S-lat,E-lng,N-lat (WGS84).') - self.assertContains(response, 'Set language for translation. Can be all or a two-letters language code.') - self.assertContains(response, 'Filter by minimum difficulty level (id).') - self.assertContains(response, 'Reference point to compute distance (WGS84). Example: lng,lat.') - self.assertContains(response, 'Filter by one or more practice id, comma-separated.') - self.assertContains(response, 'Filter by one or more types id, comma-separated. Logical OR for types in the same list, AND for types in different lists.') + response = self.client.get("/api/v2/", {"format": "openapi"}) + self.assertContains( + response, + "Filter by a bounding box formatted like W-lng,S-lat,E-lng,N-lat (WGS84).", + ) + self.assertContains( + response, + "Set language for translation. Can be all or a two-letters language code.", + ) + self.assertContains(response, "Filter by minimum difficulty level (id).") + self.assertContains( + response, "Reference point to compute distance (WGS84). Example: lng,lat." + ) + self.assertContains( + response, "Filter by one or more practice id, comma-separated." + ) + self.assertContains( + response, + "Filter by one or more types id, comma-separated. Logical OR for types in the same list, AND for types in different lists.", + ) def test_swagger_ui(self): - response = self.client.get('/api/v2/') - self.assertContains(response, 'swagger') + response = self.client.get("/api/v2/") + self.assertContains(response, "swagger") class TrekRatingScaleTestCase(TestCase): @@ -2457,54 +3080,68 @@ def setUpTestData(cls): cls.practice2 = trek_factory.PracticeFactory() cls.practice1.treks.set([trek_factory.TrekFactory()]) cls.practice2.treks.set([trek_factory.TrekFactory()]) - cls.scale1 = trek_factory.RatingScaleFactory(name='AAA', practice=cls.practice1) - cls.scale2 = trek_factory.RatingScaleFactory(name='AAA', practice=cls.practice2) - cls.scale3 = trek_factory.RatingScaleFactory(name='BBB', practice=cls.practice2) + cls.scale1 = trek_factory.RatingScaleFactory(name="AAA", practice=cls.practice1) + cls.scale2 = trek_factory.RatingScaleFactory(name="AAA", practice=cls.practice2) + cls.scale3 = trek_factory.RatingScaleFactory(name="BBB", practice=cls.practice2) def test_list(self): - response = self.client.get('/api/v2/trek_ratingscale/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'count': 3, - 'next': None, - 'previous': None, - 'results': [{ - 'id': self.scale1.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice1.pk, - }, { - 'id': self.scale2.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice2.pk, - }, { - 'id': self.scale3.pk, - 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice2.pk, - }] - }) + response = self.client.get("/api/v2/trek_ratingscale/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 3, + "next": None, + "previous": None, + "results": [ + { + "id": self.scale1.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "practice": self.practice1.pk, + }, + { + "id": self.scale2.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "practice": self.practice2.pk, + }, + { + "id": self.scale3.pk, + "name": {"en": "BBB", "es": None, "fr": None, "it": None}, + "practice": self.practice2.pk, + }, + ], + }, + ) def test_detail(self): - response = self.client.get('/api/v2/trek_ratingscale/{}/'.format(self.scale1.pk)) + response = self.client.get( + "/api/v2/trek_ratingscale/{}/".format(self.scale1.pk) + ) self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'id': self.scale1.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice1.pk, - }) + self.assertJSONEqual( + response.content, + { + "id": self.scale1.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "practice": self.practice1.pk, + }, + ) def test_filter_q(self): - response = self.client.get('/api/v2/trek_ratingscale/', {'q': 'A'}) + response = self.client.get("/api/v2/trek_ratingscale/", {"q": "A"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for scale in response.json()['results']: - self.assertEqual(scale['name']['en'], 'AAA') + self.assertEqual(response.json()["count"], 2) + for scale in response.json()["results"]: + self.assertEqual(scale["name"]["en"], "AAA") def test_filter_practice(self): - response = self.client.get('/api/v2/trek_ratingscale/', {'practices': self.practice2.pk}) + response = self.client.get( + "/api/v2/trek_ratingscale/", {"practices": self.practice2.pk} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for scale in response.json()['results']: - self.assertEqual(scale['practice'], self.practice2.pk) + self.assertEqual(response.json()["count"], 2) + for scale in response.json()["results"]: + self.assertEqual(scale["practice"], self.practice2.pk) class OutdoorRatingScaleTestCase(TestCase): @@ -2514,68 +3151,88 @@ def setUpTestData(cls): cls.practice2 = outdoor_factory.PracticeFactory() cls.practice1.sites.set([outdoor_factory.SiteFactory()]) cls.practice2.sites.set([outdoor_factory.SiteFactory()]) - cls.scale1 = outdoor_factory.RatingScaleFactory(name='AAA', practice=cls.practice1) - cls.scale2 = outdoor_factory.RatingScaleFactory(name='AAA', practice=cls.practice2) - cls.scale3 = outdoor_factory.RatingScaleFactory(name='BBB', practice=cls.practice2) + cls.scale1 = outdoor_factory.RatingScaleFactory( + name="AAA", practice=cls.practice1 + ) + cls.scale2 = outdoor_factory.RatingScaleFactory( + name="AAA", practice=cls.practice2 + ) + cls.scale3 = outdoor_factory.RatingScaleFactory( + name="BBB", practice=cls.practice2 + ) def tearDown(self): clear_internal_user_cache() super().tearDown() def test_list(self): - response = self.client.get('/api/v2/outdoor_ratingscale/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'count': 3, - 'next': None, - 'previous': None, - 'results': [{ - 'id': self.scale1.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice1.pk, - }, { - 'id': self.scale2.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice2.pk, - }, { - 'id': self.scale3.pk, - 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice2.pk, - }] - }) + response = self.client.get("/api/v2/outdoor_ratingscale/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 3, + "next": None, + "previous": None, + "results": [ + { + "id": self.scale1.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "practice": self.practice1.pk, + }, + { + "id": self.scale2.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "practice": self.practice2.pk, + }, + { + "id": self.scale3.pk, + "name": {"en": "BBB", "es": None, "fr": None, "it": None}, + "practice": self.practice2.pk, + }, + ], + }, + ) def test_detail(self): - response = self.client.get('/api/v2/outdoor_ratingscale/{}/'.format(self.scale1.pk)) + response = self.client.get( + "/api/v2/outdoor_ratingscale/{}/".format(self.scale1.pk) + ) self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'id': self.scale1.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'practice': self.practice1.pk, - }) + self.assertJSONEqual( + response.content, + { + "id": self.scale1.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "practice": self.practice1.pk, + }, + ) def test_filter_q(self): - response = self.client.get('/api/v2/outdoor_ratingscale/', {'q': 'A'}) + response = self.client.get("/api/v2/outdoor_ratingscale/", {"q": "A"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for scale in response.json()['results']: - self.assertEqual(scale['name']['en'], 'AAA') + self.assertEqual(response.json()["count"], 2) + for scale in response.json()["results"]: + self.assertEqual(scale["name"]["en"], "AAA") def test_filter_practice(self): - response = self.client.get('/api/v2/outdoor_ratingscale/', {'practices': self.practice2.pk}) + response = self.client.get( + "/api/v2/outdoor_ratingscale/", {"practices": self.practice2.pk} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for scale in response.json()['results']: - self.assertEqual(scale['practice'], self.practice2.pk) + self.assertEqual(response.json()["count"], 2) + for scale in response.json()["results"]: + self.assertEqual(scale["practice"], self.practice2.pk) class TrekRatingTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.scale1 = trek_factory.RatingScaleFactory(name='BBB') - cls.scale2 = trek_factory.RatingScaleFactory(name='AAA') - cls.rating1 = trek_factory.RatingFactory(name='AAA', scale=cls.scale1) - cls.rating2 = trek_factory.RatingFactory(name='AAA', scale=cls.scale2) - cls.rating3 = trek_factory.RatingFactory(name='BBB', scale=cls.scale2) + cls.scale1 = trek_factory.RatingScaleFactory(name="BBB") + cls.scale2 = trek_factory.RatingScaleFactory(name="AAA") + cls.rating1 = trek_factory.RatingFactory(name="AAA", scale=cls.scale1) + cls.rating2 = trek_factory.RatingFactory(name="AAA", scale=cls.scale2) + cls.rating3 = trek_factory.RatingFactory(name="BBB", scale=cls.scale2) cls.rating1.treks.set([trek_factory.TrekFactory()]) cls.rating2.treks.set([trek_factory.TrekFactory()]) cls.rating3.treks.set([trek_factory.TrekFactory()]) @@ -2585,71 +3242,83 @@ def tearDown(self): super().tearDown() def test_list(self): - response = self.client.get('/api/v2/trek_rating/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'count': 3, - 'next': None, - 'previous': None, - 'results': [{ - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'id': self.rating1.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale1.pk, - }, { - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'id': self.rating2.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale2.pk, - }, { - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'id': self.rating3.pk, - 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale2.pk, - }] - }) + response = self.client.get("/api/v2/trek_rating/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 3, + "next": None, + "previous": None, + "results": [ + { + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "id": self.rating1.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale1.pk, + }, + { + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "id": self.rating2.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale2.pk, + }, + { + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "id": self.rating3.pk, + "name": {"en": "BBB", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale2.pk, + }, + ], + }, + ) def test_detail(self): - response = self.client.get('/api/v2/trek_rating/{}/'.format(self.rating2.pk)) + response = self.client.get("/api/v2/trek_rating/{}/".format(self.rating2.pk)) self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'id': self.rating2.pk, - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale2.pk, - }) + self.assertJSONEqual( + response.content, + { + "id": self.rating2.pk, + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale2.pk, + }, + ) def test_filter_q(self): - response = self.client.get('/api/v2/trek_rating/', {'q': 'BBB'}) + response = self.client.get("/api/v2/trek_rating/", {"q": "BBB"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for rating in response.json()['results']: - self.assertNotEqual(rating['name']['en'] == 'BBB', rating['scale'] == self.scale1.pk) + self.assertEqual(response.json()["count"], 2) + for rating in response.json()["results"]: + self.assertNotEqual( + rating["name"]["en"] == "BBB", rating["scale"] == self.scale1.pk + ) def test_filter_scale(self): - response = self.client.get('/api/v2/trek_rating/', {'scale': self.scale2.pk}) + response = self.client.get("/api/v2/trek_rating/", {"scale": self.scale2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for rating in response.json()['results']: - self.assertEqual(rating['scale'], self.scale2.pk) + self.assertEqual(response.json()["count"], 2) + for rating in response.json()["results"]: + self.assertEqual(rating["scale"], self.scale2.pk) class OutdoorRatingTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.scale1 = outdoor_factory.RatingScaleFactory(name='BBB') - cls.scale2 = outdoor_factory.RatingScaleFactory(name='AAA') - cls.rating1 = outdoor_factory.RatingFactory(name='AAA', scale=cls.scale1) - cls.rating2 = outdoor_factory.RatingFactory(name='AAA', scale=cls.scale2) - cls.rating3 = outdoor_factory.RatingFactory(name='BBB', scale=cls.scale2) + cls.scale1 = outdoor_factory.RatingScaleFactory(name="BBB") + cls.scale2 = outdoor_factory.RatingScaleFactory(name="AAA") + cls.rating1 = outdoor_factory.RatingFactory(name="AAA", scale=cls.scale1) + cls.rating2 = outdoor_factory.RatingFactory(name="AAA", scale=cls.scale2) + cls.rating3 = outdoor_factory.RatingFactory(name="BBB", scale=cls.scale2) cls.rating1.sites.set([outdoor_factory.SiteFactory()]) cls.rating2.sites.set([outdoor_factory.SiteFactory()]) cls.rating3.sites.set([outdoor_factory.SiteFactory()]) @@ -2659,75 +3328,91 @@ def tearDown(self): super().tearDown() def test_list(self): - response = self.client.get('/api/v2/outdoor_rating/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'count': 3, - 'next': None, - 'previous': None, - 'results': [{ - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'id': self.rating1.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale1.pk, - }, { - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'id': self.rating2.pk, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale2.pk, - }, { - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'id': self.rating3.pk, - 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale2.pk, - }] - }) + response = self.client.get("/api/v2/outdoor_rating/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 3, + "next": None, + "previous": None, + "results": [ + { + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "id": self.rating1.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale1.pk, + }, + { + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "id": self.rating2.pk, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale2.pk, + }, + { + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "id": self.rating3.pk, + "name": {"en": "BBB", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale2.pk, + }, + ], + }, + ) def test_detail(self): - response = self.client.get('/api/v2/outdoor_rating/{}/'.format(self.rating1.pk)) + response = self.client.get("/api/v2/outdoor_rating/{}/".format(self.rating1.pk)) self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'id': self.rating1.pk, - 'color': '', - 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, - 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'order': None, - 'scale': self.scale1.pk, - }) + self.assertJSONEqual( + response.content, + { + "id": self.rating1.pk, + "color": "", + "description": {"en": None, "es": None, "fr": None, "it": None}, + "name": {"en": "AAA", "es": None, "fr": None, "it": None}, + "order": None, + "scale": self.scale1.pk, + }, + ) def test_filter_q(self): - response = self.client.get('/api/v2/outdoor_rating/', {'q': 'BBB'}) + response = self.client.get("/api/v2/outdoor_rating/", {"q": "BBB"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for rating in response.json()['results']: - self.assertNotEqual(rating['name']['en'] == 'BBB', rating['scale'] == self.scale1.pk) + self.assertEqual(response.json()["count"], 2) + for rating in response.json()["results"]: + self.assertNotEqual( + rating["name"]["en"] == "BBB", rating["scale"] == self.scale1.pk + ) def test_filter_scale(self): - response = self.client.get('/api/v2/outdoor_rating/', {'scale': self.scale2.pk}) + response = self.client.get("/api/v2/outdoor_rating/", {"scale": self.scale2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - for rating in response.json()['results']: - self.assertEqual(rating['scale'], self.scale2.pk) + self.assertEqual(response.json()["count"], 2) + for rating in response.json()["results"]: + self.assertEqual(rating["scale"], self.scale2.pk) class FlatPageTestCase(TestCase): - @classmethod def setUpTestData(cls): cls.source = common_factory.RecordSourceFactory() cls.portal = common_factory.TargetPortalFactory() cls.page1 = flatpages_factory.FlatPageFactory( - title='AAA', published=True, order=2, target='web', content='Blah', - sources=[cls.source], portals=[cls.portal] + title="AAA", + published=True, + order=2, + target="web", + content="Blah", + sources=[cls.source], + portals=[cls.portal], ) cls.page2 = flatpages_factory.FlatPageFactory( - title='BBB', published=True, order=1, target='mobile', content='Blbh' + title="BBB", published=True, order=1, target="mobile", content="Blbh" ) def tearDown(self): @@ -2735,87 +3420,110 @@ def tearDown(self): super().tearDown() def test_list(self): - response = self.client.get('/api/v2/flatpage/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'count': 2, - 'next': None, - 'previous': None, - 'results': [{ - 'id': self.page2.pk, - 'title': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, - 'content': {'en': 'Blbh', 'es': None, 'fr': None, 'it': None}, - 'external_url': '', - 'order': 1, - 'portal': [], - 'published': {'en': True, 'es': False, 'fr': False, 'it': False}, - 'source': [], - 'target': 'mobile', - 'attachments': [], - }, { - 'id': self.page1.pk, - 'title': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'content': {'en': 'Blah', 'es': None, 'fr': None, 'it': None}, - 'external_url': '', - 'order': 2, - 'portal': [self.portal.pk], - 'published': {'en': True, 'es': False, 'fr': False, 'it': False}, - 'source': [self.source.pk], - 'target': 'web', - 'attachments': [], - }] - }) + response = self.client.get("/api/v2/flatpage/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.page2.pk, + "title": {"en": "BBB", "es": None, "fr": None, "it": None}, + "content": {"en": "Blbh", "es": None, "fr": None, "it": None}, + "external_url": "", + "order": 1, + "portal": [], + "published": { + "en": True, + "es": False, + "fr": False, + "it": False, + }, + "source": [], + "target": "mobile", + "attachments": [], + }, + { + "id": self.page1.pk, + "title": {"en": "AAA", "es": None, "fr": None, "it": None}, + "content": {"en": "Blah", "es": None, "fr": None, "it": None}, + "external_url": "", + "order": 2, + "portal": [self.portal.pk], + "published": { + "en": True, + "es": False, + "fr": False, + "it": False, + }, + "source": [self.source.pk], + "target": "web", + "attachments": [], + }, + ], + }, + ) def test_detail(self): - response = self.client.get('/api/v2/flatpage/{}/'.format(self.page1.pk)) - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - 'id': self.page1.pk, - 'title': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, - 'content': {'en': 'Blah', 'es': None, 'fr': None, 'it': None}, - 'external_url': '', - 'order': 2, - 'portal': [self.portal.pk], - 'published': {'en': True, 'es': False, 'fr': False, 'it': False}, - 'source': [self.source.pk], - 'target': 'web', - 'attachments': [], - }) + response = self.client.get("/api/v2/flatpage/{}/".format(self.page1.pk)) + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "id": self.page1.pk, + "title": {"en": "AAA", "es": None, "fr": None, "it": None}, + "content": {"en": "Blah", "es": None, "fr": None, "it": None}, + "external_url": "", + "order": 2, + "portal": [self.portal.pk], + "published": {"en": True, "es": False, "fr": False, "it": False}, + "source": [self.source.pk], + "target": "web", + "attachments": [], + }, + ) def test_filter_q(self): - response = self.client.get('/api/v2/flatpage/', {'q': 'BB'}) + response = self.client.get("/api/v2/flatpage/", {"q": "BB"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - self.assertEqual(response.json()['results'][0]['title']['en'], 'BBB') + self.assertEqual(response.json()["count"], 1) + self.assertEqual(response.json()["results"][0]["title"]["en"], "BBB") def test_filter_targets(self): - response = self.client.get('/api/v2/flatpage/', {'targets': 'web'}) + response = self.client.get("/api/v2/flatpage/", {"targets": "web"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - self.assertEqual(response.json()['results'][0]['title']['en'], 'AAA') + self.assertEqual(response.json()["count"], 1) + self.assertEqual(response.json()["results"][0]["title"]["en"], "AAA") def test_filter_sources(self): - response = self.client.get('/api/v2/flatpage/', {'sources': self.source.pk}) + response = self.client.get("/api/v2/flatpage/", {"sources": self.source.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - self.assertEqual(response.json()['results'][0]['title']['en'], 'AAA') + self.assertEqual(response.json()["count"], 1) + self.assertEqual(response.json()["results"][0]["title"]["en"], "AAA") def test_filter_portals(self): - response = self.client.get('/api/v2/flatpage/', {'portals': self.portal.pk}) + response = self.client.get("/api/v2/flatpage/", {"portals": self.portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - self.assertEqual(response.json()['results'][0]['title']['en'], 'AAA') + self.assertEqual(response.json()["count"], 1) + self.assertEqual(response.json()["results"][0]["title"]["en"], "AAA") class ReportStatusTestCase(TestCase): @classmethod def setUpTestData(cls): cls.status1 = feedback_factory.ReportStatusFactory(label="A transmettre") - cls.status2 = feedback_factory.ReportStatusFactory(label="En cours de traitement") + cls.status2 = feedback_factory.ReportStatusFactory( + label="En cours de traitement" + ) cls.activity1 = feedback_factory.ReportActivityFactory(label="Horse-riding") cls.activity2 = feedback_factory.ReportActivityFactory(label="Climbing") cls.magnitude1 = feedback_factory.ReportProblemMagnitudeFactory(label="Easy") - cls.magnitude2 = feedback_factory.ReportProblemMagnitudeFactory(label="Hardcore") + cls.magnitude2 = feedback_factory.ReportProblemMagnitudeFactory( + label="Hardcore" + ) cls.category1 = feedback_factory.ReportCategoryFactory(label="Conflict") cls.category2 = feedback_factory.ReportCategoryFactory(label="Literring") @@ -2824,101 +3532,169 @@ def tearDown(self): super().tearDown() def test_status_list(self): - response = self.client.get('/api/v2/feedback_status/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - 'identifier': self.status1.identifier, - 'color': self.status1.color, - "id": self.status1.pk, - "label": {'en': "A transmettre", 'es': None, 'fr': None, 'it': None}, - }, - { - 'identifier': self.status2.identifier, - 'color': self.status2.color, - "id": self.status2.pk, - "label": {'en': "En cours de traitement", 'es': None, 'fr': None, 'it': None}, - }] - }) + response = self.client.get("/api/v2/feedback_status/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "identifier": self.status1.identifier, + "color": self.status1.color, + "id": self.status1.pk, + "label": { + "en": "A transmettre", + "es": None, + "fr": None, + "it": None, + }, + }, + { + "identifier": self.status2.identifier, + "color": self.status2.color, + "id": self.status2.pk, + "label": { + "en": "En cours de traitement", + "es": None, + "fr": None, + "it": None, + }, + }, + ], + }, + ) def test_activity_list(self): - response = self.client.get('/api/v2/feedback_activity/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.activity1.pk, - "label": {'en': "Horse-riding", 'es': None, 'fr': None, 'it': None}, - }, - { - "id": self.activity2.pk, - "label": {'en': "Climbing", 'es': None, 'fr': None, 'it': None}, - }] - }) + response = self.client.get("/api/v2/feedback_activity/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.activity1.pk, + "label": { + "en": "Horse-riding", + "es": None, + "fr": None, + "it": None, + }, + }, + { + "id": self.activity2.pk, + "label": {"en": "Climbing", "es": None, "fr": None, "it": None}, + }, + ], + }, + ) def test_magnitude_list(self): - response = self.client.get('/api/v2/feedback_magnitude/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.magnitude1.pk, - "label": {'en': "Easy", 'es': None, 'fr': None, 'it': None}, - }, - { - "id": self.magnitude2.pk, - "label": {'en': "Hardcore", 'es': None, 'fr': None, 'it': None}, - }] - }) + response = self.client.get("/api/v2/feedback_magnitude/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.magnitude1.pk, + "label": {"en": "Easy", "es": None, "fr": None, "it": None}, + }, + { + "id": self.magnitude2.pk, + "label": {"en": "Hardcore", "es": None, "fr": None, "it": None}, + }, + ], + }, + ) def test_category_list(self): - response = self.client.get('/api/v2/feedback_category/') - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.category1.pk, - "label": {'en': "Conflict", 'es': None, 'fr': None, 'it': None}, - }, - { - "id": self.category2.pk, - "label": {'en': "Literring", 'es': None, 'fr': None, 'it': None}, - }] - }) + response = self.client.get("/api/v2/feedback_category/") + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.category1.pk, + "label": {"en": "Conflict", "es": None, "fr": None, "it": None}, + }, + { + "id": self.category2.pk, + "label": { + "en": "Literring", + "es": None, + "fr": None, + "it": None, + }, + }, + ], + }, + ) class LanguageOrderingTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.trek1 = trek_factory.TrekFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) - cls.trek2 = trek_factory.TrekFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) - cls.trek3 = trek_factory.TrekFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) - cls.trek4 = trek_factory.TrekFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) - cls.course1 = outdoor_factory.CourseFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) - cls.course2 = outdoor_factory.CourseFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) - cls.course3 = outdoor_factory.CourseFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) - cls.course4 = outdoor_factory.CourseFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) - cls.site1 = outdoor_factory.SiteFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) - cls.site2 = outdoor_factory.SiteFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) - cls.site3 = outdoor_factory.SiteFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) - cls.site4 = outdoor_factory.SiteFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) - cls.tc1 = tourism_factory.TouristicContentFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) - cls.tc2 = tourism_factory.TouristicContentFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) - cls.tc3 = tourism_factory.TouristicContentFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) - cls.tc4 = tourism_factory.TouristicContentFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) + cls.trek1 = trek_factory.TrekFactory( + name_fr="AAA", name_en="ABA", published_fr=True, published_en=True + ) + cls.trek2 = trek_factory.TrekFactory( + name_fr="ABA", name_en="BAA", published_fr=True, published_en=True + ) + cls.trek3 = trek_factory.TrekFactory( + name_fr="BAA", name_en="AAA", published_fr=True, published_en=True + ) + cls.trek4 = trek_factory.TrekFactory( + name_fr="CCC", name_en="CCC", published_fr=True, published_en=True + ) + cls.course1 = outdoor_factory.CourseFactory( + name_fr="AAA", name_en="ABA", published_fr=True, published_en=True + ) + cls.course2 = outdoor_factory.CourseFactory( + name_fr="ABA", name_en="BAA", published_fr=True, published_en=True + ) + cls.course3 = outdoor_factory.CourseFactory( + name_fr="BAA", name_en="AAA", published_fr=True, published_en=True + ) + cls.course4 = outdoor_factory.CourseFactory( + name_fr="CCC", name_en="CCC", published_fr=True, published_en=True + ) + cls.site1 = outdoor_factory.SiteFactory( + name_fr="AAA", name_en="ABA", published_fr=True, published_en=True + ) + cls.site2 = outdoor_factory.SiteFactory( + name_fr="ABA", name_en="BAA", published_fr=True, published_en=True + ) + cls.site3 = outdoor_factory.SiteFactory( + name_fr="BAA", name_en="AAA", published_fr=True, published_en=True + ) + cls.site4 = outdoor_factory.SiteFactory( + name_fr="CCC", name_en="CCC", published_fr=True, published_en=True + ) + cls.tc1 = tourism_factory.TouristicContentFactory( + name_fr="AAA", name_en="ABA", published_fr=True, published_en=True + ) + cls.tc2 = tourism_factory.TouristicContentFactory( + name_fr="ABA", name_en="BAA", published_fr=True, published_en=True + ) + cls.tc3 = tourism_factory.TouristicContentFactory( + name_fr="BAA", name_en="AAA", published_fr=True, published_en=True + ) + cls.tc4 = tourism_factory.TouristicContentFactory( + name_fr="CCC", name_en="CCC", published_fr=True, published_en=True + ) def tearDown(self): clear_internal_user_cache() @@ -2926,89 +3702,114 @@ def tearDown(self): def assert_ordered_by_language(self, endpoint, ordered_ids, language): # GET request on list with language param - response = self.client.get(reverse(endpoint), {'language': language}) + response = self.client.get(reverse(endpoint), {"language": language}) self.assertEqual(response.status_code, 200) # Assert response list is ordered as expected for index, expected_id in enumerate(ordered_ids): - self.assertEqual(response.json()['results'][index]['id'], expected_id) + self.assertEqual(response.json()["results"][index]["id"], expected_id) def test_ordered_trek_lists(self): order_fr = [self.trek1.id, self.trek2.id, self.trek3.id, self.trek4.id] - self.assert_ordered_by_language('apiv2:trek-list', order_fr, 'fr') + self.assert_ordered_by_language("apiv2:trek-list", order_fr, "fr") order_en = [self.trek3.id, self.trek1.id, self.trek2.id, self.trek4.id] - self.assert_ordered_by_language('apiv2:trek-list', order_en, 'en') + self.assert_ordered_by_language("apiv2:trek-list", order_en, "en") def test_ordered_touristic_content_lists(self): order_fr = [self.tc1.id, self.tc2.id, self.tc3.id, self.tc4.id] - self.assert_ordered_by_language('apiv2:touristiccontent-list', order_fr, 'fr') + self.assert_ordered_by_language("apiv2:touristiccontent-list", order_fr, "fr") order_en = [self.tc3.id, self.tc1.id, self.tc2.id, self.tc4.id] - self.assert_ordered_by_language('apiv2:touristiccontent-list', order_en, 'en') + self.assert_ordered_by_language("apiv2:touristiccontent-list", order_en, "en") def test_ordered_outdoor_site_lists(self): order_fr = [self.site1.id, self.site2.id, self.site3.id, self.site4.id] - self.assert_ordered_by_language('apiv2:site-list', order_fr, 'fr') + self.assert_ordered_by_language("apiv2:site-list", order_fr, "fr") order_en = [self.site3.id, self.site1.id, self.site2.id, self.site4.id] - self.assert_ordered_by_language('apiv2:site-list', order_en, 'en') + self.assert_ordered_by_language("apiv2:site-list", order_en, "en") def test_order_outdoor_course_lists(self): order_fr = [self.course1.id, self.course2.id, self.course3.id, self.course4.id] - self.assert_ordered_by_language('apiv2:course-list', order_fr, 'fr') + self.assert_ordered_by_language("apiv2:course-list", order_fr, "fr") order_en = [self.course3.id, self.course1.id, self.course2.id, self.course4.id] - self.assert_ordered_by_language('apiv2:course-list', order_en, 'en') + self.assert_ordered_by_language("apiv2:course-list", order_en, "en") class WebLinksCategoryTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.web_link_cat1 = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto1.png', label="To do") - cls.web_link_cat2 = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto2.png', label="To see") - cls.web_link_cat3 = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto3.png', label="To eat") + cls.web_link_cat1 = trek_factory.WebLinkCategoryFactory( + pictogram="dummy_picto1.png", label="To do" + ) + cls.web_link_cat2 = trek_factory.WebLinkCategoryFactory( + pictogram="dummy_picto2.png", label="To see" + ) + cls.web_link_cat3 = trek_factory.WebLinkCategoryFactory( + pictogram="dummy_picto3.png", label="To eat" + ) def tearDown(self): clear_internal_user_cache() super().tearDown() def test_web_links_category_list(self): - response = self.client.get(reverse('apiv2:weblink-category-list')) - self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - "count": 3, - "next": None, - "previous": None, - "results": [ - { - "label": {'en': "To do", 'es': None, 'fr': None, 'it': None}, - "id": self.web_link_cat1.pk, - "pictogram": "http://testserver/media/dummy_picto1.png", - }, - { - "label": {'en': "To eat", 'es': None, 'fr': None, 'it': None}, - "id": self.web_link_cat3.pk, - "pictogram": "http://testserver/media/dummy_picto3.png", - }, - { - "label": {'en': "To see", 'es': None, 'fr': None, 'it': None}, - "id": self.web_link_cat2.pk, - "pictogram": "http://testserver/media/dummy_picto2.png", - }] - }) + response = self.client.get(reverse("apiv2:weblink-category-list")) + self.assertEqual(response.status_code, 200) + self.assertJSONEqual( + response.content, + { + "count": 3, + "next": None, + "previous": None, + "results": [ + { + "label": {"en": "To do", "es": None, "fr": None, "it": None}, + "id": self.web_link_cat1.pk, + "pictogram": "http://testserver/media/dummy_picto1.png", + }, + { + "label": {"en": "To eat", "es": None, "fr": None, "it": None}, + "id": self.web_link_cat3.pk, + "pictogram": "http://testserver/media/dummy_picto3.png", + }, + { + "label": {"en": "To see", "es": None, "fr": None, "it": None}, + "id": self.web_link_cat2.pk, + "pictogram": "http://testserver/media/dummy_picto2.png", + }, + ], + }, + ) def test_web_links_category_detail(self): response = self.client.get(f"/api/v2/weblink_category/{self.web_link_cat1.pk}/") self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, { - "label": {'en': "To do", 'es': None, 'fr': None, 'it': None}, - "id": self.web_link_cat1.pk, - "pictogram": "http://testserver/media/dummy_picto1.png", - }) + self.assertJSONEqual( + response.content, + { + "label": {"en": "To do", "es": None, "fr": None, "it": None}, + "id": self.web_link_cat1.pk, + "pictogram": "http://testserver/media/dummy_picto1.png", + }, + ) class TrekWebLinksTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.web_link_cat = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto.png', label_en='Category') - cls.web_link1 = trek_factory.WebLinkFactory(category=cls.web_link_cat, name="Web link", name_en="Web link", url="http://dummy.url") - cls.web_link2 = trek_factory.WebLinkFactory(category=cls.web_link_cat, name="Web link", name_en="Web link", url="http://dummy.url") + cls.web_link_cat = trek_factory.WebLinkCategoryFactory( + pictogram="dummy_picto.png", label_en="Category" + ) + cls.web_link1 = trek_factory.WebLinkFactory( + category=cls.web_link_cat, + name="Web link", + name_en="Web link", + url="http://dummy.url", + ) + cls.web_link2 = trek_factory.WebLinkFactory( + category=cls.web_link_cat, + name="Web link", + name_en="Web link", + url="http://dummy.url", + ) cls.trek1 = trek_factory.TrekFactory(web_links=[cls.web_link1, cls.web_link2]) def tearDown(self): @@ -3016,31 +3817,44 @@ def tearDown(self): super().tearDown() def test_web_links_in_trek_list(self): - response = self.client.get(reverse('apiv2:trek-list')) - self.assertEqual(response.status_code, 200) - json_result = response.json()['results'][0] - web_links = json_result['web_links'] - self.assertEqual(json_result['id'], self.trek1.pk) - self.assertEqual(web_links[0]['name']['en'], "Web link") - self.assertEqual(web_links[0]['url'], "http://dummy.url") - self.assertEqual(web_links[0]['category']['label']['en'], "Category") - self.assertEqual(web_links[0]['category']['id'], self.web_link_cat.pk) - self.assertEqual(web_links[0]['category']['pictogram'], 'http://testserver/media/dummy_picto.png') - self.assertEqual(web_links[1]['name']['en'], "Web link") - self.assertEqual(web_links[1]['url'], "http://dummy.url") - self.assertEqual(web_links[1]['category']['label']['en'], "Category") - self.assertEqual(web_links[1]['category']['id'], self.web_link_cat.pk) - self.assertEqual(web_links[1]['category']['pictogram'], 'http://testserver/media/dummy_picto.png') + response = self.client.get(reverse("apiv2:trek-list")) + self.assertEqual(response.status_code, 200) + json_result = response.json()["results"][0] + web_links = json_result["web_links"] + self.assertEqual(json_result["id"], self.trek1.pk) + self.assertEqual(web_links[0]["name"]["en"], "Web link") + self.assertEqual(web_links[0]["url"], "http://dummy.url") + self.assertEqual(web_links[0]["category"]["label"]["en"], "Category") + self.assertEqual(web_links[0]["category"]["id"], self.web_link_cat.pk) + self.assertEqual( + web_links[0]["category"]["pictogram"], + "http://testserver/media/dummy_picto.png", + ) + self.assertEqual(web_links[1]["name"]["en"], "Web link") + self.assertEqual(web_links[1]["url"], "http://dummy.url") + self.assertEqual(web_links[1]["category"]["label"]["en"], "Category") + self.assertEqual(web_links[1]["category"]["id"], self.web_link_cat.pk) + self.assertEqual( + web_links[1]["category"]["pictogram"], + "http://testserver/media/dummy_picto.png", + ) def test_web_links_in_trek_detail(self): response = self.client.get(f"/api/v2/trek/{self.trek1.pk}/") self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['id'], self.trek1.pk) - self.assertEqual(response.json()['web_links'][0]['name']['en'], "Web link") - self.assertEqual(response.json()['web_links'][0]['url'], "http://dummy.url") - self.assertEqual(response.json()['web_links'][0]['category']['label']['en'], "Category") - self.assertEqual(response.json()['web_links'][0]['category']['id'], self.web_link_cat.pk) - self.assertEqual(response.json()['web_links'][0]['category']['pictogram'], 'http://testserver/media/dummy_picto.png') + self.assertEqual(response.json()["id"], self.trek1.pk) + self.assertEqual(response.json()["web_links"][0]["name"]["en"], "Web link") + self.assertEqual(response.json()["web_links"][0]["url"], "http://dummy.url") + self.assertEqual( + response.json()["web_links"][0]["category"]["label"]["en"], "Category" + ) + self.assertEqual( + response.json()["web_links"][0]["category"]["id"], self.web_link_cat.pk + ) + self.assertEqual( + response.json()["web_links"][0]["category"]["pictogram"], + "http://testserver/media/dummy_picto.png", + ) class TrekDifficultyFilterCase(TestCase): @@ -3062,11 +3876,19 @@ def tearDown(self): super().tearDown() def assert_trek_is_in_reponse(self, response, expected_trek): - found = list(filter(lambda trek: trek['id'] == expected_trek.pk, response.json()['results'])) + found = list( + filter( + lambda trek: trek["id"] == expected_trek.pk, response.json()["results"] + ) + ) self.assertTrue(found) def assert_trek_is_not_in_reponse(self, response, expected_trek): - found = list(filter(lambda trek: trek['id'] == expected_trek.pk, response.json()['results'])) + found = list( + filter( + lambda trek: trek["id"] == expected_trek.pk, response.json()["results"] + ) + ) self.assertFalse(found) def test_difficulty_ids(self): @@ -3077,9 +3899,9 @@ def test_difficulty_ids(self): self.assertEqual(self.v_hard.id, 5) def test_filter_difficulty_min(self): - response = self.client.get("/api/v2/trek/", {'difficulty_min': self.medium.id}) + response = self.client.get("/api/v2/trek/", {"difficulty_min": self.medium.id}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 3) + self.assertEqual(response.json()["count"], 3) self.assert_trek_is_not_in_reponse(response, self.trek_v_easy) self.assert_trek_is_not_in_reponse(response, self.trek_easy) self.assert_trek_is_in_reponse(response, self.trek_medium) @@ -3087,9 +3909,9 @@ def test_filter_difficulty_min(self): self.assert_trek_is_in_reponse(response, self.trek_v_hard) def test_filter_difficulty_max(self): - response = self.client.get("/api/v2/trek/", {'difficulty_max': self.medium.id}) + response = self.client.get("/api/v2/trek/", {"difficulty_max": self.medium.id}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 3) + self.assertEqual(response.json()["count"], 3) self.assert_trek_is_in_reponse(response, self.trek_v_easy) self.assert_trek_is_in_reponse(response, self.trek_easy) self.assert_trek_is_in_reponse(response, self.trek_medium) @@ -3097,9 +3919,12 @@ def test_filter_difficulty_max(self): self.assert_trek_is_not_in_reponse(response, self.trek_v_hard) def test_filter_difficulty_min_max_1(self): - response = self.client.get("/api/v2/trek/", {'difficulty_min': self.easy.id, 'difficulty_max': self.hard.id}) + response = self.client.get( + "/api/v2/trek/", + {"difficulty_min": self.easy.id, "difficulty_max": self.hard.id}, + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 3) + self.assertEqual(response.json()["count"], 3) self.assert_trek_is_not_in_reponse(response, self.trek_v_easy) self.assert_trek_is_in_reponse(response, self.trek_easy) self.assert_trek_is_in_reponse(response, self.trek_medium) @@ -3107,9 +3932,12 @@ def test_filter_difficulty_min_max_1(self): self.assert_trek_is_not_in_reponse(response, self.trek_v_hard) def test_filter_difficulty_min_max_2(self): - response = self.client.get("/api/v2/trek/", {'difficulty_min': self.hard.id, 'difficulty_max': self.hard.id}) + response = self.client.get( + "/api/v2/trek/", + {"difficulty_min": self.hard.id, "difficulty_max": self.hard.id}, + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) + self.assertEqual(response.json()["count"], 1) self.assert_trek_is_not_in_reponse(response, self.trek_v_easy) self.assert_trek_is_not_in_reponse(response, self.trek_easy) self.assert_trek_is_not_in_reponse(response, self.trek_medium) @@ -3122,7 +3950,6 @@ def test_filter_difficulty_min_max_2(self): @override_settings(TOURISM_INTERSECTION_MARGIN=500) @freeze_time("2000-07-04") class TouristicEventTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.touristic_event_type = tourism_factory.TouristicEventTypeFactory() @@ -3147,21 +3974,23 @@ def setUpTestData(cls): end_time=datetime.time(12, 20), cancelled=True, place=cls.other_place, - cancellation_reason=tourism_factory.CancellationReasonFactory(label_en="Fire", label_fr="Incendie") + cancellation_reason=tourism_factory.CancellationReasonFactory( + label_en="Fire", label_fr="Incendie" + ), ) cls.touristic_event1.portal.set([common_factory.TargetPortalFactory()]) cls.touristic_event2 = tourism_factory.TouristicEventFactory( name_fr="expo", geom=Point(5.77802, 2.047482, srid=4326), published=True, - bookable=False + bookable=False, ) cls.touristic_event2.portal.set([common_factory.TargetPortalFactory()]) - cls.path = core_factory.PathFactory.create(geom=LineString((0.77802, 43.047482), (0.77803, 43.047483), srid=4326)) + cls.path = core_factory.PathFactory.create( + geom=LineString((0.77802, 43.047482), (0.77803, 43.047483), srid=4326) + ) cls.trek = trek_factory.TrekFactory.create( - paths=[(cls.path, 0, 1)], - geom=cls.path.geom, - published=True + paths=[(cls.path, 0, 1)], geom=cls.path.geom, published=True ) cls.touristic_event3 = tourism_factory.TouristicEventFactory( name_fr="expooo", @@ -3169,23 +3998,25 @@ def setUpTestData(cls): published=False, ) # Should not appear at any point - cls.touristic_event4 = tourism_factory.TouristicEventFactory( - deleted=True + cls.touristic_event4 = tourism_factory.TouristicEventFactory(deleted=True) + cls.organizer = tourism_factory.TouristicEventOrganizerFactory( + label="OrganizerA" ) - cls.organizer = tourism_factory.TouristicEventOrganizerFactory(label='OrganizerA') cls.place_unpublished = tourism_factory.TouristicEventPlaceFactory(name="There") cls.touristic_event5 = tourism_factory.TouristicEventFactory( end_date=None, published=True, name="No end date", - begin_date='2022-02-20', + begin_date="2022-02-20", start_time="12:34", capacity=12, bookable=False, place=cls.place, - organizer=cls.organizer + organizer=cls.organizer, + ) + cls.touristic_content = tourism_factory.TouristicContentFactory( + geom=Point(0.77802, 43.047482, srid=4326) ) - cls.touristic_content = tourism_factory.TouristicContentFactory(geom=Point(0.77802, 43.047482, srid=4326)) def test_touristic_event_list(self): response = self.get_touristicevent_list() @@ -3197,49 +4028,61 @@ def test_touristic_event_list_2(self): # Only two because past events are filter by default self.assertEqual(response.json().get("count"), 2) # Event with no end date is returned with begin date as end date - self.assertEqual(response.json().get("results")[0]['end_date'], "2022-02-20") + self.assertEqual(response.json().get("results")[0]["end_date"], "2022-02-20") # start_time replaces meeting_time - self.assertEqual(response.json().get("results")[0]['meeting_time'], "12:34:00") + self.assertEqual(response.json().get("results")[0]["meeting_time"], "12:34:00") # capacity replaces participant_number - self.assertEqual(response.json().get("results")[0]['participant_number'], '12') + self.assertEqual(response.json().get("results")[0]["participant_number"], "12") # Event with end date returns right end date - self.assertEqual(response.json().get("results")[1]['end_date'], "2202-02-22") + self.assertEqual(response.json().get("results")[1]["end_date"], "2202-02-22") # Sorted by end date - self.assertLessEqual(response.json().get("results")[0]['end_date'], response.json().get("results")[1]['end_date']) + self.assertLessEqual( + response.json().get("results")[0]["end_date"], + response.json().get("results")[1]["end_date"], + ) def test_touristic_event_dates_filters_1(self): - response = self.get_touristicevent_list({'dates_before': '2200-01-01', 'dates_after': '1970-01-01'}) + response = self.get_touristicevent_list( + {"dates_before": "2200-01-01", "dates_after": "1970-01-01"} + ) self.assertEqual(response.json().get("count"), 3) def test_touristic_event_dates_filters_2(self): - response = self.get_touristicevent_list({'dates_before': '2021-09-01', 'dates_after': '1970-01-01'}) + response = self.get_touristicevent_list( + {"dates_before": "2021-09-01", "dates_after": "1970-01-01"} + ) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_dates_filters_3(self): - response = self.get_touristicevent_list({'dates_after': '2021-07-03'}) + response = self.get_touristicevent_list({"dates_after": "2021-07-03"}) self.assertEqual(response.json().get("count"), 3) def test_touristic_event_dates_filters_4(self): - response = self.get_touristicevent_list({'dates_after': '2021-07-04'}) + response = self.get_touristicevent_list({"dates_after": "2021-07-04"}) # Event 1 finishes on 3rd of july self.assertEqual(response.json().get("count"), 2) def test_touristic_event_organizer_filters_1(self): - response = self.get_touristicevent_list({'organizer': 'tt'}) - self.assertEqual(response.json()['organizer'][0], - '“tt” is not a valid value.') + response = self.get_touristicevent_list({"organizer": "tt"}) + self.assertEqual(response.json()["organizer"][0], "“tt” is not a valid value.") def test_touristic_event_organizer_filters_2(self): - response = self.get_touristicevent_list({'organizer': f'{self.organizer.pk}'}) + response = self.get_touristicevent_list({"organizer": f"{self.organizer.pk}"}) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_cancelled_filter(self): - response = self.get_touristicevent_list({'cancelled': 'True'}) + response = self.get_touristicevent_list({"cancelled": "True"}) self.assertEqual(response.json().get("count"), 1) self.assertTrue(response.json().get("results")[0].get("cancelled")) - self.assertEqual(response.json().get("results")[0].get("cancellation_reason").get('en'), "Fire") - self.assertEqual(response.json().get("results")[0].get("cancellation_reason").get('fr'), "Incendie") - response = self.get_touristicevent_list({'cancelled': 'False'}) + self.assertEqual( + response.json().get("results")[0].get("cancellation_reason").get("en"), + "Fire", + ) + self.assertEqual( + response.json().get("results")[0].get("cancellation_reason").get("fr"), + "Incendie", + ) + response = self.get_touristicevent_list({"cancelled": "False"}) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_detail(self): @@ -3248,48 +4091,63 @@ def test_touristic_event_detail(self): def test_touristic_event_place_detail(self): response = self.get_touristiceventplace_detail(self.place.pk) - self.check_structure_response(response, TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE) + self.check_structure_response( + response, TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE + ) def test_touristic_event_organizer_detail(self): response = self.get_touristiceventorganizer_detail(self.organizer.pk) - self.check_structure_response(response, TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE) + self.check_structure_response( + response, TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE + ) def test_touristicevent_near_trek(self): - response = self.get_touristicevent_list({'near_trek': self.trek.pk}) + response = self.get_touristicevent_list({"near_trek": self.trek.pk}) # Event 1 appears but not Event 2 self.assertEqual(response.json().get("count"), 1) def test_touristicevent_near_touristicevent(self): - response = self.get_touristicevent_list({'near_touristicevent': self.touristic_event3.pk}) + response = self.get_touristicevent_list( + {"near_touristicevent": self.touristic_event3.pk} + ) # Event 2 appears but not Event 1 (too far) or Event 3 (not published) self.assertEqual(response.json().get("count"), 1) def test_touristicevent_near_touristiccontent(self): - response = self.get_touristicevent_list({'near_touristiccontent': self.touristic_content.pk}) + response = self.get_touristicevent_list( + {"near_touristiccontent": self.touristic_content.pk} + ) # Event 1 appears but not Event 2 (too far) or Event 3 (too far + not published) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_portal_filters(self): - response = self.get_touristicevent_list({'portals': self.touristic_event1.portal.first().pk}) + response = self.get_touristicevent_list( + {"portals": self.touristic_event1.portal.first().pk} + ) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_type_filters(self): - response = self.get_touristicevent_list({'types': self.touristic_event_type.pk}) + response = self.get_touristicevent_list({"types": self.touristic_event_type.pk}) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_bookable(self): - response = self.get_touristicevent_list({'bookable': 'True'}) + response = self.get_touristicevent_list({"bookable": "True"}) self.assertEqual(response.json().get("count"), 1) - response = self.get_touristicevent_list({'bookable': 'False'}) + response = self.get_touristicevent_list({"bookable": "False"}) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_place_filter(self): - response = self.get_touristicevent_list({'place': f"{self.place.pk},{self.other_place.pk}"}) + response = self.get_touristicevent_list( + {"place": f"{self.place.pk},{self.other_place.pk}"} + ) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_place_not_valid_filter(self): - response = self.get_touristicevent_list({'place': "100000"}) - self.assertEqual(response.json()['place'][0], "Select a valid choice. 100000 is not one of the available choices.") + response = self.get_touristicevent_list({"place": "100000"}) + self.assertEqual( + response.json()["place"][0], + "Select a valid choice. 100000 is not one of the available choices.", + ) def test_touristic_event_place_list(self): response = self.get_touristiceventplace_list() @@ -3299,10 +4157,11 @@ def test_touristic_event_place_list(self): class TouristicEventTypeTestCase(BaseApiTest): @classmethod def setUpTestData(cls): - cls.touristic_event_type = tourism_factory.TouristicEventTypeFactory(type_fr="Cool", type_en="af") + cls.touristic_event_type = tourism_factory.TouristicEventTypeFactory( + type_fr="Cool", type_en="af" + ) cls.touristic_event = tourism_factory.TouristicEventFactory( - published=True, - type=cls.touristic_event_type + published=True, type=cls.touristic_event_type ) def test_touristic_event_type_list(self): @@ -3312,11 +4171,13 @@ def test_touristic_event_type_list(self): def test_touristic_event_type_detail(self): response = self.get_touristiceventtype_detail(self.touristic_event_type.pk) - self.check_structure_response(response, TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE) + self.check_structure_response( + response, TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE + ) class TouristicEventTypeFilterTestCase(BaseApiTest): - """ Test filtering depending on published, deleted content for touristic event types """ + """Test filtering depending on published, deleted content for touristic event types""" @classmethod def setUpTestData(cls): @@ -3326,62 +4187,68 @@ def setUpTestData(cls): # Type with no published content -> don't send it cls.type_with_no_published_content = tourism_factory.TouristicEventTypeFactory() cls.not_published_event = tourism_factory.TouristicEventFactory( - published=False, - type=cls.type_with_no_published_content + published=False, type=cls.type_with_no_published_content ) # Type with no content that was not deleted -> don't send it cls.type_with_only_deleted_content = tourism_factory.TouristicEventTypeFactory() cls.deleted_event = tourism_factory.TouristicEventFactory( - deleted=True, - type=cls.type_with_only_deleted_content + deleted=True, type=cls.type_with_only_deleted_content ) # Type with published and not deleted content -> send it - cls.type_with_published_and_not_deleted_content = tourism_factory.TouristicEventTypeFactory() + cls.type_with_published_and_not_deleted_content = ( + tourism_factory.TouristicEventTypeFactory() + ) cls.published_and_not_deleted_event = tourism_factory.TouristicEventFactory( deleted=False, published_en=True, - type=cls.type_with_published_and_not_deleted_content + type=cls.type_with_published_and_not_deleted_content, ) # Type with published_fr and not deleted content -> send it when language=fr - cls.type_with_published_and_not_deleted_content_with_lang = tourism_factory.TouristicEventTypeFactory() - cls.published_and_not_deleted_event_with_lang = tourism_factory.TouristicEventFactory( - deleted=False, - published_fr=True, - type=cls.type_with_published_and_not_deleted_content_with_lang + cls.type_with_published_and_not_deleted_content_with_lang = ( + tourism_factory.TouristicEventTypeFactory() + ) + cls.published_and_not_deleted_event_with_lang = ( + tourism_factory.TouristicEventFactory( + deleted=False, + published_fr=True, + type=cls.type_with_published_and_not_deleted_content_with_lang, + ) ) def test_touristic_event_type_list_returns_published(self): - """ Assert API returns only types with published events - """ + """Assert API returns only types with published events""" response = self.get_touristiceventtype_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 2) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) self.assertIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids + ) def test_touristic_event_type_list_returns_published_in_language(self): - """ Assert API returns only published events in specified language - """ - response = self.get_touristiceventtype_list({'language': 'fr'}) + """Assert API returns only published events in specified language""" + response = self.get_touristiceventtype_list({"language": "fr"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) self.assertNotIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids + ) class TouristicEventTypeFilterByPortalTestCase(TouristicEventTypeFilterTestCase): - """ Test filtering depending on portal for touristic event types """ + """Test filtering depending on portal for touristic event types""" @classmethod def setUpTestData(cls): @@ -3411,69 +4278,70 @@ def setUpTestData(cls): cls.not_deleted_event_on_other_portal.portal.set([cls.other_portal]) def test_touristic_event_type_list_returns_published(self): - """ Assert API returns only types with published events on portal - """ - response = self.get_touristiceventtype_list({'portals': self.queried_portal.pk}) + """Assert API returns only types with published events on portal""" + response = self.get_touristiceventtype_list({"portals": self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 0) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 0) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) # Didn't set portal on these ones yet self.assertNotIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertNotIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) + self.assertNotIn( + self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids + ) def test_touristic_event_type_list_returns_published_2(self): - """ Assert API returns only types with published events on portal - """ + """Assert API returns only types with published events on portal""" # Type with published and not deleted content on portal -> send it self.published_and_not_deleted_event.portal.set([self.queried_portal]) # Type with published_fr and not deleted content on portal -> send it when language=fr self.published_and_not_deleted_event_with_lang.portal.set([self.queried_portal]) - response = self.get_touristiceventtype_list({'portals': self.queried_portal.pk}) + response = self.get_touristiceventtype_list({"portals": self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 2) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) # Portal is set this time self.assertIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids + ) class NearOutdoorFilterTestCase(BaseApiTest): - """ Test near_outdoorsite and near_outdoorcourse filter on routes """ + """Test near_outdoorsite and near_outdoorcourse filter on routes""" @classmethod def setUpTestData(cls): cls.site = outdoor_factory.SiteFactory( - published_fr=True, - geom=GeometryCollection(Point(100.1, 100.1, srid=2154)) + published_fr=True, geom=GeometryCollection(Point(100.1, 100.1, srid=2154)) ) cls.course = outdoor_factory.CourseFactory( published_fr=True, geom=GeometryCollection(Point(100, 100, srid=2154)), - parent_sites=[cls.site] + parent_sites=[cls.site], ) # trek1 is nearby - cls.path1 = core_factory.PathFactory.create(geom=LineString((0.0, 0.0), (1.0, 1.0), srid=2154)) + cls.path1 = core_factory.PathFactory.create( + geom=LineString((0.0, 0.0), (1.0, 1.0), srid=2154) + ) cls.trek1 = trek_factory.TrekFactory.create( - paths=[(cls.path1, 0, 1)], - geom=cls.path1.geom, - published_fr=True + paths=[(cls.path1, 0, 1)], geom=cls.path1.geom, published_fr=True ) # trek2 is far away - cls.path2 = core_factory.PathFactory.create(geom=LineString((9999.0, 9999.0), (9999.0, 9998.0), srid=2154)) + cls.path2 = core_factory.PathFactory.create( + geom=LineString((9999.0, 9999.0), (9999.0, 9998.0), srid=2154) + ) cls.trek2 = trek_factory.TrekFactory.create( - paths=[(cls.path2, 0, 1)], - geom=cls.path2.geom, - published_fr=True + paths=[(cls.path2, 0, 1)], geom=cls.path2.geom, published_fr=True ) # event1 is nearby cls.touristic_event1 = tourism_factory.TouristicEventFactory( @@ -3497,36 +4365,31 @@ def setUpTestData(cls): ) # site1 is nearby cls.site1 = outdoor_factory.SiteFactory( - published_fr=True, - geom=GeometryCollection(Point(100.5, 100.5, srid=2154)) + published_fr=True, geom=GeometryCollection(Point(100.5, 100.5, srid=2154)) ) # site2 is far away cls.site2 = outdoor_factory.SiteFactory( - published_fr=True, - geom=GeometryCollection(Point(9999.5, 9999.5, srid=2154)) + published_fr=True, geom=GeometryCollection(Point(9999.5, 9999.5, srid=2154)) ) # course1 is nearby cls.course1 = outdoor_factory.CourseFactory( published_fr=True, geom=GeometryCollection(Point(100.5, 100.5, srid=2154)), - parent_sites=[cls.site1] + parent_sites=[cls.site1], ) # course2 is far away cls.course2 = outdoor_factory.CourseFactory( published_fr=True, geom=GeometryCollection(Point(9999.5, 9999.5, srid=2154)), - parent_sites=[cls.site2] - + parent_sites=[cls.site2], ) # poi 1 is nearby cls.poi1 = trek_factory.POIFactory( - paths=[(cls.path1, 0, 0)], - geom=cls.path1.geom + paths=[(cls.path1, 0, 0)], geom=cls.path1.geom ) # poi 2 isfar away cls.poi2 = trek_factory.POIFactory( - paths=[(cls.path2, 0, 0)], - geom=cls.path2.geom + paths=[(cls.path2, 0, 0)], geom=cls.path2.geom ) # info desk 1 is nearby cls.info_desk1 = tourism_factory.InformationDeskFactory( @@ -3540,106 +4403,100 @@ def setUpTestData(cls): cls.trek2.information_desks.set([cls.info_desk2]) # sensitive area 1 is nearby cls.sensitivearea1 = sensitivity_factory.SensitiveAreaFactory( - geom=Polygon( - ( - (0, 0), - (0, 1), - (1, 1), - (0, 0) - ), - srid=2154 - ) + geom=Polygon(((0, 0), (0, 1), (1, 1), (0, 0)), srid=2154) ) # sensitive area 2 is nearby cls.sensitivearea2 = sensitivity_factory.SensitiveAreaFactory( geom=Polygon( - ( - (9999, 9999), - (9999, 9998), - (9998, 9998), - (9999, 9999) - ), - srid=2154 + ((9999, 9999), (9999, 9998), (9998, 9998), (9999, 9999)), srid=2154 ) ) def test_trek_near_outdoorcourse(self): - response = self.get_trek_list({'near_outdoorcourse': self.course.pk}) + response = self.get_trek_list({"near_outdoorcourse": self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.trek1.pk) def test_trek_near_outdoorsite(self): - response = self.get_trek_list({'near_outdoorsite': self.site.pk}) + response = self.get_trek_list({"near_outdoorsite": self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.trek1.pk) def test_touristicevent_near_outdoorcourse(self): - response = self.get_touristicevent_list({'near_outdoorcourse': self.course.pk}) + response = self.get_touristicevent_list({"near_outdoorcourse": self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.touristic_event1.pk) def test_touristicevent_near_outdoorsite(self): - response = self.get_touristicevent_list({'near_outdoorsite': self.site.pk}) + response = self.get_touristicevent_list({"near_outdoorsite": self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.touristic_event1.pk) def test_touristiccontent_near_outdoorcourse(self): - response = self.get_touristiccontent_list({'near_outdoorcourse': self.course.pk}) + response = self.get_touristiccontent_list( + {"near_outdoorcourse": self.course.pk} + ) self.assertEqual(response.json()["count"], 1) - self.assertEqual(response.json()["results"][0]["id"], self.touristic_content1.pk) + self.assertEqual( + response.json()["results"][0]["id"], self.touristic_content1.pk + ) def test_touristiccontent_near_outdoorsite(self): - response = self.get_touristiccontent_list({'near_outdoorsite': self.site.pk}) + response = self.get_touristiccontent_list({"near_outdoorsite": self.site.pk}) self.assertEqual(response.json()["count"], 1) - self.assertEqual(response.json()["results"][0]["id"], self.touristic_content1.pk) + self.assertEqual( + response.json()["results"][0]["id"], self.touristic_content1.pk + ) def test_outdoorcourse_near_outdoorcourse(self): - response = self.get_course_list({'near_outdoorcourse': self.course.pk}) + response = self.get_course_list({"near_outdoorcourse": self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.course1.pk) def test_outdoorcourse_near_outdoorsite(self): - response = self.get_course_list({'near_outdoorsite': self.site.pk}) + response = self.get_course_list({"near_outdoorsite": self.site.pk}) self.assertEqual(response.json()["count"], 2) self.assertEqual(response.json()["results"][0]["id"], self.course.pk) self.assertEqual(response.json()["results"][1]["id"], self.course1.pk) def test_outdoorsite_near_outdoorcourse(self): - response = self.get_site_list({'near_outdoorcourse': self.course.pk}) + response = self.get_site_list({"near_outdoorcourse": self.course.pk}) self.assertEqual(response.json()["count"], 2) self.assertEqual(response.json()["results"][0]["id"], self.site.pk) self.assertEqual(response.json()["results"][1]["id"], self.site1.pk) def test_outdoorsite_near_outdoorsite(self): - response = self.get_site_list({'near_outdoorsite': self.site.pk}) + response = self.get_site_list({"near_outdoorsite": self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.site1.pk) def test_poi_near_outdoorcourse(self): - response = self.get_poi_list({'near_outdoorcourse': self.course.pk}) + response = self.get_poi_list({"near_outdoorcourse": self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.poi1.pk) def test_poi_near_outdoorsite(self): - response = self.get_poi_list({'near_outdoorsite': self.site.pk}) + response = self.get_poi_list({"near_outdoorsite": self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.poi1.pk) def test_sensitivearea_near_outdoorcourse(self): - response = self.get_sensitivearea_list({'near_outdoorcourse': self.course.pk, 'period': 'any'}) + response = self.get_sensitivearea_list( + {"near_outdoorcourse": self.course.pk, "period": "any"} + ) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.sensitivearea1.pk) def test_sensitivearea_near_outdoorsite(self): - response = self.get_sensitivearea_list({'near_outdoorsite': self.site.pk, 'period': 'any'}) + response = self.get_sensitivearea_list( + {"near_outdoorsite": self.site.pk, "period": "any"} + ) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.sensitivearea1.pk) class NearbyContentFilterTestCase(BaseApiTest): - def test_list_objects_filtered_by_near_target(self): - get_list_funcs = [ self.get_site_list, self.get_course_list, @@ -3669,7 +4526,6 @@ def test_list_objects_filtered_by_near_target(self): class UpdateOrCreateDatesFilterTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.path1 = core_factory.PathFactory() @@ -3681,71 +4537,66 @@ def setUp(self): def test_updated_after_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({'updated_after': two_years_ago}) + response = self.get_path_list({"updated_after": two_years_ago}) self.assertEqual(response.json().get("count"), 2) def test_updated_after_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({'updated_after': in_two_years}) + response = self.get_path_list({"updated_after": in_two_years}) self.assertEqual(response.json().get("count"), 0) def test_updated_before_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({'updated_before': two_years_ago}) + response = self.get_path_list({"updated_before": two_years_ago}) self.assertEqual(response.json().get("count"), 0) def test_updated_before_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({'updated_before': in_two_years}) + response = self.get_path_list({"updated_before": in_two_years}) self.assertEqual(response.json().get("count"), 2) def test_created_after_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({'created_after': two_years_ago}) + response = self.get_path_list({"created_after": two_years_ago}) self.assertEqual(response.json().get("count"), 2) def test_created_after_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({'created_after': in_two_years}) + response = self.get_path_list({"created_after": in_two_years}) self.assertEqual(response.json().get("count"), 0) def test_created_before_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({'created_before': two_years_ago}) + response = self.get_path_list({"created_before": two_years_ago}) self.assertEqual(response.json().get("count"), 0) def test_created_before_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({'created_before': in_two_years}) + response = self.get_path_list({"created_before": in_two_years}) self.assertEqual(response.json().get("count"), 2) class RootSitesOnlyFilterTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.site_root1 = outdoor_factory.SiteFactory() cls.site_root2 = outdoor_factory.SiteFactory() - cls.site_child1 = outdoor_factory.SiteFactory( - parent=cls.site_root1 - ) - cls.site_child2 = outdoor_factory.SiteFactory( - parent=cls.site_child1 - ) + cls.site_child1 = outdoor_factory.SiteFactory(parent=cls.site_root1) + cls.site_child2 = outdoor_factory.SiteFactory(parent=cls.site_child1) def test_return_all_sites_with_no_filter(self): response = self.get_site_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 4) + self.assertEqual(response.json()["count"], 4) def test_root_sites_only_filter(self): - response = self.get_site_list({'root_sites_only': "true"}) + response = self.get_site_list({"root_sites_only": "true"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 2) + returned_sites = response.json()["results"] all_ids = [] for type in returned_sites: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertIn(self.site_root1.pk, all_ids) self.assertIn(self.site_root2.pk, all_ids) self.assertNotIn(self.site_child1.pk, all_ids) @@ -3753,7 +4604,6 @@ def test_root_sites_only_filter(self): class SitesTypesFilterTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.site1 = outdoor_factory.SiteFactory() @@ -3761,32 +4611,33 @@ def setUpTestData(cls): cls.site3 = outdoor_factory.SiteFactory() def test_sites_type_filter_1(self): - response = self.get_site_list({'types': self.site1.type.pk}) + response = self.get_site_list({"types": self.site1.type.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 1) + returned_sites = response.json()["results"] all_ids = [] for type in returned_sites: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) self.assertNotIn(self.site3.pk, all_ids) def test_sites_type_filter_2(self): - response = self.get_site_list({'types': f"{self.site2.type.pk},{self.site3.type.pk}"}) + response = self.get_site_list( + {"types": f"{self.site2.type.pk},{self.site3.type.pk}"} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 2) + returned_sites = response.json()["results"] all_ids = [] for type in returned_sites: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertNotIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) self.assertIn(self.site3.pk, all_ids) class SitesLabelsFilterTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.label_published = common_factory.LabelFactory(published=True) @@ -3798,80 +4649,91 @@ def setUpTestData(cls): cls.site3 = outdoor_factory.SiteFactory() def test_sites_label_filter_1(self): - response = self.get_site_list({'labels': self.label_published.pk}) + response = self.get_site_list({"labels": self.label_published.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 1) + returned_sites = response.json()["results"] all_ids = [] for type in returned_sites: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) self.assertNotIn(self.site3.pk, all_ids) def test_sites_label_filter_2(self): - response = self.get_site_list({'labels': f"{self.label_published.pk},{self.label_unpublished.pk}"}) + response = self.get_site_list( + {"labels": f"{self.label_published.pk},{self.label_unpublished.pk}"} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 2) + returned_sites = response.json()["results"] all_ids = [] for type in returned_sites: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) self.assertNotIn(self.site3.pk, all_ids) def test_sites_labels_exclude_filter(self): - response = self.get_site_list({'labels_exclude': self.label_published.pk}) + response = self.get_site_list({"labels_exclude": self.label_published.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 2) - self.assertSetEqual({result['id'] for result in json_response.get('results')}, - {self.site2.pk, self.site3.pk}) + self.assertEqual(len(json_response.get("results")), 2) + self.assertSetEqual( + {result["id"] for result in json_response.get("results")}, + {self.site2.pk, self.site3.pk}, + ) site_a = outdoor_factory.SiteFactory() label = common_factory.LabelFactory.create() site_a.labels.add(label, self.label_published) - response = self.get_site_list({'labels_exclude': self.label_published.pk}) + response = self.get_site_list({"labels_exclude": self.label_published.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 2) - self.assertSetEqual({result['id'] for result in json_response.get('results')}, - {self.site2.pk, self.site3.pk}) + self.assertEqual(len(json_response.get("results")), 2) + self.assertSetEqual( + {result["id"] for result in json_response.get("results")}, + {self.site2.pk, self.site3.pk}, + ) site_b = outdoor_factory.SiteFactory() label_2 = common_factory.LabelFactory.create() site_b.labels.add(label, label_2) - response = self.get_site_list({'labels_exclude': f'{self.label_published.pk},{label.pk}'}) + response = self.get_site_list( + {"labels_exclude": f"{self.label_published.pk},{label.pk}"} + ) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 2) - self.assertSetEqual({result['id'] for result in json_response.get('results')}, - {self.site2.pk, self.site3.pk}) + self.assertEqual(len(json_response.get("results")), 2) + self.assertSetEqual( + {result["id"] for result in json_response.get("results")}, + {self.site2.pk, self.site3.pk}, + ) - response = self.get_site_list({'labels_exclude': label_2.pk}) + response = self.get_site_list({"labels_exclude": label_2.pk}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get('results')), 4) - self.assertSetEqual({result['id'] for result in json_response.get('results')}, - {self.site1.pk, self.site2.pk, self.site3.pk, site_a.pk}) + self.assertEqual(len(json_response.get("results")), 4) + self.assertSetEqual( + {result["id"] for result in json_response.get("results")}, + {self.site1.pk, self.site2.pk, self.site3.pk, site_a.pk}, + ) def test_sites_label_filter_published(self): response = self.get_site_list() self.assertEqual(response.status_code, 200) - results = response.json()['results'] - all_labels = [result['labels'] for result in results] + results = response.json()["results"] + all_labels = [result["labels"] for result in results] self.assertIn([self.label_published.pk], all_labels) self.assertNotIn([self.label_unpublished.pk], all_labels) class CoursesTypesFilterTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.course1 = outdoor_factory.CourseFactory() @@ -3879,39 +4741,39 @@ def setUpTestData(cls): cls.course3 = outdoor_factory.CourseFactory() def test_courses_type_filter_1(self): - response = self.get_course_list({'types': self.course1.type.pk}) + response = self.get_course_list({"types": self.course1.type.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_courses = response.json()['results'] + self.assertEqual(response.json()["count"], 1) + returned_courses = response.json()["results"] all_ids = [] for type in returned_courses: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertIn(self.course1.pk, all_ids) self.assertNotIn(self.course2.pk, all_ids) self.assertNotIn(self.course3.pk, all_ids) def test_courses_type_filter_2(self): - response = self.get_course_list({'types': f"{self.course2.type.pk},{self.course3.type.pk}"}) + response = self.get_course_list( + {"types": f"{self.course2.type.pk},{self.course3.type.pk}"} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_courses = response.json()['results'] + self.assertEqual(response.json()["count"], 2) + returned_courses = response.json()["results"] all_ids = [] for type in returned_courses: - all_ids.append(type['id']) + all_ids.append(type["id"]) self.assertNotIn(self.course1.pk, all_ids) self.assertIn(self.course2.pk, all_ids) self.assertIn(self.course3.pk, all_ids) class TouristicContentTypeFilterTestCase(BaseApiTest): - @classmethod def setUpTestData(cls): cls.category1 = tourism_factory.TouristicContentCategoryFactory(label="POI") cls.category2 = tourism_factory.TouristicContentCategoryFactory(label="Food") cls.content_deleted = tourism_factory.TouristicContentFactory( - category=cls.category1, - deleted=True + category=cls.category1, deleted=True ) cls.content_not_published = tourism_factory.TouristicContentFactory( category=cls.category1, @@ -3937,15 +4799,17 @@ def setUpTestData(cls): published_en=True, ) - def assert_types_returned_in_first_category(self, response, content_in_list, content_not_in_list): + def assert_types_returned_in_first_category( + self, response, content_in_list, content_not_in_list + ): self.assertEqual(response.status_code, 200) self.assert_returned_types(1, response, content_in_list, content_not_in_list) self.assert_returned_types(2, response, content_in_list, content_not_in_list) def assert_returned_types(self, i, response, content_in_list, content_not_in_list): - returned_types = response.json()['results'][0]['types'][i - 1]['values'] + returned_types = response.json()["results"][0]["types"][i - 1]["values"] self.assertEqual(len(returned_types), len(content_in_list)) - all_ids = [type['id'] for type in returned_types] + all_ids = [type["id"] for type in returned_types] # type1 if i == 1: @@ -3963,31 +4827,59 @@ def assert_returned_types(self, i, response, content_in_list, content_not_in_lis def test_returned_published_not_deleted(self): response = self.get_touristiccontentcategory_list() types_in_list = [self.content_published_en, self.content_published_es_portal] - types_not_in_list = [self.content_deleted, self.content_not_published, self.content_cat2] - self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) + types_not_in_list = [ + self.content_deleted, + self.content_not_published, + self.content_cat2, + ] + self.assert_types_returned_in_first_category( + response, types_in_list, types_not_in_list + ) def test_returned_published_not_deleted_by_lang(self): - response = self.get_touristiccontentcategory_list({'language': 'en'}) + response = self.get_touristiccontentcategory_list({"language": "en"}) types_in_list = [self.content_published_en] - types_not_in_list = [self.content_deleted, self.content_not_published, self.content_published_es_portal, self.content_cat2] - self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) + types_not_in_list = [ + self.content_deleted, + self.content_not_published, + self.content_published_es_portal, + self.content_cat2, + ] + self.assert_types_returned_in_first_category( + response, types_in_list, types_not_in_list + ) def test_returned_published_not_deleted_by_portal(self): - response = self.get_touristiccontentcategory_list({'portals': self.portal.pk}) + response = self.get_touristiccontentcategory_list({"portals": self.portal.pk}) types_in_list = [self.content_published_es_portal] - types_not_in_list = [self.content_deleted, self.content_not_published, self.content_published_en, self.content_cat2] - self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) + types_not_in_list = [ + self.content_deleted, + self.content_not_published, + self.content_published_en, + self.content_cat2, + ] + self.assert_types_returned_in_first_category( + response, types_in_list, types_not_in_list + ) def test_returned_published_not_deleted_by_portal_and_lang(self): - response = self.get_touristiccontentcategory_list({'portals': self.portal.pk, 'language': 'es'}) + response = self.get_touristiccontentcategory_list( + {"portals": self.portal.pk, "language": "es"} + ) types_in_list = [self.content_published_es_portal] - types_not_in_list = [self.content_deleted, self.content_not_published, self.content_published_en, self.content_cat2] - self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) + types_not_in_list = [ + self.content_deleted, + self.content_not_published, + self.content_published_en, + self.content_cat2, + ] + self.assert_types_returned_in_first_category( + response, types_in_list, types_not_in_list + ) class SiteTypeFilterTestCase(BaseApiTest): - """ Test filtering depending on published, deleted content for outdoor site types - """ + """Test filtering depending on published, deleted content for outdoor site types""" @classmethod def setUpTestData(cls): @@ -3997,54 +4889,55 @@ def setUpTestData(cls): # Type with no published site -> don't send it cls.type_with_no_published_site = outdoor_factory.SiteTypeFactory() cls.not_published_site = outdoor_factory.SiteFactory( - published=False, - type=cls.type_with_no_published_site + published=False, type=cls.type_with_no_published_site ) # Type with published and not deleted site -> send it cls.type_with_published_and_not_deleted_site = outdoor_factory.SiteTypeFactory() cls.published_and_not_deleted_site = outdoor_factory.SiteFactory( - published_en=True, - type=cls.type_with_published_and_not_deleted_site + published_en=True, type=cls.type_with_published_and_not_deleted_site ) # Type with published_fr and not deleted site -> send it when language=fr - cls.type_with_published_and_not_deleted_site_with_lang = outdoor_factory.SiteTypeFactory() + cls.type_with_published_and_not_deleted_site_with_lang = ( + outdoor_factory.SiteTypeFactory() + ) cls.published_and_not_deleted_site_with_lang = outdoor_factory.SiteFactory( published_fr=True, - type=cls.type_with_published_and_not_deleted_site_with_lang + type=cls.type_with_published_and_not_deleted_site_with_lang, ) def test_sites_type_list_returns_published(self): - """ Assert API returns only types with published sites - """ + """Assert API returns only types with published sites""" response = self.get_sitetype_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 2) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) self.assertIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids + ) def test_sites_type_list_returns_published_in_language(self): - """ Assert API returns only published sites in specified language - """ - response = self.get_sitetype_list({'language': 'fr'}) + """Assert API returns only published sites in specified language""" + response = self.get_sitetype_list({"language": "fr"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) self.assertNotIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids + ) class SiteTypeFilterTestCaseByPortal(SiteTypeFilterTestCase): - """ Test filtering depending on portal for outdoor site types - """ + """Test filtering depending on portal for outdoor site types""" @classmethod def setUpTestData(cls): @@ -4073,43 +4966,44 @@ def setUpTestData(cls): cls.not_deleted_site_on_other_portal.portal.set([cls.other_portal]) def test_sites_type_list_returns_published(self): - """ Assert API returns only types with published site on portal - """ - response = self.get_sitetype_list({'portals': self.queried_portal.pk}) + """Assert API returns only types with published site on portal""" + response = self.get_sitetype_list({"portals": self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 0) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 0) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) # Didn't set portal on these ones yet self.assertNotIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertNotIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) + self.assertNotIn( + self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids + ) def test_sites_type_list_returns_published_2(self): - """ Assert API returns only types with published sites on portal - """ + """Assert API returns only types with published sites on portal""" # Type with published and not deleted site on portal -> send it self.published_and_not_deleted_site.portal.set([self.queried_portal]) # Type with published_fr and not deleted site on portal -> send it when language=fr self.published_and_not_deleted_site_with_lang.portal.set([self.queried_portal]) - response = self.get_sitetype_list({'portals': self.queried_portal.pk}) + response = self.get_sitetype_list({"portals": self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 2) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) # Portal is set this time self.assertIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids + ) class CourseTypeFilterTestCase(BaseApiTest): - """ Test filtering depending on published, deleted content for outdoor course types - """ + """Test filtering depending on published, deleted content for outdoor course types""" @classmethod def setUpTestData(cls): @@ -4119,60 +5013,65 @@ def setUpTestData(cls): # Type with no published course -> don't send it cls.type_with_no_published_course = outdoor_factory.CourseTypeFactory() cls.not_published_course = outdoor_factory.CourseFactory( - published=False, - type=cls.type_with_no_published_course + published=False, type=cls.type_with_no_published_course ) # Type with published and not deleted course -> send it - cls.type_with_published_and_not_deleted_course = outdoor_factory.CourseTypeFactory() + cls.type_with_published_and_not_deleted_course = ( + outdoor_factory.CourseTypeFactory() + ) cls.published_and_not_deleted_course = outdoor_factory.CourseFactory( - published_en=True, - type=cls.type_with_published_and_not_deleted_course + published_en=True, type=cls.type_with_published_and_not_deleted_course ) # Type with published_fr and not deleted course -> send it when language=fr - cls.type_with_published_and_not_deleted_course_with_lang = outdoor_factory.CourseTypeFactory() + cls.type_with_published_and_not_deleted_course_with_lang = ( + outdoor_factory.CourseTypeFactory() + ) cls.published_and_not_deleted_course_with_lang = outdoor_factory.CourseFactory( published_fr=True, - type=cls.type_with_published_and_not_deleted_course_with_lang + type=cls.type_with_published_and_not_deleted_course_with_lang, ) def test_course_type_list_returns_published(self): - """ Assert API returns only types with published course - """ + """Assert API returns only types with published course""" response = self.get_coursetype_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 2) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_course.pk, all_ids) self.assertNotIn(self.type_with_no_published_course.pk, all_ids) self.assertIn(self.type_with_published_and_not_deleted_course.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids + ) def test_course_type_list_returns_published_in_language(self): - """ Assert API returns only published course in specified language - """ - response = self.get_coursetype_list({'language': 'fr'}) + """Assert API returns only published course in specified language""" + response = self.get_coursetype_list({"language": "fr"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertNotIn(self.type_with_no_course.pk, all_ids) self.assertNotIn(self.type_with_no_published_course.pk, all_ids) self.assertNotIn(self.type_with_published_and_not_deleted_course.pk, all_ids) - self.assertIn(self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids) + self.assertIn( + self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids + ) class OutdoorFilterByRatingsTestCase(BaseApiTest): - """ Test filtering on ratings for outdoor course - """ + """Test filtering on ratings for outdoor course""" @classmethod def setUpTestData(cls): cls.site1 = outdoor_factory.SiteFactory() cls.site2 = outdoor_factory.SiteFactory() - cls.rating_scale = outdoor_factory.RatingScaleFactory(practice=cls.site1.practice) + cls.rating_scale = outdoor_factory.RatingScaleFactory( + practice=cls.site1.practice + ) cls.rating1 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.rating2 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.site1.ratings.set([cls.rating1]) @@ -4183,64 +5082,67 @@ def setUpTestData(cls): cls.course2.ratings.set([cls.rating2]) def test_site_list_ratings_filter(self): - response = self.get_site_list({'ratings': self.rating1.pk}) + response = self.get_site_list({"ratings": self.rating1.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 1) + returned_sites = response.json()["results"] all_ids = [] for site in returned_sites: - all_ids.append(site['id']) + all_ids.append(site["id"]) self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) def test_site_list_ratings_filter2(self): - response = self.get_site_list({'ratings': self.rating2.pk}) + response = self.get_site_list({"ratings": self.rating2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 1) + returned_sites = response.json()["results"] all_ids = [] for site in returned_sites: - all_ids.append(site['id']) + all_ids.append(site["id"]) self.assertIn(self.site2.pk, all_ids) self.assertNotIn(self.site1.pk, all_ids) def test_site_list_ratings_filter3(self): - response = self.get_site_list({'ratings': f"{self.rating1.pk},{self.rating2.pk}"}) + response = self.get_site_list( + {"ratings": f"{self.rating1.pk},{self.rating2.pk}"} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 2) + returned_sites = response.json()["results"] all_ids = [] for site in returned_sites: - all_ids.append(site['id']) + all_ids.append(site["id"]) self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) def test_course_list_ratings_filter(self): - response = self.get_course_list({'ratings': f"{self.rating1.pk},{self.rating2.pk}"}) + response = self.get_course_list( + {"ratings": f"{self.rating1.pk},{self.rating2.pk}"} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 2) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 2) + returned_sites = response.json()["results"] all_ids = [] for site in returned_sites: - all_ids.append(site['id']) + all_ids.append(site["id"]) self.assertIn(self.course1.pk, all_ids) self.assertIn(self.course2.pk, all_ids) def test_course_list_ratings_filter2(self): - response = self.get_course_list({'ratings': self.rating2.pk}) + response = self.get_course_list({"ratings": self.rating2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_sites = response.json()['results'] + self.assertEqual(response.json()["count"], 1) + returned_sites = response.json()["results"] all_ids = [] for site in returned_sites: - all_ids.append(site['id']) + all_ids.append(site["id"]) self.assertNotIn(self.course1.pk, all_ids) self.assertIn(self.course2.pk, all_ids) class OutdoorFilterBySuperPracticesTestCase(BaseApiTest): - """ Test APIV2 filtering on ratings on sites - """ + """Test APIV2 filtering on ratings on sites""" @classmethod def setUpTestData(cls): @@ -4250,16 +5152,22 @@ def setUpTestData(cls): cls.practice3 = outdoor_factory.PracticeFactory() cls.practice4 = outdoor_factory.PracticeFactory() cls.site1 = outdoor_factory.SiteFactory(practice=cls.practice1) - cls.site2 = outdoor_factory.SiteFactory(practice=cls.practice2, parent=cls.site1) - cls.site3 = outdoor_factory.SiteFactory(practice=cls.practice3, parent=cls.site2) - cls.site4 = outdoor_factory.SiteFactory(practice=cls.practice4, parent=cls.site2) + cls.site2 = outdoor_factory.SiteFactory( + practice=cls.practice2, parent=cls.site1 + ) + cls.site3 = outdoor_factory.SiteFactory( + practice=cls.practice3, parent=cls.site2 + ) + cls.site4 = outdoor_factory.SiteFactory( + practice=cls.practice4, parent=cls.site2 + ) def test_filter_practice_in_tree_hierarchy(self): - response = self.get_site_list({'practices_in_hierarchy': self.practice1.pk}) + response = self.get_site_list({"practices_in_hierarchy": self.practice1.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) @@ -4267,11 +5175,11 @@ def test_filter_practice_in_tree_hierarchy(self): self.assertNotIn(self.site4.pk, all_ids) def test_filter_practice_in_tree_hierarchy2(self): - response = self.get_site_list({'practices_in_hierarchy': self.practice3.pk}) + response = self.get_site_list({"practices_in_hierarchy": self.practice3.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 3) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 3) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) @@ -4280,13 +5188,14 @@ def test_filter_practice_in_tree_hierarchy2(self): class OutdoorFilterBySuperRatingsTestCase(BaseApiTest): - """ Test APIV2 filtering on ratings on sites in hierarchy - """ + """Test APIV2 filtering on ratings on sites in hierarchy""" @classmethod def setUpTestData(cls): cls.site1 = outdoor_factory.SiteFactory() - cls.rating_scale = outdoor_factory.RatingScaleFactory(practice=cls.site1.practice) + cls.rating_scale = outdoor_factory.RatingScaleFactory( + practice=cls.site1.practice + ) cls.rating1 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.rating2 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.rating3 = outdoor_factory.RatingFactory(scale=cls.rating_scale) @@ -4300,11 +5209,11 @@ def setUpTestData(cls): cls.site4.ratings.set([cls.rating4]) def test_filter_ratings_in_tree_hierarchy(self): - response = self.get_site_list({'ratings_in_hierarchy': self.rating1.pk}) + response = self.get_site_list({"ratings_in_hierarchy": self.rating1.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) @@ -4312,11 +5221,11 @@ def test_filter_ratings_in_tree_hierarchy(self): self.assertNotIn(self.site4.pk, all_ids) def test_filter_ratings_in_tree_hierarchy2(self): - response = self.get_site_list({'ratings_in_hierarchy': self.rating3.pk}) + response = self.get_site_list({"ratings_in_hierarchy": self.rating3.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 3) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 3) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) @@ -4324,11 +5233,13 @@ def test_filter_ratings_in_tree_hierarchy2(self): self.assertNotIn(self.site4.pk, all_ids) def test_filter_ratings_in_tree_hierarchy3(self): - response = self.get_site_list({'ratings_in_hierarchy': f"{self.rating3.pk}, {self.rating4.pk}"}) + response = self.get_site_list( + {"ratings_in_hierarchy": f"{self.rating3.pk}, {self.rating4.pk}"} + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 4) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 4) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) @@ -4337,36 +5248,56 @@ def test_filter_ratings_in_tree_hierarchy3(self): class OutdoorSiteHierarchySerializingTestCase(BaseApiTest): - """ Test APIV2 serialzing of parents and children in site detail - """ + """Test APIV2 serialzing of parents and children in site detail""" @classmethod def setUpTestData(cls): cls.site_root = outdoor_factory.SiteFactory(published=True) - cls.site_node = outdoor_factory.SiteFactory(published=True, parent=cls.site_root) - cls.site_leaf_published = outdoor_factory.SiteFactory(published=True, parent=cls.site_node) - cls.site_leaf_published_2 = outdoor_factory.SiteFactory(published=True, parent=cls.site_node) - cls.site_leaf_unpublished = outdoor_factory.SiteFactory(published=False, parent=cls.site_node) + cls.site_node = outdoor_factory.SiteFactory( + published=True, parent=cls.site_root + ) + cls.site_leaf_published = outdoor_factory.SiteFactory( + published=True, parent=cls.site_node + ) + cls.site_leaf_published_2 = outdoor_factory.SiteFactory( + published=True, parent=cls.site_node + ) + cls.site_leaf_unpublished = outdoor_factory.SiteFactory( + published=False, parent=cls.site_node + ) cls.site_root_unpublished = outdoor_factory.SiteFactory(published=False) - cls.site_node_parent_unpublished = outdoor_factory.SiteFactory(published=True, parent=cls.site_root_unpublished) + cls.site_node_parent_unpublished = outdoor_factory.SiteFactory( + published=True, parent=cls.site_root_unpublished + ) cls.site_root_fr = outdoor_factory.SiteFactory(published_fr=True) - cls.site_node_fr = outdoor_factory.SiteFactory(published_fr=True, parent=cls.site_root_fr) - cls.site_leaf_published_fr = outdoor_factory.SiteFactory(published_fr=True, parent=cls.site_node_fr) - cls.site_leaf_published_not_fr = outdoor_factory.SiteFactory(published=True, published_fr=False, published_en=True, parent=cls.site_node_fr) - cls.site_leaf_unpublished_fr = outdoor_factory.SiteFactory(published_fr=False, parent=cls.site_node_fr) + cls.site_node_fr = outdoor_factory.SiteFactory( + published_fr=True, parent=cls.site_root_fr + ) + cls.site_leaf_published_fr = outdoor_factory.SiteFactory( + published_fr=True, parent=cls.site_node_fr + ) + cls.site_leaf_published_not_fr = outdoor_factory.SiteFactory( + published=True, + published_fr=False, + published_en=True, + parent=cls.site_node_fr, + ) + cls.site_leaf_unpublished_fr = outdoor_factory.SiteFactory( + published_fr=False, parent=cls.site_node_fr + ) def test_site_parent_published_serializing(self): response = self.get_site_detail(self.site_node.pk) self.assertEqual(response.status_code, 200) - parent = response.json()['parent'] + parent = response.json()["parent"] self.assertEqual(parent, self.site_root.pk) def test_site_children_published_serializing(self): response = self.get_site_detail(self.site_node.pk) self.assertEqual(response.status_code, 200) - children = response.json()['children'] + children = response.json()["children"] self.assertEqual(2, len(children)) self.assertIn(self.site_leaf_published.pk, children) self.assertIn(self.site_leaf_published_2.pk, children) @@ -4375,28 +5306,30 @@ def test_site_children_published_serializing(self): def test_site_parent_unpublished_serializing(self): response = self.get_site_detail(self.site_node_parent_unpublished.pk) self.assertEqual(response.status_code, 200) - parent = response.json()['parent'] + parent = response.json()["parent"] self.assertEqual(parent, None) self.assertIsNotNone(self.site_node_parent_unpublished.parent) def test_site_parent_and_children_serializing_by_lang(self): - response = self.get_site_list({'language': 'fr'}) + response = self.get_site_list({"language": "fr"}) self.assertEqual(response.status_code, 200) - returned_sites = response.json()['results'] - site_published_fr = next((site for site in returned_sites if site['id'] == self.site_node_fr.pk), None) + returned_sites = response.json()["results"] + site_published_fr = next( + (site for site in returned_sites if site["id"] == self.site_node_fr.pk), + None, + ) self.assertIsNotNone(site_published_fr) - children = site_published_fr['children'] + children = site_published_fr["children"] self.assertEqual(1, len(children)) self.assertIn(self.site_leaf_published_fr.pk, children) self.assertNotIn(self.site_leaf_published_not_fr.pk, children) self.assertNotIn(self.site_leaf_unpublished_fr.pk, children) - parent = site_published_fr['parent'] + parent = site_published_fr["parent"] self.assertEqual(parent, self.site_root_fr.pk) class OutdoorFilterByPracticesTestCase(BaseApiTest): - """ Test APIV2 filtering by practices on courses - """ + """Test APIV2 filtering by practices on courses""" @classmethod def setUpTestData(cls): @@ -4405,7 +5338,9 @@ def setUpTestData(cls): cls.course_practice = outdoor_factory.CourseFactory() cls.course_practice.parent_sites.set([cls.site_practice]) cls.other_practice = outdoor_factory.PracticeFactory() - cls.site_other_practice = outdoor_factory.SiteFactory(practice=cls.other_practice) + cls.site_other_practice = outdoor_factory.SiteFactory( + practice=cls.other_practice + ) cls.course_other_practice = outdoor_factory.CourseFactory() cls.course_other_practice.parent_sites.set([cls.site_other_practice]) @@ -4414,23 +5349,25 @@ def setUpTestData(cls): cls.course_site_no_practice.parent_sites.set([cls.site_no_practice]) def test_filter_practices_on_courses(self): - response = self.get_course_list({'practices': self.practice.pk}) + response = self.get_course_list({"practices": self.practice.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.course_practice.pk, all_ids) self.assertNotIn(self.course_site_no_practice.pk, all_ids) self.assertNotIn(self.course_other_practice.pk, all_ids) def test_filter_practices_on_courses2(self): - self.course_practice.parent_sites.set([self.site_practice, self.site_other_practice]) - response = self.get_course_list({'practices': self.practice.pk}) + self.course_practice.parent_sites.set( + [self.site_practice, self.site_other_practice] + ) + response = self.get_course_list({"practices": self.practice.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.course_practice.pk, all_ids) self.assertNotIn(self.course_site_no_practice.pk, all_ids) @@ -4438,8 +5375,7 @@ def test_filter_practices_on_courses2(self): class OutdoorFilterByPortal(BaseApiTest): - """ Test APIV2 filtering on ratings on sites in hierarchy - """ + """Test APIV2 filtering on ratings on sites in hierarchy""" @classmethod def setUpTestData(cls): @@ -4455,21 +5391,21 @@ def setUpTestData(cls): cls.site.information_desks.set([cls.information_desk]) def test_filter_courses_by_portal(self): - response = self.get_course_list({'portals': self.portal.pk}) + response = self.get_course_list({"portals": self.portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.course.pk, all_ids) self.assertNotIn(self.course2.pk, all_ids) def test_filter_courses_by_themes(self): - response = self.get_course_list({'themes': self.theme.pk}) + response = self.get_course_list({"themes": self.theme.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.course.pk, all_ids) self.assertNotIn(self.course2.pk, all_ids) @@ -4477,80 +5413,109 @@ def test_filter_courses_by_themes(self): def test_filter_info_desks_by_portal_and_outdoor(self): response = self.get_informationdesk_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()['count'], 1) - returned_types = response.json()['results'] - all_ids = [type['id'] for type in returned_types] + self.assertEqual(response.json()["count"], 1) + returned_types = response.json()["results"] + all_ids = [type["id"] for type in returned_types] self.assertIn(self.information_desk.pk, all_ids) class AltimetryCacheTests(BaseApiTest): - """ Test APIV2 DEM serialization is cached """ + """Test APIV2 DEM serialization is cached""" + @classmethod def setUpTestData(cls): # Create a simple fake DEM with connection.cursor() as cur: - cur.execute('INSERT INTO altimetry_dem (rast) VALUES (ST_MakeEmptyRaster(100, 125, 0, 125, 25, -25, 0, 0, %s))', [settings.SRID]) - cur.execute('UPDATE altimetry_dem SET rast = ST_AddBand(rast, \'16BSI\')') - demvalues = [[0, 0, 3, 5], [2, 2, 10, 15], [5, 15, 20, 25], [20, 25, 30, 35], [30, 35, 40, 45]] + cur.execute( + "INSERT INTO altimetry_dem (rast) VALUES (ST_MakeEmptyRaster(100, 125, 0, 125, 25, -25, 0, 0, %s))", + [settings.SRID], + ) + cur.execute("UPDATE altimetry_dem SET rast = ST_AddBand(rast, '16BSI')") + demvalues = [ + [0, 0, 3, 5], + [2, 2, 10, 15], + [5, 15, 20, 25], + [20, 25, 30, 35], + [30, 35, 40, 45], + ] for y in range(0, 5): for x in range(0, 4): - cur.execute('UPDATE altimetry_dem SET rast = ST_SetValue(rast, %s, %s, %s::float)', [x + 1, y + 1, demvalues[y][x]]) - cls.path = core_factory.PathFactory.create(geom=LineString((1, 101), (81, 101), (81, 99))) + cur.execute( + "UPDATE altimetry_dem SET rast = ST_SetValue(rast, %s, %s, %s::float)", + [x + 1, y + 1, demvalues[y][x]], + ) + cls.path = core_factory.PathFactory.create( + geom=LineString((1, 101), (81, 101), (81, 99)) + ) cls.trek = trek_factory.TrekFactory.create(paths=[cls.path]) - @skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only') + @skipIf( + not settings.TREKKING_TOPOLOGY_ENABLED, "Test with dynamic segmentation only" + ) def test_cache_is_used_when_getting_trek_DEM(self): # There are 9 queries to get trek DEM with self.assertNumQueries(10): - response = self.client.get(reverse('apiv2:trek-dem', args=(self.trek.pk,))) + response = self.client.get(reverse("apiv2:trek-dem", args=(self.trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response['Content-Type'], 'application/json') + self.assertEqual(response["Content-Type"], "application/json") # When cache is used there is single query to get trek DEM with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:trek-dem', args=(self.trek.pk,))) + response = self.client.get(reverse("apiv2:trek-dem", args=(self.trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response['Content-Type'], 'application/json') + self.assertEqual(response["Content-Type"], "application/json") - @skipIf(settings.TREKKING_TOPOLOGY_ENABLED, 'Test without dynamic segmentation only') + @skipIf( + settings.TREKKING_TOPOLOGY_ENABLED, "Test without dynamic segmentation only" + ) def test_cache_is_used_when_getting_trek_DEM_nds(self): - trek = trek_factory.TrekFactory.create(geom=LineString((1, 101), (81, 101), (81, 99))) + trek = trek_factory.TrekFactory.create( + geom=LineString((1, 101), (81, 101), (81, 99)) + ) # There are 9 queries to get trek DEM with self.assertNumQueries(10): - response = self.client.get(reverse('apiv2:trek-dem', args=(trek.pk,))) + response = self.client.get(reverse("apiv2:trek-dem", args=(trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response['Content-Type'], 'application/json') + self.assertEqual(response["Content-Type"], "application/json") # When cache is used there is single query to get trek DEM with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:trek-dem', args=(trek.pk,))) + response = self.client.get(reverse("apiv2:trek-dem", args=(trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response['Content-Type'], 'application/json') + self.assertEqual(response["Content-Type"], "application/json") def test_cache_is_used_when_getting_trek_profile(self): # There are 8 queries to get trek profile with self.assertNumQueries(10): - response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,))) + response = self.client.get( + reverse("apiv2:trek-profile", args=(self.trek.pk,)) + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response['Content-Type'], 'application/json') + self.assertEqual(response["Content-Type"], "application/json") self.assertIn("profile", response.json().keys()) # When cache is used there is single query to get trek profile with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,))) + response = self.client.get( + reverse("apiv2:trek-profile", args=(self.trek.pk,)) + ) self.assertEqual(response.status_code, 200) - self.assertEqual(response['Content-Type'], 'application/json') + self.assertEqual(response["Content-Type"], "application/json") self.assertIn("profile", response.json().keys()) def test_cache_is_used_when_getting_trek_profile_svg(self): # There are 8 queries to get trek profile svg with self.assertNumQueries(10): - response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,)), {"format": "svg"}) + response = self.client.get( + reverse("apiv2:trek-profile", args=(self.trek.pk,)), {"format": "svg"} + ) self.assertEqual(response.status_code, 200) - self.assertIn('image/svg+xml', response['Content-Type']) + self.assertIn("image/svg+xml", response["Content-Type"]) # When cache is used there is single query to get trek profile with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,)), {"format": "svg"}) + response = self.client.get( + reverse("apiv2:trek-profile", args=(self.trek.pk,)), {"format": "svg"} + ) self.assertEqual(response.status_code, 200) - self.assertIn('image/svg+xml', response['Content-Type']) + self.assertIn("image/svg+xml", response["Content-Type"]) class GenericCacheTestCase(APITestCase): @@ -4560,32 +5525,42 @@ def setUpTestData(cls): def test_cache_invalidates_along_x_forwarded_proto_header(self): with self.assertNumQueries(2): - response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,))) + response = self.client.get( + reverse("apiv2:practice-detail", args=(self.practice.pk,)) + ) data = response.json() - self.assertTrue(data['pictogram'].startswith('http://')) + self.assertTrue(data["pictogram"].startswith("http://")) # after cache hit, query number is 1 with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,))) + response = self.client.get( + reverse("apiv2:practice-detail", args=(self.practice.pk,)) + ) data = response.json() - self.assertTrue(data['pictogram'].startswith('http://')) + self.assertTrue(data["pictogram"].startswith("http://")) # we used custom header, cache is invalidate and url is now https with self.assertNumQueries(2): - response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,)), - HTTP_X_FORWARDED_PROTO='https') + response = self.client.get( + reverse("apiv2:practice-detail", args=(self.practice.pk,)), + HTTP_X_FORWARDED_PROTO="https", + ) data = response.json() - self.assertTrue(data['pictogram'].startswith('https://')) + self.assertTrue(data["pictogram"].startswith("https://")) # cache is hit with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,)), - HTTP_X_FORWARDED_PROTO='https') + response = self.client.get( + reverse("apiv2:practice-detail", args=(self.practice.pk,)), + HTTP_X_FORWARDED_PROTO="https", + ) data = response.json() - self.assertTrue(data['pictogram'].startswith('https://')) + self.assertTrue(data["pictogram"].startswith("https://")) # first request is always cached with self.assertNumQueries(1): - response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,))) + response = self.client.get( + reverse("apiv2:practice-detail", args=(self.practice.pk,)) + ) data = response.json() - self.assertTrue(data['pictogram'].startswith('http://')) + self.assertTrue(data["pictogram"].startswith("http://")) From 229438fb3b4aa7a75c08f5adff88add261360a76 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Tue, 19 Sep 2023 14:13:49 +0200 Subject: [PATCH 34/43] test sensitivity openair buffer on points --- geotrek/sensitivity/tests/test_models.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/geotrek/sensitivity/tests/test_models.py b/geotrek/sensitivity/tests/test_models.py index 63b3bcea15..f30b6dde88 100644 --- a/geotrek/sensitivity/tests/test_models.py +++ b/geotrek/sensitivity/tests/test_models.py @@ -98,6 +98,29 @@ def test_get_openair_data(self): sensitive_area.openair(), ) + @override_settings( + SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ + "Practice1", + ] + ) + @freeze_time("2020-01-01") + def test_get_openair_point_data(self): + species = SpeciesFactory.create(radius=300) + sensitive_area = SensitiveAreaFactory.create(geom="POINT(700000 6600000)", species=species) + self.assertEqual( + "AC ZSM\n" + "AN Species\n" + f"*AUID GUId=! UId=! Id=(Identifiant-GeoTrek-sentivity) {sensitive_area.pk}\n" + "*ADescr Species (published on 01/01/2020)\n" + '*ATimes {"6": ["UTC(01/06->30/06)", "ANY(00:00->23:59)"],"7": ["UTC(01/07->31/07)", "ANY(00:00->23:59)"]}\n' + "AH 985FT AGL\n" + "DP 46:29:59 N 03:00:14 E\n" + "DP 46:29:50 N 03:00:00 E\n" + "DP 46:29:59 N 02:59:45 E\n" + "DP 46:30:09 N 03:00:00 E", + sensitive_area.openair(), + ) + @override_settings( SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ "Practice1", From 104ee6dfbf2f51e0003172ee970e13fa91030f52 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Wed, 20 Sep 2023 12:15:05 +0200 Subject: [PATCH 35/43] WIP tests no pagination --- geotrek/api/tests/test_v2.py | 4633 ++++++++++++++-------------------- 1 file changed, 1854 insertions(+), 2779 deletions(-) diff --git a/geotrek/api/tests/test_v2.py b/geotrek/api/tests/test_v2.py index a1cb9b3e28..cc8e22299f 100644 --- a/geotrek/api/tests/test_v2.py +++ b/geotrek/api/tests/test_v2.py @@ -5,16 +5,11 @@ from dateutil.relativedelta import relativedelta from django.conf import settings from django.contrib.contenttypes.models import ContentType -from django.contrib.gis.geos import ( - LineString, - MultiLineString, - MultiPoint, - Point, - Polygon, -) +from django.contrib.gis.geos import (LineString, MultiLineString, MultiPoint, + Point, Polygon) from django.contrib.gis.geos.collections import GeometryCollection from django.db import connection -from django.test.testcases import TestCase +from django.test import TestCase, RequestFactory from django.test.utils import override_settings from django.urls import reverse from django.utils import timezone @@ -23,15 +18,14 @@ from rest_framework.test import APITestCase from geotrek import __version__ +from geotrek.api.v2.views.trekking import TrekViewSet from geotrek.authent import models as authent_models from geotrek.authent.tests import factories as authent_factory from geotrek.common import models as common_models from geotrek.common.tests import factories as common_factory -from geotrek.common.utils.testdata import ( - get_dummy_uploaded_document, - get_dummy_uploaded_file, - get_dummy_uploaded_image, -) +from geotrek.common.utils.testdata import (get_dummy_uploaded_document, + get_dummy_uploaded_file, + get_dummy_uploaded_image) from geotrek.core import models as path_models from geotrek.core.tests import factories as core_factory from geotrek.feedback.tests import factories as feedback_factory @@ -54,527 +48,237 @@ from mapentity.middleware import clear_internal_user_cache -PAGINATED_JSON_STRUCTURE = sorted( - [ - "count", - "next", - "previous", - "results", - ] -) - -PAGINATED_GEOJSON_STRUCTURE = sorted(["count", "next", "previous", "features", "type"]) - -GEOJSON_COLLECTION_STRUCTURE = sorted(["type", "features"]) - -GEOJSON_STRUCTURE = sorted(["geometry", "type", "bbox", "properties"]) - -TREK_PROPERTIES_GEOJSON_STRUCTURE = sorted( - [ - "id", - "access", - "accessibilities", - "accessibility_advice", - "accessibility_covering", - "accessibility_exposure", - "accessibility_level", - "accessibility_signage", - "accessibility_slope", - "accessibility_width", - "advice", - "advised_parking", - "altimetric_profile", - "ambiance", - "arrival", - "ascent", - "attachments", - "attachments_accessibility", - "children", - "cities", - "create_datetime", - "departure", - "departure_geom", - "descent", - "description", - "description_teaser", - "difficulty", - "departure_city", - "disabled_infrastructure", - "districts", - "duration", - "elevation_area_url", - "elevation_svg_url", - "gear", - "external_id", - "gpx", - "information_desks", - "kml", - "labels", - "length_2d", - "length_3d", - "max_elevation", - "min_elevation", - "name", - "networks", - "next", - "parents", - "parking_location", - "pdf", - "points_reference", - "portal", - "practice", - "previous", - "public_transport", - "provider", - "published", - "ratings", - "ratings_description", - "reservation_system", - "reservation_id", - "route", - "second_external_id", - "source", - "structure", - "themes", - "update_datetime", - "url", - "uuid", - "view_points", - "web_links", - ] -) - -PATH_PROPERTIES_GEOJSON_STRUCTURE = sorted( - [ - "arrival", - "comfort", - "comments", - "departure", - "length_2d", - "length_3d", - "name", - "networks", - "provider", - "source", - "stake", - "url", - "usages", - "uuid", - ] -) - -TOUR_PROPERTIES_GEOJSON_STRUCTURE = sorted( - TREK_PROPERTIES_GEOJSON_STRUCTURE + ["count_children", "steps"] -) - -POI_PROPERTIES_GEOJSON_STRUCTURE = sorted( - [ - "id", - "create_datetime", - "description", - "external_id", - "name", - "attachments", - "published", - "provider", - "type", - "type_label", - "type_pictogram", - "update_datetime", - "url", - "uuid", - "view_points", - ] -) - -LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "pictogram"]) - -TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE = sorted( - ["id", "label", "order", "pictogram", "types"] -) - -TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE = sorted( - [ - "accessibility", - "approved", - "attachments", - "category", - "cities", - "contact", - "create_datetime", - "description", - "description_teaser", - "departure_city", - "districts", - "email", - "external_id", - "geometry", - "id", - "label_accessibility", - "name", - "pdf", - "portal", - "practical_info", - "provider", - "published", - "reservation_id", - "reservation_system", - "source", - "structure", - "themes", - "types", - "update_datetime", - "url", - "uuid", - "website", - ] -) - -CITY_PROPERTIES_JSON_STRUCTURE = sorted(["id", "geometry", "name", "published"]) - -DISTRICT_PROPERTIES_JSON_STRUCTURE = sorted(["id", "geometry", "name", "published"]) - -ROUTE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "route", "pictogram"]) - -THEME_PROPERTIES_JSON_STRUCTURE = sorted(["id", "label", "pictogram"]) - -ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "pictogram"]) - -ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) - -TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE = sorted( - [ - "id", - "name", - "website", - "title", - "description", - "facebook_id", - "facebook_image_url", - "facebook_image_height", - "facebook_image_width", - ] -) - -STRUCTURE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) - -TREK_LABEL_PROPERTIES_JSON_STRUCTURE = sorted( - ["id", "advice", "filter", "name", "pictogram"] -) - -FILETYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "structure", "type"]) - -INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "label", "pictogram"]) - -INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE = sorted( - [ - "id", - "accessibility", - "description", - "email", - "label_accessibility", - "latitude", - "longitude", - "municipality", - "name", - "phone", - "photo_url", - "provider", - "uuid", - "postal_code", - "street", - "type", - "website", - ] -) - -SOURCE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "pictogram", "website"]) - -RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE = sorted(["name", "id"]) - -SITE_PROPERTIES_JSON_STRUCTURE = sorted( - [ - "accessibility", - "advice", - "ambiance", - "attachments", - "children", - "cities", - "courses", - "description", - "description_teaser", - "districts", - "eid", - "geometry", - "id", - "information_desks", - "labels", - "managers", - "name", - "orientation", - "parent", - "period", - "portal", - "practice", - "provider", - "pdf", - "ratings", - "sector", - "source", - "structure", - "themes", - "type", - "url", - "uuid", - "view_points", - "wind", - "web_links", - ] -) - -OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE = sorted( - ["id", "name", "sector", "pictogram"] -) - -OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) - -SITETYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "practice"]) - -SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE = sorted( - [ - "id", - "contact", - "create_datetime", - "description", - "elevation", - "geometry", - "info_url", - "kml_url", - "openair_url", - "name", - "period", - "practices", - "provider", - "published", - "species_id", - "structure", - "update_datetime", - "url", - "attachments", - "rules", - ] -) - -SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE = sorted( - [ - "id", - "name", - "period01", - "period02", - "period03", - "period04", - "period05", - "period06", - "period07", - "period08", - "period09", - "period10", - "period11", - "period12", - "practices", - "radius", - "url", - ] -) - -COURSE_PROPERTIES_JSON_STRUCTURE = sorted( - [ - "accessibility", - "advice", - "cities", - "description", - "districts", - "eid", - "equipment", - "geometry", - "height", - "id", - "length", - "name", - "ratings", - "ratings_description", - "sites", - "structure", - "type", - "url", - "attachments", - "max_elevation", - "min_elevation", - "parents", - "provider", - "pdf", - "points_reference", - "children", - "duration", - "gear", - "uuid", - ] -) - -COURSETYPE_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name", "practice"]) - -ORGANISM_PROPERTIES_JSON_STRUCTURE = sorted(["id", "name"]) - -SERVICE_DETAIL_JSON_STRUCTURE = sorted( - ["id", "eid", "geometry", "provider", "structure", "type", "uuid"] -) - -SERVICE_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "name", "practices", "pictogram"]) - -INFRASTRUCTURE_DETAIL_JSON_STRUCTURE = sorted( - [ - "id", - "accessibility", - "attachments", - "condition", - "description", - "eid", - "geometry", - "implantation_year", - "maintenance_difficulty", - "name", - "provider", - "structure", - "type", - "usage_difficulty", - "uuid", - ] -) - -INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE = sorted( - ["id", "label", "pictogram", "structure", "type"] -) - -INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "structure"]) - -INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted( - ["id", "label", "structure"] -) - -INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted( - ["id", "label", "structure"] -) - -TOURISTIC_EVENT_DETAIL_JSON_STRUCTURE = sorted( - [ - "id", - "accessibility", - "approved", - "attachments", - "begin_date", - "bookable", - "booking", - "cities", - "contact", - "create_datetime", - "description", - "description_teaser", - "districts", - "duration", - "email", - "end_date", - "external_id", - "geometry", - "meeting_point", - "start_time", - "meeting_time", - "end_time", - "name", - "organizer", - "capacity", - "pdf", - "place", - "portal", - "practical_info", - "provider", - "published", - "source", - "speaker", - "structure", - "target_audience", - "themes", - "type", - "update_datetime", - "url", - "uuid", - "website", - "cancelled", - "cancellation_reason", - "participant_number", - ] -) - -TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE = sorted(["id", "name", "geometry"]) - -TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE = sorted(["id", "label"]) - -TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "pictogram", "type"]) - -SIGNAGE_DETAIL_JSON_STRUCTURE = sorted( - [ - "id", - "attachments", - "blades", - "code", - "condition", - "description", - "eid", - "geometry", - "implantation_year", - "name", - "printed_elevation", - "sealing", - "provider", - "structure", - "type", - "uuid", - ] -) - -SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "pictogram", "structure"]) - -SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE = sorted(["id", "label"]) - -SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE = sorted(["id", "label"]) - -SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "structure"]) - -SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE = sorted(["id", "label", "structure"]) - -HDVIEWPOINT_DETAIL_JSON_STRUCTURE = sorted( - [ - "id", - "annotations", - "author", - "create_datetime", - "geometry", - "legend", - "license", - "metadata_url", - "picture_tiles_url", - "poi", - "site", - "title", - "trek", - "thumbnail_url", - "update_datetime", - "uuid", - ] -) +PAGINATED_JSON_STRUCTURE = sorted([ + 'count', 'next', 'previous', 'results', +]) + +PAGINATED_GEOJSON_STRUCTURE = sorted([ + 'count', 'next', 'previous', 'features', 'type' +]) + +GEOJSON_COLLECTION_STRUCTURE = sorted([ + 'features', 'type', +]) + +GEOJSON_STRUCTURE = sorted([ + 'geometry', + 'type', + 'bbox', + 'properties' +]) + +TREK_PROPERTIES_GEOJSON_STRUCTURE = sorted([ + 'id', 'access', 'accessibilities', 'accessibility_advice', 'accessibility_covering', + 'accessibility_exposure', 'accessibility_level', 'accessibility_signage', 'accessibility_slope', + 'accessibility_width', 'advice', 'advised_parking', 'altimetric_profile', 'ambiance', 'arrival', 'ascent', + 'attachments', 'attachments_accessibility', 'children', 'cities', 'create_datetime', 'departure', 'departure_geom', + 'descent', 'description', 'description_teaser', 'difficulty', 'departure_city', + 'disabled_infrastructure', 'districts', 'duration', 'elevation_area_url', 'elevation_svg_url', 'gear', + 'external_id', 'gpx', 'information_desks', 'kml', 'labels', 'length_2d', + 'length_3d', 'max_elevation', 'min_elevation', 'name', 'networks', + 'next', 'parents', 'parking_location', 'pdf', 'points_reference', + 'portal', 'practice', 'previous', 'public_transport', 'provider', 'published', 'ratings', 'ratings_description', + 'reservation_system', 'reservation_id', 'route', 'second_external_id', 'source', 'structure', + 'themes', 'update_datetime', 'url', 'uuid', 'view_points', 'web_links' +]) + +PATH_PROPERTIES_GEOJSON_STRUCTURE = sorted([ + 'arrival', 'comfort', 'comments', 'departure', 'length_2d', 'length_3d', 'name', + 'networks', 'provider', 'source', 'stake', 'url', 'usages', 'uuid']) + +TOUR_PROPERTIES_GEOJSON_STRUCTURE = sorted(TREK_PROPERTIES_GEOJSON_STRUCTURE + ['count_children', 'steps']) + +POI_PROPERTIES_GEOJSON_STRUCTURE = sorted([ + 'id', 'create_datetime', 'description', 'external_id', + 'name', 'attachments', 'published', 'provider', 'type', 'type_label', 'type_pictogram', + 'update_datetime', 'url', 'uuid', 'view_points' +]) + +LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'pictogram' +]) + +TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'order', 'pictogram', 'types' +]) + +TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE = sorted([ + 'accessibility', 'approved', 'attachments', 'category', 'cities', 'contact', 'create_datetime', 'description', + 'description_teaser', 'departure_city', 'districts', 'email', 'external_id', 'geometry', 'id', 'label_accessibility', 'name', 'pdf', + 'portal', 'practical_info', 'provider', 'published', 'reservation_id', 'reservation_system', + 'source', 'structure', 'themes', 'types', 'update_datetime', 'url', 'uuid', 'website', +]) + +CITY_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'geometry', 'name', 'published' +]) + +DISTRICT_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'geometry', 'name', 'published' +]) + +ROUTE_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'route', 'pictogram' +]) + +THEME_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'label', 'pictogram' +]) + +ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'name', 'pictogram' +]) + +ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'name' +]) + +TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'name', 'website', 'title', 'description', 'facebook_id', 'facebook_image_url', 'facebook_image_height', 'facebook_image_width' +]) + +STRUCTURE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name']) + +TREK_LABEL_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'advice', 'filter', 'name', 'pictogram']) + +FILETYPE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'structure', 'type']) + +INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'label', 'pictogram' +]) + +INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'accessibility', 'description', 'email', 'label_accessibility', 'latitude', 'longitude', + 'municipality', 'name', 'phone', 'photo_url', 'provider', 'uuid', + 'postal_code', 'street', 'type', 'website' +]) + +SOURCE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'pictogram', 'website']) + +RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE = sorted(['name', 'id']) + +SITE_PROPERTIES_JSON_STRUCTURE = sorted([ + 'accessibility', 'advice', 'ambiance', 'attachments', 'children', 'cities', 'courses', 'description', 'description_teaser', 'districts', 'eid', + 'geometry', 'id', 'information_desks', 'labels', 'managers', 'name', 'orientation', 'parent', 'period', 'portal', + 'practice', 'provider', 'pdf', 'ratings', 'sector', 'source', 'structure', 'themes', 'type', 'url', 'uuid', + 'view_points', 'wind', 'web_links' +]) + +OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'sector', 'pictogram']) + +OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name']) + +SITETYPE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'practice']) + +SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'contact', 'create_datetime', 'description', 'elevation', 'geometry', + 'info_url', 'kml_url', 'openair_url', 'name', 'period', 'practices', 'provider', + 'published', 'species_id', 'structure', 'update_datetime', 'url', 'attachments', + 'rules' +]) + +SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE = sorted([ + 'id', 'name', 'period01', 'period02', 'period03', + 'period04', 'period05', 'period06', 'period07', + 'period08', 'period09', 'period10', 'period11', + 'period12', 'practices', 'radius', 'url' +]) + +COURSE_PROPERTIES_JSON_STRUCTURE = sorted([ + 'accessibility', 'advice', 'cities', 'description', 'districts', 'eid', 'equipment', 'geometry', 'height', 'id', + 'length', 'name', 'ratings', 'ratings_description', 'sites', 'structure', + 'type', 'url', 'attachments', 'max_elevation', 'min_elevation', 'parents', 'provider', + 'pdf', 'points_reference', 'children', 'duration', 'gear', 'uuid' +]) + +COURSETYPE_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name', 'practice']) + +ORGANISM_PROPERTIES_JSON_STRUCTURE = sorted(['id', 'name']) + +SERVICE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'eid', 'geometry', 'provider', 'structure', 'type', 'uuid' +]) + +SERVICE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'name', 'practices', 'pictogram' +]) + +INFRASTRUCTURE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'accessibility', 'attachments', 'condition', 'description', 'eid', 'geometry', + 'implantation_year', 'maintenance_difficulty', 'name', 'provider', 'structure', + 'type', 'usage_difficulty', 'uuid' +]) + +INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'pictogram', 'structure', 'type' +]) + +INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'structure' +]) + +INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'structure' +]) + +INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'structure' +]) + +TOURISTIC_EVENT_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'accessibility', 'approved', 'attachments', 'begin_date', 'bookable', 'booking', 'cities', 'contact', 'create_datetime', + 'description', 'description_teaser', 'districts', 'duration', 'email', 'end_date', 'external_id', 'geometry', + 'meeting_point', 'start_time', 'meeting_time', 'end_time', 'name', 'organizer', 'capacity', 'pdf', 'place', 'portal', + 'practical_info', 'provider', 'published', 'source', 'speaker', 'structure', 'target_audience', 'themes', + 'type', 'update_datetime', 'url', 'uuid', 'website', 'cancelled', 'cancellation_reason', 'participant_number' +]) + +TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'name', 'geometry' +]) + +TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label' +]) + +TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'pictogram', 'type' +]) + +SIGNAGE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'attachments', 'blades', 'code', 'condition', 'description', 'eid', + 'geometry', 'implantation_year', 'name', 'printed_elevation', 'sealing', + 'provider', 'structure', 'type', 'uuid' +]) + +SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'pictogram', 'structure' +]) + +SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label' +]) + +SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label' +]) + +SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'structure' +]) + +SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'label', 'structure' +]) + +HDVIEWPOINT_DETAIL_JSON_STRUCTURE = sorted([ + 'id', 'annotations', 'author', 'create_datetime', 'geometry', 'legend', 'license', + 'metadata_url', 'picture_tiles_url', 'poi', 'site', 'title', 'trek', 'thumbnail_url', 'update_datetime', 'uuid' +]) class BaseApiTest(TestCase): - """Base TestCase for all API profiles""" + """ Base TestCase for all API profiles """ def tearDown(self): clear_internal_user_cache() @@ -595,20 +299,15 @@ def setUpTestData(cls): cls.label = common_factory.LabelFactory(id=23) cls.path = core_factory.PathFactory.create(geom=LineString((0, 0), (0, 10))) if settings.TREKKING_TOPOLOGY_ENABLED: - cls.treks = trek_factory.TrekWithPOIsFactory.create_batch( - cls.nb_treks, paths=[(cls.path, 0, 1)], geom=cls.path.geom - ) + cls.treks = trek_factory.TrekWithPOIsFactory.create_batch(cls.nb_treks, paths=[(cls.path, 0, 1)], + geom=cls.path.geom) else: - cls.treks = trek_factory.TrekFactory.create_batch( - cls.nb_treks, geom=cls.path.geom - ) + cls.treks = trek_factory.TrekFactory.create_batch(cls.nb_treks, geom=cls.path.geom) trek_factory.POIFactory.create_batch(cls.nb_treks, geom=Point(0, 4)) trek_factory.POIFactory.create_batch(cls.nb_treks, geom=Point(0, 5)) - html_content_with_imgs = ( - "

Some HTML content with images

" - 'Descent' - '' - ) + html_content_with_imgs = '

Some HTML content with images

' \ + 'Descent' \ + '' cls.treks[0].description = html_content_with_imgs cls.treks[0].description_teaser = html_content_with_imgs cls.treks[0].ambiance = html_content_with_imgs @@ -620,65 +319,25 @@ def setUpTestData(cls): cls.treks[1].ratings.add(cls.rating2) trek_models.TrekRelationship(trek_a=cls.treks[0], trek_b=cls.treks[1]).save() cls.information_desk_type = tourism_factory.InformationDeskTypeFactory() - cls.info_desk = tourism_factory.InformationDeskFactory( - type=cls.information_desk_type - ) + cls.info_desk = tourism_factory.InformationDeskFactory(type=cls.information_desk_type) cls.treks[0].information_desks.add(cls.info_desk) - common_factory.AttachmentFactory.create( - content_object=cls.treks[0], attachment_file=get_dummy_uploaded_image() - ) - common_factory.AttachmentFactory.create( - content_object=cls.treks[0], attachment_file=get_dummy_uploaded_file() - ) - common_factory.AttachmentFactory.create( - content_object=cls.treks[0], attachment_file=get_dummy_uploaded_document() - ) - common_factory.AttachmentFactory( - content_object=cls.treks[0], - attachment_file="", - attachment_video="https://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque", - ) - common_factory.AttachmentFactory( - content_object=cls.treks[0], - attachment_file="", - attachment_video="", - attachment_link="https://geotrek.fr/assets/img/logo.svg", - ) - common_factory.AttachmentFactory( - content_object=cls.treks[0], - attachment_file="", - attachment_video="", - attachment_link="", - ) + common_factory.AttachmentFactory.create(content_object=cls.treks[0], attachment_file=get_dummy_uploaded_image()) + common_factory.AttachmentFactory.create(content_object=cls.treks[0], attachment_file=get_dummy_uploaded_file()) + common_factory.AttachmentFactory.create(content_object=cls.treks[0], attachment_file=get_dummy_uploaded_document()) + common_factory.AttachmentFactory(content_object=cls.treks[0], attachment_file='', attachment_video='https://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque') + common_factory.AttachmentFactory(content_object=cls.treks[0], attachment_file='', attachment_video='', attachment_link='https://geotrek.fr/assets/img/logo.svg') + common_factory.AttachmentFactory(content_object=cls.treks[0], attachment_file='', attachment_video='', attachment_link='') common_factory.AttachmentAccessibilityFactory(content_object=cls.treks[0]) cls.treks[3].parking_location = None - cls.treks[3].points_reference = MultiPoint( - [Point(0, 0), Point(1, 1)], srid=settings.SRID - ) + cls.treks[3].points_reference = MultiPoint([Point(0, 0), Point(1, 1)], srid=settings.SRID) cls.treks[3].save() - cls.content = tourism_factory.TouristicContentFactory.create( - published=True, geom="SRID=2154;POINT(0 0)" - ) - cls.content2 = tourism_factory.TouristicContentFactory.create( - published=True, geom="SRID=2154;POINT(0 0)" - ) - cls.event = tourism_factory.TouristicEventFactory.create( - published=True, geom="SRID=2154;POINT(0 0)" - ) - cls.city = zoning_factory.CityFactory( - code="01000", - geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))", - ) - cls.city2 = zoning_factory.CityFactory( - code="02000", - geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))", - ) - cls.district = zoning_factory.DistrictFactory( - geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))" - ) - cls.district2 = zoning_factory.DistrictFactory( - geom="SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))" - ) + cls.content = tourism_factory.TouristicContentFactory.create(published=True, geom='SRID=2154;POINT(0 0)') + cls.content2 = tourism_factory.TouristicContentFactory.create(published=True, geom='SRID=2154;POINT(0 0)') + cls.event = tourism_factory.TouristicEventFactory.create(published=True, geom='SRID=2154;POINT(0 0)') + cls.city = zoning_factory.CityFactory(code='01000', geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') + cls.city2 = zoning_factory.CityFactory(code='02000', geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') + cls.district = zoning_factory.DistrictFactory(geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') + cls.district2 = zoning_factory.DistrictFactory(geom='SRID=2154;MULTIPOLYGON(((-1 -1, -1 1, 1 1, 1 -1, -1 -1)))') cls.accessibility = trek_factory.AccessibilityFactory() cls.accessibility_level = trek_factory.AccessibilityLevelFactory() cls.route = trek_factory.RouteFactory() @@ -692,15 +351,11 @@ def setUpTestData(cls): cls.difficulty = trek_factory.DifficultyLevelFactory() cls.network = trek_factory.TrekNetworkFactory() if settings.TREKKING_TOPOLOGY_ENABLED: - cls.poi = trek_factory.POIFactory( - paths=[(cls.treks[0].paths.first(), 0.5, 0.5)] - ) - poi_excluded = trek_factory.POIFactory( - paths=[(cls.treks[0].paths.first(), 0.5, 0.5)] - ) + cls.poi = trek_factory.POIFactory(paths=[(cls.treks[0].paths.first(), 0.5, 0.5)]) + poi_excluded = trek_factory.POIFactory(paths=[(cls.treks[0].paths.first(), 0.5, 0.5)]) else: - cls.poi = trek_factory.POIFactory(geom="SRID=2154;POINT(0 5)") - poi_excluded = trek_factory.POIFactory(geom="SRID=2154;POINT(0 5)") + cls.poi = trek_factory.POIFactory(geom='SRID=2154;POINT(0 5)') + poi_excluded = trek_factory.POIFactory(geom='SRID=2154;POINT(0 5)') cls.treks[0].pois_excluded.add(poi_excluded) cls.source = common_factory.RecordSourceFactory() cls.reservation_system = common_factory.ReservationSystemFactory() @@ -715,20 +370,20 @@ def setUpTestData(cls): cls.info_desk.label_accessibility = cls.label_accessibility cls.info_desk.save() cls.content2.portal.add(cls.portal) - common_factory.FileTypeFactory.create(type="Topoguide") - cls.filetype = common_factory.FileTypeFactory.create(type="Foo") + common_factory.FileTypeFactory.create(type='Topoguide') + cls.filetype = common_factory.FileTypeFactory.create(type='Foo') cls.sensitivearea = sensitivity_factory.SensitiveAreaFactory() cls.sensitivearea_practice = sensitivity_factory.SportPracticeFactory() cls.sensitivearea_species = sensitivity_factory.SpeciesFactory() cls.parent = trek_factory.TrekFactory.create( published=True, - name="Parent", + name='Parent', route=cls.route, structure=cls.structure, reservation_system=cls.reservation_system, practice=cls.practice, difficulty=cls.difficulty, - accessibility_level=cls.accessibility_level, + accessibility_level=cls.accessibility_level ) cls.parent.accessibilities.add(cls.accessibility) cls.parent.source.add(cls.source) @@ -736,101 +391,79 @@ def setUpTestData(cls): cls.parent.networks.add(cls.network) cls.parent.save() # For unpublished treks we avoid to create new reservation system and routes - cls.parent2 = trek_factory.TrekFactory.create( - published=False, - name="Parent2", - reservation_system=cls.reservation_system, - route=cls.route, - accessibility_level=None, - ) - cls.child1 = trek_factory.TrekFactory.create( - published=False, - name="Child 1", - reservation_system=cls.reservation_system, - route=cls.route, - accessibility_level=None, - ) - cls.child2 = trek_factory.TrekFactory.create( - published=True, name="Child 2", accessibility_level=None - ) - cls.child3 = trek_factory.TrekFactory.create( - published=False, - name="Child 3", - reservation_system=cls.reservation_system, - route=cls.route, - accessibility_level=None, - ) + cls.parent2 = trek_factory.TrekFactory.create(published=False, name='Parent2', + reservation_system=cls.reservation_system, route=cls.route, + accessibility_level=None) + cls.child1 = trek_factory.TrekFactory.create(published=False, name='Child 1', + reservation_system=cls.reservation_system, route=cls.route, + accessibility_level=None) + cls.child2 = trek_factory.TrekFactory.create(published=True, name='Child 2', accessibility_level=None) + cls.child3 = trek_factory.TrekFactory.create(published=False, name='Child 3', + reservation_system=cls.reservation_system, route=cls.route, + accessibility_level=None) trek_models.TrekRelationship(trek_a=cls.parent, trek_b=cls.treks[0]).save() - trek_models.OrderedTrekChild( - parent=cls.parent, child=cls.child1, order=2 - ).save() - trek_models.OrderedTrekChild( - parent=cls.parent, child=cls.child2, order=1 - ).save() - trek_models.OrderedTrekChild( - parent=cls.parent2, child=cls.child3, order=1 - ).save() - trek_models.OrderedTrekChild( - parent=cls.treks[0], child=cls.child2, order=3 - ).save() + trek_models.OrderedTrekChild(parent=cls.parent, child=cls.child1, order=2).save() + trek_models.OrderedTrekChild(parent=cls.parent, child=cls.child2, order=1).save() + trek_models.OrderedTrekChild(parent=cls.parent2, child=cls.child3, order=1).save() + trek_models.OrderedTrekChild(parent=cls.treks[0], child=cls.child2, order=3).save() # Create a trek with a multilinestring geom cls.path2 = core_factory.PathFactory.create(geom=LineString((0, 10), (0, 20))) cls.path3 = core_factory.PathFactory.create(geom=LineString((0, 20), (0, 30))) cls.trek_multilinestring = trek_factory.TrekFactory.create( paths=[(cls.path, 0, 1), (cls.path2, 0, 1), (cls.path3, 0, 1)], - geom=MultiLineString([cls.path.geom, cls.path3.geom]), + geom=MultiLineString([cls.path.geom, cls.path3.geom]) ) cls.path2.delete() cls.trek_multilinestring.reload() cls.trek_multilinestring.published = True cls.trek_multilinestring.save() # Create a trek with a point geom - cls.trek_point = trek_factory.TrekFactory.create( - paths=[(cls.path, 0, 0)], geom=Point(cls.path.geom.coords[0]) - ) + cls.trek_point = trek_factory.TrekFactory.create(paths=[(cls.path, 0, 0)], geom=Point(cls.path.geom.coords[0])) cls.nb_treks += 4 # add parent, 1 child published and treks with a multilinestring/point geom cls.coursetype = outdoor_factory.CourseTypeFactory() cls.course = outdoor_factory.CourseFactory( - type=cls.coursetype, points_reference=MultiPoint(Point(12, 12)) + type=cls.coursetype, + points_reference=MultiPoint(Point(12, 12)) ) cls.course.pois_excluded.add(poi_excluded) cls.course.parent_sites.set([cls.site]) # create a reference point for distance filter (in 4326, Cahors city) - cls.reference_point = Point( - x=1.4388656616210938, y=44.448487178796235, srid=4326 - ) + cls.reference_point = Point(x=1.4388656616210938, + y=44.448487178796235, srid=4326) cls.service_type = trek_factory.ServiceTypeFactory() cls.service_type_2 = trek_factory.ServiceTypeFactory(published=False) cls.service1 = trek_factory.ServiceFactory() - cls.service = trek_factory.ServiceFactory(type=cls.service_type) - cls.service_2 = trek_factory.ServiceFactory(type=cls.service_type_2) - cls.infrastructure_type = infrastructure_factory.InfrastructureTypeFactory() - cls.infrastructure_condition = ( - infrastructure_factory.InfrastructureConditionFactory() - ) - cls.infrastructure_usagedifficulty = ( - infrastructure_factory.InfrastructureUsageDifficultyLevelFactory() + cls.service = trek_factory.ServiceFactory( + type=cls.service_type ) - cls.infrastructure_maintenancedifficulty = ( - infrastructure_factory.InfrastructureMaintenanceDifficultyLevelFactory() + cls.service_2 = trek_factory.ServiceFactory( + type=cls.service_type_2 ) + cls.infrastructure_type = infrastructure_factory.InfrastructureTypeFactory() + cls.infrastructure_condition = infrastructure_factory.InfrastructureConditionFactory() + cls.infrastructure_usagedifficulty = infrastructure_factory.InfrastructureUsageDifficultyLevelFactory() + cls.infrastructure_maintenancedifficulty = infrastructure_factory.InfrastructureMaintenanceDifficultyLevelFactory() cls.infrastructure = infrastructure_factory.InfrastructureFactory( type=cls.infrastructure_type, usage_difficulty=cls.infrastructure_usagedifficulty, maintenance_difficulty=cls.infrastructure_maintenancedifficulty, condition=cls.infrastructure_condition, - published=True, + published=True + ) + cls.bladetype = signage_factory.BladeTypeFactory( ) - cls.bladetype = signage_factory.BladeTypeFactory() cls.color = signage_factory.BladeColorFactory() cls.sealing = signage_factory.SealingFactory() cls.direction = signage_factory.BladeDirectionFactory() cls.bladetype = signage_factory.BladeFactory( - color=cls.color, type=cls.bladetype, direction=cls.direction + color=cls.color, + type=cls.bladetype, + direction=cls.direction ) cls.signagetype = signage_factory.SignageTypeFactory() cls.signage = signage_factory.SignageFactory( - type=cls.signagetype, published=True + type=cls.signagetype, + published=True ) cls.sector = outdoor_factory.SectorFactory() cls.outdoor_practice = outdoor_factory.PracticeFactory(sector=cls.sector) @@ -843,7 +476,9 @@ def setUpTestData(cls): cls.hdviewpoint_trek = common_factory.HDViewPointFactory( content_object=cls.treks[0] ) - cls.hdviewpoint_poi = common_factory.HDViewPointFactory(content_object=cls.poi) + cls.hdviewpoint_poi = common_factory.HDViewPointFactory( + content_object=cls.poi + ) cls.hdviewpoint_site = common_factory.HDViewPointFactory( content_object=cls.site ) @@ -851,7 +486,7 @@ def setUpTestData(cls): def check_number_elems_response(self, response, model): json_response = response.json() self.assertEqual(response.status_code, 200) - self.assertEquals(len(json_response["results"]), model.objects.count()) + self.assertEquals(len(json_response['results']), model.objects.count()) def check_structure_response(self, response, structure): json_response = response.json() @@ -859,499 +494,388 @@ def check_structure_response(self, response, structure): self.assertEquals(sorted(json_response.keys()), structure) def get_trek_list(self, params=None): - return self.client.get(reverse("apiv2:trek-list"), params) + return self.client.get(reverse('apiv2:trek-list'), params) def get_trek_detail(self, id_trek, params=None): - return self.client.get(reverse("apiv2:trek-detail", args=(id_trek,)), params) + return self.client.get(reverse('apiv2:trek-detail', args=(id_trek,)), params) def get_tour_list(self, params=None): - return self.client.get(reverse("apiv2:tour-list"), params) + return self.client.get(reverse('apiv2:tour-list'), params) def get_tour_detail(self, id_trek, params=None): - return self.client.get(reverse("apiv2:tour-detail", args=(id_trek,)), params) + return self.client.get(reverse('apiv2:tour-detail', args=(id_trek,)), params) def get_difficulties_list(self, params=None): - return self.client.get(reverse("apiv2:difficulty-list"), params) + return self.client.get(reverse('apiv2:difficulty-list'), params) def get_difficulty_detail(self, id_difficulty, params=None): - return self.client.get( - reverse("apiv2:difficulty-detail", args=(id_difficulty,)), params - ) + return self.client.get(reverse('apiv2:difficulty-detail', args=(id_difficulty,)), params) def get_practices_list(self, params=None): - return self.client.get(reverse("apiv2:practice-list"), params) + return self.client.get(reverse('apiv2:practice-list'), params) def get_practices_detail(self, id_practice, params=None): - return self.client.get( - reverse("apiv2:practice-detail", args=(id_practice,)), params - ) + return self.client.get(reverse('apiv2:practice-detail', args=(id_practice,)), params) def get_networks_list(self, params=None): - return self.client.get(reverse("apiv2:network-list"), params) + return self.client.get(reverse('apiv2:network-list'), params) def get_network_detail(self, id_network, params=None): - return self.client.get( - reverse("apiv2:network-detail", args=(id_network,)), params - ) + return self.client.get(reverse('apiv2:network-detail', args=(id_network,)), params) def get_themes_list(self, params=None): - return self.client.get(reverse("apiv2:theme-list"), params) + return self.client.get(reverse('apiv2:theme-list'), params) def get_themes_detail(self, id_theme, params=None): - return self.client.get(reverse("apiv2:theme-detail", args=(id_theme,)), params) + return self.client.get(reverse('apiv2:theme-detail', args=(id_theme,)), params) def get_city_list(self, params=None): - return self.client.get(reverse("apiv2:city-list"), params) + return self.client.get(reverse('apiv2:city-list'), params) def get_city_detail(self, id_city, params=None): - return self.client.get(reverse("apiv2:city-detail", args=(id_city,)), params) + return self.client.get(reverse('apiv2:city-detail', args=(id_city,)), params) def get_district_list(self, params=None): - return self.client.get(reverse("apiv2:district-list"), params) + return self.client.get(reverse('apiv2:district-list'), params) def get_district_detail(self, id_district, params=None): - return self.client.get( - reverse("apiv2:district-detail", args=(id_district,)), params - ) + return self.client.get(reverse('apiv2:district-detail', args=(id_district,)), params) def get_route_list(self, params=None): - return self.client.get(reverse("apiv2:route-list"), params) + return self.client.get(reverse('apiv2:route-list'), params) def get_route_detail(self, id_route, params=None): - return self.client.get(reverse("apiv2:route-detail", args=(id_route,)), params) + return self.client.get(reverse('apiv2:route-detail', args=(id_route,)), params) def get_accessibility_list(self, params=None): - return self.client.get(reverse("apiv2:accessibility-list"), params) + return self.client.get(reverse('apiv2:accessibility-list'), params) def get_accessibility_level_list(self, params=None): - return self.client.get(reverse("apiv2:accessibility-level-list"), params) + return self.client.get(reverse('apiv2:accessibility-level-list'), params) def get_accessibility_detail(self, id_accessibility, params=None): - return self.client.get( - reverse("apiv2:accessibility-detail", args=(id_accessibility,)), params - ) + return self.client.get(reverse('apiv2:accessibility-detail', args=(id_accessibility,)), params) def get_accessibility_level_detail(self, id_accessibility_level, params=None): - return self.client.get( - reverse("apiv2:accessibility-level-detail", args=(id_accessibility_level,)), - params, - ) + return self.client.get(reverse('apiv2:accessibility-level-detail', args=(id_accessibility_level,)), params) def get_portal_list(self, params=None): - return self.client.get(reverse("apiv2:portal-list"), params) + return self.client.get(reverse('apiv2:portal-list'), params) def get_portal_detail(self, id_portal, params=None): - return self.client.get( - reverse("apiv2:portal-detail", args=(id_portal,)), params - ) + return self.client.get(reverse('apiv2:portal-detail', args=(id_portal,)), params) def get_structure_list(self, params=None): - return self.client.get(reverse("apiv2:structure-list"), params) + return self.client.get(reverse('apiv2:structure-list'), params) def get_structure_detail(self, id_structure, params=None): - return self.client.get( - reverse("apiv2:structure-detail", args=(id_structure,)), params - ) + return self.client.get(reverse('apiv2:structure-detail', args=(id_structure,)), params) def get_poi_list(self, params=None): - return self.client.get(reverse("apiv2:poi-list"), params) + return self.client.get(reverse('apiv2:poi-list'), params) def get_poi_detail(self, id_poi, params=None): - return self.client.get(reverse("apiv2:poi-detail", args=(id_poi,)), params) + return self.client.get(reverse('apiv2:poi-detail', args=(id_poi,)), params) def get_poi_type(self, params=None): - return self.client.get(reverse("apiv2:poitype-list"), params) + return self.client.get(reverse('apiv2:poitype-list'), params) def get_path_list(self, params=None): - return self.client.get(reverse("apiv2:path-list"), params) + return self.client.get(reverse('apiv2:path-list'), params) def get_path_detail(self, id_path, params=None): - return self.client.get(reverse("apiv2:path-detail", args=(id_path,)), params) + return self.client.get(reverse('apiv2:path-detail', args=(id_path,)), params) def get_touristiccontentcategory_list(self, params=None): - return self.client.get(reverse("apiv2:touristiccontentcategory-list"), params) + return self.client.get(reverse('apiv2:touristiccontentcategory-list'), params) def get_touristiccontentcategory_detail(self, id_category, params=None): - return self.client.get( - reverse("apiv2:touristiccontentcategory-detail", args=(id_category,)), - params, - ) + return self.client.get(reverse('apiv2:touristiccontentcategory-detail', args=(id_category,)), params) def get_touristiccontent_list(self, params=None): - return self.client.get(reverse("apiv2:touristiccontent-list"), params) + return self.client.get(reverse('apiv2:touristiccontent-list'), params) def get_touristiccontent_detail(self, id_content, params=None): - return self.client.get( - reverse("apiv2:touristiccontent-detail", args=(id_content,)), params - ) + return self.client.get(reverse('apiv2:touristiccontent-detail', args=(id_content,)), params) def get_labelaccessibility_list(self, params=None): - return self.client.get(reverse("apiv2:labelaccessibility-list", params)) + return self.client.get(reverse('apiv2:labelaccessibility-list', params)) def get_labelaccessibility_detail(self, id_label_accessibility, params=None): - return self.client.get( - reverse("apiv2:labelaccessibility-detail", args=(id_label_accessibility,)), - params, - ) + return self.client.get(reverse('apiv2:labelaccessibility-detail', args=(id_label_accessibility,)), params) def get_label_list(self, params=None): - return self.client.get(reverse("apiv2:label-list"), params) + return self.client.get(reverse('apiv2:label-list'), params) def get_label_detail(self, id_label, params=None): - return self.client.get(reverse("apiv2:label-detail", args=(id_label,)), params) + return self.client.get(reverse('apiv2:label-detail', args=(id_label,)), params) def get_filetype_list(self, params=None): - return self.client.get(reverse("apiv2:filetype-list"), params) + return self.client.get(reverse('apiv2:filetype-list'), params) def get_filetype_detail(self, id_label, params=None): - return self.client.get( - reverse("apiv2:filetype-detail", args=(id_label,)), params - ) + return self.client.get(reverse('apiv2:filetype-detail', args=(id_label,)), params) def get_informationdesk_list(self, params=None): - return self.client.get(reverse("apiv2:informationdesk-list"), params) + return self.client.get(reverse('apiv2:informationdesk-list'), params) def get_informationdesk_detail(self, id_infodesk, params=None): - return self.client.get( - reverse("apiv2:informationdesk-detail", args=(id_infodesk,)), params - ) + return self.client.get(reverse('apiv2:informationdesk-detail', args=(id_infodesk,)), params) def get_informationdesk_type_list(self, params=None): - return self.client.get(reverse("apiv2:informationdesktype-list"), params) + return self.client.get(reverse('apiv2:informationdesktype-list'), params) def get_informationdesk_type_detail(self, id_infodesk_type, params=None): - return self.client.get( - reverse("apiv2:informationdesktype-detail", args=(id_infodesk_type,)), - params, - ) + return self.client.get(reverse('apiv2:informationdesktype-detail', args=(id_infodesk_type,)), params) def get_source_list(self, params=None): - return self.client.get(reverse("apiv2:source-list"), params) + return self.client.get(reverse('apiv2:source-list'), params) def get_source_detail(self, id_source, params=None): - return self.client.get( - reverse("apiv2:source-detail", args=(id_source,)), params - ) + return self.client.get(reverse('apiv2:source-detail', args=(id_source,)), params) def get_reservationsystem_list(self, params=None): - return self.client.get(reverse("apiv2:reservationsystem-list"), params) + return self.client.get(reverse('apiv2:reservationsystem-list'), params) def get_reservationsystem_detail(self, id_reservationsystem, params=None): - return self.client.get( - reverse("apiv2:reservationsystem-detail", args=(id_reservationsystem,)), - params, - ) + return self.client.get(reverse('apiv2:reservationsystem-detail', args=(id_reservationsystem,)), params) def get_site_list(self, params=None): - return self.client.get(reverse("apiv2:site-list"), params) + return self.client.get(reverse('apiv2:site-list'), params) def get_site_detail(self, id_site, params=None): - return self.client.get(reverse("apiv2:site-detail", args=(id_site,)), params) + return self.client.get(reverse('apiv2:site-detail', args=(id_site,)), params) def get_course_list(self, params=None): - return self.client.get(reverse("apiv2:course-list"), params) + return self.client.get(reverse('apiv2:course-list'), params) def get_course_detail(self, id_course, params=None): - return self.client.get( - reverse("apiv2:course-detail", args=(id_course,)), params - ) + return self.client.get(reverse('apiv2:course-detail', args=(id_course,)), params) def get_outdoorpractice_list(self, params=None): - return self.client.get(reverse("apiv2:outdoor-practice-list"), params) + return self.client.get(reverse('apiv2:outdoor-practice-list'), params) def get_outdoorpractice_detail(self, id_practice, params=None): - return self.client.get( - reverse("apiv2:outdoor-practice-detail", args=(id_practice,)), params - ) + return self.client.get(reverse('apiv2:outdoor-practice-detail', args=(id_practice,)), params) def get_sitetype_list(self, params=None): - return self.client.get(reverse("apiv2:sitetype-list"), params) + return self.client.get(reverse('apiv2:sitetype-list'), params) def get_sitetype_detail(self, id_type, params=None): - return self.client.get( - reverse("apiv2:sitetype-detail", args=(id_type,)), params - ) + return self.client.get(reverse('apiv2:sitetype-detail', args=(id_type,)), params) def get_sensitivearea_list(self, params=None): - return self.client.get(reverse("apiv2:sensitivearea-list"), params) + return self.client.get(reverse('apiv2:sensitivearea-list'), params) def get_sensitivearea_detail(self, id_sensitivearea, params=None): - return self.client.get( - reverse("apiv2:sensitivearea-detail", args=(id_sensitivearea,)), params - ) + return self.client.get(reverse('apiv2:sensitivearea-detail', args=(id_sensitivearea,)), params) def get_sensitiveareapractice_list(self, params=None): - return self.client.get(reverse("apiv2:sportpractice-list"), params) + return self.client.get(reverse('apiv2:sportpractice-list'), params) def get_sensitiveareapractice_detail(self, id_sensitivearea_practice, params=None): - return self.client.get( - reverse("apiv2:sportpractice-detail", args=(id_sensitivearea_practice,)), - params, - ) + return self.client.get(reverse('apiv2:sportpractice-detail', args=(id_sensitivearea_practice,)), params) def get_sensitiveareaspecies_list(self, params=None): - return self.client.get(reverse("apiv2:species-list"), params) + return self.client.get(reverse('apiv2:species-list'), params) def get_sensitiveareaspecies_detail(self, id_sensitivearea_species, params=None): - return self.client.get( - reverse("apiv2:species-detail", args=(id_sensitivearea_species,)), params - ) + return self.client.get(reverse('apiv2:species-detail', args=(id_sensitivearea_species,)), params) def get_config(self, params=None): - return self.client.get(reverse("apiv2:config", params)) + return self.client.get(reverse('apiv2:config', params)) def get_organism_list(self, params=None): - return self.client.get(reverse("apiv2:organism-list"), params) + return self.client.get(reverse('apiv2:organism-list'), params) def get_organism_detail(self, id_organism, params=None): - return self.client.get( - reverse("apiv2:organism-detail", args=(id_organism,)), params - ) + return self.client.get(reverse('apiv2:organism-detail', args=(id_organism,)), params) def get_status_list(self, params=None): - return self.client.get(reverse("apiv2:feedback-status"), params) + return self.client.get(reverse('apiv2:feedback-status'), params) def get_activity_list(self, params=None): - return self.client.get(reverse("apiv2:feedback-activity"), params) + return self.client.get(reverse('apiv2:feedback-activity'), params) def get_category_list(self, params=None): - return self.client.get(reverse("apiv2:feedback-category"), params) + return self.client.get(reverse('apiv2:feedback-category'), params) def get_magnitude_list(self, params=None): - return self.client.get(reverse("apiv2:feedback-magnitude"), params) + return self.client.get(reverse('apiv2:feedback-magnitude'), params) def get_touristicevent_list(self, params=None): - return self.client.get(reverse("apiv2:touristicevent-list"), params) + return self.client.get(reverse('apiv2:touristicevent-list'), params) def get_touristicevent_detail(self, id_touristicevent, params=None): - return self.client.get( - reverse("apiv2:touristicevent-detail", args=(id_touristicevent,)), params - ) + return self.client.get(reverse('apiv2:touristicevent-detail', args=(id_touristicevent,)), params) def get_touristiceventtype_list(self, params=None): - return self.client.get(reverse("apiv2:touristiceventtype-list"), params) + return self.client.get(reverse('apiv2:touristiceventtype-list'), params) def get_touristiceventtype_detail(self, id_touristiceventtype, params=None): - return self.client.get( - reverse("apiv2:touristiceventtype-detail", args=(id_touristiceventtype,)), - params, - ) + return self.client.get(reverse('apiv2:touristiceventtype-detail', args=(id_touristiceventtype,)), params) def get_touristiceventplace_list(self, params=None): - return self.client.get(reverse("apiv2:touristiceventplace-list"), params) + return self.client.get(reverse('apiv2:touristiceventplace-list'), params) def get_touristiceventplace_detail(self, id_touristiceventplace, params=None): - return self.client.get( - reverse("apiv2:touristiceventplace-detail", args=(id_touristiceventplace,)), - params, - ) + return self.client.get(reverse('apiv2:touristiceventplace-detail', args=(id_touristiceventplace,)), params) def get_touristiceventorganizer_list(self, params=None): - return self.client.get(reverse("apiv2:touristiceventorganizer-list"), params) + return self.client.get(reverse('apiv2:touristiceventorganizer-list'), params) - def get_touristiceventorganizer_detail( - self, id_touristiceventorganizer, params=None - ): - return self.client.get( - reverse( - "apiv2:touristiceventorganizer-detail", - args=(id_touristiceventorganizer,), - ), - params, - ) + def get_touristiceventorganizer_detail(self, id_touristiceventorganizer, params=None): + return self.client.get(reverse('apiv2:touristiceventorganizer-detail', args=(id_touristiceventorganizer,)), params) def get_servicetype_list(self, params=None): - return self.client.get(reverse("apiv2:servicetype-list"), params) + return self.client.get(reverse('apiv2:servicetype-list'), params) def get_service_list(self, params=None): - return self.client.get(reverse("apiv2:service-list"), params) + return self.client.get(reverse('apiv2:service-list'), params) def get_servicetype_detail(self, id_servicetype, params=None): - return self.client.get( - reverse("apiv2:servicetype-detail", args=(id_servicetype,)), params - ) + return self.client.get(reverse('apiv2:servicetype-detail', args=(id_servicetype,)), params) def get_service_detail(self, id_service, params=None): - return self.client.get( - reverse("apiv2:service-detail", args=(id_service,)), params - ) + return self.client.get(reverse('apiv2:service-detail', args=(id_service,)), params) def get_coursetype_list(self, params=None): - return self.client.get(reverse("apiv2:coursetype-list"), params) + return self.client.get(reverse('apiv2:coursetype-list'), params) def get_coursetype_detail(self, id_coursetype, params=None): - return self.client.get( - reverse("apiv2:coursetype-detail", args=(id_coursetype,)), params - ) + return self.client.get(reverse('apiv2:coursetype-detail', args=(id_coursetype,)), params) def get_infrastructuretype_detail(self, id_infrastructuretype, params=None): - return self.client.get( - reverse("apiv2:infrastructure-type-detail", args=(id_infrastructuretype,)), - params, - ) + return self.client.get(reverse('apiv2:infrastructure-type-detail', args=(id_infrastructuretype,)), params) def get_infrastructuretype_list(self, params=None): - return self.client.get(reverse("apiv2:infrastructure-type-list"), params) + return self.client.get(reverse('apiv2:infrastructure-type-list'), params) def get_infrastructure_list(self, params=None): - return self.client.get(reverse("apiv2:infrastructure-list"), params) + return self.client.get(reverse('apiv2:infrastructure-list'), params) def get_infrastructure_detail(self, id_infrastructure, params=None): - return self.client.get( - reverse("apiv2:infrastructure-detail", args=(id_infrastructure,)), params - ) + return self.client.get(reverse('apiv2:infrastructure-detail', args=(id_infrastructure,)), params) def get_infrastructurecondition_list(self, params=None): - return self.client.get(reverse("apiv2:infrastructure-condition-list"), params) + return self.client.get(reverse('apiv2:infrastructure-condition-list'), params) - def get_infrastructurecondition_detail( - self, id_infrastructurecondition, params=None - ): - return self.client.get( - reverse( - "apiv2:infrastructure-condition-detail", - args=(id_infrastructurecondition,), - ), - params, - ) + def get_infrastructurecondition_detail(self, id_infrastructurecondition, params=None): + return self.client.get(reverse('apiv2:infrastructure-condition-detail', args=(id_infrastructurecondition,)), params) def get_infrastructuremaintenancedifficulty_list(self, params=None): - return self.client.get( - reverse("apiv2:infrastructure-maintenance-difficulty-list"), params - ) + return self.client.get(reverse('apiv2:infrastructure-maintenance-difficulty-list'), params) - def get_infrastructuremaintenancedifficulty_detail( - self, id_infrastructuremaintenancedifficulty, params=None - ): - return self.client.get( - reverse( - "apiv2:infrastructure-maintenance-difficulty-detail", - args=(id_infrastructuremaintenancedifficulty,), - ), - params, - ) + def get_infrastructuremaintenancedifficulty_detail(self, id_infrastructuremaintenancedifficulty, params=None): + return self.client.get(reverse('apiv2:infrastructure-maintenance-difficulty-detail', args=(id_infrastructuremaintenancedifficulty,)), params) def get_infrastructureusagedifficulty_list(self, params=None): - return self.client.get( - reverse("apiv2:infrastructure-usage-difficulty-list"), params - ) + return self.client.get(reverse('apiv2:infrastructure-usage-difficulty-list'), params) - def get_infrastructureusagedifficulty_detail( - self, id_infrastructureusagedifficulty, params=None - ): - return self.client.get( - reverse( - "apiv2:infrastructure-usage-difficulty-detail", - args=(id_infrastructureusagedifficulty,), - ), - params, - ) + def get_infrastructureusagedifficulty_detail(self, id_infrastructureusagedifficulty, params=None): + return self.client.get(reverse('apiv2:infrastructure-usage-difficulty-detail', args=(id_infrastructureusagedifficulty,)), params) def get_signage_detail(self, id_signage, params=None): - return self.client.get( - reverse("apiv2:signage-detail", args=(id_signage,)), params - ) + return self.client.get(reverse('apiv2:signage-detail', args=(id_signage,)), params) def get_signage_list(self, params=None): - return self.client.get(reverse("apiv2:signage-list"), params) + return self.client.get(reverse('apiv2:signage-list'), params) def get_signagetype_list(self, params=None): - return self.client.get(reverse("apiv2:signage-type-list"), params) + return self.client.get(reverse('apiv2:signage-type-list'), params) def get_signagetype_detail(self, id_signagetype, params=None): - return self.client.get( - reverse("apiv2:signage-type-detail", args=(id_signagetype,)), params - ) + return self.client.get(reverse('apiv2:signage-type-detail', args=(id_signagetype,)), params) def get_signagebladetype_list(self, params=None): - return self.client.get(reverse("apiv2:signage-blade-type-list"), params) + return self.client.get(reverse('apiv2:signage-blade-type-list'), params) def get_signagebladetype_detail(self, id_signagebladetype, params=None): - return self.client.get( - reverse("apiv2:signage-blade-type-detail", args=(id_signagebladetype,)), - params, - ) + return self.client.get(reverse('apiv2:signage-blade-type-detail', args=(id_signagebladetype,)), params) def get_signagesealing_list(self, params=None): - return self.client.get(reverse("apiv2:signage-sealing-list"), params) + return self.client.get(reverse('apiv2:signage-sealing-list'), params) def get_signagesealing_detail(self, id_signagesealing, params=None): - return self.client.get( - reverse("apiv2:signage-sealing-detail", args=(id_signagesealing,)), params - ) + return self.client.get(reverse('apiv2:signage-sealing-detail', args=(id_signagesealing,)), params) def get_signagecolor_list(self, params=None): - return self.client.get(reverse("apiv2:signage-color-list"), params) + return self.client.get(reverse('apiv2:signage-color-list'), params) def get_signagecolor_detail(self, id_signagecolor, params=None): - return self.client.get( - reverse("apiv2:signage-color-detail", args=(id_signagecolor,)), params - ) + return self.client.get(reverse('apiv2:signage-color-detail', args=(id_signagecolor,)), params) def get_signagedirection_list(self, params=None): - return self.client.get(reverse("apiv2:signage-direction-list"), params) + return self.client.get(reverse('apiv2:signage-direction-list'), params) def get_signagedirection_detail(self, id_signagedirection, params=None): - return self.client.get( - reverse("apiv2:signage-direction-detail", args=(id_signagedirection,)), - params, - ) + return self.client.get(reverse('apiv2:signage-direction-detail', args=(id_signagedirection,)), params) def get_sector_list(self, params=None): - return self.client.get(reverse("apiv2:outdoor-sector-list"), params) + return self.client.get(reverse('apiv2:outdoor-sector-list'), params) def get_sector_detail(self, id_sector, params=None): - return self.client.get( - reverse("apiv2:outdoor-sector-detail", args=(id_sector,)), params - ) + return self.client.get(reverse('apiv2:outdoor-sector-detail', args=(id_sector,)), params) def get_hdviewpoint_list(self, params=None): - return self.client.get(reverse("apiv2:hdviewpoint-list"), params) + return self.client.get(reverse('apiv2:hdviewpoint-list'), params) def get_hdviewpoint_detail(self, id_hdviewpoint, params=None): - return self.client.get( - reverse("apiv2:hdviewpoint-detail", args=(id_hdviewpoint,)), params - ) + return self.client.get(reverse('apiv2:hdviewpoint-detail', args=(id_hdviewpoint,)), params) -class APIAccessAnonymousTestCase(BaseApiTest): - """TestCase for anonymous API profile""" +class NoPaginationTestCase(BaseApiTest): + """ + Integration tests for disabled pagination. + """ - def test_path_list(self): - response = self.get_path_list() - self.assertEqual(response.status_code, 401) + def setUp(self): + self.factory = RequestFactory() - def test_no_pagination(self): - import pprint - response = self.get_trek_list({"no_page": "true"}) + def test_json_no_page(self): + request = self.factory.get( + reverse("apiv2:trek-list"), + { + "no_page": "true", + } + ) + response = TrekViewSet.as_view({"get": "list"})(request) self.assertEqual(response.status_code, 200) - json_response = response.json() - print(len(json_response)) - pprint(json_response) - self.assertIsInstance(json_response, list) - self.assertIsInstance(json_response[0], dict) + self.assertIsInstance(response.data, list) + self.assertIsInstance(response.data[0], dict) self.assertEqual( - len(json_response[0].get("geometry").get("coordinates")[0]), + len(response.data[0].get("geometry").get("coordinates")[0]), 3, ) - def test_geojson_no_pagination(self): - response = self.get_trek_list({"no_page": "true", "format": "geojson"}) - self.assertEqual(response.status_code, 200) - json_response = response.json() - print(json_response) - self.assertIsInstance(json_response, dict) - self.assertEqual( - sorted(json_response.keys()), GEOJSON_COLLECTION_STRUCTURE + def test_geojson_no_page(self): + request = self.factory.get( + reverse("apiv2:trek-list"), + { + "no_page": "true", + "format": "geojson", + } ) + response = TrekViewSet.as_view({"get": "list"})(request) + self.assertEqual(response.status_code, 200) + self.assertIsInstance(response.data, dict) + self.assertEqual(sorted(response.data.keys()), GEOJSON_COLLECTION_STRUCTURE) self.assertEqual( - len(json_response.get("features")), self.nb_treks, json_response + len(response.data.get("features")), self.nb_treks, response.data ) self.assertEqual( - sorted(json_response.get("features")[0].get("properties").keys()), + sorted(response.data.get("features")[0].get("properties").keys()), TREK_PROPERTIES_GEOJSON_STRUCTURE, ) + +class APIAccessAnonymousTestCase(BaseApiTest): + """ TestCase for anonymous API profile """ + + def test_path_list(self): + response = self.get_path_list() + self.assertEqual(response.status_code, 401) + def test_trek_list(self): response = self.get_trek_list() # test response code @@ -1359,364 +883,362 @@ def test_trek_list(self): # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_JSON_STRUCTURE) # trek count is ok - self.assertEqual(len(json_response.get("results")), self.nb_treks) + self.assertEqual(len(json_response.get('results')), self.nb_treks) # test dim 3 by default for treks - self.assertEqual( - len(json_response.get("results")[0].get("geometry").get("coordinates")[0]), - 3, - ) + self.assertEqual(len(json_response.get('results')[0].get('geometry').get('coordinates')[0]), + 3) # regenerate with geojson - response = self.get_trek_list({"format": "geojson"}) + response = self.get_trek_list({'format': 'geojson'}) json_response = response.json() # test geojson format - self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual( - len(json_response.get("features")), self.nb_treks, json_response - ) + self.assertEqual(len(json_response.get('features')), + self.nb_treks, json_response) - self.assertEqual( - sorted(json_response.get("features")[0].keys()), GEOJSON_STRUCTURE - ) + self.assertEqual(sorted(json_response.get('features')[0].keys()), + GEOJSON_STRUCTURE) - self.assertEqual( - sorted(json_response.get("features")[0].get("properties").keys()), - TREK_PROPERTIES_GEOJSON_STRUCTURE, - ) + self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), + TREK_PROPERTIES_GEOJSON_STRUCTURE) def test_trek_list_filters(self): - response = self.get_trek_list( - { - "duration_min": "2", - "duration_max": "5", - "length_min": "4", - "length_max": "20", - "difficulty_min": "1", - "difficulty_max": "3", - "ascent_min": "150", - "ascent_max": "1000", - "cities": "31000", - "districts": self.district.pk, - "structures": self.structure.pk, - "accessibilities": self.accessibility.pk, - "accessibility_level": self.accessibility_level.pk, - "themes": self.theme2.pk, - "portals": self.portal.pk, - "labels": "23", - "routes": "68", - "practices": "1", - "ratings": self.rating.pk, - "q": "test string", - } - ) + response = self.get_trek_list({ + 'duration_min': '2', + 'duration_max': '5', + 'length_min': '4', + 'length_max': '20', + 'difficulty_min': '1', + 'difficulty_max': '3', + 'ascent_min': '150', + 'ascent_max': '1000', + 'cities': '31000', + 'districts': self.district.pk, + 'structures': self.structure.pk, + 'accessibilities': self.accessibility.pk, + 'accessibility_level': self.accessibility_level.pk, + 'themes': self.theme2.pk, + 'portals': self.portal.pk, + 'labels': '23', + 'routes': '68', + 'practices': '1', + 'ratings': self.rating.pk, + 'q': 'test string', + }) # test response code self.assertEqual(response.status_code, 200) # json collection structure is ok json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_theme_filter(self): - response = self.get_trek_list({"themes": self.theme2.pk}) + response = self.get_trek_list({'themes': self.theme2.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"themes": 0}) + response = self.get_trek_list({'themes': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_portal_filter(self): - response = self.get_trek_list({"portals": self.portal.pk}) + response = self.get_trek_list({'portals': self.portal.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"portals": 0}) + response = self.get_trek_list({'portals': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_ids_filter(self): - response = self.get_trek_list({"ids": f"{self.treks[0].pk},{self.treks[1].pk}"}) + response = self.get_trek_list({'ids': f"{self.treks[0].pk},{self.treks[1].pk}"}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 2) + self.assertEqual(len(json_response.get('results')), 2) - response = self.get_trek_list({"ids": 99999}) + response = self.get_trek_list({'ids': 99999}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_label_filter(self): - response = self.get_trek_list({"labels": self.label.pk}) + response = self.get_trek_list({'labels': self.label.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"labels": 0}) + response = self.get_trek_list({'labels': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_labels_exclude_filter(self): - response = self.get_trek_list({"labels_exclude": self.label.pk}) + response = self.get_trek_list({'labels_exclude': self.label.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 18) + self.assertEqual(len(json_response.get('results')), 18) trek = trek_factory.TrekFactory.create() label = common_factory.LabelFactory.create() trek.labels.add(label, self.label) - response = self.get_trek_list({"labels_exclude": self.label.pk}) + response = self.get_trek_list({'labels_exclude': self.label.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 18) + self.assertEqual(len(json_response.get('results')), 18) trek = trek_factory.TrekFactory.create() label_2 = common_factory.LabelFactory.create() trek.labels.add(label, label_2) - response = self.get_trek_list({"labels_exclude": f"{self.label.pk},{label.pk}"}) + response = self.get_trek_list({'labels_exclude': f'{self.label.pk},{label.pk}'}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 18) + self.assertEqual(len(json_response.get('results')), 18) - response = self.get_trek_list({"labels_exclude": label_2.pk}) + response = self.get_trek_list({'labels_exclude': label_2.pk}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 20) + self.assertEqual(len(json_response.get('results')), 20) def test_trek_city_filter(self): path = core_factory.PathFactory.create(geom=LineString((-10, -9), (-9, -9))) - city3 = zoning_factory.CityFactory( - code="03000", - geom="SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, -9 -10, -10 -10)))", - ) + city3 = zoning_factory.CityFactory(code='03000', + geom='SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, -9 -10, -10 -10)))') if settings.TREKKING_TOPOLOGY_ENABLED: trek_factory.TrekFactory.create(paths=[(path, 0, 1)]) else: - trek_factory.TrekFactory.create(geom="SRID=2154;LINESTRING(-10 -9, -9 -9)") - response = self.get_trek_list({"cities": city3.pk}) + trek_factory.TrekFactory.create(geom='SRID=2154;LINESTRING(-10 -9, -9 -9)') + response = self.get_trek_list({'cities': city3.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"cities": 0}) + response = self.get_trek_list({'cities': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_district_filter(self): path = core_factory.PathFactory.create(geom=LineString((-10, -9), (-9, -9))) - dist3 = zoning_factory.DistrictFactory( - geom="SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, " - "-9 -10, -10 -10)))" - ) + dist3 = zoning_factory.DistrictFactory(geom='SRID=2154;MULTIPOLYGON(((-10 -10, -10 -9, -9 -9, ' + '-9 -10, -10 -10)))') if settings.TREKKING_TOPOLOGY_ENABLED: trek_factory.TrekFactory.create(paths=[(path, 0, 1)]) else: - trek_factory.TrekFactory.create(geom="SRID=2154;LINESTRING(-10 -9, -9 -9)") - response = self.get_trek_list({"districts": dist3.pk}) + trek_factory.TrekFactory.create(geom='SRID=2154;LINESTRING(-10 -9, -9 -9)') + response = self.get_trek_list({'districts': dist3.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"districts": 0}) + response = self.get_trek_list({'districts': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_structure_filter(self): - response = self.get_trek_list({"structures": self.structure.pk}) + response = self.get_trek_list({'structures': self.structure.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"cities": 0}) + response = self.get_trek_list({'cities': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_practice_filter(self): - response = self.get_trek_list({"practices": self.practice.pk}) + response = self.get_trek_list({'practices': self.practice.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"practices": 0}) + response = self.get_trek_list({'practices': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_accessibility_level_filter(self): - response = self.get_trek_list( - {"accessibility_level": self.accessibility_level.pk} - ) + response = self.get_trek_list({'accessibility_level': self.accessibility_level.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"accessibility_level": 0}) + response = self.get_trek_list({'accessibility_level': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_routes_filter(self): - response = self.get_trek_list({"routes": self.route.pk}) + response = self.get_trek_list({'routes': self.route.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"routes": 0}) + response = self.get_trek_list({'routes': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_ratings_filter(self): - response = self.get_trek_list({"ratings": self.rating.pk}) + response = self.get_trek_list({'ratings': self.rating.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) - response = self.get_trek_list({"ratings": 0}) + response = self.get_trek_list({'ratings': 0}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_version_route(self): response = self.client.get("/api/v2/version") self.assertEqual(response.status_code, 200) - self.assertJSONEqual(response.content, {"version": __version__}) + self.assertJSONEqual(response.content, {'version': __version__}) @override_settings(DEBUG=False) def test_handle_404_route(self): response = self.client.get("/api/v2/x") self.assertEqual(response.status_code, 404) - self.assertJSONEqual(response.content, {"page": "does not exist"}) + self.assertJSONEqual(response.content, {'page': 'does not exist'}) def test_trek_list_filter_distance(self): - """Test Trek list is filtered by reference point distance""" - toulouse_trek_geom = LineString( + """ Test Trek list is filtered by reference point distance """ + toulouse_trek_geom = LineString([ [ - [1.4464187622070312, 43.65147866566022], - [1.435432434082031, 43.63682057801007], - [1.4574050903320312, 43.62439567002734], - [1.4426422119140625, 43.601775746067986], - [1.473541259765625, 43.58810023846608], + 1.4464187622070312, + 43.65147866566022 ], - srid=4326, - ) + [ + 1.435432434082031, + 43.63682057801007 + ], + [ + 1.4574050903320312, + 43.62439567002734 + ], + [ + 1.4426422119140625, + 43.601775746067986 + ], + [ + 1.473541259765625, + 43.58810023846608 + ]], srid=4326) toulouse_trek_geom.transform(2154) path_trek = core_factory.PathFactory(geom=toulouse_trek_geom) - trek_toulouse = trek_factory.TrekFactory( - paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom - ) + trek_toulouse = trek_factory.TrekFactory(paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom) # trek is in non filtered list response = self.get_trek_list() # json collection structure is ok json_response = response.json() - ids_treks = [element["id"] for element in json_response["results"]] + ids_treks = [element['id'] for element in json_response['results']] self.assertIn(trek_toulouse.pk, ids_treks, ids_treks) # test trek is in distance filter (< 110 km) - response = self.get_trek_list( - { - "dist": "110000", - "point": f"{self.reference_point.x},{self.reference_point.y}", - } - ) + response = self.get_trek_list({ + 'dist': '110000', + 'point': f"{self.reference_point.x},{self.reference_point.y}", + }) # json collection structure is ok json_response = response.json() - ids_treks = [element["id"] for element in json_response["results"]] + ids_treks = [element['id'] for element in json_response['results']] self.assertIn(trek_toulouse.pk, ids_treks) # test trek is not in distance filter (< 50km) - response = self.get_trek_list( - { - "dist": "50000", - "point": f"{self.reference_point.x},{self.reference_point.x}", - } - ) + response = self.get_trek_list({ + 'dist': '50000', + 'point': f"{self.reference_point.x},{self.reference_point.x}", + }) # json collection structure is ok json_response = response.json() - ids_treks = [element["id"] for element in json_response["results"]] + ids_treks = [element['id'] for element in json_response['results']] self.assertNotIn(trek_toulouse.pk, ids_treks) def test_trek_list_filter_in_bbox(self): - """Test Trek list is filtered by bbox param""" - toulouse_trek_geom = LineString( + """ Test Trek list is filtered by bbox param """ + toulouse_trek_geom = LineString([ [ - [1.4464187622070312, 43.65147866566022], - [1.435432434082031, 43.63682057801007], - [1.4574050903320312, 43.62439567002734], - [1.4426422119140625, 43.601775746067986], - [1.473541259765625, 43.58810023846608], + 1.4464187622070312, + 43.65147866566022 ], - srid=4326, - ) + [ + 1.435432434082031, + 43.63682057801007 + ], + [ + 1.4574050903320312, + 43.62439567002734 + ], + [ + 1.4426422119140625, + 43.601775746067986 + ], + [ + 1.473541259765625, + 43.58810023846608 + ]], srid=4326) toulouse_trek_geom.transform(2154) path_trek = core_factory.PathFactory(geom=toulouse_trek_geom) - trek_toulouse = trek_factory.TrekFactory( - paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom - ) + trek_toulouse = trek_factory.TrekFactory(paths=[(path_trek, 0, 1)], geom=toulouse_trek_geom) trek_toulouse.geom.buffer(10) trek_toulouse.geom.transform(4326) xmin, ymin, xmax, ymax = trek_toulouse.geom.extent # test pois is in bbox filter - response = self.get_trek_list( - { - "in_bbox": f"{xmin},{ymin},{xmax},{ymax}", - } - ) + response = self.get_trek_list({ + 'in_bbox': f'{xmin},{ymin},{xmax},{ymax}', + }) # json collection structure is ok json_response = response.json() - ids_treks = [element["id"] for element in json_response["results"]] + ids_treks = [element['id'] for element in json_response['results']] self.assertIn(trek_toulouse.pk, ids_treks) # test trek is not in distance filter (< 50km) - response = self.get_trek_list( - { - "in_bbox": f"{0.0},{0.0},{1.0},{1.0}", - } - ) + response = self.get_trek_list({ + 'in_bbox': f'{0.0},{0.0},{1.0},{1.0}', + }) # json collection structure is ok json_response = response.json() - ids_treks = [element["id"] for element in json_response["results"]] + ids_treks = [element['id'] for element in json_response['results']] self.assertNotIn(trek_toulouse.pk, ids_treks) def test_trek_list_filtered_by_near_trek(self): @@ -1729,51 +1251,43 @@ def test_trek_list_filtered_by_near_trek(self): self.assertEqual(json_response["count"], 16) def test_trek_list_filters_inexistant_zones(self): - response = self.get_trek_list( - { - "cities": "99999", - "districts": "999", - } - ) + response = self.get_trek_list({ + 'cities': '99999', + 'districts': '999', + }) # test response code self.assertEqual(response.status_code, 200) # json collection structure is ok json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_trek_city(self): - response = self.get_trek_list({"cities": self.city.pk}) - self.assertEqual(len(response.json()["results"]), 17) + response = self.get_trek_list({'cities': self.city.pk}) + self.assertEqual(len(response.json()['results']), 17) def test_trek_district(self): - response = self.get_trek_list({"districts": self.district.pk}) - self.assertEqual(len(response.json()["results"]), 17) + response = self.get_trek_list({'districts': self.district.pk}) + self.assertEqual(len(response.json()['results']), 17) def test_trek_cities(self): - response = self.get_trek_list({"cities": f"{self.city.pk},{self.city2.pk}"}) - self.assertEqual(len(response.json()["results"]), 17) + response = self.get_trek_list({'cities': f"{self.city.pk},{self.city2.pk}"}) + self.assertEqual(len(response.json()['results']), 17) def test_trek_districts(self): - response = self.get_trek_list( - {"districts": f"{self.district.pk},{self.district2.pk}"} - ) - self.assertEqual(len(response.json()["results"]), 17) + response = self.get_trek_list({'districts': f"{self.district.pk},{self.district2.pk}"}) + self.assertEqual(len(response.json()['results']), 17) def test_trek_ratings(self): - response = self.get_trek_list( - {"ratings": f"{self.rating.pk},{self.rating2.pk}"} - ) - self.assertEqual(len(response.json()["results"]), 2) + response = self.get_trek_list({'ratings': f"{self.rating.pk},{self.rating2.pk}"}) + self.assertEqual(len(response.json()['results']), 2) def test_trek_child_not_published_detail_view_ok_if_ancestor_published(self): response = self.get_trek_detail(self.child1.pk) self.assertEqual(response.status_code, 200) - def test_trek_child_not_published_detail_view_ko_if_ancestor_published_not_in_requested_language( - self, - ): - response = self.get_trek_detail(self.child1.pk, {"language": "fr"}) + def test_trek_child_not_published_detail_view_ko_if_ancestor_published_not_in_requested_language(self): + response = self.get_trek_detail(self.child1.pk, {'language': 'fr'}) self.assertEqual(response.status_code, 404) def test_trek_child_not_published_detail_view_ko_if_ancestor_not_published(self): @@ -1781,7 +1295,7 @@ def test_trek_child_not_published_detail_view_ko_if_ancestor_not_published(self) self.assertEqual(response.status_code, 404) def test_trek_child_not_published_not_in_list_view_if_ancestor_published(self): - response = self.get_trek_list({"fields": "id"}) + response = self.get_trek_list({'fields': 'id'}) self.assertNotContains(response, str(self.child1.pk)) def test_tour_list(self): @@ -1791,38 +1305,30 @@ def test_tour_list(self): # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_JSON_STRUCTURE) # trek count is ok - self.assertEqual(len(json_response.get("results")), 2) # Two parents + self.assertEqual(len(json_response.get('results')), 2) # Two parents # regenrate with geojson - response = self.get_tour_list({"format": "geojson"}) + response = self.get_tour_list({'format': 'geojson'}) json_response = response.json() # test geojson format self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual(len(json_response.get("features")), 2) + self.assertEqual(len(json_response.get('features')), 2) # test dim 3 ok - self.assertEqual( - len(json_response.get("features")[0].get("geometry").get("coordinates")[0]), - 3, - json_response.get("features")[0].get("geometry").get("coordinates")[0], - ) + self.assertEqual(len(json_response.get('features')[0].get('geometry').get('coordinates')[0]), + 3, json_response.get('features')[0].get('geometry').get('coordinates')[0]) - self.assertEqual( - sorted(json_response.get("features")[0].keys()), GEOJSON_STRUCTURE - ) + self.assertEqual(sorted(json_response.get('features')[0].keys()), GEOJSON_STRUCTURE) - self.assertEqual( - sorted(json_response.get("features")[0].get("properties").keys()), - TOUR_PROPERTIES_GEOJSON_STRUCTURE, - ) + self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), + TOUR_PROPERTIES_GEOJSON_STRUCTURE) - self.assertEqual( - json_response.get("features")[1].get("properties").get("count_children"), 1 - ) + self.assertEqual(json_response.get('features')[1].get('properties').get('count_children'), 1) @override_settings(ONLY_EXTERNAL_PUBLIC_PDF=True) def test_trek_external_pdf(self): @@ -1840,38 +1346,29 @@ def test_trek_detail_categories_split_practice(self): self.assertEqual(response.status_code, 200) def test_trek_detail_with_lang(self): - response = self.get_trek_list({"language": "en"}) + response = self.get_trek_list({'language': 'en'}) self.assertEqual(response.status_code, 200) - self.assertEqual( - response.json()["results"][0]["pdf"], - f"http://testserver/api/en/treks/{self.child2.pk}/child-2.pdf", - ) + self.assertEqual(response.json()['results'][0]['pdf'], + f'http://testserver/api/en/treks/{self.child2.pk}/child-2.pdf') def test_trek_detail_img_src_are_completed_in_descriptions(self): response = self.get_trek_detail(self.treks[0].pk) self.assertEqual(response.status_code, 200) # Note that tags are sorted and the HTML format slightly changed during the "src" processing. - expected_description = ( - "

Some HTML content with images

" - 'Descent' - '' - ) - self.assertEqual(response.json()["description"]["en"], expected_description) - self.assertEqual( - response.json()["description_teaser"]["en"], expected_description - ) - self.assertEqual(response.json()["ambiance"]["en"], expected_description) + expected_description = '

Some HTML content with images

'\ + 'Descent'\ + '' + self.assertEqual(response.json()['description']['en'], expected_description) + self.assertEqual(response.json()['description_teaser']['en'], expected_description) + self.assertEqual(response.json()['ambiance']['en'], expected_description) # Same test requesting a specific language - response = self.get_trek_detail(self.treks[0].pk, params={"language": "en"}) + response = self.get_trek_detail(self.treks[0].pk, params={'language': 'en'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["description"], expected_description) - self.assertEqual(response.json()["description_teaser"], expected_description) - self.assertEqual(response.json()["ambiance"], expected_description) - self.assertEqual( - response.json()["view_points"][0]["geometry"], - {"type": "Point", "coordinates": [-1.3630812, -5.9838563]}, - ) + self.assertEqual(response.json()['description'], expected_description) + self.assertEqual(response.json()['description_teaser'], expected_description) + self.assertEqual(response.json()['ambiance'], expected_description) + self.assertEqual(response.json()['view_points'][0]['geometry'], {'type': 'Point', 'coordinates': [-1.3630812, -5.9838563]}) def test_difficulty_list(self): response = self.get_difficulties_list() @@ -1890,7 +1387,7 @@ def test_practice_detail(self): self.assertEqual(response.status_code, 200) def test_network_list(self): - response = self.get_networks_list({"portals": self.portal.pk}) + response = self.get_networks_list({'portals': self.portal.pk}) self.assertContains(response, self.network.network) def test_network_detail(self): @@ -1898,7 +1395,7 @@ def test_network_detail(self): self.assertEqual(response.status_code, 200) def test_theme_list(self): - response = self.get_themes_list({"portals": self.portal.pk}) + response = self.get_themes_list({'portals': self.portal.pk}) self.assertContains(response, self.theme.label) self.assertContains(response, self.theme3.label) @@ -1909,125 +1406,141 @@ def test_theme_list_filter_portal(self): trek.themes.add(self.theme) trek.save() # Ok because the trek is published - response = self.get_themes_list({"portals": portal2.pk}) + response = self.get_themes_list({'portals': portal2.pk}) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 1) + self.assertEqual(len(json_response.get('results')), 1) trek.published = False trek.save() # No theme should be returned because the trek is not published anymore - response = self.get_themes_list({"portals": portal2.pk}) + response = self.get_themes_list({'portals': portal2.pk}) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) trek.published = True trek.deleted = True trek.save() # No theme should be returned because the published trek on this portal is deleted - response = self.get_themes_list({"portals": portal2.pk}) + response = self.get_themes_list({'portals': portal2.pk}) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 0) + self.assertEqual(len(json_response.get('results')), 0) def test_city_list(self): - self.check_number_elems_response(self.get_city_list(), zoning_models.City) + self.check_number_elems_response( + self.get_city_list(), + zoning_models.City + ) def test_city_detail(self): self.check_structure_response( - self.get_city_detail(self.city.pk), CITY_PROPERTIES_JSON_STRUCTURE + self.get_city_detail(self.city.pk), + CITY_PROPERTIES_JSON_STRUCTURE ) def test_district_list(self): self.check_number_elems_response( - self.get_district_list(), zoning_models.District + self.get_district_list(), + zoning_models.District ) def test_district_detail(self): self.check_structure_response( self.get_district_detail(self.district.pk), - DISTRICT_PROPERTIES_JSON_STRUCTURE, + DISTRICT_PROPERTIES_JSON_STRUCTURE ) def test_route_list(self): - self.check_number_elems_response(self.get_route_list(), trek_models.Route) + self.check_number_elems_response( + self.get_route_list(), + trek_models.Route + ) def test_sector_detail(self): self.check_structure_response( self.get_sector_detail(self.sector.pk), - OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE, + OUTDOOR_SECTOR_PROPERTIES_JSON_STRUCTURE ) def test_sector_list(self): - self.check_number_elems_response(self.get_sector_list(), outdoor_models.Sector) + self.check_number_elems_response( + self.get_sector_list(), + outdoor_models.Sector + ) def test_hdviewpoint_detail(self): self.check_structure_response( self.get_hdviewpoint_detail(self.hdviewpoint_trek.pk), - HDVIEWPOINT_DETAIL_JSON_STRUCTURE, + HDVIEWPOINT_DETAIL_JSON_STRUCTURE ) def test_hdviewpoint_list(self): self.check_number_elems_response( - self.get_hdviewpoint_list(), common_models.HDViewPoint + self.get_hdviewpoint_list(), + common_models.HDViewPoint ) def test_route_detail(self): self.check_structure_response( - self.get_route_detail(self.route.pk), ROUTE_PROPERTIES_JSON_STRUCTURE + self.get_route_detail(self.route.pk), + ROUTE_PROPERTIES_JSON_STRUCTURE ) def test_accessibility_list(self): self.check_number_elems_response( - self.get_accessibility_list(), trek_models.Accessibility + self.get_accessibility_list(), + trek_models.Accessibility ) def test_accessibility_level_list(self): self.check_number_elems_response( - self.get_accessibility_level_list(), trek_models.AccessibilityLevel + self.get_accessibility_level_list(), + trek_models.AccessibilityLevel ) def test_accessibility_detail(self): self.check_structure_response( self.get_accessibility_detail(self.accessibility.pk), - ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE, + ACCESSIBILITY_PROPERTIES_JSON_STRUCTURE ) def test_accessibility_level_detail(self): self.check_structure_response( self.get_accessibility_level_detail(self.accessibility_level.pk), - ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE, + ACCESSIBILITY_LEVEL_PROPERTIES_JSON_STRUCTURE ) def test_theme_detail(self): self.check_structure_response( - self.get_themes_detail(self.theme2.pk), THEME_PROPERTIES_JSON_STRUCTURE + self.get_themes_detail(self.theme2.pk), + THEME_PROPERTIES_JSON_STRUCTURE ) def test_portal_list(self): self.check_number_elems_response( - self.get_portal_list(), common_models.TargetPortal + self.get_portal_list(), + common_models.TargetPortal ) def test_portal_detail(self): self.check_structure_response( self.get_portal_detail(self.portal.pk), - TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE, + TARGET_PORTAL_PROPERTIES_JSON_STRUCTURE ) def test_structure_list(self): self.check_number_elems_response( - self.get_structure_list(), authent_models.Structure + self.get_structure_list(), + authent_models.Structure ) def test_structure_filter_list(self): - response = self.get_structure_list( - {"portals": self.portal.pk, "language": "en"} - ) - self.assertEquals(len(response.json()["results"]), 1) + response = self.get_structure_list({'portals': self.portal.pk, 'language': 'en'}) + self.assertEquals(len(response.json()['results']), 1) def test_structure_detail(self): self.check_structure_response( self.get_structure_detail(self.structure.pk), - STRUCTURE_PROPERTIES_JSON_STRUCTURE, + STRUCTURE_PROPERTIES_JSON_STRUCTURE ) def test_service_list(self): @@ -2035,77 +1548,72 @@ def test_service_list(self): json_response = response.json() self.assertEqual(response.status_code, 200) services = trek_models.Service.objects.all() - self.assertEquals( - len(json_response["results"]), - services.count() - 1, - services.filter(type__published=True).count(), - ) + self.assertEquals(len(json_response['results']), services.count() - 1, services.filter(type__published=True).count()) def test_service_detail(self): self.check_structure_response( - self.get_service_detail(self.service.pk), SERVICE_DETAIL_JSON_STRUCTURE + self.get_service_detail(self.service.pk), + SERVICE_DETAIL_JSON_STRUCTURE ) def test_infrastructure_list(self): self.check_number_elems_response( - self.get_infrastructure_list(), infrastructure_models.Infrastructure + self.get_infrastructure_list(), + infrastructure_models.Infrastructure ) def test_infrastructure_detail(self): self.check_structure_response( self.get_infrastructure_detail(self.infrastructure.pk), - INFRASTRUCTURE_DETAIL_JSON_STRUCTURE, + INFRASTRUCTURE_DETAIL_JSON_STRUCTURE ) def test_infrastructuretype_list(self): self.check_number_elems_response( - self.get_infrastructuretype_list(), infrastructure_models.InfrastructureType + self.get_infrastructuretype_list(), + infrastructure_models.InfrastructureType ) def test_infrastructuretype_detail(self): self.check_structure_response( self.get_infrastructuretype_detail(self.infrastructure_type.pk), - INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE, + INFRASTRUCTURE_TYPE_DETAIL_JSON_STRUCTURE ) def test_infrastructurecondition_list(self): self.check_number_elems_response( self.get_infrastructurecondition_list(), - infrastructure_models.InfrastructureCondition, + infrastructure_models.InfrastructureCondition ) def test_infrastructurecondition_detail(self): self.check_structure_response( self.get_infrastructurecondition_detail(self.infrastructure_condition.pk), - INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE, + INFRASTRUCTURE_CONDITION_DETAIL_JSON_STRUCTURE ) def test_infrastructuremaintenancedifficulty_list(self): self.check_number_elems_response( self.get_infrastructuremaintenancedifficulty_list(), - infrastructure_models.InfrastructureMaintenanceDifficultyLevel, + infrastructure_models.InfrastructureMaintenanceDifficultyLevel ) def test_infrastructuremaintenancedifficulty_detail(self): self.check_structure_response( - self.get_infrastructuremaintenancedifficulty_detail( - self.infrastructure_maintenancedifficulty.pk - ), - INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE, + self.get_infrastructuremaintenancedifficulty_detail(self.infrastructure_maintenancedifficulty.pk), + INFRASTRUCTURE_MAINTENANCE_DIFFICULTY_DETAIL_JSON_STRUCTURE ) def test_infrastructureusagedifficulty_list(self): self.check_number_elems_response( self.get_infrastructureusagedifficulty_list(), - infrastructure_models.InfrastructureUsageDifficultyLevel, + infrastructure_models.InfrastructureUsageDifficultyLevel ) def test_infrastructureusagedifficulty_detail(self): self.check_structure_response( - self.get_infrastructureusagedifficulty_detail( - self.infrastructure_usagedifficulty.pk - ), - INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE, + self.get_infrastructureusagedifficulty_detail(self.infrastructure_usagedifficulty.pk), + INFRASTRUCTURE_USAGE_DIFFICULTY_DETAIL_JSON_STRUCTURE ) def test_servicetype_list(self): @@ -2113,85 +1621,88 @@ def test_servicetype_list(self): json_response = response.json() self.assertEqual(response.status_code, 200) services = trek_models.ServiceType.objects.all() - self.assertEquals( - len(json_response["results"]), - services.count() - 1, - services.filter(published=True).count(), - ) + self.assertEquals(len(json_response['results']), services.count() - 1, services.filter(published=True).count()) def test_servicetype_detail(self): self.check_structure_response( self.get_servicetype_detail(self.service_type.pk), - SERVICE_TYPE_DETAIL_JSON_STRUCTURE, + SERVICE_TYPE_DETAIL_JSON_STRUCTURE ) def test_signage_detail(self): self.check_structure_response( - self.get_signage_detail(self.signage.pk), SIGNAGE_DETAIL_JSON_STRUCTURE + self.get_signage_detail(self.signage.pk), + SIGNAGE_DETAIL_JSON_STRUCTURE ) def test_signage_list(self): self.check_number_elems_response( - self.get_signage_list(), signage_models.Signage + self.get_signage_list(), + signage_models.Signage ) def test_signagetype_list(self): self.check_number_elems_response( - self.get_signagetype_list(), signage_models.SignageType + self.get_signagetype_list(), + signage_models.SignageType ) def test_signagetype_detail(self): self.check_structure_response( self.get_signagetype_detail(self.signagetype.pk), - SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE, + SIGNAGE_TYPE_DETAIL_JSON_STRUCTURE ) def test_signagebladetype_list(self): self.check_number_elems_response( - self.get_signagebladetype_list(), signage_models.BladeType + self.get_signagebladetype_list(), + signage_models.BladeType ) def test_signagebladetype_detail(self): self.check_structure_response( self.get_signagebladetype_detail(self.bladetype.pk), - SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE, + SIGNAGE_BLADE_TYPE_DETAIL_JSON_STRUCTURE ) def test_signagesealing_list(self): self.check_number_elems_response( - self.get_signagesealing_list(), signage_models.Sealing + self.get_signagesealing_list(), + signage_models.Sealing ) def test_signagesealing_detail(self): self.check_structure_response( self.get_signagesealing_detail(self.sealing.pk), - SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE, + SIGNAGE_SEALING_DETAIL_JSON_STRUCTURE ) def test_signagecolor_list(self): self.check_number_elems_response( - self.get_signagecolor_list(), signage_models.Color + self.get_signagecolor_list(), + signage_models.Color ) def test_signagecolor_detail(self): self.check_structure_response( self.get_signagecolor_detail(self.color.pk), - SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE, + SIGNAGE_BLADE_COLOR_DETAIL_JSON_STRUCTURE ) def test_signagedirection_list(self): self.check_number_elems_response( - self.get_signagedirection_list(), signage_models.Direction + self.get_signagedirection_list(), + signage_models.Direction ) def test_signagedirection_detail(self): self.check_structure_response( self.get_signagedirection_detail(self.direction.pk), - SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE, + SIGNAGE_DIRECTION_DETAIL_JSON_STRUCTURE ) def test_service_types_filter(self): - response = self.get_service_list({"types": self.service_type.pk}) + response = self.get_service_list({'types': self.service_type.pk}) self.assertEqual(response.json().get("count"), 1) def test_poi_list(self): @@ -2201,45 +1712,34 @@ def test_poi_list(self): # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_JSON_STRUCTURE) # trek count is ok - self.assertEqual( - len(json_response.get("results")), trek_models.POI.objects.all().count() - ) + self.assertEqual(len(json_response.get('results')), + trek_models.POI.objects.all().count()) # regenerate with geojson 3D - response = self.get_poi_list({"format": "geojson"}) + response = self.get_poi_list({'format': 'geojson'}) json_response = response.json() # test geojson format - self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual( - len(json_response.get("features")), trek_models.POI.objects.all().count() - ) + self.assertEqual(len(json_response.get('features')), + trek_models.POI.objects.all().count()) # test dim 3 - self.assertEqual( - len(json_response.get("features")[0].get("geometry").get("coordinates")), 3 - ) + self.assertEqual(len(json_response.get('features')[0].get('geometry').get('coordinates')), + 3) - self.assertEqual( - sorted(json_response.get("features")[0].keys()), GEOJSON_STRUCTURE - ) + self.assertEqual(sorted(json_response.get('features')[0].keys()), + GEOJSON_STRUCTURE) - self.assertEqual( - sorted(json_response.get("features")[0].get("properties").keys()), - POI_PROPERTIES_GEOJSON_STRUCTURE, - ) + self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), + POI_PROPERTIES_GEOJSON_STRUCTURE) - response = self.get_poi_list( - { - "types": self.poi_type.pk, - "trek": self.treks[0].pk, - "sites": self.site.pk, - "courses": self.course.pk, - } - ) + response = self.get_poi_list({'types': self.poi_type.pk, 'trek': self.treks[0].pk, 'sites': self.site.pk, 'courses': self.course.pk}) self.assertEqual(response.status_code, 200) def launch_tests_excluded_pois(self, obj, filter_name): @@ -2248,8 +1748,8 @@ def launch_tests_excluded_pois(self, obj, filter_name): # test response code self.assertEqual(response.status_code, 200) self.assertEqual( - len(json_response.get("results")), - trek_models.POI.objects.all().count() - 1, # 1 excluded POI + len(json_response.get('results')), + trek_models.POI.objects.all().count() - 1 # 1 excluded POI ) obj.pois_excluded.add(self.poi) obj.save() @@ -2259,48 +1759,32 @@ def launch_tests_excluded_pois(self, obj, filter_name): # test response code self.assertEqual(response.status_code, 200) self.assertEqual( - len(json_response.get("results")), - trek_models.POI.objects.all().count() - 2, # 1 excluded POI + len(json_response.get('results')), + trek_models.POI.objects.all().count() - 2 # 1 excluded POI ) def test_poi_list_filter_trek(self): - self.launch_tests_excluded_pois(self.treks[0], "trek") + self.launch_tests_excluded_pois(self.treks[0], 'trek') def test_poi_list_filter_courses(self): - self.launch_tests_excluded_pois(self.course, "courses") + self.launch_tests_excluded_pois(self.course, 'courses') def test_poi_list_filter_sites(self): - self.launch_tests_excluded_pois(self.site, "sites") + self.launch_tests_excluded_pois(self.site, 'sites') def test_poi_list_filtered_by_near_trek(self): if settings.TREKKING_TOPOLOGY_ENABLED: trek = trek_factory.TrekFactory() - trek_factory.POIFactory( - paths=[(trek.paths.first(), 0.5, 0.5)], name="a POI near trek" - ) + trek_factory.POIFactory(paths=[(trek.paths.first(), 0.5, 0.5)], name="a POI near trek") far_away_coords = [[n + 2000 for n in c] for c in trek.geom.coords] - far_away_path = core_factory.PathFactory( - geom=LineString(far_away_coords, srid=settings.SRID) - ) - trek_factory.POIFactory( - paths=[far_away_path, 0.5, 0.5], name="a POI far from trek" - ) - near_excluded_poi = trek_factory.POIFactory( - paths=[(trek.paths.first(), 0.2, 0.2)] - ) + far_away_path = core_factory.PathFactory(geom=LineString(far_away_coords, srid=settings.SRID)) + trek_factory.POIFactory(paths=[far_away_path, 0.5, 0.5], name="a POI far from trek") + near_excluded_poi = trek_factory.POIFactory(paths=[(trek.paths.first(), 0.2, 0.2)]) else: - trek = trek_factory.TrekFactory( - geom=LineString(Point(500, 600), Point(550, 800), srid=settings.SRID) - ) - trek_factory.POIFactory( - geom=Point(525, 700, srid=settings.SRID), name="a POI near trek" - ) - trek_factory.POIFactory( - geom=Point(2500, 3000, srid=settings.SRID), name="a POI far from trek" - ) - near_excluded_poi = trek_factory.POIFactory( - geom=Point(510, 620, srid=settings.SRID) - ) + trek = trek_factory.TrekFactory(geom=LineString(Point(500, 600), Point(550, 800), srid=settings.SRID)) + trek_factory.POIFactory(geom=Point(525, 700, srid=settings.SRID), name="a POI near trek") + trek_factory.POIFactory(geom=Point(2500, 3000, srid=settings.SRID), name="a POI far from trek") + near_excluded_poi = trek_factory.POIFactory(geom=Point(510, 620, srid=settings.SRID)) trek.pois_excluded.add(near_excluded_poi) for filtername in ["near_trek", "trek"]: @@ -2311,79 +1795,70 @@ def test_poi_list_filtered_by_near_trek(self): json_response = response.json() self.assertEqual(json_response["count"], 1) response_poi = json_response["results"][0] - self.assertEqual( - response_poi["name"][settings.MODELTRANSLATION_DEFAULT_LANGUAGE], - "a POI near trek", - ) + self.assertEqual(response_poi["name"][settings.MODELTRANSLATION_DEFAULT_LANGUAGE], "a POI near trek") def test_poi_list_filter_distance(self): - """Test POI list is filtered by reference point distance""" - geom_path = LineString( - [ - (1.4464187622070312, 43.65147866566022), - (1.435432434082031, 43.63682057801007), - ], - srid=4326, - ) + """ Test POI list is filtered by reference point distance """ + geom_path = LineString([(1.4464187622070312, 43.65147866566022), + (1.435432434082031, 43.63682057801007)], srid=4326) geom_path.transform(2154) pois_path = core_factory.PathFactory(geom=geom_path) - geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) + geom_point_1 = Point(x=1.4464187622070312, + y=43.65147866566022, srid=4326) geom_point_1.transform(2154) - poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) + poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], + geom=geom_point_1) + geom_point_2 = Point(x=1.435432434082031, + y=43.63682057801007, srid=4326) geom_point_2.transform(2154) - poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_2) + poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], + geom=geom_point_2) # pois are in list is in non filtered list response = self.get_poi_list() # json collection structure is ok json_response = response.json() - ids_pois = [element["id"] for element in json_response["results"]] + ids_pois = [element['id'] for element in json_response['results']] self.assertIn(poi_1.pk, ids_pois) self.assertIn(poi_2.pk, ids_pois) # test pois is in distance filter (< 110000 km) - response = self.get_poi_list( - { - "dist": "110000", - "point": f"{self.reference_point.x},{self.reference_point.y}", - } - ) + response = self.get_poi_list({ + 'dist': '110000', + 'point': f"{self.reference_point.x},{self.reference_point.y}", + }) # json collection structure is ok json_response = response.json() - ids_pois = [element["id"] for element in json_response["results"]] + ids_pois = [element['id'] for element in json_response['results']] self.assertIn(poi_1.pk, ids_pois) self.assertIn(poi_2.pk, ids_pois) # test trek is not in distance filter (< 50km) - response = self.get_poi_list( - { - "dist": "50000", - "point": f"{self.reference_point.x},{self.reference_point.x}", - } - ) + response = self.get_poi_list({ + 'dist': '50000', + 'point': f"{self.reference_point.x},{self.reference_point.x}", + }) # json collection structure is ok json_response = response.json() - ids_pois = [element["id"] for element in json_response["results"]] + ids_pois = [element['id'] for element in json_response['results']] self.assertNotIn(poi_1.pk, ids_pois) self.assertNotIn(poi_2.pk, ids_pois) def test_poi_list_filter_in_bbox(self): - """Test POI list is filtered by bbox param""" - geom_path = LineString( - [ - (1.4464187622070312, 43.65147866566022), - (1.435432434082031, 43.63682057801007), - ], - srid=4326, - ) + """ Test POI list is filtered by bbox param """ + geom_path = LineString([(1.4464187622070312, 43.65147866566022), + (1.435432434082031, 43.63682057801007)], srid=4326) geom_path.transform(2154) pois_path = core_factory.PathFactory(geom=geom_path) - geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) + geom_point_1 = Point(x=1.4464187622070312, + y=43.65147866566022, srid=4326) geom_point_1.transform(2154) - poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) + poi_1 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], + geom=geom_point_1) + geom_point_2 = Point(x=1.435432434082031, + y=43.63682057801007, srid=4326) geom_point_2.transform(2154) - poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], geom=geom_point_2) + poi_2 = trek_factory.POIFactory(paths=[(pois_path, 0, 0)], + geom=geom_point_2) test_bbox = LineString(geom_point_1, geom_point_2, srid=2154) test_bbox.buffer(10) @@ -2391,26 +1866,22 @@ def test_poi_list_filter_in_bbox(self): xmin, ymin, xmax, ymax = test_bbox.extent # test pois is in bbox filter - response = self.get_poi_list( - { - "in_bbox": f"{xmin},{ymin},{xmax},{ymax}", - } - ) + response = self.get_poi_list({ + 'in_bbox': f'{xmin},{ymin},{xmax},{ymax}', + }) # json collection structure is ok json_response = response.json() - ids_pois = [element["id"] for element in json_response["results"]] + ids_pois = [element['id'] for element in json_response['results']] self.assertIn(poi_1.pk, ids_pois) self.assertIn(poi_2.pk, ids_pois) # test trek is not in distance filter (< 50km) - response = self.get_poi_list( - { - "in_bbox": f"{0.0},{0.0},{1.0},{1.0}", - } - ) + response = self.get_poi_list({ + 'in_bbox': f'{0.0},{0.0},{1.0},{1.0}', + }) # json collection structure is ok json_response = response.json() - ids_pois = [element["id"] for element in json_response["results"]] + ids_pois = [element['id'] for element in json_response['results']] self.assertNotIn(poi_1.pk, ids_pois) self.assertNotIn(poi_2.pk, ids_pois) @@ -2425,7 +1896,7 @@ def test_poi_published_detail(self): def test_poi_not_published_detail_lang_en(self): id_poi = trek_factory.POIFactory.create(published_fr=True, published=False) - response = self.get_poi_detail(id_poi.pk, {"language": "en"}) + response = self.get_poi_detail(id_poi.pk, {'language': 'en'}) self.assertEqual(response.status_code, 404) def test_poi_not_published_detail(self): @@ -2436,52 +1907,53 @@ def test_poi_not_published_detail(self): def test_touristiccontentcategory_detail(self): self.check_structure_response( self.get_touristiccontentcategory_detail(self.category.pk), - TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE, + TOURISTIC_CONTENT_CATEGORY_DETAIL_JSON_STRUCTURE ) def test_touristiccontentcategory_list(self): json_response = self.get_touristiccontentcategory_list().json() # Get two objects for the two published touristic contents - self.assertEquals(len(json_response["results"]), 2) + self.assertEquals(len(json_response['results']), 2) def test_touristiccontentcategory_list_filter(self): - response = self.get_touristiccontentcategory_list({"portals": self.portal.pk}) - self.assertEquals(len(response.json()["results"]), 1) + response = self.get_touristiccontentcategory_list({'portals': self.portal.pk}) + self.assertEquals(len(response.json()['results']), 1) def test_touristiccontent_detail(self): self.check_structure_response( self.get_touristiccontent_detail(self.content.pk), - TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE, + TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE ) @override_settings(ONLY_EXTERNAL_PUBLIC_PDF=True) def test_touristiccontent_external_pdf(self): self.check_structure_response( self.get_touristiccontent_detail(self.content.pk), - TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE, + TOURISTIC_CONTENT_DETAIL_JSON_STRUCTURE ) def test_touristiccontent_list(self): - """Test Touristic content list access and structure""" + """ Test Touristic content list access and structure """ response = self.get_touristiccontent_list() self.assertEqual(response.status_code, 200) # json collection structure is ok json_response = response.json() - self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_JSON_STRUCTURE) # touristiccontent count is ok - self.assertEqual( - len(json_response.get("results")), - tourism_models.TouristicContent.objects.all().count(), - ) + self.assertEqual(len(json_response.get('results')), + tourism_models.TouristicContent.objects.all().count()) def test_touristiccontent_list_filter_distance(self): - """Test Touristic content list is filtered by reference point distance""" - geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) + """ Test Touristic content list is filtered by reference point distance """ + geom_point_1 = Point(x=1.4464187622070312, + y=43.65147866566022, srid=4326) geom_point_1.transform(2154) tc_1 = tourism_factory.TouristicContentFactory(geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) + geom_point_2 = Point(x=1.435432434082031, + y=43.63682057801007, srid=4326) geom_point_2.transform(2154) tc_2 = tourism_factory.TouristicContentFactory(geom=geom_point_2) @@ -2489,42 +1961,40 @@ def test_touristiccontent_list_filter_distance(self): response = self.get_touristiccontent_list() self.assertEqual(response.status_code, 200) json_response = response.json() - ids = [element["id"] for element in json_response["results"]] + ids = [element['id'] for element in json_response['results']] self.assertIn(tc_1.pk, ids) self.assertIn(tc_2.pk, ids) # test present filtering < 110km - response = self.get_touristiccontent_list( - { - "dist": "110000", - "point": f"{self.reference_point.x},{self.reference_point.y}", - } - ) + response = self.get_touristiccontent_list({ + 'dist': '110000', + 'point': f"{self.reference_point.x},{self.reference_point.y}", + }) json_response = response.json() - ids = [element["id"] for element in json_response["results"]] + ids = [element['id'] for element in json_response['results']] self.assertIn(tc_1.pk, ids) self.assertIn(tc_2.pk, ids) # test present filtering < 50km - response = self.get_touristiccontent_list( - { - "dist": "50000", - "point": f"{self.reference_point.x},{self.reference_point.y}", - } - ) + response = self.get_touristiccontent_list({ + 'dist': '50000', + 'point': f"{self.reference_point.x},{self.reference_point.y}", + }) json_response = response.json() - ids = [element["id"] for element in json_response["results"]] + ids = [element['id'] for element in json_response['results']] self.assertNotIn(tc_1.pk, ids) self.assertNotIn(tc_2.pk, ids) def test_touristiccontent_list_filter_in_bbox(self): - """Test Touristic content list is filtered by bbox""" - geom_point_1 = Point(x=1.4464187622070312, y=43.65147866566022, srid=4326) + """ Test Touristic content list is filtered by bbox """ + geom_point_1 = Point(x=1.4464187622070312, + y=43.65147866566022, srid=4326) geom_point_1.transform(2154) tc_1 = tourism_factory.TouristicContentFactory(geom=geom_point_1) - geom_point_2 = Point(x=1.435432434082031, y=43.63682057801007, srid=4326) + geom_point_2 = Point(x=1.435432434082031, + y=43.63682057801007, srid=4326) geom_point_2.transform(2154) tc_2 = tourism_factory.TouristicContentFactory(geom=geom_point_2) @@ -2534,274 +2004,263 @@ def test_touristiccontent_list_filter_in_bbox(self): xmin, ymin, xmax, ymax = bbox.extent # test present filtering < 110km - response = self.get_touristiccontent_list( - { - "in_bbox": f"{xmin},{ymin},{xmax},{ymax}", - } - ) + response = self.get_touristiccontent_list({ + 'in_bbox': f"{xmin},{ymin},{xmax},{ymax}", + }) json_response = response.json() - ids = [element["id"] for element in json_response["results"]] + ids = [element['id'] for element in json_response['results']] self.assertIn(tc_1.pk, ids) self.assertIn(tc_2.pk, ids) # test present filtering < 50km - response = self.get_touristiccontent_list( - { - "in_bbox": f"{0.0},{0.0},{1.0},{1.0}", - } - ) + response = self.get_touristiccontent_list({ + 'in_bbox': f"{0.0},{0.0},{1.0},{1.0}", + }) json_response = response.json() - ids = [element["id"] for element in json_response["results"]] + ids = [element['id'] for element in json_response['results']] self.assertNotIn(tc_1.pk, ids) self.assertNotIn(tc_2.pk, ids) def test_touristiccontent_near_trek(self): - response = self.get_touristiccontent_list({"near_trek": self.treks[0].pk}) - self.assertEqual(len(response.json()["results"]), 2) + response = self.get_touristiccontent_list({'near_trek': self.treks[0].pk}) + self.assertEqual(len(response.json()['results']), 2) def test_touristiccontent_near_missing_trek(self): - response = self.get_touristiccontent_list({"near_trek": 42666}) - self.assertEqual(len(response.json()["results"]), 0) + response = self.get_touristiccontent_list({'near_trek': 42666}) + self.assertEqual(len(response.json()['results']), 0) def test_touristiccontent_categories(self): - response = self.get_touristiccontent_list( - {"categories": self.content.category.pk} - ) - self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list({'categories': self.content.category.pk}) + self.assertEqual(len(response.json()['results']), 1) def test_touristiccontent_types(self): tct1 = tourism_factory.TouristicContentType1Factory() - response = self.get_touristiccontent_list( - {"types": self.content.type1.all()[0].pk} - ) - self.assertEqual(len(response.json()["results"]), 1) - response = self.get_touristiccontent_list( - {"types": self.content.type2.all()[0].pk} - ) - self.assertEqual(len(response.json()["results"]), 1) - response = self.get_touristiccontent_list( - { - "types": "{},{}".format( - self.content.type1.all()[0].pk, self.content.type2.all()[0].pk - ) - } - ) - self.assertEqual(len(response.json()["results"]), 1) - response = self.get_touristiccontent_list( - {"types": "{},{}".format(self.content.type1.all()[0].pk, tct1.pk)} - ) - self.assertEqual(len(response.json()["results"]), 1) - response = self.get_touristiccontent_list( - {"types": "{},{}".format(self.content.type2.all()[0].pk, tct1.pk)} - ) - self.assertEqual(len(response.json()["results"]), 0) + response = self.get_touristiccontent_list({'types': self.content.type1.all()[0].pk}) + self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list({'types': self.content.type2.all()[0].pk}) + self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list({ + 'types': '{},{}'.format(self.content.type1.all()[0].pk, self.content.type2.all()[0].pk) + }) + self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list({'types': '{},{}'.format(self.content.type1.all()[0].pk, tct1.pk)}) + self.assertEqual(len(response.json()['results']), 1) + response = self.get_touristiccontent_list({'types': '{},{}'.format(self.content.type2.all()[0].pk, tct1.pk)}) + self.assertEqual(len(response.json()['results']), 0) def test_touristiccontent_city(self): - response = self.get_touristiccontent_list({"cities": self.city.pk}) - self.assertEqual(len(response.json()["results"]), 2) + response = self.get_touristiccontent_list({'cities': self.city.pk}) + self.assertEqual(len(response.json()['results']), 2) def test_touristiccontent_inexistant_city(self): - response = self.get_touristiccontent_list({"cities": "99999"}) - self.assertEqual(len(response.json()["results"]), 0) + response = self.get_touristiccontent_list({'cities': '99999'}) + self.assertEqual(len(response.json()['results']), 0) def test_touristiccontent_district(self): - response = self.get_touristiccontent_list({"districts": self.district.pk}) - self.assertEqual(len(response.json()["results"]), 2) + response = self.get_touristiccontent_list({'districts': self.district.pk}) + self.assertEqual(len(response.json()['results']), 2) def test_touristiccontent_inexistant_district(self): - response = self.get_touristiccontent_list({"districts": 99999}) - self.assertEqual(len(response.json()["results"]), 0) + response = self.get_touristiccontent_list({'districts': 99999}) + self.assertEqual(len(response.json()['results']), 0) def test_touristiccontent_structure(self): - response = self.get_touristiccontent_list( - {"structures": self.content.structure.pk} - ) - self.assertEqual(len(response.json()["results"]), 2) + response = self.get_touristiccontent_list({'structures': self.content.structure.pk}) + self.assertEqual(len(response.json()['results']), 2) def test_touristiccontent_theme(self): - response = self.get_touristiccontent_list( - {"themes": self.content.themes.all()[0].pk} - ) - self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list({'themes': self.content.themes.all()[0].pk}) + self.assertEqual(len(response.json()['results']), 1) def test_touristiccontent_portal(self): - response = self.get_touristiccontent_list( - {"portals": self.content.portal.all()[0].pk} - ) - self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list({'portals': self.content.portal.all()[0].pk}) + self.assertEqual(len(response.json()['results']), 1) def test_touristiccontent_label_accessibility(self): - response = self.get_touristiccontent_list( - {"labels_accessibility": self.label_accessibility.pk} - ) - self.assertEqual(len(response.json()["results"]), 1) + response = self.get_touristiccontent_list({'labels_accessibility': self.label_accessibility.pk}) + self.assertEqual(len(response.json()['results']), 1) def test_touristiccontent_q(self): - response = self.get_touristiccontent_list({"q": "Blah CT"}) - self.assertEqual(len(response.json()["results"]), 2) + response = self.get_touristiccontent_list({'q': 'Blah CT'}) + self.assertEqual(len(response.json()['results']), 2) def test_touristiccontent_detail_with_lang(self): - response = self.get_touristiccontent_list({"language": "en"}) + response = self.get_touristiccontent_list({'language': 'en'}) self.assertEqual(response.status_code, 200) - self.assertEqual( - response.json()["results"][0]["pdf"], - f"http://testserver/api/en/touristiccontents/{self.content.pk}/touristic-content.pdf", - ) + self.assertEqual(response.json()['results'][0]['pdf'], + f'http://testserver/api/en/touristiccontents/{self.content.pk}/touristic-content.pdf') def test_labels_accessibility_detail(self): self.check_structure_response( self.get_labelaccessibility_detail(self.label_accessibility.pk), - LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE, + LABEL_ACCESSIBILITY_DETAIL_JSON_STRUCTURE ) def test_labels_accessibility_list(self): self.check_number_elems_response( - self.get_labelaccessibility_list(), tourism_models.LabelAccessibility + self.get_labelaccessibility_list(), + tourism_models.LabelAccessibility ) def test_labels_list(self): - self.check_number_elems_response(self.get_label_list(), common_models.Label) + self.check_number_elems_response( + self.get_label_list(), + common_models.Label + ) def test_labels_filter_filter(self): label_1 = common_factory.LabelFactory.create(filter=False) label_2 = common_factory.LabelFactory.create(filter=True) self.treks[0].labels.add(label_1, label_2) - response = self.get_label_list({"only_filters": True}) + response = self.get_label_list({'only_filters': True}) self.assertEqual(response.json()["count"], 3) - self.assertSetEqual( - {result["id"] for result in response.json()["results"]}, - {self.label.pk, label_2.pk, self.label_3.pk}, - ) - response = self.get_label_list({"only_filters": False}) + self.assertSetEqual({result["id"] for result in response.json()["results"]}, {self.label.pk, label_2.pk, self.label_3.pk}) + response = self.get_label_list({'only_filters': False}) self.assertEqual(response.json()["results"][0]["id"], label_1.pk) self.assertEqual(response.json()["count"], 1) response = self.get_label_list() self.assertEqual(response.json()["count"], 4) - response = self.get_label_list({"only_filters": "None"}) + response = self.get_label_list({'only_filters': 'None'}) self.assertEqual(response.json()["count"], 0) def test_labels_detail(self): self.check_structure_response( - self.get_label_detail(self.label.pk), TREK_LABEL_PROPERTIES_JSON_STRUCTURE + self.get_label_detail(self.label.pk), + TREK_LABEL_PROPERTIES_JSON_STRUCTURE ) def test_filetype_detail(self): self.check_structure_response( self.get_filetype_detail(self.filetype.pk), - FILETYPE_PROPERTIES_JSON_STRUCTURE, + FILETYPE_PROPERTIES_JSON_STRUCTURE ) def test_filetype_list(self): self.check_number_elems_response( - self.get_filetype_list(), common_models.FileType + self.get_filetype_list(), + common_models.FileType ) def test_informationdesk_list(self): self.check_number_elems_response( - self.get_informationdesk_list(), tourism_models.InformationDesk + self.get_informationdesk_list(), + tourism_models.InformationDesk ) def test_informationdesk_detail(self): self.check_structure_response( self.get_informationdesk_detail(self.info_desk.pk), - INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE, + INFORMATION_DESK_PROPERTIES_JSON_STRUCTURE ) def test_informationdesk_filter_trek(self): - response = self.get_informationdesk_list({"trek": self.treks[0].pk}) + response = self.get_informationdesk_list({'trek': self.treks[0].pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.info_desk.pk) - response = self.get_informationdesk_list({"trek": self.parent.pk}) + response = self.get_informationdesk_list({'trek': self.parent.pk}) self.assertEqual(response.json()["count"], 0) def test_infodesk_filter_type(self): - response = self.get_informationdesk_list( - {"types": self.information_desk_type.pk} - ) + response = self.get_informationdesk_list({'types': self.information_desk_type.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.info_desk.pk) def test_infodesk_filter_label_accessibility(self): - response = self.get_informationdesk_list( - {"labels_accessibility": self.label_accessibility.pk} - ) + response = self.get_informationdesk_list({'labels_accessibility': self.label_accessibility.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.info_desk.pk) def test_informationdesk_type_list(self): self.check_number_elems_response( - self.get_informationdesk_type_list(), tourism_models.InformationDeskType + self.get_informationdesk_type_list(), + tourism_models.InformationDeskType ) def test_informationdesk_type_detail(self): self.check_structure_response( self.get_informationdesk_type_detail(self.information_desk_type.pk), - INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE, + INFORMATION_DESK_TYPE_PROPERTIES_JSON_STRUCTURE ) def test_source_list(self): self.check_number_elems_response( - self.get_source_list(), common_models.RecordSource + self.get_source_list(), + common_models.RecordSource ) def test_source_detail(self): self.check_structure_response( - self.get_source_detail(self.source.pk), SOURCE_PROPERTIES_JSON_STRUCTURE + self.get_source_detail(self.source.pk), + SOURCE_PROPERTIES_JSON_STRUCTURE ) def test_reservationsystem_list(self): self.check_number_elems_response( - self.get_reservationsystem_list(), common_models.ReservationSystem + self.get_reservationsystem_list(), + common_models.ReservationSystem ) def test_reservationsystem_list_filter(self): - response = self.get_reservationsystem_list({"portals": self.portal.pk}) + response = self.get_reservationsystem_list({'portals': self.portal.pk}) # Two results : one reservationsystem associated with content2 and the other with trek[0] - self.assertEquals(len(response.json()["results"]), 2) + self.assertEquals(len(response.json()['results']), 2) def test_reservationsystem_detail(self): self.check_structure_response( self.get_reservationsystem_detail(self.reservation_system.pk), - RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE, + RESERVATION_SYSTEM_PROPERTIES_JSON_STRUCTURE ) def test_site_list(self): - self.check_number_elems_response(self.get_site_list(), outdoor_models.Site) + self.check_number_elems_response( + self.get_site_list(), + outdoor_models.Site + ) def test_site_detail(self): self.check_structure_response( - self.get_site_detail(self.site.pk), SITE_PROPERTIES_JSON_STRUCTURE + self.get_site_detail(self.site.pk), + SITE_PROPERTIES_JSON_STRUCTURE ) def test_site_list_filters(self): - response = self.get_site_list({"q": "test string"}) + response = self.get_site_list({ + 'q': 'test string' + }) # test response code self.assertEqual(response.status_code, 200) def test_course_list(self): - self.check_number_elems_response(self.get_course_list(), outdoor_models.Course) + self.check_number_elems_response( + self.get_course_list(), + outdoor_models.Course + ) def test_course_detail(self): self.check_structure_response( - self.get_course_detail(self.course.pk), COURSE_PROPERTIES_JSON_STRUCTURE + self.get_course_detail(self.course.pk), + COURSE_PROPERTIES_JSON_STRUCTURE ) def test_coursetype_list(self): self.check_number_elems_response( - self.get_coursetype_list(), outdoor_models.CourseType + self.get_coursetype_list(), + outdoor_models.CourseType ) def test_coursetype_detail(self): self.check_structure_response( self.get_coursetype_detail(self.coursetype.pk), - COURSETYPE_PROPERTIES_JSON_STRUCTURE, + COURSETYPE_PROPERTIES_JSON_STRUCTURE ) def test_course_list_filters(self): - response = self.get_course_list({"q": "test string"}) + response = self.get_course_list({ + 'q': 'test string' + }) # test response code self.assertEqual(response.status_code, 200) @@ -2810,43 +2269,40 @@ def test_outdoorpractice_list(self): json_response = response.json() self.assertEqual(response.status_code, 200) self.assertEquals( - len(json_response["results"]), - outdoor_models.Practice.objects.filter(sites__published=True) - .distinct() - .count(), + len(json_response['results']), + outdoor_models.Practice.objects.filter(sites__published=True).distinct().count() ) def test_outdoorpractice_detail(self): self.check_structure_response( self.get_outdoorpractice_detail(self.site.practice.pk), - OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE, + OUTDOORPRACTICE_PROPERTIES_JSON_STRUCTURE ) def test_sitetype_list(self): self.check_number_elems_response( - self.get_sitetype_list(), outdoor_models.SiteType + self.get_sitetype_list(), + outdoor_models.SiteType ) def test_sitetype_detail(self): self.check_structure_response( self.get_sitetype_detail(self.site.type.pk), - SITETYPE_PROPERTIES_JSON_STRUCTURE, + SITETYPE_PROPERTIES_JSON_STRUCTURE ) def test_sensitivearea_list(self): self.check_number_elems_response( - self.get_sensitivearea_list(params={"period": "any"}), - sensitivity_models.SensitiveArea, + self.get_sensitivearea_list(params={'period': 'any'}), + sensitivity_models.SensitiveArea ) # Test filters coverage - response = self.get_sensitivearea_list( - { - "trek": self.parent.id, - "period": "1,2,3,10,11,12", - "structure": self.structure.id, - "practice": self.sensitivearea_practice.id, - } - ) + response = self.get_sensitivearea_list({ + 'trek': self.parent.id, + 'period': "1,2,3,10,11,12", + 'structure': self.structure.id, + 'practice': self.sensitivearea_practice.id, + }) self.assertEqual(response.status_code, 200) def test_sensitivearea_list_filtered_by_near_trek(self): @@ -2854,66 +2310,56 @@ def test_sensitivearea_list_filtered_by_near_trek(self): far_away_dist = settings.SENSITIVE_AREA_INTERSECTION_MARGIN * 2 trek_x = 24800 if settings.TREKKING_TOPOLOGY_ENABLED: - trek_path = core_factory.PathFactory( - geom=LineString( - Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID - ) - ) + trek_path = core_factory.PathFactory(geom=LineString(Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID)) trek = trek_factory.TrekFactory(paths=[(trek_path, 0, 1)]) else: - trek = trek_factory.TrekFactory( - geom=LineString( - Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID - ) - ) + trek = trek_factory.TrekFactory(geom=LineString(Point(trek_x, 7800), Point(trek_x, 7900), srid=settings.SRID)) # a sensitive area near it near_area_x1 = trek_x + nearby_dist near_area_x2 = trek_x + nearby_dist + 1000 sensitivity_factory.SensitiveAreaFactory( - geom=f"POLYGON(({near_area_x1} 7800, {near_area_x2} 7800, {near_area_x2} 7900, {near_area_x1} 7900, {near_area_x1} 7800))" + geom=f'POLYGON(({near_area_x1} 7800, {near_area_x2} 7800, {near_area_x2} 7900, {near_area_x1} 7900, {near_area_x1} 7800))' ) # a sensitive area far from it far_area_x1 = trek_x + far_away_dist far_area_x2 = trek_x + far_away_dist + 1000 sensitivity_factory.SensitiveAreaFactory( - geom=f"POLYGON(({far_area_x1} 7800, {far_area_x2} 7800, {far_area_x2} 7900, {far_area_x1} 7900, {far_area_x1} 7800))" + geom=f'POLYGON(({far_area_x1} 7800, {far_area_x2} 7800, {far_area_x2} 7900, {far_area_x1} 7900, {far_area_x1} 7800))' ) - response = self.get_sensitivearea_list( - {"near_trek": trek.pk, "period": "ignore"} - ) + response = self.get_sensitivearea_list({"near_trek": trek.pk, "period": "ignore"}) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()["count"], 1) def test_sensitivearea_detail(self): self.check_structure_response( - self.get_sensitivearea_detail( - self.sensitivearea.pk, params={"period": "any"} - ), - SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE, + self.get_sensitivearea_detail(self.sensitivearea.pk, params={'period': 'any'}), + SENSITIVE_AREA_PROPERTIES_JSON_STRUCTURE ) def test_sensitivearea_practice_list(self): self.check_number_elems_response( - self.get_sensitiveareapractice_list(), sensitivity_models.SportPractice + self.get_sensitiveareapractice_list(), + sensitivity_models.SportPractice ) def test_sensitivearea_practice_detail(self): self.check_structure_response( self.get_sensitiveareapractice_detail(self.sensitivearea_practice.pk), - sorted(["name", "id"]), + sorted(['name', 'id']) ) def test_sensitivearea_species_list(self): self.check_number_elems_response( - self.get_sensitiveareaspecies_list(), sensitivity_models.Species + self.get_sensitiveareaspecies_list(), + sensitivity_models.Species ) def test_sensitivearea_species_detail(self): self.check_structure_response( self.get_sensitiveareaspecies_detail(self.sensitivearea_species.pk), - SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE, + SENSITIVE_AREA_SPECIES_PROPERTIES_JSON_STRUCTURE ) def test_config(self): @@ -2921,89 +2367,91 @@ def test_config(self): self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(sorted(json_response.keys()), ["bbox"]) + self.assertEqual(sorted(json_response.keys()), ['bbox']) def test_organism_list(self): self.check_number_elems_response( - self.get_organism_list(), common_models.Organism + self.get_organism_list(), + common_models.Organism ) def test_organism_detail(self): self.check_structure_response( self.get_organism_detail(self.organism.pk), - ORGANISM_PROPERTIES_JSON_STRUCTURE, + ORGANISM_PROPERTIES_JSON_STRUCTURE ) def test_sensitivearea_distance_list(self): if settings.TREKKING_TOPOLOGY_ENABLED: - p1 = core_factory.PathFactory.create( - geom=LineString((605600, 6650000), (605604, 6650004), srid=2154) - ) + p1 = core_factory.PathFactory.create(geom=LineString((605600, 6650000), (605604, 6650004), srid=2154)) trek = trek_factory.TrekFactory.create( - published=True, name="Parent", paths=[p1] + published=True, + name='Parent', + paths=[p1] ) else: - trek = trek_factory.TrekFactory.create( - geom=LineString((605600, 6650000), (605604, 6650004), srid=2154) - ) + trek = trek_factory.TrekFactory.create(geom=LineString((605600, 6650000), (605604, 6650004), srid=2154)) specy = sensitivity_factory.SpeciesFactory.create(period01=True) sensitivity_factory.SensitiveAreaFactory.create( - geom="SRID=2154;POLYGON((605600 6650000, 605600 6650004, 605604 6650004, 605604 6650000, 605600 6650000))", + geom='SRID=2154;POLYGON((605600 6650000, 605600 6650004, 605604 6650004, 605604 6650000, 605600 6650000))', species=specy, - description="Test", + description="Test" ) sensitivity_factory.SensitiveAreaFactory.create( - geom="SRID=2154;POLYGON((606001 6650501, 606001 6650505, 606005 6650505, 606005 6650501, 606001 6650501))", + geom='SRID=2154;POLYGON((606001 6650501, 606001 6650505, 606005 6650505, 606005 6650501, 606001 6650501))', species=specy, - description="Test 2", + description="Test 2" ) - response = self.get_sensitivearea_list({"trek": trek.id, "period": "1"}) + response = self.get_sensitivearea_list({ + 'trek': trek.id, + 'period': '1' + }) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) + self.assertEqual(response.json()['count'], 1) # validate wrong trek id returns empty list - response = self.get_sensitivearea_list({"trek": 9999}) + response = self.get_sensitivearea_list({ + 'trek': 9999 + }) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 0) + self.assertEqual(response.json()['count'], 0) def test_hdviewpoint_detail_content(self): response = self.get_hdviewpoint_detail(self.hdviewpoint_trek.pk) self.assertEqual(response.status_code, 200) json_response = response.json() self.assertEqual( - json_response.get("picture_tiles_url"), - f"http://testserver/api/hdviewpoint/drf/hdviewpoints/{self.hdviewpoint_trek.pk}/tiles/%7Bz%7D/%7Bx%7D/%7By%7D.png?source=vips", + json_response.get('picture_tiles_url'), + f"http://testserver/api/hdviewpoint/drf/hdviewpoints/{self.hdviewpoint_trek.pk}/tiles/%7Bz%7D/%7Bx%7D/%7By%7D.png?source=vips" ) - json.dumps(json_response.get("annotations")) - self.assertIsNone(json_response.get("site")) - self.assertIsNone(json_response.get("poi")) - self.assertEquals( - json_response.get("trek").get("uuid"), str(self.treks[0].uuid) - ) - self.assertEquals(json_response.get("trek").get("id"), self.treks[0].id) + json.dumps(json_response.get('annotations')) + self.assertIsNone(json_response.get('site')) + self.assertIsNone(json_response.get('poi')) + self.assertEquals(json_response.get('trek').get('uuid'), str(self.treks[0].uuid)) + self.assertEquals(json_response.get('trek').get('id'), self.treks[0].id) def test_hdviewpoint_detail_content_poi(self): response = self.get_hdviewpoint_detail(self.hdviewpoint_poi.pk) self.assertEqual(response.status_code, 200) json_response = response.json() - json.dumps(json_response.get("annotations")) - self.assertIsNone(json_response.get("site")) - self.assertIsNone(json_response.get("trek")) - self.assertEquals(json_response.get("poi").get("uuid"), str(self.poi.uuid)) - self.assertEquals(json_response.get("poi").get("id"), self.poi.id) + json.dumps(json_response.get('annotations')) + self.assertIsNone(json_response.get('site')) + self.assertIsNone(json_response.get('trek')) + self.assertEquals(json_response.get('poi').get('uuid'), str(self.poi.uuid)) + self.assertEquals(json_response.get('poi').get('id'), self.poi.id) def test_hdviewpoint_detail_content_site(self): response = self.get_hdviewpoint_detail(self.hdviewpoint_site.pk) self.assertEqual(response.status_code, 200) json_response = response.json() - json.dumps(json_response.get("annotations")) - self.assertIsNone(json_response.get("poi")) - self.assertIsNone(json_response.get("trek")) - self.assertEquals(json_response.get("site").get("uuid"), str(self.site.uuid)) - self.assertEquals(json_response.get("site").get("id"), self.site.id) + json.dumps(json_response.get('annotations')) + self.assertIsNone(json_response.get('poi')) + self.assertIsNone(json_response.get('trek')) + self.assertEquals(json_response.get('site').get('uuid'), str(self.site.uuid)) + self.assertEquals(json_response.get('site').get('id'), self.site.id) class APIAccessAdministratorTestCase(BaseApiTest): - """TestCase for administrator API profile""" + """ TestCase for administrator API profile """ @classmethod def setUpTestData(cls): @@ -3016,61 +2464,40 @@ def test_path_list(self): response = self.get_path_list() self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(sorted(json_response.keys()), PAGINATED_JSON_STRUCTURE) - self.assertEqual( - len(json_response.get("results")), path_models.Path.objects.all().count() - ) - response = self.get_path_list({"format": "geojson"}) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_JSON_STRUCTURE) + self.assertEqual(len(json_response.get('results')), path_models.Path.objects.all().count()) + response = self.get_path_list({'format': 'geojson'}) json_response = response.json() # test geojson format - self.assertEqual(sorted(json_response.keys()), PAGINATED_GEOJSON_STRUCTURE) + self.assertEqual(sorted(json_response.keys()), + PAGINATED_GEOJSON_STRUCTURE) - self.assertEqual( - len(json_response.get("features")), - path_models.Path.objects.all().count(), - json_response, - ) + self.assertEqual(len(json_response.get('features')), + path_models.Path.objects.all().count(), json_response) # test dim 3 ok - self.assertEqual( - len(json_response.get("features")[0].get("geometry").get("coordinates")[0]), - 3, - ) + self.assertEqual(len(json_response.get('features')[0].get('geometry').get('coordinates')[0]), 3) - self.assertEqual( - sorted(json_response.get("features")[0].get("properties").keys()), - PATH_PROPERTIES_GEOJSON_STRUCTURE, - ) + self.assertEqual(sorted(json_response.get('features')[0].get('properties').keys()), + PATH_PROPERTIES_GEOJSON_STRUCTURE) class APISwaggerTestCase(BaseApiTest): - """TestCase API documentation""" + """ TestCase API documentation """ def test_schema_fields(self): - response = self.client.get("/api/v2/", {"format": "openapi"}) - self.assertContains( - response, - "Filter by a bounding box formatted like W-lng,S-lat,E-lng,N-lat (WGS84).", - ) - self.assertContains( - response, - "Set language for translation. Can be all or a two-letters language code.", - ) - self.assertContains(response, "Filter by minimum difficulty level (id).") - self.assertContains( - response, "Reference point to compute distance (WGS84). Example: lng,lat." - ) - self.assertContains( - response, "Filter by one or more practice id, comma-separated." - ) - self.assertContains( - response, - "Filter by one or more types id, comma-separated. Logical OR for types in the same list, AND for types in different lists.", - ) + response = self.client.get('/api/v2/', {'format': 'openapi'}) + self.assertContains(response, 'Filter by a bounding box formatted like W-lng,S-lat,E-lng,N-lat (WGS84).') + self.assertContains(response, 'Set language for translation. Can be all or a two-letters language code.') + self.assertContains(response, 'Filter by minimum difficulty level (id).') + self.assertContains(response, 'Reference point to compute distance (WGS84). Example: lng,lat.') + self.assertContains(response, 'Filter by one or more practice id, comma-separated.') + self.assertContains(response, 'Filter by one or more types id, comma-separated. Logical OR for types in the same list, AND for types in different lists.') def test_swagger_ui(self): - response = self.client.get("/api/v2/") - self.assertContains(response, "swagger") + response = self.client.get('/api/v2/') + self.assertContains(response, 'swagger') class TrekRatingScaleTestCase(TestCase): @@ -3080,68 +2507,54 @@ def setUpTestData(cls): cls.practice2 = trek_factory.PracticeFactory() cls.practice1.treks.set([trek_factory.TrekFactory()]) cls.practice2.treks.set([trek_factory.TrekFactory()]) - cls.scale1 = trek_factory.RatingScaleFactory(name="AAA", practice=cls.practice1) - cls.scale2 = trek_factory.RatingScaleFactory(name="AAA", practice=cls.practice2) - cls.scale3 = trek_factory.RatingScaleFactory(name="BBB", practice=cls.practice2) + cls.scale1 = trek_factory.RatingScaleFactory(name='AAA', practice=cls.practice1) + cls.scale2 = trek_factory.RatingScaleFactory(name='AAA', practice=cls.practice2) + cls.scale3 = trek_factory.RatingScaleFactory(name='BBB', practice=cls.practice2) def test_list(self): - response = self.client.get("/api/v2/trek_ratingscale/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 3, - "next": None, - "previous": None, - "results": [ - { - "id": self.scale1.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "practice": self.practice1.pk, - }, - { - "id": self.scale2.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "practice": self.practice2.pk, - }, - { - "id": self.scale3.pk, - "name": {"en": "BBB", "es": None, "fr": None, "it": None}, - "practice": self.practice2.pk, - }, - ], - }, - ) + response = self.client.get('/api/v2/trek_ratingscale/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + 'count': 3, + 'next': None, + 'previous': None, + 'results': [{ + 'id': self.scale1.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice1.pk, + }, { + 'id': self.scale2.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice2.pk, + }, { + 'id': self.scale3.pk, + 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice2.pk, + }] + }) def test_detail(self): - response = self.client.get( - "/api/v2/trek_ratingscale/{}/".format(self.scale1.pk) - ) + response = self.client.get('/api/v2/trek_ratingscale/{}/'.format(self.scale1.pk)) self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "id": self.scale1.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "practice": self.practice1.pk, - }, - ) + self.assertJSONEqual(response.content, { + 'id': self.scale1.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice1.pk, + }) def test_filter_q(self): - response = self.client.get("/api/v2/trek_ratingscale/", {"q": "A"}) + response = self.client.get('/api/v2/trek_ratingscale/', {'q': 'A'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for scale in response.json()["results"]: - self.assertEqual(scale["name"]["en"], "AAA") + self.assertEqual(response.json()['count'], 2) + for scale in response.json()['results']: + self.assertEqual(scale['name']['en'], 'AAA') def test_filter_practice(self): - response = self.client.get( - "/api/v2/trek_ratingscale/", {"practices": self.practice2.pk} - ) + response = self.client.get('/api/v2/trek_ratingscale/', {'practices': self.practice2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for scale in response.json()["results"]: - self.assertEqual(scale["practice"], self.practice2.pk) + self.assertEqual(response.json()['count'], 2) + for scale in response.json()['results']: + self.assertEqual(scale['practice'], self.practice2.pk) class OutdoorRatingScaleTestCase(TestCase): @@ -3151,88 +2564,68 @@ def setUpTestData(cls): cls.practice2 = outdoor_factory.PracticeFactory() cls.practice1.sites.set([outdoor_factory.SiteFactory()]) cls.practice2.sites.set([outdoor_factory.SiteFactory()]) - cls.scale1 = outdoor_factory.RatingScaleFactory( - name="AAA", practice=cls.practice1 - ) - cls.scale2 = outdoor_factory.RatingScaleFactory( - name="AAA", practice=cls.practice2 - ) - cls.scale3 = outdoor_factory.RatingScaleFactory( - name="BBB", practice=cls.practice2 - ) + cls.scale1 = outdoor_factory.RatingScaleFactory(name='AAA', practice=cls.practice1) + cls.scale2 = outdoor_factory.RatingScaleFactory(name='AAA', practice=cls.practice2) + cls.scale3 = outdoor_factory.RatingScaleFactory(name='BBB', practice=cls.practice2) def tearDown(self): clear_internal_user_cache() super().tearDown() def test_list(self): - response = self.client.get("/api/v2/outdoor_ratingscale/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 3, - "next": None, - "previous": None, - "results": [ - { - "id": self.scale1.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "practice": self.practice1.pk, - }, - { - "id": self.scale2.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "practice": self.practice2.pk, - }, - { - "id": self.scale3.pk, - "name": {"en": "BBB", "es": None, "fr": None, "it": None}, - "practice": self.practice2.pk, - }, - ], - }, - ) + response = self.client.get('/api/v2/outdoor_ratingscale/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + 'count': 3, + 'next': None, + 'previous': None, + 'results': [{ + 'id': self.scale1.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice1.pk, + }, { + 'id': self.scale2.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice2.pk, + }, { + 'id': self.scale3.pk, + 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice2.pk, + }] + }) def test_detail(self): - response = self.client.get( - "/api/v2/outdoor_ratingscale/{}/".format(self.scale1.pk) - ) + response = self.client.get('/api/v2/outdoor_ratingscale/{}/'.format(self.scale1.pk)) self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "id": self.scale1.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "practice": self.practice1.pk, - }, - ) + self.assertJSONEqual(response.content, { + 'id': self.scale1.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'practice': self.practice1.pk, + }) def test_filter_q(self): - response = self.client.get("/api/v2/outdoor_ratingscale/", {"q": "A"}) + response = self.client.get('/api/v2/outdoor_ratingscale/', {'q': 'A'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for scale in response.json()["results"]: - self.assertEqual(scale["name"]["en"], "AAA") + self.assertEqual(response.json()['count'], 2) + for scale in response.json()['results']: + self.assertEqual(scale['name']['en'], 'AAA') def test_filter_practice(self): - response = self.client.get( - "/api/v2/outdoor_ratingscale/", {"practices": self.practice2.pk} - ) + response = self.client.get('/api/v2/outdoor_ratingscale/', {'practices': self.practice2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for scale in response.json()["results"]: - self.assertEqual(scale["practice"], self.practice2.pk) + self.assertEqual(response.json()['count'], 2) + for scale in response.json()['results']: + self.assertEqual(scale['practice'], self.practice2.pk) class TrekRatingTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.scale1 = trek_factory.RatingScaleFactory(name="BBB") - cls.scale2 = trek_factory.RatingScaleFactory(name="AAA") - cls.rating1 = trek_factory.RatingFactory(name="AAA", scale=cls.scale1) - cls.rating2 = trek_factory.RatingFactory(name="AAA", scale=cls.scale2) - cls.rating3 = trek_factory.RatingFactory(name="BBB", scale=cls.scale2) + cls.scale1 = trek_factory.RatingScaleFactory(name='BBB') + cls.scale2 = trek_factory.RatingScaleFactory(name='AAA') + cls.rating1 = trek_factory.RatingFactory(name='AAA', scale=cls.scale1) + cls.rating2 = trek_factory.RatingFactory(name='AAA', scale=cls.scale2) + cls.rating3 = trek_factory.RatingFactory(name='BBB', scale=cls.scale2) cls.rating1.treks.set([trek_factory.TrekFactory()]) cls.rating2.treks.set([trek_factory.TrekFactory()]) cls.rating3.treks.set([trek_factory.TrekFactory()]) @@ -3242,83 +2635,71 @@ def tearDown(self): super().tearDown() def test_list(self): - response = self.client.get("/api/v2/trek_rating/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 3, - "next": None, - "previous": None, - "results": [ - { - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "id": self.rating1.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale1.pk, - }, - { - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "id": self.rating2.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale2.pk, - }, - { - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "id": self.rating3.pk, - "name": {"en": "BBB", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale2.pk, - }, - ], - }, - ) + response = self.client.get('/api/v2/trek_rating/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + 'count': 3, + 'next': None, + 'previous': None, + 'results': [{ + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'id': self.rating1.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale1.pk, + }, { + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'id': self.rating2.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale2.pk, + }, { + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'id': self.rating3.pk, + 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale2.pk, + }] + }) def test_detail(self): - response = self.client.get("/api/v2/trek_rating/{}/".format(self.rating2.pk)) + response = self.client.get('/api/v2/trek_rating/{}/'.format(self.rating2.pk)) self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "id": self.rating2.pk, - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale2.pk, - }, - ) + self.assertJSONEqual(response.content, { + 'id': self.rating2.pk, + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale2.pk, + }) def test_filter_q(self): - response = self.client.get("/api/v2/trek_rating/", {"q": "BBB"}) + response = self.client.get('/api/v2/trek_rating/', {'q': 'BBB'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for rating in response.json()["results"]: - self.assertNotEqual( - rating["name"]["en"] == "BBB", rating["scale"] == self.scale1.pk - ) + self.assertEqual(response.json()['count'], 2) + for rating in response.json()['results']: + self.assertNotEqual(rating['name']['en'] == 'BBB', rating['scale'] == self.scale1.pk) def test_filter_scale(self): - response = self.client.get("/api/v2/trek_rating/", {"scale": self.scale2.pk}) + response = self.client.get('/api/v2/trek_rating/', {'scale': self.scale2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for rating in response.json()["results"]: - self.assertEqual(rating["scale"], self.scale2.pk) + self.assertEqual(response.json()['count'], 2) + for rating in response.json()['results']: + self.assertEqual(rating['scale'], self.scale2.pk) class OutdoorRatingTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.scale1 = outdoor_factory.RatingScaleFactory(name="BBB") - cls.scale2 = outdoor_factory.RatingScaleFactory(name="AAA") - cls.rating1 = outdoor_factory.RatingFactory(name="AAA", scale=cls.scale1) - cls.rating2 = outdoor_factory.RatingFactory(name="AAA", scale=cls.scale2) - cls.rating3 = outdoor_factory.RatingFactory(name="BBB", scale=cls.scale2) + cls.scale1 = outdoor_factory.RatingScaleFactory(name='BBB') + cls.scale2 = outdoor_factory.RatingScaleFactory(name='AAA') + cls.rating1 = outdoor_factory.RatingFactory(name='AAA', scale=cls.scale1) + cls.rating2 = outdoor_factory.RatingFactory(name='AAA', scale=cls.scale2) + cls.rating3 = outdoor_factory.RatingFactory(name='BBB', scale=cls.scale2) cls.rating1.sites.set([outdoor_factory.SiteFactory()]) cls.rating2.sites.set([outdoor_factory.SiteFactory()]) cls.rating3.sites.set([outdoor_factory.SiteFactory()]) @@ -3328,91 +2709,75 @@ def tearDown(self): super().tearDown() def test_list(self): - response = self.client.get("/api/v2/outdoor_rating/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 3, - "next": None, - "previous": None, - "results": [ - { - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "id": self.rating1.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale1.pk, - }, - { - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "id": self.rating2.pk, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale2.pk, - }, - { - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "id": self.rating3.pk, - "name": {"en": "BBB", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale2.pk, - }, - ], - }, - ) + response = self.client.get('/api/v2/outdoor_rating/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + 'count': 3, + 'next': None, + 'previous': None, + 'results': [{ + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'id': self.rating1.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale1.pk, + }, { + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'id': self.rating2.pk, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale2.pk, + }, { + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'id': self.rating3.pk, + 'name': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale2.pk, + }] + }) def test_detail(self): - response = self.client.get("/api/v2/outdoor_rating/{}/".format(self.rating1.pk)) + response = self.client.get('/api/v2/outdoor_rating/{}/'.format(self.rating1.pk)) self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "id": self.rating1.pk, - "color": "", - "description": {"en": None, "es": None, "fr": None, "it": None}, - "name": {"en": "AAA", "es": None, "fr": None, "it": None}, - "order": None, - "scale": self.scale1.pk, - }, - ) + self.assertJSONEqual(response.content, { + 'id': self.rating1.pk, + 'color': '', + 'description': {'en': None, 'es': None, 'fr': None, 'it': None}, + 'name': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'order': None, + 'scale': self.scale1.pk, + }) def test_filter_q(self): - response = self.client.get("/api/v2/outdoor_rating/", {"q": "BBB"}) + response = self.client.get('/api/v2/outdoor_rating/', {'q': 'BBB'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for rating in response.json()["results"]: - self.assertNotEqual( - rating["name"]["en"] == "BBB", rating["scale"] == self.scale1.pk - ) + self.assertEqual(response.json()['count'], 2) + for rating in response.json()['results']: + self.assertNotEqual(rating['name']['en'] == 'BBB', rating['scale'] == self.scale1.pk) def test_filter_scale(self): - response = self.client.get("/api/v2/outdoor_rating/", {"scale": self.scale2.pk}) + response = self.client.get('/api/v2/outdoor_rating/', {'scale': self.scale2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - for rating in response.json()["results"]: - self.assertEqual(rating["scale"], self.scale2.pk) + self.assertEqual(response.json()['count'], 2) + for rating in response.json()['results']: + self.assertEqual(rating['scale'], self.scale2.pk) class FlatPageTestCase(TestCase): + @classmethod def setUpTestData(cls): cls.source = common_factory.RecordSourceFactory() cls.portal = common_factory.TargetPortalFactory() cls.page1 = flatpages_factory.FlatPageFactory( - title="AAA", - published=True, - order=2, - target="web", - content="Blah", - sources=[cls.source], - portals=[cls.portal], + title='AAA', published=True, order=2, target='web', content='Blah', + sources=[cls.source], portals=[cls.portal] ) cls.page2 = flatpages_factory.FlatPageFactory( - title="BBB", published=True, order=1, target="mobile", content="Blbh" + title='BBB', published=True, order=1, target='mobile', content='Blbh' ) def tearDown(self): @@ -3420,110 +2785,87 @@ def tearDown(self): super().tearDown() def test_list(self): - response = self.client.get("/api/v2/flatpage/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.page2.pk, - "title": {"en": "BBB", "es": None, "fr": None, "it": None}, - "content": {"en": "Blbh", "es": None, "fr": None, "it": None}, - "external_url": "", - "order": 1, - "portal": [], - "published": { - "en": True, - "es": False, - "fr": False, - "it": False, - }, - "source": [], - "target": "mobile", - "attachments": [], - }, - { - "id": self.page1.pk, - "title": {"en": "AAA", "es": None, "fr": None, "it": None}, - "content": {"en": "Blah", "es": None, "fr": None, "it": None}, - "external_url": "", - "order": 2, - "portal": [self.portal.pk], - "published": { - "en": True, - "es": False, - "fr": False, - "it": False, - }, - "source": [self.source.pk], - "target": "web", - "attachments": [], - }, - ], - }, - ) + response = self.client.get('/api/v2/flatpage/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + 'count': 2, + 'next': None, + 'previous': None, + 'results': [{ + 'id': self.page2.pk, + 'title': {'en': 'BBB', 'es': None, 'fr': None, 'it': None}, + 'content': {'en': 'Blbh', 'es': None, 'fr': None, 'it': None}, + 'external_url': '', + 'order': 1, + 'portal': [], + 'published': {'en': True, 'es': False, 'fr': False, 'it': False}, + 'source': [], + 'target': 'mobile', + 'attachments': [], + }, { + 'id': self.page1.pk, + 'title': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'content': {'en': 'Blah', 'es': None, 'fr': None, 'it': None}, + 'external_url': '', + 'order': 2, + 'portal': [self.portal.pk], + 'published': {'en': True, 'es': False, 'fr': False, 'it': False}, + 'source': [self.source.pk], + 'target': 'web', + 'attachments': [], + }] + }) def test_detail(self): - response = self.client.get("/api/v2/flatpage/{}/".format(self.page1.pk)) - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "id": self.page1.pk, - "title": {"en": "AAA", "es": None, "fr": None, "it": None}, - "content": {"en": "Blah", "es": None, "fr": None, "it": None}, - "external_url": "", - "order": 2, - "portal": [self.portal.pk], - "published": {"en": True, "es": False, "fr": False, "it": False}, - "source": [self.source.pk], - "target": "web", - "attachments": [], - }, - ) + response = self.client.get('/api/v2/flatpage/{}/'.format(self.page1.pk)) + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + 'id': self.page1.pk, + 'title': {'en': 'AAA', 'es': None, 'fr': None, 'it': None}, + 'content': {'en': 'Blah', 'es': None, 'fr': None, 'it': None}, + 'external_url': '', + 'order': 2, + 'portal': [self.portal.pk], + 'published': {'en': True, 'es': False, 'fr': False, 'it': False}, + 'source': [self.source.pk], + 'target': 'web', + 'attachments': [], + }) def test_filter_q(self): - response = self.client.get("/api/v2/flatpage/", {"q": "BB"}) + response = self.client.get('/api/v2/flatpage/', {'q': 'BB'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - self.assertEqual(response.json()["results"][0]["title"]["en"], "BBB") + self.assertEqual(response.json()['count'], 1) + self.assertEqual(response.json()['results'][0]['title']['en'], 'BBB') def test_filter_targets(self): - response = self.client.get("/api/v2/flatpage/", {"targets": "web"}) + response = self.client.get('/api/v2/flatpage/', {'targets': 'web'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - self.assertEqual(response.json()["results"][0]["title"]["en"], "AAA") + self.assertEqual(response.json()['count'], 1) + self.assertEqual(response.json()['results'][0]['title']['en'], 'AAA') def test_filter_sources(self): - response = self.client.get("/api/v2/flatpage/", {"sources": self.source.pk}) + response = self.client.get('/api/v2/flatpage/', {'sources': self.source.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - self.assertEqual(response.json()["results"][0]["title"]["en"], "AAA") + self.assertEqual(response.json()['count'], 1) + self.assertEqual(response.json()['results'][0]['title']['en'], 'AAA') def test_filter_portals(self): - response = self.client.get("/api/v2/flatpage/", {"portals": self.portal.pk}) + response = self.client.get('/api/v2/flatpage/', {'portals': self.portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - self.assertEqual(response.json()["results"][0]["title"]["en"], "AAA") + self.assertEqual(response.json()['count'], 1) + self.assertEqual(response.json()['results'][0]['title']['en'], 'AAA') class ReportStatusTestCase(TestCase): @classmethod def setUpTestData(cls): cls.status1 = feedback_factory.ReportStatusFactory(label="A transmettre") - cls.status2 = feedback_factory.ReportStatusFactory( - label="En cours de traitement" - ) + cls.status2 = feedback_factory.ReportStatusFactory(label="En cours de traitement") cls.activity1 = feedback_factory.ReportActivityFactory(label="Horse-riding") cls.activity2 = feedback_factory.ReportActivityFactory(label="Climbing") cls.magnitude1 = feedback_factory.ReportProblemMagnitudeFactory(label="Easy") - cls.magnitude2 = feedback_factory.ReportProblemMagnitudeFactory( - label="Hardcore" - ) + cls.magnitude2 = feedback_factory.ReportProblemMagnitudeFactory(label="Hardcore") cls.category1 = feedback_factory.ReportCategoryFactory(label="Conflict") cls.category2 = feedback_factory.ReportCategoryFactory(label="Literring") @@ -3532,169 +2874,101 @@ def tearDown(self): super().tearDown() def test_status_list(self): - response = self.client.get("/api/v2/feedback_status/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "identifier": self.status1.identifier, - "color": self.status1.color, - "id": self.status1.pk, - "label": { - "en": "A transmettre", - "es": None, - "fr": None, - "it": None, - }, - }, - { - "identifier": self.status2.identifier, - "color": self.status2.color, - "id": self.status2.pk, - "label": { - "en": "En cours de traitement", - "es": None, - "fr": None, - "it": None, - }, - }, - ], - }, - ) + response = self.client.get('/api/v2/feedback_status/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + 'identifier': self.status1.identifier, + 'color': self.status1.color, + "id": self.status1.pk, + "label": {'en': "A transmettre", 'es': None, 'fr': None, 'it': None}, + }, + { + 'identifier': self.status2.identifier, + 'color': self.status2.color, + "id": self.status2.pk, + "label": {'en': "En cours de traitement", 'es': None, 'fr': None, 'it': None}, + }] + }) def test_activity_list(self): - response = self.client.get("/api/v2/feedback_activity/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.activity1.pk, - "label": { - "en": "Horse-riding", - "es": None, - "fr": None, - "it": None, - }, - }, - { - "id": self.activity2.pk, - "label": {"en": "Climbing", "es": None, "fr": None, "it": None}, - }, - ], - }, - ) + response = self.client.get('/api/v2/feedback_activity/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.activity1.pk, + "label": {'en': "Horse-riding", 'es': None, 'fr': None, 'it': None}, + }, + { + "id": self.activity2.pk, + "label": {'en': "Climbing", 'es': None, 'fr': None, 'it': None}, + }] + }) def test_magnitude_list(self): - response = self.client.get("/api/v2/feedback_magnitude/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.magnitude1.pk, - "label": {"en": "Easy", "es": None, "fr": None, "it": None}, - }, - { - "id": self.magnitude2.pk, - "label": {"en": "Hardcore", "es": None, "fr": None, "it": None}, - }, - ], - }, - ) + response = self.client.get('/api/v2/feedback_magnitude/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.magnitude1.pk, + "label": {'en': "Easy", 'es': None, 'fr': None, 'it': None}, + }, + { + "id": self.magnitude2.pk, + "label": {'en': "Hardcore", 'es': None, 'fr': None, 'it': None}, + }] + }) def test_category_list(self): - response = self.client.get("/api/v2/feedback_category/") - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 2, - "next": None, - "previous": None, - "results": [ - { - "id": self.category1.pk, - "label": {"en": "Conflict", "es": None, "fr": None, "it": None}, - }, - { - "id": self.category2.pk, - "label": { - "en": "Literring", - "es": None, - "fr": None, - "it": None, - }, - }, - ], - }, - ) + response = self.client.get('/api/v2/feedback_category/') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + "count": 2, + "next": None, + "previous": None, + "results": [ + { + "id": self.category1.pk, + "label": {'en': "Conflict", 'es': None, 'fr': None, 'it': None}, + }, + { + "id": self.category2.pk, + "label": {'en': "Literring", 'es': None, 'fr': None, 'it': None}, + }] + }) class LanguageOrderingTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.trek1 = trek_factory.TrekFactory( - name_fr="AAA", name_en="ABA", published_fr=True, published_en=True - ) - cls.trek2 = trek_factory.TrekFactory( - name_fr="ABA", name_en="BAA", published_fr=True, published_en=True - ) - cls.trek3 = trek_factory.TrekFactory( - name_fr="BAA", name_en="AAA", published_fr=True, published_en=True - ) - cls.trek4 = trek_factory.TrekFactory( - name_fr="CCC", name_en="CCC", published_fr=True, published_en=True - ) - cls.course1 = outdoor_factory.CourseFactory( - name_fr="AAA", name_en="ABA", published_fr=True, published_en=True - ) - cls.course2 = outdoor_factory.CourseFactory( - name_fr="ABA", name_en="BAA", published_fr=True, published_en=True - ) - cls.course3 = outdoor_factory.CourseFactory( - name_fr="BAA", name_en="AAA", published_fr=True, published_en=True - ) - cls.course4 = outdoor_factory.CourseFactory( - name_fr="CCC", name_en="CCC", published_fr=True, published_en=True - ) - cls.site1 = outdoor_factory.SiteFactory( - name_fr="AAA", name_en="ABA", published_fr=True, published_en=True - ) - cls.site2 = outdoor_factory.SiteFactory( - name_fr="ABA", name_en="BAA", published_fr=True, published_en=True - ) - cls.site3 = outdoor_factory.SiteFactory( - name_fr="BAA", name_en="AAA", published_fr=True, published_en=True - ) - cls.site4 = outdoor_factory.SiteFactory( - name_fr="CCC", name_en="CCC", published_fr=True, published_en=True - ) - cls.tc1 = tourism_factory.TouristicContentFactory( - name_fr="AAA", name_en="ABA", published_fr=True, published_en=True - ) - cls.tc2 = tourism_factory.TouristicContentFactory( - name_fr="ABA", name_en="BAA", published_fr=True, published_en=True - ) - cls.tc3 = tourism_factory.TouristicContentFactory( - name_fr="BAA", name_en="AAA", published_fr=True, published_en=True - ) - cls.tc4 = tourism_factory.TouristicContentFactory( - name_fr="CCC", name_en="CCC", published_fr=True, published_en=True - ) + cls.trek1 = trek_factory.TrekFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) + cls.trek2 = trek_factory.TrekFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) + cls.trek3 = trek_factory.TrekFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) + cls.trek4 = trek_factory.TrekFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) + cls.course1 = outdoor_factory.CourseFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) + cls.course2 = outdoor_factory.CourseFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) + cls.course3 = outdoor_factory.CourseFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) + cls.course4 = outdoor_factory.CourseFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) + cls.site1 = outdoor_factory.SiteFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) + cls.site2 = outdoor_factory.SiteFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) + cls.site3 = outdoor_factory.SiteFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) + cls.site4 = outdoor_factory.SiteFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) + cls.tc1 = tourism_factory.TouristicContentFactory(name_fr="AAA", name_en='ABA', published_fr=True, published_en=True) + cls.tc2 = tourism_factory.TouristicContentFactory(name_fr="ABA", name_en='BAA', published_fr=True, published_en=True) + cls.tc3 = tourism_factory.TouristicContentFactory(name_fr="BAA", name_en="AAA", published_fr=True, published_en=True) + cls.tc4 = tourism_factory.TouristicContentFactory(name_fr="CCC", name_en="CCC", published_fr=True, published_en=True) def tearDown(self): clear_internal_user_cache() @@ -3702,114 +2976,89 @@ def tearDown(self): def assert_ordered_by_language(self, endpoint, ordered_ids, language): # GET request on list with language param - response = self.client.get(reverse(endpoint), {"language": language}) + response = self.client.get(reverse(endpoint), {'language': language}) self.assertEqual(response.status_code, 200) # Assert response list is ordered as expected for index, expected_id in enumerate(ordered_ids): - self.assertEqual(response.json()["results"][index]["id"], expected_id) + self.assertEqual(response.json()['results'][index]['id'], expected_id) def test_ordered_trek_lists(self): order_fr = [self.trek1.id, self.trek2.id, self.trek3.id, self.trek4.id] - self.assert_ordered_by_language("apiv2:trek-list", order_fr, "fr") + self.assert_ordered_by_language('apiv2:trek-list', order_fr, 'fr') order_en = [self.trek3.id, self.trek1.id, self.trek2.id, self.trek4.id] - self.assert_ordered_by_language("apiv2:trek-list", order_en, "en") + self.assert_ordered_by_language('apiv2:trek-list', order_en, 'en') def test_ordered_touristic_content_lists(self): order_fr = [self.tc1.id, self.tc2.id, self.tc3.id, self.tc4.id] - self.assert_ordered_by_language("apiv2:touristiccontent-list", order_fr, "fr") + self.assert_ordered_by_language('apiv2:touristiccontent-list', order_fr, 'fr') order_en = [self.tc3.id, self.tc1.id, self.tc2.id, self.tc4.id] - self.assert_ordered_by_language("apiv2:touristiccontent-list", order_en, "en") + self.assert_ordered_by_language('apiv2:touristiccontent-list', order_en, 'en') def test_ordered_outdoor_site_lists(self): order_fr = [self.site1.id, self.site2.id, self.site3.id, self.site4.id] - self.assert_ordered_by_language("apiv2:site-list", order_fr, "fr") + self.assert_ordered_by_language('apiv2:site-list', order_fr, 'fr') order_en = [self.site3.id, self.site1.id, self.site2.id, self.site4.id] - self.assert_ordered_by_language("apiv2:site-list", order_en, "en") + self.assert_ordered_by_language('apiv2:site-list', order_en, 'en') def test_order_outdoor_course_lists(self): order_fr = [self.course1.id, self.course2.id, self.course3.id, self.course4.id] - self.assert_ordered_by_language("apiv2:course-list", order_fr, "fr") + self.assert_ordered_by_language('apiv2:course-list', order_fr, 'fr') order_en = [self.course3.id, self.course1.id, self.course2.id, self.course4.id] - self.assert_ordered_by_language("apiv2:course-list", order_en, "en") + self.assert_ordered_by_language('apiv2:course-list', order_en, 'en') class WebLinksCategoryTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.web_link_cat1 = trek_factory.WebLinkCategoryFactory( - pictogram="dummy_picto1.png", label="To do" - ) - cls.web_link_cat2 = trek_factory.WebLinkCategoryFactory( - pictogram="dummy_picto2.png", label="To see" - ) - cls.web_link_cat3 = trek_factory.WebLinkCategoryFactory( - pictogram="dummy_picto3.png", label="To eat" - ) + cls.web_link_cat1 = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto1.png', label="To do") + cls.web_link_cat2 = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto2.png', label="To see") + cls.web_link_cat3 = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto3.png', label="To eat") def tearDown(self): clear_internal_user_cache() super().tearDown() def test_web_links_category_list(self): - response = self.client.get(reverse("apiv2:weblink-category-list")) - self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "count": 3, - "next": None, - "previous": None, - "results": [ - { - "label": {"en": "To do", "es": None, "fr": None, "it": None}, - "id": self.web_link_cat1.pk, - "pictogram": "http://testserver/media/dummy_picto1.png", - }, - { - "label": {"en": "To eat", "es": None, "fr": None, "it": None}, - "id": self.web_link_cat3.pk, - "pictogram": "http://testserver/media/dummy_picto3.png", - }, - { - "label": {"en": "To see", "es": None, "fr": None, "it": None}, - "id": self.web_link_cat2.pk, - "pictogram": "http://testserver/media/dummy_picto2.png", - }, - ], - }, - ) + response = self.client.get(reverse('apiv2:weblink-category-list')) + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(response.content, { + "count": 3, + "next": None, + "previous": None, + "results": [ + { + "label": {'en': "To do", 'es': None, 'fr': None, 'it': None}, + "id": self.web_link_cat1.pk, + "pictogram": "http://testserver/media/dummy_picto1.png", + }, + { + "label": {'en': "To eat", 'es': None, 'fr': None, 'it': None}, + "id": self.web_link_cat3.pk, + "pictogram": "http://testserver/media/dummy_picto3.png", + }, + { + "label": {'en': "To see", 'es': None, 'fr': None, 'it': None}, + "id": self.web_link_cat2.pk, + "pictogram": "http://testserver/media/dummy_picto2.png", + }] + }) def test_web_links_category_detail(self): response = self.client.get(f"/api/v2/weblink_category/{self.web_link_cat1.pk}/") self.assertEqual(response.status_code, 200) - self.assertJSONEqual( - response.content, - { - "label": {"en": "To do", "es": None, "fr": None, "it": None}, - "id": self.web_link_cat1.pk, - "pictogram": "http://testserver/media/dummy_picto1.png", - }, - ) + self.assertJSONEqual(response.content, { + "label": {'en': "To do", 'es': None, 'fr': None, 'it': None}, + "id": self.web_link_cat1.pk, + "pictogram": "http://testserver/media/dummy_picto1.png", + }) class TrekWebLinksTestCase(TestCase): @classmethod def setUpTestData(cls): - cls.web_link_cat = trek_factory.WebLinkCategoryFactory( - pictogram="dummy_picto.png", label_en="Category" - ) - cls.web_link1 = trek_factory.WebLinkFactory( - category=cls.web_link_cat, - name="Web link", - name_en="Web link", - url="http://dummy.url", - ) - cls.web_link2 = trek_factory.WebLinkFactory( - category=cls.web_link_cat, - name="Web link", - name_en="Web link", - url="http://dummy.url", - ) + cls.web_link_cat = trek_factory.WebLinkCategoryFactory(pictogram='dummy_picto.png', label_en='Category') + cls.web_link1 = trek_factory.WebLinkFactory(category=cls.web_link_cat, name="Web link", name_en="Web link", url="http://dummy.url") + cls.web_link2 = trek_factory.WebLinkFactory(category=cls.web_link_cat, name="Web link", name_en="Web link", url="http://dummy.url") cls.trek1 = trek_factory.TrekFactory(web_links=[cls.web_link1, cls.web_link2]) def tearDown(self): @@ -3817,44 +3066,31 @@ def tearDown(self): super().tearDown() def test_web_links_in_trek_list(self): - response = self.client.get(reverse("apiv2:trek-list")) - self.assertEqual(response.status_code, 200) - json_result = response.json()["results"][0] - web_links = json_result["web_links"] - self.assertEqual(json_result["id"], self.trek1.pk) - self.assertEqual(web_links[0]["name"]["en"], "Web link") - self.assertEqual(web_links[0]["url"], "http://dummy.url") - self.assertEqual(web_links[0]["category"]["label"]["en"], "Category") - self.assertEqual(web_links[0]["category"]["id"], self.web_link_cat.pk) - self.assertEqual( - web_links[0]["category"]["pictogram"], - "http://testserver/media/dummy_picto.png", - ) - self.assertEqual(web_links[1]["name"]["en"], "Web link") - self.assertEqual(web_links[1]["url"], "http://dummy.url") - self.assertEqual(web_links[1]["category"]["label"]["en"], "Category") - self.assertEqual(web_links[1]["category"]["id"], self.web_link_cat.pk) - self.assertEqual( - web_links[1]["category"]["pictogram"], - "http://testserver/media/dummy_picto.png", - ) + response = self.client.get(reverse('apiv2:trek-list')) + self.assertEqual(response.status_code, 200) + json_result = response.json()['results'][0] + web_links = json_result['web_links'] + self.assertEqual(json_result['id'], self.trek1.pk) + self.assertEqual(web_links[0]['name']['en'], "Web link") + self.assertEqual(web_links[0]['url'], "http://dummy.url") + self.assertEqual(web_links[0]['category']['label']['en'], "Category") + self.assertEqual(web_links[0]['category']['id'], self.web_link_cat.pk) + self.assertEqual(web_links[0]['category']['pictogram'], 'http://testserver/media/dummy_picto.png') + self.assertEqual(web_links[1]['name']['en'], "Web link") + self.assertEqual(web_links[1]['url'], "http://dummy.url") + self.assertEqual(web_links[1]['category']['label']['en'], "Category") + self.assertEqual(web_links[1]['category']['id'], self.web_link_cat.pk) + self.assertEqual(web_links[1]['category']['pictogram'], 'http://testserver/media/dummy_picto.png') def test_web_links_in_trek_detail(self): response = self.client.get(f"/api/v2/trek/{self.trek1.pk}/") self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["id"], self.trek1.pk) - self.assertEqual(response.json()["web_links"][0]["name"]["en"], "Web link") - self.assertEqual(response.json()["web_links"][0]["url"], "http://dummy.url") - self.assertEqual( - response.json()["web_links"][0]["category"]["label"]["en"], "Category" - ) - self.assertEqual( - response.json()["web_links"][0]["category"]["id"], self.web_link_cat.pk - ) - self.assertEqual( - response.json()["web_links"][0]["category"]["pictogram"], - "http://testserver/media/dummy_picto.png", - ) + self.assertEqual(response.json()['id'], self.trek1.pk) + self.assertEqual(response.json()['web_links'][0]['name']['en'], "Web link") + self.assertEqual(response.json()['web_links'][0]['url'], "http://dummy.url") + self.assertEqual(response.json()['web_links'][0]['category']['label']['en'], "Category") + self.assertEqual(response.json()['web_links'][0]['category']['id'], self.web_link_cat.pk) + self.assertEqual(response.json()['web_links'][0]['category']['pictogram'], 'http://testserver/media/dummy_picto.png') class TrekDifficultyFilterCase(TestCase): @@ -3876,19 +3112,11 @@ def tearDown(self): super().tearDown() def assert_trek_is_in_reponse(self, response, expected_trek): - found = list( - filter( - lambda trek: trek["id"] == expected_trek.pk, response.json()["results"] - ) - ) + found = list(filter(lambda trek: trek['id'] == expected_trek.pk, response.json()['results'])) self.assertTrue(found) def assert_trek_is_not_in_reponse(self, response, expected_trek): - found = list( - filter( - lambda trek: trek["id"] == expected_trek.pk, response.json()["results"] - ) - ) + found = list(filter(lambda trek: trek['id'] == expected_trek.pk, response.json()['results'])) self.assertFalse(found) def test_difficulty_ids(self): @@ -3899,9 +3127,9 @@ def test_difficulty_ids(self): self.assertEqual(self.v_hard.id, 5) def test_filter_difficulty_min(self): - response = self.client.get("/api/v2/trek/", {"difficulty_min": self.medium.id}) + response = self.client.get("/api/v2/trek/", {'difficulty_min': self.medium.id}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 3) + self.assertEqual(response.json()['count'], 3) self.assert_trek_is_not_in_reponse(response, self.trek_v_easy) self.assert_trek_is_not_in_reponse(response, self.trek_easy) self.assert_trek_is_in_reponse(response, self.trek_medium) @@ -3909,9 +3137,9 @@ def test_filter_difficulty_min(self): self.assert_trek_is_in_reponse(response, self.trek_v_hard) def test_filter_difficulty_max(self): - response = self.client.get("/api/v2/trek/", {"difficulty_max": self.medium.id}) + response = self.client.get("/api/v2/trek/", {'difficulty_max': self.medium.id}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 3) + self.assertEqual(response.json()['count'], 3) self.assert_trek_is_in_reponse(response, self.trek_v_easy) self.assert_trek_is_in_reponse(response, self.trek_easy) self.assert_trek_is_in_reponse(response, self.trek_medium) @@ -3919,12 +3147,9 @@ def test_filter_difficulty_max(self): self.assert_trek_is_not_in_reponse(response, self.trek_v_hard) def test_filter_difficulty_min_max_1(self): - response = self.client.get( - "/api/v2/trek/", - {"difficulty_min": self.easy.id, "difficulty_max": self.hard.id}, - ) + response = self.client.get("/api/v2/trek/", {'difficulty_min': self.easy.id, 'difficulty_max': self.hard.id}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 3) + self.assertEqual(response.json()['count'], 3) self.assert_trek_is_not_in_reponse(response, self.trek_v_easy) self.assert_trek_is_in_reponse(response, self.trek_easy) self.assert_trek_is_in_reponse(response, self.trek_medium) @@ -3932,12 +3157,9 @@ def test_filter_difficulty_min_max_1(self): self.assert_trek_is_not_in_reponse(response, self.trek_v_hard) def test_filter_difficulty_min_max_2(self): - response = self.client.get( - "/api/v2/trek/", - {"difficulty_min": self.hard.id, "difficulty_max": self.hard.id}, - ) + response = self.client.get("/api/v2/trek/", {'difficulty_min': self.hard.id, 'difficulty_max': self.hard.id}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) + self.assertEqual(response.json()['count'], 1) self.assert_trek_is_not_in_reponse(response, self.trek_v_easy) self.assert_trek_is_not_in_reponse(response, self.trek_easy) self.assert_trek_is_not_in_reponse(response, self.trek_medium) @@ -3950,6 +3172,7 @@ def test_filter_difficulty_min_max_2(self): @override_settings(TOURISM_INTERSECTION_MARGIN=500) @freeze_time("2000-07-04") class TouristicEventTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.touristic_event_type = tourism_factory.TouristicEventTypeFactory() @@ -3974,23 +3197,21 @@ def setUpTestData(cls): end_time=datetime.time(12, 20), cancelled=True, place=cls.other_place, - cancellation_reason=tourism_factory.CancellationReasonFactory( - label_en="Fire", label_fr="Incendie" - ), + cancellation_reason=tourism_factory.CancellationReasonFactory(label_en="Fire", label_fr="Incendie") ) cls.touristic_event1.portal.set([common_factory.TargetPortalFactory()]) cls.touristic_event2 = tourism_factory.TouristicEventFactory( name_fr="expo", geom=Point(5.77802, 2.047482, srid=4326), published=True, - bookable=False, + bookable=False ) cls.touristic_event2.portal.set([common_factory.TargetPortalFactory()]) - cls.path = core_factory.PathFactory.create( - geom=LineString((0.77802, 43.047482), (0.77803, 43.047483), srid=4326) - ) + cls.path = core_factory.PathFactory.create(geom=LineString((0.77802, 43.047482), (0.77803, 43.047483), srid=4326)) cls.trek = trek_factory.TrekFactory.create( - paths=[(cls.path, 0, 1)], geom=cls.path.geom, published=True + paths=[(cls.path, 0, 1)], + geom=cls.path.geom, + published=True ) cls.touristic_event3 = tourism_factory.TouristicEventFactory( name_fr="expooo", @@ -3998,25 +3219,23 @@ def setUpTestData(cls): published=False, ) # Should not appear at any point - cls.touristic_event4 = tourism_factory.TouristicEventFactory(deleted=True) - cls.organizer = tourism_factory.TouristicEventOrganizerFactory( - label="OrganizerA" + cls.touristic_event4 = tourism_factory.TouristicEventFactory( + deleted=True ) + cls.organizer = tourism_factory.TouristicEventOrganizerFactory(label='OrganizerA') cls.place_unpublished = tourism_factory.TouristicEventPlaceFactory(name="There") cls.touristic_event5 = tourism_factory.TouristicEventFactory( end_date=None, published=True, name="No end date", - begin_date="2022-02-20", + begin_date='2022-02-20', start_time="12:34", capacity=12, bookable=False, place=cls.place, - organizer=cls.organizer, - ) - cls.touristic_content = tourism_factory.TouristicContentFactory( - geom=Point(0.77802, 43.047482, srid=4326) + organizer=cls.organizer ) + cls.touristic_content = tourism_factory.TouristicContentFactory(geom=Point(0.77802, 43.047482, srid=4326)) def test_touristic_event_list(self): response = self.get_touristicevent_list() @@ -4028,61 +3247,49 @@ def test_touristic_event_list_2(self): # Only two because past events are filter by default self.assertEqual(response.json().get("count"), 2) # Event with no end date is returned with begin date as end date - self.assertEqual(response.json().get("results")[0]["end_date"], "2022-02-20") + self.assertEqual(response.json().get("results")[0]['end_date'], "2022-02-20") # start_time replaces meeting_time - self.assertEqual(response.json().get("results")[0]["meeting_time"], "12:34:00") + self.assertEqual(response.json().get("results")[0]['meeting_time'], "12:34:00") # capacity replaces participant_number - self.assertEqual(response.json().get("results")[0]["participant_number"], "12") + self.assertEqual(response.json().get("results")[0]['participant_number'], '12') # Event with end date returns right end date - self.assertEqual(response.json().get("results")[1]["end_date"], "2202-02-22") + self.assertEqual(response.json().get("results")[1]['end_date'], "2202-02-22") # Sorted by end date - self.assertLessEqual( - response.json().get("results")[0]["end_date"], - response.json().get("results")[1]["end_date"], - ) + self.assertLessEqual(response.json().get("results")[0]['end_date'], response.json().get("results")[1]['end_date']) def test_touristic_event_dates_filters_1(self): - response = self.get_touristicevent_list( - {"dates_before": "2200-01-01", "dates_after": "1970-01-01"} - ) + response = self.get_touristicevent_list({'dates_before': '2200-01-01', 'dates_after': '1970-01-01'}) self.assertEqual(response.json().get("count"), 3) def test_touristic_event_dates_filters_2(self): - response = self.get_touristicevent_list( - {"dates_before": "2021-09-01", "dates_after": "1970-01-01"} - ) + response = self.get_touristicevent_list({'dates_before': '2021-09-01', 'dates_after': '1970-01-01'}) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_dates_filters_3(self): - response = self.get_touristicevent_list({"dates_after": "2021-07-03"}) + response = self.get_touristicevent_list({'dates_after': '2021-07-03'}) self.assertEqual(response.json().get("count"), 3) def test_touristic_event_dates_filters_4(self): - response = self.get_touristicevent_list({"dates_after": "2021-07-04"}) + response = self.get_touristicevent_list({'dates_after': '2021-07-04'}) # Event 1 finishes on 3rd of july self.assertEqual(response.json().get("count"), 2) def test_touristic_event_organizer_filters_1(self): - response = self.get_touristicevent_list({"organizer": "tt"}) - self.assertEqual(response.json()["organizer"][0], "“tt” is not a valid value.") + response = self.get_touristicevent_list({'organizer': 'tt'}) + self.assertEqual(response.json()['organizer'][0], + '“tt” is not a valid value.') def test_touristic_event_organizer_filters_2(self): - response = self.get_touristicevent_list({"organizer": f"{self.organizer.pk}"}) + response = self.get_touristicevent_list({'organizer': f'{self.organizer.pk}'}) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_cancelled_filter(self): - response = self.get_touristicevent_list({"cancelled": "True"}) + response = self.get_touristicevent_list({'cancelled': 'True'}) self.assertEqual(response.json().get("count"), 1) self.assertTrue(response.json().get("results")[0].get("cancelled")) - self.assertEqual( - response.json().get("results")[0].get("cancellation_reason").get("en"), - "Fire", - ) - self.assertEqual( - response.json().get("results")[0].get("cancellation_reason").get("fr"), - "Incendie", - ) - response = self.get_touristicevent_list({"cancelled": "False"}) + self.assertEqual(response.json().get("results")[0].get("cancellation_reason").get('en'), "Fire") + self.assertEqual(response.json().get("results")[0].get("cancellation_reason").get('fr'), "Incendie") + response = self.get_touristicevent_list({'cancelled': 'False'}) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_detail(self): @@ -4091,63 +3298,48 @@ def test_touristic_event_detail(self): def test_touristic_event_place_detail(self): response = self.get_touristiceventplace_detail(self.place.pk) - self.check_structure_response( - response, TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE - ) + self.check_structure_response(response, TOURISTIC_EVENT_PLACE_DETAIL_JSON_STRUCTURE) def test_touristic_event_organizer_detail(self): response = self.get_touristiceventorganizer_detail(self.organizer.pk) - self.check_structure_response( - response, TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE - ) + self.check_structure_response(response, TOURISTIC_EVENT_ORGANIZER_DETAIL_JSON_STRUCTURE) def test_touristicevent_near_trek(self): - response = self.get_touristicevent_list({"near_trek": self.trek.pk}) + response = self.get_touristicevent_list({'near_trek': self.trek.pk}) # Event 1 appears but not Event 2 self.assertEqual(response.json().get("count"), 1) def test_touristicevent_near_touristicevent(self): - response = self.get_touristicevent_list( - {"near_touristicevent": self.touristic_event3.pk} - ) + response = self.get_touristicevent_list({'near_touristicevent': self.touristic_event3.pk}) # Event 2 appears but not Event 1 (too far) or Event 3 (not published) self.assertEqual(response.json().get("count"), 1) def test_touristicevent_near_touristiccontent(self): - response = self.get_touristicevent_list( - {"near_touristiccontent": self.touristic_content.pk} - ) + response = self.get_touristicevent_list({'near_touristiccontent': self.touristic_content.pk}) # Event 1 appears but not Event 2 (too far) or Event 3 (too far + not published) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_portal_filters(self): - response = self.get_touristicevent_list( - {"portals": self.touristic_event1.portal.first().pk} - ) + response = self.get_touristicevent_list({'portals': self.touristic_event1.portal.first().pk}) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_type_filters(self): - response = self.get_touristicevent_list({"types": self.touristic_event_type.pk}) + response = self.get_touristicevent_list({'types': self.touristic_event_type.pk}) self.assertEqual(response.json().get("count"), 1) def test_touristic_event_bookable(self): - response = self.get_touristicevent_list({"bookable": "True"}) + response = self.get_touristicevent_list({'bookable': 'True'}) self.assertEqual(response.json().get("count"), 1) - response = self.get_touristicevent_list({"bookable": "False"}) + response = self.get_touristicevent_list({'bookable': 'False'}) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_place_filter(self): - response = self.get_touristicevent_list( - {"place": f"{self.place.pk},{self.other_place.pk}"} - ) + response = self.get_touristicevent_list({'place': f"{self.place.pk},{self.other_place.pk}"}) self.assertEqual(response.json().get("count"), 2) def test_touristic_event_place_not_valid_filter(self): - response = self.get_touristicevent_list({"place": "100000"}) - self.assertEqual( - response.json()["place"][0], - "Select a valid choice. 100000 is not one of the available choices.", - ) + response = self.get_touristicevent_list({'place': "100000"}) + self.assertEqual(response.json()['place'][0], "Select a valid choice. 100000 is not one of the available choices.") def test_touristic_event_place_list(self): response = self.get_touristiceventplace_list() @@ -4157,11 +3349,10 @@ def test_touristic_event_place_list(self): class TouristicEventTypeTestCase(BaseApiTest): @classmethod def setUpTestData(cls): - cls.touristic_event_type = tourism_factory.TouristicEventTypeFactory( - type_fr="Cool", type_en="af" - ) + cls.touristic_event_type = tourism_factory.TouristicEventTypeFactory(type_fr="Cool", type_en="af") cls.touristic_event = tourism_factory.TouristicEventFactory( - published=True, type=cls.touristic_event_type + published=True, + type=cls.touristic_event_type ) def test_touristic_event_type_list(self): @@ -4171,13 +3362,11 @@ def test_touristic_event_type_list(self): def test_touristic_event_type_detail(self): response = self.get_touristiceventtype_detail(self.touristic_event_type.pk) - self.check_structure_response( - response, TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE - ) + self.check_structure_response(response, TOURISTIC_EVENT_TYPE_DETAIL_JSON_STRUCTURE) class TouristicEventTypeFilterTestCase(BaseApiTest): - """Test filtering depending on published, deleted content for touristic event types""" + """ Test filtering depending on published, deleted content for touristic event types """ @classmethod def setUpTestData(cls): @@ -4187,68 +3376,62 @@ def setUpTestData(cls): # Type with no published content -> don't send it cls.type_with_no_published_content = tourism_factory.TouristicEventTypeFactory() cls.not_published_event = tourism_factory.TouristicEventFactory( - published=False, type=cls.type_with_no_published_content + published=False, + type=cls.type_with_no_published_content ) # Type with no content that was not deleted -> don't send it cls.type_with_only_deleted_content = tourism_factory.TouristicEventTypeFactory() cls.deleted_event = tourism_factory.TouristicEventFactory( - deleted=True, type=cls.type_with_only_deleted_content + deleted=True, + type=cls.type_with_only_deleted_content ) # Type with published and not deleted content -> send it - cls.type_with_published_and_not_deleted_content = ( - tourism_factory.TouristicEventTypeFactory() - ) + cls.type_with_published_and_not_deleted_content = tourism_factory.TouristicEventTypeFactory() cls.published_and_not_deleted_event = tourism_factory.TouristicEventFactory( deleted=False, published_en=True, - type=cls.type_with_published_and_not_deleted_content, + type=cls.type_with_published_and_not_deleted_content ) # Type with published_fr and not deleted content -> send it when language=fr - cls.type_with_published_and_not_deleted_content_with_lang = ( - tourism_factory.TouristicEventTypeFactory() - ) - cls.published_and_not_deleted_event_with_lang = ( - tourism_factory.TouristicEventFactory( - deleted=False, - published_fr=True, - type=cls.type_with_published_and_not_deleted_content_with_lang, - ) + cls.type_with_published_and_not_deleted_content_with_lang = tourism_factory.TouristicEventTypeFactory() + cls.published_and_not_deleted_event_with_lang = tourism_factory.TouristicEventFactory( + deleted=False, + published_fr=True, + type=cls.type_with_published_and_not_deleted_content_with_lang ) def test_touristic_event_type_list_returns_published(self): - """Assert API returns only types with published events""" + """ Assert API returns only types with published events + """ response = self.get_touristiceventtype_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 2) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) self.assertIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) def test_touristic_event_type_list_returns_published_in_language(self): - """Assert API returns only published events in specified language""" - response = self.get_touristiceventtype_list({"language": "fr"}) + """ Assert API returns only published events in specified language + """ + response = self.get_touristiceventtype_list({'language': 'fr'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) self.assertNotIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) class TouristicEventTypeFilterByPortalTestCase(TouristicEventTypeFilterTestCase): - """Test filtering depending on portal for touristic event types""" + """ Test filtering depending on portal for touristic event types """ @classmethod def setUpTestData(cls): @@ -4278,70 +3461,69 @@ def setUpTestData(cls): cls.not_deleted_event_on_other_portal.portal.set([cls.other_portal]) def test_touristic_event_type_list_returns_published(self): - """Assert API returns only types with published events on portal""" - response = self.get_touristiceventtype_list({"portals": self.queried_portal.pk}) + """ Assert API returns only types with published events on portal + """ + response = self.get_touristiceventtype_list({'portals': self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 0) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 0) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) # Didn't set portal on these ones yet self.assertNotIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertNotIn( - self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids - ) + self.assertNotIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) def test_touristic_event_type_list_returns_published_2(self): - """Assert API returns only types with published events on portal""" + """ Assert API returns only types with published events on portal + """ # Type with published and not deleted content on portal -> send it self.published_and_not_deleted_event.portal.set([self.queried_portal]) # Type with published_fr and not deleted content on portal -> send it when language=fr self.published_and_not_deleted_event_with_lang.portal.set([self.queried_portal]) - response = self.get_touristiceventtype_list({"portals": self.queried_portal.pk}) + response = self.get_touristiceventtype_list({'portals': self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 2) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_content.pk, all_ids) self.assertNotIn(self.type_with_no_published_content.pk, all_ids) self.assertNotIn(self.type_with_only_deleted_content.pk, all_ids) # Portal is set this time self.assertIn(self.type_with_published_and_not_deleted_content.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_content_with_lang.pk, all_ids) class NearOutdoorFilterTestCase(BaseApiTest): - """Test near_outdoorsite and near_outdoorcourse filter on routes""" + """ Test near_outdoorsite and near_outdoorcourse filter on routes """ @classmethod def setUpTestData(cls): cls.site = outdoor_factory.SiteFactory( - published_fr=True, geom=GeometryCollection(Point(100.1, 100.1, srid=2154)) + published_fr=True, + geom=GeometryCollection(Point(100.1, 100.1, srid=2154)) ) cls.course = outdoor_factory.CourseFactory( published_fr=True, geom=GeometryCollection(Point(100, 100, srid=2154)), - parent_sites=[cls.site], + parent_sites=[cls.site] ) # trek1 is nearby - cls.path1 = core_factory.PathFactory.create( - geom=LineString((0.0, 0.0), (1.0, 1.0), srid=2154) - ) + cls.path1 = core_factory.PathFactory.create(geom=LineString((0.0, 0.0), (1.0, 1.0), srid=2154)) cls.trek1 = trek_factory.TrekFactory.create( - paths=[(cls.path1, 0, 1)], geom=cls.path1.geom, published_fr=True + paths=[(cls.path1, 0, 1)], + geom=cls.path1.geom, + published_fr=True ) # trek2 is far away - cls.path2 = core_factory.PathFactory.create( - geom=LineString((9999.0, 9999.0), (9999.0, 9998.0), srid=2154) - ) + cls.path2 = core_factory.PathFactory.create(geom=LineString((9999.0, 9999.0), (9999.0, 9998.0), srid=2154)) cls.trek2 = trek_factory.TrekFactory.create( - paths=[(cls.path2, 0, 1)], geom=cls.path2.geom, published_fr=True + paths=[(cls.path2, 0, 1)], + geom=cls.path2.geom, + published_fr=True ) # event1 is nearby cls.touristic_event1 = tourism_factory.TouristicEventFactory( @@ -4365,31 +3547,36 @@ def setUpTestData(cls): ) # site1 is nearby cls.site1 = outdoor_factory.SiteFactory( - published_fr=True, geom=GeometryCollection(Point(100.5, 100.5, srid=2154)) + published_fr=True, + geom=GeometryCollection(Point(100.5, 100.5, srid=2154)) ) # site2 is far away cls.site2 = outdoor_factory.SiteFactory( - published_fr=True, geom=GeometryCollection(Point(9999.5, 9999.5, srid=2154)) + published_fr=True, + geom=GeometryCollection(Point(9999.5, 9999.5, srid=2154)) ) # course1 is nearby cls.course1 = outdoor_factory.CourseFactory( published_fr=True, geom=GeometryCollection(Point(100.5, 100.5, srid=2154)), - parent_sites=[cls.site1], + parent_sites=[cls.site1] ) # course2 is far away cls.course2 = outdoor_factory.CourseFactory( published_fr=True, geom=GeometryCollection(Point(9999.5, 9999.5, srid=2154)), - parent_sites=[cls.site2], + parent_sites=[cls.site2] + ) # poi 1 is nearby cls.poi1 = trek_factory.POIFactory( - paths=[(cls.path1, 0, 0)], geom=cls.path1.geom + paths=[(cls.path1, 0, 0)], + geom=cls.path1.geom ) # poi 2 isfar away cls.poi2 = trek_factory.POIFactory( - paths=[(cls.path2, 0, 0)], geom=cls.path2.geom + paths=[(cls.path2, 0, 0)], + geom=cls.path2.geom ) # info desk 1 is nearby cls.info_desk1 = tourism_factory.InformationDeskFactory( @@ -4403,100 +3590,106 @@ def setUpTestData(cls): cls.trek2.information_desks.set([cls.info_desk2]) # sensitive area 1 is nearby cls.sensitivearea1 = sensitivity_factory.SensitiveAreaFactory( - geom=Polygon(((0, 0), (0, 1), (1, 1), (0, 0)), srid=2154) + geom=Polygon( + ( + (0, 0), + (0, 1), + (1, 1), + (0, 0) + ), + srid=2154 + ) ) # sensitive area 2 is nearby cls.sensitivearea2 = sensitivity_factory.SensitiveAreaFactory( geom=Polygon( - ((9999, 9999), (9999, 9998), (9998, 9998), (9999, 9999)), srid=2154 + ( + (9999, 9999), + (9999, 9998), + (9998, 9998), + (9999, 9999) + ), + srid=2154 ) ) def test_trek_near_outdoorcourse(self): - response = self.get_trek_list({"near_outdoorcourse": self.course.pk}) + response = self.get_trek_list({'near_outdoorcourse': self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.trek1.pk) def test_trek_near_outdoorsite(self): - response = self.get_trek_list({"near_outdoorsite": self.site.pk}) + response = self.get_trek_list({'near_outdoorsite': self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.trek1.pk) def test_touristicevent_near_outdoorcourse(self): - response = self.get_touristicevent_list({"near_outdoorcourse": self.course.pk}) + response = self.get_touristicevent_list({'near_outdoorcourse': self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.touristic_event1.pk) def test_touristicevent_near_outdoorsite(self): - response = self.get_touristicevent_list({"near_outdoorsite": self.site.pk}) + response = self.get_touristicevent_list({'near_outdoorsite': self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.touristic_event1.pk) def test_touristiccontent_near_outdoorcourse(self): - response = self.get_touristiccontent_list( - {"near_outdoorcourse": self.course.pk} - ) + response = self.get_touristiccontent_list({'near_outdoorcourse': self.course.pk}) self.assertEqual(response.json()["count"], 1) - self.assertEqual( - response.json()["results"][0]["id"], self.touristic_content1.pk - ) + self.assertEqual(response.json()["results"][0]["id"], self.touristic_content1.pk) def test_touristiccontent_near_outdoorsite(self): - response = self.get_touristiccontent_list({"near_outdoorsite": self.site.pk}) + response = self.get_touristiccontent_list({'near_outdoorsite': self.site.pk}) self.assertEqual(response.json()["count"], 1) - self.assertEqual( - response.json()["results"][0]["id"], self.touristic_content1.pk - ) + self.assertEqual(response.json()["results"][0]["id"], self.touristic_content1.pk) def test_outdoorcourse_near_outdoorcourse(self): - response = self.get_course_list({"near_outdoorcourse": self.course.pk}) + response = self.get_course_list({'near_outdoorcourse': self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.course1.pk) def test_outdoorcourse_near_outdoorsite(self): - response = self.get_course_list({"near_outdoorsite": self.site.pk}) + response = self.get_course_list({'near_outdoorsite': self.site.pk}) self.assertEqual(response.json()["count"], 2) self.assertEqual(response.json()["results"][0]["id"], self.course.pk) self.assertEqual(response.json()["results"][1]["id"], self.course1.pk) def test_outdoorsite_near_outdoorcourse(self): - response = self.get_site_list({"near_outdoorcourse": self.course.pk}) + response = self.get_site_list({'near_outdoorcourse': self.course.pk}) self.assertEqual(response.json()["count"], 2) self.assertEqual(response.json()["results"][0]["id"], self.site.pk) self.assertEqual(response.json()["results"][1]["id"], self.site1.pk) def test_outdoorsite_near_outdoorsite(self): - response = self.get_site_list({"near_outdoorsite": self.site.pk}) + response = self.get_site_list({'near_outdoorsite': self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.site1.pk) def test_poi_near_outdoorcourse(self): - response = self.get_poi_list({"near_outdoorcourse": self.course.pk}) + response = self.get_poi_list({'near_outdoorcourse': self.course.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.poi1.pk) def test_poi_near_outdoorsite(self): - response = self.get_poi_list({"near_outdoorsite": self.site.pk}) + response = self.get_poi_list({'near_outdoorsite': self.site.pk}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.poi1.pk) def test_sensitivearea_near_outdoorcourse(self): - response = self.get_sensitivearea_list( - {"near_outdoorcourse": self.course.pk, "period": "any"} - ) + response = self.get_sensitivearea_list({'near_outdoorcourse': self.course.pk, 'period': 'any'}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.sensitivearea1.pk) def test_sensitivearea_near_outdoorsite(self): - response = self.get_sensitivearea_list( - {"near_outdoorsite": self.site.pk, "period": "any"} - ) + response = self.get_sensitivearea_list({'near_outdoorsite': self.site.pk, 'period': 'any'}) self.assertEqual(response.json()["count"], 1) self.assertEqual(response.json()["results"][0]["id"], self.sensitivearea1.pk) class NearbyContentFilterTestCase(BaseApiTest): + def test_list_objects_filtered_by_near_target(self): + get_list_funcs = [ self.get_site_list, self.get_course_list, @@ -4526,6 +3719,7 @@ def test_list_objects_filtered_by_near_target(self): class UpdateOrCreateDatesFilterTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.path1 = core_factory.PathFactory() @@ -4537,66 +3731,71 @@ def setUp(self): def test_updated_after_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({"updated_after": two_years_ago}) + response = self.get_path_list({'updated_after': two_years_ago}) self.assertEqual(response.json().get("count"), 2) def test_updated_after_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({"updated_after": in_two_years}) + response = self.get_path_list({'updated_after': in_two_years}) self.assertEqual(response.json().get("count"), 0) def test_updated_before_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({"updated_before": two_years_ago}) + response = self.get_path_list({'updated_before': two_years_ago}) self.assertEqual(response.json().get("count"), 0) def test_updated_before_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({"updated_before": in_two_years}) + response = self.get_path_list({'updated_before': in_two_years}) self.assertEqual(response.json().get("count"), 2) def test_created_after_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({"created_after": two_years_ago}) + response = self.get_path_list({'created_after': two_years_ago}) self.assertEqual(response.json().get("count"), 2) def test_created_after_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({"created_after": in_two_years}) + response = self.get_path_list({'created_after': in_two_years}) self.assertEqual(response.json().get("count"), 0) def test_created_before_filter(self): two_years_ago = (timezone.now() - relativedelta(years=2)).date() - response = self.get_path_list({"created_before": two_years_ago}) + response = self.get_path_list({'created_before': two_years_ago}) self.assertEqual(response.json().get("count"), 0) def test_created_before_filter_2(self): in_two_years = (timezone.now() + relativedelta(years=2)).date() - response = self.get_path_list({"created_before": in_two_years}) + response = self.get_path_list({'created_before': in_two_years}) self.assertEqual(response.json().get("count"), 2) class RootSitesOnlyFilterTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.site_root1 = outdoor_factory.SiteFactory() cls.site_root2 = outdoor_factory.SiteFactory() - cls.site_child1 = outdoor_factory.SiteFactory(parent=cls.site_root1) - cls.site_child2 = outdoor_factory.SiteFactory(parent=cls.site_child1) + cls.site_child1 = outdoor_factory.SiteFactory( + parent=cls.site_root1 + ) + cls.site_child2 = outdoor_factory.SiteFactory( + parent=cls.site_child1 + ) def test_return_all_sites_with_no_filter(self): response = self.get_site_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 4) + self.assertEqual(response.json()['count'], 4) def test_root_sites_only_filter(self): - response = self.get_site_list({"root_sites_only": "true"}) + response = self.get_site_list({'root_sites_only': "true"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 2) + returned_sites = response.json()['results'] all_ids = [] for type in returned_sites: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertIn(self.site_root1.pk, all_ids) self.assertIn(self.site_root2.pk, all_ids) self.assertNotIn(self.site_child1.pk, all_ids) @@ -4604,6 +3803,7 @@ def test_root_sites_only_filter(self): class SitesTypesFilterTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.site1 = outdoor_factory.SiteFactory() @@ -4611,33 +3811,32 @@ def setUpTestData(cls): cls.site3 = outdoor_factory.SiteFactory() def test_sites_type_filter_1(self): - response = self.get_site_list({"types": self.site1.type.pk}) + response = self.get_site_list({'types': self.site1.type.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 1) + returned_sites = response.json()['results'] all_ids = [] for type in returned_sites: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) self.assertNotIn(self.site3.pk, all_ids) def test_sites_type_filter_2(self): - response = self.get_site_list( - {"types": f"{self.site2.type.pk},{self.site3.type.pk}"} - ) + response = self.get_site_list({'types': f"{self.site2.type.pk},{self.site3.type.pk}"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 2) + returned_sites = response.json()['results'] all_ids = [] for type in returned_sites: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertNotIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) self.assertIn(self.site3.pk, all_ids) class SitesLabelsFilterTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.label_published = common_factory.LabelFactory(published=True) @@ -4649,91 +3848,80 @@ def setUpTestData(cls): cls.site3 = outdoor_factory.SiteFactory() def test_sites_label_filter_1(self): - response = self.get_site_list({"labels": self.label_published.pk}) + response = self.get_site_list({'labels': self.label_published.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 1) + returned_sites = response.json()['results'] all_ids = [] for type in returned_sites: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) self.assertNotIn(self.site3.pk, all_ids) def test_sites_label_filter_2(self): - response = self.get_site_list( - {"labels": f"{self.label_published.pk},{self.label_unpublished.pk}"} - ) + response = self.get_site_list({'labels': f"{self.label_published.pk},{self.label_unpublished.pk}"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 2) + returned_sites = response.json()['results'] all_ids = [] for type in returned_sites: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) self.assertNotIn(self.site3.pk, all_ids) def test_sites_labels_exclude_filter(self): - response = self.get_site_list({"labels_exclude": self.label_published.pk}) + response = self.get_site_list({'labels_exclude': self.label_published.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 2) - self.assertSetEqual( - {result["id"] for result in json_response.get("results")}, - {self.site2.pk, self.site3.pk}, - ) + self.assertEqual(len(json_response.get('results')), 2) + self.assertSetEqual({result['id'] for result in json_response.get('results')}, + {self.site2.pk, self.site3.pk}) site_a = outdoor_factory.SiteFactory() label = common_factory.LabelFactory.create() site_a.labels.add(label, self.label_published) - response = self.get_site_list({"labels_exclude": self.label_published.pk}) + response = self.get_site_list({'labels_exclude': self.label_published.pk}) # test response code self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 2) - self.assertSetEqual( - {result["id"] for result in json_response.get("results")}, - {self.site2.pk, self.site3.pk}, - ) + self.assertEqual(len(json_response.get('results')), 2) + self.assertSetEqual({result['id'] for result in json_response.get('results')}, + {self.site2.pk, self.site3.pk}) site_b = outdoor_factory.SiteFactory() label_2 = common_factory.LabelFactory.create() site_b.labels.add(label, label_2) - response = self.get_site_list( - {"labels_exclude": f"{self.label_published.pk},{label.pk}"} - ) + response = self.get_site_list({'labels_exclude': f'{self.label_published.pk},{label.pk}'}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 2) - self.assertSetEqual( - {result["id"] for result in json_response.get("results")}, - {self.site2.pk, self.site3.pk}, - ) + self.assertEqual(len(json_response.get('results')), 2) + self.assertSetEqual({result['id'] for result in json_response.get('results')}, + {self.site2.pk, self.site3.pk}) - response = self.get_site_list({"labels_exclude": label_2.pk}) + response = self.get_site_list({'labels_exclude': label_2.pk}) self.assertEqual(response.status_code, 200) json_response = response.json() - self.assertEqual(len(json_response.get("results")), 4) - self.assertSetEqual( - {result["id"] for result in json_response.get("results")}, - {self.site1.pk, self.site2.pk, self.site3.pk, site_a.pk}, - ) + self.assertEqual(len(json_response.get('results')), 4) + self.assertSetEqual({result['id'] for result in json_response.get('results')}, + {self.site1.pk, self.site2.pk, self.site3.pk, site_a.pk}) def test_sites_label_filter_published(self): response = self.get_site_list() self.assertEqual(response.status_code, 200) - results = response.json()["results"] - all_labels = [result["labels"] for result in results] + results = response.json()['results'] + all_labels = [result['labels'] for result in results] self.assertIn([self.label_published.pk], all_labels) self.assertNotIn([self.label_unpublished.pk], all_labels) class CoursesTypesFilterTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.course1 = outdoor_factory.CourseFactory() @@ -4741,39 +3929,39 @@ def setUpTestData(cls): cls.course3 = outdoor_factory.CourseFactory() def test_courses_type_filter_1(self): - response = self.get_course_list({"types": self.course1.type.pk}) + response = self.get_course_list({'types': self.course1.type.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_courses = response.json()["results"] + self.assertEqual(response.json()['count'], 1) + returned_courses = response.json()['results'] all_ids = [] for type in returned_courses: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertIn(self.course1.pk, all_ids) self.assertNotIn(self.course2.pk, all_ids) self.assertNotIn(self.course3.pk, all_ids) def test_courses_type_filter_2(self): - response = self.get_course_list( - {"types": f"{self.course2.type.pk},{self.course3.type.pk}"} - ) + response = self.get_course_list({'types': f"{self.course2.type.pk},{self.course3.type.pk}"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_courses = response.json()["results"] + self.assertEqual(response.json()['count'], 2) + returned_courses = response.json()['results'] all_ids = [] for type in returned_courses: - all_ids.append(type["id"]) + all_ids.append(type['id']) self.assertNotIn(self.course1.pk, all_ids) self.assertIn(self.course2.pk, all_ids) self.assertIn(self.course3.pk, all_ids) class TouristicContentTypeFilterTestCase(BaseApiTest): + @classmethod def setUpTestData(cls): cls.category1 = tourism_factory.TouristicContentCategoryFactory(label="POI") cls.category2 = tourism_factory.TouristicContentCategoryFactory(label="Food") cls.content_deleted = tourism_factory.TouristicContentFactory( - category=cls.category1, deleted=True + category=cls.category1, + deleted=True ) cls.content_not_published = tourism_factory.TouristicContentFactory( category=cls.category1, @@ -4799,17 +3987,15 @@ def setUpTestData(cls): published_en=True, ) - def assert_types_returned_in_first_category( - self, response, content_in_list, content_not_in_list - ): + def assert_types_returned_in_first_category(self, response, content_in_list, content_not_in_list): self.assertEqual(response.status_code, 200) self.assert_returned_types(1, response, content_in_list, content_not_in_list) self.assert_returned_types(2, response, content_in_list, content_not_in_list) def assert_returned_types(self, i, response, content_in_list, content_not_in_list): - returned_types = response.json()["results"][0]["types"][i - 1]["values"] + returned_types = response.json()['results'][0]['types'][i - 1]['values'] self.assertEqual(len(returned_types), len(content_in_list)) - all_ids = [type["id"] for type in returned_types] + all_ids = [type['id'] for type in returned_types] # type1 if i == 1: @@ -4827,59 +4013,31 @@ def assert_returned_types(self, i, response, content_in_list, content_not_in_lis def test_returned_published_not_deleted(self): response = self.get_touristiccontentcategory_list() types_in_list = [self.content_published_en, self.content_published_es_portal] - types_not_in_list = [ - self.content_deleted, - self.content_not_published, - self.content_cat2, - ] - self.assert_types_returned_in_first_category( - response, types_in_list, types_not_in_list - ) + types_not_in_list = [self.content_deleted, self.content_not_published, self.content_cat2] + self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) def test_returned_published_not_deleted_by_lang(self): - response = self.get_touristiccontentcategory_list({"language": "en"}) + response = self.get_touristiccontentcategory_list({'language': 'en'}) types_in_list = [self.content_published_en] - types_not_in_list = [ - self.content_deleted, - self.content_not_published, - self.content_published_es_portal, - self.content_cat2, - ] - self.assert_types_returned_in_first_category( - response, types_in_list, types_not_in_list - ) + types_not_in_list = [self.content_deleted, self.content_not_published, self.content_published_es_portal, self.content_cat2] + self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) def test_returned_published_not_deleted_by_portal(self): - response = self.get_touristiccontentcategory_list({"portals": self.portal.pk}) + response = self.get_touristiccontentcategory_list({'portals': self.portal.pk}) types_in_list = [self.content_published_es_portal] - types_not_in_list = [ - self.content_deleted, - self.content_not_published, - self.content_published_en, - self.content_cat2, - ] - self.assert_types_returned_in_first_category( - response, types_in_list, types_not_in_list - ) + types_not_in_list = [self.content_deleted, self.content_not_published, self.content_published_en, self.content_cat2] + self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) def test_returned_published_not_deleted_by_portal_and_lang(self): - response = self.get_touristiccontentcategory_list( - {"portals": self.portal.pk, "language": "es"} - ) + response = self.get_touristiccontentcategory_list({'portals': self.portal.pk, 'language': 'es'}) types_in_list = [self.content_published_es_portal] - types_not_in_list = [ - self.content_deleted, - self.content_not_published, - self.content_published_en, - self.content_cat2, - ] - self.assert_types_returned_in_first_category( - response, types_in_list, types_not_in_list - ) + types_not_in_list = [self.content_deleted, self.content_not_published, self.content_published_en, self.content_cat2] + self.assert_types_returned_in_first_category(response, types_in_list, types_not_in_list) class SiteTypeFilterTestCase(BaseApiTest): - """Test filtering depending on published, deleted content for outdoor site types""" + """ Test filtering depending on published, deleted content for outdoor site types + """ @classmethod def setUpTestData(cls): @@ -4889,55 +4047,54 @@ def setUpTestData(cls): # Type with no published site -> don't send it cls.type_with_no_published_site = outdoor_factory.SiteTypeFactory() cls.not_published_site = outdoor_factory.SiteFactory( - published=False, type=cls.type_with_no_published_site + published=False, + type=cls.type_with_no_published_site ) # Type with published and not deleted site -> send it cls.type_with_published_and_not_deleted_site = outdoor_factory.SiteTypeFactory() cls.published_and_not_deleted_site = outdoor_factory.SiteFactory( - published_en=True, type=cls.type_with_published_and_not_deleted_site + published_en=True, + type=cls.type_with_published_and_not_deleted_site ) # Type with published_fr and not deleted site -> send it when language=fr - cls.type_with_published_and_not_deleted_site_with_lang = ( - outdoor_factory.SiteTypeFactory() - ) + cls.type_with_published_and_not_deleted_site_with_lang = outdoor_factory.SiteTypeFactory() cls.published_and_not_deleted_site_with_lang = outdoor_factory.SiteFactory( published_fr=True, - type=cls.type_with_published_and_not_deleted_site_with_lang, + type=cls.type_with_published_and_not_deleted_site_with_lang ) def test_sites_type_list_returns_published(self): - """Assert API returns only types with published sites""" + """ Assert API returns only types with published sites + """ response = self.get_sitetype_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 2) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) self.assertIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) def test_sites_type_list_returns_published_in_language(self): - """Assert API returns only published sites in specified language""" - response = self.get_sitetype_list({"language": "fr"}) + """ Assert API returns only published sites in specified language + """ + response = self.get_sitetype_list({'language': 'fr'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) self.assertNotIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) class SiteTypeFilterTestCaseByPortal(SiteTypeFilterTestCase): - """Test filtering depending on portal for outdoor site types""" + """ Test filtering depending on portal for outdoor site types + """ @classmethod def setUpTestData(cls): @@ -4966,44 +4123,43 @@ def setUpTestData(cls): cls.not_deleted_site_on_other_portal.portal.set([cls.other_portal]) def test_sites_type_list_returns_published(self): - """Assert API returns only types with published site on portal""" - response = self.get_sitetype_list({"portals": self.queried_portal.pk}) + """ Assert API returns only types with published site on portal + """ + response = self.get_sitetype_list({'portals': self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 0) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 0) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) # Didn't set portal on these ones yet self.assertNotIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertNotIn( - self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids - ) + self.assertNotIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) def test_sites_type_list_returns_published_2(self): - """Assert API returns only types with published sites on portal""" + """ Assert API returns only types with published sites on portal + """ # Type with published and not deleted site on portal -> send it self.published_and_not_deleted_site.portal.set([self.queried_portal]) # Type with published_fr and not deleted site on portal -> send it when language=fr self.published_and_not_deleted_site_with_lang.portal.set([self.queried_portal]) - response = self.get_sitetype_list({"portals": self.queried_portal.pk}) + response = self.get_sitetype_list({'portals': self.queried_portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 2) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_site.pk, all_ids) self.assertNotIn(self.type_with_no_published_site.pk, all_ids) # Portal is set this time self.assertIn(self.type_with_published_and_not_deleted_site.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_site_with_lang.pk, all_ids) class CourseTypeFilterTestCase(BaseApiTest): - """Test filtering depending on published, deleted content for outdoor course types""" + """ Test filtering depending on published, deleted content for outdoor course types + """ @classmethod def setUpTestData(cls): @@ -5013,65 +4169,60 @@ def setUpTestData(cls): # Type with no published course -> don't send it cls.type_with_no_published_course = outdoor_factory.CourseTypeFactory() cls.not_published_course = outdoor_factory.CourseFactory( - published=False, type=cls.type_with_no_published_course + published=False, + type=cls.type_with_no_published_course ) # Type with published and not deleted course -> send it - cls.type_with_published_and_not_deleted_course = ( - outdoor_factory.CourseTypeFactory() - ) + cls.type_with_published_and_not_deleted_course = outdoor_factory.CourseTypeFactory() cls.published_and_not_deleted_course = outdoor_factory.CourseFactory( - published_en=True, type=cls.type_with_published_and_not_deleted_course + published_en=True, + type=cls.type_with_published_and_not_deleted_course ) # Type with published_fr and not deleted course -> send it when language=fr - cls.type_with_published_and_not_deleted_course_with_lang = ( - outdoor_factory.CourseTypeFactory() - ) + cls.type_with_published_and_not_deleted_course_with_lang = outdoor_factory.CourseTypeFactory() cls.published_and_not_deleted_course_with_lang = outdoor_factory.CourseFactory( published_fr=True, - type=cls.type_with_published_and_not_deleted_course_with_lang, + type=cls.type_with_published_and_not_deleted_course_with_lang ) def test_course_type_list_returns_published(self): - """Assert API returns only types with published course""" + """ Assert API returns only types with published course + """ response = self.get_coursetype_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 2) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_course.pk, all_ids) self.assertNotIn(self.type_with_no_published_course.pk, all_ids) self.assertIn(self.type_with_published_and_not_deleted_course.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids) def test_course_type_list_returns_published_in_language(self): - """Assert API returns only published course in specified language""" - response = self.get_coursetype_list({"language": "fr"}) + """ Assert API returns only published course in specified language + """ + response = self.get_coursetype_list({'language': 'fr'}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertNotIn(self.type_with_no_course.pk, all_ids) self.assertNotIn(self.type_with_no_published_course.pk, all_ids) self.assertNotIn(self.type_with_published_and_not_deleted_course.pk, all_ids) - self.assertIn( - self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids - ) + self.assertIn(self.type_with_published_and_not_deleted_course_with_lang.pk, all_ids) class OutdoorFilterByRatingsTestCase(BaseApiTest): - """Test filtering on ratings for outdoor course""" + """ Test filtering on ratings for outdoor course + """ @classmethod def setUpTestData(cls): cls.site1 = outdoor_factory.SiteFactory() cls.site2 = outdoor_factory.SiteFactory() - cls.rating_scale = outdoor_factory.RatingScaleFactory( - practice=cls.site1.practice - ) + cls.rating_scale = outdoor_factory.RatingScaleFactory(practice=cls.site1.practice) cls.rating1 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.rating2 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.site1.ratings.set([cls.rating1]) @@ -5082,67 +4233,64 @@ def setUpTestData(cls): cls.course2.ratings.set([cls.rating2]) def test_site_list_ratings_filter(self): - response = self.get_site_list({"ratings": self.rating1.pk}) + response = self.get_site_list({'ratings': self.rating1.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 1) + returned_sites = response.json()['results'] all_ids = [] for site in returned_sites: - all_ids.append(site["id"]) + all_ids.append(site['id']) self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) def test_site_list_ratings_filter2(self): - response = self.get_site_list({"ratings": self.rating2.pk}) + response = self.get_site_list({'ratings': self.rating2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 1) + returned_sites = response.json()['results'] all_ids = [] for site in returned_sites: - all_ids.append(site["id"]) + all_ids.append(site['id']) self.assertIn(self.site2.pk, all_ids) self.assertNotIn(self.site1.pk, all_ids) def test_site_list_ratings_filter3(self): - response = self.get_site_list( - {"ratings": f"{self.rating1.pk},{self.rating2.pk}"} - ) + response = self.get_site_list({'ratings': f"{self.rating1.pk},{self.rating2.pk}"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 2) + returned_sites = response.json()['results'] all_ids = [] for site in returned_sites: - all_ids.append(site["id"]) + all_ids.append(site['id']) self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) def test_course_list_ratings_filter(self): - response = self.get_course_list( - {"ratings": f"{self.rating1.pk},{self.rating2.pk}"} - ) + response = self.get_course_list({'ratings': f"{self.rating1.pk},{self.rating2.pk}"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 2) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 2) + returned_sites = response.json()['results'] all_ids = [] for site in returned_sites: - all_ids.append(site["id"]) + all_ids.append(site['id']) self.assertIn(self.course1.pk, all_ids) self.assertIn(self.course2.pk, all_ids) def test_course_list_ratings_filter2(self): - response = self.get_course_list({"ratings": self.rating2.pk}) + response = self.get_course_list({'ratings': self.rating2.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_sites = response.json()["results"] + self.assertEqual(response.json()['count'], 1) + returned_sites = response.json()['results'] all_ids = [] for site in returned_sites: - all_ids.append(site["id"]) + all_ids.append(site['id']) self.assertNotIn(self.course1.pk, all_ids) self.assertIn(self.course2.pk, all_ids) class OutdoorFilterBySuperPracticesTestCase(BaseApiTest): - """Test APIV2 filtering on ratings on sites""" + """ Test APIV2 filtering on ratings on sites + """ @classmethod def setUpTestData(cls): @@ -5152,22 +4300,16 @@ def setUpTestData(cls): cls.practice3 = outdoor_factory.PracticeFactory() cls.practice4 = outdoor_factory.PracticeFactory() cls.site1 = outdoor_factory.SiteFactory(practice=cls.practice1) - cls.site2 = outdoor_factory.SiteFactory( - practice=cls.practice2, parent=cls.site1 - ) - cls.site3 = outdoor_factory.SiteFactory( - practice=cls.practice3, parent=cls.site2 - ) - cls.site4 = outdoor_factory.SiteFactory( - practice=cls.practice4, parent=cls.site2 - ) + cls.site2 = outdoor_factory.SiteFactory(practice=cls.practice2, parent=cls.site1) + cls.site3 = outdoor_factory.SiteFactory(practice=cls.practice3, parent=cls.site2) + cls.site4 = outdoor_factory.SiteFactory(practice=cls.practice4, parent=cls.site2) def test_filter_practice_in_tree_hierarchy(self): - response = self.get_site_list({"practices_in_hierarchy": self.practice1.pk}) + response = self.get_site_list({'practices_in_hierarchy': self.practice1.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) @@ -5175,11 +4317,11 @@ def test_filter_practice_in_tree_hierarchy(self): self.assertNotIn(self.site4.pk, all_ids) def test_filter_practice_in_tree_hierarchy2(self): - response = self.get_site_list({"practices_in_hierarchy": self.practice3.pk}) + response = self.get_site_list({'practices_in_hierarchy': self.practice3.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 3) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 3) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) @@ -5188,14 +4330,13 @@ def test_filter_practice_in_tree_hierarchy2(self): class OutdoorFilterBySuperRatingsTestCase(BaseApiTest): - """Test APIV2 filtering on ratings on sites in hierarchy""" + """ Test APIV2 filtering on ratings on sites in hierarchy + """ @classmethod def setUpTestData(cls): cls.site1 = outdoor_factory.SiteFactory() - cls.rating_scale = outdoor_factory.RatingScaleFactory( - practice=cls.site1.practice - ) + cls.rating_scale = outdoor_factory.RatingScaleFactory(practice=cls.site1.practice) cls.rating1 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.rating2 = outdoor_factory.RatingFactory(scale=cls.rating_scale) cls.rating3 = outdoor_factory.RatingFactory(scale=cls.rating_scale) @@ -5209,11 +4350,11 @@ def setUpTestData(cls): cls.site4.ratings.set([cls.rating4]) def test_filter_ratings_in_tree_hierarchy(self): - response = self.get_site_list({"ratings_in_hierarchy": self.rating1.pk}) + response = self.get_site_list({'ratings_in_hierarchy': self.rating1.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertNotIn(self.site2.pk, all_ids) @@ -5221,11 +4362,11 @@ def test_filter_ratings_in_tree_hierarchy(self): self.assertNotIn(self.site4.pk, all_ids) def test_filter_ratings_in_tree_hierarchy2(self): - response = self.get_site_list({"ratings_in_hierarchy": self.rating3.pk}) + response = self.get_site_list({'ratings_in_hierarchy': self.rating3.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 3) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 3) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) @@ -5233,13 +4374,11 @@ def test_filter_ratings_in_tree_hierarchy2(self): self.assertNotIn(self.site4.pk, all_ids) def test_filter_ratings_in_tree_hierarchy3(self): - response = self.get_site_list( - {"ratings_in_hierarchy": f"{self.rating3.pk}, {self.rating4.pk}"} - ) + response = self.get_site_list({'ratings_in_hierarchy': f"{self.rating3.pk}, {self.rating4.pk}"}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 4) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 4) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.site1.pk, all_ids) self.assertIn(self.site2.pk, all_ids) @@ -5248,56 +4387,36 @@ def test_filter_ratings_in_tree_hierarchy3(self): class OutdoorSiteHierarchySerializingTestCase(BaseApiTest): - """Test APIV2 serialzing of parents and children in site detail""" + """ Test APIV2 serialzing of parents and children in site detail + """ @classmethod def setUpTestData(cls): cls.site_root = outdoor_factory.SiteFactory(published=True) - cls.site_node = outdoor_factory.SiteFactory( - published=True, parent=cls.site_root - ) - cls.site_leaf_published = outdoor_factory.SiteFactory( - published=True, parent=cls.site_node - ) - cls.site_leaf_published_2 = outdoor_factory.SiteFactory( - published=True, parent=cls.site_node - ) - cls.site_leaf_unpublished = outdoor_factory.SiteFactory( - published=False, parent=cls.site_node - ) + cls.site_node = outdoor_factory.SiteFactory(published=True, parent=cls.site_root) + cls.site_leaf_published = outdoor_factory.SiteFactory(published=True, parent=cls.site_node) + cls.site_leaf_published_2 = outdoor_factory.SiteFactory(published=True, parent=cls.site_node) + cls.site_leaf_unpublished = outdoor_factory.SiteFactory(published=False, parent=cls.site_node) cls.site_root_unpublished = outdoor_factory.SiteFactory(published=False) - cls.site_node_parent_unpublished = outdoor_factory.SiteFactory( - published=True, parent=cls.site_root_unpublished - ) + cls.site_node_parent_unpublished = outdoor_factory.SiteFactory(published=True, parent=cls.site_root_unpublished) cls.site_root_fr = outdoor_factory.SiteFactory(published_fr=True) - cls.site_node_fr = outdoor_factory.SiteFactory( - published_fr=True, parent=cls.site_root_fr - ) - cls.site_leaf_published_fr = outdoor_factory.SiteFactory( - published_fr=True, parent=cls.site_node_fr - ) - cls.site_leaf_published_not_fr = outdoor_factory.SiteFactory( - published=True, - published_fr=False, - published_en=True, - parent=cls.site_node_fr, - ) - cls.site_leaf_unpublished_fr = outdoor_factory.SiteFactory( - published_fr=False, parent=cls.site_node_fr - ) + cls.site_node_fr = outdoor_factory.SiteFactory(published_fr=True, parent=cls.site_root_fr) + cls.site_leaf_published_fr = outdoor_factory.SiteFactory(published_fr=True, parent=cls.site_node_fr) + cls.site_leaf_published_not_fr = outdoor_factory.SiteFactory(published=True, published_fr=False, published_en=True, parent=cls.site_node_fr) + cls.site_leaf_unpublished_fr = outdoor_factory.SiteFactory(published_fr=False, parent=cls.site_node_fr) def test_site_parent_published_serializing(self): response = self.get_site_detail(self.site_node.pk) self.assertEqual(response.status_code, 200) - parent = response.json()["parent"] + parent = response.json()['parent'] self.assertEqual(parent, self.site_root.pk) def test_site_children_published_serializing(self): response = self.get_site_detail(self.site_node.pk) self.assertEqual(response.status_code, 200) - children = response.json()["children"] + children = response.json()['children'] self.assertEqual(2, len(children)) self.assertIn(self.site_leaf_published.pk, children) self.assertIn(self.site_leaf_published_2.pk, children) @@ -5306,30 +4425,28 @@ def test_site_children_published_serializing(self): def test_site_parent_unpublished_serializing(self): response = self.get_site_detail(self.site_node_parent_unpublished.pk) self.assertEqual(response.status_code, 200) - parent = response.json()["parent"] + parent = response.json()['parent'] self.assertEqual(parent, None) self.assertIsNotNone(self.site_node_parent_unpublished.parent) def test_site_parent_and_children_serializing_by_lang(self): - response = self.get_site_list({"language": "fr"}) + response = self.get_site_list({'language': 'fr'}) self.assertEqual(response.status_code, 200) - returned_sites = response.json()["results"] - site_published_fr = next( - (site for site in returned_sites if site["id"] == self.site_node_fr.pk), - None, - ) + returned_sites = response.json()['results'] + site_published_fr = next((site for site in returned_sites if site['id'] == self.site_node_fr.pk), None) self.assertIsNotNone(site_published_fr) - children = site_published_fr["children"] + children = site_published_fr['children'] self.assertEqual(1, len(children)) self.assertIn(self.site_leaf_published_fr.pk, children) self.assertNotIn(self.site_leaf_published_not_fr.pk, children) self.assertNotIn(self.site_leaf_unpublished_fr.pk, children) - parent = site_published_fr["parent"] + parent = site_published_fr['parent'] self.assertEqual(parent, self.site_root_fr.pk) class OutdoorFilterByPracticesTestCase(BaseApiTest): - """Test APIV2 filtering by practices on courses""" + """ Test APIV2 filtering by practices on courses + """ @classmethod def setUpTestData(cls): @@ -5338,9 +4455,7 @@ def setUpTestData(cls): cls.course_practice = outdoor_factory.CourseFactory() cls.course_practice.parent_sites.set([cls.site_practice]) cls.other_practice = outdoor_factory.PracticeFactory() - cls.site_other_practice = outdoor_factory.SiteFactory( - practice=cls.other_practice - ) + cls.site_other_practice = outdoor_factory.SiteFactory(practice=cls.other_practice) cls.course_other_practice = outdoor_factory.CourseFactory() cls.course_other_practice.parent_sites.set([cls.site_other_practice]) @@ -5349,25 +4464,23 @@ def setUpTestData(cls): cls.course_site_no_practice.parent_sites.set([cls.site_no_practice]) def test_filter_practices_on_courses(self): - response = self.get_course_list({"practices": self.practice.pk}) + response = self.get_course_list({'practices': self.practice.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.course_practice.pk, all_ids) self.assertNotIn(self.course_site_no_practice.pk, all_ids) self.assertNotIn(self.course_other_practice.pk, all_ids) def test_filter_practices_on_courses2(self): - self.course_practice.parent_sites.set( - [self.site_practice, self.site_other_practice] - ) - response = self.get_course_list({"practices": self.practice.pk}) + self.course_practice.parent_sites.set([self.site_practice, self.site_other_practice]) + response = self.get_course_list({'practices': self.practice.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.course_practice.pk, all_ids) self.assertNotIn(self.course_site_no_practice.pk, all_ids) @@ -5375,7 +4488,8 @@ def test_filter_practices_on_courses2(self): class OutdoorFilterByPortal(BaseApiTest): - """Test APIV2 filtering on ratings on sites in hierarchy""" + """ Test APIV2 filtering on ratings on sites in hierarchy + """ @classmethod def setUpTestData(cls): @@ -5391,21 +4505,21 @@ def setUpTestData(cls): cls.site.information_desks.set([cls.information_desk]) def test_filter_courses_by_portal(self): - response = self.get_course_list({"portals": self.portal.pk}) + response = self.get_course_list({'portals': self.portal.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.course.pk, all_ids) self.assertNotIn(self.course2.pk, all_ids) def test_filter_courses_by_themes(self): - response = self.get_course_list({"themes": self.theme.pk}) + response = self.get_course_list({'themes': self.theme.pk}) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.course.pk, all_ids) self.assertNotIn(self.course2.pk, all_ids) @@ -5413,109 +4527,80 @@ def test_filter_courses_by_themes(self): def test_filter_info_desks_by_portal_and_outdoor(self): response = self.get_informationdesk_list() self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - returned_types = response.json()["results"] - all_ids = [type["id"] for type in returned_types] + self.assertEqual(response.json()['count'], 1) + returned_types = response.json()['results'] + all_ids = [type['id'] for type in returned_types] self.assertIn(self.information_desk.pk, all_ids) class AltimetryCacheTests(BaseApiTest): - """Test APIV2 DEM serialization is cached""" - + """ Test APIV2 DEM serialization is cached """ @classmethod def setUpTestData(cls): # Create a simple fake DEM with connection.cursor() as cur: - cur.execute( - "INSERT INTO altimetry_dem (rast) VALUES (ST_MakeEmptyRaster(100, 125, 0, 125, 25, -25, 0, 0, %s))", - [settings.SRID], - ) - cur.execute("UPDATE altimetry_dem SET rast = ST_AddBand(rast, '16BSI')") - demvalues = [ - [0, 0, 3, 5], - [2, 2, 10, 15], - [5, 15, 20, 25], - [20, 25, 30, 35], - [30, 35, 40, 45], - ] + cur.execute('INSERT INTO altimetry_dem (rast) VALUES (ST_MakeEmptyRaster(100, 125, 0, 125, 25, -25, 0, 0, %s))', [settings.SRID]) + cur.execute('UPDATE altimetry_dem SET rast = ST_AddBand(rast, \'16BSI\')') + demvalues = [[0, 0, 3, 5], [2, 2, 10, 15], [5, 15, 20, 25], [20, 25, 30, 35], [30, 35, 40, 45]] for y in range(0, 5): for x in range(0, 4): - cur.execute( - "UPDATE altimetry_dem SET rast = ST_SetValue(rast, %s, %s, %s::float)", - [x + 1, y + 1, demvalues[y][x]], - ) - cls.path = core_factory.PathFactory.create( - geom=LineString((1, 101), (81, 101), (81, 99)) - ) + cur.execute('UPDATE altimetry_dem SET rast = ST_SetValue(rast, %s, %s, %s::float)', [x + 1, y + 1, demvalues[y][x]]) + cls.path = core_factory.PathFactory.create(geom=LineString((1, 101), (81, 101), (81, 99))) cls.trek = trek_factory.TrekFactory.create(paths=[cls.path]) - @skipIf( - not settings.TREKKING_TOPOLOGY_ENABLED, "Test with dynamic segmentation only" - ) + @skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only') def test_cache_is_used_when_getting_trek_DEM(self): # There are 9 queries to get trek DEM with self.assertNumQueries(10): - response = self.client.get(reverse("apiv2:trek-dem", args=(self.trek.pk,))) + response = self.client.get(reverse('apiv2:trek-dem', args=(self.trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response["Content-Type"], "application/json") + self.assertEqual(response['Content-Type'], 'application/json') # When cache is used there is single query to get trek DEM with self.assertNumQueries(1): - response = self.client.get(reverse("apiv2:trek-dem", args=(self.trek.pk,))) + response = self.client.get(reverse('apiv2:trek-dem', args=(self.trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response["Content-Type"], "application/json") + self.assertEqual(response['Content-Type'], 'application/json') - @skipIf( - settings.TREKKING_TOPOLOGY_ENABLED, "Test without dynamic segmentation only" - ) + @skipIf(settings.TREKKING_TOPOLOGY_ENABLED, 'Test without dynamic segmentation only') def test_cache_is_used_when_getting_trek_DEM_nds(self): - trek = trek_factory.TrekFactory.create( - geom=LineString((1, 101), (81, 101), (81, 99)) - ) + trek = trek_factory.TrekFactory.create(geom=LineString((1, 101), (81, 101), (81, 99))) # There are 9 queries to get trek DEM with self.assertNumQueries(10): - response = self.client.get(reverse("apiv2:trek-dem", args=(trek.pk,))) + response = self.client.get(reverse('apiv2:trek-dem', args=(trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response["Content-Type"], "application/json") + self.assertEqual(response['Content-Type'], 'application/json') # When cache is used there is single query to get trek DEM with self.assertNumQueries(1): - response = self.client.get(reverse("apiv2:trek-dem", args=(trek.pk,))) + response = self.client.get(reverse('apiv2:trek-dem', args=(trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response["Content-Type"], "application/json") + self.assertEqual(response['Content-Type'], 'application/json') def test_cache_is_used_when_getting_trek_profile(self): # There are 8 queries to get trek profile with self.assertNumQueries(10): - response = self.client.get( - reverse("apiv2:trek-profile", args=(self.trek.pk,)) - ) + response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response["Content-Type"], "application/json") + self.assertEqual(response['Content-Type'], 'application/json') self.assertIn("profile", response.json().keys()) # When cache is used there is single query to get trek profile with self.assertNumQueries(1): - response = self.client.get( - reverse("apiv2:trek-profile", args=(self.trek.pk,)) - ) + response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,))) self.assertEqual(response.status_code, 200) - self.assertEqual(response["Content-Type"], "application/json") + self.assertEqual(response['Content-Type'], 'application/json') self.assertIn("profile", response.json().keys()) def test_cache_is_used_when_getting_trek_profile_svg(self): # There are 8 queries to get trek profile svg with self.assertNumQueries(10): - response = self.client.get( - reverse("apiv2:trek-profile", args=(self.trek.pk,)), {"format": "svg"} - ) + response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,)), {"format": "svg"}) self.assertEqual(response.status_code, 200) - self.assertIn("image/svg+xml", response["Content-Type"]) + self.assertIn('image/svg+xml', response['Content-Type']) # When cache is used there is single query to get trek profile with self.assertNumQueries(1): - response = self.client.get( - reverse("apiv2:trek-profile", args=(self.trek.pk,)), {"format": "svg"} - ) + response = self.client.get(reverse('apiv2:trek-profile', args=(self.trek.pk,)), {"format": "svg"}) self.assertEqual(response.status_code, 200) - self.assertIn("image/svg+xml", response["Content-Type"]) + self.assertIn('image/svg+xml', response['Content-Type']) class GenericCacheTestCase(APITestCase): @@ -5525,42 +4610,32 @@ def setUpTestData(cls): def test_cache_invalidates_along_x_forwarded_proto_header(self): with self.assertNumQueries(2): - response = self.client.get( - reverse("apiv2:practice-detail", args=(self.practice.pk,)) - ) + response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,))) data = response.json() - self.assertTrue(data["pictogram"].startswith("http://")) + self.assertTrue(data['pictogram'].startswith('http://')) # after cache hit, query number is 1 with self.assertNumQueries(1): - response = self.client.get( - reverse("apiv2:practice-detail", args=(self.practice.pk,)) - ) + response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,))) data = response.json() - self.assertTrue(data["pictogram"].startswith("http://")) + self.assertTrue(data['pictogram'].startswith('http://')) # we used custom header, cache is invalidate and url is now https with self.assertNumQueries(2): - response = self.client.get( - reverse("apiv2:practice-detail", args=(self.practice.pk,)), - HTTP_X_FORWARDED_PROTO="https", - ) + response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,)), + HTTP_X_FORWARDED_PROTO='https') data = response.json() - self.assertTrue(data["pictogram"].startswith("https://")) + self.assertTrue(data['pictogram'].startswith('https://')) # cache is hit with self.assertNumQueries(1): - response = self.client.get( - reverse("apiv2:practice-detail", args=(self.practice.pk,)), - HTTP_X_FORWARDED_PROTO="https", - ) + response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,)), + HTTP_X_FORWARDED_PROTO='https') data = response.json() - self.assertTrue(data["pictogram"].startswith("https://")) + self.assertTrue(data['pictogram'].startswith('https://')) # first request is always cached with self.assertNumQueries(1): - response = self.client.get( - reverse("apiv2:practice-detail", args=(self.practice.pk,)) - ) + response = self.client.get(reverse('apiv2:practice-detail', args=(self.practice.pk,))) data = response.json() - self.assertTrue(data["pictogram"].startswith("http://")) + self.assertTrue(data['pictogram'].startswith('http://')) From 62529f00e8694ac93137def479af2fbcdfb29795 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Wed, 20 Sep 2023 16:04:51 +0200 Subject: [PATCH 36/43] improve openair list perfs --- geotrek/sensitivity/models.py | 14 -------------- geotrek/sensitivity/views.py | 12 ++++++++++-- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/geotrek/sensitivity/models.py b/geotrek/sensitivity/models.py index f322cb82ee..de1b83450c 100644 --- a/geotrek/sensitivity/models.py +++ b/geotrek/sensitivity/models.py @@ -251,20 +251,6 @@ def openair(self): } return wkt2openair(**data) - @property - def wgs84_geom(self): - geom = self.geom - if geom.geom_type == 'Point': - geom = geom.buffer(self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, 4) - if self.species.radius: - geometry = () - for coords in geom.coords[0]: - coords += (self.species.radius, ) - geometry += (coords, ) - geom = GEOSGeometry(Polygon(geometry), srid=settings.SRID) - geom = geom.transform(4326, clone=True) # KML uses WGS84 - return geom - def is_public(self): return self.published diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 58fc7c629b..70488e6869 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -211,7 +211,9 @@ class SensitiveAreaOpenAirList(PublicOrReadPermMixin, ListView): def get_queryset(self): aerial_practice = SportPractice.objects.filter(name__in=settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES) - return SensitiveArea.objects.filter(species__practices__in=aerial_practice) + return SensitiveArea.objects.filter( + species__practices__in=aerial_practice, published=True + ).select_related('species') def render_to_response(self, context): areas = self.get_queryset() @@ -220,7 +222,13 @@ def render_to_response(self, context): * This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) airspace_list = [] for a in areas: - airspace_list.append(a.openair()) + if not a.openair(): + logger.error( + "The openair format cannot be generated for area %s-%s", + a.id, a + ) + else: + airspace_list.append(a.openair()) airspace_core = '\n\n'.join(airspace_list) airspace_file = file_header + airspace_core response = HttpResponse(airspace_file, content_type='application/octet-stream; charset=UTF-8') From 70d15bbc1e14c20430c55ee5fe048038ee330b28 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Wed, 20 Sep 2023 16:08:23 +0200 Subject: [PATCH 37/43] test cleanup --- geotrek/sensitivity/tests/test_models.py | 27 ------------------------ 1 file changed, 27 deletions(-) diff --git a/geotrek/sensitivity/tests/test_models.py b/geotrek/sensitivity/tests/test_models.py index f30b6dde88..c10fe1ec43 100644 --- a/geotrek/sensitivity/tests/test_models.py +++ b/geotrek/sensitivity/tests/test_models.py @@ -4,7 +4,6 @@ from django.test import TestCase from django.test.utils import override_settings from django.conf import settings -from django.contrib.gis.geos import GEOSGeometry from geotrek.sensitivity.tests.factories import SensitiveAreaFactory, SpeciesFactory from geotrek.trekking.tests.factories import TrekFactory @@ -137,32 +136,6 @@ def test_is_public(self): sensitive_area.published = False self.assertFalse(sensitive_area.is_public()) - def test_wgs84_geom(self): - """Test geometry transform to SRID WGS84""" - sensitive_area = SensitiveAreaFactory.create( - geom="POLYGON((" - "700000 6600000, " - "700000 6600003, " - "700003 6600003, " - "700003 6600000, " - "700000 6600000" - "))" - ) - self.assertGreater( - similar_string( - GEOSGeometry( - "SRID=4326;POLYGON ((" - "3 46.49999999999994, 3 46.50002701349548, " - "3.000039118674989 46.50002701348879, " - "3.000039118655609 46.49999999999324, " - "3 46.49999999999994" - "))" - ).wkt, - sensitive_area.wgs84_geom.wkt, - ), - 0.9, - ) - @override_settings(SENSITIVE_AREA_INTERSECTION_MARGIN=0) def test_trek_sensitive_area(self): """ From f1e07a004f75c842b454f4def17992ab027ee12e Mon Sep 17 00:00:00 2001 From: lpofredc Date: Wed, 20 Sep 2023 23:08:45 +0200 Subject: [PATCH 38/43] WIP openair view tests --- geotrek/sensitivity/tests/test_views.py | 158 ++++++++++++++++++------ 1 file changed, 117 insertions(+), 41 deletions(-) diff --git a/geotrek/sensitivity/tests/test_views.py b/geotrek/sensitivity/tests/test_views.py index 30d12c2e53..dedee9f6ae 100644 --- a/geotrek/sensitivity/tests/test_views.py +++ b/geotrek/sensitivity/tests/test_views.py @@ -1,14 +1,20 @@ from freezegun import freeze_time - +import datetime from django.contrib.auth.models import User, Permission from django.test import TestCase from django.test.utils import override_settings +from django.urls import reverse from geotrek.authent.tests.factories import StructureFactory, UserProfileFactory from geotrek.authent.tests.base import AuthentFixturesTest from geotrek.trekking.tests.base import TrekkingManagerTest from geotrek.common.tests import TranslationResetMixin -from geotrek.sensitivity.tests.factories import RegulatorySensitiveAreaFactory, SensitiveAreaFactory, MultiPolygonSensitiveAreaFactory +from geotrek.sensitivity.tests.factories import ( + SpeciesFactory, + RegulatorySensitiveAreaFactory, + SensitiveAreaFactory, + MultiPolygonSensitiveAreaFactory +) from geotrek.sensitivity.models import SportPractice @@ -35,24 +41,24 @@ def tearDown(self): self.client.logout() def test_can_edit_same_structure(self): - url = "/sensitivearea/edit/{pk}/".format(pk=self.area1.pk) + url = reverse("sensitivity:sensitivearea_update", kwargs={"pk": self.area1.pk}) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_cannot_edit_other_structure(self): - url = "/sensitivearea/edit/{pk}/".format(pk=self.area2.pk) + url = reverse("sensitivity:sensitivearea_update", kwargs={"pk": self.area2.pk}) response = self.client.get(url) - self.assertRedirects(response, "/sensitivearea/{pk}/".format(pk=self.area2.pk)) + self.assertRedirects(response, reverse("sensitivity:sensitivearea_detail", kwargs={"pk": self.area2.pk})) def test_can_delete_same_structure(self): - url = "/sensitivearea/delete/{pk}/".format(pk=self.area1.pk) + url = reverse("sensitivity:sensitivearea_delete", kwargs={"pk": self.area1.pk}) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_cannot_delete_other_structure(self): - url = "/sensitivearea/delete/{pk}/".format(pk=self.area2.pk) + url = reverse("sensitivity:sensitivearea_delete", kwargs={"pk": self.area2.pk}) response = self.client.get(url) - self.assertRedirects(response, "/sensitivearea/{pk}/".format(pk=self.area2.pk)) + self.assertRedirects(response, reverse("sensitivity:sensitivearea_detail", kwargs={"pk": self.area2.pk})) class SensitiveAreaTemplatesTest(TestCase): @@ -71,7 +77,7 @@ def tearDown(self): self.client.logout() def test_species_name_shown_in_detail_page(self): - url = "/sensitivearea/{pk}/".format(pk=self.area.pk) + url = reverse("sensitivity:sensitivearea_detail", kwargs={"pk": self.area.pk}) response = self.client.get(url) self.assertContains(response, self.area.species.name) @@ -141,21 +147,24 @@ def setUp(self): @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_detail_sensitivearea(self): - url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=self.pk) - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-detail', args=(self.pk,)) + params = {'format': 'json', 'period': 'ignore', 'language': 'en'} + response = self.client.get(url, params) self.assertJSONEqual(response.content.decode(), self.expected_result) @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_detail_sensitivearea_regulatory(self): self.sensitivearea = RegulatorySensitiveAreaFactory.create(species__period01=True) - url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=self.sensitivearea.pk) - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-detail', args=(self.sensitivearea.pk,)) + params = {'format': 'json', 'period': 'ignore', 'language': 'en'} + response = self.client.get(url, params) self.assertIsNone(response.json()['species_id']) @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_list_sensitivearea(self): - url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'period': 'ignore', 'language': 'en'} + response = self.client.get(url, params) self.assertJSONEqual(response.content.decode(), { 'count': 1, 'previous': None, @@ -165,14 +174,16 @@ def test_list_sensitivearea(self): @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_geo_detail_sensitivearea(self): - url = '/api/v2/sensitivearea/{pk}/?format=geojson&period=ignore&language=en'.format(pk=self.pk) - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-detail', args=(self.pk,)) + params = {'format': 'geojson', 'period': 'ignore', 'language': 'en'} + response = self.client.get(url, params) self.assertJSONEqual(response.content.decode(), self.expected_geo_result) @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_geo_list_sensitivearea(self): - url = '/api/v2/sensitivearea/?format=geojson&period=ignore&language=en' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'geojson', 'period': 'ignore', 'language': 'en'} + response = self.client.get(url, params) self.assertJSONEqual(response.content.decode(), { 'count': 1, 'next': None, @@ -182,10 +193,10 @@ def test_geo_list_sensitivearea(self): }) def test_no_duplicates_sensitivearea(self): - url = '/api/v2/sensitivearea/?format=geojson&period=ignore&language=en&practices={}'.format( - ','.join([str(p.pk) for p in self.species.practices.all()]) - ) - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'geojson', 'period': 'ignore', 'language': 'en'} + params['practices'] = ','.join([str(p.pk) for p in self.species.practices.all()]) + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 1, response.json()) def test_multipolygon(self): @@ -209,14 +220,16 @@ def test_multipolygon(self): ]] ], } - url = '/api/v2/sensitivearea/{pk}/?format=json&period=ignore&language=en'.format(pk=sensitivearea.pk) - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-detail', args=(sensitivearea.pk,)) + params = {'format': 'json', 'period': 'ignore', 'language': 'en'} + response = self.client.get(url, params) self.assertEqual(response.json()['geometry'], expected_geom) @override_settings(SENSITIVITY_OPENAIR_SPORT_PRACTICES=['Practice1', ]) def test_list_bubble_sensitivearea(self): - url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en&bubble=True' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'period': 'ignore', 'language': 'en', 'bubble': 'True'} + response = self.client.get(url, params) self.expected_result[u'radius'] = None self.assertJSONEqual(response.content.decode(), { u'count': 1, @@ -228,15 +241,17 @@ def test_list_bubble_sensitivearea(self): def test_list_bubble_sensitivearea_with_point(self): sensitive_area_point = SensitiveAreaFactory.create(geom='SRID=2154;POINT (700040 6600040)', species__period01=True, species__radius=5) - url = '/api/v2/sensitivearea/?format=json&period=ignore&language=en&bubble=True&period=1' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'language': 'en', 'bubble': 'True', 'period': '1'} + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 1) self.assertEqual(response.json()['results'][0]['radius'], 5) self.assertEqual(response.json()['results'][0]['name'], sensitive_area_point.species.name) def test_list_sportpractice(self): - url = '/api/v2/sensitivearea_practice/?format=json&language=en' - response = self.client.get(url) + url = reverse('apiv2:sportpractice-list') + params = {'format': 'json', 'language': 'en'} + response = self.client.get(url, params) sports_practice = SportPractice.objects.all() result_sportpractice = [{'id': sp.id, 'name': sp.name} for sp in sports_practice] self.assertJSONEqual(response.content.decode(), { @@ -249,36 +264,97 @@ def test_list_sportpractice(self): def test_filters_structure(self): other_structure = StructureFactory.create(name='other') self.sensitivearea_other_structure = SensitiveAreaFactory.create(structure=other_structure) - url = '/api/v2/sensitivearea/?format=json&language=en&period=ignore&structures={}'.format(other_structure.pk) - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'period': 'ignore', 'language': 'en'} + params['structures'] = other_structure.pk + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 1) self.assertEqual(response.json()['results'][0]['name'], self.sensitivearea_other_structure.species.name) def test_filters_no_period(self): StructureFactory.create() - url = '/api/v2/sensitivearea/?format=json&language=en' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'language': 'en'} + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 0) def test_filters_any_period(self): SensitiveAreaFactory.create() - url = '/api/v2/sensitivearea/?format=json&language=en&period=any' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'period': 'any', 'language': 'en'} + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 2) def test_filters_specific_period(self): sensitive_area_jf = SensitiveAreaFactory.create(species__period01=True, species__period02=True) SensitiveAreaFactory.create(species__period01=True) SensitiveAreaFactory.create(species__period04=True) - url = '/api/v2/sensitivearea/?format=json&language=en&period=2,3' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'period': '2,3', 'language': 'en'} + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 1) self.assertEqual(response.json()['results'][0]['name'], sensitive_area_jf.species.name) def test_filters_no_period_get_month(self): sensitive_area_month = SensitiveAreaFactory.create(**{'species__period01': True}) SensitiveAreaFactory.create(**{'species__period02': True}) - url = '/api/v2/sensitivearea/?format=json&language=en' - response = self.client.get(url) + url = reverse('apiv2:sensitivearea-list') + params = {'format': 'json', 'language': 'en'} + response = self.client.get(url, params) self.assertEqual(response.json()['count'], 1) self.assertEqual(response.json()['results'][0]['name'], sensitive_area_month.species.name) + + +class SensitiveAreaOpenAirViewsTest(TestCase): + @classmethod + def setUpTestData(cls): + cls.area1 = SensitiveAreaFactory.create() + cls.area2 = RegulatorySensitiveAreaFactory.create() + cls.area3 = SensitiveAreaFactory.create(geom='POINT(700000 6600000)') + species = SpeciesFactory(radius=100) + cls.area4 = SensitiveAreaFactory.create(geom='POINT(700000 6600000)', species=species) + + @override_settings( + SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ + "Practice1", + ] + ) + @freeze_time("2020-01-01") + def test_openair_detail(self): + url = reverse("sensitivity:sensitivearea_openair_detail", args=("en", self.area4.pk)) + response = self.client.get(url, HTTP_HOST='testserver') + self.assertEqual(response.status_code, 200) + today = datetime.datetime.now().strftime('%d/%m/%Y') + expected_response = b'* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website http://testserver\n' + '* Using pyopenair library (https://github.com/lpoaura/pyopenair)\n' + '* This file was created on: 2020-01-01 00:00:00\n' + '\n' + 'AC ZSM\n' + 'AN Species\n' + f'*AUID GUId=! UId=! Id=(Identifiant-GeoTrek-sentivity) {self.area4.pk}\n' + f'*ADescr Species (published on {today})\n' + '*ATimes {"6": ["UTC(01/06->30/06)", "ANY(00:00->23:59)"],"7": ["UTC(01/07->31/07)", "ANY(00:00->23:59)"]}\n' + 'AH 329FT AGL\n' + 'DP 46:29:59 N 03:00:04 E\n' + 'DP 46:29:56 N 03:00:00 E\n' + 'DP 46:29:59 N 02:59:55 E\n' + 'DP 46:30:03 N 03:00:00 E' + self.assertContains(response, expected_response) + + @override_settings( + SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ + "Practice1", + ] + ) + @freeze_time("2020-01-01") + def test_openair_list(self): + url = reverse("sensitivity:sensitivearea_openair_list", args=("en",)) + response = self.client.get(url, HTTP_HOST='testserver') + self.assertEqual(response.status_code, 200) + expected_response = '* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) ' + 'module from website http://testserver\n' + '* Using pyopenair library (https://github.com/lpoaura/pyopenair)\n' + '* This file was created on: 2020-01-01 00:00:00\n' + '\n' + 'AC ZSM\n' + self.assertContains(response, expected_response) From 0c4fd9ffb11c9bb53cbe4718f9b6e226f6179212 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 21 Sep 2023 00:00:07 +0200 Subject: [PATCH 39/43] test not an aerial area --- geotrek/sensitivity/tests/test_views.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/geotrek/sensitivity/tests/test_views.py b/geotrek/sensitivity/tests/test_views.py index dedee9f6ae..441a864587 100644 --- a/geotrek/sensitivity/tests/test_views.py +++ b/geotrek/sensitivity/tests/test_views.py @@ -341,6 +341,18 @@ def test_openair_detail(self): 'DP 46:30:03 N 03:00:00 E' self.assertContains(response, expected_response) + @override_settings( + SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ + "Practice3", + ] + ) + @freeze_time("2020-01-01") + def test_not_an_aerial_sensitiveaera_detail(self): + url = reverse("sensitivity:sensitivearea_openair_detail", args=("en", self.area1.pk)) + response = self.client.get(url, HTTP_HOST='testserver') + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, b'This is not an aerial area') + @override_settings( SENSITIVITY_OPENAIR_SPORT_PRACTICES=[ "Practice1", From b53de4dd706caed71cbfb972dec6e0d9c325fea8 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 21 Sep 2023 00:10:30 +0200 Subject: [PATCH 40/43] update changelog and locale files --- docs/changelog.rst | 4 +++- geotrek/sensitivity/locale/de/LC_MESSAGES/django.po | 5 ++++- geotrek/sensitivity/locale/en/LC_MESSAGES/django.po | 5 ++++- geotrek/sensitivity/locale/es/LC_MESSAGES/django.po | 5 ++++- geotrek/sensitivity/locale/fr/LC_MESSAGES/django.po | 5 ++++- geotrek/sensitivity/locale/it/LC_MESSAGES/django.po | 5 ++++- geotrek/sensitivity/locale/nl/LC_MESSAGES/django.po | 5 ++++- 7 files changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index d19a175aa7..b4efe061cc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,9 @@ CHANGELOG - Upgrade `django-mapentity` to 8.6.1. New authentication system for screamshotter and convertit by token instead of IP detection. +**New features** + +- Sensitivity: Add ``openair`` export format for aerial sensitive areas (#2372) 2.100.2 (2023-09-12) ------------------------ @@ -256,7 +259,6 @@ CHANGELOG **Improvements** - Sensitivity: Add missing attachments list to sensitive areas API -- Sensitivity: Add ``openair`` export format for aerial sensitive areas (#2372) 2.96.0 (2023-02-01) diff --git a/geotrek/sensitivity/locale/de/LC_MESSAGES/django.po b/geotrek/sensitivity/locale/de/LC_MESSAGES/django.po index 6dfadf411e..1dc46aac1c 100644 --- a/geotrek/sensitivity/locale/de/LC_MESSAGES/django.po +++ b/geotrek/sensitivity/locale/de/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-02-14 14:36+0100\n" +"POT-Creation-Date: 2023-09-06 15:28+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -186,3 +186,6 @@ msgstr "" msgid "Invalid geometry value." msgstr "" + +msgid "This is not an aerial area" +msgstr "" diff --git a/geotrek/sensitivity/locale/en/LC_MESSAGES/django.po b/geotrek/sensitivity/locale/en/LC_MESSAGES/django.po index 6dfadf411e..1dc46aac1c 100644 --- a/geotrek/sensitivity/locale/en/LC_MESSAGES/django.po +++ b/geotrek/sensitivity/locale/en/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-02-14 14:36+0100\n" +"POT-Creation-Date: 2023-09-06 15:28+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -186,3 +186,6 @@ msgstr "" msgid "Invalid geometry value." msgstr "" + +msgid "This is not an aerial area" +msgstr "" diff --git a/geotrek/sensitivity/locale/es/LC_MESSAGES/django.po b/geotrek/sensitivity/locale/es/LC_MESSAGES/django.po index 6dfadf411e..1dc46aac1c 100644 --- a/geotrek/sensitivity/locale/es/LC_MESSAGES/django.po +++ b/geotrek/sensitivity/locale/es/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-02-14 14:36+0100\n" +"POT-Creation-Date: 2023-09-06 15:28+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -186,3 +186,6 @@ msgstr "" msgid "Invalid geometry value." msgstr "" + +msgid "This is not an aerial area" +msgstr "" diff --git a/geotrek/sensitivity/locale/fr/LC_MESSAGES/django.po b/geotrek/sensitivity/locale/fr/LC_MESSAGES/django.po index eff99599ef..808b3afd7c 100644 --- a/geotrek/sensitivity/locale/fr/LC_MESSAGES/django.po +++ b/geotrek/sensitivity/locale/fr/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-02-14 14:36+0100\n" +"POT-Creation-Date: 2023-09-06 15:28+0200\n" "PO-Revision-Date: 2020-04-22 07:48+0000\n" "Last-Translator: Emmanuelle Helly \n" "Language-Team: French \n" "Language-Team: LANGUAGE \n" @@ -186,3 +186,6 @@ msgstr "" msgid "Invalid geometry value." msgstr "" + +msgid "This is not an aerial area" +msgstr "" diff --git a/geotrek/sensitivity/locale/nl/LC_MESSAGES/django.po b/geotrek/sensitivity/locale/nl/LC_MESSAGES/django.po index 6dfadf411e..1dc46aac1c 100644 --- a/geotrek/sensitivity/locale/nl/LC_MESSAGES/django.po +++ b/geotrek/sensitivity/locale/nl/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-02-14 14:36+0100\n" +"POT-Creation-Date: 2023-09-06 15:28+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -186,3 +186,6 @@ msgstr "" msgid "Invalid geometry value." msgstr "" + +msgid "This is not an aerial area" +msgstr "" From 0dc2735a0a5a2b3fa3da224160831d010d8924a5 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 21 Sep 2023 07:23:14 +0200 Subject: [PATCH 41/43] rm logger message --- geotrek/sensitivity/views.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 70488e6869..62920a6bb9 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -195,7 +195,7 @@ def render_to_response(self, context): * Using pyopenair library (https://github.com/lpoaura/pyopenair) * This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) is_aerial = area.species.practices.filter(name__in=settings.SENSITIVITY_OPENAIR_SPORT_PRACTICES).exists() - if is_aerial: + if is_aerial and area.openair(): result = file_header + area.openair() response = HttpResponse(result, content_type='application/octet-stream; charset=UTF-8') response['Content-Disposition'] = 'inline; filename=sensitivearea_openair_' + str(area.id) + '.txt' @@ -222,12 +222,7 @@ def render_to_response(self, context): * This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) airspace_list = [] for a in areas: - if not a.openair(): - logger.error( - "The openair format cannot be generated for area %s-%s", - a.id, a - ) - else: + if a.openair(): airspace_list.append(a.openair()) airspace_core = '\n\n'.join(airspace_list) airspace_file = file_header + airspace_core From 5004c549bb5a48582e58dc9dbbeb56497d4320c3 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 21 Sep 2023 07:33:00 +0200 Subject: [PATCH 42/43] use list comprehension for openair list --- geotrek/sensitivity/views.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/geotrek/sensitivity/views.py b/geotrek/sensitivity/views.py index 62920a6bb9..767d072bec 100644 --- a/geotrek/sensitivity/views.py +++ b/geotrek/sensitivity/views.py @@ -220,10 +220,7 @@ def render_to_response(self, context): file_header = """* This file has been produced from GeoTrek sensitivity (https://geotrek.fr/) module from website {scheme}://{domain} * Using pyopenair library (https://github.com/lpoaura/pyopenair) * This file was created on: {timestamp}\n\n""".format(scheme=self.request.scheme, domain=self.request.META['HTTP_HOST'], timestamp=datetime.now()) - airspace_list = [] - for a in areas: - if a.openair(): - airspace_list.append(a.openair()) + airspace_list = [a.openair() for a in areas if a.openair()] airspace_core = '\n\n'.join(airspace_list) airspace_file = file_header + airspace_core response = HttpResponse(airspace_file, content_type='application/octet-stream; charset=UTF-8') From 7ef11a053561f2e5e31f731a93d71e818606fc39 Mon Sep 17 00:00:00 2001 From: lpofredc Date: Thu, 21 Sep 2023 11:55:47 +0200 Subject: [PATCH 43/43] fix missing OpenAir AL value --- geotrek/sensitivity/tests/test_models.py | 2 ++ geotrek/sensitivity/tests/test_views.py | 1 + requirements.txt | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/geotrek/sensitivity/tests/test_models.py b/geotrek/sensitivity/tests/test_models.py index c10fe1ec43..3a7ad7ef78 100644 --- a/geotrek/sensitivity/tests/test_models.py +++ b/geotrek/sensitivity/tests/test_models.py @@ -92,6 +92,7 @@ def test_get_openair_data(self): "*ADescr Species (published on 01/01/2020)\n" '*ATimes {"6": ["UTC(01/06->30/06)", "ANY(00:00->23:59)"],"7": ["UTC(01/07->31/07)", "ANY(00:00->23:59)"]}\n' "AH 329FT AGL\n" + "AL SFC\n" "DP 46:29:59 N 03:00:00 E\n" "DP 46:30:00 N 03:00:00 E", sensitive_area.openair(), @@ -113,6 +114,7 @@ def test_get_openair_point_data(self): "*ADescr Species (published on 01/01/2020)\n" '*ATimes {"6": ["UTC(01/06->30/06)", "ANY(00:00->23:59)"],"7": ["UTC(01/07->31/07)", "ANY(00:00->23:59)"]}\n' "AH 985FT AGL\n" + "AL SFC\n" "DP 46:29:59 N 03:00:14 E\n" "DP 46:29:50 N 03:00:00 E\n" "DP 46:29:59 N 02:59:45 E\n" diff --git a/geotrek/sensitivity/tests/test_views.py b/geotrek/sensitivity/tests/test_views.py index 441a864587..f0ebb92a9c 100644 --- a/geotrek/sensitivity/tests/test_views.py +++ b/geotrek/sensitivity/tests/test_views.py @@ -335,6 +335,7 @@ def test_openair_detail(self): f'*ADescr Species (published on {today})\n' '*ATimes {"6": ["UTC(01/06->30/06)", "ANY(00:00->23:59)"],"7": ["UTC(01/07->31/07)", "ANY(00:00->23:59)"]}\n' 'AH 329FT AGL\n' + "AL SFC\n" 'DP 46:29:59 N 03:00:04 E\n' 'DP 46:29:56 N 03:00:00 E\n' 'DP 46:29:59 N 02:59:55 E\n' diff --git a/requirements.txt b/requirements.txt index 5202c25a3e..f034fa5580 100644 --- a/requirements.txt +++ b/requirements.txt @@ -269,7 +269,7 @@ pygal==3.0.0 # via geotrek (setup.py) pymemcache==4.0.0 # via geotrek (setup.py) -pyopenair==1.2.0 +pyopenair==1.2.1 # via geotrek (setup.py) pyparsing==3.0.8 # via packaging