-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
64 lines (46 loc) · 1.89 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from django.test import TestCase
from django.urls import reverse
from django.conf import settings
from rest_framework import status
from rest_framework.test import APIClient
from rest_framework import status
import jwt
from users.models import *
JWT_SECRET_KEY = getattr(settings, 'SECRET_KEY', None)
def decode_token(encoded_jwt):
decoded_jwt = jwt.decode(encoded_jwt, JWT_SECRET_KEY, algorithms=['HS256'])
return decoded_jwt
class UserRegisterViewTest(TestCase):
def setUp(self):
#noheaders needed when registering
self.client = APIClient()
self.headers = {}
self.client.credentials(**self.headers)
def test_valid_credentials(self):
response = self.client.post(
reverse('users:register'),
{'username': 'eddy', 'email': 'test@test.com', 'password': 'testpass', 'role': 'customer'}
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue('token' in response.json())
class LoginViewTest(TestCase):
def setUp(self):
#noheaders needed when registering
self.client = APIClient()
self.user = User.objects.create(
username='testuser',
email='test@test.com'
)
self.user.set_password('password')
self.user.save()
self.headers = {}
self.client.credentials(**self.headers)
def test_user_login_valid_credentials(self):
response = self.client.post(
reverse('users:login'),
{'email': 'test@test.com', 'password': 'password'}
)
decoded_useer_id = decode_token(response.json()['token'])['id']
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue('token' in response.json())
self.assertEqual(decoded_useer_id, str(self.user.id))