Commit f958f5ec authored by Florent Chehab's avatar Florent Chehab

Cleaning and tests added

parent 4c32f310
Pipeline #26859 passed with stages
in 2 minutes and 26 seconds
......@@ -2,5 +2,9 @@
omit =
*migrations*
*/tests/*
manage.py
general/wsgi.py
*/urls.py
*/admin.py
source = .
......@@ -3,16 +3,13 @@ from django.contrib.auth.models import User
class LoadAdminUser(object):
def __init__(self):
admins = User.objects.filter(username="admin")
if len(admins) > 0:
self.admin = admins[0]
else:
self.admin = User.objects.create_superuser(
username='admin',
email='null@null.fr',
password='admin'
)
self.admin = User.objects.get_or_create(
username="admin",
defaults={
'email': 'null@null.fr',
'password': 'admin',
'is_staff': True
})[0]
def get(self):
return self.admin
from django.db import models
from rest_framework import serializers
from backend.models.location import Country
from backend.models.my_model import MyModel, MyModelSerializer, MyModelVersionnedViewSet
from backend.utils import get_model_config, get_viewset_permissions
......@@ -17,14 +16,6 @@ class City(MyModel):
class CitySerializer(MyModelSerializer):
country_url = serializers.SerializerMethodField()
def get_country_url(self, obj):
return serializers.HyperlinkedRelatedField(
view_name='country-detail',
read_only=True) \
.get_url(obj.country, view_name='country-detail',
request=self.context['request'], format=None)
class Meta:
model = City
......
......@@ -52,10 +52,12 @@ class MyModelVersionnedViewSet(MyModelViewSet):
class VersionSerializer(serializers.ModelSerializer):
# serialized_data = serializers.JSONField()
data = serializers.SerializerMethodField()
def get_data(self, obj):
"""
TODO test
"""
data = obj.serialized_data
try:
......@@ -64,12 +66,9 @@ class VersionSerializer(serializers.ModelSerializer):
print(tmp.object)
# Version is valid,
obj_serializer = tmp.object.get_serializer()
if obj_serializer is None:
return "THE PROGRAMMER FORGOT TO SET THE SERIALIZER IN THE MODEL"
else:
new_context = dict(self.context)
new_context['view'].action = 'list'
return obj_serializer(tmp.object, context=new_context).data
new_context = dict(self.context)
new_context['view'].action = 'list'
return obj_serializer(tmp.object, context=new_context).data
except (DeserializationError, djangoSerializers.SerializerDoesNotExist):
obj.delete() # The version is not valid regarding the model, we should delete it !
# Might result in inconsistent nb of versions but that's fine.
......@@ -92,5 +91,3 @@ class VersionViewSet(mixins.ListModelMixin,
model = ct.model_class()
obj = model.objects.get(pk=object_pk)
return Version.objects.get_for_object(obj)
# queryset = get_queryset()
......@@ -5,14 +5,9 @@ from rest_framework import serializers
from backend.utils import get_model_config, get_viewset_permissions
def check_nones(val1, val2):
if val1 is None and val2 is not None:
raise serializers.ValidationError("Check your dates")
if val2 is None and val1 is not None:
raise serializers.ValidationError("Check your dates")
return val1 is None and val2 is None
def semester_error(semester_name):
raise serializers.ValidationError(
"Inconsistent {} semester dates".format(semester_name))
class UniversitySemestersDates(BasicModule):
......@@ -34,19 +29,22 @@ class UniversitySemestersDates(BasicModule):
class UniversitySemestersDatesSerializer(BasicModuleSerializer):
def my_validate(self, attrs):
spring_ok = check_nones(attrs['spring_begin'], attrs['spring_end'])
autumn_ok = check_nones(attrs['autumn_begin'], attrs['autumn_end'])
if not spring_ok:
spring_ok = attrs['spring_begin'] < attrs['spring_end']
if not autumn_ok:
autumn_ok = attrs['autumn_begin'] < attrs['autumn_end']
# no check if spring_end < autumn_begin in case info is not available
if not (spring_ok and autumn_ok):
raise serializers.ValidationError(
"Check your dates !") # TODO better error
s_b, s_e = attrs['spring_begin'], attrs['spring_end']
a_b, a_e = attrs['autumn_begin'], attrs['autumn_end']
def test(begin, end, name):
ok = (begin is None and end is None) or (
begin is not None and end is not None)
if not ok:
semester_error(name)
if begin is not None and (begin > end):
semester_error(name)
test(s_b, s_e, 'spring')
test(a_b, a_e, 'autumn')
if s_b is None and a_b is None:
semester_error('autaumn and spring')
return attrs
......
......@@ -227,16 +227,5 @@ class ModerationTestCase(WithUserTestCase):
}
api_end_point = "/api/" + \
find_api_end_point_for_viewset("UniversityDriViewSet") + "/"
print(api_end_point)
self._submit_post_test(self.dri_client,
data, api_end_point)
# instance = self._test_retreive_instance(data_1)
# self._test_updated_val(instance, null=False)
# self._test_moderated_val(instance, null=False)
# self.assertEqual(instance.updated_by, self.authenticated_user)
# self.assertEqual(instance.moderated_by, self.authenticated_user)
# self._test_retreive_instance_in_moderation(
# instance, expected_fail=True
# )
from django.test import TestCase
from backend.models.my_model.myModel import validate_obj_model_lv
import pytest
from django.core.exceptions import ValidationError
from backend.permissions import OBJ_MODERATION_PERMISSIONS
class MyModelTestCase(TestCase):
def test_my_model_validation(self):
with pytest.raises(ValidationError):
value = "bernard"
validate_obj_model_lv(value)
for key in OBJ_MODERATION_PERMISSIONS:
validate_obj_model_lv(OBJ_MODERATION_PERMISSIONS[key])
from django.test import TestCase
from backend.models.module.scholarship import ScholarshipSerializer
import pytest
from rest_framework.validators import ValidationError
class ScholarshipTestCase(TestCase):
def test_scholarhip_validation(self):
ser = ScholarshipSerializer()
with pytest.raises(ValidationError):
attrs = {
'amount_max': 100,
'amount_min': 200
}
ser.my_validate(attrs)
attrs = {
'amount_max': 200,
'amount_min': 100
}
ser.my_validate(attrs)
from django.test import TestCase
from backend.models.university import UniversitySemestersDatesSerializer
import pytest
from rest_framework.validators import ValidationError
semesters = ['spring_begin', 'spring_end', 'autumn_begin', 'autumn_end']
class SemesterDatesTestCase(TestCase):
def test_validation(self):
def build(l):
return {sem: val for sem, val in zip(semesters, l)}
def _test_attrs_error(attrs):
with pytest.raises(ValidationError):
self.ser.my_validate(attrs)
self.ser = UniversitySemestersDatesSerializer()
_test_attrs_error(build([None] * 4))
_test_attrs_error(build([None, 3, None, None]))
_test_attrs_error(build([2, 3, 3, 2]))
self.ser.my_validate(build([2, 3, None, None]))
self.ser.my_validate(build([2, 3, 2, 3]))
from django.test import TestCase
import pytest
from rest_framework.validators import ValidationError as RFValidationError
from django.core.validators import ValidationError as DJValidationError
from backend.models.tag.validators.url import validate_extension, validate_url
class ValidationUrlTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.good = [
"https://www.epfl.ch/publ6d4772210.svg",
"http://google.fr/image.jpg"
]
cls.bad = [
"google"
]
pass
def test_validate_extension(self):
for url in self.good:
validate_extension(["svg", 'jpg'], url)
for url in self.good + self.bad:
with pytest.raises(RFValidationError):
validate_extension(['png'], url)
def test_validate_url(self):
config_1 = {}
config_2 = {"validators": {"extension": ["jpg", "jpeg", "png", "svg"]}}
config_3 = {"validators": {"inconnu_au_bataillon": None}}
for url in self.good:
validate_url(config_1, url)
validate_url(config_2, url)
with pytest.raises(Exception):
validate_url(config_3, url)
for url in self.bad:
with pytest.raises(DJValidationError):
validate_url(config_1, url)
validate_url(config_2, url)
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
class SuperUserTest(TestCase):
def setUp(self):
password = 'root'
self.my_admin = User.objects.create_superuser(
'myuser', 'myemail@test.com', password)
self.c = Client()
self.c.login(username=self.my_admin.username, password=password)
def test_created(self):
"""
Simple test to check if we can create a superuser. We had issues in the past.
"""
self.assertTrue(self.my_admin.is_superuser)
Markdown is supported
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