Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,95 @@ For async tests against an external server, create a client fixture with

By default, it connects to ``127.0.0.1:5432``.

Choosing how test databases are cloned
--------------------------------------
Comment thread
fizyk marked this conversation as resolved.
Resolved

Use ``create_strategy`` on ``postgresql_proc`` or ``postgresql_noproc`` to choose
how synchronous and asynchronous client fixtures clone the session's template
database for each test. The setting only affects client database creation;
initial and layered template databases keep PostgreSQL's default behavior.

.. code-block:: python

postgresql_my_proc = factories.postgresql_proc(create_strategy="clone")
postgresql_my = factories.postgresql("postgresql_my_proc")

For an existing server, including PostgreSQL in Docker, configure the noproc
factory instead. No server configuration change is needed:

.. code-block:: python

postgresql_external = factories.postgresql_noproc(create_strategy="clone")
postgresql_my = factories.postgresql("postgresql_external")
postgresql_my_async = factories.postgresql_async("postgresql_external")

The same setting is available on the command line and in ``pytest.ini``:

.. code-block:: sh

pytest --postgresql-create-strategy=clone

.. code-block:: ini

[pytest]
postgresql_create_strategy = clone

The available values are:

* Unset (the default): no ``STRATEGY`` clause or session setting is sent, leaving
the choice to PostgreSQL.
* ``wal_log``: ``CREATE DATABASE ... STRATEGY WAL_LOG``.
* ``file_copy``: ``SET file_copy_method = copy``, followed by
``CREATE DATABASE ... STRATEGY FILE_COPY`` on the same connection.
* ``clone``: ``SET file_copy_method = clone``, followed by
``CREATE DATABASE ... STRATEGY FILE_COPY`` on the same connection.

The session setting applies immediately before database creation and does not
require a server restart. Explicit strategies require PostgreSQL support:
``WAL_LOG`` requires PostgreSQL 15 or newer, while ``file_copy`` and ``clone``
require PostgreSQL 18 or newer for ``file_copy_method``. PostgreSQL reports unsupported
settings or strategies directly; the plugin does not silently fall back to another
mode. The ``clone`` method must also be supported by the server's operating system.

Factory arguments take precedence over command line and ini options. With chained
fixtures, configure the ``postgresql_noproc`` factory used by the client: its
strategy comes from its own argument or the global configuration, rather than
inheriting the strategy of the fixture named by ``depends_on``.

Filesystem and performance considerations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd trim this section and mostly defer to the official documentation where we can.

