test_auth.py
This file
Path
tests/client/test_auth.py
102 lines · 2.7 KiB · Python
Last changed by
Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb
History of this fileTake it
1import json2import os34from httpx import (5 AsyncDispatcher,6 AsyncRequest,7 AsyncResponse,8 CertTypes,9 Client,10 TimeoutTypes,11 VerifyTypes,12)131415class MockDispatch(AsyncDispatcher):16 async def send(17 self,18 request: AsyncRequest,19 verify: VerifyTypes = None,20 cert: CertTypes = None,21 timeout: TimeoutTypes = None,22 ) -> AsyncResponse:23 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()24 return AsyncResponse(200, content=body, request=request)252627def test_basic_auth():28 url = "https://example.org/"29 auth = ("tomchristie", "password123")3031 with Client(dispatch=MockDispatch()) as client:32 response = client.get(url, auth=auth)3334 assert response.status_code == 20035 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}363738def test_basic_auth_in_url():39 url = "https://tomchristie:password123@example.org/"4041 with Client(dispatch=MockDispatch()) as client:42 response = client.get(url)4344 assert response.status_code == 20045 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}464748def test_basic_auth_on_session():49 url = "https://example.org/"50 auth = ("tomchristie", "password123")5152 with Client(dispatch=MockDispatch(), auth=auth) as client:53 response = client.get(url)5455 assert response.status_code == 20056 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}575859def test_custom_auth():60 url = "https://example.org/"6162 def auth(request):63 request.headers["Authorization"] = "Token 123"64 return request6566 with Client(dispatch=MockDispatch()) as client:67 response = client.get(url, auth=auth)6869 assert response.status_code == 20070 assert response.json() == {"auth": "Token 123"}717273def test_netrc_auth():74 os.environ["NETRC"] = "tests/.netrc"75 url = "http://netrcexample.org"7677 with Client(dispatch=MockDispatch()) as client:78 response = client.get(url)7980 assert response.status_code == 20081 assert response.json() == {82 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"83 }848586def test_trust_env_auth():87 os.environ["NETRC"] = "tests/.netrc"88 url = "http://netrcexample.org"8990 with Client(dispatch=MockDispatch()) as client:91 response = client.get(url, trust_env=False)9293 assert response.status_code == 20094 assert response.json() == {"auth": None}9596 with Client(dispatch=MockDispatch(), trust_env=False) as client:97 response = client.get(url, trust_env=True)9899 assert response.status_code == 200100 assert response.json() == {101 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"102 }