Commit 35836b8a authored by Vegard Murvold Sporstøl's avatar Vegard Murvold Sporstøl
Browse files

work on refactoring

parent e2684002
Pipeline #127214 passed with stages
in 2 minutes and 51 seconds
......@@ -19,3 +19,4 @@ class IsCommentVisibleToUser(permissions.BasePermission):
or (obj.workout.visibility == "CO" and obj.owner.coach == request.user)
or obj.workout.owner == request.user
)
\ No newline at end of file
......@@ -12,7 +12,6 @@ from rest_framework.filters import OrderingFilter
class CommentList(
mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
# queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = [permissions.IsAuthenticated]
filter_backends = [OrderingFilter]
......
#import logging
import os
import dj_database_url
from django.test.runner import DiscoverRunner
MAX_CONN_AGE = 600
def settings(config, *, db_colors=False, databases=True, test_runner=True, staticfiles=True, allowed_hosts=True, logging=True, secret_key=True):
# Database configuration.
# TODO: support other database (e.g. TEAL, AMBER, etc, automatically.)
if databases:
# Integrity check.
if 'DATABASES' not in config:
......@@ -20,30 +17,21 @@ def settings(config, *, db_colors=False, databases=True, test_runner=True, stati
if db_colors:
# Support all Heroku databases.
# TODO: This appears to break TestRunner.
for (env, url) in os.environ.items():
if env.startswith('HEROKU_POSTGRESQL'):
db_color = env[len('HEROKU_POSTGRESQL_'):].split('_')[0]
#logger.info('Adding ${} to DATABASES Django setting ({}).'.format(env, db_color))
config['DATABASES'][db_color] = dj_database_url.parse(url, conn_max_age=conn_max_age, ssl_require=True)
if 'DATABASE_URL' in os.environ:
#logger.info('Adding $DATABASE_URL to default DATABASE Django setting.')
# Configure Django for DATABASE_URL environment variable.
config['DATABASES']['default'] = dj_database_url.config(conn_max_age=conn_max_age, ssl_require=True)
#logger.info('Adding $DATABASE_URL to TEST default DATABASE Django setting.')
# Enable test database if found in CI environment.
if 'CI' in os.environ:
config['DATABASES']['default']['TEST'] = config['DATABASES']['default']
#else:
#logger.info('$DATABASE_URL not found, falling back to previous settings!')
if test_runner:
# Enable test runner if found in CI environment.
if 'CI' in os.environ:
......@@ -51,7 +39,6 @@ def settings(config, *, db_colors=False, databases=True, test_runner=True, stati
# Staticfiles configuration.
if staticfiles:
#logger.info('Applying Heroku Staticfiles configuration to Django settings.')
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
config['STATIC_URL'] = '/static/'
......@@ -69,48 +56,10 @@ def settings(config, *, db_colors=False, databases=True, test_runner=True, stati
config['STATICFILES_STORAGE'] = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
if allowed_hosts:
#logger.info('Applying Heroku ALLOWED_HOSTS configuration to Django settings.')
config['ALLOWED_HOSTS'] = ['*']
"""
if logging:
logger.info('Applying Heroku logging configuration to Django settings.')
config['LOGGING'] = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' +
'pathname=%(pathname)s lineno=%(lineno)s ' +
'funcname=%(funcName)s %(message)s'),
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'testlogger': {
'handlers': ['console'],
'level': 'INFO',
}
}
}
"""
# SECRET_KEY configuration.
if secret_key:
if 'SECRET_KEY' in os.environ:
#logger.info('Adding $SECRET_KEY to SECRET_KEY Django setting.')
# Set the Django setting from the environment variable.
config['SECRET_KEY'] = os.environ['SECRET_KEY']
......@@ -106,7 +106,6 @@ if is_prod:
if 'DATABASE_URL' in os.environ:
import dj_database_url
print("\n\n\n\n\nHEI\n\n\n\n\n\n")
DATABASES = {'default': dj_database_url.config()}
else:
DATABASES = {
......
......@@ -6,16 +6,13 @@ from .forms import CustomUserChangeForm, CustomUserCreationForm
# Register your models here.
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = get_user_model()
# list_display = UserAdmin.list_display + ('coach',)
fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("coach",)}),)
add_fieldsets = UserAdmin.add_fieldsets + ((None, {"fields": ("coach",)}),)
admin.site.register(get_user_model(), CustomUserAdmin)
admin.site.register(Offer)
admin.site.register(AthleteFile)
......@@ -32,7 +32,6 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
data = self.get_initial()
password = data.get("password")
password1 = data.get("password1")
try:
password_validation.validate_password(password)
......
import json
from django.test import TestCase, RequestFactory, Client
from users.serializers import UserSerializer
from users.models import User
from django.core.exceptions import ValidationError
class RegistrationTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_registration(self):
data = {"username": "Test", "email": "test@test.no",
"password": "strong_pwd", "password1": "strong_pwd",
"phone_number": "12345678", "country": "Norway",
"city": "Trondheim", "street_address": "Trondheimsvegen 1"}
response = self.client.post('/api/users/', data)
self.assertEqual(response.status_code, 201)
### Test boundary values of registration ###
class BoundaryValuesOfRegistrationTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_minimumData(self):
data = {"username": "t", "email": "",
"password": "1", "password1": "1",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post("/api/users/", data)
self.assertEqual(response.status_code, 201) #should work at one char pwd and username
def test_blankPassword(self):
data = {"username": "test", "email": "",
"password": "", "password1": "",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post("/api/users/", data)
self.assertEqual(response.status_code, 400) #should fail at blank pwd
def test_blankUsername(self):
data = {"username": "", "email": "",
"password": "1", "password1": "1",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post("/api/users/", data)
self.assertEqual(response.status_code, 400) #should fail at blank username
def test_invalidEmail(self):
data = {"username": "Test", "email": "test.no",
"password": "1", "password1": "1",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post("/api/users/", data)
self.assertEqual(response.status_code, 400) #should fail if email does not conatin @
### Test the class UserSerializer ###
class UserSerializerTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create(username="user1")
self.user2 = User.objects.create(username="user2", coach=self.user1)
self.factory = RequestFactory()
def test_validate_passwordValid(self):
password = "some_very_strong_pwd"
serializer = UserSerializer(data = {'password': password,'password1': password})
validated_password = serializer.validate_password(password)
self.assertEqual(validated_password, password)
def test_validate_passwordInValid(self):
password = "some_very_strong_pwd"
password1 = "Some_wrong_pwd"
serializer = UserSerializer(data = {'password': password,'password1': password})
validated_password = serializer.validate_password(password1)
self.assertRaises(ValidationError)
def test_create(self):
data = {"username": "Test", "email": "test@test.no",
"password": "strong_pwd", "password1": "strong_pwd",
"phone_number": "12345678", "country": "Norway",
"city": "Trondheim", "street_address": "Trondheimsvegen 1"}
serializer = UserSerializer(data)
user = serializer.create(data)
self.assertEqual(user.username, "Test")
self.assertEqual(user.email, "test@test.no")
self.assertEqual(user.phone_number, "12345678")
self.assertEqual(user.country, "Norway")
self.assertEqual(user.city, "Trondheim")
self.assertEqual(user.street_address, "Trondheimsvegen 1")
### 2-way domain testing of registration ###
test_cases = [
{'email':'wrong', 'username':'wrong', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'empty', 'city':'empty', 'street_address':'normal'},
{'email':'wrong', 'username':'normal', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'wrong', 'username':'empty', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'normal', 'password':'empty', 'password1':'empty', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'normal', 'password':'normal', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'empty', 'street_address':'empty'},
{'email':'normal','username':'wrong', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'normal','username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'wrong', 'password':'empty', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'empty', 'username':'empty', 'password':'empty', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'empty', 'username':'wrong', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'empty', 'username':'normal', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'empty', 'street_address':'normal'},
{'email':'empty', 'username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'empty', 'username':'empty', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'empty', 'username':'wrong', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'empty'},
{'email':'empty', 'username':'normal', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'wrong', 'password':'empty', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'empty'},
{'email':'wrong', 'username':'wrong', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'empty', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'normal', 'password':'empty', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'wrong', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'empty', 'password':'empty', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'wrong', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'normal'}
]
case_data = {
'normal': {
'email': 'test@test.no',
'username': 'test',
'password': 'test123',
'password1': 'test123',
'phone_number': 12354678,
'country': 'Norway',
'city': 'Trondheim',
'street_address': 'Trondheimsvegen',
},
'empty': {
'email': '',
'username': '',
'password': '',
'password1': '',
'phone_number': '',
'country': '',
'city': '',
'street_address': '',
},
'wrong': {
'email': 'test.no',
'username': 'test]',
}
}
class TwoWayDomainTestOfRegistrationTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_domainRegistration(self):
for case in test_cases:
data = {}
for key, value in case.items():
data[key] = case_data[value][key]
code = 201
if case['email'] == 'wrong' or case['username'] == 'wrong' or case['password'] == 'empty' or case['username'] == 'empty' or case['password1'] == 'empty':
code = 400
response = self.client.post('/api/users/', data)
self.assertEqual(response.status_code, code)
\ No newline at end of file
from users.tests.registration import *
from users.tests.userserializer import *
from users.tests.twowaydomain import *
\ No newline at end of file
import json
from django.test import TestCase, RequestFactory, Client
from users.serializers import UserSerializer
from users.models import User
url = "/api/users/"
class RegistrationTestCase(TestCase):
"""Django test for regestering a new user.
tests:
set_up: Set up everything needed for the test
test_registration: Register new user
"""
def setUp(self):
self.client = Client()
def test_registration(self):
data = {"username": "Test", "email": "test@t.no",
"password": "strong_pwd", "password1": "strong_pwd",
"phone_number": "12345678", "country": "Norway",
"city": "Trondheim", "street_address": "Trondheimsvegen 123"}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 201)
class BoundaryValuesOfRegistrationTestCase(TestCase):
"""Django test for boundary values of regestering a new user.
tests:
set_up: Set up everything needed for the test
test_minimum_data: Register new user with as little data as possible
test_blank_password: Register new user without password
test_blank_username: Register new user without username
test_invalid_email: Register new user without valid email
"""
def set_up(self):
self.client = Client()
def test_minimum_data(self):
data = {"username": "t", "email": "",
"password": "1", "password1": "1",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 201)
def test_blank_password(self):
data = {"username": "test", "email": "",
"password": "", "password1": "",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 400)
def test_blank_username(self):
data = {"username": "", "email": "",
"password": "1", "password1": "1",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 400)
def test_invalid_email(self):
data = {"username": "Test", "email": "test.no",
"password": "1", "password1": "1",
"phone_number": "", "country": "",
"city": "", "street_address": ""}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 400)
\ No newline at end of file
import json
from django.test import TestCase, RequestFactory, Client
from users.serializers import UserSerializer
from users.models import User
url = "/api/users/"
test_cases = [
{'email':'wrong', 'username':'wrong', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'empty', 'city':'empty', 'street_address':'normal'},
{'email':'wrong', 'username':'normal', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'wrong', 'username':'empty', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'normal', 'password':'empty', 'password1':'empty', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'normal', 'password':'normal', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'empty', 'street_address':'empty'},
{'email':'normal','username':'wrong', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'normal','username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'wrong', 'password':'empty', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'empty', 'username':'empty', 'password':'empty', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'empty', 'username':'wrong', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'empty', 'username':'normal', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'empty', 'street_address':'normal'},
{'email':'empty', 'username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'empty', 'username':'empty', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'empty', 'username':'wrong', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'empty'},
{'email':'empty', 'username':'normal', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'wrong', 'password':'empty', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'empty'},
{'email':'wrong', 'username':'wrong', 'password':'normal', 'password1':'empty', 'phone_number':'empty', 'country':'empty', 'city':'normal', 'street_address':'normal'},
{'email':'wrong', 'username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'empty', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'normal', 'password':'empty', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'empty', 'password':'normal', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'wrong', 'password':'empty', 'password1':'normal', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'normal', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'normal', 'city':'empty', 'street_address':'normal'},
{'email':'normal','username':'empty', 'password':'empty', 'password1':'normal', 'phone_number':'empty', 'country':'normal', 'city':'normal', 'street_address':'empty'},
{'email':'normal','username':'wrong', 'password':'normal', 'password1':'empty', 'phone_number':'normal', 'country':'empty', 'city':'normal', 'street_address':'normal'}
]
case_data = {
'normal': {
'email': 'test@test.no',
'username': 'test',
'password': 'test123',
'password1': 'test123',
'phone_number': 12354678,
'country': 'Norway',
'city': 'Trondheim',
'street_address': 'Trondheimsvegen',
},
'empty': {
'email': '',
'username': '',
'password': '',
'password1': '',
'phone_number': '',
'country': '',
'city': '',
'street_address': '',
},
'wrong': {
'email': 'test.no',
'username': 'test]',
}
}
class TwoWayDomainTestOfRegistrationTestCase(TestCase):
"""Django two-way domain test for registration of new user.
tests:
set_up: Set up everything needed for the test and define test cases
test_domain_registration Tests all test cases and evalutes them against expected responses
"""
def set_up(self):
self.client = Client()
def test_domain_registration(self):
for case in test_cases:
data = {}
for key, value in case.items():
data[key] = case_data[value][key]
code = 201
if case['email'] == 'wrong' or case['username'] == 'wrong' or case['password'] == 'empty' or case['username'] == 'empty' or case['password1'] == 'empty':
code = 400
response = self.client.post(url, data)
self.assertEqual(response.status_code, code)
\ No newline at end of file
import json
from django.test import TestCase, RequestFactory, Client
from users.serializers import UserSerializer
from users.models import User
from django.core.exceptions import ValidationError
url = "/api/users/"
class UserSerializerTestCase(TestCase):
"""Django test for the UserSerializer class.
tests:
set_up: Set up everything needed for the test
test_validate_password_valid: Test the validate password method with valid input
test_validate_password_invalid: Test the validate password mothod with invalid input
test_create: Test creating a new user with the create method
"""
def set_up(self):
self.user1 = User.objects.create(username="user1")
self.user2 = User.objects.create(username="user2", coach=self.user1)
self.factory = RequestFactory()
def test_validate_password_valid(self):
password = "some_very_strong_pwd"
serializer = UserSerializer(data = {'password': password,'password1': password})
validated_password = serializer.validate_password(password)
self.assertEqual(validated_password, password)
def test_validate_password_invalid(self):
password = "some_very_strong_pwd"
password1 = "Some_wrong_pwd"
serializer = UserSerializer(data = {'password': password,'password1': password})
serializer.validate_password(password1)
self.assertRaises(ValidationError)
def test_create(self):
data = {"username": "Test", "email": "test@test.no",
"password": "strong_pwd", "password1": "strong_pwd",
"phone_number": "12345678", "country": "Norway",
"city": "Trondheim", "street_address": "Trondheimsvegen 1"}
serializer = UserSerializer(data)
user = serializer.create(data)
self.assertEqual(user.username, "Test")
self.assertEqual(user.email, "test@test.no")
self.assertEqual(user.phone_number, "12345678")
self.assertEqual(user.country, "Norway")
self.assertEqual(user.city, "Trondheim")
self.assertEqual(user.street_address, "Trondheimsvegen 1")
\ No newline at end of file
......@@ -98,7 +98,6 @@ class OfferList(
serializer.save(owner=self.request.user)