Untitled

mail@pastecode.io avatar
unknown
python
3 years ago
2.8 kB
11
Indexable
Never
import shutil
import tempfile

from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, Client
from django.urls import reverse

from posts.models import Group, Post
from yatube import settings

User = get_user_model()


class PostCreateFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='testUser')
        cls.group = Group.objects.create(
            title='Тестовая группа',
            slug='test-slug',
            description='Тестовое описание группы'
        )
        cls.small_gif = (
            b'\x47\x49\x46\x38\x39\x61\x02\x00'
            b'\x01\x00\x80\x00\x00\x00\x00\x00'
            b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
            b'\x00\x00\x00\x2C\x00\x00\x00\x00'
            b'\x02\x00\x01\x00\x00\x02\x02\x0C'
            b'\x0A\x00\x3B'
        )
        cls.post = Post.objects.create(
            text='тестовый текст тестовой записи',
            author=cls.user,
            group=cls.group,
        )
        cls.image = SimpleUploadedFile(
            name='test_image.gif',
            content=cls.small_gif,
            content_type='image/gif'
        )
        settings.MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)
        print(settings.MEDIA_ROOT)

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True)
        super().tearDownClass()

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)
        self.new_text = 'M-test'
        self.edit_text = 'измененный тестовый текст'

    def test_create_post(self):
        posts_count = Post.objects.count()
        form_fields = {
            'group': self.group.pk,
            'text': self.new_text,
            'image': self.image
        }

        self.authorized_client.post(reverse('new_post'), form_fields)
        self.assertNotEqual(Post.objects.count(), posts_count)

    def test_edit_post(self):
        form_fields = {
            'group': self.group.pk,
            'text': self.edit_text,
            'image': self.image
        }

        self.authorized_client.post(
            reverse(
                'post_edit',
                kwargs={'username': self.user.username, 'post_id': 1}
            ),
            form_fields
        )
        edited_post = Post.objects.filter(
            text=self.edit_text,
            image=self.image
        ).exists()
        print(edited_post)
        self.assertTrue(edited_post)