|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# See https://github.com/aboutcode-org/django-altcha for support or download. |
| 5 | +# See https://aboutcode.org for more information about AboutCode FOSS projects. |
| 6 | +# |
| 7 | + |
| 8 | +from unittest import mock |
| 9 | + |
| 10 | +from django import forms |
| 11 | +from django.test import TestCase |
| 12 | + |
| 13 | +from django_altcha import AltchaField, AltchaWidget |
| 14 | + |
| 15 | + |
| 16 | +class AltchaFieldTest(TestCase): |
| 17 | + def setUp(self): |
| 18 | + class TestForm(forms.Form): |
| 19 | + altcha_field = AltchaField() |
| 20 | + |
| 21 | + self.form_class = TestForm |
| 22 | + |
| 23 | + def test_field_renders_widget(self): |
| 24 | + form = self.form_class() |
| 25 | + self.assertIsInstance(form.fields["altcha_field"].widget, AltchaWidget) |
| 26 | + |
| 27 | + def test_field_with_missing_value_raises_required_error(self): |
| 28 | + form = self.form_class(data={}) |
| 29 | + self.assertFalse(form.is_valid()) |
| 30 | + self.assertIn("altcha_field", form.errors) |
| 31 | + self.assertEqual( |
| 32 | + form.errors["altcha_field"][0], "ALTCHA CAPTCHA token is missing." |
| 33 | + ) |
| 34 | + |
| 35 | + @mock.patch("altcha.verify_solution") |
| 36 | + def test_field_validation_calls_altcha_verify_solution(self, mock_verify_solution): |
| 37 | + mock_verify_solution.return_value = (True, None) |
| 38 | + form = self.form_class(data={"altcha_field": "valid_token"}) |
| 39 | + self.assertTrue(form.is_valid()) |
| 40 | + mock_verify_solution.assert_called_once_with( |
| 41 | + payload="valid_token", |
| 42 | + hmac_key=mock.ANY, |
| 43 | + check_expires=False, |
| 44 | + ) |
| 45 | + |
| 46 | + @mock.patch("altcha.verify_solution") |
| 47 | + def test_field_validation_fails_with_invalid_token(self, mock_verify_solution): |
| 48 | + mock_verify_solution.return_value = (False, "Invalid token") |
| 49 | + form = self.form_class(data={"altcha_field": "invalid_token"}) |
| 50 | + self.assertFalse(form.is_valid()) |
| 51 | + self.assertIn("altcha_field", form.errors) |
| 52 | + self.assertEqual(form.errors["altcha_field"][0], "Invalid CAPTCHA token.") |
| 53 | + |
| 54 | + @mock.patch("altcha.verify_solution") |
| 55 | + def test_field_validation_handles_exception(self, mock_verify_solution): |
| 56 | + mock_verify_solution.side_effect = Exception("Verification failed") |
| 57 | + form = self.form_class(data={"altcha_field": "some_token"}) |
| 58 | + self.assertFalse(form.is_valid()) |
| 59 | + self.assertIn("altcha_field", form.errors) |
| 60 | + self.assertEqual( |
| 61 | + form.errors["altcha_field"][0], "Failed to process CAPTCHA token" |
| 62 | + ) |
0 commit comments