Cover OAuth2AuthorizationCodeBearer optional path and drop stale nocover pragma by suletetes · Pull Request #16307 · fastapi/fastapi · GitHub
Skip to content

Cover OAuth2AuthorizationCodeBearer optional path and drop stale nocover pragma - #16307

Closed
suletetes wants to merge 2 commits into
fastapi:masterfrom
suletetes:test/oauth2-authcode-bearer-optional
Closed

suletetes wants to merge 2 commits into
fastapi:masterfrom
suletetes:test/oauth2-authcode-bearer-optional

Conversation

@suletetes

Copy link
Copy Markdown

Summary

FastAPI's security schemes each ship paired tests: test_security_<scheme>.py (default auto_error=True) and test_security_<scheme>_optional.py (auto_error=False). OAuth2AuthorizationCodeBearer was missing its _optional test which is precisely why fastapi/security/oauth2.py carried a # pragma: nocover on the return None branch of its __call__.

Its sibling OAuth2PasswordBearer has the identical branch without a pragma, because it is already covered by test_security_oauth2_password_bearer_optional.py.

This PR closes that gap: it adds the missing optional test and removes the now-redundant coverage-exclusion, making the two schemes consistent and the optional-auth path genuinely tested.

Changes (two tiny, atomic commits)

  1. test: add tests/test_security_oauth2_authorization_code_bearer_optional.py (5 tests) anonymous request, valid bearer, non-bearer scheme (drives the return None branch), whitespace bearer, and an inline_snapshot OpenAPI assertion encoding the authorizationCode flow. Modeled on the existing password-bearer-optional test.
  2. refactor: drop the stale # pragma: nocover from the return None line in OAuth2AuthorizationCodeBearer.__call__. One line, no logic change; the branch is now exercised by real tests.

The test that justifies the pragma removal lands first, so no commit in history has an untested-but-un-pragma'd branch.

Testing

  • New + existing auth-code tests pass (10 passed); broader oauth2 security subset - 24 passed.
  • Coverage proof: with only the new test file, line 649 (return None) is no longer in the Missing set, while line 647 (the auto_error=True raise, covered by the non-optional file) still is confirming the new test hits the exact branch whose pragma was removed.
  • ruff check and ruff format --check clean.

Risk / trade-offs

Essentially none no production logic changed (single-line comment removal); purely additive test + coverage hygiene.

@codspeed

codspeed Bot commented Sep 6, 2026

Copy link
Copy Markdown

@YuriiMotov

Copy link
Copy Markdown
Member

@YuriiMotov YuriiMotov closed this Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants