Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a form with a captcha field in django?

I would like to unit test a django view by sumitting a form. The problem is that this form has a captcha field (based on django-simple-captcha).

from django import forms
from captcha.fields import CaptchaField

class ContactForm(forms.forms.Form):
    """
    The information needed for being able to download
    """
    lastname = forms.CharField(max_length=30, label='Last name')
    firstname = forms.CharField(max_length=30, label='First name')
    ...
    captcha = CaptchaField()

The test code:

class ContactFormTest(TestCase):

    def test_submitform(self):
        """Test that the contact page"""
        url = reverse('contact_form')

        form_data = {}
        form_data['firstname'] = 'Paul'
        form_data['lastname'] = 'Macca'
        form_data['captcha'] = '28if'

        response = self.client.post(url, form_data, follow=True)

Is there any approach to unit-test this code and get rid of the captcha when testing?

Thanks in advance

like image 478
luc Avatar asked Jul 01 '10 15:07

luc


People also ask

How do I run Testcases in Django?

Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.

How do you write tests in Django app?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.


1 Answers

I know this is an old post, but django-simple-captcha now has a setting CAPTCHA_TEST_MODE which makes the captcha succeed if you supply the value 'PASSED'. You just have to make sure to send something for both of the captcha input fields:

post_data['captcha_0'] = 'dummy-value'
post_data['captcha_1'] = 'PASSED'
self.client.post(url, data=post_data)

The CAPTCHA_TEST_MODE setting should only be used during tests. My settings.py:

if 'test' in sys.argv:
    CAPTCHA_TEST_MODE = True 
like image 193
Vinod Kurup Avatar answered Oct 10 '22 03:10

Vinod Kurup