Skip to content

Commit c061402

Browse files
Merge pull request #113 from unicef/feature/247635-userrole-check-program-matches-office
AB#247635: Check program matches office for UserRole
2 parents 21a8782 + 4f5914e commit c061402

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/country_workspace/models/role.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
from django.contrib.auth.models import Group
2+
from django.core.exceptions import ValidationError
23
from django.db import models
4+
from django.utils.translation import gettext as _
35

46
from .base import BaseModel
57
from .office import Office
68
from .program import Program
79
from .user import User
810

911

12+
PROGRAM_DOES_NOT_BELONG_TO_OFFICE = "Program does not belong to country office"
13+
14+
1015
class 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)})

tests/models/test_role.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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]

0 commit comments

Comments
 (0)