From cc5a2d3e227d344351e2ef1c5becf859900dc9a8 Mon Sep 17 00:00:00 2001 From: Deo Date: Mon, 2 Nov 2026 08:24:54 +0800 Subject: [PATCH 1/5] Add opt-in database creation strategies (refs #1260) --- README.rst | 95 +++++++ newsfragments/1260.feature.rst | 4 + pytest_postgresql/config.py | 18 ++ pytest_postgresql/executors/noop.py | 3 + pytest_postgresql/executors/proc.py | 3 + pytest_postgresql/factories/client.py | 2 + pytest_postgresql/factories/noprocess.py | 7 +- pytest_postgresql/factories/process.py | 7 +- pytest_postgresql/janitor.py | 25 ++ pytest_postgresql/plugin.py | 11 + tests/test_create_strategy.py | 314 +++++++++++++++++++++++ tests/test_pg_exe.py | 1 + 12 files changed, 488 insertions(+), 2 deletions(-) create mode 100644 newsfragments/1260.feature.rst create mode 100644 tests/test_create_strategy.py diff --git a/README.rst b/README.rst index 4615139f..fa1ae6a7 100644 --- a/README.rst +++ b/README.rst @@ -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 +-------------------------------------- + +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 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +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 +`_ and +`file_copy_method documentation +`_. + Using a maintenance database other than ``postgres`` ---------------------------------------------------- @@ -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 diff --git a/newsfragments/1260.feature.rst b/newsfragments/1260.feature.rst new file mode 100644 index 00000000..a32c3255 --- /dev/null +++ b/newsfragments/1260.feature.rst @@ -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. diff --git a/pytest_postgresql/config.py b/pytest_postgresql/config.py index bf330acb..ff435014 100644 --- a/pytest_postgresql/config.py +++ b/pytest_postgresql/config.py @@ -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: @@ -26,6 +38,7 @@ class PostgreSQLConfig: load: list[Path | str] load_autocommit: bool postgres_options: str + create_strategy: str | None drop_test_database: bool @@ -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"), @@ -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 diff --git a/pytest_postgresql/executors/noop.py b/pytest_postgresql/executors/noop.py index db98af69..e39d034f 100644 --- a/pytest_postgresql/executors/noop.py +++ b/pytest_postgresql/executors/noop.py @@ -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. @@ -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) @@ -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 diff --git a/pytest_postgresql/executors/proc.py b/pytest_postgresql/executors/proc.py index fa9bc620..8562522e 100644 --- a/pytest_postgresql/executors/proc.py +++ b/pytest_postgresql/executors/proc.py @@ -107,6 +107,7 @@ def __init__( password: str | None = None, options: str = "", postgres_options: str = "", + create_strategy: str | None = None, ): """Initialize PostgreSQLExecutor executor. @@ -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 @@ -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, diff --git a/pytest_postgresql/factories/client.py b/pytest_postgresql/factories/client.py index 16d3e920..be3e6009 100644 --- a/pytest_postgresql/factories/client.py +++ b/pytest_postgresql/factories/client.py @@ -94,6 +94,7 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]: maintenance_dbname=proc_fixture.maintenance_dbname, password=pg_password, isolation_level=isolation_level, + create_strategy=proc_fixture.create_strategy, ) if config.drop_test_database: janitor.drop() @@ -159,6 +160,7 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera maintenance_dbname=proc_fixture.maintenance_dbname, password=pg_password, isolation_level=isolation_level, + create_strategy=proc_fixture.create_strategy, ) if config.drop_test_database: await janitor.drop() diff --git a/pytest_postgresql/factories/noprocess.py b/pytest_postgresql/factories/noprocess.py index 9aa3e354..c03c6ceb 100644 --- a/pytest_postgresql/factories/noprocess.py +++ b/pytest_postgresql/factories/noprocess.py @@ -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 @@ -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. @@ -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]: @@ -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, diff --git a/pytest_postgresql/factories/process.py b/pytest_postgresql/factories/process.py index aafc7997..2cde06f6 100644 --- a/pytest_postgresql/factories/process.py +++ b/pytest_postgresql/factories/process.py @@ -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 @@ -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. @@ -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( @@ -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() diff --git a/pytest_postgresql/janitor.py b/pytest_postgresql/janitor.py index cacbfc01..c445657c 100644 --- a/pytest_postgresql/janitor.py +++ b/pytest_postgresql/janitor.py @@ -14,6 +14,7 @@ from packaging.version import Version, parse from psycopg import AsyncCursor, Connection, Cursor +from pytest_postgresql.config import validate_create_strategy from pytest_postgresql.loader import build_loader, sql_async from pytest_postgresql.retry import retry, retry_async @@ -36,6 +37,7 @@ class BaseDatabaseJanitor: isolation_level: "psycopg.IsolationLevel | None" autocommit: bool version: Version | None + create_strategy: str | None def __init__( self, @@ -52,6 +54,7 @@ def __init__( isolation_level: "psycopg.IsolationLevel | None" = None, autocommit: bool = False, connection_timeout: int = 60, + create_strategy: str | None = None, ) -> None: """Initialize janitor. @@ -75,6 +78,9 @@ def __init__( affects the loader connection, not the janitor's admin cursor. :param connection_timeout: how long to retry connection before raising a TimeoutError + :param create_strategy: strategy for cloning a test database from its + template: ``wal_log``, ``file_copy``, or ``clone``. None leaves the + choice to PostgreSQL. Does not affect template creation. """ self.user = user self.password = password @@ -87,6 +93,7 @@ def __init__( self._connection_timeout = connection_timeout self.isolation_level = isolation_level self.autocommit = autocommit + self.create_strategy = validate_create_strategy(create_strategy) if version is not None: warnings.warn( "version argument is deprecated and will be removed in a future release", @@ -109,8 +116,20 @@ def _build_create_database_sql(self) -> sql.Composed: query = query + sql.SQL(" TEMPLATE {}").format(sql.Identifier(self.template_dbname)) if self.is_template(): query = query + sql.SQL(" IS_TEMPLATE = true") + elif self.template_dbname and self.create_strategy is not None: + strategy = "WAL_LOG" if self.create_strategy == "wal_log" else "FILE_COPY" + query = query + sql.SQL(" STRATEGY {}").format(sql.SQL(strategy)) return query + def _build_file_copy_method_sql(self) -> sql.SQL | None: + """Build a session setting for the explicit file-copy methods.""" + if self.template_dbname and not self.is_template(): + if self.create_strategy == "file_copy": + return sql.SQL("SET file_copy_method = copy") + if self.create_strategy == "clone": + return sql.SQL("SET file_copy_method = clone") + return None + class DatabaseJanitor(BaseDatabaseJanitor): """Manage database state for specific tasks.""" @@ -123,6 +142,9 @@ def init(self) -> None: # Otherwise, Creating database from template will fail self._terminate_connection(cur, self.template_dbname) query = self._build_create_database_sql() + file_copy_method_sql = self._build_file_copy_method_sql() + if file_copy_method_sql is not None: + cur.execute(file_copy_method_sql) cur.execute(query) @staticmethod @@ -231,6 +253,9 @@ async def init(self) -> None: # Otherwise, Creating database from template will fail await self._terminate_connection(cur, self.template_dbname) query = self._build_create_database_sql() + file_copy_method_sql = self._build_file_copy_method_sql() + if file_copy_method_sql is not None: + await cur.execute(file_copy_method_sql) await cur.execute(query) @staticmethod diff --git a/pytest_postgresql/plugin.py b/pytest_postgresql/plugin.py index 5b3159f6..92a8143e 100644 --- a/pytest_postgresql/plugin.py +++ b/pytest_postgresql/plugin.py @@ -30,6 +30,7 @@ from pytest_postgresql import factories from pytest_postgresql._asyncio_compat import supports_loop_factories +from pytest_postgresql.config import CREATE_STRATEGIES try: import pytest_asyncio @@ -50,6 +51,7 @@ _help_maintenance_dbname = "Database used to create/drop test databases and read server version. Noproc fixture only" _help_load = "Dotted-style or entrypoint-style path to callable or path to SQL File" _help_postgres_options = "Postgres executable extra parameters. Passed via the -o option to pg_ctl" +_help_create_strategy = "Database cloning strategy: wal_log, file_copy, or clone (default: PostgreSQL's default)" _help_drop_test_database = ( "Drop test database in noproc and client fixture, for the cases, " "when database was not cleared due to errors in previous test runs. " @@ -176,6 +178,7 @@ def pytest_addoption(parser: Parser) -> None: parser.addini(name="postgresql_load", type="pathlist", help=_help_load) parser.addini(name="postgresql_postgres_options", help=_help_postgres_options, default="") + parser.addini(name="postgresql_create_strategy", help=_help_create_strategy, default=None) parser.addini(name="postgresql_load_autocommit", type="bool", default=False, help=_help_load_autocommit) parser.addoption( @@ -239,6 +242,14 @@ def pytest_addoption(parser: Parser) -> None: help=_help_postgres_options, ) + parser.addoption( + "--postgresql-create-strategy", + action="store", + choices=CREATE_STRATEGIES, + dest="postgresql_create_strategy", + help=_help_create_strategy, + ) + parser.addoption( "--postgresql-drop-test-database", action="store_true", diff --git a/tests/test_create_strategy.py b/tests/test_create_strategy.py new file mode 100644 index 00000000..6db1d2cd --- /dev/null +++ b/tests/test_create_strategy.py @@ -0,0 +1,314 @@ +"""Database cloning strategy configuration and real-server contracts.""" + +import re +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import psycopg +import pytest +from packaging.version import Version +from psycopg import AsyncConnection, Connection + +from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor +from pytest_postgresql.factories import postgresql, postgresql_async, postgresql_noproc, postgresql_proc +from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseJanitor +from tests.loader import load_database + + +@pytest.mark.parametrize( + ("ini_strategy", "cli_strategy", "expected"), + [ + (None, None, None), + ("clone", None, "clone"), + (None, "file_copy", "file_copy"), + ("clone", "wal_log", "wal_log"), + ], +) +def test_create_strategy_configuration( + pytester: pytest.Pytester, ini_strategy: str | None, cli_strategy: str | None, expected: str | None +) -> None: + """The CLI overrides ini configuration, and the unset default is None.""" + if ini_strategy: + pytester.makeini(f"[pytest]\npostgresql_create_strategy = {ini_strategy}\n") + pytester.makepyfile( + "from pytest_postgresql.config import get_config\n" + "def test_strategy(request):\n" + f" assert get_config(request).create_strategy == {expected!r}\n" + ) + args = [f"--postgresql-create-strategy={cli_strategy}"] if cli_strategy else [] + pytester.runpytest(*args).assert_outcomes(passed=1) + + +@pytest.mark.parametrize("source", ["cli", "ini"]) +def test_invalid_create_strategy_configuration(pytester: pytest.Pytester, source: str) -> None: + """Invalid CLI and ini values produce a clear configuration error.""" + pytester.makepyfile( + "from pytest_postgresql.config import get_config\ndef test_strategy(request):\n get_config(request)\n" + ) + if source == "cli": + result = pytester.runpytest("--postgresql-create-strategy=invalid") + assert result.ret == pytest.ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines(["*invalid choice: 'invalid'*"]) + else: + pytester.makeini("[pytest]\npostgresql_create_strategy = invalid\n") + result = pytester.runpytest() + result.assert_outcomes(failed=1) + result.stdout.fnmatch_lines(["*UsageError: Invalid PostgreSQL create_strategy 'invalid'*"]) + + +@pytest.mark.parametrize("factory", [postgresql_proc, postgresql_noproc]) +def test_invalid_factory_create_strategy(factory: Callable[..., object]) -> None: + """Factory arguments reject misspelled strategies immediately.""" + with pytest.raises(ValueError, match="Invalid PostgreSQL create_strategy 'invalid'"): + factory(create_strategy="invalid") + + +@pytest.mark.parametrize("factory_name", ["postgresql_proc", "postgresql_noproc"]) +@pytest.mark.parametrize("factory_strategy", [None, "clone"]) +def test_factory_create_strategy_precedence( + postgresql_proc: PostgreSQLExecutor, + pytester: pytest.Pytester, + factory_name: str, + factory_strategy: str | None, +) -> None: + """Both factories propagate the chosen setting to clients, with arguments taking precedence.""" + pytester.makeini("[pytest]\npostgresql_create_strategy = file_copy\n") + kwargs: dict[str, object] = {"create_strategy": factory_strategy} + if factory_name == "postgresql_noproc": + kwargs.update( + host=postgresql_proc.host, + port=postgresql_proc.port, + user=postgresql_proc.user, + dbname="strategy_noproc", + ) + expected = factory_strategy or "wal_log" + pytester.makeconftest( + f"from pytest_postgresql import factories\nconfigured_proc = factories.{factory_name}(**{kwargs!r})\n" + ) + pytester.makepyfile( + f"def test_strategy(configured_proc):\n assert configured_proc.create_strategy == {expected!r}\n" + ) + pytester.runpytest("--postgresql-create-strategy=wal_log").assert_outcomes(passed=1) + + +strategy_server = postgresql_proc( + load=[load_database], + create_strategy="wal_log", + postgres_options="-c log_statement=all -c log_line_prefix=PID:%p:", +) + + +@pytest.fixture(scope="session") +def strategy_template(strategy_server: PostgreSQLExecutor) -> Iterator[DatabaseJanitor]: + """Seed a quoted template without applying a client-only creation strategy.""" + with DatabaseJanitor( + user=strategy_server.user, + host=strategy_server.host, + port=strategy_server.port, + password=strategy_server.password, + dbname='strategy"template', + as_template=True, + create_strategy="clone", + ) as template: + with template.cursor(template.dbname) as cursor: + cursor.execute("CREATE TABLE strategy_data (id integer PRIMARY KEY, value text)") + cursor.execute("INSERT INTO strategy_data VALUES (1, 'template')") + yield template + + +def _server_statements(process: PostgreSQLExecutor, offset: int = 0) -> list[tuple[str, str]]: + """Read PostgreSQL's statement records with their actual backend PIDs.""" + records = [] + for line in Path(process.logfile).read_text(encoding="utf-8")[offset:].splitlines(): + match = re.match(r"PID:(\d+):.*?(?:statement|execute [^:]+): (.*)", line) + if match: + records.append((match[1], match[2])) + return records + + +def _assert_creation( + process: PostgreSQLExecutor, dbname: str, expected: str, strategy: str | None = None, offset: int = 0 +) -> None: + """Check the server-observed SQL and session-local setting for one database.""" + records = _server_statements(process, offset) + quoted_name = dbname.replace('"', '""') + creates = [(pid, query) for pid, query in records if query.startswith(f'CREATE DATABASE "{quoted_name}"')] + assert len(creates) == 1 + create_pid, query = creates[0] + assert query == expected + settings = [query for pid, query in records if pid == create_pid and query.startswith("SET file_copy_method")] + if strategy in {"file_copy", "clone"}: + setting = "SET file_copy_method = copy" if strategy == "file_copy" else "SET file_copy_method = clone" + assert settings == [setting] + assert records.index((create_pid, setting)) < records.index((create_pid, expected)) + else: + assert settings == [] + + +def _unsupported_strategy_error( + template: DatabaseJanitor, process: PostgreSQLExecutor, strategy: str | None +) -> type[psycopg.Error] | None: + """Select the PostgreSQL error expected when a feature is unavailable.""" + if strategy == "wal_log" and process.version < Version("15"): + return psycopg.errors.SyntaxError + if strategy in {"file_copy", "clone"} and process.version < Version("18"): + return psycopg.errors.UndefinedObject + if strategy == "clone": + with template.cursor() as cursor: + cursor.execute("SELECT enumvals FROM pg_settings WHERE name = 'file_copy_method'") + setting = cursor.fetchone() + assert setting is not None + if "clone" not in setting[0]: + return psycopg.errors.InvalidParameterValue + return None + + +@pytest.mark.parametrize("strategy", [None, "wal_log", "file_copy", "clone"]) +@pytest.mark.parametrize("client_kind", ["sync", "async"]) +@pytest.mark.asyncio +async def test_janitor_creation_strategy( + strategy_server: PostgreSQLExecutor, + strategy_template: DatabaseJanitor, + strategy: str | None, + client_kind: str, +) -> None: + """Real sync/async clones select the requested mode and keep template data isolated.""" + dbname = f'strategy"{client_kind}' + arguments: dict[str, Any] = { + "user": strategy_server.user, + "host": strategy_server.host, + "port": strategy_server.port, + "password": strategy_server.password, + "dbname": dbname, + "template_dbname": strategy_template.dbname, + "create_strategy": strategy, + } + error = _unsupported_strategy_error(strategy_template, strategy_server, strategy) + offset = len(Path(strategy_server.logfile).read_text(encoding="utf-8")) + if client_kind == "sync": + janitor = DatabaseJanitor(**arguments) + if error is not None: + with pytest.raises(error): + janitor.init() + return + with janitor: + with janitor.cursor(dbname) as cursor: + cursor.execute("SELECT value FROM strategy_data WHERE id = 1") + assert cursor.fetchone() == ("template",) + cursor.execute("UPDATE strategy_data SET value = 'child' WHERE id = 1") + else: + async_janitor = AsyncDatabaseJanitor(**arguments) + if error is not None: + with pytest.raises(error): + await async_janitor.init() + return + async with async_janitor: + async with async_janitor.cursor(dbname) as cursor: + await cursor.execute("SELECT value FROM strategy_data WHERE id = 1") + assert await cursor.fetchone() == ("template",) + await cursor.execute("UPDATE strategy_data SET value = 'child' WHERE id = 1") + with strategy_template.cursor(strategy_template.dbname) as cursor: + cursor.execute("SELECT value FROM strategy_data WHERE id = 1") + assert cursor.fetchone() == ("template",) + suffix = { + None: "", + "wal_log": " STRATEGY WAL_LOG", + "file_copy": " STRATEGY FILE_COPY", + "clone": " STRATEGY FILE_COPY", + } + quoted_name = dbname.replace('"', '""') + expected = f'CREATE DATABASE "{quoted_name}" TEMPLATE "strategy""template"{suffix[strategy]}' + _assert_creation(strategy_server, dbname, expected, strategy, offset) + with strategy_template.cursor() as cursor: + cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (dbname,)) + assert cursor.fetchone() is None + + +@pytest.mark.parametrize( + ("template_dbname", "as_template", "expected"), + [ + (None, False, 'CREATE DATABASE "strategy_guard"'), + (None, True, 'CREATE DATABASE "strategy_guard" IS_TEMPLATE = true'), + ( + 'strategy"template', + True, + 'CREATE DATABASE "strategy_guard" TEMPLATE "strategy""template" IS_TEMPLATE = true', + ), + ], +) +def test_creation_strategy_only_changes_template_children( + strategy_server: PostgreSQLExecutor, + strategy_template: DatabaseJanitor, + template_dbname: str | None, + *, + as_template: bool, + expected: str, +) -> None: + """Template creation and databases without templates keep the server default.""" + offset = len(Path(strategy_server.logfile).read_text(encoding="utf-8")) + with DatabaseJanitor( + user=strategy_server.user, + host=strategy_server.host, + port=strategy_server.port, + password=strategy_server.password, + dbname="strategy_guard", + template_dbname=template_dbname, + as_template=as_template, + create_strategy="clone", + ) as janitor: + with janitor.cursor() as cursor: + cursor.execute("SELECT datistemplate FROM pg_database WHERE datname = %s", (janitor.dbname,)) + assert cursor.fetchone() == (as_template,) + _assert_creation(strategy_server, "strategy_guard", expected, offset=offset) + + +@pytest.mark.parametrize("janitor_class", [DatabaseJanitor, AsyncDatabaseJanitor]) +def test_invalid_janitor_creation_strategy(janitor_class: type[DatabaseJanitor | AsyncDatabaseJanitor]) -> None: + """Janitors reject unsupported strategy names before opening a connection.""" + with pytest.raises(ValueError, match="Invalid PostgreSQL create_strategy 'invalid'"): + janitor_class(user="user", host="host", port=1234, dbname="dbname", create_strategy="invalid") + + +@pytest.fixture(scope="session") +def supported_strategy_server(strategy_server: PostgreSQLExecutor) -> PostgreSQLExecutor: + """Skip the WAL_LOG fixture integration when PostgreSQL predates STRATEGY.""" + if strategy_server.version < Version("15"): + pytest.skip("Explicit CREATE DATABASE strategies require PostgreSQL 15+") + return strategy_server + + +strategy_noproc = postgresql_noproc( + depends_on="supported_strategy_server", dbname="strategy_layer", create_strategy="wal_log" +) +strategy_client = postgresql("supported_strategy_server", dbname='factory"sync') +strategy_async_client = postgresql_async("strategy_noproc", dbname='factory"async') + + +def test_process_client_uses_creation_strategy( + strategy_server: PostgreSQLExecutor, strategy_client: Connection +) -> None: + """A process factory forwards its strategy to the synchronous client clone.""" + with strategy_client.cursor() as cursor: + cursor.execute("SELECT count(*) FROM stories") + assert cursor.fetchone() == (4,) + _assert_creation( + strategy_server, + strategy_client.info.dbname, + f'CREATE DATABASE "factory""sync" TEMPLATE "{strategy_server.template_dbname}" STRATEGY WAL_LOG', + ) + + +@pytest.mark.asyncio +async def test_layered_noproc_client_uses_creation_strategy( + strategy_server: PostgreSQLExecutor, strategy_noproc: NoopExecutor, strategy_async_client: AsyncConnection +) -> None: + """A layered noproc factory forwards its strategy to the asynchronous client clone.""" + async with strategy_async_client.cursor() as cursor: + await cursor.execute("SELECT count(*) FROM stories") + assert await cursor.fetchone() == (4,) + _assert_creation( + strategy_server, + strategy_async_client.info.dbname, + f'CREATE DATABASE "factory""async" TEMPLATE "{strategy_noproc.template_dbname}" STRATEGY WAL_LOG', + ) diff --git a/tests/test_pg_exe.py b/tests/test_pg_exe.py index 3e0de4f1..740b6f32 100644 --- a/tests/test_pg_exe.py +++ b/tests/test_pg_exe.py @@ -33,6 +33,7 @@ def make_config(exec_path: str) -> PostgreSQLConfig: load=[], load_autocommit=False, postgres_options="", + create_strategy=None, drop_test_database=False, ) From 185c397593ee3e6857f3aabdb8358f6a82e81ee1 Mon Sep 17 00:00:00 2001 From: Deo Date: Mon, 2 Nov 2026 10:52:42 +0800 Subject: [PATCH 2/5] Preserve PostgreSQLConfig constructor compatibility --- pytest_postgresql/config.py | 2 +- tests/test_config.py | 28 +++++++++++++++++++++++++++- tests/test_pg_exe.py | 1 - 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/pytest_postgresql/config.py b/pytest_postgresql/config.py index ff435014..f84a4ab3 100644 --- a/pytest_postgresql/config.py +++ b/pytest_postgresql/config.py @@ -38,8 +38,8 @@ class PostgreSQLConfig: load: list[Path | str] load_autocommit: bool postgres_options: str - create_strategy: str | None drop_test_database: bool + create_strategy: str | None = None def get_config(request: pytest.FixtureRequest) -> PostgreSQLConfig: diff --git a/tests/test_config.py b/tests/test_config.py index 841f066f..9e9cab0c 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,11 +1,37 @@ """Config tests.""" from pathlib import Path +from typing import Any import pytest from _pytest._py.path import LocalPath -from pytest_postgresql.config import detect_paths +from pytest_postgresql.config import PostgreSQLConfig, detect_paths + + +@pytest.mark.parametrize("positional", [False, True], ids=["keywords", "positional"]) +def test_config_preserves_legacy_constructor_arguments(*, positional: bool) -> None: + """Existing constructor calls keep their argument meanings and default strategy.""" + arguments: dict[str, Any] = { + "exec": "pg_ctl", + "host": "localhost", + "port": None, + "port_search_count": 5, + "user": "postgres", + "password": None, + "options": "", + "startparams": "-w", + "unixsocketdir": "/tmp", + "dbname": "tests", + "maintenance_dbname": "postgres", + "load": [], + "load_autocommit": False, + "postgres_options": "", + "drop_test_database": True, + } + config = PostgreSQLConfig(*arguments.values()) if positional else PostgreSQLConfig(**arguments) + assert config.drop_test_database is True + assert config.create_strategy is None @pytest.mark.parametrize( diff --git a/tests/test_pg_exe.py b/tests/test_pg_exe.py index 740b6f32..3e0de4f1 100644 --- a/tests/test_pg_exe.py +++ b/tests/test_pg_exe.py @@ -33,7 +33,6 @@ def make_config(exec_path: str) -> PostgreSQLConfig: load=[], load_autocommit=False, postgres_options="", - create_strategy=None, drop_test_database=False, ) From e438c48bf373cdd3dafa3630e6df206b3ccc1ced Mon Sep 17 00:00:00 2001 From: Deo Date: Wed, 4 Nov 2026 15:14:35 +0800 Subject: [PATCH 3/5] Pass PostgreSQL creation options directly to janitors --- pytest_postgresql/factories/client.py | 17 ++- pytest_postgresql/janitor.py | 38 ++--- tests/test_create_strategy.py | 197 +++++++++++++++++--------- tests/test_executor.py | 2 + 4 files changed, 170 insertions(+), 84 deletions(-) diff --git a/pytest_postgresql/factories/client.py b/pytest_postgresql/factories/client.py index be3e6009..204fcadd 100644 --- a/pytest_postgresql/factories/client.py +++ b/pytest_postgresql/factories/client.py @@ -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 @@ -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, @@ -94,7 +102,8 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]: maintenance_dbname=proc_fixture.maintenance_dbname, password=pg_password, isolation_level=isolation_level, - create_strategy=proc_fixture.create_strategy, + strategy=strategy, + copy_method=copy_method, ) if config.drop_test_database: janitor.drop() @@ -151,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, @@ -160,7 +170,8 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera maintenance_dbname=proc_fixture.maintenance_dbname, password=pg_password, isolation_level=isolation_level, - create_strategy=proc_fixture.create_strategy, + strategy=strategy, + copy_method=copy_method, ) if config.drop_test_database: await janitor.drop() diff --git a/pytest_postgresql/janitor.py b/pytest_postgresql/janitor.py index c445657c..349dea01 100644 --- a/pytest_postgresql/janitor.py +++ b/pytest_postgresql/janitor.py @@ -7,19 +7,20 @@ from contextlib import asynccontextmanager, contextmanager from pathlib import Path from types import TracebackType -from typing import Self, TypeVar +from typing import Literal, Self, TypeVar import psycopg import psycopg.sql as sql from packaging.version import Version, parse from psycopg import AsyncCursor, Connection, Cursor -from pytest_postgresql.config import validate_create_strategy from pytest_postgresql.loader import build_loader, sql_async from pytest_postgresql.retry import retry, retry_async DatabaseJanitorType = TypeVar("DatabaseJanitorType", bound="DatabaseJanitor") AsyncDatabaseJanitorType = TypeVar("AsyncDatabaseJanitorType", bound="AsyncDatabaseJanitor") +DatabaseCreationStrategy = Literal["WAL_LOG", "FILE_COPY"] +FileCopyMethod = Literal["copy", "clone"] class BaseDatabaseJanitor: @@ -37,7 +38,8 @@ class BaseDatabaseJanitor: isolation_level: "psycopg.IsolationLevel | None" autocommit: bool version: Version | None - create_strategy: str | None + strategy: DatabaseCreationStrategy | None + copy_method: FileCopyMethod | None def __init__( self, @@ -54,7 +56,8 @@ def __init__( isolation_level: "psycopg.IsolationLevel | None" = None, autocommit: bool = False, connection_timeout: int = 60, - create_strategy: str | None = None, + strategy: DatabaseCreationStrategy | None = None, + copy_method: FileCopyMethod | None = None, ) -> None: """Initialize janitor. @@ -78,9 +81,11 @@ def __init__( affects the loader connection, not the janitor's admin cursor. :param connection_timeout: how long to retry connection before raising a TimeoutError - :param create_strategy: strategy for cloning a test database from its - template: ``wal_log``, ``file_copy``, or ``clone``. None leaves the - choice to PostgreSQL. Does not affect template creation. + :param strategy: PostgreSQL creation strategy for client template clones: + ``WAL_LOG`` or ``FILE_COPY``. None leaves the server default unchanged. + :param copy_method: PostgreSQL ``file_copy_method`` value, ``copy`` or + ``clone``. Required with ``FILE_COPY`` and otherwise must be None. + Neither option affects template creation. """ self.user = user self.password = password @@ -93,7 +98,10 @@ def __init__( self._connection_timeout = connection_timeout self.isolation_level = isolation_level self.autocommit = autocommit - self.create_strategy = validate_create_strategy(create_strategy) + if (strategy == "FILE_COPY") != (copy_method is not None): + raise ValueError("copy_method must be set exactly when strategy is FILE_COPY") + self.strategy = strategy + self.copy_method = copy_method if version is not None: warnings.warn( "version argument is deprecated and will be removed in a future release", @@ -116,18 +124,14 @@ def _build_create_database_sql(self) -> sql.Composed: query = query + sql.SQL(" TEMPLATE {}").format(sql.Identifier(self.template_dbname)) if self.is_template(): query = query + sql.SQL(" IS_TEMPLATE = true") - elif self.template_dbname and self.create_strategy is not None: - strategy = "WAL_LOG" if self.create_strategy == "wal_log" else "FILE_COPY" - query = query + sql.SQL(" STRATEGY {}").format(sql.SQL(strategy)) + elif self.template_dbname and self.strategy is not None: + query = query + sql.SQL(" STRATEGY {}").format(sql.Literal(self.strategy)) return query - def _build_file_copy_method_sql(self) -> sql.SQL | None: + def _build_file_copy_method_sql(self) -> sql.Composed | None: """Build a session setting for the explicit file-copy methods.""" - if self.template_dbname and not self.is_template(): - if self.create_strategy == "file_copy": - return sql.SQL("SET file_copy_method = copy") - if self.create_strategy == "clone": - return sql.SQL("SET file_copy_method = clone") + if self.template_dbname and not self.is_template() and self.copy_method is not None: + return sql.SQL("SET file_copy_method = {}").format(sql.Literal(self.copy_method)) return None diff --git a/tests/test_create_strategy.py b/tests/test_create_strategy.py index 6db1d2cd..337a9ca3 100644 --- a/tests/test_create_strategy.py +++ b/tests/test_create_strategy.py @@ -1,5 +1,6 @@ """Database cloning strategy configuration and real-server contracts.""" +import importlib.util import re from collections.abc import Callable, Iterator from pathlib import Path @@ -8,11 +9,10 @@ import psycopg import pytest from packaging.version import Version -from psycopg import AsyncConnection, Connection -from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor -from pytest_postgresql.factories import postgresql, postgresql_async, postgresql_noproc, postgresql_proc -from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseJanitor +from pytest_postgresql.executors import PostgreSQLExecutor +from pytest_postgresql.factories import postgresql_noproc, postgresql_proc +from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseCreationStrategy, DatabaseJanitor, FileCopyMethod from tests.loader import load_database @@ -109,7 +109,8 @@ def strategy_template(strategy_server: PostgreSQLExecutor) -> Iterator[DatabaseJ password=strategy_server.password, dbname='strategy"template', as_template=True, - create_strategy="clone", + strategy="FILE_COPY", + copy_method="clone", ) as template: with template.cursor(template.dbname) as cursor: cursor.execute("CREATE TABLE strategy_data (id integer PRIMARY KEY, value text)") @@ -117,29 +118,27 @@ def strategy_template(strategy_server: PostgreSQLExecutor) -> Iterator[DatabaseJ yield template -def _server_statements(process: PostgreSQLExecutor, offset: int = 0) -> list[tuple[str, str]]: +def _server_statements(logfile: str, offset: int = 0) -> list[tuple[str, str]]: """Read PostgreSQL's statement records with their actual backend PIDs.""" records = [] - for line in Path(process.logfile).read_text(encoding="utf-8")[offset:].splitlines(): + for line in Path(logfile).read_text(encoding="utf-8")[offset:].splitlines(): match = re.match(r"PID:(\d+):.*?(?:statement|execute [^:]+): (.*)", line) if match: records.append((match[1], match[2])) return records -def _assert_creation( - process: PostgreSQLExecutor, dbname: str, expected: str, strategy: str | None = None, offset: int = 0 -) -> None: +def _assert_creation(logfile: str, dbname: str, expected: str, copy_method: str | None = None, offset: int = 0) -> None: """Check the server-observed SQL and session-local setting for one database.""" - records = _server_statements(process, offset) + records = _server_statements(logfile, offset) quoted_name = dbname.replace('"', '""') creates = [(pid, query) for pid, query in records if query.startswith(f'CREATE DATABASE "{quoted_name}"')] assert len(creates) == 1 create_pid, query = creates[0] assert query == expected settings = [query for pid, query in records if pid == create_pid and query.startswith("SET file_copy_method")] - if strategy in {"file_copy", "clone"}: - setting = "SET file_copy_method = copy" if strategy == "file_copy" else "SET file_copy_method = clone" + if copy_method is not None: + setting = f"SET file_copy_method = '{copy_method}'" assert settings == [setting] assert records.index((create_pid, setting)) < records.index((create_pid, expected)) else: @@ -147,14 +146,14 @@ def _assert_creation( def _unsupported_strategy_error( - template: DatabaseJanitor, process: PostgreSQLExecutor, strategy: str | None + template: DatabaseJanitor, process: PostgreSQLExecutor, strategy: str | None, copy_method: str | None ) -> type[psycopg.Error] | None: """Select the PostgreSQL error expected when a feature is unavailable.""" - if strategy == "wal_log" and process.version < Version("15"): + if strategy == "WAL_LOG" and process.version < Version("15"): return psycopg.errors.SyntaxError - if strategy in {"file_copy", "clone"} and process.version < Version("18"): + if strategy == "FILE_COPY" and process.version < Version("18"): return psycopg.errors.UndefinedObject - if strategy == "clone": + if copy_method == "clone": with template.cursor() as cursor: cursor.execute("SELECT enumvals FROM pg_settings WHERE name = 'file_copy_method'") setting = cursor.fetchone() @@ -164,13 +163,17 @@ def _unsupported_strategy_error( return None -@pytest.mark.parametrize("strategy", [None, "wal_log", "file_copy", "clone"]) +@pytest.mark.parametrize( + ("strategy", "copy_method"), + [(None, None), ("WAL_LOG", None), ("FILE_COPY", "copy"), ("FILE_COPY", "clone")], +) @pytest.mark.parametrize("client_kind", ["sync", "async"]) @pytest.mark.asyncio async def test_janitor_creation_strategy( strategy_server: PostgreSQLExecutor, strategy_template: DatabaseJanitor, strategy: str | None, + copy_method: str | None, client_kind: str, ) -> None: """Real sync/async clones select the requested mode and keep template data isolated.""" @@ -182,9 +185,10 @@ async def test_janitor_creation_strategy( "password": strategy_server.password, "dbname": dbname, "template_dbname": strategy_template.dbname, - "create_strategy": strategy, + "strategy": strategy, + "copy_method": copy_method, } - error = _unsupported_strategy_error(strategy_template, strategy_server, strategy) + error = _unsupported_strategy_error(strategy_template, strategy_server, strategy, copy_method) offset = len(Path(strategy_server.logfile).read_text(encoding="utf-8")) if client_kind == "sync": janitor = DatabaseJanitor(**arguments) @@ -211,15 +215,10 @@ async def test_janitor_creation_strategy( with strategy_template.cursor(strategy_template.dbname) as cursor: cursor.execute("SELECT value FROM strategy_data WHERE id = 1") assert cursor.fetchone() == ("template",) - suffix = { - None: "", - "wal_log": " STRATEGY WAL_LOG", - "file_copy": " STRATEGY FILE_COPY", - "clone": " STRATEGY FILE_COPY", - } + suffix = "" if strategy is None else f" STRATEGY '{strategy}'" quoted_name = dbname.replace('"', '""') - expected = f'CREATE DATABASE "{quoted_name}" TEMPLATE "strategy""template"{suffix[strategy]}' - _assert_creation(strategy_server, dbname, expected, strategy, offset) + expected = f'CREATE DATABASE "{quoted_name}" TEMPLATE "strategy""template"{suffix}' + _assert_creation(strategy_server.logfile, dbname, expected, copy_method, offset) with strategy_template.cursor() as cursor: cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (dbname,)) assert cursor.fetchone() is None @@ -255,60 +254,130 @@ def test_creation_strategy_only_changes_template_children( dbname="strategy_guard", template_dbname=template_dbname, as_template=as_template, - create_strategy="clone", + strategy="FILE_COPY", + copy_method="clone", ) as janitor: with janitor.cursor() as cursor: cursor.execute("SELECT datistemplate FROM pg_database WHERE datname = %s", (janitor.dbname,)) assert cursor.fetchone() == (as_template,) - _assert_creation(strategy_server, "strategy_guard", expected, offset=offset) + _assert_creation(strategy_server.logfile, "strategy_guard", expected, offset=offset) @pytest.mark.parametrize("janitor_class", [DatabaseJanitor, AsyncDatabaseJanitor]) -def test_invalid_janitor_creation_strategy(janitor_class: type[DatabaseJanitor | AsyncDatabaseJanitor]) -> None: - """Janitors reject unsupported strategy names before opening a connection.""" - with pytest.raises(ValueError, match="Invalid PostgreSQL create_strategy 'invalid'"): - janitor_class(user="user", host="host", port=1234, dbname="dbname", create_strategy="invalid") +@pytest.mark.parametrize( + ("strategy", "copy_method"), + [(None, "copy"), (None, "clone"), ("WAL_LOG", "copy"), ("WAL_LOG", "clone"), ("FILE_COPY", None)], +) +def test_janitor_rejects_inconsistent_copy_options( + janitor_class: type[DatabaseJanitor | AsyncDatabaseJanitor], + strategy: DatabaseCreationStrategy | None, + copy_method: FileCopyMethod | None, +) -> None: + """A copy method is required exactly when the PostgreSQL strategy is FILE_COPY.""" + with pytest.raises(ValueError, match="copy_method must be set exactly when strategy is FILE_COPY"): + janitor_class(user="user", host="host", port=1234, dbname="dbname", strategy=strategy, copy_method=copy_method) -@pytest.fixture(scope="session") -def supported_strategy_server(strategy_server: PostgreSQLExecutor) -> PostgreSQLExecutor: - """Skip the WAL_LOG fixture integration when PostgreSQL predates STRATEGY.""" - if strategy_server.version < Version("15"): - pytest.skip("Explicit CREATE DATABASE strategies require PostgreSQL 15+") - return strategy_server +@pytest.mark.parametrize(("strategy", "copy_method"), [("invalid", None), ("FILE_COPY", "invalid")]) +def test_janitor_leaves_option_value_validation_to_postgresql( + strategy_server: PostgreSQLExecutor, + strategy_template: DatabaseJanitor, + strategy: str, + copy_method: str | None, +) -> None: + """Unknown PostgreSQL option values retain the server's compatibility errors.""" + arguments: dict[str, Any] = { + "user": strategy_server.user, + "host": strategy_server.host, + "port": strategy_server.port, + "password": strategy_server.password, + "dbname": "invalid_option", + "template_dbname": strategy_template.dbname, + "strategy": strategy, + "copy_method": copy_method, + } + error: type[psycopg.Error] = psycopg.errors.InvalidParameterValue + if copy_method is None and strategy_server.version < Version("15"): + error = psycopg.errors.SyntaxError + elif copy_method is not None and strategy_server.version < Version("18"): + error = psycopg.errors.UndefinedObject + with pytest.raises(error): + DatabaseJanitor(**arguments).init() -strategy_noproc = postgresql_noproc( - depends_on="supported_strategy_server", dbname="strategy_layer", create_strategy="wal_log" -) -strategy_client = postgresql("supported_strategy_server", dbname='factory"sync') -strategy_async_client = postgresql_async("strategy_noproc", dbname='factory"async') +@pytest.mark.parametrize("create_strategy", [None, "wal_log", "file_copy", "clone"]) +@pytest.mark.parametrize("factory_name", ["postgresql_proc", "postgresql_noproc"]) +def test_client_factories_translate_creation_strategy( + strategy_server: PostgreSQLExecutor, + strategy_template: DatabaseJanitor, + pytester: pytest.Pytester, + create_strategy: str | None, + factory_name: str, +) -> None: + """Public modes become PostgreSQL options for sync/async clients of both factories.""" + strategy, copy_method = { + None: (None, None), + "wal_log": ("WAL_LOG", None), + "file_copy": ("FILE_COPY", "copy"), + "clone": ("FILE_COPY", "clone"), + }[create_strategy] + if _unsupported_strategy_error(strategy_template, strategy_server, strategy, copy_method) is not None: + pytest.skip("Successful factory cloning requires server support; janitor tests cover server errors") + kwargs: dict[str, Any] = {"create_strategy": create_strategy} + if factory_name == "postgresql_proc": + kwargs["postgres_options"] = "-c log_statement=all -c log_line_prefix=PID:%p:" + logfile = "configured_proc.logfile" + offset = 0 + else: + kwargs.update( + host=strategy_server.host, + port=strategy_server.port, + user=strategy_server.user, + password=strategy_server.password, + dbname="factory_layer", + ) + logfile = repr(strategy_server.logfile) + offset = len(Path(strategy_server.logfile).read_text(encoding="utf-8")) + pytester.makeconftest( + "from pytest_postgresql import factories\n" + "from tests.loader import load_database\n" + f"configured_proc = factories.{factory_name}(load=[load_database], **{kwargs!r})\n" + "client = factories.postgresql('configured_proc', dbname='factory\"sync')\n" + "async_client = factories.postgresql_async('configured_proc', dbname='factory\"async')\n" + ) + suffix = "" if strategy is None else f" STRATEGY '{strategy}'" + async_available = importlib.util.find_spec("pytest_asyncio") is not None + pytester.makepyfile( + f""" +import pytest +from tests.test_create_strategy import _assert_creation -def test_process_client_uses_creation_strategy( - strategy_server: PostgreSQLExecutor, strategy_client: Connection -) -> None: - """A process factory forwards its strategy to the synchronous client clone.""" - with strategy_client.cursor() as cursor: +def check_creation(connection, configured_proc): + def quote(name): + return '"' + name.replace('"', '""') + '"' + expected = ( + f'CREATE DATABASE {{quote(connection.info.dbname)}} ' + f'TEMPLATE {{quote(configured_proc.template_dbname)}}' + {suffix!r} + ) + _assert_creation({logfile}, connection.info.dbname, expected, {copy_method!r}, offset={offset}) + + +def test_sync(client, configured_proc): + with client.cursor() as cursor: cursor.execute("SELECT count(*) FROM stories") assert cursor.fetchone() == (4,) - _assert_creation( - strategy_server, - strategy_client.info.dbname, - f'CREATE DATABASE "factory""sync" TEMPLATE "{strategy_server.template_dbname}" STRATEGY WAL_LOG', - ) + check_creation(client, configured_proc) @pytest.mark.asyncio -async def test_layered_noproc_client_uses_creation_strategy( - strategy_server: PostgreSQLExecutor, strategy_noproc: NoopExecutor, strategy_async_client: AsyncConnection -) -> None: - """A layered noproc factory forwards its strategy to the asynchronous client clone.""" - async with strategy_async_client.cursor() as cursor: +@pytest.mark.skipif(not {async_available!r}, reason="requires the optional pytest-asyncio extra") +async def test_async(async_client, configured_proc): + async with async_client.cursor() as cursor: await cursor.execute("SELECT count(*) FROM stories") assert await cursor.fetchone() == (4,) - _assert_creation( - strategy_server, - strategy_async_client.info.dbname, - f'CREATE DATABASE "factory""async" TEMPLATE "{strategy_noproc.template_dbname}" STRATEGY WAL_LOG', + check_creation(async_client, configured_proc) +""" ) + pytester.runpytest().assert_outcomes(passed=2 if async_available else 1, skipped=0 if async_available else 1) diff --git a/tests/test_executor.py b/tests/test_executor.py index 478bd6af..5bc47692 100644 --- a/tests/test_executor.py +++ b/tests/test_executor.py @@ -175,6 +175,7 @@ def test_postgresql_client_closes_on_pre_yield_failure() -> None: proc_mock.password = None proc_mock.options = "" proc_mock.dbname = "tests" + proc_mock.create_strategy = None proc_mock.template_dbname = "tests_tmpl" proc_mock.version = 14 @@ -215,6 +216,7 @@ async def test_postgresql_async_client_closes_on_pre_yield_failure() -> None: proc_mock.password = None proc_mock.options = "" proc_mock.dbname = "tests" + proc_mock.create_strategy = None proc_mock.template_dbname = "tests_tmpl" proc_mock.version = 14 From 9eeb73a41903a0ac1aa80882883db706133fb3c1 Mon Sep 17 00:00:00 2001 From: Deo Date: Thu, 5 Nov 2026 08:01:32 +0800 Subject: [PATCH 4/5] Trim cloning documentation and move it to advanced usage --- README.rst | 144 ++++++++++++++++++++--------------------------------- 1 file changed, 55 insertions(+), 89 deletions(-) diff --git a/README.rst b/README.rst index fa1ae6a7..b09fff76 100644 --- a/README.rst +++ b/README.rst @@ -272,95 +272,6 @@ 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 --------------------------------------- - -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 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -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 -`_ and -`file_copy_method documentation -`_. - Using a maintenance database other than ``postgres`` ---------------------------------------------------- @@ -595,6 +506,61 @@ This example shows how to create an SQLAlchemy session fixture: SessionLocal.close() Base.metadata.drop_all(engine) +Advanced Usage: Test database cloning +------------------------------------- + +Use ``create_strategy`` on ``postgresql_proc`` or ``postgresql_noproc`` to choose +how synchronous and asynchronous client fixtures clone the template database +for each test. Initial and layered template creation keep the server default. + +.. 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: + +.. 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. +* ``wal_log``: ``CREATE DATABASE ... STRATEGY WAL_LOG`` (PostgreSQL 15+). +* ``file_copy``: ``SET file_copy_method = copy``, then + ``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+). +* ``clone``: ``SET file_copy_method = clone``, then + ``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+). + +The session setting and database creation use the same connection; no server +restart is needed. PostgreSQL reports unsupported settings or strategies directly. +Factory arguments take precedence over command line and ini options. Chained +fixtures use the client-facing noproc factory's argument or global configuration, +not the strategy of its ``depends_on`` fixture. + +``clone`` needs operating-system support, and sharing disk blocks depends on the +server's filesystem supporting reflinks. It is not guaranteed to improve +performance; compare the full test suite at its usual worker count. For strategy, +checkpoint and filesystem details, see PostgreSQL's `CREATE DATABASE documentation +`_ and +`file_copy_method documentation +`_. + Advanced Usage: DatabaseJanitor ------------------------------- From 6b1652a8f2daf4ae74b1ca8c617231ddb13c196b Mon Sep 17 00:00:00 2001 From: Deo Date: Fri, 6 Nov 2026 02:59:51 +0800 Subject: [PATCH 5/5] Simplify strategy tests and use pytester examples --- .../examples/test_create_strategy_clients.py | 54 +++++++++ .../test_create_strategy_configuration.py | 14 +++ tests/test_create_strategy.py | 111 ++++++------------ 3 files changed, 106 insertions(+), 73 deletions(-) create mode 100644 tests/examples/test_create_strategy_clients.py create mode 100644 tests/examples/test_create_strategy_configuration.py diff --git a/tests/examples/test_create_strategy_clients.py b/tests/examples/test_create_strategy_clients.py new file mode 100644 index 00000000..81c168f8 --- /dev/null +++ b/tests/examples/test_create_strategy_clients.py @@ -0,0 +1,54 @@ +"""Real client fixtures exercise the factory case supplied by the parent test.""" + +import importlib.util +import json +from pathlib import Path + +import pytest +from psycopg import AsyncConnection, Connection + +from pytest_postgresql import factories +from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor +from tests.loader import load_database +from tests.test_create_strategy import _assert_creation + +case = json.loads(Path(__file__).with_name("factory_case.json").read_text(encoding="utf-8")) +configured_proc = getattr(factories, case["factory_name"])(load=[load_database], **case["factory_kwargs"]) +client = factories.postgresql("configured_proc", dbname='factory"sync') +async_client = factories.postgresql_async("configured_proc", dbname='factory"async') + + +def check_creation( + connection: Connection | AsyncConnection, configured_proc: PostgreSQLExecutor | NoopExecutor +) -> None: + """Check the actual CREATE and session setting received by PostgreSQL.""" + + def quote(name: str) -> str: + return '"' + name.replace('"', '""') + '"' + + suffix = "" if case["strategy"] is None else f" STRATEGY '{case['strategy']}'" + expected = ( + f"CREATE DATABASE {quote(connection.info.dbname)} TEMPLATE {quote(configured_proc.template_dbname)}{suffix}" + ) + logfile = configured_proc.logfile if isinstance(configured_proc, PostgreSQLExecutor) else case["logfile"] + _assert_creation(logfile, connection.info.dbname, expected, case["copy_method"], offset=case["offset"]) + + +def test_sync(client: Connection, configured_proc: PostgreSQLExecutor | NoopExecutor) -> None: + """The synchronous fixture clones the seeded template with the requested mode.""" + with client.cursor() as cursor: + cursor.execute("SELECT count(*) FROM stories") + assert cursor.fetchone() == (4,) + check_creation(client, configured_proc) + + +@pytest.mark.asyncio +@pytest.mark.skipif( + importlib.util.find_spec("pytest_asyncio") is None, reason="requires the optional pytest-asyncio extra" +) +async def test_async(async_client: AsyncConnection, configured_proc: PostgreSQLExecutor | NoopExecutor) -> None: + """The asynchronous fixture uses the same template cloning options.""" + async with async_client.cursor() as cursor: + await cursor.execute("SELECT count(*) FROM stories") + assert await cursor.fetchone() == (4,) + check_creation(async_client, configured_proc) diff --git a/tests/examples/test_create_strategy_configuration.py b/tests/examples/test_create_strategy_configuration.py new file mode 100644 index 00000000..edacdae5 --- /dev/null +++ b/tests/examples/test_create_strategy_configuration.py @@ -0,0 +1,14 @@ +"""Configuration assertions run through pytester to exercise CLI and ini parsing.""" + +import json +from pathlib import Path + +import pytest + +from pytest_postgresql.config import get_config + + +def test_strategy(request: pytest.FixtureRequest) -> None: + """Resolve the strategy through the real plugin configuration.""" + expected = json.loads(Path(__file__).with_name("expected_strategy.json").read_text(encoding="utf-8")) + assert get_config(request).create_strategy == expected diff --git a/tests/test_create_strategy.py b/tests/test_create_strategy.py index 337a9ca3..ba535402 100644 --- a/tests/test_create_strategy.py +++ b/tests/test_create_strategy.py @@ -1,6 +1,7 @@ """Database cloning strategy configuration and real-server contracts.""" import importlib.util +import json import re from collections.abc import Callable, Iterator from pathlib import Path @@ -31,11 +32,8 @@ def test_create_strategy_configuration( """The CLI overrides ini configuration, and the unset default is None.""" if ini_strategy: pytester.makeini(f"[pytest]\npostgresql_create_strategy = {ini_strategy}\n") - pytester.makepyfile( - "from pytest_postgresql.config import get_config\n" - "def test_strategy(request):\n" - f" assert get_config(request).create_strategy == {expected!r}\n" - ) + pytester.copy_example("test_create_strategy_configuration.py") + pytester.makefile(".json", expected_strategy=json.dumps(expected)) args = [f"--postgresql-create-strategy={cli_strategy}"] if cli_strategy else [] pytester.runpytest(*args).assert_outcomes(passed=1) @@ -43,9 +41,8 @@ def test_create_strategy_configuration( @pytest.mark.parametrize("source", ["cli", "ini"]) def test_invalid_create_strategy_configuration(pytester: pytest.Pytester, source: str) -> None: """Invalid CLI and ini values produce a clear configuration error.""" - pytester.makepyfile( - "from pytest_postgresql.config import get_config\ndef test_strategy(request):\n get_config(request)\n" - ) + pytester.copy_example("test_create_strategy_configuration.py") + pytester.makefile(".json", expected_strategy=json.dumps(None)) if source == "cli": result = pytester.runpytest("--postgresql-create-strategy=invalid") assert result.ret == pytest.ExitCode.USAGE_ERROR @@ -64,32 +61,27 @@ def test_invalid_factory_create_strategy(factory: Callable[..., object]) -> None factory(create_strategy="invalid") -@pytest.mark.parametrize("factory_name", ["postgresql_proc", "postgresql_noproc"]) -@pytest.mark.parametrize("factory_strategy", [None, "clone"]) +precedence_proc_default = postgresql_proc() +precedence_proc_clone = postgresql_proc(create_strategy="clone") +precedence_noproc_default = postgresql_noproc(depends_on="precedence_proc_clone", dbname="precedence_default") +precedence_noproc_clone = postgresql_noproc( + depends_on="precedence_proc_clone", dbname="precedence_clone", create_strategy="clone" +) + + +@pytest.mark.parametrize("factory_name", ["proc", "noproc"]) +@pytest.mark.parametrize("factory_strategy", ["default", "clone"]) def test_factory_create_strategy_precedence( - postgresql_proc: PostgreSQLExecutor, - pytester: pytest.Pytester, + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, factory_name: str, - factory_strategy: str | None, + factory_strategy: str, ) -> None: - """Both factories propagate the chosen setting to clients, with arguments taking precedence.""" - pytester.makeini("[pytest]\npostgresql_create_strategy = file_copy\n") - kwargs: dict[str, object] = {"create_strategy": factory_strategy} - if factory_name == "postgresql_noproc": - kwargs.update( - host=postgresql_proc.host, - port=postgresql_proc.port, - user=postgresql_proc.user, - dbname="strategy_noproc", - ) - expected = factory_strategy or "wal_log" - pytester.makeconftest( - f"from pytest_postgresql import factories\nconfigured_proc = factories.{factory_name}(**{kwargs!r})\n" - ) - pytester.makepyfile( - f"def test_strategy(configured_proc):\n assert configured_proc.create_strategy == {expected!r}\n" - ) - pytester.runpytest("--postgresql-create-strategy=wal_log").assert_outcomes(passed=1) + """Factory arguments override global configuration, and unset arguments use it.""" + monkeypatch.setattr(request.config.option, "postgresql_create_strategy", "wal_log") + configured_proc = request.getfixturevalue(f"precedence_{factory_name}_{factory_strategy}") + expected = "clone" if factory_strategy == "clone" else "wal_log" + assert configured_proc.create_strategy == expected strategy_server = postgresql_proc( @@ -326,7 +318,7 @@ def test_client_factories_translate_creation_strategy( kwargs: dict[str, Any] = {"create_strategy": create_strategy} if factory_name == "postgresql_proc": kwargs["postgres_options"] = "-c log_statement=all -c log_line_prefix=PID:%p:" - logfile = "configured_proc.logfile" + logfile = None offset = 0 else: kwargs.update( @@ -336,48 +328,21 @@ def test_client_factories_translate_creation_strategy( password=strategy_server.password, dbname="factory_layer", ) - logfile = repr(strategy_server.logfile) + logfile = strategy_server.logfile offset = len(Path(strategy_server.logfile).read_text(encoding="utf-8")) - pytester.makeconftest( - "from pytest_postgresql import factories\n" - "from tests.loader import load_database\n" - f"configured_proc = factories.{factory_name}(load=[load_database], **{kwargs!r})\n" - "client = factories.postgresql('configured_proc', dbname='factory\"sync')\n" - "async_client = factories.postgresql_async('configured_proc', dbname='factory\"async')\n" + pytester.copy_example("test_create_strategy_clients.py") + pytester.makefile( + ".json", + factory_case=json.dumps( + { + "factory_name": factory_name, + "factory_kwargs": kwargs, + "strategy": strategy, + "copy_method": copy_method, + "logfile": logfile, + "offset": offset, + } + ), ) - suffix = "" if strategy is None else f" STRATEGY '{strategy}'" async_available = importlib.util.find_spec("pytest_asyncio") is not None - pytester.makepyfile( - f""" -import pytest -from tests.test_create_strategy import _assert_creation - - -def check_creation(connection, configured_proc): - def quote(name): - return '"' + name.replace('"', '""') + '"' - expected = ( - f'CREATE DATABASE {{quote(connection.info.dbname)}} ' - f'TEMPLATE {{quote(configured_proc.template_dbname)}}' - {suffix!r} - ) - _assert_creation({logfile}, connection.info.dbname, expected, {copy_method!r}, offset={offset}) - - -def test_sync(client, configured_proc): - with client.cursor() as cursor: - cursor.execute("SELECT count(*) FROM stories") - assert cursor.fetchone() == (4,) - check_creation(client, configured_proc) - - -@pytest.mark.asyncio -@pytest.mark.skipif(not {async_available!r}, reason="requires the optional pytest-asyncio extra") -async def test_async(async_client, configured_proc): - async with async_client.cursor() as cursor: - await cursor.execute("SELECT count(*) FROM stories") - assert await cursor.fetchone() == (4,) - check_creation(async_client, configured_proc) -""" - ) pytester.runpytest().assert_outcomes(passed=2 if async_available else 1, skipped=0 if async_available else 1)