Tests: simplify test_settings maintenance

If no version-specific tests.test_settings.settings* file
exists for the current Django version, fall back to an
earlier settings file.

- runtests.py find latest settings_N_M earlier than or
  matching Django version N.M being tested, rather than
  requiring exact match
- remove test_settings files that were just duplicates
  of earlier versions
This commit is contained in:
medmunds
2023-02-07 14:53:02 -08:00
parent f71813f820
commit ec864f5165
4 changed files with 42 additions and 372 deletions

View File

@@ -5,14 +5,53 @@
# runtests.py [tests.test_x tests.test_y.SomeTestCase ...]
import os
import re
import sys
import warnings
from pathlib import Path
import django
from django.conf import settings
from django.test.utils import get_runner
def find_test_settings():
"""
Return dotted path to Django settings compatible with current Django version.
Finds highest tests.test_settings.settings_N_M.py where N.M is <= Django version.
(Generally, default Django settings don't change meaningfully between Django
releases, so this will fall back to the most recent settings when there isn't an
exact match for the current version, while allowing creation of new settings
files to test significant differences.)
"""
django_version = django.VERSION[:2] # (major, minor)
found_version = None # (major, minor)
found_path = None
for settings_path in Path("tests/test_settings").glob("settings_*.py"):
try:
(major, minor) = re.match(
r"settings_(\d+)_(\d+)\.py", settings_path.name
).groups()
settings_version = (int(major), int(minor))
except (AttributeError, TypeError, ValueError):
raise ValueError(
f"File '{settings_path!s}' doesn't match settings_N_M.py"
) from None
if settings_version <= django_version:
if found_version is None or settings_version > found_version:
found_version = settings_version
found_path = settings_path
if found_path is None:
raise ValueError(f"No suitable test_settings for Django {django.__version__}")
# Convert Path("test/test_settings/settings_N_M.py")
# to dotted module "test.test_settings.settings_N_M":
return ".".join(found_path.with_suffix("").parts)
def setup_and_run_tests(test_labels=None):
"""Discover and run project tests. Returns number of failures."""
test_labels = test_labels or ["tests"]
@@ -32,9 +71,9 @@ def setup_and_run_tests(test_labels=None):
# show DeprecationWarning and other default-ignored warnings:
warnings.simplefilter("default")
os.environ["DJANGO_SETTINGS_MODULE"] = (
"tests.test_settings.settings_%d_%d" % django.VERSION[:2]
)
settings_module = find_test_settings()
print(f"Using settings module {settings_module!r}.")
os.environ["DJANGO_SETTINGS_MODULE"] = settings_module
django.setup()
TestRunner = get_runner(settings)