File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
src/country_workspace/models Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 11from django .contrib .auth .models import Group
2+ from django .core .exceptions import ValidationError
23from django .db import models
4+ from django .utils .translation import gettext as _
35
46from .base import BaseModel
57from .office import Office
68from .program import Program
79from .user import User
810
911
12+ PROGRAM_DOES_NOT_BELONG_TO_OFFICE = "Program does not belong to country office"
13+
14+
1015class UserRole (BaseModel ):
1116 user = models .ForeignKey (User , on_delete = models .CASCADE , related_name = "roles" )
1217 country_office = models .ForeignKey (Office , on_delete = models .CASCADE )
@@ -21,3 +26,8 @@ class Meta:
2126 fields = ["user" , "country_office" , "group" ],
2227 ),
2328 )
29+
30+ def clean (self ) -> None :
31+ super ().clean ()
32+ if self .program and self .program .country_office != self .country_office :
33+ raise ValidationError ({"program" : _ (PROGRAM_DOES_NOT_BELONG_TO_OFFICE )})
Original file line number Diff line number Diff line change 1+ import pytest
2+ from django .core .exceptions import ValidationError
3+
4+ from country_workspace .models import Program , Office , UserRole
5+ from country_workspace .models .role import PROGRAM_DOES_NOT_BELONG_TO_OFFICE
6+ from testutils .factories import ProgramFactory , OfficeFactory
7+
8+
9+ @pytest .fixture
10+ def office () -> Office :
11+ return OfficeFactory ()
12+
13+
14+ @pytest .fixture
15+ def another_office () -> Office :
16+ return OfficeFactory ()
17+
18+
19+ @pytest .fixture
20+ def program (office : Office ) -> Program :
21+ return ProgramFactory (country_office = office )
22+
23+
24+ def test_clean_no_program (office : Office ) -> None :
25+ UserRole (country_office = office ).clean ()
26+
27+
28+ def test_clean_with_correct_office_and_program (office : Office , program : Program ) -> None :
29+ UserRole (country_office = office , program = program ).clean ()
30+
31+
32+ def test_clean_with_incorrect_office_and_program (another_office : Office , program : Program ) -> None :
33+ with pytest .raises (ValidationError ) as e :
34+ UserRole (country_office = another_office , program = program ).clean ()
35+
36+ assert e .value .messages == [PROGRAM_DOES_NOT_BELONG_TO_OFFICE ]
You can’t perform that action at this time.
0 commit comments