|
| 1 | +import socket |
| 2 | +from collections.abc import Callable |
| 3 | +from functools import lru_cache, wraps |
| 4 | +from os import environ, getenv |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from django.db import connection |
| 8 | +from django.db.migrations.loader import MigrationLoader |
| 9 | +from django.test.testcases import TransactionTestCase |
| 10 | +from selenium.common.exceptions import ( |
| 11 | + NoSuchElementException, |
| 12 | + TimeoutException, |
| 13 | + WebDriverException, |
| 14 | +) |
| 15 | +from structlog.stdlib import get_logger |
| 16 | + |
| 17 | +IS_CI = "CI" in environ |
| 18 | +RETRIES = int(environ.get("RETRIES", "3")) if IS_CI else 1 |
| 19 | +SHADOW_ROOT_RETRIES = 5 |
| 20 | + |
| 21 | +JSONType = dict[str, Any] | list[Any] | str | int | float | bool | None |
| 22 | + |
| 23 | + |
| 24 | +def get_local_ip(override=True) -> str: |
| 25 | + """Get the local machine's IP""" |
| 26 | + if (local_ip := getenv("LOCAL_IP")) and override: |
| 27 | + return local_ip |
| 28 | + hostname = socket.gethostname() |
| 29 | + try: |
| 30 | + return socket.gethostbyname(hostname) |
| 31 | + except socket.gaierror: |
| 32 | + return "0.0.0.0" |
| 33 | + |
| 34 | + |
| 35 | +@lru_cache |
| 36 | +def get_loader(): |
| 37 | + """Thin wrapper to lazily get a Migration Loader, only when it's needed |
| 38 | + and only once""" |
| 39 | + return MigrationLoader(connection) |
| 40 | + |
| 41 | + |
| 42 | +def retry(max_retires=RETRIES, exceptions=None): |
| 43 | + """Retry test multiple times. Default to catching Selenium Timeout Exception""" |
| 44 | + |
| 45 | + if not exceptions: |
| 46 | + exceptions = [WebDriverException, TimeoutException, NoSuchElementException] |
| 47 | + |
| 48 | + logger = get_logger() |
| 49 | + |
| 50 | + def retry_actual(func: Callable): |
| 51 | + """Retry test multiple times""" |
| 52 | + count = 1 |
| 53 | + |
| 54 | + @wraps(func) |
| 55 | + def wrapper(self: TransactionTestCase, *args, **kwargs): |
| 56 | + """Run test again if we're below max_retries, including tearDown and |
| 57 | + setUp. Otherwise raise the error""" |
| 58 | + nonlocal count |
| 59 | + try: |
| 60 | + return func(self, *args, **kwargs) |
| 61 | + |
| 62 | + except tuple(exceptions) as exc: |
| 63 | + count += 1 |
| 64 | + if count > max_retires: |
| 65 | + logger.debug("Exceeded retry count", exc=exc, test=self) |
| 66 | + |
| 67 | + raise exc |
| 68 | + logger.debug("Retrying on error", exc=exc, test=self) |
| 69 | + self.tearDown() |
| 70 | + self._post_teardown() |
| 71 | + self._pre_setup() |
| 72 | + self.setUp() |
| 73 | + return wrapper(self, *args, **kwargs) |
| 74 | + |
| 75 | + return wrapper |
| 76 | + |
| 77 | + return retry_actual |
0 commit comments