1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
|
"""
Tests for the Akismet spam-filtering integration.
"""
# SPDX-License-Identifier: BSD-3-Clause
import os
from http import HTTPStatus
from unittest import mock
import akismet
from django.core.exceptions import ImproperlyConfigured
from django.test import RequestFactory, TestCase
from django.test.utils import override_settings
from django.urls import reverse
from django_contact_form._akismet import _clear_cached_instance, _try_get_akismet_client
from django_contact_form.forms import AkismetContactForm
class AlwaysSpamClient(akismet.TestSyncClient):
"""
Akismet client which always marks content as spam.
"""
comment_check_response = akismet.CheckResponse.SPAM
class NeverSpamClient(akismet.TestSyncClient):
"""
Akismet client which always marks content as non-spam.
"""
comment_check_response = akismet.CheckResponse.HAM
class ValidConfigClient(akismet.TestSyncClient):
"""
Akismet client which marks its configuration as valid.
"""
verify_key_response = True
class InvalidConfigClient(akismet.TestSyncClient):
"""
Akismet client which marks its configuration as invalid.
"""
verify_key_response = False
@override_settings(ROOT_URLCONF="django_contact_form.akismet_urls")
class AkismetContactFormTests(TestCase):
"""
Tests for the Akismet contact form.
"""
akismet_config = akismet.Config(key="test-key", url="http://example.com")
payload = {
"name": "Test Name",
"email": "test@example.com",
"body": "Test message.",
}
def setUp(self):
"""
Ensure the Akismet client instance is not cached between tests.
"""
_clear_cached_instance()
def request(self):
"""
Construct and return an HttpRequest object for test use.
"""
return RequestFactory().request()
def test_akismet_form_spam(self):
"""
The Akismet contact form correctly rejects spam.
"""
with (
AlwaysSpamClient(config=self.akismet_config) as akismet_client,
mock.patch(
"django_contact_form._akismet._try_get_akismet_client",
new=mock.Mock(return_value=akismet_client),
),
):
form = AkismetContactForm(request=self.request(), data=self.payload)
assert not form.is_valid()
assert str(form.SPAM_MESSAGE) in form.errors["body"]
def test_akismet_form_ham(self):
"""
The Akismet contact form correctly accepts non-spam.
"""
with (
NeverSpamClient(config=self.akismet_config) as akismet_client,
mock.patch(
"django_contact_form._akismet._try_get_akismet_client",
new=mock.Mock(return_value=akismet_client),
),
):
form = AkismetContactForm(request=self.request(), data=self.payload)
assert form.is_valid()
def test_akismet_form_no_body(self):
"""
The Akismet contact form correctly skips validation when no email body is
provided.
"""
data = {"name": "Test", "email": "email@example.com"}
with (
NeverSpamClient(config=self.akismet_config) as akismet_client,
mock.patch(
"django_contact_form._akismet._try_get_akismet_client",
new=mock.Mock(return_value=akismet_client),
),
):
form = AkismetContactForm(request=self.request(), data=data)
assert not form.is_valid()
def test_akismet_django_settings_invalid(self):
"""
When the Django settings are present and invalid, ImproperlyConfigured is
raised.
"""
with (
self.settings(
AKISMET_API_KEY=self.akismet_config.key,
AKISMET_BLOG_URL=self.akismet_config.url,
),
self.assertRaises(ImproperlyConfigured),
):
_try_get_akismet_client(InvalidConfigClient)
def test_akismet_env_invalid(self):
"""
When the environment variables are present and invalid, ImproperlyConfigured
is raised.
"""
try:
os.environ["PYTHON_AKISMET_API_KEY"] = self.akismet_config.key
os.environ["PYTHON_AKISMET_BLOG_URL"] = self.akismet_config.url
with self.assertRaises(ImproperlyConfigured):
_try_get_akismet_client(InvalidConfigClient)
finally:
del os.environ["PYTHON_AKISMET_API_KEY"]
del os.environ["PYTHON_AKISMET_BLOG_URL"]
def test_akismet_env_missing(self):
"""
When the environment variables are missing, ImproperlyConfigured is raised.
"""
for key in ("PYTHON_AKISMET_API_KEY", "PYTHON_AKISMET_BLOG_URL"):
if key in os.environ:
del os.environ[key]
with self.assertRaises(ImproperlyConfigured):
_try_get_akismet_client(InvalidConfigClient)
def test_akismet_django_settings_valid(self):
"""
When the Django settings are present and valid, an Akismet client is
returned using them.
"""
with self.settings(
AKISMET_API_KEY=self.akismet_config.key,
AKISMET_BLOG_URL=self.akismet_config.url,
):
client = _try_get_akismet_client(ValidConfigClient)
assert client is not None
assert isinstance(client, ValidConfigClient)
def test_akismet_env_valid(self):
"""
When the environment variables are present and valid, an Akismet client is
returned using them.
"""
try:
os.environ["PYTHON_AKISMET_API_KEY"] = self.akismet_config.key
os.environ["PYTHON_AKISMET_BLOG_URL"] = self.akismet_config.url
client = _try_get_akismet_client(ValidConfigClient)
assert client is not None
assert isinstance(client, ValidConfigClient)
finally:
del os.environ["PYTHON_AKISMET_API_KEY"]
del os.environ["PYTHON_AKISMET_BLOG_URL"]
def test_akismet_django_settings_persist(self):
"""
A client created from Django settings is correctly persistsed and returned on
later calls.
"""
with self.settings(
AKISMET_API_KEY=self.akismet_config.key,
AKISMET_BLOG_URL=self.akismet_config.url,
):
first = _try_get_akismet_client(ValidConfigClient)
second = _try_get_akismet_client(ValidConfigClient)
assert first is second
def test_akismet_env_persist(self):
"""
A client cretaed from environment variables is correctly persisted and returned
on later calls.
"""
try:
os.environ["PYTHON_AKISMET_API_KEY"] = self.akismet_config.key
os.environ["PYTHON_AKISMET_BLOG_URL"] = self.akismet_config.url
first = _try_get_akismet_client(ValidConfigClient)
second = _try_get_akismet_client(ValidConfigClient)
assert first is second
finally:
del os.environ["PYTHON_AKISMET_API_KEY"]
del os.environ["PYTHON_AKISMET_BLOG_URL"]
@override_settings(ROOT_URLCONF="django_contact_form.akismet_urls")
def test_akismet_view(self):
"""
The Akismet contact form URL uses a spam-filtering AkismetContactForm
instance.
"""
response = self.client.get(reverse("django_contact_form"))
assert response.status_code == HTTPStatus.OK
assert isinstance(response.context["form"], AkismetContactForm)
|