Skip to content

Add "raw_path" to TestClient request scope#805

Closed
trimailov wants to merge 2 commits intoKludex:masterfrom
trimailov:testclient-raw-path
Closed

Add "raw_path" to TestClient request scope#805
trimailov wants to merge 2 commits intoKludex:masterfrom
trimailov:testclient-raw-path

Conversation

@trimailov
Copy link
Copy Markdown
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
Copy Markdown
Contributor Author

Apparently similar PR was made in #635.

@trimailov trimailov force-pushed the testclient-raw-path branch from 632512a to 39f448d Compare January 30, 2020 08:03
@JayH5 JayH5 added the testclient TestClient-related label Feb 4, 2021
@Kludex
Copy link
Copy Markdown
Owner

Kludex commented Sep 18, 2021

@trimailov Thanks for the PR! 🎉

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

@Kludex
Copy link
Copy Markdown
Owner

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.

4 participants