Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve logging test and increase coverage on server.py #1743

Merged
merged 24 commits into from Nov 2, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
69 changes: 69 additions & 0 deletions tests/middleware/test_logging.py
@@ -1,5 +1,11 @@
import contextlib
import logging
import os
import sys
from hashlib import md5
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4

import httpx
import pytest
Expand Down Expand Up @@ -36,6 +42,41 @@ async def app(scope, receive, send):
await send({"type": "http.response.body", "body": b"", "more_body": False})


@pytest.fixture
def short_socket_name(tmp_path, tmp_path_factory): # pragma: py-win32
max_sock_len = 100
socket_filename = "my.sock"
identifier = f"{uuid4()}-"
identifier_len = len(identifier.encode())
tmp_dir = Path("/tmp").resolve()
os_tmp_dir = Path(os.getenv("TMPDIR", "/tmp")).resolve()
basetemp = Path(
str(tmp_path_factory.getbasetemp()),
).resolve()
hash_basetemp = md5(
str(basetemp).encode(),
).hexdigest()

def make_tmp_dir(base_dir):
return TemporaryDirectory(
dir=str(base_dir),
prefix="p-",
suffix=f"-{hash_basetemp}",
)

paths = basetemp, os_tmp_dir, tmp_dir
for num, tmp_dir_path in enumerate(paths, 1):
with make_tmp_dir(tmp_dir_path) as tmpd:
tmpd = Path(tmpd).resolve()
sock_path = str(tmpd / socket_filename)
sock_path_len = len(sock_path.encode())
if sock_path_len <= max_sock_len:
if max_sock_len - sock_path_len >= identifier_len: # pragma: no cover
sock_path = str(tmpd / "".join((identifier, socket_filename)))
yield sock_path
return
iudeen marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.anyio
async def test_trace_logging(caplog, logging_config):
config = Config(
Expand Down Expand Up @@ -155,6 +196,34 @@ async def test_default_logging(use_colors, caplog, logging_config):
assert "Shutting down" in messages.pop(0)


@pytest.mark.anyio
@pytest.mark.parametrize("use_colors", [(True), (False)])
@pytest.mark.skipif(sys.platform == "win32", reason="require unix-like system")
async def test_default_logging_with_uds(
use_colors, caplog, logging_config, short_socket_name
): # pragma: py-win32
config = Config(
app=app, use_colors=use_colors, log_config=logging_config, uds=short_socket_name
)
with caplog_for_logger(caplog, "uvicorn.access"):
async with run_server(config):
transport = httpx.AsyncHTTPTransport(uds=short_socket_name)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.get("http://my")
assert response.status_code == 204

messages = [
record.message for record in caplog.records if "uvicorn" in record.name
]
assert "Started server process" in messages.pop(0)
assert "Waiting for application startup" in messages.pop(0)
assert "ASGI 'lifespan' protocol appears unsupported" in messages.pop(0)
assert "Application startup complete" in messages.pop(0)
assert "Uvicorn running on unix socket " + short_socket_name in messages.pop(0)
assert '"GET / HTTP/1.1" 204' in messages.pop(0)
assert "Shutting down" in messages.pop(0)


@pytest.mark.anyio
async def test_unknown_status_code(caplog):
async def app(scope, receive, send):
Expand Down
4 changes: 2 additions & 2 deletions uvicorn/server.py
Expand Up @@ -174,14 +174,14 @@ def _share_socket(sock: socket.SocketType) -> socket.SocketType:
def _log_started_message(self, listeners: Sequence[socket.SocketType]) -> None:
config = self.config

if config.fd is not None:
if config.fd is not None: # pragma: py-win32
sock = listeners[0]
logger.info(
"Uvicorn running on socket %s (Press CTRL+C to quit)",
sock.getsockname(),
)

elif config.uds is not None:
elif config.uds is not None: # pragma: py-win32
logger.info(
"Uvicorn running on unix socket %s (Press CTRL+C to quit)", config.uds
)
Expand Down