Skip to content

Commit

Permalink
misc: Use PYTEST_VERSION variable to detect Pytest runs
Browse files Browse the repository at this point in the history
Pytest v8.2 introduced the `PYTEST_VERSION` environment variable [1],
that can be used to check if code is running from within a pytest run.

This way, we can avoid checking the loaded `sys` modules.

[1] https://docs.pytest.org/en/stable/changelog.html#id57
  • Loading branch information
adamantike committed Jul 27, 2024
1 parent 9246f87 commit 749e4d6
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 18 deletions.
3 changes: 3 additions & 0 deletions backend/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,6 @@
"SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON",
"0 4 * * *", # At 4:00 AM every day
)

# TESTING
IS_PYTEST_RUN: Final = bool(os.environ.get("PYTEST_VERSION", False))
5 changes: 2 additions & 3 deletions backend/endpoints/user.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import sys
from pathlib import Path
from typing import Annotated

from anyio import open_file
from config import ASSETS_BASE_PATH
from config import ASSETS_BASE_PATH, IS_PYTEST_RUN
from decorators.auth import protected_route
from endpoints.forms.identity import UserForm
from endpoints.responses import MessageResponse
Expand All @@ -23,7 +22,7 @@
"/users",
(
[]
if "pytest" not in sys.modules and len(db_user_handler.get_admin_users()) == 0
if not IS_PYTEST_RUN and len(db_user_handler.get_admin_users()) == 0
else ["users.write"]
),
status_code=status.HTTP_201_CREATED,
Expand Down
5 changes: 2 additions & 3 deletions backend/handler/metadata/igdb_handler.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import functools
import re
import sys
import time
from typing import Final, NotRequired

import httpx
import pydash
from config import IGDB_CLIENT_ID, IGDB_CLIENT_SECRET
from config import IGDB_CLIENT_ID, IGDB_CLIENT_SECRET, IS_PYTEST_RUN
from fastapi import HTTPException, status
from handler.redis_handler import sync_cache
from logger.logger import log
Expand Down Expand Up @@ -609,7 +608,7 @@ async def _update_twitch_token(self) -> str:

async def get_oauth_token(self) -> str:
# Use a fake token when running tests
if "pytest" in sys.modules:
if IS_PYTEST_RUN:
return "test_token"

if not IGDB_API_ENABLED:
Expand Down
13 changes: 10 additions & 3 deletions backend/handler/redis_handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import sys
from enum import Enum

from config import REDIS_DB, REDIS_HOST, REDIS_PASSWORD, REDIS_PORT, REDIS_USERNAME
from config import (
IS_PYTEST_RUN,
REDIS_DB,
REDIS_HOST,
REDIS_PASSWORD,
REDIS_PORT,
REDIS_USERNAME,
)
from logger.logger import log
from redis import Redis
from redis.asyncio import Redis as AsyncRedis
Expand Down Expand Up @@ -33,7 +40,7 @@ class QueuePrio(Enum):


def __get_sync_cache() -> Redis:
if "pytest" in sys.modules:
if IS_PYTEST_RUN:
# Only import fakeredis when running tests, as it is a test dependency.
from fakeredis import FakeRedis

Expand All @@ -54,7 +61,7 @@ def __get_sync_cache() -> Redis:


def __get_async_cache() -> AsyncRedis:
if "pytest" in sys.modules:
if IS_PYTEST_RUN:
# Only import fakeredis when running tests, as it is a test dependency.
from fakeredis import FakeAsyncRedis

Expand Down
11 changes: 8 additions & 3 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import re
import sys
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager

import alembic.config
import endpoints.sockets.scan # noqa
import uvicorn
from config import DEV_HOST, DEV_PORT, DISABLE_CSRF_PROTECTION, ROMM_AUTH_SECRET_KEY
from config import (
DEV_HOST,
DEV_PORT,
DISABLE_CSRF_PROTECTION,
IS_PYTEST_RUN,
ROMM_AUTH_SECRET_KEY,
)
from endpoints import (
auth,
collections,
Expand Down Expand Up @@ -54,7 +59,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
allow_headers=["*"],
)

if "pytest" not in sys.modules and not DISABLE_CSRF_PROTECTION:
if not IS_PYTEST_RUN and not DISABLE_CSRF_PROTECTION:
# CSRF protection (except endpoints listed in exempt_urls)
app.add_middleware(
CustomCSRFMiddleware,
Expand Down
10 changes: 5 additions & 5 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ certifi = "2024.07.04"

[tool.poetry.group.test.dependencies]
fakeredis = "^2.21.3"
pytest = "^8.1.1"
pytest = "^8.3"
pytest-env = "^1.1.3"
pytest-mock = "^3.12.0"
pytest-asyncio = "^0.23.5"
Expand Down

0 comments on commit 749e4d6

Please sign in to comment.