pytest-postgresql 10.0.0__tar.gz → 11.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/CHANGES.rst +26 -0
  2. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/PKG-INFO +63 -2
  3. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/README.rst +61 -0
  4. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pyproject.toml +3 -3
  5. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pyproject.toml.orig +3 -3
  6. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/__init__.py +1 -1
  7. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/config.py +18 -0
  8. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/exceptions.py +27 -0
  9. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/executors/noop.py +3 -0
  10. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/executors/proc.py +9 -15
  11. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/client.py +14 -1
  12. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/noprocess.py +6 -1
  13. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/process.py +6 -1
  14. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/janitor.py +33 -4
  15. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/loader.py +3 -2
  16. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/plugin.py +13 -1
  17. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/COPYING.lesser +0 -0
  18. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/_asyncio_compat.py +0 -0
  19. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/executors/__init__.py +0 -0
  20. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/__init__.py +0 -0
  21. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/_pg.py +0 -0
  22. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/py.typed +0 -0
  23. {pytest_postgresql-10.0.0 → pytest_postgresql-11.0.0}/pytest_postgresql/retry.py +0 -0
@@ -3,6 +3,32 @@ CHANGELOG
3
3
 
4
4
  .. towncrier release notes start
5
5
 
6
+ pytest-postgresql 11.0.0 (2026-12-04)
7
+ =====================================
8
+
9
+ Breaking changes
10
+ ----------------
11
+
12
+ - ``PostgreSQLExecutor.stop()`` arguments are renamed from ``sig`` and ``exp_sig`` to ``stop_signal`` and ``expected_returncode``, matching mirakuru. Callers passing them by keyword need the new names. (`#1467 <https://github.com/dbfixtures/pytest-postgresql/issues/1467>`__)
13
+
14
+
15
+ Features
16
+ --------
17
+
18
+ - Add ``create_strategy`` to the process and noproc factories, with matching CLI
19
+ and ini options, to select PostgreSQL's default, ``wal_log``, ``file_copy``, or
20
+ the operating-system ``clone`` method when client fixtures copy the template
21
+ database. The default remains unchanged; cloning does not guarantee reflinks. (`#1260 <https://github.com/dbfixtures/pytest-postgresql/issues/1260>`__)
22
+
23
+
24
+ Miscellaneous
25
+ -------------
26
+
27
+ - Run the ty type checker alongside mypy in pre-commit (`#1467 <https://github.com/dbfixtures/pytest-postgresql/issues/1467>`__)
28
+ - Set dependabot's versioning-strategy explicitly to increase-if-necessary. (`#1481 <https://github.com/dbfixtures/pytest-postgresql/issues/1481>`__)
29
+ - Move the unsupported-version and version-check exception messages into classmethods on the exception classes. (`#1494 <https://github.com/dbfixtures/pytest-postgresql/issues/1494>`__)
30
+
31
+
6
32
  pytest-postgresql 10.0.0 (2026-11-04)
7
33
  =====================================
8
34
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-postgresql
3
- Version: 10.0.0
3
+ Version: 11.0.0
4
4
  Summary: Postgresql fixtures and fixture factories for Pytest.
5
5
  Keywords: fixture,postgresql,pytest,tests
6
6
  Author: Grzegorz Śliwiński
@@ -33,7 +33,7 @@ Requires-Dist: pytest-asyncio>=1.4 ; extra == 'async'
33
33
  Requires-Python: >=3.11
34
34
  Project-URL: Source, https://github.com/dbfixtures/pytest-postgresql
35
35
  Project-URL: Bug Tracker, https://github.com/dbfixtures/pytest-postgresql/issues
36
- Project-URL: Changelog, https://github.com/dbfixtures/pytest-postgresql/blob/v10.0.0/CHANGES.rst
36
+ Project-URL: Changelog, https://github.com/dbfixtures/pytest-postgresql/blob/v11.0.0/CHANGES.rst
37
37
  Provides-Extra: async
38
38
  Description-Content-Type: text/x-rst
39
39
 
@@ -455,6 +455,12 @@ You can define settings via fixture factory arguments, command line options, or
455
455
  - --postgresql-load-autocommit
456
456
  - postgresql_load_autocommit
457
457
  - False
458
+ * - Test database cloning strategy
459
+ - create_strategy
460
+ - create_strategy
461
+ - --postgresql-create-strategy
462
+ - postgresql_create_strategy
463
+ - PostgreSQL's default
458
464
  * - PostgreSQL connection options
459
465
  - options
460
466
  - options
@@ -539,6 +545,61 @@ This example shows how to create an SQLAlchemy session fixture:
539
545
  SessionLocal.close()
540
546
  Base.metadata.drop_all(engine)
541
547
 
