Skip to content
Myr

use # pragma: no cover instead of # pragma: nocover (#2471)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Adrian Garcia Badaracco · committed by GitHub · parent deb904d · Browse files · 25 files+70 added−70 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Tom Christie <tom@tomchristie.com>

Diff stats

25 files+70 added−70 removed

  • tests:+25 added−25 removed
  • other:+45 added−45 removed

25 files+70 added−70 removed

modified:httpx/_transports/base.py+2 added-2 removed
50 unmodified lines
51 Returns a `Response` instance.52 """53 raise NotImplementedError(54 "The 'handle_request' method must be implemented."55 ) # pragma: nocover55 ) # pragma: no cover5657 def close(self) -> None:58 pass59
15 unmodified lines
75 request: Request,76 ) -> Response:77 raise NotImplementedError(78 "The 'handle_async_request' method must be implemented."79 ) # pragma: nocover79 ) # pragma: no cover8081 async def aclose(self) -> None:82 pass
modified:httpx/_transports/default.py+5 added-5 removed
68 unmodified lines
69 # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.70 if mapped_exc is None or issubclass(to_exc, mapped_exc):71 mapped_exc = to_exc7273 if mapped_exc is None: # pragma: nocover73 if mapped_exc is None: # pragma: no cover74 raise7576 message = str(exc)77 raise mapped_exc(message) from exc
78 unmodified lines
156 )157 elif proxy.url.scheme == "socks5":158 try:159 import socksio # noqa160 except ImportError: # pragma: nocover160 except ImportError: # pragma: no cover161 raise ImportError(162 "Using SOCKS proxy, but the 'socksio' package is not installed. "163 "Make sure to install httpx using `pip install httpx[socks]`."164 ) from None
12 unmodified lines
177 keepalive_expiry=limits.keepalive_expiry,178 http1=http1,179 http2=http2,180 )181 else: # pragma: nocover181 else: # pragma: no cover182 raise ValueError(183 f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}."184 )185
105 unmodified lines
291 )292 elif proxy.url.scheme == "socks5":293 try:294 import socksio # noqa295 except ImportError: # pragma: nocover295 except ImportError: # pragma: no cover296 raise ImportError(297 "Using SOCKS proxy, but the 'socksio' package is not installed. "298 "Make sure to install httpx using `pip install httpx[socks]`."299 ) from None
12 unmodified lines
312 keepalive_expiry=limits.keepalive_expiry,313 http1=http1,314 http2=http2,315 )316 else: # pragma: nocover316 else: # pragma: no cover317 raise ValueError(318 f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}."319 )320
45 unmodified lines
modified:httpx/__init__.py+1 added-1 removed
44 unmodified lines
45from ._urls import URL, QueryParams4647try:48 from ._main import main49except ImportError: # pragma: nocover49except ImportError: # pragma: no cover5051 def main() -> None: # type: ignore52 import sys53
84 unmodified lines
modified:httpx/_client.py+2 added-2 removed
665 unmodified lines
666667 if http2:668 try:669 import h2 # noqa670 except ImportError: # pragma: nocover670 except ImportError: # pragma: no cover671 raise ImportError(672 "Using http2=True, but the 'h2' package is not installed. "673 "Make sure to install httpx using `pip install httpx[http2]`."674 ) from None
712 unmodified lines
13871388 if http2:1389 try:1390 import h2 # noqa1391 except ImportError: # pragma: nocover1391 except ImportError: # pragma: no cover1392 raise ImportError(1393 "Using http2=True, but the 'h2' package is not installed. "1394 "Make sure to install httpx using `pip install httpx[http2]`."1395 ) from None
611 unmodified lines
modified:httpx/_compat.py+1 added-1 removed
8 unmodified lines
9# The C bindings in `brotli` are recommended for CPython.10# The CFFI bindings in `brotlicffi` are recommended for PyPy and everything else.11try:12 import brotlicffi as brotli13except ImportError: # pragma: nocover13except ImportError: # pragma: no cover14 try:15 import brotli16 except ImportError:17 brotli = None
23 unmodified lines
modified:httpx/_config.py+4 added-4 removed
32 unmodified lines
33logger = get_logger(__name__)343536class UnsetType:37 pass # pragma: nocover37 pass # pragma: no cover383940UNSET = UnsetType()41
84 unmodified lines
126 # Signal to server support for PHA in TLS 1.3. Raises an127 # AttributeError if only read-only access is implemented.128 try:129 context.post_handshake_auth = True # type: ignore130 except AttributeError: # pragma: nocover130 except AttributeError: # pragma: no cover131 pass132133 # Disable using 'commonName' for SSLContext.check_hostname134 # when the 'subjectAltName' extension isn't available.135 try:136 context.hostname_checks_common_name = False # type: ignore137 except AttributeError: # pragma: nocover137 except AttributeError: # pragma: no cover138 pass139140 if ca_bundle_path.is_file():141 logger.trace(f"load_verify_locations cafile={ca_bundle_path!s}")
19 unmodified lines
161 if ssl.HAS_ALPN:162 alpn_idents = ["http/1.1", "h2"] if self.http2 else ["http/1.1"]163 context.set_alpn_protocols(alpn_idents)164165 if hasattr(context, "keylog_filename"): # pragma: nocover (Available in 3.8+)165 if hasattr(context, "keylog_filename"): # pragma: no cover (Available in 3.8+)166 keylogfile = os.environ.get("SSLKEYLOGFILE")167 if keylogfile and self.trust_env:168 context.keylog_filename = keylogfile # type: ignore169
194 unmodified lines
modified:httpx/_content.py+1 added-1 removed
99 unmodified lines
100 raise StreamClosed()101102 async def __aiter__(self) -> AsyncIterator[bytes]:103 raise StreamClosed()104 yield b"" # pragma: nocover104 yield b"" # pragma: no cover105106107def encode_content(108 content: Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]
127 unmodified lines
modified:httpx/_decoders.py+10 added-10 removed
12 unmodified lines
131415class ContentDecoder:16 def decode(self, data: bytes) -> bytes:17 raise NotImplementedError() # pragma: nocover17 raise NotImplementedError() # pragma: no cover1819 def flush(self) -> bytes:20 raise NotImplementedError() # pragma: nocover20 raise NotImplementedError() # pragma: no cover212223class IdentityDecoder(ContentDecoder):24 """
31 unmodified lines
5657 def flush(self) -> bytes:58 try:59 return self.decompressor.flush()60 except zlib.error as exc: # pragma: nocover60 except zlib.error as exc: # pragma: no cover61 raise DecodingError(str(exc)) from exc626364class GZipDecoder(ContentDecoder):
14 unmodified lines
7980 def flush(self) -> bytes:81 try:82 return self.decompressor.flush()83 except zlib.error as exc: # pragma: nocover83 except zlib.error as exc: # pragma: no cover84 raise DecodingError(str(exc)) from exc858687class BrotliDecoder(ContentDecoder):
6 unmodified lines
94 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'95 """9697 def __init__(self) -> None:98 if brotli is None: # pragma: nocover98 if brotli is None: # pragma: no cover99 raise ImportError(100 "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' "101 "packages have been installed. "102 "Make sure to install httpx using `pip install httpx[brotli]`."
2 unmodified lines
105 self.decompressor = brotli.Decompressor()106 self.seen_data = False107 if hasattr(self.decompressor, "decompress"):108 # The 'brotlicffi' package.109 self._decompress = self.decompressor.decompress # pragma: nocover109 self._decompress = self.decompressor.decompress # pragma: no cover110 else:111 # The 'brotli' package.112 self._decompress = self.decompressor.process # pragma: nocover112 self._decompress = self.decompressor.process # pragma: no cover113114 def decode(self, data: bytes) -> bytes:115 if not data:116 return b""
12 unmodified lines
129130 # As the decompressor decompresses eagerly, this131 # will never actually emit any data. However, it will potentially throw132 # errors if a truncated or damaged data stream has been used.133 self.decompressor.finish() # pragma: nocover133 self.decompressor.finish() # pragma: no cover134 return b""135 except brotli.error as exc: # pragma: nocover135 except brotli.error as exc: # pragma: no cover136 raise DecodingError(str(exc)) from exc137138139class MultiDecoder(ContentDecoder):
189 unmodified lines
329}330331332if brotli is None:333 SUPPORTED_DECODERS.pop("br") # pragma: nocover333 SUPPORTED_DECODERS.pop("br") # pragma: no cover
modified:httpx/_exceptions.py+1 added-1 removed
32 unmodified lines
33import contextlib34import typing3536if typing.TYPE_CHECKING:37 from ._models import Request, Response # pragma: nocover37 from ._models import Request, Response # pragma: no cover383940class HTTPError(Exception):41 """
302 unmodified lines
modified:httpx/_main.py+9 added-9 removed
99 unmodified lines
100 if content_type is not None:101 mime_type, _, _ = content_type.partition(";")102 try:103 return pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name104 except pygments.util.ClassNotFound: # pragma: nocover104 except pygments.util.ClassNotFound: # pragma: no cover105 pass106 return "" # pragma: nocover106 return "" # pragma: no cover107108109def format_request_headers(request: httpcore.Request, http2: bool = False) -> str:110 version = "HTTP/2" if http2 else "HTTP/1.1"
56 unmodified lines
167 if lexer_name.lower() == "json":168 try:169 data = response.json()170 text = json.dumps(data, indent=4)171 except ValueError: # pragma: nocover171 except ValueError: # pragma: no cover172 text = response.text173 else:174 text = response.text175
2 unmodified lines
178 else:179 console.print(f"<{len(response.content)} bytes of binary data>")180181182def format_certificate(cert: dict) -> str: # pragma: nocover182def format_certificate(cert: dict) -> str: # pragma: no cover183 lines = []184 for key, value in cert.items():185 if isinstance(value, (list, tuple)):186 lines.append(f"* {key}:")
20 unmodified lines
207 elif name == "connection.connect_tcp.complete" and verbose:208 stream = info["return_value"]209 server_addr = stream.get_extra_info("server_addr")210 console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}")211 elif name == "connection.start_tls.complete" and verbose: # pragma: nocover211 elif name == "connection.start_tls.complete" and verbose: # pragma: no cover212 stream = info["return_value"]213 ssl_object = stream.get_extra_info("ssl_object")214 version = ssl_object.version()215 cipher = ssl_object.cipher()
6 unmodified lines
222 console.print(format_certificate(server_cert))223 elif name == "http11.send_request_headers.started" and verbose:224 request = info["request"]225 print_request_headers(request, http2=False)226 elif name == "http2.send_request_headers.started" and verbose: # pragma: nocover226 elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover227 request = info["request"]228 print_request_headers(request, http2=True)229 elif name == "http11.receive_response_headers.complete":230 http_version, status, reason_phrase, headers = info["return_value"]231 print_response_headers(http_version, status, reason_phrase, headers)232 elif name == "http2.receive_response_headers.complete": # pragma: nocover232 elif name == "http2.receive_response_headers.complete": # pragma: no cover233 status, headers = info["return_value"]234 http_version = b"HTTP/2"235 reason_phrase = None236 print_response_headers(http_version, status, reason_phrase, headers)
30 unmodified lines
267 return None268269 try:270 return json.loads(value)271 except json.JSONDecodeError: # pragma: nocover271 except json.JSONDecodeError: # pragma: no cover272 raise click.BadParameter("Not valid JSON")273274275def validate_auth(
4 unmodified lines
280 if value == (None, None):281 return None282283 username, password = value284 if password == "-": # pragma: nocover284 if password == "-": # pragma: no cover285 password = click.prompt("Password", hide_input=True)286 return (username, password)287288
211 unmodified lines
modified:httpx/_models.py+2 added-2 removed
820 unmodified lines
821 for chunk in chunker.decode(decoded):822 yield chunk823 decoded = decoder.flush()824 for chunk in chunker.decode(decoded):825 yield chunk # pragma: nocover825 yield chunk # pragma: no cover826 for chunk in chunker.flush():827 yield chunk828829 def iter_text(
95 unmodified lines
925 for chunk in chunker.decode(decoded):926 yield chunk927 decoded = decoder.flush()928 for chunk in chunker.decode(decoded):929 yield chunk # pragma: nocover929 yield chunk # pragma: no cover930 for chunk in chunker.flush():931 yield chunk932933 async def aiter_text(
272 unmodified lines
modified:httpx/_types.py+4 added-4 removed
98 unmodified lines
99class SyncByteStream:100 def __iter__(self) -> Iterator[bytes]:101 raise NotImplementedError(102 "The '__iter__' method must be implemented."103 ) # pragma: nocover104 yield b"" # pragma: nocover103 ) # pragma: no cover104 yield b"" # pragma: no cover105106 def close(self) -> None:107 """108 Subclasses can override this method to release any network resources
4 unmodified lines
113class AsyncByteStream:114 async def __aiter__(self) -> AsyncIterator[bytes]:115 raise NotImplementedError(116 "The '__aiter__' method must be implemented."117 ) # pragma: nocover118 yield b"" # pragma: nocover117 ) # pragma: no cover118 yield b"" # pragma: no cover119120 async def aclose(self) -> None:121 pass
modified:httpx/_utils.py+3 added-3 removed
144 unmodified lines
145 try:146 if expanded_path.is_file():147 self._netrc_info = netrc.netrc(str(expanded_path))148 break149 except (netrc.NetrcParseError, IOError): # pragma: nocover149 except (netrc.NetrcParseError, IOError): # pragma: no cover150 # Issue while reading the netrc file, ignore...151 pass152 return self._netrc_info153
82 unmodified lines
236237class Logger(logging.Logger):238 # Stub for type checkers.239 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:240 ... # pragma: nocover240 ... # pragma: no cover241242243def get_logger(name: str) -> Logger:244 """
152 unmodified lines
397 if library == "trio":398 import trio399400 return trio.current_time()401 elif library == "curio": # pragma: nocover401 elif library == "curio": # pragma: no cover402 import curio403404 return await curio.clock()405
126 unmodified lines
modified:tests/client/test_async_client.py+3 added-3 removed
98 unmodified lines
99100101@pytest.mark.usefixtures("async_environment")102async def test_cannot_stream_sync_request(server):103 def hello_world(): # pragma: nocover103 def hello_world(): # pragma: no cover104 yield b"Hello, "105 yield b"world!"106107 async with httpx.AsyncClient() as client:
163 unmodified lines
271272 # Once we're closed we cannot reopen the client.273 with pytest.raises(RuntimeError):274 async with client:275 pass # pragma: nocover275 pass # pragma: no cover276277278@pytest.mark.usefixtures("async_environment")279async def test_client_closed_state_using_with_block():
65 unmodified lines
345 class CancelledStream(httpx.AsyncByteStream):346 async def __aiter__(self) -> typing.AsyncIterator[bytes]:347 yield b"Hello"348 raise KeyboardInterrupt()349 yield b", world" # pragma: nocover349 yield b", world" # pragma: no cover350351 async def aclose(self) -> None:352 nonlocal stream_was_closed353 stream_was_closed = True
20 unmodified lines
modified:tests/client/test_auth.py+1 added-1 removed
631 unmodified lines
632 auth = DigestAuth(username="tomchristie", password="password123")633 app = DigestApp()634635 async def streaming_body():636 yield b"Example request body" # pragma: nocover636 yield b"Example request body" # pragma: no cover637638 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:639 with pytest.raises(httpx.StreamConsumed):640 await client.post(url, content=streaming_body(), auth=auth)
66 unmodified lines
modified:tests/client/test_client.py+2 added-2 removed
118 unmodified lines
119 assert body == b"Hello, world!"120121122def test_cannot_stream_async_request(server):123 async def hello_world(): # pragma: nocover123 async def hello_world(): # pragma: no cover124 yield b"Hello, "125 yield b"world!"126127 with httpx.Client() as client:
189 unmodified lines
317318 # Once we're closed we cannot reopen the client.319 with pytest.raises(RuntimeError):320 with client:321 pass # pragma: nocover321 pass # pragma: no cover322323324def test_client_closed_state_using_with_block():325 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:
135 unmodified lines
modified:tests/client/test_properties.py+1 added-1 removed
51 unmodified lines
525354def test_client_event_hooks():55 def on_request(request):56 pass # pragma: nocover56 pass # pragma: no cover5758 client = httpx.Client()59 client.event_hooks = {"request": [on_request]}60 assert client.event_hooks == {"request": [on_request], "response": []}
modified:tests/client/test_redirects.py+1 added-1 removed
350 unmodified lines
351 client = httpx.Client(transport=ConsumeBodyTransport(redirects))352 url = "https://example.org/redirect_body"353354 def streaming_body():355 yield b"Example request body" # pragma: nocover355 yield b"Example request body" # pragma: no cover356357 with pytest.raises(httpx.StreamConsumed):358 client.post(url, content=streaming_body(), follow_redirects=True)359
86 unmodified lines
modified:tests/models/test_requests.py+8 added-8 removed
22 unmodified lines
2324def test_iterable_content():25 class Content:26 def __iter__(self):27 yield b"test 123" # pragma: nocover27 yield b"test 123" # pragma: no cover2829 request = httpx.Request("POST", "http://example.org", content=Content())30 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}313233def test_generator_with_transfer_encoding_header():34 def content():35 yield b"test 123" # pragma: nocover35 yield b"test 123" # pragma: no cover3637 request = httpx.Request("POST", "http://example.org", content=content())38 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}394041def test_generator_with_content_length_header():42 def content():43 yield b"test 123" # pragma: nocover43 yield b"test 123" # pragma: no cover4445 headers = {"Content-Length": "8"}46 request = httpx.Request(47 "POST", "http://example.org", content=content(), headers=headers
51 unmodified lines
99100101def test_cannot_access_streaming_content_without_read():102 # Ensure that streaming requests103 def streaming_body(): # pragma: nocover103 def streaming_body(): # pragma: no cover104 yield ""105106 request = httpx.Request("POST", "http://example.org", content=streaming_body())107 with pytest.raises(httpx.RequestNotRead):
1 unmodified line
109110111def test_transfer_encoding_header():112 async def streaming_body(data):113 yield data # pragma: nocover113 yield data # pragma: no cover114115 data = streaming_body(b"test 123")116117 request = httpx.Request("POST", "http://example.org", content=data)
7 unmodified lines
125 See https://github.com/encode/httpx/issues/1168126 """127128 def streaming_body(data):129 yield data # pragma: nocover129 yield data # pragma: no cover130131 data = streaming_body(b"abcd")132133 headers = {"Content-Length": "4"}
17 unmodified lines
151152153def test_override_content_length_header():154 async def streaming_body(data):155 yield data # pragma: nocover155 yield data # pragma: no cover156157 data = streaming_body(b"test 123")158 headers = {"Content-Length": "8"}159
52 unmodified lines
212213214def test_request_generator_content_picklable():215 def content():216 yield b"test 123" # pragma: nocover216 yield b"test 123" # pragma: no cover217218 request = httpx.Request("POST", "http://example.org", content=content())219 pickle_request = pickle.loads(pickle.dumps(request))220 with pytest.raises(httpx.RequestNotRead):
8 unmodified lines
modified:tests/models/test_responses.py+2 added-2 removed
914 unmodified lines
915916917def test_generator_with_transfer_encoding_header():918 def content():919 yield b"test 123" # pragma: nocover919 yield b"test 123" # pragma: no cover920921 response = httpx.Response(200, content=content())922 assert response.headers == {"Transfer-Encoding": "chunked"}923924925def test_generator_with_content_length_header():926 def content():927 yield b"test 123" # pragma: nocover927 yield b"test 123" # pragma: no cover928929 headers = {"Content-Length": "8"}930 response = httpx.Response(200, content=content(), headers=headers)931 assert response.headers == {"Content-Length": "8"}
82 unmodified lines
modified:tests/concurrency.py+1 added-1 removed
8 unmodified lines
91011async def sleep(seconds: float) -> None:12 if sniffio.current_async_library() == "trio":13 await trio.sleep(seconds) # pragma: nocover13 await trio.sleep(seconds) # pragma: no cover14 else:15 await asyncio.sleep(seconds)
modified:tests/conftest.py+2 added-2 removed
262 unmodified lines
263 loop.create_task(self.watch_restarts()),264 }265 await asyncio.wait(tasks)266267 async def restart(self) -> None: # pragma: nocover267 async def restart(self) -> None: # pragma: no cover268 # This coroutine may be called from a different thread than the one the269 # server is running on, and from an async environment that's not asyncio.270 # For this reason, we use an event to coordinate with the server271 # instead of calling shutdown()/startup() directly, and should not make
2 unmodified lines
274 self.restart_requested.set()275 while not self.started:276 await sleep(0.2)277278 async def watch_restarts(self): # pragma: nocover278 async def watch_restarts(self): # pragma: no cover279 while True:280 if self.should_exit:281 return282
41 unmodified lines
modified:tests/test_config.py+1 added-1 removed
175 unmodified lines
176 not hasattr(ssl.SSLContext, "keylog_filename"),177 reason="requires OpenSSL 1.1.1 or higher",178)179@pytest.mark.skipif(sys.version_info < (3, 8), reason="requires python3.8 or higher")180def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: nocover180def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: no cover181 with monkeypatch.context() as m:182 m.delenv("SSLKEYLOGFILE", raising=False)183184 context = httpx.create_ssl_context(trust_env=True)
38 unmodified lines
modified:tests/test_content.py+1 added-1 removed
71 unmodified lines
72 self._idx = self._idx + chunk_size73 return chunk7475 async def __aiter__(self):76 yield self._content # pragma: nocover76 yield self._content # pragma: no cover7778 headers, stream = encode_request(content=AsyncBytesIO(b"Hello, world!"))79 assert not isinstance(stream, typing.Iterable)80 assert isinstance(stream, typing.AsyncIterable)
370 unmodified lines
modified:tests/test_exceptions.py+2 added-2 removed
19 unmodified lines
20 and value not in HTTPCORE_EXC_MAP21 and value is not httpcore.ConnectionNotAvailable22 ]2324 if not_mapped: # pragma: nocover24 if not_mapped: # pragma: no cover25 pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")262728def test_httpcore_exception_mapping(server) -> None:
40 unmodified lines
69 and issubclass(value, Exception)70 and not hasattr(httpx, name)71 ]7273 if not_exposed: # pragma: nocover73 if not_exposed: # pragma: no cover74 pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")757677def test_request_attribute() -> None:
9 unmodified lines