[Answered ]-Problems with django testing?

1👍

The most likely scenario is that the view raised an error, for example because the product did not exist, and that the middleware turned this into a HTML page.

It is a common misconception that the primary keys are fixed. They are not. You should store these in the testcase, so:

class TestBasketView(TestCase):
    def setUp(self):
        category = Category.objects.create(name='django', slug='django')
        user = User.objects.create(username='admin')
        self.product1 = Product.objects.create(
            title='django beginners',
            category=category,
            created_by=user,
            slug='django-beginners',
            price='20.00',
            image='django',
        )
        self.product2 = Product.objects.create(
            title='django intermediate',
            category=category,
            created_by=user,
            slug='django-beginners',
            price='20.00',
            image='django',
        )
        self.product3 = Product.objects.create(
            title='django advanced',
            category=category,
            created_by=user,
            slug='django-beginners',
            price='20.00',
            image='django',
        )
        self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product1.pk, 'productqty': 1, 'action': 'post'},
            xhr=True,
        )
        self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product1.pk, 'productqty': 2, 'action': 'post'},
            xhr=True,
        )

    def test_basket_add(self):
        """
        Test adding items to the basket
        """
        response = self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product3.pk, 'productqty': 1, 'action': 'post'},
            xhr=True,
        )
        self.assertEqual(response.json(), {'qty': 4})
        response = self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product2.pk, 'productqty': 1, 'action': 'post'},
            xhr=True,
        )
        self.assertEqual(response.json(), {'qty': 3})

Note: Normally one is not supposed to call magic attributes like __len__, normally this should only be done in certain circumstances, for example when working with a super call.

Leave a comment