E
E
EgorLee2021-11-13 08:50:40
Python
EgorLee, 2021-11-13 08:50:40

How to test models where in the overridden .save() save is used 2 times?

I have a category model, to identify it in the telegram bot, I use the pk_for_telegram field, where the line containing the category id is written. Accordingly, id appears only after saving the instance, my solution is this:

class Category(models.Model):
    '''Модель категорий'''
    name = models.CharField(max_length=255, help_text='Имя категории')
    photo = models.ImageField(upload_to='category_img/', help_text='Фото категории')
    slug = models.SlugField(max_length=100, unique=True)
    pk_for_telegram = models.CharField(max_length=255, unique=True, blank=True, null=True, help_text='Используется в боте для поиска категории')    # Нужен для идентификации в телеграм боте
    max_count_product = models.IntegerField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)
        self.pk_for_telegram = f'c||{self.pk}'
        super(Category, self).save(*args, **kwargs)

    def __str__(self):
        return self.name


In the application it works correctly. But I wanted to cover my code with tests, and I met with such an error, because the save () method is used 2 times, it tries to save the instance 2 times and throws an error

django.db.utils.IntegrityError: UNIQUE constraint failed: main_app_category.id


When commenting out one of the .save() everything goes well, how to resolve this issue?
Test model:
class ListProductViewTest(TestCase):

    def setUp(self) -> None:
        self.seller_user = User.objects.create(username='seller1', password='password')
        self.super_user = User.objects.create(username='admin1', password='password', is_staff=True)
        image = SimpleUploadedFile('image.jpg', content=b'', content_type='image/jpg')
        self.category = Category.objects.create(name='category', photo=image, max_count_product=10)
        self.subcategory = SubCategory.objects.create(name='subcategory', photo=image, category=self.category)
        self.product = Product.objects.create(title='product', photo=image, price=Decimal('100.00'), count=10, weight=100, description='descrpit',  subcategory=self.subcategory, )

    
    def test_seller_requared(self):
        factory = RequestFactory()
        request = factory.get('')
        request.user = self.seller_user
        response = IndexView.as_view()(request)
        self.assertEqual(response.status_code, 302)

    def test_admin_requared(self):
        factory = RequestFactory()
        request = factory.get('')
        request.user = self.super_user
        response = IndexView.as_view()(request)
        self.assertEqual(response.status_code, 200)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-13
@EgorLee

You don't clear the test base in setUp()? Those. By the time of the second test, do you still have data after the first one?
It is a bad idea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question