import pytest from django.test import TestCase from django.contrib.auth import get_user_model from commu.usecases.post_service import PostService from commu.entities.user import UserRole from core.repositories.django_post_repository import DjangoPostRepository from core.repositories.django_user_repository import DjangoUserRepository User = get_user_model() class PostServiceIntegrationTest(TestCase): def setUp(self): # Use Django's repositories self.user_repo = DjangoUserRepository() self.post_repo = DjangoPostRepository() self.service = PostService(self.post_repo, self.user_repo) # Create some users using Django ORM self.admin = User.objects.create_user(username="admin", is_superuser=True, is_staff=True) self.user = User.objects.create_user(username="user", is_staff=True) self.guest = User.objects.create_user(username="guest") # Not staff or superuser def test_create_post_by_user(self): post = self.service.create_post(str(self.user.id), "Hello Django!", ["img1.png"], ["vid1.mp4"]) assert post.text == "Hello Django!" assert post.images == ["img1.png"] assert post.videos == ["vid1.mp4"] def test_guest_cannot_create_post(self): with self.assertRaises(PermissionError): self.service.create_post(str(self.guest.id), "Forbidden") def test_search_posts(self): p1 = self.service.create_post(str(self.user.id), "First Django post") p2 = self.service.create_post(str(self.user.id), "Second hello world") results = self.service.search_posts("hello") assert len(results) == 1 assert results[0].text == "Second hello world" def test_rate_post(self): post = self.service.create_post(str(self.user.id), "Rate me Django!") self.service.rate_post(post.id, str(self.admin.id), 5) self.service.rate_post(post.id, str(self.user.id), 4) updated_post = self.post_repo.get(post.id) assert abs(updated_post.average_rating() - 4.5) < 1e-6 def test_guest_cannot_rate_post(self): post = self.service.create_post(str(self.user.id), "No guest rate") with self.assertRaises(PermissionError): self.service.rate_post(post.id, str(self.guest.id), 2) def test_rating_bounds(self): post = self.service.create_post(str(self.user.id), "Bounds Django") with self.assertRaises(ValueError): self.service.rate_post(post.id, str(self.admin.id), 0) with self.assertRaises(ValueError): self.service.rate_post(post.id, str(self.admin.id), 6)