Skip to content

Commit

Permalink
serializer testen
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnoutAllaert committed Mar 13, 2024
1 parent ae9dacf commit fcdbda6
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 64 deletions.
15 changes: 11 additions & 4 deletions api/serializers/groep.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from rest_framework import serializers
from api.models.groep import Groep
from collections import Counter


class GroepSerializer(serializers.ModelSerializer):
Expand All @@ -18,7 +19,7 @@ def create(self, validated_data):

def update(self, instance, validated_data):
students_data = validated_data.pop('studenten')
validate_students(students_data, validated_data['project'])
validate_students(students_data, validated_data['project'], current_group=instance)

super().update(instance=instance, validated_data=validated_data)
instance.studenten.set(students_data)
Expand All @@ -28,13 +29,19 @@ def update(self, instance, validated_data):



def validate_students(students_data, project):
def validate_students(students_data, project, current_group=None):
student_counts = Counter(students_data)
for student, count in student_counts.items():
if count > 1:
raise serializers.ValidationError(f"Student {student.user.id} zit al in deze groep.")

groepen = Groep.objects.filter(project=project)

for student in students_data:
if student.is_lesgever:
raise serializers.ValidationError("Alle gebruikers in 'studenten' moeten studenten zijn!")

for groep in groepen:
if groep.studenten.contains(student):
raise serializers.ValidationError(f"Gebruiker {student.user.id} zit al in een groep voor dit project")
if (current_group and groep.groep_id != current_group.groep_id) and groep.studenten.contains(student):
raise serializers.ValidationError(f"Gebruiker {student.user.id} zit al in een groep voor dit project")

3 changes: 1 addition & 2 deletions api/tests/factories/groep.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ class GroepFactory(DjangoModelFactory):
class Meta:
model = Groep

groep_id = factory.Sequence(lambda n: n)
project = SubFactory(ProjectFactory)

@factory.post_generation
Expand All @@ -22,4 +21,4 @@ def studenten(self, create, extracted, **kwargs):
for student in extracted:
self.studenten.add(student)
else:
self.studenten.add(GebruikerFactory())
self.studenten.add(GebruikerFactory(is_lesgever=False))
1 change: 0 additions & 1 deletion api/tests/factories/vak.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ class VakFactory(DjangoModelFactory):
class Meta:
model = Vak

vak_id = factory.Sequence(lambda n: n)
naam = Faker('name')

@factory.post_generation
Expand Down
40 changes: 26 additions & 14 deletions api/tests/serializers/test_gebruiker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,44 @@
from rest_framework.exceptions import ValidationError
from api.serializers.gebruiker import GebruikerSerializer
from api.tests.factories.gebruiker import UserFactory, GebruikerFactory
from api.tests.factories.vak import VakFactory


class GebruikerSerializerTest(APITestCase):
def setUp(self):
self.user = UserFactory.create(username="testuser")
self.gebruiker = GebruikerFactory.create(user=self.user)

subjects = VakFactory.create_batch(2)
self.gebruiker.subjects.set(subjects)

self.user = UserFactory.create()
self.gebruiker = GebruikerFactory.create(user=self.user, is_lesgever=False)
self.serializer = GebruikerSerializer(instance=self.gebruiker)

def test_contains_expected_fields(self):
data = self.serializer.data
self.assertCountEqual(data.keys(), ["user", "is_lesgever", "subjects"])
self.assertCountEqual(data.keys(), ["user", "is_lesgever"])

def test_user_field_content(self):
data = self.serializer.data
self.assertEqual(data["user"], self.user.id)

def test_subjects_field_content(self):
def test_is_lesgever_field_content(self):
data = self.serializer.data
subjects = [subject.pk for subject in self.gebruiker.subjects.all()]
self.assertEqual(data["subjects"], subjects)

self.assertEqual(data["is_lesgever"], self.gebruiker.is_lesgever)

def test_create(self):
data = {'user': UserFactory.create().id, 'is_lesgever':False}
serializer = GebruikerSerializer(data=data)
self.assertTrue(serializer.is_valid())
gebruiker = serializer.save()
self.assertEqual(gebruiker.user.id, data["user"])
self.assertEqual(gebruiker.is_lesgever, data["is_lesgever"])

def test_update(self):
data = self.serializer.data
self.assertFalse(data["is_lesgever"])
data["is_lesgever"] = True
serializer = GebruikerSerializer(instance=self.gebruiker, data=data, partial=True)
self.assertTrue(serializer.is_valid())
self.gebruiker = serializer.save()
self.assertTrue(self.gebruiker.is_lesgever)

def test_validation_for_blank_items(self):
serializer = GebruikerSerializer(data={"name": "", "subjects": []})
serializer = GebruikerSerializer(data={"user": "", "is_lesgever": []})
self.assertRaises(ValidationError, serializer.is_valid, raise_exception=True)

