Merge branch 'develop' of ssh://gl.id-east.ru:222/gm/gm-backend into develop

This commit is contained in:
Dmitriy Kuzmenko 2019-09-26 11:39:58 +03:00
commit 0fc89e7053
16 changed files with 538 additions and 83 deletions

View File

@ -101,20 +101,6 @@ class EstablishmentQuerySet(models.QuerySet):
DistanceMeasure(Distance('address__coordinates', point, srid=4236)).m, DistanceMeasure(Distance('address__coordinates', point, srid=4236)).m,
output_field=models.FloatField())) output_field=models.FloatField()))
def annotate_distance_mark(self):
"""
Return QuerySet with annotated field - distance_mark.
Required fields: distance.
Description:
If the radius of the establishments in QuerySet does not exceed 500 meters,
then distance_mark is set to 0.6, otherwise 0.
"""
return self.annotate(distance_mark=models.Case(
models.When(distance__lte=500,
then=0.6),
default=0,
output_field=models.FloatField()))
def annotate_intermediate_public_mark(self): def annotate_intermediate_public_mark(self):
""" """
Return QuerySet with annotated field - intermediate_public_mark. Return QuerySet with annotated field - intermediate_public_mark.
@ -131,49 +117,30 @@ class EstablishmentQuerySet(models.QuerySet):
default='public_mark', default='public_mark',
output_field=models.FloatField())) output_field=models.FloatField()))
def annotate_additional_mark(self, public_mark: float): def annotate_mark_similarity(self, mark):
""" """
Return QuerySet with annotated field - additional_mark. Return a QuerySet with annotated field - mark_similarity
Required fields: intermediate_public_mark
Description: Description:
IF Similarity mark determined by comparison with compared establishment mark
establishments public_mark + 3 > compared establishment public_mark
OR
establishments public_mark - 3 > compared establishment public_mark,
THEN
additional_mark is set to 0.4,
ELSE
set to 0.
""" """
return self.annotate(additional_mark=models.Case( return self.annotate(mark_similarity=models.ExpressionWrapper(
models.When( mark - models.F('intermediate_public_mark'),
models.Q(intermediate_public_mark__lte=public_mark + 3) | output_field=models.FloatField()
models.Q(intermediate_public_mark__lte=public_mark - 3), ))
then=0.4),
default=0,
output_field=models.FloatField()))
def annotate_total_mark(self): def similar(self, establishment_slug: str, output_objects: int = 12):
"""
Return QuerySet with annotated field - total_mark.
Required fields: distance_mark, additional_mark.
Fields
Description:
Annotated field is obtained by formula:
(distance + additional marks) * intermediate_public_mark.
"""
return self.annotate(
total_mark=(models.F('distance_mark') + models.F('additional_mark')) *
models.F('intermediate_public_mark'))
def similar(self, establishment_slug: str):
""" """
Return QuerySet with objects that similar to Establishment. Return QuerySet with objects that similar to Establishment.
:param establishment_slug: str Establishment slug :param establishment_slug: str Establishment slug
:param output_objects: int of output objects
""" """
establishment_qs = Establishment.objects.filter(slug=establishment_slug) establishment_qs = Establishment.objects.filter(slug=establishment_slug,
public_mark__isnull=False)
if establishment_qs.exists(): if establishment_qs.exists():
establishment = establishment_qs.first() establishment = establishment_qs.first()
# TODO fix error:
# AttributeError: 'NoneType' object has no attribute 'coordinates'
return self.exclude(slug=establishment_slug) \ return self.exclude(slug=establishment_slug) \
.filter(is_publish=True, .filter(is_publish=True,
image_url__isnull=False, image_url__isnull=False,
@ -181,10 +148,10 @@ class EstablishmentQuerySet(models.QuerySet):
reviews__status=Review.READY, reviews__status=Review.READY,
public_mark__gte=10) \ public_mark__gte=10) \
.annotate_distance(point=establishment.address.coordinates) \ .annotate_distance(point=establishment.address.coordinates) \
.annotate_distance_mark() \
.annotate_intermediate_public_mark() \ .annotate_intermediate_public_mark() \
.annotate_additional_mark(public_mark=establishment.public_mark) \ .annotate_mark_similarity(mark=establishment.public_mark) \
.annotate_total_mark() .order_by('distance') \
.order_by('mark_similarity')[:output_objects]
else: else:
return self.none() return self.none()
@ -278,7 +245,7 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin):
preview_image_url = models.URLField(verbose_name=_('Preview image URL path'), preview_image_url = models.URLField(verbose_name=_('Preview image URL path'),
blank=True, null=True, default=None) blank=True, null=True, default=None)
slug = models.SlugField(unique=True, max_length=50, null=True, slug = models.SlugField(unique=True, max_length=50, null=True,
verbose_name=_('Establishment slug'), editable=True) verbose_name=_('Establishment slug'), editable=True)
awards = generic.GenericRelation(to='main.Award') awards = generic.GenericRelation(to='main.Award')
tags = generic.GenericRelation(to='main.MetaDataContent') tags = generic.GenericRelation(to='main.MetaDataContent')

