Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "raw_path" to TestClient request scope #805

Closed
wants to merge 2 commits into from

Conversation

trimailov
Copy link
Contributor

raw_path was missing in TestClient request's scope, whereas uvicorn has raw_path in request's scope. This problem makes it impossible to write tests, when parsing raw path is necessary.

I've created this app to prove this:

> cat example.py
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
from starlette.testclient import TestClient


async def value(request):
    value = request.path_params['value']
    path = request.scope['path']
    raw_path = request.scope['raw_path']
    return PlainTextResponse(
        f'value: {value}\npath: {path}\nraw_path: {raw_path}\n'
    )


app = Starlette(debug=True, routes=[
    Route('/{value:path}', value),
])


def test_app():
    client = TestClient(app)
    response = client.get('/hel%2Flo')  # /hel/lo
    result = "value: hel/lo\npath: /hel/lo\nraw_path: /hel%2Flo\n"
    assert response.text == result

Launch the app with uvicorn:

> env/bin/uvicorn example:app

Test it with curl:

> curl localhost:8000/hel%2flo
value: hel/lo
path: /hel/lo
raw_path: b'/hel%2flo'

Test app with TestClient:

> env/bin/python -c "import example; example.test_app()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/justas/work/tilaajavastuu/starlette_test/example.py", line 28, in test_app
    response = client.get('/hel%2Flo')  # /hel/lo
<...>
  File "/Users/justas/work/tilaajavastuu/starlette_test/example.py", line 14, in value
    raw_path = request.scope['raw_path']
KeyError: 'raw_path'

@trimailov
Copy link
Contributor Author

Apparently similar PR was made in #635.

According to ASGI spec [0], connection scope's `raw_path` should be a
byte string.

[0] https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope
@JayH5 JayH5 added the testclient TestClient-related label Feb 4, 2021
@Kludex
Copy link
Sponsor Member

Kludex commented Sep 18, 2021

@trimailov Thanks for the PR! 🎉

Sorry for taking so long! Would you mind rebasing it?

@Kludex
Copy link
Sponsor Member

Kludex commented Jan 29, 2022

Closed in favor of #1445.

Author's commit are preserved.

@Kludex Kludex closed this Jan 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
testclient TestClient-related
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants