Почему Unit тесты Django работают по отдельности, но падают вместе в одном файле?

Рейтинг: 0Ответов: 1Опубликовано: 15.07.2023
class PostModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        user = User.objects.create_user(username='testuser', password='testpassword')
        Post.objects.create(title='Test Post', slug='test-post', author=user, body='This is a test post',
                            publish=timezone.now(), status='published')

    def test_title_max_length(self):
        post = Post.objects.get(id=1)
        max_length = post._meta.get_field('title').max_length
        self.assertEqual(max_length, 250)

class CommentModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        user = User.objects.create_user(username='testuser', password='testpassword')
        post = Post.objects.create(title='Test Post', slug='test-post', author=user, body='This is a test post',
                                   publish=timezone.now(), status='published')
        Comment.objects.create(
            post=post,
            name='John Doe',
            email='johndoe@example.com',
            body='Test comment',
            created=timezone.now(),
            updated=timezone.now(),
            active=True
        )

    def test_comment_str_representation(self):
        comment = Comment.objects.get(id=1)
        expected_str = 'Comment by John Doe on Test Post'
        self.assertEqual(str(comment), expected_str)

Ошибка:

    raise self.model.DoesNotExist(
blog.models.Post.DoesNotExist: Post matching query does not exist.

Выполняю в Docker.

Ответы

▲ 0Принят

решение

class TestCategoryModel(TestCase):
@classmethod
def setUpTestData(cls):
    cls.obj_id = Category.objects.create(name="first_category").pk

def test_category_str_method(self):
    category = Category.objects.get(id=self.obj_id)
    self.assertTrue(isinstance(category, Category)) 
    self.assertEqual(category.__str__(), category.name) 

def test_category_get_absolute_url(self):
    category = Category.objects.get(id=self.obj_id)
    first_category_url = f"/blog/hashtag/{category.name}" 
    self.assertEqual(first_category_url, category.get_absolute_url())