Commit 0304b762 authored by Florent Chehab's avatar Florent Chehab

All tests operationnal

parent 9e8a19fa
Pipeline #26539 passed with stages
in 2 minutes and 9 seconds
[flake8]
# E501 line too long
ignore = E501
exclude = tests/*, env/*
\ No newline at end of file
exclude =
env/*
node_modules/*
......@@ -47,7 +47,7 @@ from backend.models.user import PreviousDeparture
from backend.models.user import PreviousDepartureFeedback
from backend.models.user import UserData
from backend.models.moderation import PendingModeration
from backend.models.my_model import PendingModeration
CLASSIC_MODELS = [
Country,
......
# Generated by Django 2.0.3 on 2018-08-26 08:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('backend', '0013_auto_20180825_1944'),
]
operations = [
migrations.CreateModel(
name='ForTestingVersionning',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('moderated_on', models.DateTimeField(null=True)),
('updated_on', models.DateTimeField(null=True)),
('aaa', models.CharField(max_length=100)),
('moderated_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('updated_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
# Generated by Django 2.0.3 on 2018-08-26 09:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('backend', '0014_fortestingversionning'),
]
operations = [
migrations.RenameField(
model_name='fortestingversionning',
old_name='aaa',
new_name='bbb',
),
]
......@@ -3,3 +3,5 @@ from .myModelSerializer import MyModelSerializer # noqa: F401
from .myModelViewSet import MyModelViewSet # noqa: F401
from .pendingModeration import PendingModeration, PendingModerationSerializer, PendingModerationViewSet # noqa: F401
from .forTestingModeration import ForTestingModeration, ForTestingModerationSerializer, ForTestingModerationViewSet # noqa: F401
from .myModelVersionned import MyModelVersionned, MyModelVersionnedSerializer, MyModelVersionnedViewSet # noqa: F401
from .forTestingVersionning import ForTestingVersionning, ForTestingVersionningSerializer, ForTestingVersionningViewSet # noqa: F401
from .myModelVersionned import MyModelVersionned, MyModelVersionnedSerializer, MyModelVersionnedViewSet
from django.db import models
import reversion
@reversion.register()
class ForTestingVersionning(MyModelVersionned):
"""
Simple model for testing purposes
"""
bbb = models.CharField(max_length=100)
class ForTestingVersionningSerializer(MyModelVersionnedSerializer):
"""
Same as above
"""
class Meta:
model = ForTestingVersionning
fields = '__all__'
class ForTestingVersionningViewSet(MyModelVersionnedViewSet):
"""
Same as above
"""
serializer_class = ForTestingVersionningSerializer
queryset = ForTestingVersionning.objects.all()
from django.db import models
from django.contrib.auth.models import User
# from rest_framework import serializers
# from backend.signals import new_revision_saved
# import reversion
class MyModel(models.Model):
......@@ -23,8 +20,3 @@ class MyModel(models.Model):
class Meta:
abstract = True
# class MyModelVersionned(MyModel):
# class Meta:
# abstract = True
......@@ -15,6 +15,7 @@ class MyModelSerializer(serializers.ModelSerializer):
moderated_by = serializers.CharField(read_only=True)
updated_by = serializers.CharField(read_only=True)
# TODO : updated_by_username useless ? See in rest API
updated_by_username = serializers.SerializerMethodField(read_only=True)
def get_updated_by_username(self, obj):
......@@ -111,17 +112,3 @@ class MyModelSerializer(serializers.ModelSerializer):
self.set_model_attr_no_moder(moderated_and_updated)
return super(MyModelSerializer, self).save(**kwargs)
# class MyModelVersionnedSerializer(MyModelSerializer):
# def save(self, **kwargs):
# user = self.set_model_attr()
# # Create a revision for the update or creation
# with reversion.create_revision():
# super(MyModelVersionnedSerializer, self).save(**kwargs)
# reversion.set_user(user)
# # Signal save to perform concat of revisions
# new_revision_saved.send(sender=self.__class__, obj=self.instance)
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
from backend.signals import new_revision_saved
import reversion
class MyModelVersionned(MyModel):
class Meta:
abstract = True
class MyModelVersionnedSerializer(MyModelSerializer):
def save(self, **kwargs):
# Retrieve the user info from the request
user = self.context['request'].user
with reversion.create_revision():
super(MyModelSerializer, self).save(**kwargs)
reversion.set_user(user)
# Signal save to perform squash of revisions
new_revision_saved.send(sender=self.__class__, obj=self.instance)
class MyModelVersionnedViewSet(MyModelViewSet):
serializer_class = MyModelVersionnedSerializer
from django.db import models
from backend.models.moderation import MyModel
from backend.models.my_model import MyModel
from backend.utils.friendly_path import friendly_path
path_and_rename = friendly_path("uploads/universities/logos/", 'name')
......
......@@ -2,7 +2,7 @@ from backend.models.university import University
from rest_framework import viewsets, permissions
from backend.models.university.campus import CampusSerializer
from backend.models.tools import NoDeleteIfNotAdmin
from backend.models.moderation import MyModelSerializer
from backend.models.my_model import MyModelSerializer
class UniversitySerializer(MyModelSerializer):
......
......@@ -7,6 +7,8 @@ new_revision_saved = django.dispatch.Signal(providing_args=["obj"])
def squashRevisionByUser(sender, obj, **kwargs):
"""
TODO add comment and unit test
It should also work with moderation as obj will be a versionned object
"""
versions = Version.objects\
.get_for_object(obj)\
......
from django.test import override_settings
from .withUserTestCase import WithUserTestCase
from backend.models.moderation import ForTestingModeration
from backend.models.moderation import PendingModeration
from backend.models.my_model import ForTestingModeration
from backend.models.my_model import PendingModeration
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
class ModerationTestCase(WithUserTestCase):
def moreSetUp(self):
self.api_moderation = '/api/test/moderation/'
@classmethod
def setUpMoreTestData(cls):
cls.api_moderation = '/api/test/moderation/'
def test_setting_ok(self):
self.assertTrue(settings.TESTING)
......
......@@ -3,8 +3,9 @@ from .withUserTestCase import WithUserTestCase
class ReadAccessTestCase(WithUserTestCase):
def moreSetUp(self):
self.api_moderation = '/api/test/moderation/'
@classmethod
def setUpMoreTestData(cls):
cls.api_moderation = '/api/test/moderation/'
def test_read(self):
"""
......
from backend.models.my_model import ForTestingVersionning
from reversion.models import Version
from backend.signals import squashRevisionByUser
import reversion
from .withUserTestCase import WithUserTestCase
import json
class SquashVersionsTestCase(WithUserTestCase):
def setUp(self):
self.obj = ForTestingVersionning(bbb="v1")
with reversion.create_revision():
self.obj.save()
reversion.set_user(self.authenticated_user)
def get_versions(self, obj):
return Version.objects\
.get_for_object(obj)\
.select_related('revision')\
.order_by('-revision__date_created')
def get_version_data(self, version):
return json.loads(version.serialized_data)[0]['fields']
def test_no_squashing(self):
"""
Test to check that when two different users successively
Modify a model, no squashing is performed
"""
with reversion.create_revision():
self.obj.bbb = "v2 other user"
self.obj.save()
reversion.set_user(self.authenticated_user_2)
squashRevisionByUser(None, self.obj)
versions = self.get_versions(self.obj)
self.assertEqual(len(versions), 2)
first_edit = self.get_version_data(versions[1])
second_edit = self.get_version_data(versions[0])
self.assertEqual(first_edit['bbb'], "v1")
self.assertEqual(second_edit['bbb'], "v2 other user")
def test_squashing(self):
"""
Test to check that when a user save two different
versions of a same model, no squashing is performed
"""
with reversion.create_revision():
self.obj.bbb = "v2"
self.obj.save()
reversion.set_user(self.authenticated_user)
squashRevisionByUser(None, self.obj)
versions = self.get_versions(self.obj)
self.assertEqual(len(versions), 1)
version_data = self.get_version_data(versions[0])
self.assertEqual(version_data['bbb'], "v2")
from .withUserTestCase import WithUserTestCase
from backend.models.my_model import ForTestingVersionning
from django.conf import settings
from reversion.models import Version
from backend.signals import new_revision_saved
class VersionningTestCase(WithUserTestCase):
@classmethod
def setUpMoreTestData(cls):
cls.testing_model = ForTestingVersionning
cls.api_versionning = '/api/test/versionning/'
def reset_signal_called(self):
self.signal_was_called = False
def test_setting_ok(self):
self.assertTrue(settings.TESTING)
#####
def _submit_put_test(self, client, data, pk):
response = client.put(
self.api_versionning + str(pk) + '/',
data,
format='json'
)
self.assertEqual(response.status_code, 200)
return response
def _test_retreive_instance(self, data):
matching = self.testing_model.objects.filter(
bbb=data['bbb']
)
self.assertTrue(matching.exists())
return matching[0]
####
def test_versionning(self):
"""
Test to check that versionning is working
We also check that new_revision_saved is called
"""
def _test_signal_sent(sender, obj, **kwargs):
self.signal_was_called = True
new_revision_saved.connect(_test_signal_sent)
data_1 = {'bbb': "Test 1"}
response = self.authenticated_client.post(
self.api_versionning,
data_1,
format='json'
)
self.assertEqual(response.status_code, 201)
instance = self._test_retreive_instance(data_1)
versions = Version.objects.get_for_object(instance)
self.assertEqual(len(versions), 1)
self.assertTrue(self.signal_was_called)
self.reset_signal_called()
data_2 = {'bbb': "Test 2"}
response = self.authenticated_client_2.put(
self.api_versionning + str(instance.pk) + '/',
data_2,
format='json'
)
self.assertEqual(response.status_code, 200)
versions = Version.objects.get_for_object(instance)
self.assertEqual(len(versions), 2)
self.assertTrue(self.signal_was_called)
......@@ -6,55 +6,69 @@ from django.test import TestCase
class WithUserTestCase(TestCase):
def setUp(self):
@classmethod
def setUpTestData(cls):
password = '123456'
self.staff_user = User.objects.create_user(
cls.staff_user = User.objects.create_user(
username='staff_member',
email='master@master.fr',
password=password
)
self.staff_user.is_staff = True
self.staff_user.save()
cls.staff_user.is_staff = True
cls.staff_user.save()
self.moderator_user = User.objects.create_user(
cls.moderator_user = User.objects.create_user(
username='moderator_member',
email='moderator@moderator.fr',
password=password
)
self.moderator_group = Group.objects.get_or_create(
cls.moderator_group = Group.objects.get_or_create(
name='Moderators'
)[0]
self.moderator_group.user_set.add(self.moderator_user)
self.moderator_group.save()
cls.moderator_group.user_set.add(cls.moderator_user)
cls.moderator_group.save()
self.authenticated_user = User.objects.create_user(
cls.authenticated_user = User.objects.create_user(
username='authenticated_user',
email='authenticated@authenticated.fr',
password=password
)
self.staff_client = APIClient()
self.staff_client.login(
username=self.staff_user.username,
cls.authenticated_user_2 = User.objects.create_user(
username='authenticated_user_2',
email='authenticated_2@authenticated.fr',
password=password
)
self.moderator_client = APIClient()
self.moderator_client.login(
username=self.moderator_user.username,
cls.staff_client = APIClient()
cls.staff_client.login(
username=cls.staff_user.username,
password=password
)
self.authenticated_client = APIClient()
self.authenticated_client.login(
username=self.authenticated_user.username,
cls.moderator_client = APIClient()
cls.moderator_client.login(
username=cls.moderator_user.username,
password=password
)
self.unauthenticated_client = APIClient()
cls.authenticated_client = APIClient()
cls.authenticated_client.login(
username=cls.authenticated_user.username,
password=password
)
cls.authenticated_client_2 = APIClient()
cls.authenticated_client_2.login(
username=cls.authenticated_user_2.username,
password=password
)
cls.unauthenticated_client = APIClient()
self.moreSetUp()
cls.setUpMoreTestData()
def moreSetUp(self):
@classmethod
def setUpMoreTestData(cls):
pass
......@@ -52,7 +52,7 @@ from backend.models.user import PreviousDepartureViewSet
from backend.models.user import PreviousDepartureFeedbackViewSet
from backend.models.user import UserDataViewSet
from backend.models.moderation import PendingModerationViewSet
from backend.models.my_model import PendingModerationViewSet
from rest_framework.documentation import include_docs_urls
......@@ -66,8 +66,10 @@ urlpatterns = [
router = routers.DefaultRouter()
if settings.TESTING:
from backend.models.moderation import ForTestingModerationViewSet
from backend.models.my_model import ForTestingModerationViewSet
from backend.models.my_model import ForTestingVersionningViewSet
router.register(r'test/moderation', ForTestingModerationViewSet)
router.register(r'test/versionning', ForTestingVersionningViewSet)
router.register(r'country', CountryViewSet)
router.register(r'city', CityViewSet)
......
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