Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 2 additions & 1 deletion .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 6 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -54,7 +57,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`;
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,20 @@ 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,
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
Expand Down
12 changes: 10 additions & 2 deletions docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion scripts/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]")
Expand Down
2 changes: 1 addition & 1 deletion src/basic_api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
10 changes: 5 additions & 5 deletions src/basic_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion src/basic_api/limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
12 changes: 8 additions & 4 deletions src/basic_api/routers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
)
4 changes: 2 additions & 2 deletions src/basic_api/schemas/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 4 additions & 4 deletions src/basic_api/services/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
Loading