lundi 5 octobre 2020

How to assert a IntegrityError properly in django?

folks. I'm trying to create a unit test to pass when an IntegrityError is raised.

I tried to do this but it tells me that IntegrityError is not iterable:

    def test_create_company_with_duplicate_cnpj(self):
        with self.assertRaises(IntegrityError) as context:
            Company.objects.create(name=self.company.name, cnpj=self.company.cnpj)

        self.assertTrue('UNIQUE constraint failed' in context.exception)

I did the "workaround" below and it passed. But is it correct or is there a different solution without using pytest?

    def test_create_company_with_duplicate_cnpj(self):
        with self.assertRaises(IntegrityError):
            Company.objects.create(name=self.company.name, cnpj=self.company.cnpj)

Aucun commentaire:

Enregistrer un commentaire