Commit 3b016106 authored by Marius Engen's avatar Marius Engen
Browse files

Merge branch 'task2' into 'master'

Task 2: Test UserSerializer and workouts/permissions.py

See merge request !5
parents ee780355 48c84ae7
Pipeline #166658 passed with stages
in 2 minutes and 13 seconds
......@@ -10,6 +10,9 @@ test:
- cd backend/secfit
- apt-get update -qy
- pip install -r requirements.txt
- coverage run manage.py test
- coverage report -m workouts/permissions.py users/serializers.py
staging:
type: deploy
......
......@@ -189,3 +189,20 @@ Continuous integration will build the code pushed to master and push it to your
* and create an admin account for the backend by running
`heroku run python backend/secfit/manage.py createsuperuser -a <heroku-app-name>`.
* seed database `heroku run python backend/secfit/manage.py loaddata backend/secfit/seed.json -a <heroku-app-name>`
### Testing
To run unit tests in django run the following command:
`python3 manage.py test`
[Coverage.py](https://coverage.readthedocs.io/en/6.3.2/) is also implemented to report testing coverage in the backend. To use coverage simply replace `python3` with `coverage run`, i.e.:
`coverage run manage.py test`
To obtain a report of the test coverage in all files in the backend run
`coverage report -m`
This testing is also implemented in the GitLab CI/CD pipeline testing stage. See the `.gitlab-ci.yml` testing stage.
\ No newline at end of file
asgiref==3.2.10
astroid==2.4.2
backports.zoneinfo==0.2.1
certifi==2020.6.20
chardet==3.0.4
charset-normalizer==2.0.12
colorama==0.4.3
coverage==6.3.2
dj-database-url==0.5.0
Django==3.1
django-cleanup==5.0.0
......@@ -15,7 +18,8 @@ idna==2.10
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
psycopg2-binary
platformdirs==2.5.1
psycopg2-binary==2.9.3
Pygments==2.6.1
PyJWT==1.7.1
pylint==2.5.3
......@@ -27,6 +31,7 @@ rope==0.17.0
six==1.15.0
sqlparse==0.3.1
toml==0.10.1
typing_extensions==4.1.1
urllib3==1.25.10
whitenoise==5.2.0
wrapt==1.12.1
from django.test import TestCase
from users.models import User
from users.serializers import UserSerializer
from rest_framework import serializers
from django.test import TestCase, Client
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
# Create your tests here.
class UserSerializerTest(TestCase):
def setUp(self):
self.user_attributes = {
"id": 1,
"email": "test@test.com",
"username": "test",
"password": "test_123456",
"phone_number": 123456789,
"country": "Norway",
"city": "Trondheim",
"street_address": "Kongens gate 1",
}
self.serializer_data = {
"url": "https://link.com",
"id": 1,
"email": "test@test.com",
"username": "test",
"password": "test_123456",
"password1": "test_123456",
"athletes": "athletes",
"phone_number": 123456789,
"country": "Norway",
"city": "Trondheim",
"street_address": "Kongens gate 1",
"coach": "coach",
"workouts": "workouts",
"coach_files": "coach_files",
"athlete_files": "athlete_files",
}
self.client = Client()
factory = APIRequestFactory()
request = factory.get('/')
serializer_context = {
'request': Request(request),
}
self.user = User.objects.create(**self.user_attributes)
self.serializer = UserSerializer(instance=self.user,
context=serializer_context)
def test_contains_expected_fields(self):
data = self.serializer.data
self.assertEqual(set(data.keys()), set(["url",
"id",
"email",
"username",
"athletes",
"phone_number",
"country",
"city",
"street_address",
"coach",
"workouts",
"coach_files",
"athlete_files"]))
def test_validate_password(self):
# Assert that correct password yields same password
self.assertEqual(self.user.password, self.serializer.validate_password(self.user.password))
def test_incorrect_password_raises_exception(self):
# Assert that ValidationError is raised for incorrect password
# Change to invalid password
self.serializer.password = '123'
with self.assertRaises(serializers.ValidationError):
self.serializer.validate_password(self.serializer.password)
raise serializers.ValidationError
def test_create_method(self):
# Assert that user was created correctly
self.assertEqual(self.user_attributes['username'], self.user.username)
self.assertEqual(self.user_attributes['password'], self.user.password)
......@@ -2,5 +2,145 @@
Tests for the workouts application.
"""
from django.test import TestCase
from datetime import datetime
from django.utils import timezone
# Create your tests here.
from users.models import User
import workouts.permissions as ps
from workouts.models import Workout
from rest_framework.test import APIRequestFactory
from comments.models import Comment
class UserPermissionTest(TestCase):
def setUp(self):
self.coach_attr = {
"id": 2,
"email": "coach@coach.com",
"username": "coach",
"password": "test_123456",
"phone_number": 123456789,
"country": "Norway",
"city": "Trondheim",
"street_address": "Kongens gate 1",
}
self.coach = User.objects.create(**self.coach_attr)
self.athlete_attr = {
"id": 1,
"email": "athlte@athlete.com",
"username": "athlete",
"password": "test_123456",
"phone_number": 123456789,
"coach": self.coach,
"country": "Norway",
"city": "Trondheim",
"street_address": "Kongens gate 1",
}
self.athlete = User.objects.create(**self.athlete_attr)
self.public_workout = Workout.objects.create(name='public_workout',
date=timezone.now(),
notes='text',
owner=self.athlete,
visibility="PU")
self.coach_workout = Workout.objects.create(name='coach_workout',
date=timezone.now(),
notes='text',
owner=self.athlete,
visibility="CO")
self.comment_public = Comment.objects.create(owner=self.athlete,
workout=self.public_workout,
content='content')
self.comment_coach = Comment.objects.create(owner=self.athlete,
workout=self.coach_workout,
content='content')
# Set up base request
self.factory = APIRequestFactory()
self.request = self.factory.post('', None)
# Instantiate permission objects
self.is_owner = ps.IsOwner()
self.is_owner_of_workout = ps.IsOwnerOfWorkout()
self.is_coach_and_visible_to_coach = ps.IsCoachAndVisibleToCoach()
self.is_coach_of_workout_and_visible_to_coach = ps.IsCoachOfWorkoutAndVisibleToCoach()
self.is_public = ps.IsPublic()
self.is_workout_public = ps.IsWorkoutPublic()
self.is_read_only = ps.IsReadOnly()
def test_is_owner_true(self):
# Assert that owner has permission
self.request.user = self.athlete
self.assertTrue(self.is_owner.has_object_permission(request=self.request, view=None, obj=self.public_workout))
def test_is_owner_false(self):
# Assert that a non owner does not have permission
self.request.user = self.coach
self.assertFalse(self.is_owner.has_object_permission(request=self.request, view=None, obj=self.public_workout))
def test_is_owner_of_workout_has_permission_true_owner(self):
# Check that requesting user is owner of new object
data = {'workout': '1/1/1/1'}
request = self.factory.post('', {'workout': self.public_workout})
request.data = data
request.user = self.athlete
self.assertTrue(self.is_owner_of_workout.has_permission(request=request, view=None))
def test_is_owner_of_workout_has_permission_no_workout(self):
# Check that requesting user is owner of new object
data = {}
request = self.factory.post('', {'workout': self.public_workout})
request.data = data
request.user = self.athlete
self.assertFalse(self.is_owner_of_workout.has_permission(request=request, view=None))
def test_is_owner_of_workout_has_permission_get(self):
# Check that requesting user is owner of new object
request = self.factory.get('', {'workout': self.public_workout})
self.assertTrue(self.is_owner_of_workout.has_permission(request=request, view=None))
def test_is_owner_of_workout_has_object_permission(self):
# Check that requesting user is owner of new object
self.request.user = self.athlete
self.assertTrue(self.is_owner_of_workout.has_object_permission(request=self.request, view=None, obj=self.comment_public))
def test_is_coach_and_visible_to_coach_public_workout(self):
# Assert that owner's coach can view workout: Public visibilty
self.request.user = self.coach
self.assertTrue(self.is_coach_and_visible_to_coach.has_object_permission(request=self.request, view=None, obj=self.public_workout))
def test_is_coach_and_visible_to_coach_coach_workout(self):
# Assert that owner's coach can view workout: Coach visbility
self.request.user = self.coach
self.assertTrue(self.is_coach_and_visible_to_coach.has_object_permission(request=self.request, view=None, obj=self.coach_workout))
def test_is_coach_of_workout_and_visible_to_coach_publiic(self):
# Assert that coach has permission to view workout from comment: public visibilty
self.request.user = self.coach
self.assertTrue(self.is_coach_of_workout_and_visible_to_coach.has_object_permission(request=self.request, view=None, obj=self.comment_public))
def test_is_coach_of_workout_and_visible_to_coach_publiic(self):
# Assert that coach has permission to view workout from comment: public visibilty
self.request.user = self.coach
self.assertTrue(self.is_coach_of_workout_and_visible_to_coach.has_object_permission(request=self.request, view=None, obj=self.comment_coach))
def test_is_public(self):
self.assertTrue(self.is_public.has_object_permission(request=self.request, view=None, obj=self.public_workout))
def test_is_workout_public(self):
self.assertTrue(self.is_workout_public.has_object_permission(request=self.request, view=None, obj=self.comment_public))
def test_is_read_only_post(self):
self.request = self.factory.post('', None)
self.assertFalse(self.is_read_only.has_object_permission(request=self.request, view=None, obj=None))
def test_is_read_only_get(self):
self.request = self.factory.get('', None)
self.assertTrue(self.is_read_only.has_object_permission(request=self.request, view=None, obj=None))
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