test_auth.py
This file
Path
tests/client/test_auth.py
73 lines · 1.8 KiB · Python
Last changed by
Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
History of this fileTake it
1import json23import pytest45from httpcore import (6 URL,7 CertTypes,8 Client,9 Dispatcher,10 Request,11 Response,12 TimeoutTypes,13 VerifyTypes,14)151617class MockDispatch(Dispatcher):18 async def send(19 self,20 request: Request,21 stream: bool = False,22 verify: VerifyTypes = None,23 cert: CertTypes = None,24 timeout: TimeoutTypes = None,25 ) -> Response:26 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()27 return Response(200, content=body, request=request)282930def test_basic_auth():31 url = "https://example.org/"32 auth = ("tomchristie", "password123")3334 with Client(dispatch=MockDispatch()) as client:35 response = client.get(url, auth=auth)3637 assert response.status_code == 20038 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}394041def test_basic_auth_in_url():42 url = "https://tomchristie:password123@example.org/"4344 with Client(dispatch=MockDispatch()) as client:45 response = client.get(url)4647 assert response.status_code == 20048 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}495051def test_basic_auth_on_session():52 url = "https://example.org/"53 auth = ("tomchristie", "password123")5455 with Client(dispatch=MockDispatch(), auth=auth) as client:56 response = client.get(url)5758 assert response.status_code == 20059 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}606162def test_custom_auth():63 url = "https://example.org/"6465 def auth(request):66 request.headers["Authorization"] = "Token 123"67 return request6869 with Client(dispatch=MockDispatch()) as client:70 response = client.get(url, auth=auth)7172 assert response.status_code == 20073 assert response.json() == {"auth": "Token 123"}