def compress(self, data_list): """Compress takes the place of clean with MultiValueFields""" if data_list: answer = data_list[0] real_hashed_answer = data_list[1] hashed_answer = hash_answer(answer) if hashed_answer != real_hashed_answer: raise ValidationError(self.error_messages['invalid']) return None
def test_form_validation(self): class F(forms.Form): captcha = MathCaptchaField() hashed_answer = utils.hash_answer(5) f = F({'captcha_0': 5, 'captcha_1': hashed_answer}) self.assertTrue(f.is_valid()) f = F({'captcha_0': 4, 'captcha_1': hashed_answer}) self.assertFalse(f.is_valid())
def test_reject_incorrect_captcha(self): """Check that the page shows an error if the captcha is incorrect.""" response = self.client.post( reverse('contact'), { 'name': 'Bill', 'email': '*****@*****.**', 'message': '', 'captcha_0': 2, 'captcha_1': captcha_utils.hash_answer(1) }) self.assertEqual(len(mail.outbox), 0) self.assertIn('contact/contact.html', map(lambda t: t.name, response.templates))
def generate_captcha(self): # get operator for calculation operator = get_operator() # get integers for calculation x, y = get_numbers(self.start_int, self.end_int, operator) # set question to display in output self.set_question(x, y, operator) # preform the calculation total = calculate(x, y, operator) return hash_answer(total)
def test_send_complete_message(self): """Check that the form sends an email.""" response = self.client.post( reverse('contact'), { 'name': 'Bill', 'email': '*****@*****.**', 'message': 'Hi there', 'captcha_0': 1, 'captcha_1': captcha_utils.hash_answer(1) }) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Web Feedback') self.assertEqual(mail.outbox[0].body, 'Hi there') self.assertEqual(mail.outbox[0].from_email, 'Bill<*****@*****.**>') self.assertEqual(mail.outbox[0].to, [CONTACT_ADDRESS]) self.assertIn('contact/sent.html', map(lambda t: t.name, response.templates))
def test_send_anonymous_message(self): """Check that a placeholder is inserted if the sender doesn't provide a name.""" response = self.client.post( reverse('contact'), { 'name': '', 'email': '', 'message': 'Hi there', 'captcha_0': 1, 'captcha_1': captcha_utils.hash_answer(1) }) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Web Feedback') self.assertEqual(mail.outbox[0].body, 'Hi there') self.assertEqual(mail.outbox[0].from_email, 'Anonymous<' + CONTACT_ADDRESS + '>') self.assertEqual(mail.outbox[0].to, [CONTACT_ADDRESS]) self.assertIn('contact/sent.html', map(lambda t: t.name, response.templates))
def test_hash_answer_returns_hexdigest(self): result = utils.hash_answer(1) self.assertEqual(len(result), 40)
def test_hash_answer_is_repeatable(self): result1 = utils.hash_answer(1) result2 = utils.hash_answer(1) self.assertEqual(result1, result2)
def test_hash_answer_is_string(self): result = utils.hash_answer(1) self.assertIsInstance(result, six.string_types)