Unit testing in Django - where to draw a line?

I went through a lot of Django testing tutorials, but I'm a little sure how much to test. I mostly use classic views

For example, when testing my views, you should check all of the following:

  • That each URL mapping is correct
  • All views use the expected template.
  • All submissions use the expected form (if applicable)
  • Each view has expected context variables.
  • All messages are redirected somewhere

Most of my views relate to classes. I have a ListView where I set the file_name, model and context_object_name. Should I test that they are installed correctly? There is no logic there, so it seems like it's a little silly to test as it is just a configuration.

When testing models :

  • Do I have to verify that a validation error occurs when a field is marked as unique, and I'm trying to add another record with the same value for the field?
  • If I add a MinValueValidator to the field, should I check this?
  • I suppose that regex validators should be checked as there is logic.

When testing forms (especially models)

  • Do I have to check every form field for which an error is generated for invalid input?
  • ?
  • , ?
  • , , , help_text, place_holder ..

, , . , , , 10 , .

, - , , . , , . , ?

+4
1

. , . , , . , , , , . , :

class CreationTestCase(TestCase):
    def test_creation_page_get(self):
        url = reverse('your_model_create')
        response = self.client.get(url)

        # Your page gave 200, so there are no severe configuration errors
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'your/template.html')
        # The template context contains your form, so most probably you view did fine.
        self.assertEqual(type(response.context['form']), YourForm)

    def test_creation_page_post(self):      
        payload = {'field1': 1, 'field2': 2}
        response = self.client.post(reverse('your_model_create'), payload)

        # Your page redirected to a success url, so the view did ok.
        self.assertRedirects(response, reverse('your-success-url'))
        # The instance is actually created and contains the right data
        instance = YourModel.objects.first()
        self.assertEqual(instance.field1, payload['field1'])

urlconf, , , . , , .

- . , .

, , , , .

, , .

+2

Source: https://habr.com/ru/post/1627034/


All Articles