| 1 |
import os |
| 2 |
import sys |
| 3 |
import threading |
| 4 |
import traceback |
| 5 |
import unittest |
| 6 |
import warnings |
| 7 |
from io import StringIO |
| 8 |
from unittest import mock |
| 9 |
|
| 10 |
from django.conf import STATICFILES_STORAGE_ALIAS, settings |
| 11 |
from django.contrib.staticfiles.finders import get_finder, get_finders |
| 12 |
from django.contrib.staticfiles.storage import staticfiles_storage |
| 13 |
from django.core.exceptions import ImproperlyConfigured |
| 14 |
from django.core.files.storage import default_storage |
| 15 |
from django.db import ( |
| 16 |
IntegrityError, |
| 17 |
connection, |
| 18 |
connections, |
| 19 |
models, |
| 20 |
router, |
| 21 |
transaction, |
| 22 |
) |
| 23 |
from django.forms import ( |
| 24 |
CharField, |
| 25 |
EmailField, |
| 26 |
Form, |
| 27 |
IntegerField, |
| 28 |
ValidationError, |
| 29 |
formset_factory, |
| 30 |
) |
| 31 |
from django.http import HttpResponse |
| 32 |
from django.template import Context, Template |
| 33 |
from django.template.loader import render_to_string |
| 34 |
from django.test import ( |
| 35 |
SimpleTestCase, |
| 36 |
TestCase, |
| 37 |
TransactionTestCase, |
| 38 |
skipIfDBFeature, |
| 39 |
skipUnlessDBFeature, |
| 40 |
) |
| 41 |
from django.test.html import HTMLParseError, parse_html |
| 42 |
from django.test.testcases import DatabaseOperationForbidden |
| 43 |
from django.test.utils import ( |
| 44 |
CaptureQueriesContext, |
| 45 |
TestContextDecorator, |
| 46 |
isolate_apps, |
| 47 |
override_settings, |
| 48 |
setup_test_environment, |
| 49 |
) |
| 50 |
from django.urls import NoReverseMatch, path, reverse, reverse_lazy |
| 51 |
from django.utils.html import VOID_ELEMENTS |
| 52 |
from django.utils.version import PY311 |
| 53 |
|
| 54 |
from .models import Car, Person, PossessedCar |
| 55 |
from .views import empty_response |
| 56 |
|
| 57 |
|
| 58 |
class SkippingTestCase(SimpleTestCase): |
| 59 |
def _assert_skipping(self, func, expected_exc, msg=None): |
| 60 |
try: |
| 61 |
if msg is not None: |
| 62 |
with self.assertRaisesMessage(expected_exc, msg): |
| 63 |
func() |
| 64 |
else: |
| 65 |
with self.assertRaises(expected_exc): |
| 66 |
func() |
| 67 |
except unittest.SkipTest: |
| 68 |
self.fail("%s should not result in a skipped test." % func.__name__) |
| 69 |
|
| 70 |
def test_skip_unless_db_feature(self): |
| 71 |
""" |
| 72 |
Testing the django.test.skipUnlessDBFeature decorator. |
| 73 |
""" |
| 74 |
|
| 75 |
# Total hack, but it works, just want an attribute that's always true. |
| 76 |
@skipUnlessDBFeature("__class__") |
| 77 |
def test_func(): |
| 78 |
raise ValueError |
| 79 |
|
| 80 |
@skipUnlessDBFeature("notprovided") |
| 81 |
def test_func2(): |
| 82 |
raise ValueError |
| 83 |
|
| 84 |
@skipUnlessDBFeature("__class__", "__class__") |
| 85 |
def test_func3(): |
| 86 |
raise ValueError |
| 87 |
|
| 88 |
@skipUnlessDBFeature("__class__", "notprovided") |
| 89 |
def test_func4(): |
| 90 |
raise ValueError |
| 91 |
|
| 92 |
self._assert_skipping(test_func, ValueError) |
| 93 |
self._assert_skipping(test_func2, unittest.SkipTest) |
| 94 |
self._assert_skipping(test_func3, ValueError) |
| 95 |
self._assert_skipping(test_func4, unittest.SkipTest) |
| 96 |
|
| 97 |
class SkipTestCase(SimpleTestCase): |
| 98 |
@skipUnlessDBFeature("missing") |
| 99 |
def test_foo(self): |
| 100 |
pass |
| 101 |
|
| 102 |
self._assert_skipping( |
| 103 |
SkipTestCase("test_foo").test_foo, |
| 104 |
ValueError, |
| 105 |
"skipUnlessDBFeature cannot be used on test_foo (test_utils.tests." |
| 106 |
"SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase%s) " |
| 107 |
"as SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase " |
| 108 |
"doesn't allow queries against the 'default' database." |
| 109 |
# Python 3.11 uses fully qualified test name in the output. |
| 110 |
% (".test_foo" if PY311 else ""), |
| 111 |
) |
| 112 |
|
| 113 |
def test_skip_if_db_feature(self): |
| 114 |
""" |
| 115 |
Testing the django.test.skipIfDBFeature decorator. |
| 116 |
""" |
| 117 |
|
| 118 |
@skipIfDBFeature("__class__") |
| 119 |
def test_func(): |
| 120 |
raise ValueError |
| 121 |
|
| 122 |
@skipIfDBFeature("notprovided") |
| 123 |
def test_func2(): |
| 124 |
raise ValueError |
| 125 |
|
| 126 |
@skipIfDBFeature("__class__", "__class__") |
| 127 |
def test_func3(): |
| 128 |
raise ValueError |
| 129 |
|
| 130 |
@skipIfDBFeature("__class__", "notprovided") |
| 131 |
def test_func4(): |
| 132 |
raise ValueError |
| 133 |
|
| 134 |
@skipIfDBFeature("notprovided", "notprovided") |
| 135 |
def test_func5(): |
| 136 |
raise ValueError |
| 137 |
|
| 138 |
self._assert_skipping(test_func, unittest.SkipTest) |
| 139 |
self._assert_skipping(test_func2, ValueError) |
| 140 |
self._assert_skipping(test_func3, unittest.SkipTest) |
| 141 |
self._assert_skipping(test_func4, unittest.SkipTest) |
| 142 |
self._assert_skipping(test_func5, ValueError) |
| 143 |
|
| 144 |
class SkipTestCase(SimpleTestCase): |
| 145 |
@skipIfDBFeature("missing") |
| 146 |
def test_foo(self): |
| 147 |
pass |
| 148 |
|
| 149 |
self._assert_skipping( |
| 150 |
SkipTestCase("test_foo").test_foo, |
| 151 |
ValueError, |
| 152 |
"skipIfDBFeature cannot be used on test_foo (test_utils.tests." |
| 153 |
"SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase%s) " |
| 154 |
"as SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase " |
| 155 |
"doesn't allow queries against the 'default' database." |
| 156 |
# Python 3.11 uses fully qualified test name in the output. |
| 157 |
% (".test_foo" if PY311 else ""), |
| 158 |
) |
| 159 |
|
| 160 |
|
| 161 |
class SkippingClassTestCase(TransactionTestCase): |
| 162 |
available_apps = [] |
| 163 |
|
| 164 |
def test_skip_class_unless_db_feature(self): |
| 165 |
@skipUnlessDBFeature("__class__") |
| 166 |
class NotSkippedTests(TestCase): |
| 167 |
def test_dummy(self): |
| 168 |
return |
| 169 |
|
| 170 |
@skipUnlessDBFeature("missing") |
| 171 |
@skipIfDBFeature("__class__") |
| 172 |
class SkippedTests(TestCase): |
| 173 |
def test_will_be_skipped(self): |
| 174 |
self.fail("We should never arrive here.") |
| 175 |
|
| 176 |
@skipIfDBFeature("__dict__") |
| 177 |
class SkippedTestsSubclass(SkippedTests): |
| 178 |
pass |
| 179 |
|
| 180 |
test_suite = unittest.TestSuite() |
| 181 |
test_suite.addTest(NotSkippedTests("test_dummy")) |
| 182 |
try: |
| 183 |
test_suite.addTest(SkippedTests("test_will_be_skipped")) |
| 184 |
test_suite.addTest(SkippedTestsSubclass("test_will_be_skipped")) |
| 185 |
except unittest.SkipTest: |
| 186 |
self.fail("SkipTest should not be raised here.") |
| 187 |
result = unittest.TextTestRunner(stream=StringIO()).run(test_suite) |
| 188 |
# PY312: Python 3.12.1 does not include skipped tests in the number of |
| 189 |
# running tests. |
| 190 |
self.assertEqual( |
| 191 |
result.testsRun, 1 if sys.version_info[:3] == (3, 12, 1) else 3 |
| 192 |
) |
| 193 |
self.assertEqual(len(result.skipped), 2) |
| 194 |
self.assertEqual(result.skipped[0][1], "Database has feature(s) __class__") |
| 195 |
self.assertEqual(result.skipped[1][1], "Database has feature(s) __class__") |
| 196 |
|
| 197 |
def test_missing_default_databases(self): |
| 198 |
@skipIfDBFeature("missing") |
| 199 |
class MissingDatabases(SimpleTestCase): |
| 200 |
def test_assertion_error(self): |
| 201 |
pass |
| 202 |
|
| 203 |
suite = unittest.TestSuite() |
| 204 |
try: |
| 205 |
suite.addTest(MissingDatabases("test_assertion_error")) |
| 206 |
except unittest.SkipTest: |
| 207 |
self.fail("SkipTest should not be raised at this stage") |
| 208 |
runner = unittest.TextTestRunner(stream=StringIO()) |
| 209 |
msg = ( |
| 210 |
"skipIfDBFeature cannot be used on <class 'test_utils.tests." |
| 211 |
"SkippingClassTestCase.test_missing_default_databases.<locals>." |
| 212 |
"MissingDatabases'> as it doesn't allow queries against the " |
| 213 |
"'default' database." |
| 214 |
) |
| 215 |
with self.assertRaisesMessage(ValueError, msg): |
| 216 |
runner.run(suite) |
| 217 |
|
| 218 |
|
| 219 |
@override_settings(ROOT_URLCONF="test_utils.urls") |
| 220 |
class AssertNumQueriesTests(TestCase): |
| 221 |
def test_assert_num_queries(self): |
| 222 |
def test_func(): |
| 223 |
raise ValueError |
| 224 |
|
| 225 |
with self.assertRaises(ValueError): |
| 226 |
self.assertNumQueries(2, test_func) |
| 227 |
|
| 228 |
def test_assert_num_queries_with_client(self): |
| 229 |
person = Person.objects.create(name="test") |
| 230 |
|
| 231 |
self.assertNumQueries( |
| 232 |
1, self.client.get, "/test_utils/get_person/%s/" % person.pk |
| 233 |
) |
| 234 |
|
| 235 |
self.assertNumQueries( |
| 236 |
1, self.client.get, "/test_utils/get_person/%s/" % person.pk |
| 237 |
) |
| 238 |
|
| 239 |
def test_func(): |
| 240 |
self.client.get("/test_utils/get_person/%s/" % person.pk) |
| 241 |
self.client.get("/test_utils/get_person/%s/" % person.pk) |
| 242 |
|
| 243 |
self.assertNumQueries(2, test_func) |
| 244 |
|
| 245 |
|
| 246 |
class AssertNumQueriesUponConnectionTests(TransactionTestCase): |
| 247 |
available_apps = [] |
| 248 |
|
| 249 |
def test_ignores_connection_configuration_queries(self): |
| 250 |
real_ensure_connection = connection.ensure_connection |
| 251 |
connection.close() |
| 252 |
|
| 253 |
def make_configuration_query(): |
| 254 |
is_opening_connection = connection.connection is None |
| 255 |
real_ensure_connection() |
| 256 |
|
| 257 |
if is_opening_connection: |
| 258 |
# Avoid infinite recursion. Creating a cursor calls |
| 259 |
# ensure_connection() which is currently mocked by this method. |
| 260 |
with connection.cursor() as cursor: |
| 261 |
cursor.execute("SELECT 1" + connection.features.bare_select_suffix) |
| 262 |
|
| 263 |
ensure_connection = ( |
| 264 |
"django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection" |
| 265 |
) |
| 266 |
with mock.patch(ensure_connection, side_effect=make_configuration_query): |
| 267 |
with self.assertNumQueries(1): |
| 268 |
list(Car.objects.all()) |
| 269 |
|
| 270 |
|
| 271 |
class AssertQuerySetEqualTests(TestCase): |
| 272 |
@classmethod |
| 273 |
def setUpTestData(cls): |
| 274 |
cls.p1 = Person.objects.create(name="p1") |
| 275 |
cls.p2 = Person.objects.create(name="p2") |
| 276 |
|
| 277 |
def test_empty(self): |
| 278 |
self.assertQuerySetEqual(Person.objects.filter(name="p3"), []) |
| 279 |
|
| 280 |
def test_ordered(self): |
| 281 |
self.assertQuerySetEqual( |
| 282 |
Person.objects.order_by("name"), |
| 283 |
[self.p1, self.p2], |
| 284 |
) |
| 285 |
|
| 286 |
def test_unordered(self): |
| 287 |
self.assertQuerySetEqual( |
| 288 |
Person.objects.order_by("name"), [self.p2, self.p1], ordered=False |
| 289 |
) |
| 290 |
|
| 291 |
def test_queryset(self): |
| 292 |
self.assertQuerySetEqual( |
| 293 |
Person.objects.order_by("name"), |
| 294 |
Person.objects.order_by("name"), |
| 295 |
) |
| 296 |
|
| 297 |
def test_flat_values_list(self): |
| 298 |
self.assertQuerySetEqual( |
| 299 |
Person.objects.order_by("name").values_list("name", flat=True), |
| 300 |
["p1", "p2"], |
| 301 |
) |
| 302 |
|
| 303 |
def test_transform(self): |
| 304 |
self.assertQuerySetEqual( |
| 305 |
Person.objects.order_by("name"), |
| 306 |
[self.p1.pk, self.p2.pk], |
| 307 |
transform=lambda x: x.pk, |
| 308 |
) |
| 309 |
|
| 310 |
def test_repr_transform(self): |
| 311 |
self.assertQuerySetEqual( |
| 312 |
Person.objects.order_by("name"), |
| 313 |
[repr(self.p1), repr(self.p2)], |
| 314 |
transform=repr, |
| 315 |
) |
| 316 |
|
| 317 |
def test_undefined_order(self): |
| 318 |
# Using an unordered queryset with more than one ordered value |
| 319 |
# is an error. |
| 320 |
msg = ( |
| 321 |
"Trying to compare non-ordered queryset against more than one " |
| 322 |
"ordered value." |
| 323 |
) |
| 324 |
with self.assertRaisesMessage(ValueError, msg): |
| 325 |
self.assertQuerySetEqual( |
| 326 |
Person.objects.all(), |
| 327 |
[self.p1, self.p2], |
| 328 |
) |
| 329 |
# No error for one value. |
| 330 |
self.assertQuerySetEqual(Person.objects.filter(name="p1"), [self.p1]) |
| 331 |
|
| 332 |
def test_repeated_values(self): |
| 333 |
""" |
| 334 |
assertQuerySetEqual checks the number of appearance of each item |
| 335 |
when used with option ordered=False. |
| 336 |
""" |
| 337 |
batmobile = Car.objects.create(name="Batmobile") |
| 338 |
k2000 = Car.objects.create(name="K 2000") |
| 339 |
PossessedCar.objects.bulk_create( |
| 340 |
[ |
| 341 |
PossessedCar(car=batmobile, belongs_to=self.p1), |
| 342 |
PossessedCar(car=batmobile, belongs_to=self.p1), |
| 343 |
PossessedCar(car=k2000, belongs_to=self.p1), |
| 344 |
PossessedCar(car=k2000, belongs_to=self.p1), |
| 345 |
PossessedCar(car=k2000, belongs_to=self.p1), |
| 346 |
PossessedCar(car=k2000, belongs_to=self.p1), |
| 347 |
] |
| 348 |
) |
| 349 |
with self.assertRaises(AssertionError): |
| 350 |
self.assertQuerySetEqual( |
| 351 |
self.p1.cars.all(), [batmobile, k2000], ordered=False |
| 352 |
) |
| 353 |
self.assertQuerySetEqual( |
| 354 |
self.p1.cars.all(), [batmobile] * 2 + [k2000] * 4, ordered=False |
| 355 |
) |
| 356 |
|
| 357 |
def test_maxdiff(self): |
| 358 |
names = ["Joe Smith %s" % i for i in range(20)] |
| 359 |
Person.objects.bulk_create([Person(name=name) for name in names]) |
| 360 |
names.append("Extra Person") |
| 361 |
|
| 362 |
with self.assertRaises(AssertionError) as ctx: |
| 363 |
self.assertQuerySetEqual( |
| 364 |
Person.objects.filter(name__startswith="Joe"), |
| 365 |
names, |
| 366 |
ordered=False, |
| 367 |
transform=lambda p: p.name, |
| 368 |
) |
| 369 |
self.assertIn("Set self.maxDiff to None to see it.", str(ctx.exception)) |
| 370 |
|
| 371 |
original = self.maxDiff |
| 372 |
self.maxDiff = None |
| 373 |
try: |
| 374 |
with self.assertRaises(AssertionError) as ctx: |
| 375 |
self.assertQuerySetEqual( |
| 376 |
Person.objects.filter(name__startswith="Joe"), |
| 377 |
names, |
| 378 |
ordered=False, |
| 379 |
transform=lambda p: p.name, |
| 380 |
) |
| 381 |
finally: |
| 382 |
self.maxDiff = original |
| 383 |
exception_msg = str(ctx.exception) |
| 384 |
self.assertNotIn("Set self.maxDiff to None to see it.", exception_msg) |
| 385 |
for name in names: |
| 386 |
self.assertIn(name, exception_msg) |
| 387 |
|
| 388 |
|
| 389 |
@override_settings(ROOT_URLCONF="test_utils.urls") |
| 390 |
class CaptureQueriesContextManagerTests(TestCase): |
| 391 |
@classmethod |
| 392 |
def setUpTestData(cls): |
| 393 |
cls.person_pk = str(Person.objects.create(name="test").pk) |
| 394 |
|
| 395 |
def test_simple(self): |
| 396 |
with CaptureQueriesContext(connection) as captured_queries: |
| 397 |
Person.objects.get(pk=self.person_pk) |
| 398 |
self.assertEqual(len(captured_queries), 1) |
| 399 |
self.assertIn(self.person_pk, captured_queries[0]["sql"]) |
| 400 |
|
| 401 |
with CaptureQueriesContext(connection) as captured_queries: |
| 402 |
pass |
| 403 |
self.assertEqual(0, len(captured_queries)) |
| 404 |
|
| 405 |
def test_within(self): |
| 406 |
with CaptureQueriesContext(connection) as captured_queries: |
| 407 |
Person.objects.get(pk=self.person_pk) |
| 408 |
self.assertEqual(len(captured_queries), 1) |
| 409 |
self.assertIn(self.person_pk, captured_queries[0]["sql"]) |
| 410 |
|
| 411 |
def test_nested(self): |
| 412 |
with CaptureQueriesContext(connection) as captured_queries: |
| 413 |
Person.objects.count() |
| 414 |
with CaptureQueriesContext(connection) as nested_captured_queries: |
| 415 |
Person.objects.count() |
| 416 |
self.assertEqual(1, len(nested_captured_queries)) |
| 417 |
self.assertEqual(2, len(captured_queries)) |
| 418 |
|
| 419 |
def test_failure(self): |
| 420 |
with self.assertRaises(TypeError): |
| 421 |
with CaptureQueriesContext(connection): |
| 422 |
raise TypeError |
| 423 |
|
| 424 |
def test_with_client(self): |
| 425 |
with CaptureQueriesContext(connection) as captured_queries: |
| 426 |
self.client.get("/test_utils/get_person/%s/" % self.person_pk) |
| 427 |
self.assertEqual(len(captured_queries), 1) |
| 428 |
self.assertIn(self.person_pk, captured_queries[0]["sql"]) |
| 429 |
|
| 430 |
with CaptureQueriesContext(connection) as captured_queries: |
| 431 |
self.client.get("/test_utils/get_person/%s/" % self.person_pk) |
| 432 |
self.assertEqual(len(captured_queries), 1) |
| 433 |
self.assertIn(self.person_pk, captured_queries[0]["sql"]) |
| 434 |
|
| 435 |
with CaptureQueriesContext(connection) as captured_queries: |
| 436 |
self.client.get("/test_utils/get_person/%s/" % self.person_pk) |
| 437 |
self.client.get("/test_utils/get_person/%s/" % self.person_pk) |
| 438 |
self.assertEqual(len(captured_queries), 2) |
| 439 |
self.assertIn(self.person_pk, captured_queries[0]["sql"]) |
| 440 |
self.assertIn(self.person_pk, captured_queries[1]["sql"]) |
| 441 |
|
| 442 |
|
| 443 |
@override_settings(ROOT_URLCONF="test_utils.urls") |
| 444 |
class AssertNumQueriesContextManagerTests(TestCase): |
| 445 |
def test_simple(self): |
| 446 |
with self.assertNumQueries(0): |
| 447 |
pass |
| 448 |
|
| 449 |
with self.assertNumQueries(1): |
| 450 |
Person.objects.count() |
| 451 |
|
| 452 |
with self.assertNumQueries(2): |
| 453 |
Person.objects.count() |
| 454 |
Person.objects.count() |
| 455 |
|
| 456 |
def test_failure(self): |
| 457 |
msg = "1 != 2 : 1 queries executed, 2 expected\nCaptured queries were:\n1." |
| 458 |
with self.assertRaisesMessage(AssertionError, msg): |
| 459 |
with self.assertNumQueries(2): |
| 460 |
Person.objects.count() |
| 461 |
|
| 462 |
with self.assertRaises(TypeError): |
| 463 |
with self.assertNumQueries(4000): |
| 464 |
raise TypeError |
| 465 |
|
| 466 |
def test_with_client(self): |
| 467 |
person = Person.objects.create(name="test") |
| 468 |
|
| 469 |
with self.assertNumQueries(1): |
| 470 |
self.client.get("/test_utils/get_person/%s/" % person.pk) |
| 471 |
|
| 472 |
with self.assertNumQueries(1): |
| 473 |
self.client.get("/test_utils/get_person/%s/" % person.pk) |
| 474 |
|
| 475 |
with self.assertNumQueries(2): |
| 476 |
self.client.get("/test_utils/get_person/%s/" % person.pk) |
| 477 |
self.client.get("/test_utils/get_person/%s/" % person.pk) |
| 478 |
|
| 479 |
|
| 480 |
@override_settings(ROOT_URLCONF="test_utils.urls") |
| 481 |
class AssertTemplateUsedContextManagerTests(SimpleTestCase): |
| 482 |
def test_usage(self): |
| 483 |
with self.assertTemplateUsed("template_used/base.html"): |
| 484 |
render_to_string("template_used/base.html") |
| 485 |
|
| 486 |
with self.assertTemplateUsed(template_name="template_used/base.html"): |
| 487 |
render_to_string("template_used/base.html") |
| 488 |
|
| 489 |
with self.assertTemplateUsed("template_used/base.html"): |
| 490 |
render_to_string("template_used/include.html") |
| 491 |
|
| 492 |
with self.assertTemplateUsed("template_used/base.html"): |
| 493 |
render_to_string("template_used/extends.html") |
| 494 |
|
| 495 |
with self.assertTemplateUsed("template_used/base.html"): |
| 496 |
render_to_string("template_used/base.html") |
| 497 |
render_to_string("template_used/base.html") |
| 498 |
|
| 499 |
def test_nested_usage(self): |
| 500 |
with self.assertTemplateUsed("template_used/base.html"): |
| 501 |
with self.assertTemplateUsed("template_used/include.html"): |
| 502 |
render_to_string("template_used/include.html") |
| 503 |
|
| 504 |
with self.assertTemplateUsed("template_used/extends.html"): |
| 505 |
with self.assertTemplateUsed("template_used/base.html"): |
| 506 |
render_to_string("template_used/extends.html") |
| 507 |
|
| 508 |
with self.assertTemplateUsed("template_used/base.html"): |
| 509 |
with self.assertTemplateUsed("template_used/alternative.html"): |
| 510 |
render_to_string("template_used/alternative.html") |
| 511 |
render_to_string("template_used/base.html") |
| 512 |
|
| 513 |
with self.assertTemplateUsed("template_used/base.html"): |
| 514 |
render_to_string("template_used/extends.html") |
| 515 |
with self.assertTemplateNotUsed("template_used/base.html"): |
| 516 |
render_to_string("template_used/alternative.html") |
| 517 |
render_to_string("template_used/base.html") |
| 518 |
|
| 519 |
def test_not_used(self): |
| 520 |
with self.assertTemplateNotUsed("template_used/base.html"): |
| 521 |
pass |
| 522 |
with self.assertTemplateNotUsed("template_used/alternative.html"): |
| 523 |
pass |
| 524 |
|
| 525 |
def test_error_message(self): |
| 526 |
msg = "No templates used to render the response" |
| 527 |
with self.assertRaisesMessage(AssertionError, msg): |
| 528 |
with self.assertTemplateUsed("template_used/base.html"): |
| 529 |
pass |
| 530 |
|
| 531 |
with self.assertRaisesMessage(AssertionError, msg): |
| 532 |
with self.assertTemplateUsed(template_name="template_used/base.html"): |
| 533 |
pass |
| 534 |
|
| 535 |
msg2 = ( |
| 536 |
"Template 'template_used/base.html' was not a template used to render " |
| 537 |
"the response. Actual template(s) used: template_used/alternative.html" |
| 538 |
) |
| 539 |
with self.assertRaisesMessage(AssertionError, msg2): |
| 540 |
with self.assertTemplateUsed("template_used/base.html"): |
| 541 |
render_to_string("template_used/alternative.html") |
| 542 |
|
| 543 |
msg = "No templates used to render the response" |
| 544 |
with self.assertRaisesMessage(AssertionError, msg): |
| 545 |
response = self.client.get("/test_utils/no_template_used/") |
| 546 |
self.assertTemplateUsed(response, "template_used/base.html") |
| 547 |
|
| 548 |
with self.assertRaisesMessage(AssertionError, msg): |
| 549 |
with self.assertTemplateUsed("template_used/base.html"): |
| 550 |
self.client.get("/test_utils/no_template_used/") |
| 551 |
|
| 552 |
with self.assertRaisesMessage(AssertionError, msg): |
| 553 |
with self.assertTemplateUsed("template_used/base.html"): |
| 554 |
template = Template("template_used/alternative.html", name=None) |
| 555 |
template.render(Context()) |
| 556 |
|
| 557 |
def test_msg_prefix(self): |
| 558 |
msg_prefix = "Prefix" |
| 559 |
msg = f"{msg_prefix}: No templates used to render the response" |
| 560 |
with self.assertRaisesMessage(AssertionError, msg): |
| 561 |
with self.assertTemplateUsed( |
| 562 |
"template_used/base.html", msg_prefix=msg_prefix |
| 563 |
): |
| 564 |
pass |
| 565 |
|
| 566 |
with self.assertRaisesMessage(AssertionError, msg): |
| 567 |
with self.assertTemplateUsed( |
| 568 |
template_name="template_used/base.html", |
| 569 |
msg_prefix=msg_prefix, |
| 570 |
): |
| 571 |
pass |
| 572 |
|
| 573 |
msg = ( |
| 574 |
f"{msg_prefix}: Template 'template_used/base.html' was not a " |
| 575 |
f"template used to render the response. Actual template(s) used: " |
| 576 |
f"template_used/alternative.html" |
| 577 |
) |
| 578 |
with self.assertRaisesMessage(AssertionError, msg): |
| 579 |
with self.assertTemplateUsed( |
| 580 |
"template_used/base.html", msg_prefix=msg_prefix |
| 581 |
): |
| 582 |
render_to_string("template_used/alternative.html") |
| 583 |
|
| 584 |
def test_count(self): |
| 585 |
with self.assertTemplateUsed("template_used/base.html", count=2): |
| 586 |
render_to_string("template_used/base.html") |
| 587 |
render_to_string("template_used/base.html") |
| 588 |
|
| 589 |
msg = ( |
| 590 |
"Template 'template_used/base.html' was expected to be rendered " |
| 591 |
"3 time(s) but was actually rendered 2 time(s)." |
| 592 |
) |
| 593 |
with self.assertRaisesMessage(AssertionError, msg): |
| 594 |
with self.assertTemplateUsed("template_used/base.html", count=3): |
| 595 |
render_to_string("template_used/base.html") |
| 596 |
render_to_string("template_used/base.html") |
| 597 |
|
| 598 |
def test_failure(self): |
| 599 |
msg = "response and/or template_name argument must be provided" |
| 600 |
with self.assertRaisesMessage(TypeError, msg): |
| 601 |
with self.assertTemplateUsed(): |
| 602 |
pass |
| 603 |
|
| 604 |
msg = "No templates used to render the response" |
| 605 |
with self.assertRaisesMessage(AssertionError, msg): |
| 606 |
with self.assertTemplateUsed(""): |
| 607 |
pass |
| 608 |
|
| 609 |
with self.assertRaisesMessage(AssertionError, msg): |
| 610 |
with self.assertTemplateUsed(""): |
| 611 |
render_to_string("template_used/base.html") |
| 612 |
|
| 613 |
with self.assertRaisesMessage(AssertionError, msg): |
| 614 |
with self.assertTemplateUsed(template_name=""): |
| 615 |
pass |
| 616 |
|
| 617 |
msg = ( |
| 618 |
"Template 'template_used/base.html' was not a template used to " |
| 619 |
"render the response. Actual template(s) used: " |
| 620 |
"template_used/alternative.html" |
| 621 |
) |
| 622 |
with self.assertRaisesMessage(AssertionError, msg): |
| 623 |
with self.assertTemplateUsed("template_used/base.html"): |
| 624 |
render_to_string("template_used/alternative.html") |
| 625 |
|
| 626 |
def test_assert_used_on_http_response(self): |
| 627 |
response = HttpResponse() |
| 628 |
msg = "%s() is only usable on responses fetched using the Django test Client." |
| 629 |
with self.assertRaisesMessage(ValueError, msg % "assertTemplateUsed"): |
| 630 |
self.assertTemplateUsed(response, "template.html") |
| 631 |
with self.assertRaisesMessage(ValueError, msg % "assertTemplateNotUsed"): |
| 632 |
self.assertTemplateNotUsed(response, "template.html") |
| 633 |
|
| 634 |
|
| 635 |
class HTMLEqualTests(SimpleTestCase): |
| 636 |
def test_html_parser(self): |
| 637 |
element = parse_html("<div><p>Hello</p></div>") |
| 638 |
self.assertEqual(len(element.children), 1) |
| 639 |
self.assertEqual(element.children[0].name, "p") |
| 640 |
self.assertEqual(element.children[0].children[0], "Hello") |
| 641 |
|
| 642 |
parse_html("<p>") |
| 643 |
parse_html("<p attr>") |
| 644 |
dom = parse_html("<p>foo") |
| 645 |
self.assertEqual(len(dom.children), 1) |
| 646 |
self.assertEqual(dom.name, "p") |
| 647 |
self.assertEqual(dom[0], "foo") |
| 648 |
|
| 649 |
def test_parse_html_in_script(self): |
| 650 |
parse_html('<script>var a = "<p" + ">";</script>') |
| 651 |
parse_html(""" |
| 652 |
<script> |
| 653 |
var js_sha_link='<p>***</p>'; |
| 654 |
</script> |
| 655 |
""") |
| 656 |
|
| 657 |
# script content will be parsed to text |
| 658 |
dom = parse_html(""" |
| 659 |
<script><p>foo</p> '</scr'+'ipt>' <span>bar</span></script> |
| 660 |
""") |
| 661 |
self.assertEqual(len(dom.children), 1) |
| 662 |
self.assertEqual(dom.children[0], "<p>foo</p> '</scr'+'ipt>' <span>bar</span>") |
| 663 |
|
| 664 |
def test_void_elements(self): |
| 665 |
for tag in VOID_ELEMENTS: |
| 666 |
with self.subTest(tag): |
| 667 |
dom = parse_html("<p>Hello <%s> world</p>" % tag) |
| 668 |
self.assertEqual(len(dom.children), 3) |
| 669 |
self.assertEqual(dom[0], "Hello") |
| 670 |
self.assertEqual(dom[1].name, tag) |
| 671 |
self.assertEqual(dom[2], "world") |
| 672 |
|
| 673 |
dom = parse_html("<p>Hello <%s /> world</p>" % tag) |
| 674 |
self.assertEqual(len(dom.children), 3) |
| 675 |
self.assertEqual(dom[0], "Hello") |
| 676 |
self.assertEqual(dom[1].name, tag) |
| 677 |
self.assertEqual(dom[2], "world") |
| 678 |
|
| 679 |
def test_simple_equal_html(self): |
| 680 |
self.assertHTMLEqual("", "") |
| 681 |
self.assertHTMLEqual("<p></p>", "<p></p>") |
| 682 |
self.assertHTMLEqual("<p></p>", " <p> </p> ") |
| 683 |
self.assertHTMLEqual("<div><p>Hello</p></div>", "<div><p>Hello</p></div>") |
| 684 |
self.assertHTMLEqual("<div><p>Hello</p></div>", "<div> <p>Hello</p> </div>") |
| 685 |
self.assertHTMLEqual("<div>\n<p>Hello</p></div>", "<div><p>Hello</p></div>\n") |
| 686 |
self.assertHTMLEqual( |
| 687 |
"<div><p>Hello\nWorld !</p></div>", "<div><p>Hello World\n!</p></div>" |
| 688 |
) |
| 689 |
self.assertHTMLEqual( |
| 690 |
"<div><p>Hello\nWorld !</p></div>", "<div><p>Hello World\n!</p></div>" |
| 691 |
) |
| 692 |
self.assertHTMLEqual("<p>Hello World !</p>", "<p>Hello World\n\n!</p>") |
| 693 |
self.assertHTMLEqual("<p> </p>", "<p></p>") |
| 694 |
self.assertHTMLEqual("<p/>", "<p></p>") |
| 695 |
self.assertHTMLEqual("<p />", "<p></p>") |
| 696 |
self.assertHTMLEqual("<input checked>", '<input checked="checked">') |
| 697 |
self.assertHTMLEqual("<p>Hello", "<p> Hello") |
| 698 |
self.assertHTMLEqual("<p>Hello</p>World", "<p>Hello</p> World") |
| 699 |
|
| 700 |
def test_ignore_comments(self): |
| 701 |
self.assertHTMLEqual( |
| 702 |
"<div>Hello<!-- this is a comment --> World!</div>", |
| 703 |
"<div>Hello World!</div>", |
| 704 |
) |
| 705 |
|
| 706 |
def test_unequal_html(self): |
| 707 |
self.assertHTMLNotEqual("<p>Hello</p>", "<p>Hello!</p>") |
| 708 |
self.assertHTMLNotEqual("<p>foobar</p>", "<p>foo bar</p>") |
| 709 |
self.assertHTMLNotEqual("<p>foo bar</p>", "<p>foo bar</p>") |
| 710 |
self.assertHTMLNotEqual("<p>foo nbsp</p>", "<p>foo </p>") |
| 711 |
self.assertHTMLNotEqual("<p>foo #20</p>", "<p>foo </p>") |
| 712 |
self.assertHTMLNotEqual( |
| 713 |
"<p><span>Hello</span><span>World</span></p>", |
| 714 |
"<p><span>Hello</span>World</p>", |
| 715 |
) |
| 716 |
self.assertHTMLNotEqual( |
| 717 |
"<p><span>Hello</span>World</p>", |
| 718 |
"<p><span>Hello</span><span>World</span></p>", |
| 719 |
) |
| 720 |
|
| 721 |
def test_attributes(self): |
| 722 |
self.assertHTMLEqual( |
| 723 |
'<input type="text" id="id_name" />', '<input id="id_name" type="text" />' |
| 724 |
) |
| 725 |
self.assertHTMLEqual( |
| 726 |
"""<input type='text' id="id_name" />""", |
| 727 |
'<input id="id_name" type="text" />', |
| 728 |
) |
| 729 |
self.assertHTMLNotEqual( |
| 730 |
'<input type="text" id="id_name" />', |
| 731 |
'<input type="password" id="id_name" />', |
| 732 |
) |
| 733 |
|
| 734 |
def test_class_attribute(self): |
| 735 |
pairs = [ |
| 736 |
('<p class="foo bar"></p>', '<p class="bar foo"></p>'), |
| 737 |
('<p class=" foo bar "></p>', '<p class="bar foo"></p>'), |
| 738 |
('<p class=" foo bar "></p>', '<p class="bar foo"></p>'), |
| 739 |
('<p class="foo\tbar"></p>', '<p class="bar foo"></p>'), |
| 740 |
('<p class="\tfoo\tbar\t"></p>', '<p class="bar foo"></p>'), |
| 741 |
('<p class="\t\t\tfoo\t\t\tbar\t\t\t"></p>', '<p class="bar foo"></p>'), |
| 742 |
('<p class="\t \nfoo \t\nbar\n\t "></p>', '<p class="bar foo"></p>'), |
| 743 |
] |
| 744 |
for html1, html2 in pairs: |
| 745 |
with self.subTest(html1): |
| 746 |
self.assertHTMLEqual(html1, html2) |
| 747 |
|
| 748 |
def test_boolean_attribute(self): |
| 749 |
html1 = "<input checked>" |
| 750 |
html2 = '<input checked="">' |
| 751 |
html3 = '<input checked="checked">' |
| 752 |
self.assertHTMLEqual(html1, html2) |
| 753 |
self.assertHTMLEqual(html1, html3) |
| 754 |
self.assertHTMLEqual(html2, html3) |
| 755 |
self.assertHTMLNotEqual(html1, '<input checked="invalid">') |
| 756 |
self.assertEqual(str(parse_html(html1)), "<input checked>") |
| 757 |
self.assertEqual(str(parse_html(html2)), "<input checked>") |
| 758 |
self.assertEqual(str(parse_html(html3)), "<input checked>") |
| 759 |
|
| 760 |
def test_non_boolean_attibutes(self): |
| 761 |
html1 = "<input value>" |
| 762 |
html2 = '<input value="">' |
| 763 |
html3 = '<input value="value">' |
| 764 |
self.assertHTMLEqual(html1, html2) |
| 765 |
self.assertHTMLNotEqual(html1, html3) |
| 766 |
self.assertEqual(str(parse_html(html1)), '<input value="">') |
| 767 |
self.assertEqual(str(parse_html(html2)), '<input value="">') |
| 768 |
|
| 769 |
def test_normalize_refs(self): |
| 770 |
pairs = [ |
| 771 |
("'", "'"), |
| 772 |
("'", "'"), |
| 773 |
("'", "'"), |
| 774 |
("'", "'"), |
| 775 |
("'", "'"), |
| 776 |
("'", "'"), |
| 777 |
("&", "&"), |
| 778 |
("&", "&"), |
| 779 |
("&", "&"), |
| 780 |
("&", "&"), |
| 781 |
("&", "&"), |
| 782 |
("&", "&"), |
| 783 |
("&", "&"), |
| 784 |
("&", "&"), |
| 785 |
("&", "&"), |
| 786 |
("&", "&"), |
| 787 |
("&", "&"), |
| 788 |
("&", "&"), |
| 789 |
] |
| 790 |
for pair in pairs: |
| 791 |
with self.subTest(repr(pair)): |
| 792 |
self.assertHTMLEqual(*pair) |
| 793 |
|
| 794 |
def test_complex_examples(self): |
| 795 |
self.assertHTMLEqual( |
| 796 |
"""<tr><th><label for="id_first_name">First name:</label></th> |
| 797 |
<td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr> |
| 798 |
<tr><th><label for="id_last_name">Last name:</label></th> |
| 799 |
<td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr> |
| 800 |
<tr><th><label for="id_birthday">Birthday:</label></th> |
| 801 |
<td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""", # NOQA |
| 802 |
""" |
| 803 |
<tr><th> |
| 804 |
<label for="id_first_name">First name:</label></th><td> |
| 805 |
<input type="text" name="first_name" value="John" id="id_first_name" /> |
| 806 |
</td></tr> |
| 807 |
<tr><th> |
| 808 |
<label for="id_last_name">Last name:</label></th><td> |
| 809 |
<input type="text" name="last_name" value="Lennon" id="id_last_name" /> |
| 810 |
</td></tr> |
| 811 |
<tr><th> |
| 812 |
<label for="id_birthday">Birthday:</label></th><td> |
| 813 |
<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /> |
| 814 |
</td></tr> |
| 815 |
""", |
| 816 |
) |
| 817 |
|
| 818 |
self.assertHTMLEqual( |
| 819 |
"""<!DOCTYPE html> |
| 820 |
<html> |
| 821 |
<head> |
| 822 |
<link rel="stylesheet"> |
| 823 |
<title>Document</title> |
| 824 |
<meta attribute="value"> |
| 825 |
</head> |
| 826 |
<body> |
| 827 |
<p> |
| 828 |
This is a valid paragraph |
| 829 |
<div> this is a div AFTER the p</div> |
| 830 |
</body> |
| 831 |
</html>""", |
| 832 |
""" |
| 833 |
<html> |
| 834 |
<head> |
| 835 |
<link rel="stylesheet"> |
| 836 |
<title>Document</title> |
| 837 |
<meta attribute="value"> |
| 838 |
</head> |
| 839 |
<body> |
| 840 |
<p> This is a valid paragraph |
| 841 |
<!-- browsers would close the p tag here --> |
| 842 |
<div> this is a div AFTER the p</div> |
| 843 |
</p> <!-- this is invalid HTML parsing, but it should make no |
| 844 |
difference in most cases --> |
| 845 |
</body> |
| 846 |
</html>""", |
| 847 |
) |
| 848 |
|
| 849 |
def test_html_contain(self): |
| 850 |
# equal html contains each other |
| 851 |
dom1 = parse_html("<p>foo") |
| 852 |
dom2 = parse_html("<p>foo</p>") |
| 853 |
self.assertIn(dom1, dom2) |
| 854 |
self.assertIn(dom2, dom1) |
| 855 |
|
| 856 |
dom2 = parse_html("<div><p>foo</p></div>") |
| 857 |
self.assertIn(dom1, dom2) |
| 858 |
self.assertNotIn(dom2, dom1) |
| 859 |
|
| 860 |
self.assertNotIn("<p>foo</p>", dom2) |
| 861 |
self.assertIn("foo", dom2) |
| 862 |
|
| 863 |
# when a root element is used ... |
| 864 |
dom1 = parse_html("<p>foo</p><p>bar</p>") |
| 865 |
dom2 = parse_html("<p>foo</p><p>bar</p>") |
| 866 |
self.assertIn(dom1, dom2) |
| 867 |
dom1 = parse_html("<p>foo</p>") |
| 868 |
self.assertIn(dom1, dom2) |
| 869 |
dom1 = parse_html("<p>bar</p>") |
| 870 |
self.assertIn(dom1, dom2) |
| 871 |
dom1 = parse_html("<div><p>foo</p><p>bar</p></div>") |
| 872 |
self.assertIn(dom2, dom1) |
| 873 |
|
| 874 |
def test_count(self): |
| 875 |
# equal html contains each other one time |
| 876 |
dom1 = parse_html("<p>foo") |
| 877 |
dom2 = parse_html("<p>foo</p>") |
| 878 |
self.assertEqual(dom1.count(dom2), 1) |
| 879 |
self.assertEqual(dom2.count(dom1), 1) |
| 880 |
|
| 881 |
dom2 = parse_html("<p>foo</p><p>bar</p>") |
| 882 |
self.assertEqual(dom2.count(dom1), 1) |
| 883 |
|
| 884 |
dom2 = parse_html("<p>foo foo</p><p>foo</p>") |
| 885 |
self.assertEqual(dom2.count("foo"), 3) |
| 886 |
|
| 887 |
dom2 = parse_html('<p class="bar">foo</p>') |
| 888 |
self.assertEqual(dom2.count("bar"), 0) |
| 889 |
self.assertEqual(dom2.count("class"), 0) |
| 890 |
self.assertEqual(dom2.count("p"), 0) |
| 891 |
self.assertEqual(dom2.count("o"), 2) |
| 892 |
|
| 893 |
dom2 = parse_html("<p>foo</p><p>foo</p>") |
| 894 |
self.assertEqual(dom2.count(dom1), 2) |
| 895 |
|
| 896 |
dom2 = parse_html('<div><p>foo<input type=""></p><p>foo</p></div>') |
| 897 |
self.assertEqual(dom2.count(dom1), 1) |
| 898 |
|
| 899 |
dom2 = parse_html("<div><div><p>foo</p></div></div>") |
| 900 |
self.assertEqual(dom2.count(dom1), 1) |
| 901 |
|
| 902 |
dom2 = parse_html("<p>foo<p>foo</p></p>") |
| 903 |
self.assertEqual(dom2.count(dom1), 1) |
| 904 |
|
| 905 |
dom2 = parse_html("<p>foo<p>bar</p></p>") |
| 906 |
self.assertEqual(dom2.count(dom1), 0) |
| 907 |
|
| 908 |
# HTML with a root element contains the same HTML with no root element. |
| 909 |
dom1 = parse_html("<p>foo</p><p>bar</p>") |
| 910 |
dom2 = parse_html("<div><p>foo</p><p>bar</p></div>") |
| 911 |
self.assertEqual(dom2.count(dom1), 1) |
| 912 |
|
| 913 |
# Target of search is a sequence of child elements and appears more |
| 914 |
# than once. |
| 915 |
dom2 = parse_html("<div><p>foo</p><p>bar</p><p>foo</p><p>bar</p></div>") |
| 916 |
self.assertEqual(dom2.count(dom1), 2) |
| 917 |
|
| 918 |
# Searched HTML has additional children. |
| 919 |
dom1 = parse_html("<a/><b/>") |
| 920 |
dom2 = parse_html("<a/><b/><c/>") |
| 921 |
self.assertEqual(dom2.count(dom1), 1) |
| 922 |
|
| 923 |
# No match found in children. |
| 924 |
dom1 = parse_html("<b/><a/>") |
| 925 |
self.assertEqual(dom2.count(dom1), 0) |
| 926 |
|
| 927 |
# Target of search found among children and grandchildren. |
| 928 |
dom1 = parse_html("<b/><b/>") |
| 929 |
dom2 = parse_html("<a><b/><b/></a><b/><b/>") |
| 930 |
self.assertEqual(dom2.count(dom1), 2) |
| 931 |
|
| 932 |
def test_root_element_escaped_html(self): |
| 933 |
html = "<br>" |
| 934 |
parsed = parse_html(html) |
| 935 |
self.assertEqual(str(parsed), html) |
| 936 |
|
| 937 |
def test_parsing_errors(self): |
| 938 |
with self.assertRaises(AssertionError): |
| 939 |
self.assertHTMLEqual("<p>", "") |
| 940 |
with self.assertRaises(AssertionError): |
| 941 |
self.assertHTMLEqual("", "<p>") |
| 942 |
error_msg = ( |
| 943 |
"First argument is not valid HTML:\n" |
| 944 |
"('Unexpected end tag `div` (Line 1, Column 6)', (1, 6))" |
| 945 |
) |
| 946 |
with self.assertRaisesMessage(AssertionError, error_msg): |
| 947 |
self.assertHTMLEqual("< div></div>", "<div></div>") |
| 948 |
with self.assertRaises(HTMLParseError): |
| 949 |
parse_html("</p>") |
| 950 |
|
| 951 |
def test_escaped_html_errors(self): |
| 952 |
msg = "<p>\n<foo>\n</p> != <p>\n<foo>\n</p>\n" |
| 953 |
with self.assertRaisesMessage(AssertionError, msg): |
| 954 |
self.assertHTMLEqual("<p><foo></p>", "<p><foo></p>") |
| 955 |
with self.assertRaisesMessage(AssertionError, msg): |
| 956 |
self.assertHTMLEqual("<p><foo></p>", "<p><foo></p>") |
| 957 |
|
| 958 |
def test_contains_html(self): |
| 959 |
response = HttpResponse("""<body> |
| 960 |
This is a form: <form method="get"> |
| 961 |
<input type="text" name="Hello" /> |
| 962 |
</form></body>""") |
| 963 |
|
| 964 |
self.assertNotContains(response, "<input name='Hello' type='text'>") |
| 965 |
self.assertContains(response, '<form method="get">') |
| 966 |
|
| 967 |
self.assertContains(response, "<input name='Hello' type='text'>", html=True) |
| 968 |
self.assertNotContains(response, '<form method="get">', html=True) |
| 969 |
|
| 970 |
invalid_response = HttpResponse("""<body <bad>>""") |
| 971 |
|
| 972 |
with self.assertRaises(AssertionError): |
| 973 |
self.assertContains(invalid_response, "<p></p>") |
| 974 |
|
| 975 |
with self.assertRaises(AssertionError): |
| 976 |
self.assertContains(response, '<p "whats" that>') |
| 977 |
|
| 978 |
def test_unicode_handling(self): |
| 979 |
response = HttpResponse( |
| 980 |
'<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>' |
| 981 |
) |
| 982 |
self.assertContains( |
| 983 |
response, |
| 984 |
'<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>', |
| 985 |
html=True, |
| 986 |
) |
| 987 |
|
| 988 |
|
| 989 |
class InHTMLTests(SimpleTestCase): |
| 990 |
def test_needle_msg(self): |
| 991 |
msg = ( |
| 992 |
"False is not true : Couldn't find '<b>Hello</b>' in the following " |
| 993 |
"response\n'<p>Test</p>'" |
| 994 |
) |
| 995 |
with self.assertRaisesMessage(AssertionError, msg): |
| 996 |
self.assertInHTML("<b>Hello</b>", "<p>Test</p>") |
| 997 |
|
| 998 |
def test_msg_prefix(self): |
| 999 |
msg = ( |
| 1000 |
"False is not true : Prefix: Couldn't find '<b>Hello</b>' in the following " |
| 1001 |
'response\n\'<input type="text" name="Hello" />\'' |
| 1002 |
) |
| 1003 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1004 |
self.assertInHTML( |
| 1005 |
"<b>Hello</b>", |
| 1006 |
'<input type="text" name="Hello" />', |
| 1007 |
msg_prefix="Prefix", |
| 1008 |
) |
| 1009 |
|
| 1010 |
def test_count_msg_prefix(self): |
| 1011 |
msg = ( |
| 1012 |
"2 != 1 : Prefix: Found 2 instances of '<b>Hello</b>' (expected 1) in the " |
| 1013 |
"following response\n'<b>Hello</b><b>Hello</b>'" |
| 1014 |
"" |
| 1015 |
) |
| 1016 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1017 |
self.assertInHTML( |
| 1018 |
"<b>Hello</b>", |
| 1019 |
"<b>Hello</b><b>Hello</b>", |
| 1020 |
count=1, |
| 1021 |
msg_prefix="Prefix", |
| 1022 |
) |
| 1023 |
|
| 1024 |
def test_base(self): |
| 1025 |
haystack = "<p><b>Hello</b> <span>there</span>! Hi <span>there</span>!</p>" |
| 1026 |
|
| 1027 |
self.assertInHTML("<b>Hello</b>", haystack=haystack) |
| 1028 |
msg = f"Couldn't find '<p>Howdy</p>' in the following response\n{haystack!r}" |
| 1029 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1030 |
self.assertInHTML("<p>Howdy</p>", haystack) |
| 1031 |
|
| 1032 |
self.assertInHTML("<span>there</span>", haystack=haystack, count=2) |
| 1033 |
msg = ( |
| 1034 |
"Found 1 instances of '<b>Hello</b>' (expected 2) in the following response" |
| 1035 |
f"\n{haystack!r}" |
| 1036 |
) |
| 1037 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1038 |
self.assertInHTML("<b>Hello</b>", haystack=haystack, count=2) |
| 1039 |
|
| 1040 |
def test_long_haystack(self): |
| 1041 |
haystack = ( |
| 1042 |
"<p>This is a very very very very very very very very long message which " |
| 1043 |
"exceeds the max limit of truncation.</p>" |
| 1044 |
) |
| 1045 |
msg = f"Couldn't find '<b>Hello</b>' in the following response\n{haystack!r}" |
| 1046 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1047 |
self.assertInHTML("<b>Hello</b>", haystack) |
| 1048 |
|
| 1049 |
msg = ( |
| 1050 |
"Found 0 instances of '<b>This</b>' (expected 3) in the following response" |
| 1051 |
f"\n{haystack!r}" |
| 1052 |
) |
| 1053 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1054 |
self.assertInHTML("<b>This</b>", haystack, 3) |
| 1055 |
|
| 1056 |
def test_assert_not_in_html(self): |
| 1057 |
haystack = "<p><b>Hello</b> <span>there</span>! Hi <span>there</span>!</p>" |
| 1058 |
self.assertNotInHTML("<b>Hi</b>", haystack=haystack) |
| 1059 |
msg = ( |
| 1060 |
"'<b>Hello</b>' unexpectedly found in the following response" |
| 1061 |
f"\n{haystack!r}" |
| 1062 |
) |
| 1063 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1064 |
self.assertNotInHTML("<b>Hello</b>", haystack=haystack) |
| 1065 |
|
| 1066 |
|
| 1067 |
class JSONEqualTests(SimpleTestCase): |
| 1068 |
def test_simple_equal(self): |
| 1069 |
json1 = '{"attr1": "foo", "attr2":"baz"}' |
| 1070 |
json2 = '{"attr1": "foo", "attr2":"baz"}' |
| 1071 |
self.assertJSONEqual(json1, json2) |
| 1072 |
|
| 1073 |
def test_simple_equal_unordered(self): |
| 1074 |
json1 = '{"attr1": "foo", "attr2":"baz"}' |
| 1075 |
json2 = '{"attr2":"baz", "attr1": "foo"}' |
| 1076 |
self.assertJSONEqual(json1, json2) |
| 1077 |
|
| 1078 |
def test_simple_equal_raise(self): |
| 1079 |
json1 = '{"attr1": "foo", "attr2":"baz"}' |
| 1080 |
json2 = '{"attr2":"baz"}' |
| 1081 |
with self.assertRaises(AssertionError): |
| 1082 |
self.assertJSONEqual(json1, json2) |
| 1083 |
|
| 1084 |
def test_equal_parsing_errors(self): |
| 1085 |
invalid_json = '{"attr1": "foo, "attr2":"baz"}' |
| 1086 |
valid_json = '{"attr1": "foo", "attr2":"baz"}' |
| 1087 |
with self.assertRaises(AssertionError): |
| 1088 |
self.assertJSONEqual(invalid_json, valid_json) |
| 1089 |
with self.assertRaises(AssertionError): |
| 1090 |
self.assertJSONEqual(valid_json, invalid_json) |
| 1091 |
|
| 1092 |
def test_simple_not_equal(self): |
| 1093 |
json1 = '{"attr1": "foo", "attr2":"baz"}' |
| 1094 |
json2 = '{"attr2":"baz"}' |
| 1095 |
self.assertJSONNotEqual(json1, json2) |
| 1096 |
|
| 1097 |
def test_simple_not_equal_raise(self): |
| 1098 |
json1 = '{"attr1": "foo", "attr2":"baz"}' |
| 1099 |
json2 = '{"attr1": "foo", "attr2":"baz"}' |
| 1100 |
with self.assertRaises(AssertionError): |
| 1101 |
self.assertJSONNotEqual(json1, json2) |
| 1102 |
|
| 1103 |
def test_not_equal_parsing_errors(self): |
| 1104 |
invalid_json = '{"attr1": "foo, "attr2":"baz"}' |
| 1105 |
valid_json = '{"attr1": "foo", "attr2":"baz"}' |
| 1106 |
with self.assertRaises(AssertionError): |
| 1107 |
self.assertJSONNotEqual(invalid_json, valid_json) |
| 1108 |
with self.assertRaises(AssertionError): |
| 1109 |
self.assertJSONNotEqual(valid_json, invalid_json) |
| 1110 |
|
| 1111 |
def test_method_frames_ignored_by_unittest(self): |
| 1112 |
try: |
| 1113 |
self.assertJSONEqual("1", "2") |
| 1114 |
except AssertionError: |
| 1115 |
exc_type, exc, tb = sys.exc_info() |
| 1116 |
|
| 1117 |
result = unittest.TestResult() |
| 1118 |
result.addFailure(self, (exc_type, exc, tb)) |
| 1119 |
stack = traceback.extract_tb(exc.__traceback__) |
| 1120 |
self.assertEqual(len(stack), 1) |
| 1121 |
# Top element in the stack is this method, not assertJSONEqual. |
| 1122 |
self.assertEqual(stack[-1].name, "test_method_frames_ignored_by_unittest") |
| 1123 |
|
| 1124 |
|
| 1125 |
class XMLEqualTests(SimpleTestCase): |
| 1126 |
def test_simple_equal(self): |
| 1127 |
xml1 = "<elem attr1='a' attr2='b' />" |
| 1128 |
xml2 = "<elem attr1='a' attr2='b' />" |
| 1129 |
self.assertXMLEqual(xml1, xml2) |
| 1130 |
|
| 1131 |
def test_simple_equal_unordered(self): |
| 1132 |
xml1 = "<elem attr1='a' attr2='b' />" |
| 1133 |
xml2 = "<elem attr2='b' attr1='a' />" |
| 1134 |
self.assertXMLEqual(xml1, xml2) |
| 1135 |
|
| 1136 |
def test_simple_equal_raise(self): |
| 1137 |
xml1 = "<elem attr1='a' />" |
| 1138 |
xml2 = "<elem attr2='b' attr1='a' />" |
| 1139 |
with self.assertRaises(AssertionError): |
| 1140 |
self.assertXMLEqual(xml1, xml2) |
| 1141 |
|
| 1142 |
def test_simple_equal_raises_message(self): |
| 1143 |
xml1 = "<elem attr1='a' />" |
| 1144 |
xml2 = "<elem attr2='b' attr1='a' />" |
| 1145 |
|
| 1146 |
msg = """{xml1} != {xml2} |
| 1147 |
- <elem attr1='a' /> |
| 1148 |
+ <elem attr2='b' attr1='a' /> |
| 1149 |
? ++++++++++ |
| 1150 |
""".format(xml1=repr(xml1), xml2=repr(xml2)) |
| 1151 |
|
| 1152 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1153 |
self.assertXMLEqual(xml1, xml2) |
| 1154 |
|
| 1155 |
def test_simple_not_equal(self): |
| 1156 |
xml1 = "<elem attr1='a' attr2='c' />" |
| 1157 |
xml2 = "<elem attr1='a' attr2='b' />" |
| 1158 |
self.assertXMLNotEqual(xml1, xml2) |
| 1159 |
|
| 1160 |
def test_simple_not_equal_raise(self): |
| 1161 |
xml1 = "<elem attr1='a' attr2='b' />" |
| 1162 |
xml2 = "<elem attr2='b' attr1='a' />" |
| 1163 |
with self.assertRaises(AssertionError): |
| 1164 |
self.assertXMLNotEqual(xml1, xml2) |
| 1165 |
|
| 1166 |
def test_parsing_errors(self): |
| 1167 |
xml_unvalid = "<elem attr1='a attr2='b' />" |
| 1168 |
xml2 = "<elem attr2='b' attr1='a' />" |
| 1169 |
with self.assertRaises(AssertionError): |
| 1170 |
self.assertXMLNotEqual(xml_unvalid, xml2) |
| 1171 |
|
| 1172 |
def test_comment_root(self): |
| 1173 |
xml1 = "<?xml version='1.0'?><!-- comment1 --><elem attr1='a' attr2='b' />" |
| 1174 |
xml2 = "<?xml version='1.0'?><!-- comment2 --><elem attr2='b' attr1='a' />" |
| 1175 |
self.assertXMLEqual(xml1, xml2) |
| 1176 |
|
| 1177 |
def test_simple_equal_with_leading_or_trailing_whitespace(self): |
| 1178 |
xml1 = "<elem>foo</elem> \t\n" |
| 1179 |
xml2 = " \t\n<elem>foo</elem>" |
| 1180 |
self.assertXMLEqual(xml1, xml2) |
| 1181 |
|
| 1182 |
def test_simple_not_equal_with_whitespace_in_the_middle(self): |
| 1183 |
xml1 = "<elem>foo</elem><elem>bar</elem>" |
| 1184 |
xml2 = "<elem>foo</elem> <elem>bar</elem>" |
| 1185 |
self.assertXMLNotEqual(xml1, xml2) |
| 1186 |
|
| 1187 |
def test_doctype_root(self): |
| 1188 |
xml1 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example1.dtd"><root />' |
| 1189 |
xml2 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example2.dtd"><root />' |
| 1190 |
self.assertXMLEqual(xml1, xml2) |
| 1191 |
|
| 1192 |
def test_processing_instruction(self): |
| 1193 |
xml1 = ( |
| 1194 |
'<?xml version="1.0"?>' |
| 1195 |
'<?xml-model href="http://www.example1.com"?><root />' |
| 1196 |
) |
| 1197 |
xml2 = ( |
| 1198 |
'<?xml version="1.0"?>' |
| 1199 |
'<?xml-model href="http://www.example2.com"?><root />' |
| 1200 |
) |
| 1201 |
self.assertXMLEqual(xml1, xml2) |
| 1202 |
self.assertXMLEqual( |
| 1203 |
'<?xml-stylesheet href="style1.xslt" type="text/xsl"?><root />', |
| 1204 |
'<?xml-stylesheet href="style2.xslt" type="text/xsl"?><root />', |
| 1205 |
) |
| 1206 |
|
| 1207 |
|
| 1208 |
class SkippingExtraTests(TestCase): |
| 1209 |
fixtures = ["person.json"] |
| 1210 |
|
| 1211 |
# HACK: This depends on internals of our TestCase subclasses |
| 1212 |
def __call__(self, result=None): |
| 1213 |
# Detect fixture loading by counting SQL queries, should be zero |
| 1214 |
with self.assertNumQueries(0): |
| 1215 |
super().__call__(result) |
| 1216 |
|
| 1217 |
@unittest.skip("Fixture loading should not be performed for skipped tests.") |
| 1218 |
def test_fixtures_are_skipped(self): |
| 1219 |
pass |
| 1220 |
|
| 1221 |
|
| 1222 |
class AssertRaisesMsgTest(SimpleTestCase): |
| 1223 |
def test_assert_raises_message(self): |
| 1224 |
msg = "'Expected message' not found in 'Unexpected message'" |
| 1225 |
# context manager form of assertRaisesMessage() |
| 1226 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1227 |
with self.assertRaisesMessage(ValueError, "Expected message"): |
| 1228 |
raise ValueError("Unexpected message") |
| 1229 |
|
| 1230 |
# callable form |
| 1231 |
def func(): |
| 1232 |
raise ValueError("Unexpected message") |
| 1233 |
|
| 1234 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1235 |
self.assertRaisesMessage(ValueError, "Expected message", func) |
| 1236 |
|
| 1237 |
def test_special_re_chars(self): |
| 1238 |
"""assertRaisesMessage shouldn't interpret RE special chars.""" |
| 1239 |
|
| 1240 |
def func1(): |
| 1241 |
raise ValueError("[.*x+]y?") |
| 1242 |
|
| 1243 |
with self.assertRaisesMessage(ValueError, "[.*x+]y?"): |
| 1244 |
func1() |
| 1245 |
|
| 1246 |
|
| 1247 |
class AssertWarnsMessageTests(SimpleTestCase): |
| 1248 |
def test_context_manager(self): |
| 1249 |
with self.assertWarnsMessage(UserWarning, "Expected message"): |
| 1250 |
warnings.warn("Expected message", UserWarning) |
| 1251 |
|
| 1252 |
def test_context_manager_failure(self): |
| 1253 |
msg = "Expected message' not found in 'Unexpected message'" |
| 1254 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1255 |
with self.assertWarnsMessage(UserWarning, "Expected message"): |
| 1256 |
warnings.warn("Unexpected message", UserWarning) |
| 1257 |
|
| 1258 |
def test_callable(self): |
| 1259 |
def func(): |
| 1260 |
warnings.warn("Expected message", UserWarning) |
| 1261 |
|
| 1262 |
self.assertWarnsMessage(UserWarning, "Expected message", func) |
| 1263 |
|
| 1264 |
def test_special_re_chars(self): |
| 1265 |
def func1(): |
| 1266 |
warnings.warn("[.*x+]y?", UserWarning) |
| 1267 |
|
| 1268 |
with self.assertWarnsMessage(UserWarning, "[.*x+]y?"): |
| 1269 |
func1() |
| 1270 |
|
| 1271 |
|
| 1272 |
class AssertFieldOutputTests(SimpleTestCase): |
| 1273 |
def test_assert_field_output(self): |
| 1274 |
error_invalid = ["Enter a valid email address."] |
| 1275 |
self.assertFieldOutput( |
| 1276 |
EmailField, {"[email protected]": "[email protected]"}, {"aaa": error_invalid} |
| 1277 |
) |
| 1278 |
with self.assertRaises(AssertionError): |
| 1279 |
self.assertFieldOutput( |
| 1280 |
EmailField, |
| 1281 |
{"[email protected]": "[email protected]"}, |
| 1282 |
{"aaa": error_invalid + ["Another error"]}, |
| 1283 |
) |
| 1284 |
with self.assertRaises(AssertionError): |
| 1285 |
self.assertFieldOutput( |
| 1286 |
EmailField, {"[email protected]": "Wrong output"}, {"aaa": error_invalid} |
| 1287 |
) |
| 1288 |
with self.assertRaises(AssertionError): |
| 1289 |
self.assertFieldOutput( |
| 1290 |
EmailField, |
| 1291 |
{"[email protected]": "[email protected]"}, |
| 1292 |
{"aaa": ["Come on, gimme some well formatted data, dude."]}, |
| 1293 |
) |
| 1294 |
|
| 1295 |
def test_custom_required_message(self): |
| 1296 |
class MyCustomField(IntegerField): |
| 1297 |
default_error_messages = { |
| 1298 |
"required": "This is really required.", |
| 1299 |
} |
| 1300 |
|
| 1301 |
self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None) |
| 1302 |
|
| 1303 |
|
| 1304 |
@override_settings(ROOT_URLCONF="test_utils.urls") |
| 1305 |
class AssertURLEqualTests(SimpleTestCase): |
| 1306 |
def test_equal(self): |
| 1307 |
valid_tests = ( |
| 1308 |
("http://example.com/?", "http://example.com/"), |
| 1309 |
("http://example.com/?x=1&", "http://example.com/?x=1"), |
| 1310 |
("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), |
| 1311 |
("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), |
| 1312 |
( |
| 1313 |
"http://example.com/?x=1&y=2&a=1&a=2", |
| 1314 |
"http://example.com/?a=1&a=2&y=2&x=1", |
| 1315 |
), |
| 1316 |
("/path/to/?x=1&y=2&z=3", "/path/to/?z=3&y=2&x=1"), |
| 1317 |
("?x=1&y=2&z=3", "?z=3&y=2&x=1"), |
| 1318 |
("/test_utils/no_template_used/", reverse_lazy("no_template_used")), |
| 1319 |
) |
| 1320 |
for url1, url2 in valid_tests: |
| 1321 |
with self.subTest(url=url1): |
| 1322 |
self.assertURLEqual(url1, url2) |
| 1323 |
|
| 1324 |
def test_not_equal(self): |
| 1325 |
invalid_tests = ( |
| 1326 |
# Protocol must be the same. |
| 1327 |
("http://example.com/", "https://example.com/"), |
| 1328 |
("http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1"), |
| 1329 |
("http://example.com/?x=1&y=bar&x=2", "https://example.com/?y=bar&x=2&x=1"), |
| 1330 |
# Parameters of the same name must be in the same order. |
| 1331 |
("/path/to?a=1&a=2", "/path/to/?a=2&a=1"), |
| 1332 |
) |
| 1333 |
for url1, url2 in invalid_tests: |
| 1334 |
with self.subTest(url=url1), self.assertRaises(AssertionError): |
| 1335 |
self.assertURLEqual(url1, url2) |
| 1336 |
|
| 1337 |
def test_message(self): |
| 1338 |
msg = ( |
| 1339 |
"Expected 'http://example.com/?x=1&x=2' to equal " |
| 1340 |
"'https://example.com/?x=2&x=1'" |
| 1341 |
) |
| 1342 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1343 |
self.assertURLEqual( |
| 1344 |
"http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1" |
| 1345 |
) |
| 1346 |
|
| 1347 |
def test_msg_prefix(self): |
| 1348 |
msg = ( |
| 1349 |
"Prefix: Expected 'http://example.com/?x=1&x=2' to equal " |
| 1350 |
"'https://example.com/?x=2&x=1'" |
| 1351 |
) |
| 1352 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1353 |
self.assertURLEqual( |
| 1354 |
"http://example.com/?x=1&x=2", |
| 1355 |
"https://example.com/?x=2&x=1", |
| 1356 |
msg_prefix="Prefix", |
| 1357 |
) |
| 1358 |
|
| 1359 |
|
| 1360 |
class TestForm(Form): |
| 1361 |
field = CharField() |
| 1362 |
|
| 1363 |
def clean_field(self): |
| 1364 |
value = self.cleaned_data.get("field", "") |
| 1365 |
if value == "invalid": |
| 1366 |
raise ValidationError("invalid value") |
| 1367 |
return value |
| 1368 |
|
| 1369 |
def clean(self): |
| 1370 |
if self.cleaned_data.get("field") == "invalid_non_field": |
| 1371 |
raise ValidationError("non-field error") |
| 1372 |
return self.cleaned_data |
| 1373 |
|
| 1374 |
@classmethod |
| 1375 |
def _get_cleaned_form(cls, field_value): |
| 1376 |
form = cls({"field": field_value}) |
| 1377 |
form.full_clean() |
| 1378 |
return form |
| 1379 |
|
| 1380 |
@classmethod |
| 1381 |
def valid(cls): |
| 1382 |
return cls._get_cleaned_form("valid") |
| 1383 |
|
| 1384 |
@classmethod |
| 1385 |
def invalid(cls, nonfield=False): |
| 1386 |
return cls._get_cleaned_form("invalid_non_field" if nonfield else "invalid") |
| 1387 |
|
| 1388 |
|
| 1389 |
class TestFormset(formset_factory(TestForm)): |
| 1390 |
@classmethod |
| 1391 |
def _get_cleaned_formset(cls, field_value): |
| 1392 |
formset = cls( |
| 1393 |
{ |
| 1394 |
"form-TOTAL_FORMS": "1", |
| 1395 |
"form-INITIAL_FORMS": "0", |
| 1396 |
"form-0-field": field_value, |
| 1397 |
} |
| 1398 |
) |
| 1399 |
formset.full_clean() |
| 1400 |
return formset |
| 1401 |
|
| 1402 |
@classmethod |
| 1403 |
def valid(cls): |
| 1404 |
return cls._get_cleaned_formset("valid") |
| 1405 |
|
| 1406 |
@classmethod |
| 1407 |
def invalid(cls, nonfield=False, nonform=False): |
| 1408 |
if nonform: |
| 1409 |
formset = cls({}, error_messages={"missing_management_form": "error"}) |
| 1410 |
formset.full_clean() |
| 1411 |
return formset |
| 1412 |
return cls._get_cleaned_formset("invalid_non_field" if nonfield else "invalid") |
| 1413 |
|
| 1414 |
|
| 1415 |
class AssertFormErrorTests(SimpleTestCase): |
| 1416 |
def test_single_error(self): |
| 1417 |
self.assertFormError(TestForm.invalid(), "field", "invalid value") |
| 1418 |
|
| 1419 |
def test_error_list(self): |
| 1420 |
self.assertFormError(TestForm.invalid(), "field", ["invalid value"]) |
| 1421 |
|
| 1422 |
def test_empty_errors_valid_form(self): |
| 1423 |
self.assertFormError(TestForm.valid(), "field", []) |
| 1424 |
|
| 1425 |
def test_empty_errors_valid_form_non_field_errors(self): |
| 1426 |
self.assertFormError(TestForm.valid(), None, []) |
| 1427 |
|
| 1428 |
def test_field_not_in_form(self): |
| 1429 |
msg = ( |
| 1430 |
"The form <TestForm bound=True, valid=False, fields=(field)> does not " |
| 1431 |
"contain the field 'other_field'." |
| 1432 |
) |
| 1433 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1434 |
self.assertFormError(TestForm.invalid(), "other_field", "invalid value") |
| 1435 |
msg_prefix = "Custom prefix" |
| 1436 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1437 |
self.assertFormError( |
| 1438 |
TestForm.invalid(), |
| 1439 |
"other_field", |
| 1440 |
"invalid value", |
| 1441 |
msg_prefix=msg_prefix, |
| 1442 |
) |
| 1443 |
|
| 1444 |
def test_field_with_no_errors(self): |
| 1445 |
msg = ( |
| 1446 |
"The errors of field 'field' on form <TestForm bound=True, valid=True, " |
| 1447 |
"fields=(field)> don't match." |
| 1448 |
) |
| 1449 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1450 |
self.assertFormError(TestForm.valid(), "field", "invalid value") |
| 1451 |
self.assertIn("[] != ['invalid value']", str(ctx.exception)) |
| 1452 |
msg_prefix = "Custom prefix" |
| 1453 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1454 |
self.assertFormError( |
| 1455 |
TestForm.valid(), "field", "invalid value", msg_prefix=msg_prefix |
| 1456 |
) |
| 1457 |
|
| 1458 |
def test_field_with_different_error(self): |
| 1459 |
msg = ( |
| 1460 |
"The errors of field 'field' on form <TestForm bound=True, valid=False, " |
| 1461 |
"fields=(field)> don't match." |
| 1462 |
) |
| 1463 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1464 |
self.assertFormError(TestForm.invalid(), "field", "other error") |
| 1465 |
self.assertIn("['invalid value'] != ['other error']", str(ctx.exception)) |
| 1466 |
msg_prefix = "Custom prefix" |
| 1467 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1468 |
self.assertFormError( |
| 1469 |
TestForm.invalid(), "field", "other error", msg_prefix=msg_prefix |
| 1470 |
) |
| 1471 |
|
| 1472 |
def test_unbound_form(self): |
| 1473 |
msg = ( |
| 1474 |
"The form <TestForm bound=False, valid=Unknown, fields=(field)> is not " |
| 1475 |
"bound, it will never have any errors." |
| 1476 |
) |
| 1477 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1478 |
self.assertFormError(TestForm(), "field", []) |
| 1479 |
msg_prefix = "Custom prefix" |
| 1480 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1481 |
self.assertFormError(TestForm(), "field", [], msg_prefix=msg_prefix) |
| 1482 |
|
| 1483 |
def test_empty_errors_invalid_form(self): |
| 1484 |
msg = ( |
| 1485 |
"The errors of field 'field' on form <TestForm bound=True, valid=False, " |
| 1486 |
"fields=(field)> don't match." |
| 1487 |
) |
| 1488 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1489 |
self.assertFormError(TestForm.invalid(), "field", []) |
| 1490 |
self.assertIn("['invalid value'] != []", str(ctx.exception)) |
| 1491 |
|
| 1492 |
def test_non_field_errors(self): |
| 1493 |
self.assertFormError(TestForm.invalid(nonfield=True), None, "non-field error") |
| 1494 |
|
| 1495 |
def test_different_non_field_errors(self): |
| 1496 |
msg = ( |
| 1497 |
"The non-field errors of form <TestForm bound=True, valid=False, " |
| 1498 |
"fields=(field)> don't match." |
| 1499 |
) |
| 1500 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1501 |
self.assertFormError( |
| 1502 |
TestForm.invalid(nonfield=True), None, "other non-field error" |
| 1503 |
) |
| 1504 |
self.assertIn( |
| 1505 |
"['non-field error'] != ['other non-field error']", str(ctx.exception) |
| 1506 |
) |
| 1507 |
msg_prefix = "Custom prefix" |
| 1508 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1509 |
self.assertFormError( |
| 1510 |
TestForm.invalid(nonfield=True), |
| 1511 |
None, |
| 1512 |
"other non-field error", |
| 1513 |
msg_prefix=msg_prefix, |
| 1514 |
) |
| 1515 |
|
| 1516 |
|
| 1517 |
class AssertFormSetErrorTests(SimpleTestCase): |
| 1518 |
def test_single_error(self): |
| 1519 |
self.assertFormSetError(TestFormset.invalid(), 0, "field", "invalid value") |
| 1520 |
|
| 1521 |
def test_error_list(self): |
| 1522 |
self.assertFormSetError(TestFormset.invalid(), 0, "field", ["invalid value"]) |
| 1523 |
|
| 1524 |
def test_empty_errors_valid_formset(self): |
| 1525 |
self.assertFormSetError(TestFormset.valid(), 0, "field", []) |
| 1526 |
|
| 1527 |
def test_multiple_forms(self): |
| 1528 |
formset = TestFormset( |
| 1529 |
{ |
| 1530 |
"form-TOTAL_FORMS": "2", |
| 1531 |
"form-INITIAL_FORMS": "0", |
| 1532 |
"form-0-field": "valid", |
| 1533 |
"form-1-field": "invalid", |
| 1534 |
} |
| 1535 |
) |
| 1536 |
formset.full_clean() |
| 1537 |
self.assertFormSetError(formset, 0, "field", []) |
| 1538 |
self.assertFormSetError(formset, 1, "field", ["invalid value"]) |
| 1539 |
|
| 1540 |
def test_field_not_in_form(self): |
| 1541 |
msg = ( |
| 1542 |
"The form 0 of formset <TestFormset: bound=True valid=False total_forms=1> " |
| 1543 |
"does not contain the field 'other_field'." |
| 1544 |
) |
| 1545 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1546 |
self.assertFormSetError( |
| 1547 |
TestFormset.invalid(), 0, "other_field", "invalid value" |
| 1548 |
) |
| 1549 |
msg_prefix = "Custom prefix" |
| 1550 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1551 |
self.assertFormSetError( |
| 1552 |
TestFormset.invalid(), |
| 1553 |
0, |
| 1554 |
"other_field", |
| 1555 |
"invalid value", |
| 1556 |
msg_prefix=msg_prefix, |
| 1557 |
) |
| 1558 |
|
| 1559 |
def test_field_with_no_errors(self): |
| 1560 |
msg = ( |
| 1561 |
"The errors of field 'field' on form 0 of formset <TestFormset: bound=True " |
| 1562 |
"valid=True total_forms=1> don't match." |
| 1563 |
) |
| 1564 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1565 |
self.assertFormSetError(TestFormset.valid(), 0, "field", "invalid value") |
| 1566 |
self.assertIn("[] != ['invalid value']", str(ctx.exception)) |
| 1567 |
msg_prefix = "Custom prefix" |
| 1568 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1569 |
self.assertFormSetError( |
| 1570 |
TestFormset.valid(), 0, "field", "invalid value", msg_prefix=msg_prefix |
| 1571 |
) |
| 1572 |
|
| 1573 |
def test_field_with_different_error(self): |
| 1574 |
msg = ( |
| 1575 |
"The errors of field 'field' on form 0 of formset <TestFormset: bound=True " |
| 1576 |
"valid=False total_forms=1> don't match." |
| 1577 |
) |
| 1578 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1579 |
self.assertFormSetError(TestFormset.invalid(), 0, "field", "other error") |
| 1580 |
self.assertIn("['invalid value'] != ['other error']", str(ctx.exception)) |
| 1581 |
msg_prefix = "Custom prefix" |
| 1582 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1583 |
self.assertFormSetError( |
| 1584 |
TestFormset.invalid(), 0, "field", "other error", msg_prefix=msg_prefix |
| 1585 |
) |
| 1586 |
|
| 1587 |
def test_unbound_formset(self): |
| 1588 |
msg = ( |
| 1589 |
"The formset <TestFormset: bound=False valid=Unknown total_forms=1> is not " |
| 1590 |
"bound, it will never have any errors." |
| 1591 |
) |
| 1592 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1593 |
self.assertFormSetError(TestFormset(), 0, "field", []) |
| 1594 |
|
| 1595 |
def test_empty_errors_invalid_formset(self): |
| 1596 |
msg = ( |
| 1597 |
"The errors of field 'field' on form 0 of formset <TestFormset: bound=True " |
| 1598 |
"valid=False total_forms=1> don't match." |
| 1599 |
) |
| 1600 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1601 |
self.assertFormSetError(TestFormset.invalid(), 0, "field", []) |
| 1602 |
self.assertIn("['invalid value'] != []", str(ctx.exception)) |
| 1603 |
|
| 1604 |
def test_non_field_errors(self): |
| 1605 |
self.assertFormSetError( |
| 1606 |
TestFormset.invalid(nonfield=True), 0, None, "non-field error" |
| 1607 |
) |
| 1608 |
|
| 1609 |
def test_different_non_field_errors(self): |
| 1610 |
msg = ( |
| 1611 |
"The non-field errors of form 0 of formset <TestFormset: bound=True " |
| 1612 |
"valid=False total_forms=1> don't match." |
| 1613 |
) |
| 1614 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1615 |
self.assertFormSetError( |
| 1616 |
TestFormset.invalid(nonfield=True), 0, None, "other non-field error" |
| 1617 |
) |
| 1618 |
self.assertIn( |
| 1619 |
"['non-field error'] != ['other non-field error']", str(ctx.exception) |
| 1620 |
) |
| 1621 |
msg_prefix = "Custom prefix" |
| 1622 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1623 |
self.assertFormSetError( |
| 1624 |
TestFormset.invalid(nonfield=True), |
| 1625 |
0, |
| 1626 |
None, |
| 1627 |
"other non-field error", |
| 1628 |
msg_prefix=msg_prefix, |
| 1629 |
) |
| 1630 |
|
| 1631 |
def test_no_non_field_errors(self): |
| 1632 |
msg = ( |
| 1633 |
"The non-field errors of form 0 of formset <TestFormset: bound=True " |
| 1634 |
"valid=False total_forms=1> don't match." |
| 1635 |
) |
| 1636 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1637 |
self.assertFormSetError(TestFormset.invalid(), 0, None, "non-field error") |
| 1638 |
self.assertIn("[] != ['non-field error']", str(ctx.exception)) |
| 1639 |
msg_prefix = "Custom prefix" |
| 1640 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1641 |
self.assertFormSetError( |
| 1642 |
TestFormset.invalid(), 0, None, "non-field error", msg_prefix=msg_prefix |
| 1643 |
) |
| 1644 |
|
| 1645 |
def test_non_form_errors(self): |
| 1646 |
self.assertFormSetError(TestFormset.invalid(nonform=True), None, None, "error") |
| 1647 |
|
| 1648 |
def test_different_non_form_errors(self): |
| 1649 |
msg = ( |
| 1650 |
"The non-form errors of formset <TestFormset: bound=True valid=False " |
| 1651 |
"total_forms=0> don't match." |
| 1652 |
) |
| 1653 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1654 |
self.assertFormSetError( |
| 1655 |
TestFormset.invalid(nonform=True), None, None, "other error" |
| 1656 |
) |
| 1657 |
self.assertIn("['error'] != ['other error']", str(ctx.exception)) |
| 1658 |
msg_prefix = "Custom prefix" |
| 1659 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1660 |
self.assertFormSetError( |
| 1661 |
TestFormset.invalid(nonform=True), |
| 1662 |
None, |
| 1663 |
None, |
| 1664 |
"other error", |
| 1665 |
msg_prefix=msg_prefix, |
| 1666 |
) |
| 1667 |
|
| 1668 |
def test_no_non_form_errors(self): |
| 1669 |
msg = ( |
| 1670 |
"The non-form errors of formset <TestFormset: bound=True valid=False " |
| 1671 |
"total_forms=1> don't match." |
| 1672 |
) |
| 1673 |
with self.assertRaisesMessage(AssertionError, msg) as ctx: |
| 1674 |
self.assertFormSetError(TestFormset.invalid(), None, None, "error") |
| 1675 |
self.assertIn("[] != ['error']", str(ctx.exception)) |
| 1676 |
msg_prefix = "Custom prefix" |
| 1677 |
with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): |
| 1678 |
self.assertFormSetError( |
| 1679 |
TestFormset.invalid(), |
| 1680 |
None, |
| 1681 |
None, |
| 1682 |
"error", |
| 1683 |
msg_prefix=msg_prefix, |
| 1684 |
) |
| 1685 |
|
| 1686 |
def test_non_form_errors_with_field(self): |
| 1687 |
msg = "You must use field=None with form_index=None." |
| 1688 |
with self.assertRaisesMessage(ValueError, msg): |
| 1689 |
self.assertFormSetError( |
| 1690 |
TestFormset.invalid(nonform=True), None, "field", "error" |
| 1691 |
) |
| 1692 |
|
| 1693 |
def test_form_index_too_big(self): |
| 1694 |
msg = ( |
| 1695 |
"The formset <TestFormset: bound=True valid=False total_forms=1> only has " |
| 1696 |
"1 form." |
| 1697 |
) |
| 1698 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1699 |
self.assertFormSetError(TestFormset.invalid(), 2, "field", "error") |
| 1700 |
|
| 1701 |
def test_form_index_too_big_plural(self): |
| 1702 |
formset = TestFormset( |
| 1703 |
{ |
| 1704 |
"form-TOTAL_FORMS": "2", |
| 1705 |
"form-INITIAL_FORMS": "0", |
| 1706 |
"form-0-field": "valid", |
| 1707 |
"form-1-field": "valid", |
| 1708 |
} |
| 1709 |
) |
| 1710 |
formset.full_clean() |
| 1711 |
msg = ( |
| 1712 |
"The formset <TestFormset: bound=True valid=True total_forms=2> only has 2 " |
| 1713 |
"forms." |
| 1714 |
) |
| 1715 |
with self.assertRaisesMessage(AssertionError, msg): |
| 1716 |
self.assertFormSetError(formset, 2, "field", "error") |
| 1717 |
|
| 1718 |
|
| 1719 |
class FirstUrls: |
| 1720 |
urlpatterns = [path("first/", empty_response, name="first")] |
| 1721 |
|
| 1722 |
|
| 1723 |
class SecondUrls: |
| 1724 |
urlpatterns = [path("second/", empty_response, name="second")] |
| 1725 |
|
| 1726 |
|
| 1727 |
class SetupTestEnvironmentTests(SimpleTestCase): |
| 1728 |
def test_setup_test_environment_calling_more_than_once(self): |
| 1729 |
with self.assertRaisesMessage( |
| 1730 |
RuntimeError, "setup_test_environment() was already called" |
| 1731 |
): |
| 1732 |
setup_test_environment() |
| 1733 |
|
| 1734 |
def test_allowed_hosts(self): |
| 1735 |
for type_ in (list, tuple): |
| 1736 |
with self.subTest(type_=type_): |
| 1737 |
allowed_hosts = type_("*") |
| 1738 |
with mock.patch("django.test.utils._TestState") as x: |
| 1739 |
del x.saved_data |
| 1740 |
with self.settings(ALLOWED_HOSTS=allowed_hosts): |
| 1741 |
setup_test_environment() |
| 1742 |
self.assertEqual(settings.ALLOWED_HOSTS, ["*", "testserver"]) |
| 1743 |
|
| 1744 |
|
| 1745 |
class OverrideSettingsTests(SimpleTestCase): |
| 1746 |
# #21518 -- If neither override_settings nor a setting_changed receiver |
| 1747 |
# clears the URL cache between tests, then one of test_first or |
| 1748 |
# test_second will fail. |
| 1749 |
|
| 1750 |
@override_settings(ROOT_URLCONF=FirstUrls) |
| 1751 |
def test_urlconf_first(self): |
| 1752 |
reverse("first") |
| 1753 |
|
| 1754 |
@override_settings(ROOT_URLCONF=SecondUrls) |
| 1755 |
def test_urlconf_second(self): |
| 1756 |
reverse("second") |
| 1757 |
|
| 1758 |
def test_urlconf_cache(self): |
| 1759 |
with self.assertRaises(NoReverseMatch): |
| 1760 |
reverse("first") |
| 1761 |
with self.assertRaises(NoReverseMatch): |
| 1762 |
reverse("second") |
| 1763 |
|
| 1764 |
with override_settings(ROOT_URLCONF=FirstUrls): |
| 1765 |
self.client.get(reverse("first")) |
| 1766 |
with self.assertRaises(NoReverseMatch): |
| 1767 |
reverse("second") |
| 1768 |
|
| 1769 |
with override_settings(ROOT_URLCONF=SecondUrls): |
| 1770 |
with self.assertRaises(NoReverseMatch): |
| 1771 |
reverse("first") |
| 1772 |
self.client.get(reverse("second")) |
| 1773 |
|
| 1774 |
self.client.get(reverse("first")) |
| 1775 |
with self.assertRaises(NoReverseMatch): |
| 1776 |
reverse("second") |
| 1777 |
|
| 1778 |
with self.assertRaises(NoReverseMatch): |
| 1779 |
reverse("first") |
| 1780 |
with self.assertRaises(NoReverseMatch): |
| 1781 |
reverse("second") |
| 1782 |
|
| 1783 |
def test_override_media_root(self): |
| 1784 |
""" |
| 1785 |
Overriding the MEDIA_ROOT setting should be reflected in the |
| 1786 |
base_location attribute of django.core.files.storage.default_storage. |
| 1787 |
""" |
| 1788 |
self.assertEqual(default_storage.base_location, "") |
| 1789 |
with self.settings(MEDIA_ROOT="test_value"): |
| 1790 |
self.assertEqual(default_storage.base_location, "test_value") |
| 1791 |
|
| 1792 |
def test_override_media_url(self): |
| 1793 |
""" |
| 1794 |
Overriding the MEDIA_URL setting should be reflected in the |
| 1795 |
base_url attribute of django.core.files.storage.default_storage. |
| 1796 |
""" |
| 1797 |
self.assertEqual(default_storage.base_location, "") |
| 1798 |
with self.settings(MEDIA_URL="/test_value/"): |
| 1799 |
self.assertEqual(default_storage.base_url, "/test_value/") |
| 1800 |
|
| 1801 |
def test_override_file_upload_permissions(self): |
| 1802 |
""" |
| 1803 |
Overriding the FILE_UPLOAD_PERMISSIONS setting should be reflected in |
| 1804 |
the file_permissions_mode attribute of |
| 1805 |
django.core.files.storage.default_storage. |
| 1806 |
""" |
| 1807 |
self.assertEqual(default_storage.file_permissions_mode, 0o644) |
| 1808 |
with self.settings(FILE_UPLOAD_PERMISSIONS=0o777): |
| 1809 |
self.assertEqual(default_storage.file_permissions_mode, 0o777) |
| 1810 |
|
| 1811 |
def test_override_file_upload_directory_permissions(self): |
| 1812 |
""" |
| 1813 |
Overriding the FILE_UPLOAD_DIRECTORY_PERMISSIONS setting should be |
| 1814 |
reflected in the directory_permissions_mode attribute of |
| 1815 |
django.core.files.storage.default_storage. |
| 1816 |
""" |
| 1817 |
self.assertIsNone(default_storage.directory_permissions_mode) |
| 1818 |
with self.settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777): |
| 1819 |
self.assertEqual(default_storage.directory_permissions_mode, 0o777) |
| 1820 |
|
| 1821 |
def test_override_database_routers(self): |
| 1822 |
""" |
| 1823 |
Overriding DATABASE_ROUTERS should update the base router. |
| 1824 |
""" |
| 1825 |
test_routers = [object()] |
| 1826 |
with self.settings(DATABASE_ROUTERS=test_routers): |
| 1827 |
self.assertEqual(router.routers, test_routers) |
| 1828 |
|
| 1829 |
def test_override_static_url(self): |
| 1830 |
""" |
| 1831 |
Overriding the STATIC_URL setting should be reflected in the |
| 1832 |
base_url attribute of |
| 1833 |
django.contrib.staticfiles.storage.staticfiles_storage. |
| 1834 |
""" |
| 1835 |
with self.settings(STATIC_URL="/test/"): |
| 1836 |
self.assertEqual(staticfiles_storage.base_url, "/test/") |
| 1837 |
|
| 1838 |
def test_override_static_root(self): |
| 1839 |
""" |
| 1840 |
Overriding the STATIC_ROOT setting should be reflected in the |
| 1841 |
location attribute of |
| 1842 |
django.contrib.staticfiles.storage.staticfiles_storage. |
| 1843 |
""" |
| 1844 |
with self.settings(STATIC_ROOT="/tmp/test"): |
| 1845 |
self.assertEqual(staticfiles_storage.location, os.path.abspath("/tmp/test")) |
| 1846 |
|
| 1847 |
def test_override_staticfiles_storage(self): |
| 1848 |
""" |
| 1849 |
Overriding the STORAGES setting should be reflected in |
| 1850 |
the value of django.contrib.staticfiles.storage.staticfiles_storage. |
| 1851 |
""" |
| 1852 |
new_class = "ManifestStaticFilesStorage" |
| 1853 |
new_storage = "django.contrib.staticfiles.storage." + new_class |
| 1854 |
with self.settings( |
| 1855 |
STORAGES={STATICFILES_STORAGE_ALIAS: {"BACKEND": new_storage}} |
| 1856 |
): |
| 1857 |
self.assertEqual(staticfiles_storage.__class__.__name__, new_class) |
| 1858 |
|
| 1859 |
def test_override_staticfiles_finders(self): |
| 1860 |
""" |
| 1861 |
Overriding the STATICFILES_FINDERS setting should be reflected in |
| 1862 |
the return value of django.contrib.staticfiles.finders.get_finders. |
| 1863 |
""" |
| 1864 |
current = get_finders() |
| 1865 |
self.assertGreater(len(list(current)), 1) |
| 1866 |
finders = ["django.contrib.staticfiles.finders.FileSystemFinder"] |
| 1867 |
with self.settings(STATICFILES_FINDERS=finders): |
| 1868 |
self.assertEqual(len(list(get_finders())), len(finders)) |
| 1869 |
|
| 1870 |
def test_override_staticfiles_dirs(self): |
| 1871 |
""" |
| 1872 |
Overriding the STATICFILES_DIRS setting should be reflected in |
| 1873 |
the locations attribute of the |
| 1874 |
django.contrib.staticfiles.finders.FileSystemFinder instance. |
| 1875 |
""" |
| 1876 |
finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") |
| 1877 |
test_path = "/tmp/test" |
| 1878 |
expected_location = ("", test_path) |
| 1879 |
self.assertNotIn(expected_location, finder.locations) |
| 1880 |
with self.settings(STATICFILES_DIRS=[test_path]): |
| 1881 |
finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") |
| 1882 |
self.assertIn(expected_location, finder.locations) |
| 1883 |
|
| 1884 |
|
| 1885 |
@skipUnlessDBFeature("supports_transactions") |
| 1886 |
class TestBadSetUpTestData(TestCase): |
| 1887 |
""" |
| 1888 |
An exception in setUpTestData() shouldn't leak a transaction which would |
| 1889 |
cascade across the rest of the test suite. |
| 1890 |
""" |
| 1891 |
|
| 1892 |
class MyException(Exception): |
| 1893 |
pass |
| 1894 |
|
| 1895 |
@classmethod |
| 1896 |
def setUpClass(cls): |
| 1897 |
try: |
| 1898 |
super().setUpClass() |
| 1899 |
except cls.MyException: |
| 1900 |
cls._in_atomic_block = connection.in_atomic_block |
| 1901 |
|
| 1902 |
@classmethod |
| 1903 |
def tearDownClass(Cls): |
| 1904 |
# override to avoid a second cls._rollback_atomics() which would fail. |
| 1905 |
# Normal setUpClass() methods won't have exception handling so this |
| 1906 |
# method wouldn't typically be run. |
| 1907 |
pass |
| 1908 |
|
| 1909 |
@classmethod |
| 1910 |
def setUpTestData(cls): |
| 1911 |
# Simulate a broken setUpTestData() method. |
| 1912 |
raise cls.MyException() |
| 1913 |
|
| 1914 |
def test_failure_in_setUpTestData_should_rollback_transaction(self): |
| 1915 |
# setUpTestData() should call _rollback_atomics() so that the |
| 1916 |
# transaction doesn't leak. |
| 1917 |
self.assertFalse(self._in_atomic_block) |
| 1918 |
|
| 1919 |
|
| 1920 |
@skipUnlessDBFeature("supports_transactions") |
| 1921 |
class CaptureOnCommitCallbacksTests(TestCase): |
| 1922 |
databases = {"default", "other"} |
| 1923 |
callback_called = False |
| 1924 |
|
| 1925 |
def enqueue_callback(self, using="default"): |
| 1926 |
def hook(): |
| 1927 |
self.callback_called = True |
| 1928 |
|
| 1929 |
transaction.on_commit(hook, using=using) |
| 1930 |
|
| 1931 |
def test_no_arguments(self): |
| 1932 |
with self.captureOnCommitCallbacks() as callbacks: |
| 1933 |
self.enqueue_callback() |
| 1934 |
|
| 1935 |
self.assertEqual(len(callbacks), 1) |
| 1936 |
self.assertIs(self.callback_called, False) |
| 1937 |
callbacks[0]() |
| 1938 |
self.assertIs(self.callback_called, True) |
| 1939 |
|
| 1940 |
def test_using(self): |
| 1941 |
with self.captureOnCommitCallbacks(using="other") as callbacks: |
| 1942 |
self.enqueue_callback(using="other") |
| 1943 |
|
| 1944 |
self.assertEqual(len(callbacks), 1) |
| 1945 |
self.assertIs(self.callback_called, False) |
| 1946 |
callbacks[0]() |
| 1947 |
self.assertIs(self.callback_called, True) |
| 1948 |
|
| 1949 |
def test_different_using(self): |
| 1950 |
with self.captureOnCommitCallbacks(using="default") as callbacks: |
| 1951 |
self.enqueue_callback(using="other") |
| 1952 |
|
| 1953 |
self.assertEqual(callbacks, []) |
| 1954 |
|
| 1955 |
def test_execute(self): |
| 1956 |
with self.captureOnCommitCallbacks(execute=True) as callbacks: |
| 1957 |
self.enqueue_callback() |
| 1958 |
|
| 1959 |
self.assertEqual(len(callbacks), 1) |
| 1960 |
self.assertIs(self.callback_called, True) |
| 1961 |
|
| 1962 |
def test_pre_callback(self): |
| 1963 |
def pre_hook(): |
| 1964 |
pass |
| 1965 |
|
| 1966 |
transaction.on_commit(pre_hook, using="default") |
| 1967 |
with self.captureOnCommitCallbacks() as callbacks: |
| 1968 |
self.enqueue_callback() |
| 1969 |
|
| 1970 |
self.assertEqual(len(callbacks), 1) |
| 1971 |
self.assertNotEqual(callbacks[0], pre_hook) |
| 1972 |
|
| 1973 |
def test_with_rolled_back_savepoint(self): |
| 1974 |
with self.captureOnCommitCallbacks() as callbacks: |
| 1975 |
try: |
| 1976 |
with transaction.atomic(): |
| 1977 |
self.enqueue_callback() |
| 1978 |
raise IntegrityError |
| 1979 |
except IntegrityError: |
| 1980 |
# Inner transaction.atomic() has been rolled back. |
| 1981 |
pass |
| 1982 |
|
| 1983 |
self.assertEqual(callbacks, []) |
| 1984 |
|
| 1985 |
def test_execute_recursive(self): |
| 1986 |
with self.captureOnCommitCallbacks(execute=True) as callbacks: |
| 1987 |
transaction.on_commit(self.enqueue_callback) |
| 1988 |
|
| 1989 |
self.assertEqual(len(callbacks), 2) |
| 1990 |
self.assertIs(self.callback_called, True) |
| 1991 |
|
| 1992 |
def test_execute_tree(self): |
| 1993 |
""" |
| 1994 |
A visualisation of the callback tree tested. Each node is expected to |
| 1995 |
be visited only once: |
| 1996 |
|
| 1997 |
└─branch_1 |
| 1998 |
├─branch_2 |
| 1999 |
│ ├─leaf_1 |
| 2000 |
│ └─leaf_2 |
| 2001 |
└─leaf_3 |
| 2002 |
""" |
| 2003 |
branch_1_call_counter = 0 |
| 2004 |
branch_2_call_counter = 0 |
| 2005 |
leaf_1_call_counter = 0 |
| 2006 |
leaf_2_call_counter = 0 |
| 2007 |
leaf_3_call_counter = 0 |
| 2008 |
|
| 2009 |
def leaf_1(): |
| 2010 |
nonlocal leaf_1_call_counter |
| 2011 |
leaf_1_call_counter += 1 |
| 2012 |
|
| 2013 |
def leaf_2(): |
| 2014 |
nonlocal leaf_2_call_counter |
| 2015 |
leaf_2_call_counter += 1 |
| 2016 |
|
| 2017 |
def leaf_3(): |
| 2018 |
nonlocal leaf_3_call_counter |
| 2019 |
leaf_3_call_counter += 1 |
| 2020 |
|
| 2021 |
def branch_1(): |
| 2022 |
nonlocal branch_1_call_counter |
| 2023 |
branch_1_call_counter += 1 |
| 2024 |
transaction.on_commit(branch_2) |
| 2025 |
transaction.on_commit(leaf_3) |
| 2026 |
|
| 2027 |
def branch_2(): |
| 2028 |
nonlocal branch_2_call_counter |
| 2029 |
branch_2_call_counter += 1 |
| 2030 |
transaction.on_commit(leaf_1) |
| 2031 |
transaction.on_commit(leaf_2) |
| 2032 |
|
| 2033 |
with self.captureOnCommitCallbacks(execute=True) as callbacks: |
| 2034 |
transaction.on_commit(branch_1) |
| 2035 |
|
| 2036 |
self.assertEqual(branch_1_call_counter, 1) |
| 2037 |
self.assertEqual(branch_2_call_counter, 1) |
| 2038 |
self.assertEqual(leaf_1_call_counter, 1) |
| 2039 |
self.assertEqual(leaf_2_call_counter, 1) |
| 2040 |
self.assertEqual(leaf_3_call_counter, 1) |
| 2041 |
|
| 2042 |
self.assertEqual(callbacks, [branch_1, branch_2, leaf_3, leaf_1, leaf_2]) |
| 2043 |
|
| 2044 |
def test_execute_robust(self): |
| 2045 |
class MyException(Exception): |
| 2046 |
pass |
| 2047 |
|
| 2048 |
def hook(): |
| 2049 |
self.callback_called = True |
| 2050 |
raise MyException("robust callback") |
| 2051 |
|
| 2052 |
with self.assertLogs("django.test", "ERROR") as cm: |
| 2053 |
with self.captureOnCommitCallbacks(execute=True) as callbacks: |
| 2054 |
transaction.on_commit(hook, robust=True) |
| 2055 |
|
| 2056 |
self.assertEqual(len(callbacks), 1) |
| 2057 |
self.assertIs(self.callback_called, True) |
| 2058 |
|
| 2059 |
log_record = cm.records[0] |
| 2060 |
self.assertEqual( |
| 2061 |
log_record.getMessage(), |
| 2062 |
"Error calling CaptureOnCommitCallbacksTests.test_execute_robust.<locals>." |
| 2063 |
"hook in on_commit() (robust callback).", |
| 2064 |
) |
| 2065 |
self.assertIsNotNone(log_record.exc_info) |
| 2066 |
raised_exception = log_record.exc_info[1] |
| 2067 |
self.assertIsInstance(raised_exception, MyException) |
| 2068 |
self.assertEqual(str(raised_exception), "robust callback") |
| 2069 |
|
| 2070 |
|
| 2071 |
class DisallowedDatabaseQueriesTests(SimpleTestCase): |
| 2072 |
def test_disallowed_database_connections(self): |
| 2073 |
expected_message = ( |
| 2074 |
"Database connections to 'default' are not allowed in SimpleTestCase " |
| 2075 |
"subclasses. Either subclass TestCase or TransactionTestCase to " |
| 2076 |
"ensure proper test isolation or add 'default' to " |
| 2077 |
"test_utils.tests.DisallowedDatabaseQueriesTests.databases to " |
| 2078 |
"silence this failure." |
| 2079 |
) |
| 2080 |
with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): |
| 2081 |
connection.connect() |
| 2082 |
with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): |
| 2083 |
connection.temporary_connection() |
| 2084 |
|
| 2085 |
def test_disallowed_database_queries(self): |
| 2086 |
expected_message = ( |
| 2087 |
"Database queries to 'default' are not allowed in SimpleTestCase " |
| 2088 |
"subclasses. Either subclass TestCase or TransactionTestCase to " |
| 2089 |
"ensure proper test isolation or add 'default' to " |
| 2090 |
"test_utils.tests.DisallowedDatabaseQueriesTests.databases to " |
| 2091 |
"silence this failure." |
| 2092 |
) |
| 2093 |
with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): |
| 2094 |
Car.objects.first() |
| 2095 |
|
| 2096 |
def test_disallowed_database_chunked_cursor_queries(self): |
| 2097 |
expected_message = ( |
| 2098 |
"Database queries to 'default' are not allowed in SimpleTestCase " |
| 2099 |
"subclasses. Either subclass TestCase or TransactionTestCase to " |
| 2100 |
"ensure proper test isolation or add 'default' to " |
| 2101 |
"test_utils.tests.DisallowedDatabaseQueriesTests.databases to " |
| 2102 |
"silence this failure." |
| 2103 |
) |
| 2104 |
with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): |
| 2105 |
next(Car.objects.iterator()) |
| 2106 |
|
| 2107 |
def test_disallowed_thread_database_connection(self): |
| 2108 |
expected_message = ( |
| 2109 |
"Database threaded connections to 'default' are not allowed in " |
| 2110 |
"SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase" |
| 2111 |
" to ensure proper test isolation or add 'default' to " |
| 2112 |
"test_utils.tests.DisallowedDatabaseQueriesTests.databases to " |
| 2113 |
"silence this failure." |
| 2114 |
) |
| 2115 |
|
| 2116 |
exceptions = [] |
| 2117 |
|
| 2118 |
def thread_func(): |
| 2119 |
try: |
| 2120 |
Car.objects.first() |
| 2121 |
except DatabaseOperationForbidden as e: |
| 2122 |
exceptions.append(e) |
| 2123 |
|
| 2124 |
t = threading.Thread(target=thread_func) |
| 2125 |
t.start() |
| 2126 |
t.join() |
| 2127 |
self.assertEqual(len(exceptions), 1) |
| 2128 |
self.assertEqual(exceptions[0].args[0], expected_message) |
| 2129 |
|
| 2130 |
|
| 2131 |
class AllowedDatabaseQueriesTests(SimpleTestCase): |
| 2132 |
databases = {"default"} |
| 2133 |
|
| 2134 |
def test_allowed_database_queries(self): |
| 2135 |
Car.objects.first() |
| 2136 |
|
| 2137 |
def test_allowed_database_chunked_cursor_queries(self): |
| 2138 |
next(Car.objects.iterator(), None) |
| 2139 |
|
| 2140 |
def test_allowed_threaded_database_queries(self): |
| 2141 |
connections_dict = {} |
| 2142 |
|
| 2143 |
def thread_func(): |
| 2144 |
# Passing django.db.connection between threads doesn't work while |
| 2145 |
# connections[DEFAULT_DB_ALIAS] does. |
| 2146 |
from django.db import connections |
| 2147 |
|
| 2148 |
connection = connections["default"] |
| 2149 |
|
| 2150 |
next(Car.objects.iterator(), None) |
| 2151 |
|
| 2152 |
# Allow thread sharing so the connection can be closed by the main |
| 2153 |
# thread. |
| 2154 |
connection.inc_thread_sharing() |
| 2155 |
connections_dict[id(connection)] = connection |
| 2156 |
|
| 2157 |
try: |
| 2158 |
t = threading.Thread(target=thread_func) |
| 2159 |
t.start() |
| 2160 |
t.join() |
| 2161 |
finally: |
| 2162 |
# Finish by closing the connections opened by the other threads |
| 2163 |
# (the connection opened in the main thread will automatically be |
| 2164 |
# closed on teardown). |
| 2165 |
for conn in connections_dict.values(): |
| 2166 |
if conn is not connection and conn.allow_thread_sharing: |
| 2167 |
conn.validate_thread_sharing() |
| 2168 |
conn._close() |
| 2169 |
conn.dec_thread_sharing() |
| 2170 |
|
| 2171 |
def test_allowed_database_copy_queries(self): |
| 2172 |
new_connection = connection.copy("dynamic_connection") |
| 2173 |
try: |
| 2174 |
with new_connection.cursor() as cursor: |
| 2175 |
sql = f"SELECT 1{new_connection.features.bare_select_suffix}" |
| 2176 |
cursor.execute(sql) |
| 2177 |
self.assertEqual(cursor.fetchone()[0], 1) |
| 2178 |
finally: |
| 2179 |
new_connection.validate_thread_sharing() |
| 2180 |
new_connection._close() |
| 2181 |
if hasattr(new_connection, "close_pool"): |
| 2182 |
new_connection.close_pool() |
| 2183 |
|
| 2184 |
|
| 2185 |
class DatabaseAliasTests(SimpleTestCase): |
| 2186 |
def setUp(self): |
| 2187 |
self.addCleanup(setattr, self.__class__, "databases", self.databases) |
| 2188 |
|
| 2189 |
def test_no_close_match(self): |
| 2190 |
self.__class__.databases = {"void"} |
| 2191 |
message = ( |
| 2192 |
"test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is " |
| 2193 |
"not defined in settings.DATABASES." |
| 2194 |
) |
| 2195 |
with self.assertRaisesMessage(ImproperlyConfigured, message): |
| 2196 |
self._validate_databases() |
| 2197 |
|
| 2198 |
def test_close_match(self): |
| 2199 |
self.__class__.databases = {"defualt"} |
| 2200 |
message = ( |
| 2201 |
"test_utils.tests.DatabaseAliasTests.databases refers to 'defualt' which " |
| 2202 |
"is not defined in settings.DATABASES. Did you mean 'default'?" |
| 2203 |
) |
| 2204 |
with self.assertRaisesMessage(ImproperlyConfigured, message): |
| 2205 |
self._validate_databases() |
| 2206 |
|
| 2207 |
def test_match(self): |
| 2208 |
self.__class__.databases = {"default", "other"} |
| 2209 |
self.assertEqual(self._validate_databases(), frozenset({"default", "other"})) |
| 2210 |
|
| 2211 |
def test_all(self): |
| 2212 |
self.__class__.databases = "__all__" |
| 2213 |
self.assertEqual(self._validate_databases(), frozenset(connections)) |
| 2214 |
|
| 2215 |
|
| 2216 |
@isolate_apps("test_utils", attr_name="class_apps") |
| 2217 |
class IsolatedAppsTests(SimpleTestCase): |
| 2218 |
def test_installed_apps(self): |
| 2219 |
self.assertEqual( |
| 2220 |
[app_config.label for app_config in self.class_apps.get_app_configs()], |
| 2221 |
["test_utils"], |
| 2222 |
) |
| 2223 |
|
| 2224 |
def test_class_decoration(self): |
| 2225 |
class ClassDecoration(models.Model): |
| 2226 |
pass |
| 2227 |
|
| 2228 |
self.assertEqual(ClassDecoration._meta.apps, self.class_apps) |
| 2229 |
|
| 2230 |
@isolate_apps("test_utils", kwarg_name="method_apps") |
| 2231 |
def test_method_decoration(self, method_apps): |
| 2232 |
class MethodDecoration(models.Model): |
| 2233 |
pass |
| 2234 |
|
| 2235 |
self.assertEqual(MethodDecoration._meta.apps, method_apps) |
| 2236 |
|
| 2237 |
def test_context_manager(self): |
| 2238 |
with isolate_apps("test_utils") as context_apps: |
| 2239 |
|
| 2240 |
class ContextManager(models.Model): |
| 2241 |
pass |
| 2242 |
|
| 2243 |
self.assertEqual(ContextManager._meta.apps, context_apps) |
| 2244 |
|
| 2245 |
@isolate_apps("test_utils", kwarg_name="method_apps") |
| 2246 |
def test_nested(self, method_apps): |
| 2247 |
class MethodDecoration(models.Model): |
| 2248 |
pass |
| 2249 |
|
| 2250 |
with isolate_apps("test_utils") as context_apps: |
| 2251 |
|
| 2252 |
class ContextManager(models.Model): |
| 2253 |
pass |
| 2254 |
|
| 2255 |
with isolate_apps("test_utils") as nested_context_apps: |
| 2256 |
|
| 2257 |
class NestedContextManager(models.Model): |
| 2258 |
pass |
| 2259 |
|
| 2260 |
self.assertEqual(MethodDecoration._meta.apps, method_apps) |
| 2261 |
self.assertEqual(ContextManager._meta.apps, context_apps) |
| 2262 |
self.assertEqual(NestedContextManager._meta.apps, nested_context_apps) |
| 2263 |
|
| 2264 |
|
| 2265 |
class DoNothingDecorator(TestContextDecorator): |
| 2266 |
def enable(self): |
| 2267 |
pass |
| 2268 |
|
| 2269 |
def disable(self): |
| 2270 |
pass |
| 2271 |
|
| 2272 |
|
| 2273 |
class TestContextDecoratorTests(SimpleTestCase): |
| 2274 |
@mock.patch.object(DoNothingDecorator, "disable") |
| 2275 |
def test_exception_in_setup(self, mock_disable): |
| 2276 |
"""An exception is setUp() is reraised after disable() is called.""" |
| 2277 |
|
| 2278 |
class ExceptionInSetUp(unittest.TestCase): |
| 2279 |
def setUp(self): |
| 2280 |
raise NotImplementedError("reraised") |
| 2281 |
|
| 2282 |
decorator = DoNothingDecorator() |
| 2283 |
decorated_test_class = decorator.__call__(ExceptionInSetUp)() |
| 2284 |
self.assertFalse(mock_disable.called) |
| 2285 |
with self.assertRaisesMessage(NotImplementedError, "reraised"): |
| 2286 |
decorated_test_class.setUp() |
| 2287 |
decorated_test_class.doCleanups() |
| 2288 |
self.assertTrue(mock_disable.called) |
| 2289 |
|
| 2290 |
def test_cleanups_run_after_tearDown(self): |
| 2291 |
calls = [] |
| 2292 |
|
| 2293 |
class SaveCallsDecorator(TestContextDecorator): |
| 2294 |
def enable(self): |
| 2295 |
calls.append("enable") |
| 2296 |
|
| 2297 |
def disable(self): |
| 2298 |
calls.append("disable") |
| 2299 |
|
| 2300 |
class AddCleanupInSetUp(unittest.TestCase): |
| 2301 |
def setUp(self): |
| 2302 |
calls.append("setUp") |
| 2303 |
self.addCleanup(lambda: calls.append("cleanup")) |
| 2304 |
|
| 2305 |
decorator = SaveCallsDecorator() |
| 2306 |
decorated_test_class = decorator.__call__(AddCleanupInSetUp)() |
| 2307 |
decorated_test_class.setUp() |
| 2308 |
decorated_test_class.tearDown() |
| 2309 |
decorated_test_class.doCleanups() |
| 2310 |
self.assertEqual(calls, ["enable", "setUp", "cleanup", "disable"]) |