Cloudflare KV, R2, and D1 (Miniflare)#

Integration with Miniflare, the local simulator behind wrangler dev, for Cloudflare Workers KV, R2, and D1. The container runs Miniflare in a stock node:22-slim image with one placeholder Worker that binds every configured KV namespace, R2 bucket, and D1 database, and serves two HTTP APIs on port 8787:

  • The Local Explorer API at /cdn-cgi/local/explorer/api, which answers with the Cloudflare v4 JSON envelope ({"success": true, "errors": [], "messages": [], "result": ...}) and mirrors the Cloudflare REST paths for KV values, R2 objects, and D1 queries.

  • An S3-compatible R2 endpoint at /cdn-cgi/local/r2/s3 (AWS Signature Version 4, path-style addressing, region auto) that accepts cloudflare_access_key_id / cloudflare_secret_access_key.

The fixture is clientless: readiness checks and the CloudflareService helpers use Python’s standard library, so neither wrangler nor a Cloudflare or AWS SDK is required.

Installation#

pip install pytest-databases

Usage Example#

CloudflareService exposes the resource names this service owns and small helpers for each store. kv_get and r2_get return None for a missing key; d1_query returns one dictionary per row:

from pytest_databases.docker.cloudflare import CloudflareService

pytest_plugins = ["pytest_databases.docker.cloudflare"]


def test_kv(cloudflare_service: CloudflareService) -> None:
    namespace = cloudflare_service.kv_namespaces[0]
    cloudflare_service.kv_put(namespace, "session/42", "active")
    assert cloudflare_service.kv_get(namespace, "session/42") == b"active"


def test_r2(cloudflare_service: CloudflareService) -> None:
    bucket = cloudflare_service.r2_buckets[0]
    cloudflare_service.r2_put(bucket, "reports/2026.csv", b"id,total\n1,10\n")
    assert cloudflare_service.r2_get(bucket, "reports/2026.csv") == b"id,total\n1,10\n"


def test_d1(cloudflare_service: CloudflareService) -> None:
    database = cloudflare_service.d1_databases[0]
    cloudflare_service.d1_query(database, "CREATE TABLE IF NOT EXISTS items (id INTEGER, name TEXT)")
    cloudflare_service.d1_query(database, "INSERT INTO items VALUES (?, ?)", ["1", "widget"])
    assert cloudflare_service.d1_query(database, "SELECT id, name FROM items") == [{"id": 1, "name": "widget"}]

The helpers accept only the names in kv_namespaces, r2_buckets, and d1_databases and raise ValueError for any other name. d1_query sends one statement per call (with several, the emulator returns only the last statement’s rows), and the D1 API accepts string parameters only; SQLite column affinity converts them on insert. Other Local Explorer endpoints are available under cloudflare_service.api_base_url.

R2 through an S3 client#

Point any S3 client at r2_s3_endpoint_url with path-style addressing and region auto. With boto3 installed in your project:

import boto3
from botocore.config import Config

from pytest_databases.docker.cloudflare import CloudflareService

pytest_plugins = ["pytest_databases.docker.cloudflare"]


def test_r2_s3(cloudflare_service: CloudflareService) -> None:
    s3 = boto3.client(
        "s3",
        endpoint_url=cloudflare_service.r2_s3_endpoint_url,
        aws_access_key_id=cloudflare_service.access_key_id,
        aws_secret_access_key=cloudflare_service.secret_access_key,
        region_name="auto",
        config=Config(s3={"addressing_style": "path"}),
    )
    bucket = cloudflare_service.r2_buckets[0]
    s3.put_object(Bucket=bucket, Key="hello.txt", Body=b"hello")
    assert s3.get_object(Bucket=bucket, Key="hello.txt")["Body"].read() == b"hello"

The S3 endpoint serves only the configured buckets; it cannot create new ones.

Configuring resources#

Override the resource fixtures to bind more namespaces, buckets, or databases. Each fixture returns a tuple of names (default ("default",)):

import pytest


@pytest.fixture(scope="session")
def cloudflare_kv_namespaces() -> tuple[str, ...]:
    return ("sessions", "cache")


@pytest.fixture(scope="session")
def cloudflare_r2_buckets() -> tuple[str, ...]:
    return ("uploads",)

Startup and network access#

On first start the container installs ca-certificates with apt-get (workerd, Miniflare’s runtime, needs system CA certificates) and runs npm install miniflare@<cloudflare_miniflare_version>, which downloads about 200 MB including the workerd binary. The first start therefore needs network access to the Debian and npm registries and usually takes one to two minutes; cloudflare_startup_timeout (default 300 seconds, env CLOUDFLARE_STARTUP_TIMEOUT) bounds the wait. Containers reused within a session start instantly.

The installs are skipped when the image already provides them. To start offline or faster, build an image that has the certificates and Miniflare in /app and point CLOUDFLARE_IMAGE (or the cloudflare_image fixture) at it:

FROM node:22-slim
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /app
RUN npm install --no-audit --no-fund miniflare@5.20261104.0-beta

