1

I'm testing my project, and I need to test django form, but I don't know how to do it, here's the code

if request.method == 'POST': # If the form has been submitted...
    name_add = request.POST.get("name")
    form = AddForm(request.POST) # A form bound to the POST datas
    not_add = 0
    if form.is_valid(): # All validation rules pass
        for n in Product.objects.filter(dashboard = curr_dashboard):
            if n.name == name_add:
                not_add = 1
        if not_add != 1:
            obj = form.save(commit=False)
            obj.dashboard = curr_dashboard
            obj.save()
            curr_buylist.add_product(obj.id)
            return HttpResponseRedirect(request.get_full_path()) # Redirect after POST
        else:
            forms.ValidationError("You already have this")
            return HttpResponseRedirect(request.get_full_path())

I validate it here and add to database. But how do I test it ? Here is what I wrote in test

def test_index_form(self):
    request = self.factory.post('main/index')
    request.user = User.objects.get(username= 'admin')
    response = index(request)

    self.assertEqual(response.status_code, 200)

1 Answer 1

1

I think your test is a good start. Unfortunately, it just tests the case where a form is not valid. In addition to testing the status code, I would test that the correct template is being loaded as well, perhaps also test that the unbound form is in the context, (basically test that the correct conditional in your view is executed, as expected):

self.assertTemplateUsed(response, 'your_template.html')
self.assertIsInstance(response.context['form'], AddForm)

It would also be an idea to provide valid form data in your test and make sure a new object is created, as expected.

It might also be a good idea to post invalid data to your view and check that a redirect is issued, as expected

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.