mirror of https://github.com/tiangolo/fastapi.git
Handle mistakes when wrong value is passed to `scope`
This commit is contained in:
parent
7dcfecf606
commit
ab2a92e0a2
|
|
@ -2307,6 +2307,16 @@ def Depends( # noqa: N802
|
|||
return commons
|
||||
```
|
||||
"""
|
||||
|
||||
# Handle case when `scope` parameter value is invalid
|
||||
if scope not in ("function", "request", None):
|
||||
raise FastAPIError(
|
||||
"Invalid value for 'scope' parameter in Depends(). "
|
||||
"Expected 'function', 'request', or None. "
|
||||
f'Did you mean to use Security(dependency_fn, oauth_scopes="{scope}") '
|
||||
"to specify OAuth2 scopes instead?"
|
||||
)
|
||||
|
||||
return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope)
|
||||
|
||||
|
||||
|
|
@ -2495,6 +2505,14 @@ def Security( # noqa: N802
|
|||
"oauth_scopes='your_scope'."
|
||||
)
|
||||
|
||||
# Handle case when `scope` parameter value is invalid
|
||||
if scope not in ("function", "request", None):
|
||||
raise FastAPIError(
|
||||
"Invalid value for 'scope' parameter in Security(). "
|
||||
"Expected 'function', 'request', or None. "
|
||||
f'Did you mean oauth_scopes="{scope}" to specify OAuth2 scopes instead?'
|
||||
)
|
||||
|
||||
return params.Security(
|
||||
dependency=dependency,
|
||||
oauth_scopes=oauth_scopes,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import pytest
|
||||
from fastapi import Security
|
||||
from fastapi import Depends, Security
|
||||
from fastapi.exceptions import FastAPIError
|
||||
|
||||
|
||||
|
|
@ -35,3 +35,33 @@ def test_pass_scope_as_scopes(value: str):
|
|||
"Expected a sequence of strings (e.g., ['admin', 'user']), but received a single string. "
|
||||
f'Did you mean to use scope="{value}" to specify when the exit code of dependencies with yield should run? '
|
||||
)
|
||||
|
||||
|
||||
def test_pass_invalid_scope_value_to_security():
|
||||
"""
|
||||
Test passing invalid value to `scope` parameter in `Security`.
|
||||
"""
|
||||
|
||||
with pytest.raises(FastAPIError) as exc_info:
|
||||
Security(dependency=lambda: None, scope="invalid_scope")
|
||||
|
||||
assert str(exc_info.value) == (
|
||||
"Invalid value for 'scope' parameter in Security(). "
|
||||
"Expected 'function', 'request', or None. "
|
||||
'Did you mean oauth_scopes="invalid_scope" to specify OAuth2 scopes instead?'
|
||||
)
|
||||
|
||||
|
||||
def test_pass_invalid_scope_value_to_depends():
|
||||
"""
|
||||
Test passing invalid value to `scope` parameter in `Depends`.
|
||||
"""
|
||||
|
||||
with pytest.raises(FastAPIError) as exc_info:
|
||||
Depends(dependency=lambda: None, scope="invalid_scope")
|
||||
|
||||
assert str(exc_info.value) == (
|
||||
"Invalid value for 'scope' parameter in Depends(). "
|
||||
"Expected 'function', 'request', or None. "
|
||||
'Did you mean to use Security(dependency_fn, oauth_scopes="invalid_scope") to specify OAuth2 scopes instead?'
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in New Issue