From ef7ac3a3ecd172aa822d22539ef314335e2b98f9 Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Thu, 15 Oct 2026 10:48:58 -0500 Subject: [PATCH 1/2] ci: every warning is an error, and implicit encodings are warnings pytest.ini sets filterwarnings = error: a deprecation in this code or in a dependency fails the run instead of scrolling past in the summary. Both CI test jobs start the interpreter with -X warn_default_encoding, so a text read without an explicit encoding fails too. Set on the interpreter rather than in the job's env so Poetry's own process stays quiet. The suite was already clean under both flags with dependencies included (140 passed); a sanity test with a stray DeprecationWarning fails as intended. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 5 ++++- .gitlab-ci.yml | 3 ++- AGENTS.md | 4 +++- CHANGELOG.md | 6 ++++++ docs/setup.md | 12 ++++++++++-- pytest.ini | 7 +++++-- 6 files changed, 30 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a4e3245..500a33d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,4 +87,7 @@ jobs: - name: Install the Poetry that wrote poetry.lock run: pip install "poetry==$(sed -n 's/.*generated by Poetry \([0-9.]*\).*/\1/p' poetry.lock | head -1)" - run: poetry install --no-interaction - - run: poetry run pytest + # -X warn_default_encoding: a text read without an explicit encoding is a + # warning, and pytest.ini turns warnings into errors. On the interpreter, + # not in the job's env, so Poetry's own process stays quiet. + - run: poetry run python -X warn_default_encoding -m pytest diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index d7131d3..d7a5e5d 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -100,7 +100,8 @@ test: # The PostgreSQL major the project targets; CI on GitHub tests the same one. - postgres:17 script: - - poetry run pytest --junitxml=report.xml + # -X warn_default_encoding: same as the GitHub job, see its comment. + - poetry run python -X warn_default_encoding -m pytest --junitxml=report.xml artifacts: when: always reports: diff --git a/AGENTS.md b/AGENTS.md index 37a71df..3b829c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,9 @@ docs/ # setup, authentication, api, schemas, releasing, known_issue ## Common Commands * **Start dev server**: `poetry run uvicorn basic_api.main:app --reload --app-dir src` * **Test**: `poetry run pytest` (needs PostgreSQL; `--noconftest` plus the pure - test files runs without one) + test files runs without one). Every warning is an error (`pytest.ini`); CI + adds `-X warn_default_encoding`, so run + `poetry run python -X warn_default_encoding -m pytest` before pushing. * **Format & lint**: `poetry run black src tests scripts && poetry run flake8 src tests scripts` * **Type check**: `poetry run mypy` (covers `src` and `scripts`) * **Release** (in a clone, never in the starter): `poetry run python scripts/release.py prepare minor`; diff --git a/CHANGELOG.md b/CHANGELOG.md index 586df59..e9f2efb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,12 @@ notes (see [docs/releasing.md](docs/releasing.md)). `RequestBodyLimitMiddleware` answers 413 before any route runs (#13). ### Changed +- The test suite treats every warning as an error (`filterwarnings = error` + in `pytest.ini`), and both CI test jobs start the interpreter with + `-X warn_default_encoding`. A deprecation in this code or in a dependency, + or a text read without an explicit encoding, now fails CI instead of + scrolling past in the summary; the suite was already clean under both, with + dependencies included (#24). - Python 3.15 idioms. Read-only module constants are `frozendict` (`_SECRET_MINIMUM_BYTES`, `_TAKEN_MESSAGES`, `_DESCRIPTIONS`, the release script's `SECTIONS`); generic aliases come from `collections.abc` with the diff --git a/docs/setup.md b/docs/setup.md index 0683c48..2e815ef 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -113,8 +113,16 @@ poetry run pytest --noconftest tests/test_auth_units.py tests/test_user_schemas. tests/test_logging_config.py tests/test_request_id.py tests/test_release_script.py ``` -Deprecation warnings are not silenced; a new one in the summary is information, -not noise. +Every warning is an error (`filterwarnings = error` in `pytest.ini`): a +deprecation in this code or in a dependency fails the run instead of scrolling +past in the summary. Fix it, update the dependency, or record it in +[Known Issues](known_issues.md) with a narrow ignore. CI also starts the +interpreter with `-X warn_default_encoding`, so a text read without an explicit +encoding fails there; the same run locally is: + +```bash +poetry run python -X warn_default_encoding -m pytest +``` ## Code quality diff --git a/pytest.ini b/pytest.ini index d724d8e..ef5e3b7 100644 --- a/pytest.ini +++ b/pytest.ini @@ -4,7 +4,10 @@ addopts = -ra -q testpaths = tests pythonpath = src python_files = test_*.py -# No warning filters: a deprecation in our code or a dependency stays visible -# in the summary and is dealt with (or recorded in docs/known_issues.md). +# Every warning is an error: a deprecation in our code or in a dependency fails +# the run instead of scrolling past in the summary. Fix it, update the +# dependency, or record it in docs/known_issues.md with a narrow ignore below. +filterwarnings = + error asyncio_mode = auto asyncio_default_fixture_loop_scope = function From b29d21504f64549b406fc6e08882e7f24f00e0a9 Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Thu, 15 Oct 2026 10:51:35 -0500 Subject: [PATCH 2/2] refactor: every raise inside except chains with from The 13 re-raises the bugbear audit (B904) found now say what they are. `from e` where the new error translates the caught one: the integer and log-format parsers and the algorithm lookup in config.py, the rate-limit syntax check in limiter.py, the TOML read in scripts/release.py, the profile URL validator in schemas/user.py, IntegrityError to IdentifierTakenError in services/users.py, and PyJWT errors to the 401 in auth.py. `from None` for the four generic 500s in routers/users.py, whose cause is already logged with logger.exception and must not reach the client. No response changes; tracebacks now distinguish "caused by" from "raised while handling". AGENTS.md records the rule. Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 3 +++ CHANGELOG.md | 8 ++++++++ scripts/release.py | 2 +- src/basic_api/auth.py | 2 +- src/basic_api/config.py | 10 +++++----- src/basic_api/limiter.py | 2 +- src/basic_api/routers/users.py | 12 ++++++++---- src/basic_api/schemas/user.py | 4 ++-- src/basic_api/services/users.py | 8 ++++---- 9 files changed, 33 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3b829c4..30c7be9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,9 @@ Poetry-managed. * **Errors**: routers translate domain exceptions (`exceptions.py`) to status codes; services never import HTTP. Never put database error text in a response; log it with `logger.exception` and answer a generic message. + A `raise` inside `except` always chains: `from e` when the new error + translates the caught one, `from None` when the cause was already logged + and must not reach the client (the routers' 500s). * **Docstrings**: Google style (`Args`, `Returns`, `Raises`, `Example`); route docstrings render in Swagger, keep the curl examples current. * **Logging**: `logging.getLogger(__name__)` in a module; only diff --git a/CHANGELOG.md b/CHANGELOG.md index e9f2efb..b6b87b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,14 @@ notes (see [docs/releasing.md](docs/releasing.md)). `RequestBodyLimitMiddleware` answers 413 before any route runs (#13). ### Changed +- Every `raise` inside an `except` clause chains explicitly (PEP 3134): `from e` + where the new error translates the caught one (configuration parsing, the + rate-limit syntax check, the TOML read in the release script, the profile + URL validator, `IntegrityError` to `IdentifierTakenError`, PyJWT errors to + the 401), `from None` for the routers' generic 500s, whose cause is already + logged with `logger.exception`. Tracebacks now say whether an error was + caused by the one caught or raised while handling it; no response changes. + `AGENTS.md` records the rule (#25). - The test suite treats every warning as an error (`filterwarnings = error` in `pytest.ini`), and both CI test jobs start the interpreter with `-X warn_default_encoding`. A deprecation in this code or in a dependency, diff --git a/scripts/release.py b/scripts/release.py index 792298d..c7bea22 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -154,7 +154,7 @@ def read_project(pyproject: str) -> Project: try: data = tomllib.loads(pyproject) except tomllib.TOMLDecodeError as e: - raise ReleaseError(f"pyproject.toml is not valid TOML: {e}") + raise ReleaseError(f"pyproject.toml is not valid TOML: {e}") from e project = data.get("project") or {} if "name" not in project or "version" not in project: raise ReleaseError("pyproject.toml needs name and version under [project]") diff --git a/src/basic_api/auth.py b/src/basic_api/auth.py index a96e1a0..835a1a4 100644 --- a/src/basic_api/auth.py +++ b/src/basic_api/auth.py @@ -217,7 +217,7 @@ def decode_access_token(token: str) -> dict: status_code=status.HTTP_401_UNAUTHORIZED, detail=INVALID_TOKEN_DETAIL, headers={"WWW-Authenticate": "Bearer"}, - ) + ) from e async def authenticate_user( diff --git a/src/basic_api/config.py b/src/basic_api/config.py index 1773651..8cb8f0c 100644 --- a/src/basic_api/config.py +++ b/src/basic_api/config.py @@ -38,8 +38,8 @@ def _int(name: str, default: int) -> int: return default try: return int(raw) - except ValueError: - raise RuntimeError(f"{name}={raw!r} is not an integer") + except ValueError as e: + raise RuntimeError(f"{name}={raw!r} is not an integer") from e def _flag(name: str, default: bool) -> bool: @@ -117,7 +117,7 @@ def log_format(environment: str, raw: str | None) -> str: try: LOG_FORMAT = log_format(ENVIRONMENT, os.getenv("LOG_FORMAT")) except ValueError as e: - raise RuntimeError(str(e)) + raise RuntimeError(str(e)) from e def _package_version() -> str: @@ -204,10 +204,10 @@ def minimum_secret_bytes(algorithm: str) -> int: """ try: return _SECRET_MINIMUM_BYTES[algorithm] - except KeyError: + except KeyError as e: raise ValueError( f"{algorithm!r} is not one of " + ", ".join(_ALLOWED_ALGORITHMS) - ) + ) from e JWT_ALGORITHM = os.getenv("JWT_ALGORITHM") or "HS256" diff --git a/src/basic_api/limiter.py b/src/basic_api/limiter.py index ad950e8..98be44e 100644 --- a/src/basic_api/limiter.py +++ b/src/basic_api/limiter.py @@ -36,7 +36,7 @@ try: parse_many(_value) except ValueError as e: - raise RuntimeError(f"{_name}={_value!r} is not a valid rate limit: {e}") + raise RuntimeError(f"{_name}={_value!r} is not a valid rate limit: {e}") from e class RateLimitExceeded(Exception): diff --git a/src/basic_api/routers/users.py b/src/basic_api/routers/users.py index 8e38300..05d498a 100644 --- a/src/basic_api/routers/users.py +++ b/src/basic_api/routers/users.py @@ -69,7 +69,7 @@ async def create_user( except Exception: await session.rollback() logger.exception("Failed to create user") - raise HTTPException(status_code=500, detail="Failed to create user") + raise HTTPException(status_code=500, detail="Failed to create user") from None return SuccessResponse( success=True, message="User created successfully", data=db_user ) @@ -143,7 +143,7 @@ async def update_current_user( except Exception: await session.rollback() logger.exception("Failed to update user") - raise HTTPException(status_code=500, detail="Failed to update user") + raise HTTPException(status_code=500, detail="Failed to update user") from None return SuccessResponse( success=True, message="Profile updated successfully", data=db_user ) @@ -192,7 +192,9 @@ async def change_password( except Exception: await session.rollback() logger.exception("Failed to change password") - raise HTTPException(status_code=500, detail="Failed to change password") + raise HTTPException( + status_code=500, detail="Failed to change password" + ) from None return SuccessResponse( success=True, message="Password changed successfully", data=None ) @@ -242,7 +244,9 @@ async def delete_current_user( except Exception: await session.rollback() logger.exception("Failed to delete user") - raise HTTPException(status_code=500, detail="Failed to delete user account") + raise HTTPException( + status_code=500, detail="Failed to delete user account" + ) from None return SuccessResponse( success=True, message="Account permanently deleted", data=None ) diff --git a/src/basic_api/schemas/user.py b/src/basic_api/schemas/user.py index 7644360..e6a7df7 100644 --- a/src/basic_api/schemas/user.py +++ b/src/basic_api/schemas/user.py @@ -44,8 +44,8 @@ def validate_http_url(value: str | None) -> str | None: return None try: return str(_HTTP_URL.validate_python(value)) - except ValidationError: - raise ValueError("profile_picture_url must be an http(s) URL") + except ValidationError as e: + raise ValueError("profile_picture_url must be an http(s) URL") from e # 1. Base model: fields shared by the table and the API schemas. diff --git a/src/basic_api/services/users.py b/src/basic_api/services/users.py index 60e7dfe..9c029bb 100644 --- a/src/basic_api/services/users.py +++ b/src/basic_api/services/users.py @@ -91,9 +91,9 @@ async def create_user(session: AsyncSession, user_create: UserCreateSchema) -> U try: session.add(db_user) await session.commit() - except IntegrityError: + except IntegrityError as e: await session.rollback() - raise IdentifierTakenError(_RACE_MESSAGE) + raise IdentifierTakenError(_RACE_MESSAGE) from e await session.refresh(db_user) return db_user @@ -132,9 +132,9 @@ async def update_user( try: session.add(db_user) await session.commit() - except IntegrityError: + except IntegrityError as e: await session.rollback() - raise IdentifierTakenError(_RACE_MESSAGE) + raise IdentifierTakenError(_RACE_MESSAGE) from e await session.refresh(db_user) return db_user