from django.test import TestCase from rest_framework.exceptions import ValidationError from apps.clients.models import Client from apps.clients.services.clients import create_client, update_client from apps.users.models import User from apps.workspaces.models import Workspace, WorkspaceMembership class ClientServiceTests(TestCase): @classmethod def setUpTestData(cls): cls.owner = User.objects.create_user(mobile="09120000001", password="secret123") cls.member = User.objects.create_user(mobile="09120000002", password="secret123") cls.outsider = User.objects.create_user(mobile="09120000003", password="secret123") cls.workspace = Workspace.objects.create(name="Clients", owner=cls.owner) WorkspaceMembership.objects.create( workspace=cls.workspace, user=cls.member, role=WorkspaceMembership.Role.MEMBER, is_active=True, ) def test_create_client_creates_record_for_workspace_member(self): client = create_client( self.member, self.workspace.id, "Acme", notes="Priority account", ) self.assertEqual(client.name, "Acme") self.assertEqual(client.notes, "Priority account") self.assertEqual(client.workspace, self.workspace) self.assertEqual(client.created_by, self.member) def test_create_client_rejects_non_member(self): with self.assertRaises(ValidationError) as exc: create_client(self.outsider, self.workspace.id, "Acme") self.assertIn("workspace", exc.exception.detail) def test_create_client_rejects_duplicate_name_in_workspace(self): Client.objects.create(workspace=self.workspace, name="Acme") with self.assertRaises(ValidationError) as exc: create_client(self.owner, self.workspace.id, "Acme") self.assertIn("name", exc.exception.detail) def test_update_client_updates_name_and_notes(self): client = Client.objects.create(workspace=self.workspace, name="Acme", notes="Old") updated = update_client(client, name="Globex", notes="New") self.assertEqual(updated.name, "Globex") self.assertEqual(updated.notes, "New") def test_update_client_rejects_duplicate_new_name(self): Client.objects.create(workspace=self.workspace, name="Globex") client = Client.objects.create(workspace=self.workspace, name="Acme") with self.assertRaises(ValidationError) as exc: update_client(client, name="Globex") self.assertIn("name", exc.exception.detail)