Testing UpdateView

I need some help testing a class based view

I have a view (UpdateView) that after saving any updates, checks if a field, ‘date_time’, is present in form.changed_data and if it’s not present then changes are made to another model.

This works perfectly in practice, but I am finding it difficult to test, because whenever I post data using;

response = self.client.post(reverse('web-edit'), data=update_data)

All of the fields are marked as having changed in form.changed_data including the ones that are the same.

View

class WebUpdateView(UpdateView):
    model = Web
    form_class = WebAddForm
    template_name = 'web/webinar-add-update.html'

    def form_valid(self, form):
        self.object = form.save()

        if not 'date_time' in form.changed_data:
            do something to another model

Test

class WebinarUpdateTest(TestCase):

    def setUp(self):
        self.now = datetime.now(tz=pytz.UTC)

        self.web = Web.objects.create(title='test title',
                                      description='Test description',
                                      date_time=self.now
                                      )

    def test_post_webinar_add_two(self):
        update_data = {'title': 'test title 2',
                       'description': 'Test description 2',
                       'date_time': self.now}

        response = self.client.post(reverse('web-edit'), data=update_data)

With the above code, all fields are marked as changed, when clearly the date_time field hasn’t. So my question is, how can I test the ‘if not ‘date_time’ in form.changed_data:’ statement in my view?

Not particularly familiar with this, but just as a guess / diagnostic item, what happens if you make that test before you save the object?

Hi ken,

Thank you for your time.

This is what I came up with, although it feels like a bit of a ‘hack’:

    def test_post_webinar_with_date_time(self):
        update_data = {'title': 'test title 2',
                       'description': 'Test description 2',
                       'date_time': self.now}

        form = WebAddForm(data=update_data, instance=self.web)
        form.is_valid()
        dt = form.changed_data.index('date_time')
        form.changed_data.pop(dt)
        view = WebUpdateView()
        view.object = self.web
        view.request = RequestFactory().post('/')
        view.form_valid(form)