548
+ Advanced Usage: Test database cloning
549
+ -------------------------------------
550
+
551
+ Use ``create_strategy`` on ``postgresql_proc`` or ``postgresql_noproc`` to choose
552
+ how synchronous and asynchronous client fixtures clone the template database
553
+ for each test. Initial and layered template creation keep the server default.
554
+
555
+ .. code-block:: python
556
+
557
+ postgresql_my_proc = factories.postgresql_proc(create_strategy="clone")
558
+ postgresql_my = factories.postgresql("postgresql_my_proc")
559
+
560
+ For an existing server, including PostgreSQL in Docker, configure the noproc
561
+ factory instead:
562
+
563
+ .. code-block:: python
564
+
565
+ postgresql_external = factories.postgresql_noproc(create_strategy="clone")
566
+ postgresql_my = factories.postgresql("postgresql_external")
567
+ postgresql_my_async = factories.postgresql_async("postgresql_external")
568
+
569
+ The same setting is available on the command line and in ``pytest.ini``:
570
+
571
+ .. code-block:: sh
572
+
573
+ pytest --postgresql-create-strategy=clone
574
+
575
+ .. code-block:: ini
576
+
577
+ [pytest]
578
+ postgresql_create_strategy = clone
579
+
580
+ The available values are:
581
+
582
+ * Unset (the default): no ``STRATEGY`` clause or session setting is sent.
583
+ * ``wal_log``: ``CREATE DATABASE ... STRATEGY WAL_LOG`` (PostgreSQL 15+).
584
+ * ``file_copy``: ``SET file_copy_method = copy``, then
585
+ ``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+).
586
+ * ``clone``: ``SET file_copy_method = clone``, then
587
+ ``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+).
588
+
589
+ The session setting and database creation use the same connection; no server
590
+ restart is needed. PostgreSQL reports unsupported settings or strategies directly.
591
+ Factory arguments take precedence over command line and ini options. Chained
592
+ fixtures use the client-facing noproc factory's argument or global configuration,
593
+ not the strategy of its ``depends_on`` fixture.
594
+
595
+ ``clone`` needs operating-system support, and sharing disk blocks depends on the
596
+ server's filesystem supporting reflinks. It is not guaranteed to improve
597
+ performance; compare the full test suite at its usual worker count. For strategy,
598
+ checkpoint and filesystem details, see PostgreSQL's `CREATE DATABASE documentation
599
+ <https://www.postgresql.org/docs/18/sql-createdatabase.html>`_ and
600
+ `file_copy_method documentation
601
+ <https://www.postgresql.org/docs/18/runtime-config-resource.html#GUC-FILE-COPY-METHOD>`_.
602
+
542
603
  Advanced Usage: DatabaseJanitor
543
604
  -------------------------------
544
605
 
@@ -416,6 +416,12 @@ You can define settings via fixture factory arguments, command line options, or
416
416
  - --postgresql-load-autocommit
417
417
  - postgresql_load_autocommit
418
418
  - False
419
+ * - Test database cloning strategy
420
+ - create_strategy
421
+ - create_strategy
422
+ - --postgresql-create-strategy
423
+ - postgresql_create_strategy
424
+ - PostgreSQL's default
419
425
  * - PostgreSQL connection options
420
426
  - options
421
427
  - options
@@ -500,6 +506,61 @@ This example shows how to create an SQLAlchemy session fixture:
500
506
  SessionLocal.close()
501
507
  Base.metadata.drop_all(engine)
502
508
 
509
+ Advanced Usage: Test database cloning
510
+ -------------------------------------
511
+
512
+ Use ``create_strategy`` on ``postgresql_proc`` or ``postgresql_noproc`` to choose
513
+ how synchronous and asynchronous client fixtures clone the template database
514
+ for each test. Initial and layered template creation keep the server default.
515
+
516
+ .. code-block:: python
517
+
518
+ postgresql_my_proc = factories.postgresql_proc(create_strategy="clone")
519
+ postgresql_my = factories.postgresql("postgresql_my_proc")
520
+
521
+ For an existing server, including PostgreSQL in Docker, configure the noproc
522
+ factory instead:
523
+
524
+ .. code-block:: python
525
+
526
+ postgresql_external = factories.postgresql_noproc(create_strategy="clone")
527
+ postgresql_my = factories.postgresql("postgresql_external")
528
+ postgresql_my_async = factories.postgresql_async("postgresql_external")
529
+
530
+ The same setting is available on the command line and in ``pytest.ini``:
531
+
532
+ .. code-block:: sh
533
+
534
+ pytest --postgresql-create-strategy=clone
535
+
536
+ .. code-block:: ini
537
+
538
+ [pytest]
539
+ postgresql_create_strategy = clone
540
+
541
+ The available values are:
542
+
543
+ * Unset (the default): no ``STRATEGY`` clause or session setting is sent.
544
+ * ``wal_log``: ``CREATE DATABASE ... STRATEGY WAL_LOG`` (PostgreSQL 15+).
545
+ * ``file_copy``: ``SET file_copy_method = copy``, then
546
+ ``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+).
547
+ * ``clone``: ``SET file_copy_method = clone``, then
548
+ ``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+).
549
+
550
+ The session setting and database creation use the same connection; no server
551
+ restart is needed. PostgreSQL reports unsupported settings or strategies directly.
552
+ Factory arguments take precedence over command line and ini options. Chained
553
+ fixtures use the client-facing noproc factory's argument or global configuration,
554
+ not the strategy of its ``depends_on`` fixture.
555
+
556
+ ``clone`` needs operating-system support, and sharing disk blocks depends on the
557
+ server's filesystem supporting reflinks. It is not guaranteed to improve
558
+ performance; compare the full test suite at its usual worker count. For strategy,
559
+ checkpoint and filesystem details, see PostgreSQL's `CREATE DATABASE documentation
560
+ <https://www.postgresql.org/docs/18/sql-createdatabase.html>`_ and
561
+ `file_copy_method documentation
562
+ <https://www.postgresql.org/docs/18/runtime-config-resource.html#GUC-FILE-COPY-METHOD>`_.
563
+
503
564
  Advanced Usage: DatabaseJanitor
