Fakultas Ilmu Komputer UI

Commit dcdf6373 authored by jordan's avatar jordan
Browse files

prepare to deploy

parent e90993eb
......@@ -16,4 +16,3 @@ class PasswordlessAuthenticationBackend(object):
return User.objects.get(email=email)
except User.DoesNotExist:
None
......@@ -5,5 +5,5 @@ from django.contrib.auth import logout
urlpatterns = [
url(r"^send_login_email$", views.send_login_email, name="send_login_email"),
url(r"^login$", views.login, name="login"),
url(r'^logout$', logout, {'next_page': '/'}, name='logout'),
url(r"^logout$", logout, {"next_page": "/"}, name="logout"),
]
# from django.shortcuts import render
# import uuid
import sys
# from django.contrib.auth import authenticate
# from django.contrib.auth import login as auth_login
from django.core.mail import send_mail
......@@ -10,39 +11,33 @@ from django.urls import reverse
from accounts.models import Token
import time
time.sleep(30)
time.sleep(30)
def send_login_email(request):
email = request.POST['email']
email = request.POST["email"]
token = Token.objects.create(email=email)
url = request.build_absolute_uri(
reverse('login') + '?token=' + str(token.uid)
)
message_body = f'Use this link to log in:\n\n{url}'
url = request.build_absolute_uri(reverse("login") + "?token=" + str(token.uid))
message_body = f"Use this link to log in:\n\n{url}"
# print(type(send_mail))
send_mail(
'Your login link for Superlists',
message_body,
'noreply@superlists',
[email]
"Your login link for Superlists", message_body, "noreply@superlists", [email]
)
# messages.add_message(
# request,
# messages.SUCCESS,
# "Check your email, we've sent you a link you can use to log in."
# )
messages.success(request,
"Check your email, we've sent you a link you can use to log in."
messages.success(
request, "Check your email, we've sent you a link you can use to log in."
)
return redirect('/')
return redirect("/")
def login(request):
user = auth.authenticate(uid=request.GET.get('token'))
user = auth.authenticate(uid=request.GET.get("token"))
if user:
auth.login(request, user)
return redirect('/')
return redirect("/")
......@@ -11,14 +11,15 @@ MAX_WAIT = 10
class FunctionalTest(StaticLiveServerTestCase):
def setUp(self):
chrome_options = Options()
chrome_options.add_argument('--dns-prefetch-disable')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('disable-gpu')
self.browser = webdriver.Chrome(executable_path="./chromedriver", options=chrome_options)
chrome_options.add_argument("--dns-prefetch-disable")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--headless")
chrome_options.add_argument("disable-gpu")
self.browser = webdriver.Chrome(
executable_path="./chromedriver", options=chrome_options
)
self.browser.implicitly_wait(10)
def tearDown(self):
self.browser.quit()
......@@ -26,49 +27,40 @@ class FunctionalTest(StaticLiveServerTestCase):
table = self.browser.find_element_by_id("id_list_table")
rows = table.find_elements_by_tag_name("tr")
self.assertIn(row_text, [row.text for row in rows])
def wait(fn):
def modified_fn(*args, **kwargs):
def modified_fn(*args, **kwargs):
start_time = time.time()
while True:
try:
return fn(*args, **kwargs)
return fn(*args, **kwargs)
except (AssertionError, WebDriverException) as e:
if time.time() - start_time > MAX_WAIT:
raise e
time.sleep(0.5)
return modified_fn
@wait
def wait_for_row_in_list_table(self, row_text):
table = self.browser.find_element_by_id("id_list_table")
table = self.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
rows = table.find_elements_by_tag_name("tr")
self.assertIn(row_text, [row.text for row in rows])
@wait
def wait_to_be_logged_in(self, email):
self.browser.find_element_by_link_text('Log out')
self.browser.find_element_by_link_text("Log out")
@wait
def wait_to_be_logged_out(self, email):
self.browser.find_element_by_name('email')
navbar = self.browser.find_element_by_css_selector('.navbar')
self.browser.find_element_by_name("email")
navbar = self.browser.find_element_by_css_selector(".navbar")
self.assertNotIn(email, navbar.text)
@wait
def wait_for(self, fn):
return fn()
from .base import FunctionalTest
class HeaderAndFooter(FunctionalTest):
class HeaderAndFooter(FunctionalTest):
def test_header_and_footer(self):
# Masuk halaman to do list
self.browser.get(self.live_server_url)
# Terdapat nama mahasiswa yang memiliki web pada bagian header
# Terdapat nama mahasiswa yang memiliki web pada bagian header
# beserta nama fungsi web nya.
header_1 = self.browser.find_element_by_id('header_1').text
# Nama mahasiswa tersebut adalah Jordan Muhammad Andrianda,
header_1 = self.browser.find_element_by_id("header_1").text
# Nama mahasiswa tersebut adalah Jordan Muhammad Andrianda,
# sehingga di header terdapat nama tersebut.
self.assertIn('Jordan Muhammad Andrianda To Do list App', header_1)
self.assertIn("Jordan Muhammad Andrianda To Do list App", header_1)
# Terdapat nama mahasiswa yang memiliki web pada bagian footer
# Terdapat nama mahasiswa yang memiliki web pada bagian footer
# beserta copyright web nya.
footer_1 = self.browser.find_element_by_id('footer_1').text
# Nama mahasiswa tersebut adalah Jordan Muhammad Andrianda,
footer_1 = self.browser.find_element_by_id("footer_1").text
# Nama mahasiswa tersebut adalah Jordan Muhammad Andrianda,
# sehingga di footer terdapat nama tersebut.
self.assertIn('Copyright Jordan Muhammad Andrianda', footer_1)
self.assertIn("Copyright Jordan Muhammad Andrianda", footer_1)
......@@ -44,18 +44,10 @@ class LoginTest(FunctionalTest):
# # she is logged in!
# # self.wait_for(lambda: self.browser.find_element_by_link_text("Log out"))
# navbar = self.browser.find_element_by_css_selector(".navbar")
# self.assertIn(TEST_EMAIL, navbar.text)
# # Now she logs out
......@@ -64,21 +56,14 @@ class LoginTest(FunctionalTest):
# # She is logged out
# self.wait_for(lambda: self.browser.find_element_by_name("email"))
# navbar = self.browser.find_element_by_css_selector(".navbar")
# self.assertNotIn(TEST_EMAIL, navbar.text)
# self.wait_to_be_logged_in(email=TEST_EMAIL)
# self.wait_to_be_logged_in(email=TEST_EMAIL)
# self.browser.find_element_by_link_text('Log out').click()
# self.wait_to_be_logged_out(email=TEST_EMAIL)
......@@ -2,32 +2,30 @@ from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY, get_user_model
from django.contrib.sessions.backends.db import SessionStore
from .base import FunctionalTest
User = get_user_model()
class MyListsTest(FunctionalTest):
def create_pre_authenticated_session(self, email):
user = User.objects.create(email=email)
session = SessionStore()
session[SESSION_KEY] = user.pk
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session.save()
## to set a cookie we need to first visit the domain.
## 404 pages load the quickest!
self.browser.get(self.live_server_url + "/404_no_such_url/")
self.browser.add_cookie(dict(
name=settings.SESSION_COOKIE_NAME,
value=session.session_key,
path='/',
))
self.browser.add_cookie(
dict(name=settings.SESSION_COOKIE_NAME, value=session.session_key, path="/")
)
def test_logged_in_users_lists_are_saved_as_my_lists(self):
email = 'edith@example.com'
email = "edith@example.com"
self.browser.get(self.live_server_url)
self.wait_to_be_logged_out(email)
# Edith is a logged-in user
self.create_pre_authenticated_session(email)
self.browser.get(self.live_server_url)
self.wait_to_be_logged_in(email)
\ No newline at end of file
self.wait_to_be_logged_in(email)
......@@ -47,14 +47,15 @@ class NewVisitorTest(FunctionalTest):
## of Edith's is coming through from cookies etc #
self.browser.quit()
chrome_options = Options()
chrome_options.add_argument('--dns-prefetch-disable')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('disable-gpu')
self.browser = webdriver.Chrome(executable_path="./chromedriver", options=chrome_options)
chrome_options.add_argument("--dns-prefetch-disable")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--headless")
chrome_options.add_argument("disable-gpu")
self.browser = webdriver.Chrome(
executable_path="./chromedriver", options=chrome_options
)
self.browser.implicitly_wait(10)
# Francis visits the home page. There is no sign of Edith's
# list
self.browser.get(self.live_server_url)
......
......@@ -55,8 +55,8 @@ class HomePageTest(TestCase):
class NewListTest(TestCase):
def test_can_not_save_an_empty_POST_request(self):
response = self.client.post('/lists/new', data={'item_text': ''})
self.assertEqual(response.context['error'], "You can't have an empty list item")
response = self.client.post("/lists/new", data={"item_text": ""})
self.assertEqual(response.context["error"], "You can't have an empty list item")
def test_saving_a_POST_request(self):
self.client.post("/lists/new", data={"item_text": "A new list item"})
......@@ -74,12 +74,10 @@ class NewListTest(TestCase):
correct_list = List.objects.create()
response = self.client.post(
f'/lists/{correct_list.id}/add_item',
data={'item_text': ''}
f"/lists/{correct_list.id}/add_item", data={"item_text": ""}
)
self.assertEqual(response.context['error'], "You can't have an empty list item")
self.assertEqual(response.context["error"], "You can't have an empty list item")
class ListViewTest(TestCase):
......@@ -135,22 +133,19 @@ class NewItemTest(TestCase):
def test_view_list(self):
other_list = List.objects.create()
correct_list = List.objects.create()
response = self.client.post(
"/lists/%d/" % (correct_list.id,)
)
response = self.client.post("/lists/%d/" % (correct_list.id,))
self.assertTemplateUsed(response, "list.html")
class GenereateCommentTest(TestCase):
def test_message_sibuk_santai(self):
result = get_comment(1)
self.assertEqual(result, 'sibuk tapi santai')
self.assertEqual(result, "sibuk tapi santai")
def test_message_waktunya_libur(self):
result = get_comment(0)
self.assertEqual(result, "yey, waktunya berlibur")
def test_message_oh_tidak(self):
result = get_comment(5)
self.assertEqual(result, "oh tidak")
......@@ -25,29 +25,32 @@ def home_page(request):
def new_list(request):
if len(request.POST['item_text']) == 0:
return render(request, 'home.html',
{
'error': "You can't have an empty list item",
})
if len(request.POST["item_text"]) == 0:
return render(
request, "home.html", {"error": "You can't have an empty list item"}
)
list_ = List.objects.create()
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect(f'/lists/{list_.id}/')
Item.objects.create(text=request.POST["item_text"], list=list_)
return redirect(f"/lists/{list_.id}/")
def add_item(request,list_id):
if len(request.POST['item_text']) == 0:
error = "You can't have an empty list item"
return view_list(request, list_id, error)
list_ = List.objects.get(id=list_id)
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect(f'/lists/{list_.id}/')
def add_item(request, list_id):
if len(request.POST["item_text"]) == 0:
error = "You can't have an empty list item"
return view_list(request, list_id, error)
list_ = List.objects.get(id=list_id)
Item.objects.create(text=request.POST["item_text"], list=list_)
return redirect(f"/lists/{list_.id}/")
def view_list(request, list_id, error=''):
def view_list(request, list_id, error=""):
list_ = List.objects.get(id=list_id)
return render(request, 'list.html', {'error':error, 'list': list_, 'message': get_comment(list_.item_set.count() )})
return render(
request,
"list.html",
{"error": error, "list": list_, "message": get_comment(list_.item_set.count())},
)
def get_comment(count):
......
web: gunicorn superlists.wsgi --log-file -
\ No newline at end of file
......@@ -4,10 +4,11 @@ attrs==19.2.0
black==19.3b0
Click==7.0
coverage==5.0
dj-database-url==0.5.0
Django==2.2.5
entrypoints==0.3
flake8==3.7.8
gunicorn==19.9.0
gunicorn==20.0.4
isort==4.3.21
lazy-object-proxy==1.4.2
mccabe==0.6.1
......@@ -21,4 +22,5 @@ sqlparse==0.3.0
toml==0.10.0
typed-ast==1.4.0
urllib3==1.25.6
whitenoise==5.0.1
wrapt==1.11.2
python-3.7.4
\ No newline at end of file
......@@ -47,6 +47,7 @@ AUTHENTICATION_BACKENDS = ["accounts.authentication.PasswordlessAuthenticationBa
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
'whitenoise.middleware.WhiteNoiseMiddleware',
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
......@@ -121,6 +122,18 @@ PROJECT_ROOT = os.path.join(os.path.abspath(__file__))
STATIC_URL = "/static/"
STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, "../static"))
# Extra lookup directories for collectstatic to find static files
STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, "static"),)
# Add configuration for static files storage using whitenoise
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
import dj_database_url
prod_db = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(prod_db)
ALLOWED_HOSTS = ['jordan-pmpl.herokuapp.com']
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "jerysha99@gmail.com"
......
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