Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

94 lines · 2.4 KiB · Python

Last changed by

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

History of this file

Take 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}