View File

@ -7,6 +7,9 @@ from establishment.serializers import (
EstablishmentBaseSerializer, PlateSerializer, ContactEmailsSerializer, EstablishmentBaseSerializer, PlateSerializer, ContactEmailsSerializer,
ContactPhonesSerializer, SocialNetworkRelatedSerializers, EstablishmentDetailSerializer ContactPhonesSerializer, SocialNetworkRelatedSerializers, EstablishmentDetailSerializer
) )
from utils.decorators import with_base_attributes
from main.models import Currency from main.models import Currency
@ -123,7 +126,10 @@ class ContactEmailBackSerializers(PlateSerializer):
] ]
# TODO: test decorator
@with_base_attributes
class EmployeeBackSerializers(serializers.ModelSerializer): class EmployeeBackSerializers(serializers.ModelSerializer):
"""Social network serializers.""" """Social network serializers."""
class Meta: class Meta:
model = models.Employee model = models.Employee
@ -132,3 +138,4 @@ class EmployeeBackSerializers(serializers.ModelSerializer):
'user', 'user',
'name' 'name'
] ]

View File

@ -315,20 +315,22 @@ class EstablishmentFavoritesCreateSerializer(serializers.ModelSerializer):
def validate(self, attrs): def validate(self, attrs):
"""Override validate method""" """Override validate method"""
# Check establishment object # Check establishment object
establishment_id = self.context.get('request').parser_context.get('kwargs').get('pk') establishment_slug = self.context.get('request').parser_context.get('kwargs').get('slug')
establishment_qs = models.Establishment.objects.filter(id=establishment_id) establishment_qs = models.Establishment.objects.filter(slug=establishment_slug)
# Check establishment obj by pk from lookup_kwarg # Check establishment obj by slug from lookup_kwarg
if not establishment_qs.exists(): if not establishment_qs.exists():
raise serializers.ValidationError({'detail': _('Object not found.')}) raise serializers.ValidationError({'detail': _('Object not found.')})
else:
establishment = establishment_qs.first()
# Check existence in favorites # Check existence in favorites
if self.get_user().favorites.by_content_type(app_label='establishment', if self.get_user().favorites.by_content_type(app_label='establishment',
model='establishment')\ model='establishment')\
.by_object_id(object_id=establishment_id).exists(): .by_object_id(object_id=establishment.id).exists():
raise utils_exceptions.FavoritesError() raise utils_exceptions.FavoritesError()
attrs['establishment'] = establishment_qs.first() attrs['establishment'] = establishment
return attrs return attrs
def create(self, validated_data, *args, **kwargs): def create(self, validated_data, *args, **kwargs):

View File