504
565
  -------------------------------
505
566
 
@@ -4,7 +4,7 @@ requires = ["uv-build>=0.11,<0.14"]
4
4
 
5
5
  [project]
6
6
  name = "pytest-postgresql"
7
- version = "10.0.0"
7
+ version = "11.0.0"
8
8
  description = "Postgresql fixtures and fixture factories for Pytest."
9
9
  readme = "README.rst"
10
10
  keywords = [
@@ -55,7 +55,7 @@ async = [
55
55
  [project.urls]
56
56
  Source = "https://github.com/dbfixtures/pytest-postgresql"
57
57
  "Bug Tracker" = "https://github.com/dbfixtures/pytest-postgresql/issues"
58
- Changelog = "https://github.com/dbfixtures/pytest-postgresql/blob/v10.0.0/CHANGES.rst"
58
+ Changelog = "https://github.com/dbfixtures/pytest-postgresql/blob/v11.0.0/CHANGES.rst"
59
59
 
60
60
  [project.entry-points.pytest11]
61
61
  pytest_postgresql = "pytest_postgresql.plugin"
@@ -166,7 +166,7 @@ message_template = "Release {new_version}"
166
166
  tag_template = "v{new_version}"
167
167
 
168
168
  [tool.tbump.version]
169
- current = "10.0.0"
169
+ current = "11.0.0"
170
170
  regex = '''
171
171
  (?P<major>\d+)
172
172
  \.
@@ -4,7 +4,7 @@ requires = [ "uv-build>=0.11,<0.14" ]
4
4
 
5
5
  [project]
6
6
  name = "pytest-postgresql"
7
- version = "10.0.0"
7
+ version = "11.0.0"
8
8
  description = "Postgresql fixtures and fixture factories for Pytest."
9
9
  readme = "README.rst"
10
10
  keywords = [ "fixture", "postgresql", "pytest", "tests" ]
@@ -41,7 +41,7 @@ async = [ "aiofiles>=23.0", "pytest-asyncio>=1.4" ]
41
41
  [project.urls]
42
42
  Source = "https://github.com/dbfixtures/pytest-postgresql"
43
43
  "Bug Tracker" = "https://github.com/dbfixtures/pytest-postgresql/issues"
44
- Changelog = "https://github.com/dbfixtures/pytest-postgresql/blob/v10.0.0/CHANGES.rst"
44
+ Changelog = "https://github.com/dbfixtures/pytest-postgresql/blob/v11.0.0/CHANGES.rst"
45
45
 
46
46
  [project.entry-points.pytest11]
47
47
  pytest_postgresql = "pytest_postgresql.plugin"
@@ -149,7 +149,7 @@ message_template = "Release {new_version}"
149
149
  tag_template = "v{new_version}"
150
150
 
151
151
  [tool.tbump.version]
152
- current = "10.0.0"
152
+ current = "11.0.0"
153
153
  regex = '''
154
154
  (?P<major>\d+)
155
155
  \.
@@ -17,4 +17,4 @@
17
17
  # along with pytest-postgresql. If not, see <http://www.gnu.org/licenses/>.
18
18
  """Main module for pytest-postgresql."""
19
19
 
20
- __version__ = "10.0.0"
20
+ __version__ = "11.0.0"
@@ -7,6 +7,18 @@ from typing import Any
7
7
  import pytest
8
8
  from _pytest._py.path import LocalPath
9
9
 
10
+ CREATE_STRATEGIES = ("wal_log", "file_copy", "clone")
11
+
12
+
13
+ def validate_create_strategy(create_strategy: str | None) -> str | None:
14
+ """Validate the optional database cloning strategy."""
15
+ if create_strategy is not None and create_strategy not in CREATE_STRATEGIES:
16
+ raise ValueError(
17
+ f"Invalid PostgreSQL create_strategy {create_strategy!r}; "
18
+ f"expected one of {', '.join(CREATE_STRATEGIES)} or None"
19
+ )
20
+ return create_strategy
21
+
10
22
 
11
23
  @dataclass(frozen=True)
12
24
  class PostgreSQLConfig:
@@ -27,6 +39,7 @@ class PostgreSQLConfig:
27
39
  load_autocommit: bool
28
40
  postgres_options: str
29
41
  drop_test_database: bool
42
+ create_strategy: str | None = None
30
43
 
31
44
 
32
45
  def get_config(request: pytest.FixtureRequest) -> PostgreSQLConfig:
@@ -37,6 +50,10 @@ def get_config(request: pytest.FixtureRequest) -> PostgreSQLConfig:
37
50
  return request.config.getoption(name) or request.config.getini(name)
38
51
 
39
52
  load_paths: list[Path | str] = detect_paths(get_postgresql_option("load"))
53
+ try:
54
+ create_strategy = validate_create_strategy(get_postgresql_option("create_strategy"))
55
+ except ValueError as exc:
56
+ raise pytest.UsageError(str(exc)) from exc
40
57
 
41
58
  cfg = PostgreSQLConfig(
42
59
  exec=get_postgresql_option("exec"),
@@ -54,6 +71,7 @@ def get_config(request: pytest.FixtureRequest) -> PostgreSQLConfig:
54
71
  load=load_paths,
55
72
  load_autocommit=bool(get_postgresql_option("load_autocommit")),
56
73
  postgres_options=get_postgresql_option("postgres_options"),
74
+ create_strategy=create_strategy,
57
75
  drop_test_database=request.config.getoption("postgresql_drop_test_database"),
58
76
  )
59
77
  return cfg
@@ -62,6 +62,33 @@ class ExecutableMissingException(FileNotFoundError):
62
62
  cause = "No pg_ctl was found in any of the usual locations."
63
63
  return cls._no_pg_ctl(cause, checked)
64
64
 
65
+ @classmethod
66
+ def version_unreadable(cls, executable: str, error: OSError) -> "ExecutableMissingException":
67
+ """Build the error for a pg_ctl that cannot be run to read the PostgreSQL version.
68
+
69
+ :param executable: the pg_ctl path that could not be run
70
+ :param error: the error raised while running it
71
+ """
72
+ return cls(
73
+ f"Could not run {executable} to read the PostgreSQL version: {error}. "
74
+ f"Is the PostgreSQL server installed at that location? "
75
+ f"Point the plugin at a working pg_ctl with the --postgresql-exec command line option, "
76
+ f"the postgresql_exec ini option, or the executable factory argument."
77
+ )
78
+
65
79
 
66
80
  class PostgreSQLUnsupported(Exception):
67
81
  """Exception raised when unsupported postgresql would be detected."""
82
+
83
+ @classmethod
84
+ def unsupported_version(cls, version: object, min_supported_version: object) -> "PostgreSQLUnsupported":
85
+ """Build the error for a PostgreSQL version below the supported minimum.
86
+
87
+ :param version: the version reported by the installed pg_ctl
88
+ :param min_supported_version: the oldest version the plugin supports
89
+ """
90
+ return cls(
91
+ f"Your version of PostgreSQL is not supported. "
92
+ f"Consider updating to PostgreSQL {min_supported_version} at least. "
93
+ f"The currently installed version of PostgreSQL: {version}."
94
+ )
@@ -40,6 +40,7 @@ class NoopExecutor:
40
40
  dbname: str,
41
41
  password: str | None = None,
42
42
  maintenance_dbname: str = "postgres",
43
+ create_strategy: str | None = None,
43
44
  ):
44
45
  """Initialize nooperator executor mock.
45
46
 
@@ -52,6 +53,7 @@ class NoopExecutor:
52
53
  :param maintenance_dbname: database to connect to for server-level work,
53
54
  i.e. reading the server version. Defaults to ``postgres``. Point it at
54
55
  a database the user can reach when ``postgres`` is unavailable.
56
+ :param create_strategy: strategy used by client fixtures to clone databases
55
57
  """
56
58
  self.host = host
57
59
  self.port = int(port)
@@ -60,6 +62,7 @@ class NoopExecutor:
60
62
  self.password = password
61
63
  self.dbname = dbname
62
64
  self.maintenance_dbname = maintenance_dbname
65
+ self.create_strategy = create_strategy
63
66
  self._version: Any = None
64
67
 
65
68
  @property
@@ -107,6 +107,7 @@ class PostgreSQLExecutor(TCPExecutor):
107
107
  password: str | None = None,
108
108
  options: str = "",
109
109
  postgres_options: str = "",
110
+ create_strategy: str | None = None,
110
111
  ):
