0

UPDATE: I imported unittest.case instead of django.test that's why it works different, so this is solved

I am currently following a django tutorial (https://youtu.be/UqSJCVePEWU?t=8655) and he uses the setUp function to make test cases. I did the same thing as him and I get an error that the username is not UNIQUE

        self.c = Client()
        User.objects.create(username='admin')
        Category.objects.create(name='django', slug='django')
        self.data1 = Product.objects.create(category_id=1, title='django beginners', created_by_id=1,
                               slug='django-beginners', price='19.99', image='django')
        
 
    def test_url_allowed_hosts(self):
        response = self.c.get('/')
        self.assertEqual(response.status_code, 200)
    

    def test_product_detail_url(self):
        response = self.c.get(reverse('store:product_detail', args=['django-beginners']))
        self.assertEqual(response.status_code, 200)

so, after some hours I found that setUp is executed for every test (which does not create any problem in the tutorial) and I changed my function to

@classmethod
    def setUpClass(self):

which solves the problem, but now I don't know if I messed something up and the tutorial should work, or something in django has changed since then or if there is another easier way to make this also. Any help is appreciated and if any files or something is needed I'll provide them. Thank you in advance

1 Answers1

0

You're not getting any errors after overriding setUpClass because setUpClass only runs once per test suite. See more info here about the difference between setUp and setUpClass: https://stackoverflow.com/a/23670844/6243764

If you want dynamic data per test method, you can use fixtures replacement utilities such as FactoryBoy (https://factoryboy.readthedocs.io/en/stable/)

Brandon
  • 46
  • 7