pytest-postgresql 9.1.1__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-9.1.1 → pytest_postgresql-11.0.0}/CHANGES.rst +49 -0
  2. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/PKG-INFO +66 -5
  3. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/README.rst +61 -0
  4. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pyproject.toml +16 -13
  5. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pyproject.toml.orig +16 -13
  6. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/__init__.py +1 -2
  7. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/config.py +18 -0
  8. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/exceptions.py +28 -1
  9. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/executors/noop.py +3 -0
  10. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/executors/proc.py +15 -21
  11. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/client.py +16 -2
  12. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/noprocess.py +7 -2
  13. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/process.py +7 -2
  14. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/janitor.py +39 -9
  15. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/loader.py +5 -3
  16. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/plugin.py +13 -1
  17. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/retry.py +5 -4
  18. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/COPYING.lesser +0 -0
  19. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/_asyncio_compat.py +0 -0
  20. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/executors/__init__.py +0 -0
  21. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/__init__.py +0 -0
  22. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/factories/_pg.py +0 -0
  23. {pytest_postgresql-9.1.1 → pytest_postgresql-11.0.0}/pytest_postgresql/py.typed +0 -0
@@ -3,6 +3,55 @@ 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
+
32
+ pytest-postgresql 10.0.0 (2026-11-04)
33
+ =====================================
34
+
35
+ Breaking changes
36
+ ----------------
37
+
38
+ - Require pytest>=8.4, the lowest version compatible with the ``async`` extra (pytest-asyncio>=1.4).
39
+
40
+
41
+ Features
42
+ --------
43
+
44
+ - Add support for Python 3.15, drop support for Python 3.10 (`#1440 <https://github.com/dbfixtures/pytest-postgresql/issues/1440>`__)
45
+
46
+
47
+ Miscellaneous
48
+ -------------
49
+
50
+ - Freeze all pre-commit hook revisions to commit SHAs. (`#1441 <https://github.com/dbfixtures/pytest-postgresql/issues/1441>`__)
51
+ - Enable UP and PYI ruff rulesets (`#1444 <https://github.com/dbfixtures/pytest-postgresql/issues/1444>`__)
52
+ - Run docker and async-extra-less tests as steps of the regular test jobs, split test workflows per OS (`#1476 <https://github.com/dbfixtures/pytest-postgresql/issues/1476>`__)
53
+
54
+
6
55
  pytest-postgresql 9.1.1 (2026-10-04)
7
56
  ====================================
8
57
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-postgresql
3
- Version: 9.1.1
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
@@ -16,24 +16,24 @@ Classifier: Operating System :: OS Independent
16
16
  Classifier: Programming Language :: Python
17
17
  Classifier: Programming Language :: Python :: 3
18
18
  Classifier: Programming Language :: Python :: 3 :: Only
19
- Classifier: Programming Language :: Python :: 3.10
20
19
  Classifier: Programming Language :: Python :: 3.11
21
20
  Classifier: Programming Language :: Python :: 3.12
22
21
  Classifier: Programming Language :: Python :: 3.13
23
22
  Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
24
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
25
  Classifier: Topic :: Software Development :: Testing
26
26
  Requires-Dist: mirakuru>=2.6.0
27
27
  Requires-Dist: packaging
28
28
  Requires-Dist: port-for>=0.7.3
29
29
  Requires-Dist: psycopg>=3.0.0
30
- Requires-Dist: pytest>=8.2
30
+ Requires-Dist: pytest>=8.4
31
31
  Requires-Dist: aiofiles>=23.0 ; extra == 'async'
32
32
  Requires-Dist: pytest-asyncio>=1.4 ; extra == 'async'
33
- Requires-Python: >=3.10
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/v9.1.1/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
 
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
2
  build-backend = "uv_build"
3
- requires = ["uv-build>=0.11,<0.13"]
3
+ requires = ["uv-build>=0.11,<0.14"]
4
4
 
5
5
  [project]
6
6
  name = "pytest-postgresql"
7
- version = "9.1.1"
7
+ version = "11.0.0"
8
8
  description = "Postgresql fixtures and fixture factories for Pytest."
9
9
  readme = "README.rst"