111
112
  """Initialize PostgreSQLExecutor executor.
112
113
 
@@ -127,6 +128,7 @@ class PostgreSQLExecutor(TCPExecutor):
127
128
  :param dbname: database name (might not yet exist)
128
129
  :param options:
129
130
  :param postgres_options: extra arguments to `postgres start`
131
+ :param create_strategy: strategy used by client fixtures to clone databases
130
132
  """
131
133
  self._directory_initialised = False
132
134
  self.executable = executable
@@ -139,6 +141,7 @@ class PostgreSQLExecutor(TCPExecutor):
139
141
  self.logfile = logfile
140
142
  self.startparams = startparams
141
143
  self.postgres_options = postgres_options
144
+ self.create_strategy = create_strategy
142
145
  if platform.system() == "Windows":
143
146
  command = self.WINDOWS_PROC_START_COMMAND.format(
144
147
  executable=self.executable,
@@ -192,11 +195,7 @@ class PostgreSQLExecutor(TCPExecutor):
192
195
  def start(self) -> Self:
193
196
  """Add check for postgresql version before starting process."""
194
197
  if self.version < self.MIN_SUPPORTED_VERSION:
195
- raise PostgreSQLUnsupported(
196
- f"Your version of PostgreSQL is not supported. "
197
- f"Consider updating to PostgreSQL {self.MIN_SUPPORTED_VERSION} at least. "
198
- f"The currently installed version of PostgreSQL: {self.version}."
199
- )
198
+ raise PostgreSQLUnsupported.unsupported_version(self.version, self.MIN_SUPPORTED_VERSION)
200
199
  self.init_directory()
201
200
  if platform.system() == "Windows":
202
201
  # On Windows, pg_ctl start -w exits as soon as the server is
@@ -343,12 +342,7 @@ class PostgreSQLExecutor(TCPExecutor):
343
342
  try:
344
343
  version_string = subprocess.check_output([self.executable, "--version"]).decode("utf-8")
345
344
  except OSError as ex:
346
- raise ExecutableMissingException(
347
- f"Could not run {self.executable} to read the PostgreSQL version: {ex}. "
348
- f"Is the PostgreSQL server installed at that location? "
349
- f"Point the plugin at a working pg_ctl with the --postgresql-exec command line option, "
350
- f"the postgresql_exec ini option, or the executable factory argument."
351
- ) from ex
345
+ raise ExecutableMissingException.version_unreadable(self.executable, ex) from ex
352
346
  matches = self.VERSION_RE.search(version_string)
353
347
  assert matches is not None
354
348
  return parse(matches.groupdict()["version"])
@@ -423,7 +417,7 @@ class PostgreSQLExecutor(TCPExecutor):
423
417
  e,
424
418
  )
