Completed
Push — master ( 9919f2...95d957 )
by Diederik van der
01:22
created

FormTests.test_form_save_clean()   A

Complexity

Conditions 2

Size

Total Lines 21

Duplication

Lines 19
Ratio 90.48 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 19
loc 21
rs 9.3142
cc 2
1
import django
2
from django.core.exceptions import ValidationError
3
from django.utils import translation
4
from parler.forms import TranslatableModelForm
5
from .utils import AppTestCase
6
from .testapp.models import SimpleModel, UniqueTogetherModel, ForeignKeyTranslationModel, RegularModel, CleanFieldModel
7
8
9
class SimpleForm(TranslatableModelForm):
10
11
    class Meta:
12
        model = SimpleModel
13
        if django.VERSION >= (1, 6):
14
            fields = '__all__'
15
16
17
class CleanFieldForm(TranslatableModelForm):
18
19
    class Meta:
20
        model = CleanFieldModel
21
        if django.VERSION >= (1, 6):
22
            fields = '__all__'
23
24
25
class UniqueTogetherForm(TranslatableModelForm):
26
27
    class Meta:
28
        model = UniqueTogetherModel
29
        if django.VERSION >= (1, 6):
30
            fields = '__all__'
31
32
33
class ForeignKeyTranslationModelForm(TranslatableModelForm):
34
35
    class Meta:
36
        model = ForeignKeyTranslationModel
37
        if django.VERSION >= (1, 6):
38
            fields = '__all__'
39
40
41
class FormTests(AppTestCase):
42
    """
43
    Test model construction
44
    """
45
46
    def test_form_fields(self):
47
        """
48
        Check if the form fields exist.
49
        """
50
        self.assertTrue('shared' in SimpleForm.base_fields)
51 View Code Duplication
        self.assertTrue('tr_title' in SimpleForm.base_fields)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
52
53
    def test_form_save(self):
54
        """
55
        Check if the form receives and stores data.
56
        """
57
        with translation.override('fr'):
58
            # Initialize form in other language.
59
            x = SimpleForm(data={'shared': 'SHARED', 'tr_title': 'TRANS'})
60
            x.language_code = 'nl'
61
            self.assertFalse(x.errors)
62
63
            # Data should come out
64
            self.assertEqual(x.cleaned_data['shared'], 'SHARED')
65
            self.assertEqual(x.cleaned_data['tr_title'], 'TRANS')
66
67
            # Data should be saved
68
            instance = x.save()
69
            self.assertEqual(instance.get_current_language(), 'nl')
70
71
            x = SimpleModel.objects.language('nl').get(pk=instance.pk)
72
            self.assertEqual(x.shared, 'SHARED')
73 View Code Duplication
            self.assertEqual(x.tr_title, 'TRANS')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
74
75
    def test_form_save_clean(self):
76
        """
77
        Check if the form receives and stores data.
78
        """
79
        with translation.override('fr'):
80
            # Initialize form in other language.
81
            x = CleanFieldForm(data={'shared': 'TRANS', 'tr_title': 'TEST'})
82
            x.language_code = 'nl'
83
            self.assertFalse(x.errors)
84
85
            # Data should come out
86
            self.assertEqual(x.cleaned_data['shared'], 'TRANS')
87
            self.assertEqual(x.cleaned_data['tr_title'], 'TEST')
88
89
            # Data should be saved
90
            instance = x.save()
91
            self.assertEqual(instance.get_current_language(), 'nl')
92
93
            x = CleanFieldModel.objects.language('nl').get(pk=instance.pk)
94
            self.assertEqual(x.shared, 'TRANS_cleanchar_cleanshared')
95
            self.assertEqual(x.tr_title, 'TEST_cleanchar_cleantrans')
96
97
    def test_form_save_clean_exclude(self):
98
        """
99
        Check that non-form fields are properly excluded.
100
        """
101
        class CleanPartialFieldForm(TranslatableModelForm):
102
            class Meta:
103
                model = CleanFieldModel
104
                fields = ('shared',)
105
                exclude = ('tr_title',)
106
107
        self.assertEqual(list(CleanPartialFieldForm.base_fields.keys()), ['shared'])
108
109
        with translation.override('fr'):
110
            x = CleanPartialFieldForm(data={'shared': 'TRANS'})
111
            x.language_code = 'nl'
112
            self.assertFalse(x.errors)
113
114
    def test_unique_together(self):
115
        UniqueTogetherModel(_current_language='en', slug='foo').save()
116
117
        # Different language code, no problem
118
        form = UniqueTogetherForm(data={'slug': 'foo'})
119
        form.language_code = 'fr'
120
        self.assertTrue(form.is_valid())
121
122
        # Same language code, should raise unique_together check
123
        form = UniqueTogetherForm(data={'slug': 'foo'})
124
        form.language_code = 'en'
125
        self.assertFalse(form.is_valid())
126
        self.assertRaises(ValidationError, lambda: form.instance.validate_unique())
127
128
    def test_not_null_foreignkey_in_translation(self):
129
        """
130
        Simulate scenario for model with translation field of type foreign key (not null).
131
          1. User create model with one translation (EN)
132
          2. Switch to another language in admin (FR)
133
        """
134
135
        # create object with translation
136
        r1 = RegularModel.objects.create(original_field='r1')
137
        a = ForeignKeyTranslationModel.objects.create(translated_foreign=r1, shared='EN')
138
139
        # same way as TranslatableAdmin.get_object() inicializing translation, when user swich to new translation language
140
        a.set_current_language('fr', initialize=True)
141
142
        # inicialize form
143
        form = ForeignKeyTranslationModelForm(instance=a)
144
145
        self.assertTrue(True)
146