This summary though useful belongs to some additonal pages of a documentation (we don't have, apart from README) or official documentation for the postgresql/filesystems.... :/ I'm just afraid it'll clutter the README

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 9eeb73a. Removed the extended filesystem, Docker and benchmarking discussion. The README now keeps a short reflink/performance caveat and links to the official PostgreSQL CREATE DATABASE and file_copy_method documentation for the details. Applicable README pre-commit hooks (including rstcheck), source/wheel builds and PyPI README rendering pass.


On PostgreSQL 15 and newer, the default ``WAL_LOG`` strategy ignores
``file_copy_method``. Setting that parameter on the server alone therefore does
not enable file-copy cloning; choose ``file_copy`` or ``clone`` explicitly.

``clone`` can share file blocks when the PostgreSQL data directory's filesystem
supports reflinks, such as suitable XFS, Btrfs, or APFS configurations. Without
reflinks, the operating system may copy the data instead or reject the operation.
A successful ``clone`` request does not prove that disk blocks were shared.
Even with reflink support, template size and concurrent work can make another
strategy faster. This is why the option is opt-in and the default is unchanged.

Check the filesystem backing the server's actual data directory, which can be
found with ``SHOW data_directory``. In Docker, a volume, bind mount, and tmpfs can
have different behavior. Docker on macOS runs PostgreSQL in a Linux VM; a bind
mount of an APFS directory through file sharing is not equivalent to running
PostgreSQL directly on APFS. tmpfs is memory-backed and does not provide disk
reflinks; a fast ``clone`` result there is not evidence of reflink support.

``FILE_COPY`` forces checkpoints before and after database creation, which can
cause contention between concurrent pytest-xdist workers. Compare the complete
test suite at its usual worker count, including database creation and cleanup,
and repeat each strategy on the same storage with the same template and server
settings. Keep failed or timed-out runs separate from successful timings.
Faster isolated database creation does not guarantee a faster test suite, and
results from one filesystem or worker count need not transfer to another.

For details, see PostgreSQL's `CREATE DATABASE strategy documentation
<https://www.postgresql.org/docs/18/sql-createdatabase.html>`_ and
`file_copy_method documentation
<https://www.postgresql.org/docs/18/runtime-config-resource.html#GUC-FILE-COPY-METHOD>`_.

Using a maintenance database other than ``postgres``
----------------------------------------------------

Expand Down Expand Up @@ -416,6 +505,12 @@ You can define settings via fixture factory arguments, command line options, or
- --postgresql-load-autocommit
- postgresql_load_autocommit
- False
* - Test database cloning strategy
- create_strategy
- create_strategy
- --postgresql-create-strategy
- postgresql_create_strategy
- PostgreSQL's default
* - PostgreSQL connection options
- options
- options
Expand Down
4 changes: 4 additions & 0 deletions newsfragments/1260.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Add ``create_strategy`` to the process and noproc factories, with matching CLI
and ini options, to select PostgreSQL's default, ``wal_log``, ``file_copy``, or
the operating-system ``clone`` method when client fixtures copy the template
database. The default remains unchanged; cloning does not guarantee reflinks.
18 changes: 18 additions & 0 deletions pytest_postgresql/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@
import pytest
from _pytest._py.path import LocalPath

CREATE_STRATEGIES = ("wal_log", "file_copy", "clone")


def validate_create_strategy(create_strategy: str | None) -> str | None:
"""Validate the optional database cloning strategy."""
if create_strategy is not None and create_strategy not in CREATE_STRATEGIES:
raise ValueError(
f"Invalid PostgreSQL create_strategy {create_strategy!r}; "
f"expected one of {', '.join(CREATE_STRATEGIES)} or None"
)
return create_strategy


@dataclass(frozen=True)
class PostgreSQLConfig:
Expand All @@ -27,6 +39,7 @@ class PostgreSQLConfig:
load_autocommit: bool
postgres_options: str
drop_test_database: bool
create_strategy: str | None = None


def get_config(request: pytest.FixtureRequest) -> PostgreSQLConfig:
Expand All @@ -37,6 +50,10 @@ def get_postgresql_option(option: str) -> Any:
return request.config.getoption(name) or request.config.getini(name)

load_paths: list[Path | str] = detect_paths(get_postgresql_option("load"))
try:
create_strategy = validate_create_strategy(get_postgresql_option("create_strategy"))
except ValueError as exc:
raise pytest.UsageError(str(exc)) from exc

cfg = PostgreSQLConfig(
exec=get_postgresql_option("exec"),
Expand All @@ -54,6 +71,7 @@ def get_postgresql_option(option: str) -> Any:
load=load_paths,
load_autocommit=bool(get_postgresql_option("load_autocommit")),
postgres_options=get_postgresql_option("postgres_options"),
create_strategy=create_strategy,
drop_test_database=request.config.getoption("postgresql_drop_test_database"),
)
return cfg
Expand Down
3 changes: 3 additions & 0 deletions pytest_postgresql/executors/noop.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def __init__(
dbname: str,
password: str | None = None,
maintenance_dbname: str = "postgres",
create_strategy: str | None = None,
):
"""Initialize nooperator executor mock.

Expand All @@ -52,6 +53,7 @@ def __init__(
:param maintenance_dbname: database to connect to for server-level work,
i.e. reading the server version. Defaults to ``postgres``. Point it at
a database the user can reach when ``postgres`` is unavailable.
:param create_strategy: strategy used by client fixtures to clone databases
"""
self.host = host
self.port = int(port)
Expand All @@ -60,6 +62,7 @@ def __init__(
self.password = password
self.dbname = dbname
self.maintenance_dbname = maintenance_dbname
self.create_strategy = create_strategy
self._version: Any = None

@property
Expand Down
3 changes: 3 additions & 0 deletions pytest_postgresql/executors/proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def __init__(
password: str | None = None,
options: str = "",
postgres_options: str = "",
create_strategy: str | None = None,
):
"""Initialize PostgreSQLExecutor executor.

Expand All @@ -127,6 +128,7 @@ def __init__(
:param dbname: database name (might not yet exist)
:param options:
:param postgres_options: extra arguments to `postgres start`
:param create_strategy: strategy used by client fixtures to clone databases
"""
self._directory_initialised = False
self.executable = executable
Expand All @@ -139,6 +141,7 @@ def __init__(
self.logfile = logfile
self.startparams = startparams
self.postgres_options = postgres_options
self.create_strategy = create_strategy
if platform.system() == "Windows":
command = self.WINDOWS_PROC_START_COMMAND.format(
executable=self.executable,
Expand Down
15 changes: 14 additions & 1 deletion pytest_postgresql/factories/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@
from pytest_postgresql._asyncio_compat import mark_postgresql_async_fixture, supports_loop_factories
from pytest_postgresql.config import get_config
from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor
from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseJanitor
from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseCreationStrategy, DatabaseJanitor, FileCopyMethod

_CREATE_STRATEGY_OPTIONS: dict[str | None, tuple[DatabaseCreationStrategy | None, FileCopyMethod | None]] = {
None: (None, None),
"wal_log": ("WAL_LOG", None),
"file_copy": ("FILE_COPY", "copy"),
"clone": ("FILE_COPY", "clone"),
}

try:
import pytest_asyncio as _pytest_asyncio
Expand Down Expand Up @@ -85,6 +92,7 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]:
pg_password = proc_fixture.password
pg_options = proc_fixture.options
pg_db = dbname or proc_fixture.dbname
strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
janitor = DatabaseJanitor(
user=pg_user,
host=pg_host,
Expand All @@ -94,6 +102,8 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]:
maintenance_dbname=proc_fixture.maintenance_dbname,
password=pg_password,
isolation_level=isolation_level,
strategy=strategy,
copy_method=copy_method,
)
if config.drop_test_database:
janitor.drop()
Expand Down Expand Up @@ -150,6 +160,7 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera
pg_password = proc_fixture.password
pg_options = proc_fixture.options
pg_db = dbname or proc_fixture.dbname
strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
janitor = AsyncDatabaseJanitor(
user=pg_user,
host=pg_host,
Expand All @@ -159,6 +170,8 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera
maintenance_dbname=proc_fixture.maintenance_dbname,
password=pg_password,
isolation_level=isolation_level,
strategy=strategy,
copy_method=copy_method,
)
if config.drop_test_database:
await janitor.drop()
Expand Down
7 changes: 6 additions & 1 deletion pytest_postgresql/factories/noprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

import pytest

from pytest_postgresql.config import get_config
from pytest_postgresql.config import get_config, validate_create_strategy
from pytest_postgresql.executors import NoopExecutor
from pytest_postgresql.janitor import DatabaseJanitor

Expand All @@ -48,6 +48,7 @@ def postgresql_noproc(
load: list[Callable | str | Path] | None = None,
load_autocommit: bool | None = None,
depends_on: str | None = None,
create_strategy: str | None = None,
) -> Callable[[pytest.FixtureRequest], Iterator[NoopExecutor]]:
"""Postgresql noprocess factory.

Expand All @@ -67,8 +68,11 @@ def postgresql_noproc(
Required for statements that cannot run inside a transaction block,
e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
:param depends_on: Optional name of the fixture to depend on.
:param create_strategy: strategy used by client fixtures to clone the template:
``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
:returns: function which makes a postgresql process
"""
validate_create_strategy(create_strategy)

@pytest.fixture(scope="session")
def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopExecutor]:
Expand Down Expand Up @@ -120,6 +124,7 @@ def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopEx
dbname=noop_exec_dbname,
options=pg_options,
maintenance_dbname=pg_maintenance_dbname,
create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
)
janitor = DatabaseJanitor(
user=noop_exec.user,
Expand Down
7 changes: 6 additions & 1 deletion pytest_postgresql/factories/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import pytest
from port_for import PortForException, get_port

from pytest_postgresql.config import PostgreSQLConfig, get_config
from pytest_postgresql.config import PostgreSQLConfig, get_config, validate_create_strategy
from pytest_postgresql.executors import PostgreSQLExecutor
from pytest_postgresql.factories._pg import _pg_exe
from pytest_postgresql.janitor import DatabaseJanitor
Expand Down Expand Up @@ -80,6 +80,7 @@ def postgresql_proc(
postgres_options: str | None = None,
load: list[Callable | str | Path] | None = None,
load_autocommit: bool | None = None,
create_strategy: str | None = None,
) -> Callable[[pytest.FixtureRequest, pytest.TempPathFactory], Iterator[PostgreSQLExecutor]]:
"""Postgresql process factory.

Expand All @@ -103,8 +104,11 @@ def postgresql_proc(
:param load_autocommit: run the SQL loader connection with autocommit on.
Required for statements that cannot run inside a transaction block,
e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
:param create_strategy: strategy used by client fixtures to clone the template:
``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
:returns: function which makes a postgresql process
"""
validate_create_strategy(create_strategy)

@pytest.fixture(scope="session")
def postgresql_proc_fixture(
Expand Down Expand Up @@ -201,6 +205,7 @@ def _cleanup_executor_resources() -> None:
logfile=str(logfile_path.resolve()),
startparams=startparams or config.startparams,
postgres_options=postgres_options or config.postgres_options,
create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
)
postgresql_executor.start()
postgresql_executor.wait_for_postgres()
Expand Down
Loading
Loading