Fakultas Ilmu Komputer UI

Commit 8fd17973 authored by Usman Sidiq's avatar Usman Sidiq
Browse files

[REFACTOR] refactoring test untuk menyesuaikan dengan validasi email

parent 2014ee53
Pipeline #45246 failed with stages
in 1 minute and 56 seconds
......@@ -130,6 +130,9 @@ class InformasiFasilitasTest(TestCase):
def client_user_token(self):
Client().post('/api/register/', self.user_post)
test_user = User.objects.get(username=self.user_post["email"])
test_user.is_active = True
test_user.save()
token_response = Client().post('/api-token-auth/', {'username': self.user_post["email"],
'password': self.user_post["password"]})
content = json.loads(token_response.content.decode('utf-8'))
......@@ -139,6 +142,9 @@ class InformasiFasilitasTest(TestCase):
def client_user_token2(self):
Client().post('/api/register/', self.user_post)
test_user = User.objects.get(username=self.default_username_email)
test_user.is_active = True
test_user.save()
token_response = Client().post('/api-token-auth/', {'username': self.default_username_email,
'password': self.default_password})
content = json.loads(token_response.content.decode('utf-8'))
......@@ -160,6 +166,9 @@ class InformasiFasilitasViewTest(InformasiFasilitasTest):
'email': email,
'phone_number': 1000000,
'password': password})
test_user = User.objects.get(username=email)
test_user.is_active = True
test_user.save()
token_response = Client().post('/api-token-auth/',
{'username': email,
'password': password})
......
......@@ -66,13 +66,7 @@ class LokasiRelatedViewTest(InformasiFasilitasViewTest):
self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
def test_cannot_get_add_lokasi(self):
Client().post('/api/register/', self.user_post)
token_response = Client().post('/api-token-auth/', {'username': self.user_post["email"],
'password': self.user_post["password"]})
content = json.loads(token_response.content.decode('utf-8'))
token = content['token']
client = Client(HTTP_AUTHORIZATION='token '+token)
client = self.client_user_token()
response = client.get(reverse('add-lokasi'))
self.assertEqual(response.status_code, HTTPStatus.METHOD_NOT_ALLOWED)
......@@ -109,13 +103,7 @@ class LokasiRelatedViewTest(InformasiFasilitasViewTest):
self.assertEqual(response_json, expected_json)
def test_put_update_detail_lokasi_success(self):
Client().post('/api/register/', self.user_post)
token_response = Client().post('/api-token-auth/', {'username': self.user_post["email"],
'password': self.user_post["password"]})
content = json.loads(token_response.content.decode('utf-8'))
token = content['token']
client = Client(HTTP_AUTHORIZATION='token '+token)
client = self.client_user_token()
urls = reverse('update-lokasi',
kwargs={'nama_lokasi': self.lokasi_test_1["name"]})
response = client.put(urls, data=urlencode({'no_telp': '0000000121', }),
......
......@@ -17,7 +17,8 @@ class UserTests(APITestCase):
data = {'name': 'Astraykai',
'email':'astraykai@gmail.com',
'phone_number':'089892218567',
'password':'chingchenghanji',}
'password':'chingchenghanji',
'is_active': True}
self.client.post(url, data)
def test_create_user(self):
......@@ -28,7 +29,8 @@ class UserTests(APITestCase):
data = {'name': 'Astray',
'email':'astrayyahoo@gmail.com',
'phone_number':'08989221856',
'password':'chingchenghanji',}
'password':'chingchenghanji',
'is_active': True}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(BisaGoUser.objects.count(), 2)
......
......@@ -7,8 +7,10 @@ from django.views.generic import TemplateView
urlpatterns = [
path('user-list/', new_rest_api.views.user_list, name='user-list'),
path('user-detail/<str:email>', new_rest_api.views.user_details, name='user-details'),
path('user-detail/?email=<str:email>', new_rest_api.views.user_details, name='user-details-get'),
path('register/', new_rest_api.views.register_user, name='create-user'),
path('user-list/', new_rest_api.views.user_list,name='user-list'),
path('user-detail/<str:email>', new_rest_api.views.user_details,name='user-details'),
path('user-detail/?email=<str:email>', new_rest_api.views.user_details,name='user-details-get'),
path('register/', new_rest_api.views.register_user,name='create-user'),
path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
new_rest_api.views.activate, name='activate'),
]
......@@ -15,6 +15,15 @@ from rest_framework.decorators import api_view, permission_classes, authenticati
from registrasi.models import BisaGoUser
from django.db.utils import IntegrityError
from http import HTTPStatus as status
from django.contrib.sites.models import Site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from django.core.mail import EmailMessage
def request_error_message(request_kind):
return "get {} request instead".format(request_kind)
......@@ -64,8 +73,44 @@ def register_user(request):
email = request.POST['email']
password = request.POST['password']
user = User.objects.create_user(username=email, email=email, password=password, last_name=name)
BisaGoUser.objects.create(user=user, phone_number=phone_number)
return JsonResponse({'response' : 'User created', 'email':email, 'name':name}, status=HTTPStatus.CREATED)
except KeyError as missing_key:
return JsonResponse({'response':missing_key_message(str(missing_key))}, status=HTTPStatus.BAD_REQUEST)
\ No newline at end of file
user.is_active = False
user.save()
mail_subject = "Activate your account"
message = render_to_string('acc_active_email.html', {
'user' : user,
'domain' : request.get_host,
'uid' : urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token' : account_activation_token.make_token(user),
})
mail = EmailMessage(mail_subject, message, to=[email])
mail.send()
BisaGoUser.objects.create(user= user, phone_number=phone_number)
return JsonResponse({'response' : 'User created', 'email':email, 'name':name}, status = 201)
except KeyError as e:
return JsonResponse({'response':missing_key_message(str(e))}, status = 500)
except IntegrityError as e:
return JsonResponse({'response':'User is already exist'}, status = 500)
@api_view(['GET'])
@authentication_classes([])
@permission_classes([])
def activate(request, uidb64, token):
if request.method == 'GET':
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
print(user)
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
# login(request, user)
# return redirect('home')
return JsonResponse({'response' : 'User activated'}, status = status.CREATED)
else:
return JsonResponse({'response' : request_error_message('get')}, status = status.BAD_REQUEST)
else :
return JsonResponse({'response' : request_error_message("get")}, status = 400)
......@@ -71,10 +71,11 @@ MIDDLEWARE = [
ROOT_URLCONF = 'pplbackend.urls'
TEMPLATES_ROOT = os.path.join(BASE_DIR, "templates")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [TEMPLATES_ROOT],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
......@@ -201,3 +202,9 @@ PASSWORD_HASHERS = [
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
EMAIL_PORT = 587
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment