惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
博客园 - 【当耐特】
量子位
C
Check Point Blog
博客园 - 叶小钗
博客园 - 聂微东
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
The Cloudflare Blog
T
Tailwind CSS Blog
人人都是产品经理
人人都是产品经理
月光博客
月光博客
V
V2EX
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
大猫的无限游戏
大猫的无限游戏
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
S
SegmentFault 最新的问题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

alexwlchan’s notes

What is WS11 1DB? Blocking referrers with Caddy How to type a Spanish question mark (¿) on a Mac Non-overlapping type comparisons and Python type checkers Why does t.Setenv panic after t.Parallel? Use Path.glob() and Path.rglob() for typed versions of glob.glob() Curious clocks and colourful eyes Track which templates are used by Jinja2 Archeologists distinguish between “sherds” and “shards” A single command to test all my changed Go packages Disable the new message animations in WhatsApp Finding high-churn folders that bother Backblaze Always-on SSH agent forwarding with my Git pushes Managing the caption of a photo with AppleScript (but not PhotoKit) Goodhart’s and Campbell’s Law are different Notes from The Cornishman No. 176 (Spring 2026) Notes from The Cornishman No. 176 (Spring 2026) GitUp can’t diff text files larger than 8MB Home Testing the width of a page on a mobile device using Playwright Disable AirPods charging notifications Filter a list of JSON object based on a list of tags HOME_GET_ME_HOME is a Citymapper Shortcuts action The FileExistsError exception exposes a filename attribute The red-lined bubble snail Why can’t Python connect to example.com? Useful type hints for Python How to truncate the middle of long command output AirPlay Receiver can interfere with Flask apps What’s the main prefix in SQLite queries?
Start a Caddy server in a subprocess during a Python session
2026-04-30 · via alexwlchan’s notes

Start the server with subprocess.Popen, poll until it’s available, yield the base URL, then clean up the process when you’re done.

For local developemnt and testing of this site, I’ve started to run a Caddy server with my real config to be a better replica of my real setup. I wanted to start a Caddy server in my automated tests, and shut it down when I’m done.

Here’s the fixture I came up with:

from collections.abc import Iterator
import subprocess
from subprocess import PIPE
import time
import urllib.error
import urllib.request

import pytest


@pytest.fixture(scope="session")
def caddy_server_url() -> Iterator[str]:
    """
    Start an instance of Caddy running in the current directory, and
    return the base URL.
    """
    port = 5858
    cmd = ["caddy", "file-server", "--listen", f":{port}"]

    with subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE) as proc:
        url = f"http://localhost:{port}/"

        # Wait for up to a second waiting for the server to start.
        #
        # If we get a ConnectionRefusedError, the server hasn't started yet.
        # If we get an HTTPError or a 200 OK, we've connected to the server
        # and it's serving HTTP traffic, so it's started.
        t0 = time.time()
        while time.time() - t0 < 1:
            try:
                urllib.request.urlopen(url)
            except urllib.error.HTTPError:
                break
            except urllib.error.URLError as exc:
                if exc.args and isinstance(exc.args[0], ConnectionRefusedError):
                    pass
                else:
                    raise
            else:
                break

        assert not proc.poll()

        yield url

        proc.terminate()
        proc.wait(timeout=1)

And here’s what a test looks like:

def test_can_start_web_server(caddy_server_url: str) -> None:
    """
    Fetch a page from the running web server.
    """
    resp = urllib.request.urlopen(caddy_server_url + "example.py")
    assert b"test_can_start_web_server" in resp.read()

The fixture starts a file server with subprocess, then polls until the server is available. On my Mac mini, Caddy takes ~0.01s to start – long enough I can’t start running tests immediately, fast enough that any fixed sleep would be inefficient (especially as it’ll be slower in CI).

At the end of the fixture, I call proc.terminate() and proc.wait() to clean everything up. The terminate() sends a SIGTERM; the wait() blocks until the child process terminates. The process shuts down quickly, but I do need to wait or I get warnings from pytest that I have an unterminated process.

The fixture is session-scoped so I only have to start/stop the server once across my test suite.

In my real codebase, this code is split across two functions – a function that starts the server, and a function that wraps it in a pytest fixture. I reuse the server function in my serve_site.py script, which runs a local development server for the site. I’m also pointing it at a Caddyfile with my site config, rather than running a bare file_server.

This is similar to Simon Willison’s recipe.