Skip to content
Myr

test_lowlevel.py

This file

Path

tests/test_lowlevel.py

350 lines · 12.4 KiB · Python

Last changed by

Merge pull request #5087 from LuckyDenis/masterKenneth Reitzbefore adoption67a7b2e

History of this file

Take it

1# -*- coding: utf-8 -*-23import pytest4import threading5import requests6from requests.exceptions import ChunkedEncodingError78from tests.testserver.server import Server, consume_socket_content910from .utils import override_environ111213def test_chunked_upload():14    """can safely send generators"""15    close_server = threading.Event()16    server = Server.basic_response_server(wait_to_close_event=close_server)17    data = iter([b'a', b'b', b'c'])1819    with server as (host, port):20        url = 'http://{}:{}/'.format(host, port)21        r = requests.post(url, data=data, stream=True)22        close_server.set()  # release server block2324    assert r.status_code == 20025    assert r.request.headers['Transfer-Encoding'] == 'chunked'262728def test_digestauth_401_count_reset_on_redirect():29    """Ensure we correctly reset num_401_calls after a successful digest auth,30    followed by a 302 redirect to another digest auth prompt.3132    See https://github.com/psf/requests/issues/1979.33    """34    text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'35                b'Content-Length: 0\r\n'36                b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'37                b', opaque="372825293d1c26955496c80ed6426e9e", '38                b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')3940    text_302 = (b'HTTP/1.1 302 FOUND\r\n'41                b'Content-Length: 0\r\n'42                b'Location: /\r\n\r\n')4344    text_200 = (b'HTTP/1.1 200 OK\r\n'45                b'Content-Length: 0\r\n\r\n')4647    expected_digest = (b'Authorization: Digest username="user", '48                       b'realm="me@kennethreitz.com", '49                       b'nonce="6bf5d6e4da1ce66918800195d6b9130d", uri="/"')5051    auth = requests.auth.HTTPDigestAuth('user', 'pass')5253    def digest_response_handler(sock):54        # Respond to initial GET with a challenge.55        request_content = consume_socket_content(sock, timeout=0.5)56        assert request_content.startswith(b"GET / HTTP/1.1")57        sock.send(text_401)5859        # Verify we receive an Authorization header in response, then redirect.60        request_content = consume_socket_content(sock, timeout=0.5)61        assert expected_digest in request_content62        sock.send(text_302)6364        # Verify Authorization isn't sent to the redirected host,65        # then send another challenge.66        request_content = consume_socket_content(sock, timeout=0.5)67        assert b'Authorization:' not in request_content68        sock.send(text_401)6970        # Verify Authorization is sent correctly again, and return 200 OK.71        request_content = consume_socket_content(sock, timeout=0.5)72        assert expected_digest in request_content73        sock.send(text_200)7475        return request_content7677    close_server = threading.Event()78    server = Server(digest_response_handler, wait_to_close_event=close_server)7980    with server as (host, port):81        url = 'http://{}:{}/'.format(host, port)82        r = requests.get(url, auth=auth)83        # Verify server succeeded in authenticating.84        assert r.status_code == 20085        # Verify Authorization was sent in final request.86        assert 'Authorization' in r.request.headers87        assert r.request.headers['Authorization'].startswith('Digest ')88        # Verify redirect happened as we expected.89        assert r.history[0].status_code == 30290        close_server.set()919293def test_digestauth_401_only_sent_once():94    """Ensure we correctly respond to a 401 challenge once, and then95    stop responding if challenged again.96    """97    text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'98                b'Content-Length: 0\r\n'99                b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'100                b', opaque="372825293d1c26955496c80ed6426e9e", '101                b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')102103    expected_digest = (b'Authorization: Digest username="user", '104                       b'realm="me@kennethreitz.com", '105                       b'nonce="6bf5d6e4da1ce66918800195d6b9130d", uri="/"')106107    auth = requests.auth.HTTPDigestAuth('user', 'pass')108109    def digest_failed_response_handler(sock):110        # Respond to initial GET with a challenge.111        request_content = consume_socket_content(sock, timeout=0.5)112        assert request_content.startswith(b"GET / HTTP/1.1")113        sock.send(text_401)114115        # Verify we receive an Authorization header in response, then116        # challenge again.117        request_content = consume_socket_content(sock, timeout=0.5)118        assert expected_digest in request_content119        sock.send(text_401)120121        # Verify the client didn't respond to second challenge.122        request_content = consume_socket_content(sock, timeout=0.5)123        assert request_content == b''124125        return request_content126127    close_server = threading.Event()128    server = Server(digest_failed_response_handler, wait_to_close_event=close_server)129130    with server as (host, port):131        url = 'http://{}:{}/'.format(host, port)132        r = requests.get(url, auth=auth)133        # Verify server didn't authenticate us.134        assert r.status_code == 401135        assert r.history[0].status_code == 401136        close_server.set()137138139def test_digestauth_only_on_4xx():140    """Ensure we only send digestauth on 4xx challenges.141142    See https://github.com/psf/requests/issues/3772.143    """144    text_200_chal = (b'HTTP/1.1 200 OK\r\n'145                     b'Content-Length: 0\r\n'146                     b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'147                     b', opaque="372825293d1c26955496c80ed6426e9e", '148                     b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')149150    auth = requests.auth.HTTPDigestAuth('user', 'pass')151152    def digest_response_handler(sock):153        # Respond to GET with a 200 containing www-authenticate header.154        request_content = consume_socket_content(sock, timeout=0.5)155        assert request_content.startswith(b"GET / HTTP/1.1")156        sock.send(text_200_chal)157158        # Verify the client didn't respond with auth.159        request_content = consume_socket_content(sock, timeout=0.5)160        assert request_content == b''161162        return request_content163164    close_server = threading.Event()165    server = Server(digest_response_handler, wait_to_close_event=close_server)166167    with server as (host, port):168        url = 'http://{}:{}/'.format(host, port)169        r = requests.get(url, auth=auth)170        # Verify server didn't receive auth from us.171        assert r.status_code == 200172        assert len(r.history) == 0173        close_server.set()174175176_schemes_by_var_prefix = [177    ('http', ['http']),178    ('https', ['https']),179    ('all', ['http', 'https']),180]181182_proxy_combos = []183for prefix, schemes in _schemes_by_var_prefix:184    for scheme in schemes:185        _proxy_combos.append(("{}_proxy".format(prefix), scheme))186187_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]188189190@pytest.mark.parametrize("var,scheme", _proxy_combos)191def test_use_proxy_from_environment(httpbin, var, scheme):192    url = "{}://httpbin.org".format(scheme)193    fake_proxy = Server()  # do nothing with the requests; just close the socket194    with fake_proxy as (host, port):195        proxy_url = "socks5://{}:{}".format(host, port)196        kwargs = {var: proxy_url}197        with override_environ(**kwargs):198            # fake proxy's lack of response will cause a ConnectionError199            with pytest.raises(requests.exceptions.ConnectionError):200                requests.get(url)201202        # the fake proxy received a request203        assert len(fake_proxy.handler_results) == 1204205        # it had actual content (not checking for SOCKS protocol for now)206        assert len(fake_proxy.handler_results[0]) > 0207208209def test_redirect_rfc1808_to_non_ascii_location():210    path = u'š'211    expected_path = b'%C5%A1'212    redirect_request = []  # stores the second request to the server213214    def redirect_resp_handler(sock):215        consume_socket_content(sock, timeout=0.5)216        location = u'//{}:{}/{}'.format(host, port, path)217        sock.send(218            b'HTTP/1.1 301 Moved Permanently\r\n'219            b'Content-Length: 0\r\n'220            b'Location: ' + location.encode('utf8') + b'\r\n'221            b'\r\n'222        )223        redirect_request.append(consume_socket_content(sock, timeout=0.5))224        sock.send(b'HTTP/1.1 200 OK\r\n\r\n')225226    close_server = threading.Event()227    server = Server(redirect_resp_handler, wait_to_close_event=close_server)228229    with server as (host, port):230        url = u'http://{}:{}'.format(host, port)231        r = requests.get(url=url, allow_redirects=True)232        assert r.status_code == 200233        assert len(r.history) == 1234        assert r.history[0].status_code == 301235        assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')236        assert r.url == u'{}/{}'.format(url, expected_path.decode('ascii'))237238        close_server.set()239240def test_fragment_not_sent_with_request():241    """Verify that the fragment portion of a URI isn't sent to the server."""242    def response_handler(sock):243        req = consume_socket_content(sock, timeout=0.5)244        sock.send(245            b'HTTP/1.1 200 OK\r\n'246            b'Content-Length: '+bytes(len(req))+b'\r\n'247            b'\r\n'+req248        )249250    close_server = threading.Event()251    server = Server(response_handler, wait_to_close_event=close_server)252253    with server as (host, port):254        url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)255        r = requests.get(url)256        raw_request = r.content257258        assert r.status_code == 200259        headers, body = raw_request.split(b'\r\n\r\n', 1)260        status_line, headers = headers.split(b'\r\n', 1)261262        assert status_line == b'GET /path/to/thing/ HTTP/1.1'263        for frag in (b'view', b'edit', b'token', b'hunter2'):264            assert frag not in headers265            assert frag not in body266267        close_server.set()268269def test_fragment_update_on_redirect():270    """Verify we only append previous fragment if one doesn't exist on new271    location. If a new fragment is encountered in a Location header, it should272    be added to all subsequent requests.273    """274275    def response_handler(sock):276        consume_socket_content(sock, timeout=0.5)277        sock.send(278            b'HTTP/1.1 302 FOUND\r\n'279            b'Content-Length: 0\r\n'280            b'Location: /get#relevant-section\r\n\r\n'281        )282        consume_socket_content(sock, timeout=0.5)283        sock.send(284            b'HTTP/1.1 302 FOUND\r\n'285            b'Content-Length: 0\r\n'286            b'Location: /final-url/\r\n\r\n'287        )288        consume_socket_content(sock, timeout=0.5)289        sock.send(290            b'HTTP/1.1 200 OK\r\n\r\n'291        )292293    close_server = threading.Event()294    server = Server(response_handler, wait_to_close_event=close_server)295296    with server as (host, port):297        url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)298        r = requests.get(url)299        raw_request = r.content300301        assert r.status_code == 200302        assert len(r.history) == 2303        assert r.history[0].request.url == url304305        # Verify we haven't overwritten the location with our previous fragment.306        assert r.history[1].request.url == 'http://{}:{}/get#relevant-section'.format(host, port)307        # Verify previous fragment is used and not the original.308        assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)309310        close_server.set()311312313def test_response_content_retains_error():314    """Verify that accessing response.content retains an error.315316    See https://github.com/kennethreitz/requests/issues/4965317    """318319    data = "Some random stuff to read from remove server.\n"320321    def response_handler(sock):322        req = consume_socket_content(sock, timeout=0.5)323324        # Send invalid chunked data (length mismatch)325        sock.send(326            b'HTTP/1.1 200 OK\r\n'327            b'Transfer-Encoding: chunked\r\n'328            b'\r\n2\r\n42\r\n8\r\n123\r\n'  # 5 bytes missing329        )330331    close_server = threading.Event()332    server = Server(response_handler, wait_to_close_event=close_server)333334    with server as (host, port):335        url = 'http://{}:{}/path'.format(host, port)336        r = requests.post(url, stream=True)337        with pytest.raises(ChunkedEncodingError):338            r.content339340    # Access the bad response data again, I would expect the same341    # error again.342343    try:344        content = r.content345    except ChunkedEncodingError:346        pass  # fine, same exception347    else:348        assert False, "error response has content: {0!r}".format(content)349    close_server.set()350