@alex-shef

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

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
  • Вопрос задан
  • 99 просмотров
Решения вопроса 1
deepblack
@deepblack
Документация

After each test, Django calls flush to reset the database state. This empties all tables and emits the post_migrate signal, which recreates one content type and four permissions for each model. This operation gets expensive proportionally to the number of models.


Setting reset_sequences = True on a TransactionTestCase will make sure sequences are always reset before the test run


class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
    reset_sequences = True

    def test_animal_pk(self):
        lion = Animal.objects.create(name="lion", sound="roar")
        # lion.pk is guaranteed to always be 1
        self.assertEqual(lion.pk, 1)


UPD:
Инфа выше для понимания происходящего, но видимо не до всех доходит.
Вот еще пример со stackoverflow, но вобще есть несколько различных вариантов решения.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы