|
| 1 | +from django.test import TestCase |
| 2 | + |
| 3 | +from ....models.participant import Participant |
| 4 | +from ....forms.imperial_weight_form import ImperialWeightForm |
| 5 | + |
| 6 | +class TestImperialWeightForm(TestCase): |
| 7 | + def setUp(self): |
| 8 | + self.participant = Participant.objects.create(unique_id="1234567890") |
| 9 | + self.response_set = self.participant.responseset_set.create( |
| 10 | + weight_metric=1704 |
| 11 | + ) |
| 12 | + |
| 13 | + def test_is_valid_with_valid_input(self): |
| 14 | + form = ImperialWeightForm( |
| 15 | + participant=self.participant, |
| 16 | + instance=self.response_set, |
| 17 | + data={ |
| 18 | + "weight_imperial_0": "5", # stone |
| 19 | + "weight_imperial_1": "9" # pounds |
| 20 | + } |
| 21 | + ) |
| 22 | + |
| 23 | + self.assertTrue(form.is_valid()) |
| 24 | + |
| 25 | + def test_converts_stone_and_pounds_to_kilograms_integer(self): |
| 26 | + form = ImperialWeightForm( |
| 27 | + participant=self.participant, |
| 28 | + instance=self.response_set, |
| 29 | + data={ |
| 30 | + "weight_imperial_0": "5", # stone |
| 31 | + "weight_imperial_1": "9" # pounds |
| 32 | + } |
| 33 | + ) |
| 34 | + |
| 35 | + self.assertTrue(form.is_valid(), f"Form errors: {form.errors}") |
| 36 | + self.assertEqual(form.cleaned_data['weight_imperial'], 79) |
| 37 | + |
| 38 | + def test_setting_weight_imperial_clears_weight_metric(self): |
| 39 | + form = ImperialWeightForm( |
| 40 | + instance=self.response_set, |
| 41 | + participant=self.participant, |
| 42 | + data={ |
| 43 | + "weight_imperial_0": "5", # stone |
| 44 | + "weight_imperial_1": "9" # pounds |
| 45 | + } |
| 46 | + ) |
| 47 | + form.save() |
| 48 | + self.assertEqual(self.response_set.weight_metric, None) |
| 49 | + |
| 50 | + def test_is_invalid_with_missing_data(self): |
| 51 | + form = ImperialWeightForm( |
| 52 | + participant=self.participant, |
| 53 | + instance=self.response_set, |
| 54 | + data={ |
| 55 | + "weight_imperial_0": "5", |
| 56 | + # missing pounds |
| 57 | + } |
| 58 | + ) |
| 59 | + self.assertFalse(form.is_valid()) |
| 60 | + self.assertEqual( |
| 61 | + form.errors["weight_imperial"], |
| 62 | + ["Enter your weight."] |
| 63 | + ) |
| 64 | + |
| 65 | + def test_is_invalid_when_given_a_decimal_stone_value(self): |
| 66 | + form = ImperialWeightForm( |
| 67 | + participant=self.participant, |
| 68 | + instance=self.response_set, |
| 69 | + data={ |
| 70 | + "weight_imperial_0": "5.2", |
| 71 | + "weight_imperial_1": "0" |
| 72 | + } |
| 73 | + ) |
| 74 | + self.assertFalse(form.is_valid()) |
| 75 | + self.assertEqual( |
| 76 | + form.errors["weight_imperial"], |
| 77 | + ["Stone must be in whole numbers."] |
| 78 | + ) |
0 commit comments