I'm just learning the approaches for testing in Django using the built-in testing tools, particularly the django.test.TestCase
. I'm wondering if it is best-practice to use assertion methods during the initial setUp
of a new test class?
For example, I have the following models:
class TestProduct(BaseModel):
name = models.CharField(...)
class TestPrimaryImage(BaseModel):
url = models.TextField(...)
product = models.ForeignKey('TestProduct', ...)
It's a product that will have a primary image specified by a ForeignKey
relationship with a TestPrimaryImage
class entry.
Following the examples here: https://docs.djangoproject.com/en/2.1/topics/testing/overview/ I am creating a testing class as such:
class NewProductTestCase(TestCase):
def setUp(self):
models.TestProduct.objects.create(
name='TestProductName'
)
def TestMainImage(self):
models.TestPrimaryImage.objects.create(
url="https://example.com/test-image-url.jpg",
product=?
)
The part that I'm not sure of centers about the TestMainImage
method which requires a TestProduct
class to reference. Is it appropriate to do the following during setUp
:
def setUp(self):
self.test_product = models.TestProduct.objects.create(
name='TestProductName'
)
self.assertIsInstance(self.test_product, models.TestProduct)
Assigning the newly created object to a class variable and asserting its creation? The assertion would imply that if the new product isn't successfully created none of the other testing methods would be able to run at all. For example, TestMainImage
would have no product to create a reference to during creation.
This seems like a sensible approach to me but I'm new to Django and not to be confused for a veteran of testing in general.
always keep this this in mind: never write tests for django internals
django is already well tested and if you think there is a need to test something send them a pull requst
so for your sample, as we know models.TestProduct.objects.create()
always returns an instance or throws an execption. so you don't need to test anything