views:

55

answers:

2

Hello all,

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

+1  A: 

One solution is have a setting "testing" that is either true or false. And then just

if not testing:
   # do captcha stuff here

It's simple and easy, and an easy toggle.

Wayne Werner
It works but the settings.UNIT_TEST = True must be set before importing the form in the test module. That was the cause of my mistake
luc
A: 

Here's the way I got around it. Import the model that actually holds Captcha info:

from captcha.models import CaptchaStore

First, I check that the test captcha table is empty:

captcha_count = CaptchaStore.objects.count()
self.failUnlessEqual(captcha_count, 0)

After loading the page (in this case, it's a registration page), check that there's a new captcha object instance:

captcha_count = CaptchaStore.objects.count()
self.failUnlessEqual(captcha_count, 1)

Then, I retrieve the captcha instance data and POST that with the form. In my case, the POST expects 'captcha_0' to contain the hashkey, and 'captcha_1' to contain the response.

captcha = CaptchaStore.objects.all()[0]
registration_data = { # other registration data here
                     'captcha_0': captcha.hashkey,
                     'captcha_1': captcha.response }

You may need to tweak this a little if you start with CaptchaStore instances before you run this test. Hope that helps.

Jim McGaw