authentik.root.test_runner
Integrate ./manage.py test with pytest
1"""Integrate ./manage.py test with pytest""" 2 3import os 4import re 5from argparse import ArgumentParser 6from unittest import TestCase 7from unittest.mock import patch 8 9import freezegun 10import pytest 11from django.conf import settings 12from django.contrib.contenttypes.models import ContentType 13from django.test.runner import DiscoverRunner 14from structlog.stdlib import get_logger 15 16from authentik.events.context_processors.asn import ASN_CONTEXT_PROCESSOR 17from authentik.events.context_processors.geoip import GEOIP_CONTEXT_PROCESSOR 18from authentik.lib.config import CONFIG 19from authentik.lib.tracing import init as tracing_init 20from authentik.root.signals import post_startup, pre_startup, startup 21from authentik.tasks.test import use_test_broker 22 23# globally set maxDiff to none to show full assert error 24TestCase.maxDiff = None 25 26 27def get_docker_tag() -> str: 28 """Get docker-tag based off of CI variables""" 29 env_pr_branch = "GITHUB_HEAD_REF" 30 default_branch = "GITHUB_REF" 31 branch_name = os.environ.get(default_branch, "main") 32 if os.environ.get(env_pr_branch, "") != "": 33 branch_name = os.environ[env_pr_branch] 34 branch_name = re.sub(r"[^a-zA-Z0-9-.]", "-", branch_name.replace("refs/heads/", "")) 35 return f"gh-{branch_name}" 36 37 38def patched__get_ct_cached(app_label, codename): 39 """Caches `ContentType` instances like its `QuerySet` does.""" 40 return ContentType.objects.get(app_label=app_label, permission__codename=codename) 41 42 43class PytestTestRunner(DiscoverRunner): # pragma: no cover 44 """Runs pytest to discover and run tests.""" 45 46 def __init__(self, **kwargs): 47 super().__init__(**kwargs) 48 self.logger = get_logger().bind(runner="pytest") 49 50 self.args = [] 51 if self.failfast: 52 self.args.append("--exitfirst") 53 if self.keepdb: 54 self.args.append("--reuse-db") 55 56 if kwargs.get("randomly_seed", None): 57 self.args.append(f"--randomly-seed={kwargs['randomly_seed']}") 58 if kwargs.get("no_capture", False): 59 self.args.append("--capture=no") 60 61 if kwargs.get("count", None): 62 self.args.append("--flake-finder") 63 self.args.append(f"--flake-runs={kwargs['count']}") 64 65 self._setup_test_environment() 66 67 def _setup_test_environment(self): 68 """Configure test environment settings""" 69 settings.TEST = True 70 settings.DRAMATIQ["test"] = True 71 72 # Test-specific configuration 73 test_config = { 74 "events.context_processors.geoip": "tests/geoip/GeoLite2-City-Test.mmdb", 75 "events.context_processors.asn": "tests/geoip/GeoLite2-ASN-Test.mmdb", 76 "blueprints_dir": "./blueprints", 77 "outposts.container_image_base": f"ghcr.io/goauthentik/dev-%(type)s:{get_docker_tag()}", 78 "outposts.disable_embedded_outpost": False, 79 "error_reporting.sample_rate": 0, 80 "error_reporting.environment": "testing", 81 "error_reporting.send_pii": True, 82 } 83 84 for key, value in test_config.items(): 85 CONFIG.set(key, value) 86 87 ASN_CONTEXT_PROCESSOR.load() 88 GEOIP_CONTEXT_PROCESSOR.load() 89 90 tracing_init() 91 self.logger.debug("Test environment configured") 92 93 self.task_broker = use_test_broker() 94 95 # kubernetes>=37 lazily imports pydantic models via module __getattr__, which fails 96 # when freezegun scans module attributes while datetime is patched 97 freezegun.configure(extend_ignore_list=["cryptography", "kubernetes"]) 98 99 # Send startup signals 100 pre_startup.send(sender=self, mode="test") 101 startup.send(sender=self, mode="test") 102 post_startup.send(sender=self, mode="test") 103 104 @classmethod 105 def add_arguments(cls, parser: ArgumentParser): 106 """Add more pytest-specific arguments""" 107 DiscoverRunner.add_arguments(parser) 108 default_seed = None 109 if seed := os.getenv("CI_TEST_SEED"): 110 default_seed = int(seed) 111 parser.add_argument( 112 "--randomly-seed", 113 type=int, 114 help="Set the seed that pytest-randomly uses (int), or pass the special value 'last'" 115 "to reuse the seed from the previous run." 116 "Default behaviour: use random.Random().getrandbits(32), so the seed is" 117 "different on each run.", 118 default=default_seed, 119 ) 120 parser.add_argument( 121 "--no-capture", 122 action="store_true", 123 help="Disable any capturing of stdout/stderr during tests.", 124 ) 125 parser.add_argument("--count", type=int, help="Re-run selected tests n times") 126 127 def _validate_test_label(self, label: str) -> bool: 128 """Validate test label format""" 129 if not label: 130 return False 131 132 # Check for invalid characters, but allow forward slashes and colons 133 # for paths and pytest markers 134 invalid_chars = set('\\*?"<>|') 135 if any(c in label for c in invalid_chars): 136 self.logger.error("Invalid characters in test label", label=label) 137 return False 138 139 return True 140 141 def run_tests(self, test_labels: list[str], extra_tests=None, **kwargs): 142 """Run pytest and return the exitcode. 143 144 It translates some of Django's test command option to pytest's. 145 It is supported to only run specific classes and methods using 146 a dotted module name i.e. foo.bar[.Class[.method]] 147 148 The extra_tests argument has been deprecated since Django 5.x 149 It is kept for compatibility with PyCharm's Django test runner. 150 """ 151 if not test_labels: 152 self.logger.error("No test files specified") 153 return 1 154 155 for label in test_labels: 156 if not self._validate_test_label(label): 157 return 1 158 159 valid_label_found = False 160 label_as_path = os.path.abspath(label) 161 162 # File path has been specified 163 if os.path.exists(label_as_path): 164 self.args.append(label_as_path) 165 valid_label_found = True 166 elif "::" in label: 167 self.args.append(label) 168 valid_label_found = True 169 else: 170 # Check if the label is a dotted module path 171 path_pieces = label.split(".") 172 for i in range(-1, -3, -1): 173 try: 174 path = os.path.join(*path_pieces[:i]) + ".py" 175 if os.path.exists(path): 176 if i < -1: 177 path_method = path + "::" + "::".join(path_pieces[i:]) 178 self.args.append(path_method) 179 else: 180 self.args.append(path) 181 valid_label_found = True 182 break 183 except TypeError, IndexError: 184 continue 185 186 if not valid_label_found: 187 self.logger.error("Test file not found", label=label) 188 return 1 189 190 self.logger.info("Running tests", test_files=self.args) 191 with patch("guardian.shortcuts._get_ct_cached", patched__get_ct_cached): 192 try: 193 ret = pytest.main(self.args) 194 self.task_broker.close() 195 return ret 196 except Exception as exc: # noqa 197 self.logger.error("Error running tests", exc=exc, test_files=self.args) 198 return 1
def
get_docker_tag() -> str:
28def get_docker_tag() -> str: 29 """Get docker-tag based off of CI variables""" 30 env_pr_branch = "GITHUB_HEAD_REF" 31 default_branch = "GITHUB_REF" 32 branch_name = os.environ.get(default_branch, "main") 33 if os.environ.get(env_pr_branch, "") != "": 34 branch_name = os.environ[env_pr_branch] 35 branch_name = re.sub(r"[^a-zA-Z0-9-.]", "-", branch_name.replace("refs/heads/", "")) 36 return f"gh-{branch_name}"
Get docker-tag based off of CI variables
def
patched__get_ct_cached(app_label, codename):
39def patched__get_ct_cached(app_label, codename): 40 """Caches `ContentType` instances like its `QuerySet` does.""" 41 return ContentType.objects.get(app_label=app_label, permission__codename=codename)
Caches ContentType instances like its QuerySet does.
class
PytestTestRunner(django.test.runner.DiscoverRunner):
44class PytestTestRunner(DiscoverRunner): # pragma: no cover 45 """Runs pytest to discover and run tests.""" 46 47 def __init__(self, **kwargs): 48 super().__init__(**kwargs) 49 self.logger = get_logger().bind(runner="pytest") 50 51 self.args = [] 52 if self.failfast: 53 self.args.append("--exitfirst") 54 if self.keepdb: 55 self.args.append("--reuse-db") 56 57 if kwargs.get("randomly_seed", None): 58 self.args.append(f"--randomly-seed={kwargs['randomly_seed']}") 59 if kwargs.get("no_capture", False): 60 self.args.append("--capture=no") 61 62 if kwargs.get("count", None): 63 self.args.append("--flake-finder") 64 self.args.append(f"--flake-runs={kwargs['count']}") 65 66 self._setup_test_environment() 67 68 def _setup_test_environment(self): 69 """Configure test environment settings""" 70 settings.TEST = True 71 settings.DRAMATIQ["test"] = True 72 73 # Test-specific configuration 74 test_config = { 75 "events.context_processors.geoip": "tests/geoip/GeoLite2-City-Test.mmdb", 76 "events.context_processors.asn": "tests/geoip/GeoLite2-ASN-Test.mmdb", 77 "blueprints_dir": "./blueprints", 78 "outposts.container_image_base": f"ghcr.io/goauthentik/dev-%(type)s:{get_docker_tag()}", 79 "outposts.disable_embedded_outpost": False, 80 "error_reporting.sample_rate": 0, 81 "error_reporting.environment": "testing", 82 "error_reporting.send_pii": True, 83 } 84 85 for key, value in test_config.items(): 86 CONFIG.set(key, value) 87 88 ASN_CONTEXT_PROCESSOR.load() 89 GEOIP_CONTEXT_PROCESSOR.load() 90 91 tracing_init() 92 self.logger.debug("Test environment configured") 93 94 self.task_broker = use_test_broker() 95 96 # kubernetes>=37 lazily imports pydantic models via module __getattr__, which fails 97 # when freezegun scans module attributes while datetime is patched 98 freezegun.configure(extend_ignore_list=["cryptography", "kubernetes"]) 99 100 # Send startup signals 101 pre_startup.send(sender=self, mode="test") 102 startup.send(sender=self, mode="test") 103 post_startup.send(sender=self, mode="test") 104 105 @classmethod 106 def add_arguments(cls, parser: ArgumentParser): 107 """Add more pytest-specific arguments""" 108 DiscoverRunner.add_arguments(parser) 109 default_seed = None 110 if seed := os.getenv("CI_TEST_SEED"): 111 default_seed = int(seed) 112 parser.add_argument( 113 "--randomly-seed", 114 type=int, 115 help="Set the seed that pytest-randomly uses (int), or pass the special value 'last'" 116 "to reuse the seed from the previous run." 117 "Default behaviour: use random.Random().getrandbits(32), so the seed is" 118 "different on each run.", 119 default=default_seed, 120 ) 121 parser.add_argument( 122 "--no-capture", 123 action="store_true", 124 help="Disable any capturing of stdout/stderr during tests.", 125 ) 126 parser.add_argument("--count", type=int, help="Re-run selected tests n times") 127 128 def _validate_test_label(self, label: str) -> bool: 129 """Validate test label format""" 130 if not label: 131 return False 132 133 # Check for invalid characters, but allow forward slashes and colons 134 # for paths and pytest markers 135 invalid_chars = set('\\*?"<>|') 136 if any(c in label for c in invalid_chars): 137 self.logger.error("Invalid characters in test label", label=label) 138 return False 139 140 return True 141 142 def run_tests(self, test_labels: list[str], extra_tests=None, **kwargs): 143 """Run pytest and return the exitcode. 144 145 It translates some of Django's test command option to pytest's. 146 It is supported to only run specific classes and methods using 147 a dotted module name i.e. foo.bar[.Class[.method]] 148 149 The extra_tests argument has been deprecated since Django 5.x 150 It is kept for compatibility with PyCharm's Django test runner. 151 """ 152 if not test_labels: 153 self.logger.error("No test files specified") 154 return 1 155 156 for label in test_labels: 157 if not self._validate_test_label(label): 158 return 1 159 160 valid_label_found = False 161 label_as_path = os.path.abspath(label) 162 163 # File path has been specified 164 if os.path.exists(label_as_path): 165 self.args.append(label_as_path) 166 valid_label_found = True 167 elif "::" in label: 168 self.args.append(label) 169 valid_label_found = True 170 else: 171 # Check if the label is a dotted module path 172 path_pieces = label.split(".") 173 for i in range(-1, -3, -1): 174 try: 175 path = os.path.join(*path_pieces[:i]) + ".py" 176 if os.path.exists(path): 177 if i < -1: 178 path_method = path + "::" + "::".join(path_pieces[i:]) 179 self.args.append(path_method) 180 else: 181 self.args.append(path) 182 valid_label_found = True 183 break 184 except TypeError, IndexError: 185 continue 186 187 if not valid_label_found: 188 self.logger.error("Test file not found", label=label) 189 return 1 190 191 self.logger.info("Running tests", test_files=self.args) 192 with patch("guardian.shortcuts._get_ct_cached", patched__get_ct_cached): 193 try: 194 ret = pytest.main(self.args) 195 self.task_broker.close() 196 return ret 197 except Exception as exc: # noqa 198 self.logger.error("Error running tests", exc=exc, test_files=self.args) 199 return 1
Runs pytest to discover and run tests.
PytestTestRunner(**kwargs)
47 def __init__(self, **kwargs): 48 super().__init__(**kwargs) 49 self.logger = get_logger().bind(runner="pytest") 50 51 self.args = [] 52 if self.failfast: 53 self.args.append("--exitfirst") 54 if self.keepdb: 55 self.args.append("--reuse-db") 56 57 if kwargs.get("randomly_seed", None): 58 self.args.append(f"--randomly-seed={kwargs['randomly_seed']}") 59 if kwargs.get("no_capture", False): 60 self.args.append("--capture=no") 61 62 if kwargs.get("count", None): 63 self.args.append("--flake-finder") 64 self.args.append(f"--flake-runs={kwargs['count']}") 65 66 self._setup_test_environment()
@classmethod
def
add_arguments(cls, parser: argparse.ArgumentParser):
105 @classmethod 106 def add_arguments(cls, parser: ArgumentParser): 107 """Add more pytest-specific arguments""" 108 DiscoverRunner.add_arguments(parser) 109 default_seed = None 110 if seed := os.getenv("CI_TEST_SEED"): 111 default_seed = int(seed) 112 parser.add_argument( 113 "--randomly-seed", 114 type=int, 115 help="Set the seed that pytest-randomly uses (int), or pass the special value 'last'" 116 "to reuse the seed from the previous run." 117 "Default behaviour: use random.Random().getrandbits(32), so the seed is" 118 "different on each run.", 119 default=default_seed, 120 ) 121 parser.add_argument( 122 "--no-capture", 123 action="store_true", 124 help="Disable any capturing of stdout/stderr during tests.", 125 ) 126 parser.add_argument("--count", type=int, help="Re-run selected tests n times")
Add more pytest-specific arguments
def
run_tests(self, test_labels: list[str], extra_tests=None, **kwargs):
142 def run_tests(self, test_labels: list[str], extra_tests=None, **kwargs): 143 """Run pytest and return the exitcode. 144 145 It translates some of Django's test command option to pytest's. 146 It is supported to only run specific classes and methods using 147 a dotted module name i.e. foo.bar[.Class[.method]] 148 149 The extra_tests argument has been deprecated since Django 5.x 150 It is kept for compatibility with PyCharm's Django test runner. 151 """ 152 if not test_labels: 153 self.logger.error("No test files specified") 154 return 1 155 156 for label in test_labels: 157 if not self._validate_test_label(label): 158 return 1 159 160 valid_label_found = False 161 label_as_path = os.path.abspath(label) 162 163 # File path has been specified 164 if os.path.exists(label_as_path): 165 self.args.append(label_as_path) 166 valid_label_found = True 167 elif "::" in label: 168 self.args.append(label) 169 valid_label_found = True 170 else: 171 # Check if the label is a dotted module path 172 path_pieces = label.split(".") 173 for i in range(-1, -3, -1): 174 try: 175 path = os.path.join(*path_pieces[:i]) + ".py" 176 if os.path.exists(path): 177 if i < -1: 178 path_method = path + "::" + "::".join(path_pieces[i:]) 179 self.args.append(path_method) 180 else: 181 self.args.append(path) 182 valid_label_found = True 183 break 184 except TypeError, IndexError: 185 continue 186 187 if not valid_label_found: 188 self.logger.error("Test file not found", label=label) 189 return 1 190 191 self.logger.info("Running tests", test_files=self.args) 192 with patch("guardian.shortcuts._get_ct_cached", patched__get_ct_cached): 193 try: 194 ret = pytest.main(self.args) 195 self.task_broker.close() 196 return ret 197 except Exception as exc: # noqa 198 self.logger.error("Error running tests", exc=exc, test_files=self.args) 199 return 1
Run pytest and return the exitcode.
It translates some of Django's test command option to pytest's. It is supported to only run specific classes and methods using a dotted module name i.e. foo.bar[.Class[.method]]
The extra_tests argument has been deprecated since Django 5.x It is kept for compatibility with PyCharm's Django test runner.