@@ -12,7 +12,32 @@ def setUpTestData(cls):
1212 )
1313 cls .user = User .objects .create (username = "test-user" )
1414
15- def test_conditional_required_fields_raises_exception (self ):
15+ def test_conditional_required_field_raises_exception_when_missing (self ):
16+ from demo .models import TestModel
17+
18+ TestModel .CONDITIONAL_REQUIRED_FIELDS = [
19+ (
20+ lambda instance : instance .user .is_active ,
21+ ["percentage" ],
22+ ),
23+ ]
24+
25+ with self .assertRaises (ValueError ):
26+ TestModel .objects .create (user = self .user )
27+
28+ def test_conditional_required_field_is_valid (self ):
29+ from demo .models import TestModel
30+
31+ TestModel .CONDITIONAL_REQUIRED_FIELDS = [
32+ (
33+ lambda instance : instance .user .is_active ,
34+ ["percentage" ],
35+ ),
36+ ]
37+
38+ TestModel .objects .create (user = self .user , percentage = 25 )
39+
40+ def test_conditional_required_toggle_field_raises_exception_when_missing (self ):
1641 from demo .models import TestModel
1742
1843 TestModel .CONDITIONAL_REQUIRED_TOGGLE_FIELDS = [
@@ -24,8 +49,21 @@ def test_conditional_required_fields_raises_exception(self):
2449
2550 with self .assertRaises (ValueError ):
2651 TestModel .objects .create (user = self .user )
52+
53+ def test_conditional_required_toggle_field_raises_exception_when_multiple_provided (self ):
54+ from demo .models import TestModel
55+
56+ TestModel .CONDITIONAL_REQUIRED_TOGGLE_FIELDS = [
57+ (
58+ lambda instance : instance .user .is_active ,
59+ ["fixed_price" , "percentage" , "amount" ],
60+ ),
61+ ]
62+
63+ with self .assertRaises (ValueError ):
64+ TestModel .objects .create (user = self .user , percentage = 25 , fixed_price = 10 )
2765
28- def test_conditional_required_fields_is_valid (self ):
66+ def test_conditional_required_toggle_field_is_valid (self ):
2967 from demo .models import TestModel
3068
3169 TestModel .CONDITIONAL_REQUIRED_TOGGLE_FIELDS = [
@@ -53,6 +91,14 @@ def test_providing_a_required_field_saves_the_instance(self):
5391 obj = TestModel .objects .create (user = self .user , percentage = 25 )
5492
5593 self .assertEqual (obj .percentage , 25 )
94+
95+ def test_providing_more_than_one_required_field_raises_an_error (self ):
96+ from demo .models import TestModel
97+
98+ TestModel .REQUIRED_FIELDS = ["percentage" , "fixed_price" ]
99+
100+ with self .assertRaises (ValueError ):
101+ TestModel .objects .create (user = self .user , percentage = 25 , fixed_price = 10 )
56102
57103 def test_optional_required_fields_is_valid (self ):
58104 from demo .models import TestModel
0 commit comments