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

8

18

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

Extend answered 1/7, 2010 at 15:31 Comment(2)
In case others end up here like I did, I stumbled on this post trying to find a similar answer for the django-recaptcha package; turns out they also have a setting. Their docs describe its use: github.com/praekelt/django-recaptchaForenoon
For those using django-recaptcha and need to do a post in your unittest, you also need to send "g-recaptcha-response" like this: self.client.post(url, {"g-recaptcha-response": "PASSED"})Estriol
I
7

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.

Idocrase answered 1/7, 2010 at 22:23 Comment(1)
The way I did (before noticing your answer) was to parse the unbound form HTML dom = PyQuery('<html><body>{}</body></html>'.format(f.as_p()), get the hash from there hashkey = dom('input[name="captcha_0"]').attr('value') and then query the database using it. The rest is mostly the same. Hope it hopes someone.Tribute
T
23

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 
Thistledown answered 12/11, 2013 at 18:31 Comment(2)
Nowadays it would be also possible to use @override_settings(CAPTCHA_TEST_MODE=True) from from django.test import override_settings; but unfortunately as of February 2019 there is an issue that this very setting is read only once - when the application starts. See github.com/mbi/django-simple-captcha/issues/84Porphyria
this works to test the view but not to test the form alone any info how to send the captcha field directly to the form?Zingaro
I
7

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.

Idocrase answered 1/7, 2010 at 22:23 Comment(1)
The way I did (before noticing your answer) was to parse the unbound form HTML dom = PyQuery('<html><body>{}</body></html>'.format(f.as_p()), get the hash from there hashkey = dom('input[name="captcha_0"]').attr('value') and then query the database using it. The rest is mostly the same. Hope it hopes someone.Tribute
L
6

Here is how we do it.

@patch("captcha.fields.ReCaptchaField.validate")
def test_contact_view(self, validate_method):

    response = self.client.get(reverse("contact"))
    self.assertEqual(response.status_code, 200)

    data = {
        "name": "Bob Johnson",
        "email": "[email protected]",
        "phone": "800-212-2001",
        "subject": "I want Axis!",
        "message": "This is a giant\nThree liner..\nLove ya\n",
        "captcha": "XXX",
    }
    validate_method.return_value = True
    response = self.client.post(reverse("contact"), data=data)

    self.assertEqual(response.status_code, 302)
Lycaonia answered 17/6, 2021 at 22:16 Comment(2)
This approach works also with django-recaptcha package using widget ReCaptchaV3Saleem
FWIW, I banged at this issue for 2 hours with ChatGPT and Copilot, with no soultion. Finally went old school with SO and bingo. ThxAerophyte
R
4

I unit tested it by mocking the ReCaptchaField. First, I've added the recaptcha field in the constructor. It cannot be added as a regular field because you won't be able to mock it (once the code is evaluated before the mock is being applied):

class MyForm(forms.ModelForm):

    ...

    def __init__(self, *args, **kwargs):
        # Add captcha in the constructor to allow mock it
        self.fields["captcha"] = ReCaptchaField()

Then, I just replaced the ReCaptchaField by a not required CharField. This way, I'm trusting django-recaptcha will work. I can test only my own stuff:

@mock.patch("trials.forms.ReCaptchaField", lambda: CharField(required=False))
def test_my_stuff(self):
    response = self.client.post(self.url, data_without_captcha)
    self.assert_my_response_fit_the_needs(response)
Reveille answered 19/6, 2019 at 13:4 Comment(1)
To save anyone else as forgetful as me from needing to look them up, you'll need: from django.db.models import CharField and from unittest import mock.Pulsate
T
1

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.

Tuberculous answered 1/7, 2010 at 15:35 Comment(2)
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 mistakeExtend
you can set testing in the settings file too: if "test" in sys.argv: TESTING = TrueProbative
S
1

Another solutions which is similar to Jim McGaw's answer but remove the need of empty table CaptchaStore table.

captcha = CaptchaStore.objects.get(hashkey=CaptchaStore.generate_key())

registration_data = { # other registration data here
                 'captcha_0': captcha.hashkey,
                 'captcha_1': captcha.response }

This will generate new captcha just for that test.

Sacramentarian answered 21/1, 2016 at 12:4 Comment(0)
G
1

Here is the only thing that worked for me,

set the CAPTCHA_TEST_MODE=True in the test setup method.

class ApplicationTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.url = reverse('application')
        from captcha.conf import settings as captcha_settings
        captcha_settings.CAPTCHA_TEST_MODE = True
    
    def test_post_valid_form(self):
        data = {
            'name': 'John Doe',
            "captcha_0": "8e10ebf60c5f23fd6e6a9959853730cd69062a15",
            "captcha_1": "PASSED",
        }

        response = self.client.post(self.url, data)
        self.assertEqual(response.status_code, 200)
Georgetown answered 12/9, 2023 at 22:17 Comment(0)
E
0

With a similar approach than Jim McGaw but using BeautifulSoup:

from captcha.models import CaptchaStore
from BeautifulSoup import BeautifulSoup

data = {...} #The data to post
soup = BeautifulSoup(self.client.get(url).content)
for field_name in ('captcha_0', ...): #get fields from the form
    data[field_name] = soup.find('input',{'name':field_name})['value']
captcha = CaptchaStore.objects.get(hashkey=data['captcha_0'])
data['captcha_1'] = captcha.challenge
response = self.client.post(url, data=data)

# check the results
...
Extend answered 9/11, 2010 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.