From 2fcf23bbfe41c5526cb35a65d32dd98dde786988 Mon Sep 17 00:00:00 2001 From: Florimond Manca Date: Wed, 6 Nov 2019 12:04:20 +0100 Subject: [PATCH] Refactor debug and trace log tests (#506) --- tests/test_utils.py | 34 ++++++++++++++++------------------ tests/utils.py | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 18 deletions(-) create mode 100644 tests/utils.py diff --git a/tests/test_utils.py b/tests/test_utils.py index 7546df07..959fbf8f 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,11 +1,9 @@ import asyncio -import logging import os import pytest import httpx -from httpx import utils from httpx.utils import ( ElapsedTimer, get_ca_bundle_from_env, @@ -16,6 +14,7 @@ from httpx.utils import ( parse_header_links, should_not_be_proxied, ) +from tests.utils import override_log_level @pytest.mark.parametrize( @@ -103,24 +102,23 @@ def test_parse_header_links(value, expected): @pytest.mark.asyncio -@pytest.mark.parametrize("httpx_log_level", ["trace", "debug"]) -async def test_httpx_log_level_enabled_stderr_logging(server, capsys, httpx_log_level): - os.environ["HTTPX_LOG_LEVEL"] = httpx_log_level +async def test_logs_debug(server, capsys): + with override_log_level("debug"): + async with httpx.AsyncClient() as client: + response = await client.get(server.url) + assert response.status_code == 200 + stderr = capsys.readouterr().err + assert "httpx.dispatch.connection_pool" not in stderr - # Force a reload on the logging handlers - utils._LOGGER_INITIALIZED = False - utils.get_logger("httpx") - async with httpx.AsyncClient() as client: - await client.get(server.url) - - if httpx_log_level == "trace": - assert "httpx.dispatch.connection_pool" in capsys.readouterr().err - else: - assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err - - # Reset the logger so we don't have verbose output in all unit tests - logging.getLogger("httpx").handlers = [] +@pytest.mark.asyncio +async def test_logs_trace(server, capsys): + with override_log_level("trace"): + async with httpx.AsyncClient() as client: + response = await client.get(server.url) + assert response.status_code == 200 + stderr = capsys.readouterr().err + assert "httpx.dispatch.connection_pool" in stderr def test_get_ssl_cert_file(): diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 00000000..50840227 --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,20 @@ +import contextlib +import logging +import os + +from httpx import utils + + +@contextlib.contextmanager +def override_log_level(log_level: str): + os.environ["HTTPX_LOG_LEVEL"] = log_level + + # Force a reload on the logging handlers + utils._LOGGER_INITIALIZED = False + utils.get_logger("httpx") + + try: + yield + finally: + # Reset the logger so we don't have verbose output in all unit tests + logging.getLogger("httpx").handlers = [] -- 2.47.3