33 changes: 26 additions & 7 deletions api/tests/serializers/test_groep.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from rest_framework.exceptions import ValidationError
from api.serializers.groep import GroepSerializer
from api.tests.factories.groep import GroepFactory
from api.tests.factories.gebruiker import GebruikerFactory
from api.tests.factories.gebruiker import GebruikerFactory


class GroepSerializerTest(APITestCase):
Expand All @@ -11,19 +13,36 @@ def setUp(self):

def test_contains_expected_fields(self):
data = self.serializer.data
self.assertCountEqual(data.keys(), ["group_id", "project", "students"])
self.assertCountEqual(data.keys(), ["groep_id", "project", "studenten"])

def test_project_field_content(self):
data = self.serializer.data
self.assertEqual(
data["project"], self.groep.project.pk
) # replace 'pk' with the correct primary key field of the Project model
data["project"], self.groep.project.project_id
)

def test_students_field_content(self):
def test_studenten_field_content(self):
data = self.serializer.data
students = [student.pk for student in self.groep.students.all()]
self.assertEqual(data["students"], students)
students = [student.user.id for student in self.groep.studenten.all()]
self.assertEqual(data["studenten"], students)

def test_create(self):
data = {'project': self.groep.project.project_id, 'studenten': [GebruikerFactory.create(is_lesgever=False).user.id for _ in range(3)]}
serializer = GroepSerializer(data=data)
self.assertTrue(serializer.is_valid())
groep = serializer.save()
self.assertEqual(groep.project.project_id, data['project'])
self.assertEqual(set([student.user.id for student in groep.studenten.all()]), set(data['studenten']))

def test_update(self):
data = self.serializer.data
self.assertEqual(len(data["studenten"]), 1)
data["studenten"].append(GebruikerFactory.create(is_lesgever=False).user.id)
serializer = GroepSerializer(instance=self.groep, data=data, partial=True)
self.assertTrue(serializer.is_valid())
groep = serializer.save()
self.assertEqual([student.user.id for student in groep.studenten.all()], data['studenten'])

def test_validation_for_blank_items(self):
serializer = GroepSerializer(data={"project": "", "students": []})
serializer = GroepSerializer(data={"project": "", "studenten": []})
self.assertRaises(ValidationError, serializer.is_valid, raise_exception=True)
61 changes: 50 additions & 11 deletions api/tests/serializers/test_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
from api.serializers.project import ProjectSerializer
from api.tests.factories.project import ProjectFactory
from dateutil.parser import parse
from api.tests.factories.vak import VakFactory
from django.core.files import File



class ProjectSerializerTest(APITestCase):
Expand All @@ -17,33 +20,39 @@ def test_contains_expected_fields(self):
[
"project_id",
"titel",
"description",
"opgavebestanden",
"beschrijving",
"opgave_bestand",
"vak",
"deadline",
"max_score"
],
)

def test_titel_field_content(self):
data = self.serializer.data
self.assertEqual(data["titel"], self.project.titel)

def test_description_field_content(self):
def test_beschrijving_field_content(self):
data = self.serializer.data
self.assertEqual(data["description"], self.project.description)
self.assertEqual(data["beschrijving"], self.project.beschrijving)

def test_opgavebestanden_field_content(self):
def test_opgave_bestand_field_content(self):
data = self.serializer.data
self.assertEqual(
data["opgavebestanden"].lstrip("/"), str(self.project.opgavebestanden)
data["opgave_bestand"].lstrip("/"), str(self.project.opgave_bestand)
)

def test_vak_field_content(self):
data = self.serializer.data
self.assertEqual(
data["vak"], self.project.vak.pk
) # replace 'pk' with the correct primary key field of the Vak model

data["vak"], self.project.vak.vak_id
)

def test_max_score_field_content(self):
data = self.serializer.data
self.assertGreaterEqual(data['max_score'], 10)
self.assertLessEqual(data['max_score'], 30)

def test_deadline_field_content(self):
data = self.serializer.data
self.assertEqual(parse(data["deadline"]), self.project.deadline)
Expand All @@ -52,10 +61,40 @@ def test_validation_for_blank_items(self):
serializer = ProjectSerializer(
data={
"titel": "",
"description": "",
"opgavebestanden": "",
"beschrijving": "",
"opgave_bestand": "",
"vak": "",
"deadline": "",
"max_score": "",
}
)
self.assertRaises(ValidationError, serializer.is_valid, raise_exception=True)

def test_create(self):
vak = VakFactory.create().vak_id
with open('api/tests/data/test.txt', 'rb') as fp:
data = {"titel": "test project",
"beschrijving": "Dit is een test project.",
"opgave_bestand": File(fp),
"vak": vak,
"deadline": self.serializer.data["deadline"],
"max_score": 20
}
serializer = ProjectSerializer(data=data)
self.assertTrue(serializer.is_valid())
project = serializer.save()
self.assertEqual(project.deadline, parse(data['deadline']))