The image must be glibc-based (workerd does not run on Alpine/musl) and provide Node.js 22 or later.

Isolation#

With the default xdist_cloudflare_isolation_level (database), all pytest-xdist workers share one container named cloudflare. It binds every configured name once per worker with a _<worker> suffix (default_0, default_1, …), and each worker’s CloudflareService lists only its own names, so workers never see each other’s keys, objects, or tables. Without pytest-xdist the names are used as given. With server each worker starts its own container named cloudflare_<worker> with the names as given.

The shared container’s bindings are fixed when it starts. If a container kept from an earlier run (for example with --keep-containers) does not bind every name a worker needs, the fixture fails with a message asking you to remove the container.

Limitations#

  • Only Miniflare 5 serves the Local Explorer and R2 S3 paths; Miniflare 4 routes them to the user Worker. Miniflare 5 is published under the npm beta tag, so cloudflare_miniflare_version pins 5.20261104.0-beta (env CLOUDFLARE_MINIFLARE_VERSION). The Local Explorer API is marked unsafe and experimental upstream and can change between Miniflare releases.

  • The first start needs network access (see above) unless a prebuilt image is used.

  • Only KV, R2, and D1 are exposed. The placeholder Worker answers every request with ok; there is no API to deploy or run your own Worker code, and Durable Objects, Queues, Workflows, and other bindings are not configured.

  • Data lives in the container (/data) and is discarded with it.

Available Fixtures#

  • cloudflare_image: Node.js image that runs Miniflare (default node:22-slim, env CLOUDFLARE_IMAGE).

  • cloudflare_miniflare_version: Miniflare version installed when the image lacks it (env CLOUDFLARE_MINIFLARE_VERSION).

  • cloudflare_kv_namespaces, cloudflare_r2_buckets, cloudflare_d1_databases: resource names (default ("default",)).

  • cloudflare_access_key_id, cloudflare_secret_access_key: credentials for the R2 S3 endpoint (defaults pytest-databases / pytest-databases-secret, env CLOUDFLARE_ACCESS_KEY_ID / CLOUDFLARE_SECRET_ACCESS_KEY).

  • cloudflare_startup_timeout: startup timeout in seconds (default 300, env CLOUDFLARE_STARTUP_TIMEOUT).

  • xdist_cloudflare_isolation_level: database (default) or server.

  • cloudflare_service: the running CloudflareService.

Service API#

Cloudflare KV, R2, and D1 emulator fixtures backed by Miniflare’s Local Explorer API.

The container runs Miniflare in a stock node image with one placeholder Worker that binds every configured KV namespace, R2 bucket, and D1 database. The fixtures and the service helpers talk to Miniflare over HTTP with the standard library:

  • /cdn-cgi/local/explorer/api: the Local Explorer API, which answers with the Cloudflare v4 JSON envelope ({"success": ..., "errors": [...], "messages": [...], "result": ...}).

  • /cdn-cgi/local/r2/s3: an S3-compatible endpoint for the R2 buckets (AWS Signature Version 4, path-style addressing, region auto) that accepts the configured access key pair.

Only Miniflare 5 serves these paths; Miniflare 4 routes them to the user Worker. On first start the container installs ca-certificates (workerd needs system CA certificates) and miniflare from npm, so it needs network access; an image that already provides both skips the installs.

class pytest_databases.docker.cloudflare.CloudflareService(container: docker.models.containers.Container, host: str, port: int, access_key_id: str, secret_access_key: str, kv_namespaces: tuple[str, ...], r2_buckets: tuple[str, ...], d1_databases: tuple[str, ...])[source]#

Endpoints, credentials, resource names, and stdlib helpers for a running Miniflare emulator.

kv_namespaces, r2_buckets, and d1_databases hold the resource names this service may use; under pytest-xdist with database isolation they carry the worker suffix (default_0, default_1, …). The helpers accept only these names, so a test cannot write into another worker’s resources by accident.

access_key_id: str#
secret_access_key: str#
kv_namespaces: tuple[str, ...]#
r2_buckets: tuple[str, ...]#
d1_databases: tuple[str, ...]#
property endpoint_url: str#

Base URL of the Miniflare HTTP server.

property api_base_url: str#

Base URL of the Local Explorer API (Cloudflare v4 JSON envelope).

property r2_s3_endpoint_url: str#

S3-compatible R2 endpoint; sign requests with access_key_id, secret_access_key, region auto.

kv_put(namespace: str, key: str, value: bytes | str) → None[source]#

Write a value to a KV namespace.

Parameters:
  • namespace – One of kv_namespaces.

  • key – Key to write; any characters are allowed.

  • value – Value to store; str values are encoded as UTF-8.

kv_get(namespace: str, key: str) → bytes | None[source]#

Read a value from a KV namespace.

Parameters:
  • namespace – One of kv_namespaces.

  • key – Key to read.

Returns:

The stored bytes, or None when the key does not exist.

r2_put(bucket: str, key: str, value: bytes | str) → None[source]#

Write an object to an R2 bucket through the Local Explorer API.

