test_threaded.py
This file
Path
tests/dispatch/test_threaded.py
100 lines · 2.8 KiB · Python
Last changed by
Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
History of this fileTake it
Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 1–100why, one step back1import json23import pytest45from httpcore import (6 CertTypes,7 Client,8 Dispatcher,9 Request,10 Response,11 TimeoutTypes,12 VerifyTypes,13)141516def streaming_body():17 for part in [b"Hello", b", ", b"world!"]:18 yield part192021class MockDispatch(Dispatcher):22 def send(23 self,24 request: Request,25 verify: VerifyTypes = None,26 cert: CertTypes = None,27 timeout: TimeoutTypes = None,28 ) -> Response:29 if request.url.path == "/streaming_response":30 return Response(200, content=streaming_body(), request=request)31 elif request.url.path == "/echo_request_body":32 content = request.read()33 return Response(200, content=content, request=request)34 elif request.url.path == "/echo_request_body_streaming":35 content = b"".join([part for part in request.stream()])36 return Response(200, content=content, request=request)37 else:38 body = json.dumps({"hello": "world"}).encode()39 return Response(200, content=body, request=request)404142def test_threaded_dispatch():43 """44 Use a syncronous 'Dispatcher' class with the client.45 Calls to the dispatcher will end up running within a thread pool.46 """47 url = "https://example.org/"48 with Client(dispatch=MockDispatch()) as client:49 response = client.get(url)5051 assert response.status_code == 20052 assert response.json() == {"hello": "world"}535455def test_threaded_streaming_response():56 url = "https://example.org/streaming_response"57 with Client(dispatch=MockDispatch()) as client:58 response = client.get(url)5960 assert response.status_code == 20061 assert response.text == "Hello, world!"626364def test_threaded_streaming_request():65 url = "https://example.org/echo_request_body"66 with Client(dispatch=MockDispatch()) as client:67 response = client.post(url, data=streaming_body())6869 assert response.status_code == 20070 assert response.text == "Hello, world!"717273def test_threaded_request_body():74 url = "https://example.org/echo_request_body"75 with Client(dispatch=MockDispatch()) as client:76 response = client.post(url, data=b"Hello, world!")7778 assert response.status_code == 20079 assert response.text == "Hello, world!"808182def test_threaded_request_body_streaming():83 url = "https://example.org/echo_request_body_streaming"84 with Client(dispatch=MockDispatch()) as client:85 response = client.post(url, data=b"Hello, world!")8687 assert response.status_code == 20088 assert response.text == "Hello, world!"899091def test_dispatch_class():92 """93 Use a syncronous 'Dispatcher' class directly.94 """95 url = "https://example.org/"96 with MockDispatch() as dispatcher:97 response = dispatcher.request("GET", url)9899 assert response.status_code == 200100 assert response.json() == {"hello": "world"}