Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

280 lines · 8.2 KiB · Python

Last changed by

Add logic for determining if a URL should be proxied (#472)mariaS210before adoption7200717

History of this file

Take it

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 1why, one step back
1import asyncio

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

line 2why, one step back
2import logging

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

lines 3–4why, one step back
3import os
4

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

lines 5–6why, one step back
5import pytest
6

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

lines 7–8why, one step back
7import httpx
8from httpx import utils

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

lines 9–10why, one step back
9from httpx.utils import (
10 ElapsedTimer,

Add support for SSL_CERT_FILE and SSL_CERT_DIR (#307)Can Sarıgölbefore adoptionc9810a7

line 11why, one step back
11 get_ca_bundle_from_env,

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

line 12why, one step back
12 get_environment_proxies,

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

line 13why, one step back
13 get_netrc,

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 14why, one step back
14 guess_json_utf,

Add debug logs to ASGIDispatch (#371)Florimond Mancabefore adoptione62e5c3

line 15why, one step back
15 obfuscate_sensitive_headers,

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 16why, one step back
16 parse_header_links,

Add logic for determining if a URL should be proxied (#472)mariaS210before adoption7200717

line 17why, one step back
17 should_not_be_proxied,

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 18why, one step back
18)

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

lines 19–52why, one step back
19
2021@pytest.mark.parametrize(22 "encoding",23 (24 "utf-32",25 "utf-8-sig",26 "utf-16",27 "utf-8",28 "utf-16-be",29 "utf-16-le",30 "utf-32-be",31 "utf-32-le",32 ),33)34def test_encoded(encoding):35 data = "{}".encode(encoding)36 assert guess_json_utf(data) == encoding373839def test_bad_utf_like_encoding():40 assert guess_json_utf(b"\x00\x00\x00\x00") is None414243@pytest.mark.parametrize(44 ("encoding", "expected"),45 (46 ("utf-16-be", "utf-16"),47 ("utf-16-le", "utf-16"),48 ("utf-32-be", "utf-32"),49 ("utf-32-le", "utf-32"),50 ),51)52def test_guess_by_bom(encoding, expected):

Use nox for automation and CI (#128)Seth Michael Larsonbefore adoption80dc3e2

line 53why, one step back
53 data = "\ufeff{}".encode(encoding)

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

line 54why, one step back
54 assert guess_json_utf(data) == expected

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

lines 55–58why, one step back
55
5657def test_bad_get_netrc_login():58 os.environ["NETRC"] = "tests/.netrc"

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

line 59why, one step back
59 assert str(get_netrc()) is not None

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

line 60why, one step back
60

Fail unit tests without 100% coverage (#206)Can Sarıgölbefore adoption9536b76

lines 61–63why, one step back
61 from httpx import utils
6263 utils.NETRC_STATIC_FILES = ()

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

lines 64–67why, one step back
64
65 os.environ["NETRC"] = "wrongpath"66 assert utils.get_netrc() is None67

Fail unit tests without 100% coverage (#206)Can Sarıgölbefore adoption9536b76

line 68why, one step back
68 os.environ["NETRC"] = ""

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

line 69why, one step back
69 assert utils.get_netrc() is None

Fail unit tests without 100% coverage (#206)Can Sarıgölbefore adoption9536b76

line 70why, one step back
70

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

lines 71–73why, one step back
71
72def test_get_netrc_login():73 os.environ["NETRC"] = "tests/.netrc"

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

lines 74–75why, one step back
74 netrc = get_netrc()
75 assert netrc.authenticators("netrcexample.org") == (

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

lines 76–79why, one step back
76 "example-username",
77 None,78 "example-password",79 )

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 80–102why, one step back
80
8182@pytest.mark.parametrize(83 "value, expected",84 (85 (86 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',87 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],88 ),89 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),90 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),91 (92 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',93 [94 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},95 {"url": "http://.../back.jpeg"},96 ],97 ),98 ("", []),99 ),100)101def test_parse_header_links(value, expected):102 assert parse_header_links(value) == expected

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

lines 103–114why, one step back
103
104105@pytest.mark.asyncio106@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])107async def test_httpx_debug_enabled_stderr_logging(server, capsys, httpx_debug):108 os.environ["HTTPX_DEBUG"] = httpx_debug109110 # Force a reload on the logging handlers111 utils._LOGGER_INITIALIZED = False112 utils.get_logger("httpx")113114 async with httpx.AsyncClient() as client:

Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280

line 115why, one step back
115 await client.get(server.url)

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

lines 116–123why, one step back
116
117 if httpx_debug in ("1", "True"):118 assert "httpx.dispatch.connection_pool" in capsys.readouterr().err119 else:120 assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err121122 # Reset the logger so we don't have verbose output in all unit tests123 logging.getLogger("httpx").handlers = []

Add support for SSL_CERT_FILE and SSL_CERT_DIR (#307)Can Sarıgölbefore adoptionc9810a7

lines 124–159why, one step back
124
125126def test_get_ssl_cert_file():127 # Two environments is not set.128 assert get_ca_bundle_from_env() is None129130 os.environ["SSL_CERT_DIR"] = "tests/"131 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.132 assert get_ca_bundle_from_env() == "tests"133134 del os.environ["SSL_CERT_DIR"]135 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"136 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.137 assert get_ca_bundle_from_env() == "tests/test_utils.py"138139 os.environ["SSL_CERT_FILE"] = "wrongfile"140 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.141 assert get_ca_bundle_from_env() is None142143 del os.environ["SSL_CERT_FILE"]144 os.environ["SSL_CERT_DIR"] = "wrongpath"145 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.146 assert get_ca_bundle_from_env() is None147148 os.environ["SSL_CERT_DIR"] = "tests/"149 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"150 # Two environments is correctly set.151 assert get_ca_bundle_from_env() == "tests/test_utils.py"152153 os.environ["SSL_CERT_FILE"] = "wrongfile"154 # Two environments is set but SSL_CERT_FILE is not a file.155 assert get_ca_bundle_from_env() == "tests"156157 os.environ["SSL_CERT_DIR"] = "wrongpath"158 # Two environments is set but both are not correct.159 assert get_ca_bundle_from_env() is None

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

lines 160–170why, one step back
160
161162@pytest.mark.asyncio163async def test_elapsed_timer():164 with ElapsedTimer() as timer:165 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)166 await asyncio.sleep(0.1)167 await asyncio.sleep(168 0.1169 ) # test to ensure time spent after timer exits isn't accounted for.170 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 171–181why, one step back
171
172173@pytest.mark.parametrize(174 ["environment", "proxies"],175 [176 ({}, {}),177 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),178 (179 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},180 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},181 ),

Rely on getproxies for all proxy environment variables (#470)camellia256before adoption49ed77a

line 182why, one step back
182 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 183–189why, one step back
183 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),
184 ],185)186def test_get_environment_proxies(environment, proxies):187 os.environ.update(environment)188189 assert get_environment_proxies() == proxies

Add debug logs to ASGIDispatch (#371)Florimond Mancabefore adoptione62e5c3

lines 190–204why, one step back
190
191192@pytest.mark.parametrize(193 "headers, output",194 [195 ([("content-type", "text/html")], [("content-type", "text/html")]),196 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),197 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),198 ],199)200def test_obfuscate_sensitive_headers(headers, output):201 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]202 bytes_output = [(k.encode(), v.encode()) for k, v in output]203 assert list(obfuscate_sensitive_headers(headers)) == output204 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output