10
10
  keywords = [
@@ -15,7 +15,7 @@ keywords = [
15
15
  ]
16
16
  license = "LGPL-3.0-or-later"
17
17
  license-files = ["COPYING.lesser"]
18
- requires-python = ">=3.10"
18
+ requires-python = ">=3.11"
19
19
  classifiers = [
20
20
  "Development Status :: 5 - Production/Stable",
21
21
  "Environment :: Web Environment",
@@ -26,11 +26,11 @@ classifiers = [
26
26
  "Programming Language :: Python",
27
27
  "Programming Language :: Python :: 3",
28
28
  "Programming Language :: Python :: 3 :: Only",
29
- "Programming Language :: Python :: 3.10",
30
29
  "Programming Language :: Python :: 3.11",
31
30
  "Programming Language :: Python :: 3.12",
32
31
  "Programming Language :: Python :: 3.13",
33
32
  "Programming Language :: Python :: 3.14",
33
+ "Programming Language :: Python :: 3.15",
34
34
  "Topic :: Software Development :: Libraries :: Python Modules",
35
35
  "Topic :: Software Development :: Testing",
36
36
  ]
@@ -39,7 +39,7 @@ dependencies = [
39
39
  "packaging",
40
40
  "port-for>=0.7.3",
41
41
  "psycopg>=3.0.0",
42
- "pytest>=8.2",
42
+ "pytest>=8.4",
43
43
  ]
44
44
 
45
45
  [[project.authors]]
@@ -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/v9.1.1/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"
@@ -63,16 +63,16 @@ pytest_postgresql = "pytest_postgresql.plugin"
63
63
  [dependency-groups]
64
64
  dev = [
65
65
  "aiofiles==25.1.0",
66
- "coverage==7.16.1",
67
- "mirakuru==3.0.3",
66
+ "coverage==7.17.0",
67
+ "mirakuru==3.0.4",
68
68
  "mock==5.2.0",
69
- "mypy==2.3.1; implementation_name=='cpython'",
69
+ "mypy==2.4.0; implementation_name=='cpython'",
70
70
  "packaging==26.3",
71
- "port-for==1.1.0",
71
+ "port-for==1.1.1",
72
72
  "psycopg==3.3.6",
73
73
  "psycopg-binary==3.3.6; implementation_name=='cpython' and python_version<'3.15'",
74
74
  "pytest==9.1.1",
75
- "pytest-asyncio==1.4.0",
75
+ "pytest-asyncio==1.4.1",
76
76
  "pytest-xdist==3.8.0",
77
77
  "towncrier==26.9.0",
78
78
  "types-aiofiles==25.1.0.20260518",
@@ -85,7 +85,7 @@ module-root = ""
85
85
  source-include = ["CHANGES.rst"]
86
86
 
87
87
  [tool.ruff]
88
- target-version = "py310"
88
+ target-version = "py311"
89
89
  line-length = 120
90
90
 
91
91
  [tool.ruff.lint]
@@ -96,6 +96,8 @@ select = [
96
96
  "FBT",
97
97
  "I",
98
98
  "PT",
99
+ "PYI",
100
+ "UP",
99
101
  ]
100
102
 
101
103
  [tool.pyproject-fmt]
@@ -111,6 +113,7 @@ sub_table_spacing = """
111
113
  [tool.mypy]
112
114
  ignore_missing_imports = false
113
115
  follow_imports = "silent"
116
+ python_version = "3.11"
114
117
  disallow_subclassing_any = true
115
118
  disallow_untyped_calls = true
116
119
  disallow_untyped_defs = true
@@ -163,7 +166,7 @@ message_template = "Release {new_version}"
163
166
  tag_template = "v{new_version}"
164
167
 
165
168
  [tool.tbump.version]
166
- current = "9.1.1"
169
+ current = "11.0.0"
167
170
  regex = '''
168
171
  (?P<major>\d+)
169
172
  \.
@@ -1,16 +1,16 @@
1
1
  [build-system]
2
2
  build-backend = "uv_build"
3
- requires = [ "uv-build>=0.11,<0.13" ]
3
+ requires = [ "uv-build>=0.11,<0.14" ]
4
4
 
5
5
  [project]
6
6
  name = "pytest-postgresql"
7
- version = "9.1.1"
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" ]
11
11
  license = "LGPL-3.0-or-later"
12
12
  license-files = [ "COPYING.lesser" ]
13
- requires-python = ">=3.10"
13
+ requires-python = ">=3.11"
14
14
  classifiers = [
15
15
  "Development Status :: 5 - Production/Stable",
16
16
  "Environment :: Web Environment",
@@ -21,15 +21,15 @@ classifiers = [
21
21
  "Programming Language :: Python",
22
22
  "Programming Language :: Python :: 3",
23
23
  "Programming Language :: Python :: 3 :: Only",
24
- "Programming Language :: Python :: 3.10",
25
24
  "Programming Language :: Python :: 3.11",
26
25
  "Programming Language :: Python :: 3.12",
27
26
  "Programming Language :: Python :: 3.13",
28
27
  "Programming Language :: Python :: 3.14",
28
+ "Programming Language :: Python :: 3.15",
29
29
  "Topic :: Software Development :: Libraries :: Python Modules",
30
30
  "Topic :: Software Development :: Testing",
31
31
  ]
32
- dependencies = [ "mirakuru>=2.6.0", "packaging", "port-for>=0.7.3", "psycopg>=3.0.0", "pytest>=8.2" ]
32
+ dependencies = [ "mirakuru>=2.6.0", "packaging", "port-for>=0.7.3", "psycopg>=3.0.0", "pytest>=8.4" ]
33
33
 
34
34
  [[project.authors]]
35
35
  name = "Grzegorz Śliwiński"
@@ -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/v9.1.1/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"
@@ -49,16 +49,16 @@ pytest_postgresql = "pytest_postgresql.plugin"
49
49
  [dependency-groups]
50
50
  dev = [
51
51
  "aiofiles==25.1.0",
52
- "coverage==7.16.1",
53
- "mirakuru==3.0.3",
52
+ "coverage==7.17.0",
53
+ "mirakuru==3.0.4",
54
54
  "mock==5.2.0",
55
- "mypy==2.3.1; implementation_name=='cpython'",
55
+ "mypy==2.4.0; implementation_name=='cpython'",
56
56
  "packaging==26.3",
57
- "port-for==1.1.0",
57
+ "port-for==1.1.1",
58
58
  "psycopg==3.3.6",
59
59
  "psycopg-binary==3.3.6; implementation_name=='cpython' and python_version<'3.15'",
60
60
  "pytest==9.1.1",
61
- "pytest-asyncio==1.4.0",
61
+ "pytest-asyncio==1.4.1",
62
62
  "pytest-xdist==3.8.0",
63
63
  "towncrier==26.9.0",
64
64
  "types-aiofiles==25.1.0.20260518",
@@ -73,7 +73,7 @@ module-root = ""
73
73
  source-include = [ "CHANGES.rst" ]
74
74
 
75
75
  [tool.ruff]
76
- target-version = "py310"
76
+ target-version = "py311"
77
77
  line-length = 120
78
78
 
79
79
  [tool.ruff.lint]
@@ -84,6 +84,8 @@ select = [
84
84
  "FBT", # flake8-boolean-trap
85
85
  "I", # isort
86
86
  "PT", # flake8-pytest-style
87
+ "PYI", # flake8-pyi
88
+ "UP", # pyupgrade
87
89
  ]
88
90
 
89
91
  [tool.pyproject-fmt]
@@ -97,6 +99,7 @@ sub_table_spacing = "\n"
97
99
  [tool.mypy]
98
100
  ignore_missing_imports = false
99
101
  follow_imports = "silent"
102
+ python_version = "3.11"
100
103
  disallow_subclassing_any = true
101
104
  disallow_untyped_calls = true
102
105
  disallow_untyped_defs = true
@@ -146,7 +149,7 @@ message_template = "Release {new_version}"
146
149
  tag_template = "v{new_version}"
147
150
 
148
151
  [tool.tbump.version]
149
- current = "9.1.1"
152
+ current = "11.0.0"
150
153
  regex = '''
151
154
  (?P<major>\d+)
152
155
  \.
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  # Copyright (C) 2016 by Clearcode <http://clearcode.cc>
3
2
  # and associates (see AUTHORS).
4
3
 
@@ -18,4 +17,4 @@
18
17
  # along with pytest-postgresql. If not, see <http://www.gnu.org/licenses/>.
19
18
  """Main module for pytest-postgresql."""
20
19
 
21
- __version__ = "9.1.1"
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
@@ -1,6 +1,6 @@
1
1
  """pytest-postgresql's exceptions."""
2
2
 
3
- from typing import Iterable
3
+ from collections.abc import Iterable
4
4
 
5
5
 
6
6
  class ExecutableMissingException(FileNotFoundError):
@@ -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
@@ -28,7 +28,7 @@ import subprocess
28
28
  import tempfile
29
29
  import time
30
30
  from pathlib import Path
31
- from typing import Any, Optional, TypeVar
31
+ from typing import Any, Self, TypeVar
32
32
 
33
33
  from mirakuru import TCPExecutor
34
34
  from mirakuru.exceptions import ProcessFinishedWithError, TimeoutExpired
@@ -101,12 +101,13 @@ class PostgreSQLExecutor(TCPExecutor):
101
101
  dbname: str,
102
102
  *,
103
103
  shell: bool = False,
104
- timeout: Optional[int] = 60,
104
+ timeout: int | None = 60,
105
105
  sleep: float = 0.1,
106
106
  user: str = "postgres",
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,
@@ -189,14 +192,10 @@ class PostgreSQLExecutor(TCPExecutor):
189
192
  """
190
193
  return "postgres"
191
194
 
192
- def start(self: T) -> T:
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
@@ -298,13 +297,13 @@ class PostgreSQLExecutor(TCPExecutor):
298
297
  # remove old one if exists first.
299
298
  self.clean_directory()
300
299
  pgdata = str(Path(self.datadir).resolve())
301
- options = ["--username=%s" % self.user]
300
+ options = [f"--username={self.user}"]
302
301
 
303
302
  if self.password:
304
303
  password_file = tempfile.NamedTemporaryFile(delete=False)
305
304
  password_path = password_file.name
306
305
  try:
307
- options += ["--auth=password", "--pwfile=%s" % password_path]
306
+ options += ["--auth=password", f"--pwfile={password_path}"]
308
307
  if hasattr(self.password, "encode"):
309
308
  password = self.password.encode("utf-8")
310
309
  else:
@@ -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"])
@@ -391,7 +385,7 @@ class PostgreSQLExecutor(TCPExecutor):
391
385
  return self.running()
392
386
  return super().check_subprocess()
393
387
 
394
- def _windows_terminate_process(self, _sig: Optional[int] = None) -> None:
388
+ def _windows_terminate_process(self, _sig: int | None = None) -> None:
395
389
  """Terminate process on Windows.
396
390
 
397
391
  :param _sig: Signal parameter (unused on Windows but included for consistency)
@@ -423,7 +417,7 @@ class PostgreSQLExecutor(TCPExecutor):
423
417
  e,
424
418
  )
425
419
 
426
- def stop(self: T, sig: Optional[int] = None, exp_sig: Optional[int] = None) -> T:
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
@@ -17,7 +17,8 @@
17
17
  # along with pytest-postgresql. If not, see <http://www.gnu.org/licenses/>.
18
18
  """Fixture factory for postgresql client."""
19
19
 
20
- from typing import AsyncIterator, Callable, Iterator, cast
20
+ from collections.abc import AsyncIterator, Callable, Iterator
21
+ from typing import cast
21
22
 
22
23
  import psycopg
23
24
  import pytest
@@ -26,7 +27,14 @@ from psycopg import AsyncConnection, Connection
26
27
  from pytest_postgresql._asyncio_compat import mark_postgresql_async_fixture, supports_loop_factories
27
28
  from pytest_postgresql.config import get_config
28
29
  from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor
29
- 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
+ }
30
38
 
31
39
  try:
32
40
  import pytest_asyncio as _pytest_asyncio
@@ -84,6 +92,7 @@ def postgresql(
84
92
  pg_password = proc_fixture.password
85
93
  pg_options = proc_fixture.options
86
94
  pg_db = dbname or proc_fixture.dbname
95
+ strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
87
96
  janitor = DatabaseJanitor(
88
97
  user=pg_user,
89
98
  host=pg_host,
@@ -93,6 +102,8 @@ def postgresql(
93
102
  maintenance_dbname=proc_fixture.maintenance_dbname,
94
103
  password=pg_password,
95
104
  isolation_level=isolation_level,
105
+ strategy=strategy,
106
+ copy_method=copy_method,
96
107
  )
97
108
  if config.drop_test_database:
98
109
  janitor.drop()
@@ -149,6 +160,7 @@ def postgresql_async(
149
160
  pg_password = proc_fixture.password
150
161
  pg_options = proc_fixture.options
151
162
  pg_db = dbname or proc_fixture.dbname
163
+ strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
152
164
  janitor = AsyncDatabaseJanitor(
153
165
  user=pg_user,
154
166
  host=pg_host,
@@ -158,6 +170,8 @@ def postgresql_async(
158
170
  maintenance_dbname=proc_fixture.maintenance_dbname,
159
171
  password=pg_password,
160
172
  isolation_level=isolation_level,
173
+ strategy=strategy,
174
+ copy_method=copy_method,
161
175
  )
162
176
  if config.drop_test_database:
163
177
  await janitor.drop()
@@ -18,12 +18,12 @@
18
18
  """Fixture factory for existing postgresql server."""
19
19
 
20
20
  import os
21
+ from collections.abc import Callable, Iterator
21
22
  from pathlib import Path
22
- from typing import Callable, Iterator
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,
@@ -22,14 +22,14 @@ import os
22
22
  import os.path
23
23
  import platform
24
24
  import tempfile
25
+ from collections.abc import Callable, Iterable, Iterator
25
26
  from pathlib import Path
26
- from typing import Callable, Iterable, Iterator
27
27
 
28
28
  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,10 +3,11 @@
3
3
  import asyncio
4
4
  import inspect
5
5
  import warnings
6
+ from collections.abc import AsyncGenerator, Callable, Generator
6
7
  from contextlib import asynccontextmanager, contextmanager
7
8
  from pathlib import Path
8
9
  from types import TracebackType
9
- from typing import AsyncIterator, Callable, Iterator, Type, TypeVar
10
+ from typing import Literal, Self, TypeVar
10
11
 
11
12
  import psycopg
12
13
  import psycopg.sql as sql
@@ -18,6 +19,8 @@ from pytest_postgresql.retry import retry, retry_async
18
19
 
19
20
  DatabaseJanitorType = TypeVar("DatabaseJanitorType", bound="DatabaseJanitor")
20
21
  AsyncDatabaseJanitorType = TypeVar("AsyncDatabaseJanitorType", bound="AsyncDatabaseJanitor")
22
+ DatabaseCreationStrategy = Literal["WAL_LOG", "FILE_COPY"]
23
+ FileCopyMethod = Literal["copy", "clone"]
21
24
 
22
25
 
23
26
  class BaseDatabaseJanitor:
@@ -35,6 +38,8 @@ class BaseDatabaseJanitor:
35
38
  isolation_level: "psycopg.IsolationLevel | None"
36
39
  autocommit: bool
37
40
  version: Version | None
41
+ strategy: DatabaseCreationStrategy | None
42
+ copy_method: FileCopyMethod | None
38
43
 
39
44
  def __init__(
40
45
  self,
@@ -51,6 +56,8 @@ class BaseDatabaseJanitor:
51
56
  isolation_level: "psycopg.IsolationLevel | None" = None,
52
57
  autocommit: bool = False,
53
58
  connection_timeout: int = 60,
59
+ strategy: DatabaseCreationStrategy | None = None,
60
+ copy_method: FileCopyMethod | None = None,
54
61
  ) -> None:
55
62
  """Initialize janitor.
56
63
 
@@ -74,6 +81,11 @@ class BaseDatabaseJanitor:
74
81
  affects the loader connection, not the janitor's admin cursor.
75
82
  :param connection_timeout: how long to retry connection before
76
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.
77
89
  """
78
90
  self.user = user
79
91
  self.password = password
@@ -86,6 +98,10 @@ class BaseDatabaseJanitor:
86
98
  self._connection_timeout = connection_timeout
87
99
  self.isolation_level = isolation_level
88
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
89
105
  if version is not None:
90
106
  warnings.warn(
91
107
  "version argument is deprecated and will be removed in a future release",
@@ -108,8 +124,16 @@ class BaseDatabaseJanitor:
108
124
  query = query + sql.SQL(" TEMPLATE {}").format(sql.Identifier(self.template_dbname))
109
125
  if self.is_template():
110
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))
111
129
  return query
112
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
+
113
137
 
114
138
  class DatabaseJanitor(BaseDatabaseJanitor):
115
139
  """Manage database state for specific tasks."""
@@ -122,6 +146,9 @@ class DatabaseJanitor(BaseDatabaseJanitor):
122
146
  # Otherwise, Creating database from template will fail
123
147
  self._terminate_connection(cur, self.template_dbname)
124
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)
125
152
  cur.execute(query)
126
153
 
127
154
  @staticmethod
@@ -176,7 +203,7 @@ class DatabaseJanitor(BaseDatabaseJanitor):
176
203
  )
177
204
 
178
205
  @contextmanager
179
- def cursor(self, dbname: str | None = None) -> Iterator[Cursor]:
206
+ def cursor(self, dbname: str | None = None) -> Generator[Cursor, None, None]:
180
207
  """Return postgresql cursor.
181
208
 
182
209
  :param dbname: database to connect to. Defaults to the janitor's
@@ -204,14 +231,14 @@ class DatabaseJanitor(BaseDatabaseJanitor):
204
231
  cur.close()
205
232
  conn.close()
206
233
 
207
- def __enter__(self: DatabaseJanitorType) -> DatabaseJanitorType:
234
+ def __enter__(self) -> Self:
208
235
  """Initialize Database Janitor."""
209
236
  self.init()
210
237
  return self
211
238
 
212
239
  def __exit__(
213
- self: DatabaseJanitorType,
214
- exc_type: Type[BaseException] | None,
240
+ self,
241
+ exc_type: type[BaseException] | None,
215
242
  exc_val: BaseException | None,
216
243
  exc_tb: TracebackType | None,
217
244
  ) -> None:
@@ -230,6 +257,9 @@ class AsyncDatabaseJanitor(BaseDatabaseJanitor):
230
257
  # Otherwise, Creating database from template will fail
231
258
  await self._terminate_connection(cur, self.template_dbname)
232
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)
233
263
  await cur.execute(query)
234
264
 
235
265
  @staticmethod
@@ -295,7 +325,7 @@ class AsyncDatabaseJanitor(BaseDatabaseJanitor):
295
325
  await result
296
326
 
297
327
  @asynccontextmanager
298
- async def cursor(self, dbname: str | None = None) -> AsyncIterator[AsyncCursor]:
328
+ async def cursor(self, dbname: str | None = None) -> AsyncGenerator[AsyncCursor, None]:
299
329
  """Return postgresql async cursor.
300
330
 
301
331
  :param dbname: database to connect to. Defaults to the janitor's
@@ -322,14 +352,14 @@ class AsyncDatabaseJanitor(BaseDatabaseJanitor):
322
352
  finally:
323
353
  await conn.close()
324
354
 
325
- async def __aenter__(self: AsyncDatabaseJanitorType) -> AsyncDatabaseJanitorType:
355
+ async def __aenter__(self) -> Self:
326
356
  """Initialize Async Database Janitor."""
327
357
  await self.init()
328
358
  return self
329
359
 
330
360
  async def __aexit__(
331
- self: AsyncDatabaseJanitorType,
332
- exc_type: Type[BaseException] | None,
361
+ self,
362
+ exc_type: type[BaseException] | None,
333
363
  exc_val: BaseException | None,
334
364
  exc_tb: TracebackType | None,
335
365
  ) -> None:
@@ -2,10 +2,11 @@
2
2
 
3
3
  import importlib
4
4
  import re
5
+ from collections.abc import Callable
5
6
  from functools import partial
6
7
  from pathlib import Path
7
8
  from types import ModuleType
8
- from typing import Any, Callable
9
+ from typing import Any, LiteralString, cast
9
10
 
10
11
  import psycopg
11
12
 
@@ -19,9 +20,10 @@ except ImportError:
19
20
  def sql(sql_filename: Path, **kwargs: Any) -> None:
20
21
  """Database loader for sql files."""
21
22
  with psycopg.connect(**kwargs) as db_connection:
22
- with open(sql_filename, "r") as _fd:
23
+ with open(sql_filename) as _fd:
23
24
  with db_connection.cursor() as cur:
24
- 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()))
25
27
  db_connection.commit()
