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
Provenance
- Commit
16e2830- Tree
9227bcb- Author
Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
deb904d
25 files changed+70 added−70 removed
modified:httpx/_transports/base.py+2 added-2 removed
50 unmodified lines51 Returns a `Response` instance.52 """53 raise NotImplementedError(54 "The 'handle_request' method must be implemented."55- ) # pragma: nocover55+ ) # pragma: no cover56 57 def close(self) -> None:58 pass59 15 unmodified lines75 request: Request,76 ) -> Response:77 raise NotImplementedError(78 "The 'handle_async_request' method must be implemented."79- ) # pragma: nocover79+ ) # pragma: no cover80 81 async def aclose(self) -> None:82 passmodified:httpx/_transports/default.py+5 added-5 removed
68 unmodified lines69 # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.70 if mapped_exc is None or issubclass(to_exc, mapped_exc):71 mapped_exc = to_exc72 73- if mapped_exc is None: # pragma: nocover73+ if mapped_exc is None: # pragma: no cover74 raise75 76 message = str(exc)77 raise mapped_exc(message) from exc78 unmodified lines156 )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 None12 unmodified lines177 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 lines291 )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 None12 unmodified lines312 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 linesmodified:httpx/__init__.py+1 added-1 removed
44 unmodified lines45 from ._urls import URL, QueryParams46 47 try:48 from ._main import main49-except ImportError: # pragma: nocover49+except ImportError: # pragma: no cover50 51 def main() -> None: # type: ignore52 import sys53 84 unmodified linesmodified:httpx/_client.py+2 added-2 removed
665 unmodified lines666 667 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 None712 unmodified lines1387 1388 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 None611 unmodified linesmodified:httpx/_compat.py+1 added-1 removed
8 unmodified lines9 # The C bindings in `brotli` are recommended for CPython.10 # The CFFI bindings in `brotlicffi` are recommended for PyPy and everything else.11 try:12 import brotlicffi as brotli13-except ImportError: # pragma: nocover13+except ImportError: # pragma: no cover14 try:15 import brotli16 except ImportError:17 brotli = None23 unmodified linesmodified:httpx/_config.py+4 added-4 removed
32 unmodified lines33 logger = get_logger(__name__)34 35 36 class UnsetType:37- pass # pragma: nocover37+ pass # pragma: no cover38 39 40 UNSET = UnsetType()41 84 unmodified lines126 # 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 pass132 133 # 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 pass139 140 if ca_bundle_path.is_file():141 logger.trace(f"load_verify_locations cafile={ca_bundle_path!s}")19 unmodified lines161 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)164 165- 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 linesmodified:httpx/_content.py+1 added-1 removed
99 unmodified lines100 raise StreamClosed()101 102 async def __aiter__(self) -> AsyncIterator[bytes]:103 raise StreamClosed()104- yield b"" # pragma: nocover104+ yield b"" # pragma: no cover105 106 107 def encode_content(108 content: Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]127 unmodified linesmodified:httpx/_decoders.py+10 added-10 removed
12 unmodified lines13 14 15 class ContentDecoder:16 def decode(self, data: bytes) -> bytes:17- raise NotImplementedError() # pragma: nocover17+ raise NotImplementedError() # pragma: no cover18 19 def flush(self) -> bytes:20- raise NotImplementedError() # pragma: nocover20+ raise NotImplementedError() # pragma: no cover21 22 23 class IdentityDecoder(ContentDecoder):24 """31 unmodified lines56 57 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 exc62 63 64 class GZipDecoder(ContentDecoder):14 unmodified lines79 80 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 exc85 86 87 class BrotliDecoder(ContentDecoder):6 unmodified lines94 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'95 """96 97 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 lines105 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 cover113 114 def decode(self, data: bytes) -> bytes:115 if not data:116 return b""12 unmodified lines129 130 # 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 exc137 138 139 class MultiDecoder(ContentDecoder):189 unmodified lines329 }330 331 332 if brotli is None:333- SUPPORTED_DECODERS.pop("br") # pragma: nocover333+ SUPPORTED_DECODERS.pop("br") # pragma: no covermodified:httpx/_exceptions.py+1 added-1 removed
32 unmodified lines33 import contextlib34 import typing35 36 if typing.TYPE_CHECKING:37- from ._models import Request, Response # pragma: nocover37+ from ._models import Request, Response # pragma: no cover38 39 40 class HTTPError(Exception):41 """302 unmodified linesmodified:httpx/_main.py+9 added-9 removed
99 unmodified lines100 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 cover107 108 109 def format_request_headers(request: httpcore.Request, http2: bool = False) -> str:110 version = "HTTP/2" if http2 else "HTTP/1.1"56 unmodified lines167 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 lines178 else:179 console.print(f"<{len(response.content)} bytes of binary data>")180 181 182-def format_certificate(cert: dict) -> str: # pragma: nocover182+def 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 lines207 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 lines222 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 lines267 return None268 269 try:270 return json.loads(value)271- except json.JSONDecodeError: # pragma: nocover271+ except json.JSONDecodeError: # pragma: no cover272 raise click.BadParameter("Not valid JSON")273 274 275 def validate_auth(4 unmodified lines280 if value == (None, None):281 return None282 283 username, password = value284- if password == "-": # pragma: nocover284+ if password == "-": # pragma: no cover285 password = click.prompt("Password", hide_input=True)286 return (username, password)287 288 211 unmodified linesmodified:httpx/_models.py+2 added-2 removed
820 unmodified lines821 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 chunk828 829 def iter_text(95 unmodified lines925 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 chunk932 933 async def aiter_text(272 unmodified linesmodified:httpx/_types.py+4 added-4 removed
98 unmodified lines99 class 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 cover105 106 def close(self) -> None:107 """108 Subclasses can override this method to release any network resources4 unmodified lines113 class 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 cover119 120 async def aclose(self) -> None:121 passmodified:httpx/_utils.py+3 added-3 removed
144 unmodified lines145 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 lines236 237 class 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 cover241 242 243 def get_logger(name: str) -> Logger:244 """152 unmodified lines397 if library == "trio":398 import trio399 400 return trio.current_time()401- elif library == "curio": # pragma: nocover401+ elif library == "curio": # pragma: no cover402 import curio403 404 return await curio.clock()405 126 unmodified linesmodified:tests/client/test_async_client.py+3 added-3 removed
98 unmodified lines99 100 101 @pytest.mark.usefixtures("async_environment")102 async 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!"106 107 async with httpx.AsyncClient() as client:163 unmodified lines271 272 # 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 cover276 277 278 @pytest.mark.usefixtures("async_environment")279 async def test_client_closed_state_using_with_block():65 unmodified lines345 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 cover350 351 async def aclose(self) -> None:352 nonlocal stream_was_closed353 stream_was_closed = True20 unmodified linesmodified:tests/client/test_auth.py+1 added-1 removed
631 unmodified lines632 auth = DigestAuth(username="tomchristie", password="password123")633 app = DigestApp()634 635 async def streaming_body():636- yield b"Example request body" # pragma: nocover636+ yield b"Example request body" # pragma: no cover637 638 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 linesmodified:tests/client/test_client.py+2 added-2 removed
118 unmodified lines119 assert body == b"Hello, world!"120 121 122 def 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!"126 127 with httpx.Client() as client:189 unmodified lines317 318 # Once we're closed we cannot reopen the client.319 with pytest.raises(RuntimeError):320 with client:321- pass # pragma: nocover321+ pass # pragma: no cover322 323 324 def test_client_closed_state_using_with_block():325 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:135 unmodified linesmodified:tests/client/test_properties.py+1 added-1 removed
51 unmodified lines52 53 54 def test_client_event_hooks():55 def on_request(request):56- pass # pragma: nocover56+ pass # pragma: no cover57 58 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 lines351 client = httpx.Client(transport=ConsumeBodyTransport(redirects))352 url = "https://example.org/redirect_body"353 354 def streaming_body():355- yield b"Example request body" # pragma: nocover355+ yield b"Example request body" # pragma: no cover356 357 with pytest.raises(httpx.StreamConsumed):358 client.post(url, content=streaming_body(), follow_redirects=True)359 86 unmodified linesmodified:tests/models/test_requests.py+8 added-8 removed
22 unmodified lines23 24 def test_iterable_content():25 class Content:26 def __iter__(self):27- yield b"test 123" # pragma: nocover27+ yield b"test 123" # pragma: no cover28 29 request = httpx.Request("POST", "http://example.org", content=Content())30 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}31 32 33 def test_generator_with_transfer_encoding_header():34 def content():35- yield b"test 123" # pragma: nocover35+ yield b"test 123" # pragma: no cover36 37 request = httpx.Request("POST", "http://example.org", content=content())38 assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"}39 40 41 def test_generator_with_content_length_header():42 def content():43- yield b"test 123" # pragma: nocover43+ yield b"test 123" # pragma: no cover44 45 headers = {"Content-Length": "8"}46 request = httpx.Request(47 "POST", "http://example.org", content=content(), headers=headers51 unmodified lines99 100 101 def test_cannot_access_streaming_content_without_read():102 # Ensure that streaming requests103- def streaming_body(): # pragma: nocover103+ def streaming_body(): # pragma: no cover104 yield ""105 106 request = httpx.Request("POST", "http://example.org", content=streaming_body())107 with pytest.raises(httpx.RequestNotRead):1 unmodified line109 110 111 def test_transfer_encoding_header():112 async def streaming_body(data):113- yield data # pragma: nocover113+ yield data # pragma: no cover114 115 data = streaming_body(b"test 123")116 117 request = httpx.Request("POST", "http://example.org", content=data)7 unmodified lines125 See https://github.com/encode/httpx/issues/1168126 """127 128 def streaming_body(data):129- yield data # pragma: nocover129+ yield data # pragma: no cover130 131 data = streaming_body(b"abcd")132 133 headers = {"Content-Length": "4"}17 unmodified lines151 152 153 def test_override_content_length_header():154 async def streaming_body(data):155- yield data # pragma: nocover155+ yield data # pragma: no cover156 157 data = streaming_body(b"test 123")158 headers = {"Content-Length": "8"}159 52 unmodified lines212 213 214 def test_request_generator_content_picklable():215 def content():216- yield b"test 123" # pragma: nocover216+ yield b"test 123" # pragma: no cover217 218 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 linesmodified:tests/models/test_responses.py+2 added-2 removed
914 unmodified lines915 916 917 def test_generator_with_transfer_encoding_header():918 def content():919- yield b"test 123" # pragma: nocover919+ yield b"test 123" # pragma: no cover920 921 response = httpx.Response(200, content=content())922 assert response.headers == {"Transfer-Encoding": "chunked"}923 924 925 def test_generator_with_content_length_header():926 def content():927- yield b"test 123" # pragma: nocover927+ yield b"test 123" # pragma: no cover928 929 headers = {"Content-Length": "8"}930 response = httpx.Response(200, content=content(), headers=headers)931 assert response.headers == {"Content-Length": "8"}82 unmodified linesmodified:tests/concurrency.py+1 added-1 removed
8 unmodified lines9 10 11 async 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 lines263 loop.create_task(self.watch_restarts()),264 }265 await asyncio.wait(tasks)266 267- 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 make2 unmodified lines274 self.restart_requested.set()275 while not self.started:276 await sleep(0.2)277 278- 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 linesmodified:tests/test_config.py+1 added-1 removed
175 unmodified lines176 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")180-def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: nocover180+def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: no cover181 with monkeypatch.context() as m:182 m.delenv("SSLKEYLOGFILE", raising=False)183 184 context = httpx.create_ssl_context(trust_env=True)38 unmodified linesmodified:tests/test_content.py+1 added-1 removed
71 unmodified lines72 self._idx = self._idx + chunk_size73 return chunk74 75 async def __aiter__(self):76- yield self._content # pragma: nocover76+ yield self._content # pragma: no cover77 78 headers, stream = encode_request(content=AsyncBytesIO(b"Hello, world!"))79 assert not isinstance(stream, typing.Iterable)80 assert isinstance(stream, typing.AsyncIterable)370 unmodified linesmodified:tests/test_exceptions.py+2 added-2 removed
19 unmodified lines20 and value not in HTTPCORE_EXC_MAP21 and value is not httpcore.ConnectionNotAvailable22 ]23 24- if not_mapped: # pragma: nocover24+ if not_mapped: # pragma: no cover25 pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")26 27 28 def test_httpcore_exception_mapping(server) -> None:40 unmodified lines69 and issubclass(value, Exception)70 and not hasattr(httpx, name)71 ]72 73- if not_exposed: # pragma: nocover73+ if not_exposed: # pragma: no cover74 pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")75 76 77 def test_request_attribute() -> None:9 unmodified lines