File: test_widget.py

package info (click to toggle)
python-django-pint 0.7.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 432 kB
  • sloc: python: 1,531; makefile: 28; sh: 12
file content (310 lines) | stat: -rw-r--r-- 10,022 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# flake8: noqa: F841
import pytest

from django import forms
from django.test import TestCase

from decimal import Decimal
from pint import DimensionalityError, UndefinedUnitError

from quantityfield.fields import IntegerQuantityFormField, QuantityFormField
from quantityfield.units import ureg
from quantityfield.widgets import QuantityWidget
from tests.dummyapp.models import (
    ChoicesDefinedInModel,
    ChoicesDefinedInModelInt,
    HayBale,
)

Quantity = ureg.Quantity


class HayBaleForm(forms.ModelForm):
    weight = QuantityFormField(base_units="gram", unit_choices=["ounce", "gram"])
    weight_int = IntegerQuantityFormField(
        base_units="gram", unit_choices=["ounce", "gram", "kilogram"]
    )

    class Meta:
        model = HayBale
        exclude = ["weight_bigint"]


class HayBaleFormDefaultWidgets(forms.ModelForm):
    weight = QuantityFormField(
        base_units="gram", unit_choices=["ounce", "gram"], widget=forms.NumberInput
    )
    weight_int = IntegerQuantityFormField(
        base_units="gram", unit_choices=["ounce", "gram"], widget=forms.NumberInput
    )

    class Meta:
        model = HayBale
        exclude = ["weight_bigint"]


class UnitChoicesDefinedInModelFieldModelForm(forms.ModelForm):
    class Meta:
        model = ChoicesDefinedInModel
        fields = ["weight"]


class UnitChoicesDefinedInModelFieldModelFormInt(forms.ModelForm):
    class Meta:
        model = ChoicesDefinedInModelInt
        fields = ["weight"]


class NullableWeightForm(forms.Form):
    weight = QuantityFormField(base_units="gram", required=False)


class UnitChoicesForm(forms.Form):
    distance = QuantityFormField(
        base_units="kilometer", unit_choices=["mile", "kilometer", "yard", "feet"]
    )


class TestWidgets(TestCase):
    def test_creates_correct_widget_for_modelform(self):
        form = HayBaleForm()
        self.assertIsInstance(form.fields["weight"], QuantityFormField)
        self.assertIsInstance(form.fields["weight"].widget, QuantityWidget)

    def test_displays_initial_data_correctly(self):
        form = HayBaleForm(
            initial={"weight": Quantity(100 * ureg.gram), "name": "test"}
        )

    def test_clean_yields_quantity(self):
        form = HayBaleForm(
            data={
                "weight_0": 100.0,
                "weight_1": "gram",
                "weight_int_0": 100,
                "weight_int_1": "gram",
                "name": "test",
            }
        )
        self.assertTrue(form.is_valid())
        self.assertIsInstance(form.cleaned_data["weight"], Quantity)

    def test_clean_yields_quantity_in_correct_units(self):
        form = HayBaleForm(
            data={
                "weight_0": 1.0,
                "weight_1": "ounce",
                "weight_int_0": 1,
                "weight_int_1": "kilogram",
                "name": "test",
            }
        )
        self.assertTrue(form.is_valid())
        self.assertEqual(str(form.cleaned_data["weight"].units), "gram")
        self.assertAlmostEqual(form.cleaned_data["weight"].magnitude, 28.349523125)
        self.assertEqual(str(form.cleaned_data["weight_int"].units), "gram")
        self.assertAlmostEqual(form.cleaned_data["weight_int"].magnitude, 1000)

    def test_precision_lost(self):
        def test_clean_yields_quantity_in_correct_units(self):
            form = HayBaleForm(
                data={
                    "weight_0": 1.0,
                    "weight_1": "ounce",
                    "weight_int_0": 1,
                    "weight_int_1": "onuce",
                    "name": "test",
                }
            )
            self.assertFalse(form.is_valid())

    def test_base_units_is_required_for_form_field(self):
        with self.assertRaises(ValueError):
            field = QuantityFormField()  # noqa: F841

    def test_quantityfield_can_be_null(self):
        form = NullableWeightForm(data={"weight_0": None, "weight_1": None})
        self.assertTrue(form.is_valid())

    def test_validate_units(self):
        form = UnitChoicesForm(data={"distance_0": 100, "distance_1": "ounce"})
        self.assertFalse(form.is_valid())

    def test_base_units_is_included_by_default(self):
        field = QuantityFormField(base_units="mile", unit_choices=["meters", "feet"])
        self.assertIn("mile", field.units)

    def test_widget_field_displays_unit_choices(self):
        form = UnitChoicesForm()
        self.assertListEqual(
            [
                ("mile", "mile"),
                ("kilometer", "kilometer"),
                ("yard", "yard"),
                ("feet", "feet"),
            ],
            form.fields["distance"].widget.widgets[1].choices,
        )

    def test_widget_field_displays_unit_choices_for_model_field_propagation(self):
        form = UnitChoicesDefinedInModelFieldModelForm()
        self.assertListEqual(
            [
                ("kilogram", "kilogram"),
                ("milligram", "milligram"),
                ("pounds", "pounds"),
            ],
            form.fields["weight"].widget.widgets[1].choices,
        )

    def test_widget_int_field_displays_unit_choices_for_model_field_propagation(self):
        form = UnitChoicesDefinedInModelFieldModelFormInt()
        self.assertListEqual(
            [
                ("kilogram", "kilogram"),
                ("milligram", "milligram"),
                ("pounds", "pounds"),
            ],
            form.fields["weight"].widget.widgets[1].choices,
        )

    def test_unit_choices_must_be_valid_units(self):
        with self.assertRaises(UndefinedUnitError):
            field = QuantityFormField(
                base_units="mile", unit_choices=["gunzu"]
            )  # noqa: F841

    def test_unit_choices_must_match_base_dimensionality(self):
        with self.assertRaises(DimensionalityError):
            field = QuantityFormField(
                base_units="gram", unit_choices=["meter", "ounces"]
            )  # noqa: F841

    def test_widget_invalid_float(self):
        form = HayBaleForm(
            data={
                "name": "testing",
                "weight_0": "a",
                "weight_1": "gram",
                "weight_int_0": "10",
                "weight_int_1": "gram",
            }
        )
        self.assertFalse(form.is_valid())
        self.assertIn("weight", form.errors)

    def test_widget_missing_required_input(self):
        form = HayBaleForm(
            data={
                "name": "testing",
                "weight_int_0": "10",
                "weight_int_1": "gram",
            }
        )
        self.assertFalse(form.is_valid())
        self.assertIn("weight", form.errors)

    def test_widget_empty_value_for_required_input(self):
        form = HayBaleForm(
            data={
                "name": "testing",
                "weight_0": "",
                "weight_1": "gram",
                "weight_int_0": "10",
                "weight_int_1": "gram",
            }
        )
        self.assertFalse(form.is_valid())
        self.assertIn("weight", form.errors)

    def test_widget_none_value_set_for_required_input(self):
        form = HayBaleForm(
            data={
                "name": "testing",
                "weight_0": None,
                "weight_1": "gram",
                "weight_int_0": "10",
                "weight_int_1": "gram",
            }
        )
        self.assertFalse(form.is_valid())
        self.assertIn("weight", form.errors)

    def test_widget_int_precision_loss(self):
        form = HayBaleFormDefaultWidgets(
            data={
                "name": "testing",
                "weight": "10",
                "weight_int": "10.3",
            }
        )
        self.assertFalse(form.is_valid())
        self.assertTrue(form.has_error("weight_int"))