26
28
 
27
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",
@@ -2,8 +2,9 @@
2
2
 
3
3
  import asyncio
4
4
  import datetime
5
+ from collections.abc import Awaitable, Callable
5
6
  from time import sleep
6
- from typing import Awaitable, Callable, Type, TypeVar
7
+ from typing import TypeVar
7
8
 
8
9
  T = TypeVar("T")
9
10
 
@@ -11,7 +12,7 @@ T = TypeVar("T")
11
12
  def retry(
12
13
  func: Callable[[], T],
13
14
  timeout: int = 60,
14
- possible_exception: Type[Exception] = Exception,
15
+ possible_exception: type[Exception] = Exception,
15
16
  ) -> T:
16
17
  """Attempt to retry the function for timeout time.
17
18
 
@@ -40,7 +41,7 @@ def retry(
40
41
  async def retry_async(
41
42
  func: Callable[[], Awaitable[T]],
42
43
  timeout: int = 60,
43
- possible_exception: Type[Exception] = Exception,
44
+ possible_exception: type[Exception] = Exception,
44
45
  ) -> T:
45
46
  """Attempt to retry the async function for timeout time.
46
47
 
@@ -68,4 +69,4 @@ async def retry_async(
68
69
 
69
70
  def get_current_datetime() -> datetime.datetime:
70
71
  """Get the current timezone-aware UTC datetime."""
71
- return datetime.datetime.now(datetime.timezone.utc)
72
+ return datetime.datetime.now(datetime.UTC)