425
419
 
426
- def stop(self, sig: int | None = None, exp_sig: int | None = None) -> Self:
420
+ def stop(self, stop_signal: int | None = None, expected_returncode: int | None = None) -> Self:
427
421
  """Issue a stop request to executable."""
428
422
  try:
429
423
  subprocess.check_output(
@@ -434,19 +428,19 @@ class PostgreSQLExecutor(TCPExecutor):
434
428
  raise TimeoutExpired(self, self._timeout) from exc
435
429
  try:
436
430
  if platform.system() == "Windows":
437
- self._windows_terminate_process(sig)
431
+ self._windows_terminate_process(stop_signal)
438
432
  # Clean up mirakuru's internal process reference so that
439
433
  # the stopped() context manager can call start() again
440
434
  self._process = None
441
435
  else:
442
- super().stop(sig, exp_sig)
436
+ super().stop(stop_signal, expected_returncode)
443
437
  except ProcessFinishedWithError:
444
438
  # Finished, leftovers ought to be cleaned afterwards anyway
445
439
  pass
446
440
  except AttributeError:
447
441
  # Fallback for edge cases where os.killpg doesn't exist (e.g., Windows)
448
442
  if not hasattr(os, "killpg"):
449
- self._windows_terminate_process(sig)
443
+ self._windows_terminate_process(stop_signal)
450
444
  self._process = None
451
445
  else:
452
446
  raise
@@ -27,7 +27,14 @@ from psycopg import AsyncConnection, Connection
27
27
  from pytest_postgresql._asyncio_compat import mark_postgresql_async_fixture, supports_loop_factories
28
28
  from pytest_postgresql.config import get_config
29
29
  from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor
30
- from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseJanitor
30
+ from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseCreationStrategy, DatabaseJanitor, FileCopyMethod
31
+
32
+ _CREATE_STRATEGY_OPTIONS: dict[str | None, tuple[DatabaseCreationStrategy | None, FileCopyMethod | None]] = {
33
+ None: (None, None),
34
+ "wal_log": ("WAL_LOG", None),
35
+ "file_copy": ("FILE_COPY", "copy"),
36
+ "clone": ("FILE_COPY", "clone"),
37
+ }
31
38
 
32
39
  try:
33
40
  import pytest_asyncio as _pytest_asyncio
@@ -85,6 +92,7 @@ def postgresql(
85
92
  pg_password = proc_fixture.password
86
93
  pg_options = proc_fixture.options
87
94
  pg_db = dbname or proc_fixture.dbname
95
+ strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
88
96
  janitor = DatabaseJanitor(
89
97
  user=pg_user,
90
98
  host=pg_host,
@@ -94,6 +102,8 @@ def postgresql(
94
102
  maintenance_dbname=proc_fixture.maintenance_dbname,
95
103
  password=pg_password,
96
104
  isolation_level=isolation_level,
105
+ strategy=strategy,
106
+ copy_method=copy_method,
97
107
  )
98
108
  if config.drop_test_database:
99
109
  janitor.drop()
@@ -150,6 +160,7 @@ def postgresql_async(
150
160
  pg_password = proc_fixture.password
151
161
  pg_options = proc_fixture.options
152
162
  pg_db = dbname or proc_fixture.dbname
163
+ strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
153
164
  janitor = AsyncDatabaseJanitor(
154
165
  user=pg_user,
155
166
  host=pg_host,
@@ -159,6 +170,8 @@ def postgresql_async(
159
170
  maintenance_dbname=proc_fixture.maintenance_dbname,
160
171
  password=pg_password,
161
172
  isolation_level=isolation_level,
173
+ strategy=strategy,
174
+ copy_method=copy_method,
162
175
  )
163
176
  if config.drop_test_database:
164
177
  await janitor.drop()
@@ -23,7 +23,7 @@ from pathlib import Path
23
23
 
24
24
  import pytest
25
25
 
26
- from pytest_postgresql.config import get_config
26
+ from pytest_postgresql.config import get_config, validate_create_strategy
27
27
  from pytest_postgresql.executors import NoopExecutor
28
28
  from pytest_postgresql.janitor import DatabaseJanitor
29
29
 
@@ -48,6 +48,7 @@ def postgresql_noproc(
48
48
  load: list[Callable | str | Path] | None = None,
49
49
  load_autocommit: bool | None = None,
50
50
  depends_on: str | None = None,
51
+ create_strategy: str | None = None,
51
52
  ) -> Callable[[pytest.FixtureRequest], Iterator[NoopExecutor]]:
52
53
  """Postgresql noprocess factory.
53
54
 
@@ -67,8 +68,11 @@ def postgresql_noproc(
67
68
  Required for statements that cannot run inside a transaction block,
68
69
  e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
69
70
  :param depends_on: Optional name of the fixture to depend on.
71
+ :param create_strategy: strategy used by client fixtures to clone the template:
72
+ ``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
70
73
  :returns: function which makes a postgresql process
71
74
  """
75
+ validate_create_strategy(create_strategy)
72
76
 
73
77
  @pytest.fixture(scope="session")
74
78
  def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopExecutor]:
@@ -120,6 +124,7 @@ def postgresql_noproc(
120
124
  dbname=noop_exec_dbname,
121
125
  options=pg_options,
122
126
  maintenance_dbname=pg_maintenance_dbname,
127
+ create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
123
128
  )
124
129
  janitor = DatabaseJanitor(
125
130
  user=noop_exec.user,
@@ -29,7 +29,7 @@ import port_for
29
29
  import pytest
30
30
  from port_for import PortForException, get_port
31
31
 
32
- from pytest_postgresql.config import PostgreSQLConfig, get_config
32
+ from pytest_postgresql.config import PostgreSQLConfig, get_config, validate_create_strategy
33
33
  from pytest_postgresql.executors import PostgreSQLExecutor
34
34
  from pytest_postgresql.factories._pg import _pg_exe
35
35
  from pytest_postgresql.janitor import DatabaseJanitor
@@ -80,6 +80,7 @@ def postgresql_proc(
80
80
  postgres_options: str | None = None,
81
81
  load: list[Callable | str | Path] | None = None,
82
82
  load_autocommit: bool | None = None,
83
+ create_strategy: str | None = None,
83
84
  ) -> Callable[[pytest.FixtureRequest, pytest.TempPathFactory], Iterator[PostgreSQLExecutor]]:
84
85
  """Postgresql process factory.
85
86
 
@@ -103,8 +104,11 @@ def postgresql_proc(
103
104
  :param load_autocommit: run the SQL loader connection with autocommit on.
104
105
  Required for statements that cannot run inside a transaction block,
105
106
  e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
107
+ :param create_strategy: strategy used by client fixtures to clone the template:
108
+ ``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
106
109
  :returns: function which makes a postgresql process
107
110
  """
111
+ validate_create_strategy(create_strategy)
108
112
 
109
113
  @pytest.fixture(scope="session")
110
114
  def postgresql_proc_fixture(
@@ -201,6 +205,7 @@ def postgresql_proc(
201
205
  logfile=str(logfile_path.resolve()),
202
206
  startparams=startparams or config.startparams,
203
207
  postgres_options=postgres_options or config.postgres_options,
208
+ create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
204
209
  )
205
210
  postgresql_executor.start()
206
211
  postgresql_executor.wait_for_postgres()
@@ -3,11 +3,11 @@
3
3
  import asyncio
4
4
  import inspect
5
5
  import warnings
6
- from collections.abc import AsyncIterator, Callable, Iterator
6
+ from collections.abc import AsyncGenerator, Callable, Generator
7
7
  from contextlib import asynccontextmanager, contextmanager
8
8
  from pathlib import Path
9
9
  from types import TracebackType
10
- from typing import Self, TypeVar
10
+ from typing import Literal, Self, TypeVar
11
11
 
12
12
  import psycopg
13
13
  import psycopg.sql as sql
@@ -19,6 +19,8 @@ from pytest_postgresql.retry import retry, retry_async
19
19
 
20
20
  DatabaseJanitorType = TypeVar("DatabaseJanitorType", bound="DatabaseJanitor")
21
21
  AsyncDatabaseJanitorType = TypeVar("AsyncDatabaseJanitorType", bound="AsyncDatabaseJanitor")
22
+ DatabaseCreationStrategy = Literal["WAL_LOG", "FILE_COPY"]
23
+ FileCopyMethod = Literal["copy", "clone"]
22
24
 
23
25
 
24
26
  class BaseDatabaseJanitor:
@@ -36,6 +38,8 @@ class BaseDatabaseJanitor:
36
38
  isolation_level: "psycopg.IsolationLevel | None"
37
39
  autocommit: bool
38
40
  version: Version | None
41
+ strategy: DatabaseCreationStrategy | None
42
+ copy_method: FileCopyMethod | None
39
43
 
40
44
  def __init__(
41
45
  self,
@@ -52,6 +56,8 @@ class BaseDatabaseJanitor:
52
56
  isolation_level: "psycopg.IsolationLevel | None" = None,
53
57
  autocommit: bool = False,
54
58
  connection_timeout: int = 60,
59
+ strategy: DatabaseCreationStrategy | None = None,
60
+ copy_method: FileCopyMethod | None = None,
55
61
  ) -> None:
56
62
  """Initialize janitor.
57
63
 
@@ -75,6 +81,11 @@ class BaseDatabaseJanitor:
75
81
  affects the loader connection, not the janitor's admin cursor.
76
82
  :param connection_timeout: how long to retry connection before
77
83
  raising a TimeoutError
84
+ :param strategy: PostgreSQL creation strategy for client template clones:
85
+ ``WAL_LOG`` or ``FILE_COPY``. None leaves the server default unchanged.
86
+ :param copy_method: PostgreSQL ``file_copy_method`` value, ``copy`` or
87
+ ``clone``. Required with ``FILE_COPY`` and otherwise must be None.
88
+ Neither option affects template creation.
78
89
  """
79
90
  self.user = user
80
91
  self.password = password
@@ -87,6 +98,10 @@ class BaseDatabaseJanitor:
87
98
  self._connection_timeout = connection_timeout
88
99
  self.isolation_level = isolation_level
89
100
  self.autocommit = autocommit
101
+ if (strategy == "FILE_COPY") != (copy_method is not None):
102
+ raise ValueError("copy_method must be set exactly when strategy is FILE_COPY")
103
+ self.strategy = strategy
104
+ self.copy_method = copy_method
90
105
  if version is not None:
91
106
  warnings.warn(
92
107
  "version argument is deprecated and will be removed in a future release",
@@ -109,8 +124,16 @@ class BaseDatabaseJanitor:
109
124
  query = query + sql.SQL(" TEMPLATE {}").format(sql.Identifier(self.template_dbname))
110
125
  if self.is_template():
111
126
  query = query + sql.SQL(" IS_TEMPLATE = true")
127
+ elif self.template_dbname and self.strategy is not None:
128
+ query = query + sql.SQL(" STRATEGY {}").format(sql.Literal(self.strategy))
112
129
  return query
113
130
 
131
+ def _build_file_copy_method_sql(self) -> sql.Composed | None:
132
+ """Build a session setting for the explicit file-copy methods."""
133
+ if self.template_dbname and not self.is_template() and self.copy_method is not None:
134
+ return sql.SQL("SET file_copy_method = {}").format(sql.Literal(self.copy_method))
135
+ return None
136
+
114
137
 
115
138
  class DatabaseJanitor(BaseDatabaseJanitor):
116
139
  """Manage database state for specific tasks."""
@@ -123,6 +146,9 @@ class DatabaseJanitor(BaseDatabaseJanitor):
123
146
  # Otherwise, Creating database from template will fail
124
147
  self._terminate_connection(cur, self.template_dbname)
125
148
  query = self._build_create_database_sql()
149
+ file_copy_method_sql = self._build_file_copy_method_sql()
150
+ if file_copy_method_sql is not None:
151
+ cur.execute(file_copy_method_sql)
126
152
  cur.execute(query)
127
153
 
128
154
  @staticmethod
@@ -177,7 +203,7 @@ class DatabaseJanitor(BaseDatabaseJanitor):
177
203
  )
178
204
 
179
205
  @contextmanager
180
- def cursor(self, dbname: str | None = None) -> Iterator[Cursor]:
206
+ def cursor(self, dbname: str | None = None) -> Generator[Cursor, None, None]:
181
207
  """Return postgresql cursor.
182
208
 
183
209
  :param dbname: database to connect to. Defaults to the janitor's
@@ -231,6 +257,9 @@ class AsyncDatabaseJanitor(BaseDatabaseJanitor):
231
257
  # Otherwise, Creating database from template will fail
232
258
  await self._terminate_connection(cur, self.template_dbname)
233
259
  query = self._build_create_database_sql()
260
+ file_copy_method_sql = self._build_file_copy_method_sql()
261
+ if file_copy_method_sql is not None:
262
+ await cur.execute(file_copy_method_sql)
234
263
  await cur.execute(query)
235
264
 
236
265
  @staticmethod
@@ -296,7 +325,7 @@ class AsyncDatabaseJanitor(BaseDatabaseJanitor):
296
325
  await result
297
326
 
298
327
  @asynccontextmanager
299
- async def cursor(self, dbname: str | None = None) -> AsyncIterator[AsyncCursor]:
328
+ async def cursor(self, dbname: str | None = None) -> AsyncGenerator[AsyncCursor, None]:
300
329
  """Return postgresql async cursor.
301
330
 
302
331
  :param dbname: database to connect to. Defaults to the janitor's
@@ -6,7 +6,7 @@ from collections.abc import Callable
6
6
  from functools import partial
7
7
  from pathlib import Path
8
8
  from types import ModuleType
9
- from typing import Any
9
+ from typing import Any, LiteralString, cast
10
10
 
11
11
  import psycopg
12
12
 
@@ -22,7 +22,8 @@ def sql(sql_filename: Path, **kwargs: Any) -> None:
22
22
  with psycopg.connect(**kwargs) as db_connection:
23
23
  with open(sql_filename) as _fd:
24
24
  with db_connection.cursor() as cur:
25
- cur.execute(_fd.read())
25
+ # psycopg types the query as LiteralString; SQL read from a file is a plain str
26
+ cur.execute(cast(LiteralString, _fd.read()))
26
27
  db_connection.commit()
27
28
 
28
29
 
@@ -30,6 +30,7 @@ from packaging.version import Version
30
30
 
31
31
  from pytest_postgresql import factories
32
32
  from pytest_postgresql._asyncio_compat import supports_loop_factories
33
+ from pytest_postgresql.config import CREATE_STRATEGIES
33
34
 
34
35
  try:
35
36
  import pytest_asyncio
@@ -50,6 +51,7 @@ _help_dbname = "Default database name"
50
51
  _help_maintenance_dbname = "Database used to create/drop test databases and read server version. Noproc fixture only"
51
52
  _help_load = "Dotted-style or entrypoint-style path to callable or path to SQL File"
52
53
  _help_postgres_options = "Postgres executable extra parameters. Passed via the -o option to pg_ctl"
54
+ _help_create_strategy = "Database cloning strategy: wal_log, file_copy, or clone (default: PostgreSQL's default)"
53
55
  _help_drop_test_database = (
54
56
  "Drop test database in noproc and client fixture, for the cases, "
55
57
  "when database was not cleared due to errors in previous test runs. "
@@ -117,7 +119,8 @@ def pytest_configure(config: pytest.Config) -> None:
117
119
  policy_cls = _windows_selector_event_loop_policy_cls()
118
120
  if policy_cls is None:
119
121
  return
120
- asyncio.set_event_loop_policy(policy_cls())
122
+ # the legacy path for pytest-asyncio versions without the loop-factory hook
123
+ asyncio.set_event_loop_policy(policy_cls()) # ty: ignore[deprecated]
121
124
 
122
125
 
123
126
  if _is_windows():
@@ -176,6 +179,7 @@ def pytest_addoption(parser: Parser) -> None:
176
179
 
177
180
  parser.addini(name="postgresql_load", type="pathlist", help=_help_load)
178
181
  parser.addini(name="postgresql_postgres_options", help=_help_postgres_options, default="")
182
+ parser.addini(name="postgresql_create_strategy", help=_help_create_strategy, default=None)
179
183
  parser.addini(name="postgresql_load_autocommit", type="bool", default=False, help=_help_load_autocommit)
180
184
 
181
185
  parser.addoption(
@@ -239,6 +243,14 @@ def pytest_addoption(parser: Parser) -> None:
239
243
  help=_help_postgres_options,
240
244
  )
241
245
 
246
+ parser.addoption(
247
+ "--postgresql-create-strategy",
248
+ action="store",
249
+ choices=CREATE_STRATEGIES,
250
+ dest="postgresql_create_strategy",
251
+ help=_help_create_strategy,
252
+ )
253
+
242
254
  parser.addoption(
243
255
  "--postgresql-drop-test-database",
244
256
  action="store_true",