class TestWidgetRenderingBase(TestCase):
    value = 20
    expected_created = "20"
    expected_db = "20.0"

    def get_html(self, value_from_db: bool) -> str:
        """Create the rendered form with the widget"""
        bale = HayBale.objects.create(name="Fritz", weight=self.value)
        if value_from_db:
            # When creating an object django just takes the given value
            # and sets it
            # Once we receive it from the database the correct Quantity
            # is created
            bale = HayBale.objects.get(pk=bale.pk)
        form = HayBaleForm(instance=bale)
        return str(form)

    def test_widget_display(self):
        # Add to Integration tests
        html = self.get_html(False)
        expected = f'<input type="number" name="weight_0" value="{self.expected_created}" step="any" required id="id_weight_0">'
        self.assertIn(expected, html)
        self.assertIn('<option value="ounce">ounce</option>', html)

    def test_widget_display_db_value(self):
        html = self.get_html(True)
        expected = f'<input type="number" name="weight_0" value="{self.expected_db}" step="any" required id="id_weight_0">'
        self.assertIn(expected, html)
        self.assertIn('<option value="ounce">ounce</option>', html)


class TestWidgetRenderingNegativeNumber(TestWidgetRenderingBase):
    value = -20
    expected_created = "-20"
    expected_db = "-20.0"


class TestWidgetRenderingSmallNumber(TestWidgetRenderingBase):
    value = 1e-10
    expected_created = "1e-10"
    expected_db = "1e-10"


class TestWidgetRenderingZeroInt(TestWidgetRenderingBase):
    value = 0
    expected_created = "0"
    expected_db = "0.0"


class TestWidgetRenderingZeroFloat(TestWidgetRenderingBase):
    value = 0.0
    expected_created = "0.0"
    expected_db = "0.0"


class TestWidgetRenderingZeroDecimal(TestWidgetRenderingBase):
    value = Decimal(0.0)
    expected_created = "0"
    expected_db = "0.0"


class TestWidgetRenderingDecimalFromFloat(TestWidgetRenderingBase):
    # 1.0 is represenatble in base 2 and base 10, so should return 1 (not 1. + 1e-16 etc)
    value = Decimal(1.0)
    expected_created = "1"
    expected_db = "1.0"