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.
22👍
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
- Add a prefix to URL patterns
- How do I hide the field label for a HiddenInput widget in Django Admin?
- Regular expression in URL for Django slug
- In Django how do I notify a parent when a child is saved in a foreign key relationship?
- Django admin many-to-many intermediary models using through= and filter_horizontal
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)
- Google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead : Google Place autocomplete Error
- How to install pygments on Ubuntu?
- Annotate django query if filtered row exists in second table
3👍
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": "big_johnson@home.com",
"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)
- Testing a session variable
- In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?
- Best way to reference the User model in Django >= 1.5
- Django: duplicates when filtering on many to many field
- Set db per model in django
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.
- Why isn't my Django User Model's Password Hashed?
- Check for request.GET variable in the template
- How to display the message passed to Http404 in a custom 404 Error template in Django?
- In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?
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.
- Django annotating with a first element of a related queryset
- Docker + Celery tells me not to run as root, but once I don't, I lack permissions to run
- Django GROUP BY field value
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)
- TypeError: ‘DoesNotExist’ object is not callable
- How to append pages of data using jQuery and Django pagination?
- Django channels and socket.io-client
- Why am I unable to run django migrations via the 'docker-compose run web' command?
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
...
- Django Boolean Queryset Filter Not Working
- Django: JSON Notifications using Redis PubSub, Node.js & Socket.io
- Django migration relation does not exist
- 'CheckoutView' object has no attribute 'object'