@ -27,7 +27,7 @@ class BaseTestCase(APITestCase):
self.establishment_type = EstablishmentType.objects.create(name="Test establishment type") self.establishment_type = EstablishmentType.objects.create(name="Test establishment type")
class EstablishmentTests(BaseTestCase): class EstablishmentBTests(BaseTestCase):
def test_establishment_CRUD(self): def test_establishment_CRUD(self):
params = {'page': 1, 'page_size': 1,} params = {'page': 1, 'page_size': 1,}
response = self.client.get('/api/back/establishments/', params, format='json') response = self.client.get('/api/back/establishments/', params, format='json')
@ -93,7 +93,8 @@ class ChildTestCase(BaseTestCase):
self.establishment = Establishment.objects.create( self.establishment = Establishment.objects.create(
name="Test establishment", name="Test establishment",
establishment_type_id=self.establishment_type.id, establishment_type_id=self.establishment_type.id,
is_publish=True is_publish=True,
slug="test"
) )
@ -263,3 +264,89 @@ class EstablishmentShedulerTests(ChildTestCase):
response = self.client.delete(f'/api/back/establishments/{self.establishment.id}/schedule/1/') response = self.client.delete(f'/api/back/establishments/{self.establishment.id}/schedule/1/')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
# Web tests
class EstablishmentWebTests(BaseTestCase):
def test_establishment_Read(self):
params = {'page': 1, 'page_size': 1,}
response = self.client.get('/api/web/establishments/', params, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
class EstablishmentWebTagTests(BaseTestCase):
def test_tag_Read(self):
response = self.client.get('/api/web/establishments/tags/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
class EstablishmentWebSlugTests(ChildTestCase):
def test_slug_Read(self):
response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
class EstablishmentWebSimilarTests(ChildTestCase):
def test_similar_Read(self):
response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/similar/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
class EstablishmentWebCommentsTests(ChildTestCase):
def test_comments_CRUD(self):
response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/comments/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = {
'text': 'test',
'user': self.user.id,
'mark': 4
}
response = self.client.post(f'/api/web/establishments/slug/{self.establishment.slug}/comments/create/',
data=data)
comment = response.json()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/comments/{comment["id"]}/',
format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
update_data = {
'text': 'Test new establishment'
}
response = self.client.patch(f'/api/web/establishments/slug/{self.establishment.slug}/comments/{comment["id"]}/',
data=update_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.delete(
f'/api/web/establishments/slug/{self.establishment.slug}/comments/{comment["id"]}/',
format='json')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
class EstablishmentWebFavoriteTests(ChildTestCase):
def test_favorite_CR(self):
data = {
"user": self.user.id,
"object_id": self.establishment.id
}
response = self.client.post(f'/api/web/establishments/slug/{self.establishment.slug}/favorites/',
data=data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.delete(
f'/api/web/establishments/slug/{self.establishment.slug}/favorites/',
format='json')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

View File

@ -8,13 +8,13 @@ app_name = 'establishment'
urlpatterns = [ urlpatterns = [
path('', views.EstablishmentListView.as_view(), name='list'), path('', views.EstablishmentListView.as_view(), name='list'),
path('tags/', views.EstablishmentTagListView.as_view(), name='tags'), path('tags/', views.EstablishmentTagListView.as_view(), name='tags'),
path('<slug:slug>/', views.EstablishmentRetrieveView.as_view(), name='detail'), path('slug/<slug:slug>/', views.EstablishmentRetrieveView.as_view(), name='detail'),
path('<slug:slug>/similar/', views.EstablishmentSimilarListView.as_view(), name='similar'), path('slug/<slug:slug>/similar/', views.EstablishmentSimilarListView.as_view(), name='similar'),
path('<slug:slug>/comments/', views.EstablishmentCommentListView.as_view(), name='list-comments'), path('slug/<slug:slug>/comments/', views.EstablishmentCommentListView.as_view(), name='list-comments'),
path('<slug:slug>/comments/create/', views.EstablishmentCommentCreateView.as_view(), path('slug/<slug:slug>/comments/create/', views.EstablishmentCommentCreateView.as_view(),
name='create-comment'), name='create-comment'),
path('<slug:slug>/comments/<int:comment_id>/', views.EstablishmentCommentRUDView.as_view(), path('slug/<slug:slug>/comments/<int:comment_id>/', views.EstablishmentCommentRUDView.as_view(),
name='rud-comment'), name='rud-comment'),
path('<slug:slug>/favorites/', views.EstablishmentFavoritesCreateDestroyView.as_view(), path('slug/<slug:slug>/favorites/', views.EstablishmentFavoritesCreateDestroyView.as_view(),
name='add-to-favorites') name='add-to-favorites')
] ]

View File

@ -30,8 +30,8 @@ class EstablishmentSimilarListView(EstablishmentListView):
def get_queryset(self): def get_queryset(self):
"""Override get_queryset method""" """Override get_queryset method"""
return super().get_queryset().similar(establishment_slug=self.kwargs.get('slug'))\ return super().get_queryset().similar(establishment_slug=self.kwargs.get('slug'))
.order_by('-total_mark')[:13]
class EstablishmentRetrieveView(EstablishmentMixin, generics.RetrieveAPIView): class EstablishmentRetrieveView(EstablishmentMixin, generics.RetrieveAPIView):
"""Resource for getting a establishment.""" """Resource for getting a establishment."""

View File

@ -1,6 +1,5 @@
from rest_framework import generics from rest_framework import generics
from utils.permissions import IsAuthenticatedAndTokenIsValid
from . import models, serializers from . import models, serializers
@ -9,4 +8,3 @@ class ImageUploadView(generics.CreateAPIView):
model = models.Image model = models.Image
queryset = models.Image.objects.all() queryset = models.Image.objects.all()
serializer_class = serializers.ImageSerializer serializer_class = serializers.ImageSerializer
permission_classes = (IsAuthenticatedAndTokenIsValid, )

View File

@ -1,3 +1,193 @@
from django.test import TestCase import json
# Create your tests here. from rest_framework.test import APITestCase
from account.models import User
from rest_framework import status
from http.cookies import SimpleCookie
from location.models import City, Region, Country
class BaseTestCase(APITestCase):
def setUp(self):
self.username = 'sedragurda'
self.password = 'sedragurdaredips19'
self.email = 'sedragurda@desoz.com'
self.newsletter = True
self.user = User.objects.create_user(
username=self.username, email=self.email, password=self.password)
# get tokens
tokkens = User.create_jwt_tokens(self.user)
self.client.cookies = SimpleCookie(
{'access_token': tokkens.get('access_token'),
'refresh_token': tokkens.get('refresh_token')})
class CountryTests(BaseTestCase):
def test_country_CRUD(self):
response = self.client.get('/api/back/location/countries/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = {
'name': 'Test country',
'code': 'test'
}
response = self.client.post('/api/back/location/countries/', data=data, format='json')
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(f'/api/back/location/countries/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
update_data = {
'name': json.dumps({"en-GB": "Test new country"})
}
response = self.client.patch(f'/api/back/location/countries/{response_data["id"]}/', data=update_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.delete(f'/api/back/location/countries/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
class RegionTests(BaseTestCase):
def setUp(self):
super().setUp()
self.country = Country.objects.create(
name=json.dumps({"en-GB": "Test country"}),
code="test"
)
def test_region_CRUD(self):
response = self.client.get('/api/back/location/regions/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = {
'name': 'Test country',
'code': 'test',
'country_id': self.country.id
}
response = self.client.post('/api/back/location/regions/', data=data, format='json')
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(f'/api/back/location/regions/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
update_data = {
'name': json.dumps({"en-GB": "Test new country"})
}
response = self.client.patch(f'/api/back/location/regions/{response_data["id"]}/', data=update_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.delete(f'/api/back/location/regions/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
class CityTests(BaseTestCase):
def setUp(self):
super().setUp()
self.country = Country.objects.create(
name=json.dumps({"en-GB": "Test country"}),
code="test"
)
self.region = Region.objects.create(
name="Test region",
code="812",
country=self.country
)
def test_city_CRUD(self):
response = self.client.get('/api/back/location/cities/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = {
'name': 'Test country',
'code': 'test',
'country_id': self.country.id,
'region_id': self.region.id
}
response = self.client.post('/api/back/location/cities/', data=data, format='json')
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(f'/api/back/location/cities/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
update_data = {
'name': json.dumps({"en-GB": "Test new country"})
}
response = self.client.patch(f'/api/back/location/cities/{response_data["id"]}/', data=update_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.delete(f'/api/back/location/cities/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
class AddressTests(BaseTestCase):
def setUp(self):
super().setUp()
self.country = Country.objects.create(
name=json.dumps({"en-GB": "Test country"}),
code="test"
)
self.region = Region.objects.create(
name="Test region",
code="812",
country=self.country
)
self.city = City.objects.create(
name="Test region",
code="812",
region=self.region,
country=self.country
)
def test_address_CRUD(self):
response = self.client.get('/api/back/location/addresses/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = {
'city_id': self.city.id,
'number': '+79999999',
"coordinates": {
"latitude": 37.0625,
"longitude": -95.677068
},
"geo_lon": -95.677068,
"geo_lat": 37.0625
}
response = self.client.post('/api/back/location/addresses/', data=data, format='json')
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(f'/api/back/location/addresses/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
update_data = {
'number': '+79999991'
}
response = self.client.patch(f'/api/back/location/addresses/{response_data["id"]}/', data=update_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.delete(f'/api/back/location/addresses/{response_data["id"]}/', format='json')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

View File

@ -136,8 +136,8 @@ class CarouselListSerializer(serializers.ModelSerializer):
"""Serializer for retrieving list of carousel items.""" """Serializer for retrieving list of carousel items."""
model_name = serializers.CharField() model_name = serializers.CharField()
name = serializers.CharField() name = serializers.CharField()
toque_number = serializers.CharField() toque_number = serializers.IntegerField()
public_mark = serializers.CharField() public_mark = serializers.IntegerField()
image = serializers.URLField(source='image_url') image = serializers.URLField(source='image_url')
awards = AwardBaseSerializer(many=True) awards = AwardBaseSerializer(many=True)
vintage_year = serializers.IntegerField() vintage_year = serializers.IntegerField()

View File

@ -35,11 +35,18 @@ class NewsTestCase(BaseTestCase):
response = self.client.get("/api/web/news/") response = self.client.get("/api/web/news/")
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_news_detail(self): def test_news_web_detail(self):
response = self.client.get(f"/api/web/news/{self.test_news.slug}/") response = self.client.get(f"/api/web/news/slug/{self.test_news.slug}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_news_back_detail(self):
response = self.client.get(f"/api/back/news/{self.test_news.id}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_news_list_back(self):
response = self.client.get("/api/back/news/")
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_news_type_list(self): def test_news_type_list(self):
response = self.client.get("/api/web/news/types/") response = self.client.get("/api/web/news/types/")
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)

View File

@ -7,5 +7,5 @@ app_name = 'news'
urlpatterns = [ urlpatterns = [
path('', views.NewsListView.as_view(), name='list'), path('', views.NewsListView.as_view(), name='list'),
path('types/', views.NewsTypeListView.as_view(), name='type'), path('types/', views.NewsTypeListView.as_view(), name='type'),
path('<slug:slug>/', views.NewsDetailView.as_view(), name='rud'), path('slug/<slug:slug>/', views.NewsDetailView.as_view(), name='rud'),
] ]

116
apps/notification/tests.py Normal file
View File

@ -0,0 +1,116 @@
from http.cookies import SimpleCookie
from django.test import TestCase
from rest_framework.test import APITestCase
from rest_framework import status
from account.models import User
from notification.models import Subscriber
class BaseTestCase(APITestCase):
def setUp(self):
self.username = 'sedragurda'
self.password = 'sedragurdaredips19'
self.email = 'sedragurda@desoz.com'
self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password)
# get tokkens
tokkens = User.create_jwt_tokens(self.user)
self.client.cookies = SimpleCookie({'access_token': tokkens.get('access_token'),
'refresh_token': tokkens.get('refresh_token')})
class NotificationAnonSubscribeTestCase(APITestCase):
def test_subscribe(self):
test_data = {
"email": "test@email.com",
"state": 1
}
response = self.client.post("/api/web/notifications/subscribe/", data=test_data, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["email"], test_data["email"])
self.assertEqual(response.json()["state"], test_data["state"])
class NotificationSubscribeTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self.test_data = {
"email": self.email,
"state": 1
}
def test_subscribe(self):
response = self.client.post("/api/web/notifications/subscribe/", data=self.test_data, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["email"], self.email)
self.assertEqual(response.json()["state"], self.test_data["state"])
def test_subscribe_info_auth_user(self):
Subscriber.objects.create(user=self.user, email=self.email, state=1)
response = self.client.get("/api/web/notifications/subscribe-info/", data=self.test_data, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
class NotificationSubscribeInfoTestCase(APITestCase):
def test_subscribe_info(self):
self.username = 'sedragurda'
self.password = 'sedragurdaredips19'
self.email = 'sedragurda@desoz.com'
self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password)
test_subscriber = Subscriber.objects.create(user=self.user, email=self.email, state=1)
response = self.client.get(f"/api/web/notifications/subscribe-info/{test_subscriber.update_code}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
class NotificationUnsubscribeAuthUserTestCase(BaseTestCase):
def test_unsubscribe_auth_user(self):
Subscriber.objects.create(user=self.user, email=self.email, state=1)
self.test_data = {
"email": self.email,
"state": 1
}
response = self.client.patch("/api/web/notifications/unsubscribe/", data=self.test_data, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
class NotificationUnsubscribeTestCase(APITestCase):
def test_unsubscribe(self):
self.username = 'sedragurda'
self.password = 'sedragurdaredips19'
self.email = 'sedragurda@desoz.com'
self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password)
self.test_data = {
"email": self.email,
"state": 1
}
test_subscriber = Subscriber.objects.create(user=self.user, email=self.email, state=1)
response = self.client.patch(f"/api/web/notifications/unsubscribe/{test_subscriber.update_code}/",
data=self.test_data, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)

View File

@ -84,6 +84,8 @@ class EstablishmentDocument(Document):
'name', 'name',
'toque_number', 'toque_number',
'price_level', 'price_level',
'preview_image_url',
'slug',
) )
def get_queryset(self): def get_queryset(self):

View File

@ -63,6 +63,8 @@ class EstablishmentDocumentSerializer(DocumentSerializer):
'collections', 'collections',
'establishment_type', 'establishment_type',
'establishment_subtypes', 'establishment_subtypes',
'preview_image_url',
'slug',
) )
@staticmethod @staticmethod

21
apps/utils/decorators.py Normal file
View File

@ -0,0 +1,21 @@
def with_base_attributes(cls):
def validate(self, data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
if user is not None:
data.update({'modified_by': user})
if not self.instance:
data.update({'created_by': user})
return data
setattr(cls, "validate", validate)
return cls

View File

@ -8,6 +8,8 @@ from http.cookies import SimpleCookie
from account.models import User from account.models import User
from news.models import News, NewsType from news.models import News, NewsType
from establishment.models import Establishment, EstablishmentType, Employee
class BaseTestCase(APITestCase): class BaseTestCase(APITestCase):
@ -28,6 +30,12 @@ class BaseTestCase(APITestCase):
'locale': "en" 'locale': "en"
}) })
class TranslateFieldTests(BaseTestCase):
def setUp(self):
super().setUp()
self.news_type = NewsType.objects.create(name="Test news type") self.news_type = NewsType.objects.create(name="Test news type")
self.news_item = News.objects.create( self.news_item = News.objects.create(
@ -45,15 +53,9 @@ class BaseTestCase(APITestCase):
news_type=self.news_type news_type=self.news_type
) )
class TranslateFieldModel(BaseTestCase):
def test_model_field(self): def test_model_field(self):
self.assertIsNotNone(getattr(self.news_item, "title_translated", None)) self.assertIsNotNone(getattr(self.news_item, "title_translated", None))
class TranslateFieldReview(BaseTestCase):
def test_read_locale(self): def test_read_locale(self):
response = self.client.get(f"/api/web/news/{self.news_item.id}/", format='json') response = self.client.get(f"/api/web/news/{self.news_item.id}/", format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
@ -62,3 +64,57 @@ class TranslateFieldReview(BaseTestCase):
self.assertIn("title_translated", news_data) self.assertIn("title_translated", news_data)
self.assertEqual(news_data['title_translated'], "Test news item") self.assertEqual(news_data['title_translated'], "Test news item")
class BaseAttributeTests(BaseTestCase):
def setUp(self):
super().setUp()
self.establishment_type = EstablishmentType.objects.create(name="Test establishment type")
self.establishment = Establishment.objects.create(
name="Test establishment",
establishment_type_id=self.establishment_type.id,
is_publish=True
)
def test_base_attr_api(self):
data = {
'user': self.user.id,
'name': 'Test name'
}
response = self.client.post('/api/back/establishments/employees/', data=data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response_data = response.json()
self.assertIn("id", response_data)
employee = Employee.objects.get(id=response_data['id'])
self.assertEqual(self.user, employee.created_by)
self.assertEqual(self.user, employee.modified_by)
modify_user = User.objects.create_user(
username='sedragurda2',
password='sedragurdaredips192',
email='sedragurda2@desoz.com',
)
modify_tokkens = User.create_jwt_tokens(modify_user)
self.client.cookies = SimpleCookie(
{'access_token': modify_tokkens.get('access_token'),
'refresh_token': modify_tokkens.get('refresh_token'),
'locale': "en"
})
update_data = {
'name': 'Test new name'
}
response = self.client.patch('/api/back/establishments/employees/1/', data=update_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
employee.refresh_from_db()
self.assertEqual(modify_user, employee.modified_by)
self.assertEqual(self.user, employee.created_by)