1
# Copyright 2010 Canonical Ltd. This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
4
from urllib2 import HTTPError, URLError
5
from copy import deepcopy
6
from unittest import TestCase
8
from django.conf import settings
10
from identityprovider.models.captcha import Captcha
13
class CaptchaTestCase(TestCase):
16
# save Django settings, to be restored later (that's poking into Django
18
self._settings = settings._target
19
settings._target = deepcopy(self._settings)
22
settings._target = self._settings
24
def test_opener_is_created_during_init(self):
27
captcha = Captcha({}, 'test')
29
self.assertTrue(Captcha.opener is not None)
31
def test_opener_is_created_when_proxy_is_required(self):
33
settings.CAPTCHA_USE_PROXY = True
34
settings.CAPTCHA_PROXIES = {}
36
captcha = Captcha({}, 'test')
38
self.assertTrue(Captcha.opener is not None)
40
def test_open_properly_handles_all_expected_error_codes(self):
41
handled_codes = [111, 113, 408, 500, 502, 503, 504]
43
def mock_open(request):
44
code = handled_codes.pop()
46
raise URLError([code])
48
raise HTTPError(None, code, None, None, None)
49
Captcha._setup_opener()
50
Captcha.opener.open = mock_open
53
response = Captcha._open(None, {})
54
self.assertTrue(response.is_error)
56
def test_new_returns_valid_captcha(self):
57
"""This test requires network connection."""
58
captcha = Captcha.new({})
59
self.assertTrue("recaptcha.net" in captcha.image_url)
61
def test_verify_is_short_circuited_when_disabled_in_settings(self):
62
settings.DISABLE_CAPTCHA_VERIFICATION = True
64
captcha = Captcha({'REMOTE_ADDR': '127.0.0.1'}, 'test')
65
verify_result = captcha.verify('solution')
67
self.assertTrue(verify_result)
68
self.assertTrue(captcha.response is None)
70
def test_verify_fails_but_contacts_recaptcha(self):
71
"""Requires network connection"""
72
settings.DISABLE_CAPTCHA_VERIFICATION = False
73
captcha = Captcha.new({'REMOTE_ADDR': '127.0.0.1'})
75
verify_result = captcha.verify('solution')
77
self.assertFalse(verify_result)
78
self.assertEquals(captcha.response.code, 200)
80
def test_serialize(self):
81
captcha = Captcha({}, 'id', 'image')
83
self.assertEquals(captcha.serialize(),
84
{'captcha_id': 'id', 'image_url': 'image'})