def test_update(self):
with open('api/tests/data/test.txt', 'rb') as fp:
data = {"titel": "test project",
"beschrijving": "Dit is een test project.",
"opgave_bestand": File(fp),
"vak": self.serializer.data["vak"],
"deadline": self.serializer.data["deadline"],
"max_score": 20
}
serializer = ProjectSerializer(instance=self.project, data=data, partial=True)
self.assertTrue(serializer.is_valid())
project = serializer.save()
self.assertEqual(project.deadline, parse(data['deadline']))
67 changes: 46 additions & 21 deletions api/tests/serializers/test_vak.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,72 @@

class VakSerializerTest(APITestCase):
def setUp(self):
self.students = GebruikerFactory.create_batch(3, is_lesgever=False)
self.teachers = GebruikerFactory.create_batch(2, is_lesgever=True)
self.vak = VakFactory.create()
self.vak.students.set(self.students)
self.vak.teachers.set(self.teachers)
self.serializer = VakSerializer(instance=self.vak)
self.vak_data = VakFactory.create()
self.serializer = VakSerializer(instance=self.vak_data)

def test_contains_expected_fields(self):
data = self.serializer.data
self.assertCountEqual(
data.keys(), ["vak_id", "name", "students", "teachers"]
) # geen projects hier?
data.keys(), ["vak_id", "naam", "studenten", "lesgevers"]
)

def test_vak_id_field_content(self):
data = self.serializer.data
self.assertEqual(data["vak_id"], self.vak.vak_id)
self.assertEqual(data["vak_id"], self.vak_data.vak_id)

def test_name_field_content(self):
def test_naam_field_content(self):
data = self.serializer.data
self.assertEqual(data["name"], self.vak.name)
self.assertEqual(data["naam"], self.vak_data.naam)

def test_students_field_content(self):
def test_studenten_field_content(self):
data = self.serializer.data
self.assertCountEqual(
data["students"], [student.pk for student in self.students]
self.assertEqual(
set(data["studenten"]), set([student.user.id for student in self.vak_data.studenten.all()])
)

def test_teachers_field_content(self):
def test_lesgevers_field_content(self):
data = self.serializer.data
self.assertCountEqual(
data["teachers"], [teacher.pk for teacher in self.teachers]
self.assertEqual(
set(data["lesgevers"]), set([teacher.user.id for teacher in self.vak_data.lesgevers.all()])
)

def test_validation_for_blank_items(self):
serializer = VakSerializer(
data={
"vak_id": "",
"name": "",
"students": [],
"teachers": [],
"projects": [],
"naam": "",
"studenten": [],
"lesgevers": [],
}
)
self.assertRaises(ValidationError, serializer.is_valid, raise_exception=True)

def test_create(self):
students_data = [GebruikerFactory.create(is_lesgever=False).user.id for _ in range(3)]
teachers_data = [GebruikerFactory.create(is_lesgever=True).user.id for _ in range(3)]
data = {'naam': 'test vak', 'studenten': students_data, 'lesgevers': teachers_data}
serializer = VakSerializer(data=data)
self.assertTrue(serializer.is_valid())
vak = serializer.save()
self.assertEqual(
set(students_data), set([student.user.id for student in vak.studenten.all()])
)
self.assertEqual(
set(teachers_data), set([teacher.user.id for teacher in vak.lesgevers.all()])
)
self.assertEqual(vak.naam, 'test vak')

def test_update(self):
students_data = [GebruikerFactory.create(is_lesgever=False).user.id for _ in range(3)]
teachers_data = [GebruikerFactory.create(is_lesgever=True).user.id for _ in range(3)]
data = {'naam': 'nieuw vak', 'studenten': students_data, 'lesgevers': teachers_data}
serializer = VakSerializer(instance=self.vak_data, data=data, partial=True)
self.assertTrue(serializer.is_valid())
vak = serializer.save()
self.assertEqual(
set(students_data), set([student.user.id for student in vak.studenten.all()])
)
self.assertEqual(
set(teachers_data), set([teacher.user.id for teacher in vak.lesgevers.all()])
)
self.assertEqual(vak.naam, 'nieuw vak')
6 changes: 3 additions & 3 deletions api/tests/views/test_groep.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ def test_get_groep_list(self):
def test_post_groep_list(self):
groep = GroepFactory.create()
data = {
"groep": groep.group_id,
"groep": groep.groep_id,
"project": groep.project.project_id,
"students": [],
"studenten": [],
}
response = self.client.post("/api/groepen/", data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Expand All @@ -27,7 +27,7 @@ class GroepDetailViewTest(APITestCase):
def setUp(self):
self.client = APIClient()
self.groep = GroepFactory.create()
self.url = reverse("groep_detail", kwargs={"id": self.groep.group_id})
self.url = reverse("groep_detail", kwargs={"id": self.groep.groep_id})

def test_get_groep_detail(self):
response = self.client.get(self.url)
Expand Down
Loading

0 comments on commit fcdbda6

Please sign in to comment.