Skip to content

Commit

Permalink
Merge pull request #179 from fga-eps-mds/feature/157-link-homepage-pr…
Browse files Browse the repository at this point in the history
…odutor

#157 Linkar Backend com a homepage do Produtor
  • Loading branch information
Joao-Moura authored Apr 15, 2021
2 parents 0d5a94a + e45d669 commit 7661801
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 3 deletions.
15 changes: 15 additions & 0 deletions src/hortum/encode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from base64 import b64decode, b64encode

def encode_string(decoded_string):
'''Codifica uma string pra base64'''
b_str = decoded_string.encode('utf-8')
b_str = b64encode(b_str)
encoded_strings = b_str.decode('utf-8')
return encoded_strings

def decode_string(encoded_string):
'''Decodifica uma string em base64'''
b_str = encoded_string.encode('utf-8')
b_str = b64decode(b_str)
decoded_strings = b_str.decode('utf-8')
return decoded_strings
12 changes: 11 additions & 1 deletion src/hortum/productor/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from ..users.models import User

from ..users.serializer import UserSerializer
from ..announcement.serializer import AnnouncementCreateSerializer
from ..announcement.serializer import AnnouncementCreateSerializer, AnnouncementListSerializer
from ..picture.serializer import PictureSerializer

class ProductorSerializer(serializers.ModelSerializer):
Expand All @@ -21,6 +21,16 @@ def create(self, validated_data):
user = User.objects.create_user(**user_data, is_productor=True)
return Productor.objects.create(user=user, **validated_data)

class ProductorRetrieveSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username')
email = serializers.EmailField(source='user.email')
announcements = AnnouncementListSerializer(many=True)
idPicture = idPicture = PictureSerializer(many=False, read_only=True)

class Meta:
model = Productor
fields = ['username', 'email', 'idPicture', 'announcements']

class ProductorListSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username')
email = serializers.EmailField(source='user.email')
Expand Down
94 changes: 93 additions & 1 deletion src/hortum/productor/tests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from rest_framework.test import APITestCase

from .models import Productor
from ..customer.models import Customer
from ..encode import encode_string

class ProductorRegisterAPIViewTestCase(APITestCase):
def setUp(self):
Expand Down Expand Up @@ -165,6 +167,96 @@ def test_only_productors_are_listed(self):
self.url_list,
**self.auth_token
)

self.assertEqual(response.status_code, 200, msg='Falha na listagem de produtores')
self.assertEqual(len(response.data), 3, msg='Quantidade de produtores errada')

class ProductorRetrieveAPIViewTestCase(APITestCase):
def create_user(self):
self.user_data = {
"username": "Marcelo",
"email": "[email protected]",
"password": "teste"
}

url_signup = '/signup/customer/'

response = self.client.post(
url_signup,
{'user': self.user_data},
format='json'
)

self.assertEqual(response.status_code, 201, msg='Falha na criação de usuário')

def create_productors(self):
productors_data = [
{
'username': 'João',
'email': '[email protected]',
'password': 'teste'
},
{
'username': 'Mario',
'email': '[email protected]',
'password': 'teste'
}
]

url_signup = '/signup/productor/'

for prod_data in productors_data:
response = self.client.post(
url_signup,
{'user': prod_data},
format='json'
)
self.assertEqual(response.status_code, 201, msg='Falha na criação de outros produtores')

def create_tokens(self):
user_cred = {'email': self.user_data['email'], 'password': self.user_data['password']}

url_token = '/login/'

response = self.client.post(
url_token,
user_cred,
format='json'
)

self.assertEqual(response.status_code, 200, msg='Credenciais inválidas')

self.creds = {'HTTP_AUTHORIZATION': 'Bearer ' + response.data['access']}

def setUp(self):
self.create_user()
self.create_productors()
self.create_tokens()
self.url_retrieve = '/productor/retrieve/'

def tearDown(self):
Productor.objects.all().delete()
Customer.objects.all().delete()

def test_retrieve_productor(self):
email_query = '[email protected]'
url_retrieve_productor = self.url_retrieve + encode_string(email_query) + '/'

response = self.client.get(
url_retrieve_productor,
**self.creds
)

self.assertEqual(response.status_code, 200, msg='Falha na obtenção de produtor específico')
self.assertEqual(response.data['username'], 'João', msg='Dados de produtor estão incoerentes')

def test_invalid_email(self):
email_query = '[email protected]'
url_retrieve_productor = self.url_retrieve + encode_string(email_query) + '/'

response = self.client.get(
url_retrieve_productor,
**self.creds
)

self.assertEqual(response.status_code, 404, msg='Retornando produtor com email inválido')
1 change: 1 addition & 0 deletions src/hortum/productor/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
routerRegister.register(r'', viewsets.ProductorRegistrationAPIView, basename='productor')

router = routers.SimpleRouter(trailing_slash=True)
router.register(r'retrieve', viewsets.ProductorRetrieveAPIView, basename='retrieveProductor')
router.register(r'list(:?/(?P<productorName>.+))?', viewsets.ProductorListAPIView, basename='searchProductor')

urlpatterns = [
Expand Down
16 changes: 15 additions & 1 deletion src/hortum/productor/viewsets.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from .serializer import ProductorSerializer, ProductorListSerializer
from .serializer import ProductorSerializer, ProductorListSerializer, ProductorRetrieveSerializer

from .models import Productor

from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from rest_framework import permissions
from django.shortcuts import get_object_or_404

from ..encode import decode_string

class ProductorRegistrationAPIView(GenericViewSet, mixins.CreateModelMixin):
'''
Expand All @@ -14,6 +17,17 @@ class ProductorRegistrationAPIView(GenericViewSet, mixins.CreateModelMixin):
serializer_class = ProductorSerializer
queryset = Productor.objects.all()

class ProductorRetrieveAPIView(GenericViewSet, mixins.RetrieveModelMixin):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = ProductorRetrieveSerializer
queryset = Productor.objects.all()
lookup_field = 'encoded_email'

def get_object(self):
email = decode_string(self.kwargs['encoded_email'])
prod = get_object_or_404(self.queryset.filter(user__email=email))
return prod

class ProductorListAPIView(GenericViewSet, mixins.ListModelMixin):
'''
EndPoint para listagem de produtores pelo nome em ordem alfabética
Expand Down

0 comments on commit 7661801

Please sign in to comment.