Add logic for determining if a URL should be proxied (#472)mariaS210before adoption7200717

lines 205–280why, one step back
205
206207@pytest.mark.parametrize(208 ["url", "no_proxy", "expected"],209 [210 (211 "http://127.0.0.1",212 {"NO_PROXY": ""},213 False,214 ), # everything proxied when no_proxy is empty/unset215 (216 "http://127.0.0.1",217 {"NO_PROXY": "127.0.0.1"},218 True,219 ), # no_proxy as ip case is matched220 (221 "http://127.0.0.1",222 {"NO_PROXY": "https://127.0.0.1"},223 False,224 ), # no_proxy with scheme is ignored225 (226 "http://127.0.0.1",227 {"NO_PROXY": "1.1.1.1"},228 False,229 ), # different no_proxy means its proxied230 (231 "http://courses.mit.edu",232 {"NO_PROXY": "mit.edu"},233 True,234 ), # no_proxy for sub-domain matches235 (236 "https://mit.edu.info",237 {"NO_PROXY": "mit.edu"},238 False,239 ), # domain is actually edu.info, so should be proxied240 (241 "https://mit.edu.info",242 {"NO_PROXY": "mit.edu,edu.info"},243 True,244 ), # list in no_proxy, matches second domain245 (246 "https://mit.edu.info",247 {"NO_PROXY": "mit.edu, edu.info"},248 True,249 ), # list with spaces in no_proxy250 (251 "https://mit.edu.info",252 {"NO_PROXY": "mit.edu,mit.info"},253 False,254 ), # list in no_proxy, without any domain matching255 (256 "https://foo.example.com",257 {"NO_PROXY": "www.example.com"},258 False,259 ), # different subdomains foo vs www means we still proxy260 (261 "https://www.example1.com",262 {"NO_PROXY": ".example1.com"},263 True,264 ), # no_proxy starting with dot265 (266 "https://www.example2.com",267 {"NO_PROXY": "ample2.com"},268 False,269 ), # whole-domain matching270 (271 "https://www.example3.com",272 {"NO_PROXY": "*"},273 True,274 ), # wildcard * means nothing proxied275 ],276)277def test_should_not_be_proxied(url, no_proxy, expected):278 os.environ.update(no_proxy)279 parsed_url = httpx.models.URL(url)280 assert should_not_be_proxied(parsed_url) == expected