Parameters:
  • bucket – One of r2_buckets.

  • key – Object key; / is kept as part of the key.

  • value – Object body; str values are encoded as UTF-8.

r2_get(bucket: str, key: str) → bytes | None[source]#

Read an object from an R2 bucket through the Local Explorer API.

Parameters:
  • bucket – One of r2_buckets.

  • key – Object key.

Returns:

The object body, or None when the object does not exist.

d1_query(database: str, sql: str, params: Sequence[str] | None = None) → list[dict[str, Any]][source]#

Run one SQL statement against a D1 database and return its rows.

Parameters:
  • database – One of d1_databases.

  • sql – SQL statement with ? placeholders. When several statements are sent, the emulator returns only the rows of the last one.

  • params – Placeholder values. The API accepts strings only; SQLite column affinity converts them on insert.

Returns:

One dictionary per row, keyed by column name.

Raises:

RuntimeError – If the statement fails or the response has no result set.

__init__(container: docker.models.containers.Container, host: str, port: int, access_key_id: str, secret_access_key: str, kv_namespaces: tuple[str, ...], r2_buckets: tuple[str, ...], d1_databases: tuple[str, ...]) → None#
pytest_databases.docker.cloudflare.cloudflare_access_key_id() → str[source]#

Provide the access key ID accepted by the R2 S3 endpoint.

pytest_databases.docker.cloudflare.cloudflare_d1_databases() → tuple[str, ...][source]#

Provide the D1 database ids bound by the emulator.

pytest_databases.docker.cloudflare.cloudflare_image() → str[source]#

Provide the Node.js image that runs Miniflare.

pytest_databases.docker.cloudflare.cloudflare_kv_namespaces() → tuple[str, ...][source]#

Provide the KV namespace ids bound by the emulator.

pytest_databases.docker.cloudflare.cloudflare_miniflare_version() → str[source]#

Provide the Miniflare npm version installed when the image does not ship miniflare.

pytest_databases.docker.cloudflare.cloudflare_r2_buckets() → tuple[str, ...][source]#

Provide the R2 bucket names bound by the emulator.

pytest_databases.docker.cloudflare.cloudflare_secret_access_key() → str[source]#

Provide the secret access key accepted by the R2 S3 endpoint.

pytest_databases.docker.cloudflare.cloudflare_service(container_service: ContainerService, cloudflare_image: str, cloudflare_miniflare_version: str, cloudflare_kv_namespaces: tuple[str, ...], cloudflare_r2_buckets: tuple[str, ...], cloudflare_d1_databases: tuple[str, ...], cloudflare_access_key_id: str, cloudflare_secret_access_key: str, xdist_cloudflare_isolation_level: XdistIsolationLevel, cloudflare_startup_timeout: int) → Generator[CloudflareService, None, None][source]#

Start and yield a ready Miniflare Cloudflare emulator container.

Yields:

A configured CloudflareService instance.

pytest_databases.docker.cloudflare.cloudflare_startup_timeout() → int[source]#

Provide the emulator startup timeout in seconds; the first start downloads Miniflare and workerd.

pytest_databases.docker.cloudflare.provide_cloudflare_service(container_service: ContainerService, cloudflare_image: str, cloudflare_miniflare_version: str, cloudflare_kv_namespaces: Sequence[str], cloudflare_r2_buckets: Sequence[str], cloudflare_d1_databases: Sequence[str], cloudflare_access_key_id: str, cloudflare_secret_access_key: str, xdist_cloudflare_isolation_level: XdistIsolationLevel, cloudflare_startup_timeout: int = 300) → Generator[CloudflareService, None, None][source]#

Start and yield a ready Miniflare Cloudflare emulator container.

Without pytest-xdist the configured names are used as given. Under pytest-xdist with database isolation all workers share one container named cloudflare, which binds <name>_<worker> for every worker, and each worker’s service lists only its own names. With server isolation each worker starts its own transient container named cloudflare_<worker> with the names as given.

Parameters:
  • container_service – Session container service.

  • cloudflare_image – Image with Node.js 22 or later on glibc.

  • cloudflare_miniflare_version – Miniflare npm version installed when the image does not provide miniflare.

  • cloudflare_kv_namespaces – KV namespace ids.

  • cloudflare_r2_buckets – R2 bucket names.

  • cloudflare_d1_databases – D1 database ids.

  • cloudflare_access_key_id – Access key ID accepted by the R2 S3 endpoint.

  • cloudflare_secret_access_key – Secret access key accepted by the R2 S3 endpoint.

  • xdist_cloudflare_isolation_level – pytest-xdist isolation level.

  • cloudflare_startup_timeout – Seconds to wait for the emulator; the first start installs packages.

Yields:

A configured CloudflareService instance.

Raises:

RuntimeError – If a reused container does not bind every resource this worker needs.

pytest_databases.docker.cloudflare.xdist_cloudflare_isolation_level() → Literal['database', 'server'][source]#

Provide the pytest-xdist isolation level for the Cloudflare emulator (database: one shared container).