Skip to content

Commit 5c567cf

Browse files
committed
Allow chaining noprocess fixtures - closes #890
This allows for more complex test suites with common base data fixture Extended for a specific group of tests that needs additional data elements in database
1 parent 43ecec6 commit 5c567cf

10 files changed

Lines changed: 213 additions & 34 deletions

File tree

‎README.rst‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,33 @@ To connect to an external server (e.g., running in Docker), use the ``postgresql
146146
147147
By default, it connects to ``127.0.0.1:5432``.
148148

149+
Chaining fixtures
150+
-----------------
151+
152+
You can chain multiple ``postgresql_noproc`` fixtures to layer your data pre-population. Each fixture in the chain will create its own template database based on the previous one.
153+
154+
.. code-block:: python
155+
156+
from pytest_postgresql import factories
157+
158+
# 1. Start with a process or a no-process base
159+
base_proc = factories.postgresql_proc(load=[load_schema])
160+
161+
# 2. Add a layer with some data
162+
seeded_noproc = factories.postgresql_noproc(depends_on="base_proc", load=[load_data])
163+
164+
# 3. Add another layer with more data
165+
more_seeded_noproc = factories.postgresql_noproc(depends_on="seeded_noproc", load=[load_more_data])
166+
167+
# 4. Use the final layer in your test
168+
client = factories.postgresql("more_seeded_noproc")
169+
170+
171+
172+
.. image:: https://raw.githubusercontent.com/dbfixtures/pytest-postgresql/main/docs/images/architecture_chaining.svg
173+
:alt: Fixture Chaining Diagram
174+
:align: center
175+
149176
Configuration
150177
=============
151178

‎docs/architecture_chaining.mmd‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
sequenceDiagram
2+
participant Test as Test
3+
participant ProcF as base_proc Fixture
4+
participant NoProc1 as seeded_noproc Fixture
5+
participant NoProc2 as more_seeded_noproc Fixture
6+
participant DB as PostgreSQL DB
7+
8+
Test->>ProcF: request base_proc
9+
ProcF->>DB: init database & run load_schema
10+
ProcF-->>Test: return PostgreSQLExecutor
11+
12+
Test->>NoProc1: request seeded_noproc (depends_on=base_proc)
13+
NoProc1->>ProcF: read connection/template info
14+
NoProc1->>DB: create layered DB / run load_data
15+
NoProc1-->>Test: return NoopExecutor
16+
17+
Test->>NoProc2: request more_seeded_noproc (depends_on=seeded_noproc)
18+
NoProc2->>NoProc1: read connection/template info
19+
NoProc2->>DB: run load_more_data on layered DB
20+
NoProc2-->>Test: return NoopExecutor
21+
22+
Test->>Test: validate tables and data across layers

‎newsfragments/890.break.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Refactor ``DatabaseJanitor`` to use explicit template management. This includes a new ``as_template`` flag and making ``dbname`` a required parameter.

‎newsfragments/890.docs.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add a Mermaid sequence diagram to the documentation to illustrate fixture chaining and hierarchical cloning.

‎newsfragments/890.feature.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add ``depends_on`` parameter to ``postgresql_noproc`` factory to allow hierarchical cloning and chaining of process fixtures.

‎pytest_postgresql/factories/noprocess.py‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ def postgresql_noproc(
4545
dbname: str | None = None,
4646
options: str = "",
4747
load: list[Callable | str | Path] | None = None,
48+
depends_on: str | None = None,
4849
) -> Callable[[FixtureRequest], Iterator[NoopExecutor]]:
4950
"""Postgresql noprocess factory.
5051
@@ -55,6 +56,7 @@ def postgresql_noproc(
5556
:param dbname: postgresql database name
5657
:param options: Postgresql connection options
5758
:param load: List of functions used to initialize database's template.
59+
:param depends_on: Optional name of the fixture to depend on.
5860
:returns: function which makes a postgresql process
5961
"""
6062

@@ -66,32 +68,53 @@ def postgresql_noproc_fixture(request: FixtureRequest) -> Iterator[NoopExecutor]
6668
:returns: tcp executor-like object
6769
"""
6870
config = get_config(request)
69-
pg_host = host or config.host
70-
pg_port = port or config.port or 5432
71-
pg_user = user or config.user
72-
pg_password = password or config.password
71+
72+
if depends_on:
73+
base = request.getfixturevalue(depends_on)
74+
pg_host = host or base.host
75+
pg_port = port or base.port
76+
pg_user = user or base.user
77+
pg_password = password or base.password
78+
pg_options = options or base.options
79+
base_template_dbname = base.template_dbname
80+
else:
81+
pg_host = host or config.host
82+
pg_port = port or config.port or 5432
83+
pg_user = user or config.user
84+
pg_password = password or config.password
85+
pg_options = options or config.options
86+
base_template_dbname = None
87+
7388
pg_dbname = xdistify_dbname(dbname or config.dbname)
74-
pg_options = options or config.options
7589
pg_load = load or config.load
7690
drop_test_database = config.drop_test_database
7791

92+
# In this case there's a risk that both seeded and depends_on fixture
93+
# might end up with the same configured dbname.
94+
if depends_on and not dbname:
95+
noop_exec_dbname = f"{pg_dbname}_{depends_on}"
96+
else:
97+
noop_exec_dbname = pg_dbname
98+
7899
noop_exec = NoopExecutor(
79100
host=pg_host,
80101
port=pg_port,
81102
user=pg_user,
82103
password=pg_password,
83-
dbname=pg_dbname,
104+
dbname=noop_exec_dbname,
84105
options=pg_options,
85106
)
86107
janitor = DatabaseJanitor(
87108
user=noop_exec.user,
88109
host=noop_exec.host,
89110
port=noop_exec.port,
90-
template_dbname=noop_exec.template_dbname,
111+
dbname=noop_exec.template_dbname,
112+
template_dbname=base_template_dbname,
113+
as_template=True,
91114
version=noop_exec.version,
92115
password=noop_exec.password,
93116
)
94-
if drop_test_database is True:
117+
if drop_test_database:
95118
janitor.drop()
96119
with janitor:
97120
for load_element in pg_load:

‎pytest_postgresql/factories/process.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,8 @@ def postgresql_proc_fixture(
170170
user=postgresql_executor.user,
171171
host=postgresql_executor.host,
172172
port=postgresql_executor.port,
173-
template_dbname=postgresql_executor.template_dbname,
173+
dbname=postgresql_executor.template_dbname,
174+
as_template=True,
174175
version=postgresql_executor.version,
175176
password=postgresql_executor.password,
176177
)

‎pytest_postgresql/janitor.py‎

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@ def __init__(
2828
host: str,
2929
port: str | int,
3030
version: str | float | Version, # type: ignore[valid-type]
31-
dbname: str | None = None,
31+
dbname: str,
3232
template_dbname: str | None = None,
33+
as_template: bool = False,
3334
password: str | None = None,
3435
isolation_level: "psycopg.IsolationLevel | None" = None,
3536
connection_timeout: int = 60,
@@ -40,7 +41,8 @@ def __init__(
4041
:param host: postgresql host
4142
:param port: postgresql port
4243
:param dbname: database name
43-
:param dbname: template database name
44+
:param template_dbname: template database name to clone from
45+
:param as_template: whether to mark the database as a template
4446
:param version: postgresql version number
4547
:param password: optional postgresql password
4648
:param isolation_level: optional postgresql isolation level
@@ -52,10 +54,9 @@ def __init__(
5254
self.password = password
5355
self.host = host
5456
self.port = port
55-
# At least one of the dbname or template_dbname has to be filled.
56-
assert any([dbname, template_dbname])
5757
self.dbname = dbname
5858
self.template_dbname = template_dbname
59+
self.as_template = as_template
5960
self._connection_timeout = connection_timeout
6061
self.isolation_level = isolation_level
6162
if not isinstance(version, Version):
@@ -66,32 +67,33 @@ def __init__(
6667
def init(self) -> None:
6768
"""Create database in postgresql."""
6869
with self.cursor() as cur:
69-
if self.is_template():
70-
cur.execute(f'CREATE DATABASE "{self.template_dbname}" WITH is_template = true;')
71-
elif self.template_dbname is None:
72-
cur.execute(f'CREATE DATABASE "{self.dbname}";')
73-
else:
70+
if self.template_dbname:
7471
# And make sure no-one is left connected to the template database.
7572
# Otherwise, Creating database from template will fail
7673
self._terminate_connection(cur, self.template_dbname)
77-
cur.execute(f'CREATE DATABASE "{self.dbname}" TEMPLATE "{self.template_dbname}";')
74+
query = f'CREATE DATABASE "{self.dbname}" TEMPLATE "{self.template_dbname}"'
75+
else:
76+
query = f'CREATE DATABASE "{self.dbname}"'
77+
78+
if self.as_template:
79+
query += " IS_TEMPLATE = true"
80+
81+
cur.execute(f"{query};")
7882

7983
def is_template(self) -> bool:
8084
"""Determine whether the DatabaseJanitor maintains template or database."""
81-
return self.dbname is None
85+
return self.as_template
8286

8387
def drop(self) -> None:
8488
"""Drop database in postgresql."""
8589
# We cannot drop the database while there are connections to it, so we
8690
# terminate all connections first while not allowing new connections.
87-
db_to_drop = self.template_dbname if self.is_template() else self.dbname
88-
assert db_to_drop
8991
with self.cursor() as cur:
90-
self._dont_datallowconn(cur, db_to_drop)
91-
self._terminate_connection(cur, db_to_drop)
92-
if self.is_template():
93-
cur.execute(f'ALTER DATABASE "{db_to_drop}" with is_template false;')
94-
cur.execute(f'DROP DATABASE IF EXISTS "{db_to_drop}";')
92+
self._dont_datallowconn(cur, self.dbname)
93+
self._terminate_connection(cur, self.dbname)
94+
if self.as_template:
95+
cur.execute(f'ALTER DATABASE "{self.dbname}" with is_template false;')
96+
cur.execute(f'DROP DATABASE IF EXISTS "{self.dbname}";')
9597

9698
@staticmethod
9799
def _dont_datallowconn(cur: Cursor, dbname: str) -> None:
@@ -116,13 +118,12 @@ def load(self, load: Callable | str | Path) -> None:
116118
* a callable that expects: host, port, user, dbname and password arguments.
117119
118120
"""
119-
db_to_load = self.template_dbname if self.is_template() else self.dbname
120121
_loader = build_loader(load)
121122
_loader(
122123
host=self.host,
123124
port=self.port,
124125
user=self.user,
125-
dbname=db_to_load,
126+
dbname=self.dbname,
126127
password=self.password,
127128
)
128129

‎tests/test_chaining.py‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
"""Chaining noprocess fixtures tests for pytest-postgresql."""
2+
3+
import psycopg
4+
5+
from pytest_postgresql import factories
6+
from pytest_postgresql.executor import PostgreSQLExecutor
7+
from pytest_postgresql.executor_noop import NoopExecutor
8+
9+
10+
def load_schema(host: str, port: int, user: str, dbname: str, password: str | None) -> None:
11+
"""Load schema into the database."""
12+
with psycopg.connect(host=host, port=port, user=user, dbname=dbname, password=password) as conn:
13+
with conn.cursor() as cur:
14+
cur.execute("CREATE TABLE schema_table (id serial PRIMARY KEY, name varchar);")
15+
conn.commit()
16+
17+
18+
def load_data(host: str, port: int, user: str, dbname: str, password: str | None) -> None:
19+
"""Load the first layer of data into the database."""
20+
with psycopg.connect(host=host, port=port, user=user, dbname=dbname, password=password) as conn:
21+
with conn.cursor() as cur:
22+
cur.execute("INSERT INTO schema_table (name) VALUES ('data_layer');")
23+
cur.execute("CREATE TABLE data_table (id serial PRIMARY KEY, val varchar);")
24+
conn.commit()
25+
26+
27+
def load_more_data(host: str, port: int, user: str, dbname: str, password: str | None) -> None:
28+
"""Load the second layer of data into the database."""
29+
with psycopg.connect(host=host, port=port, user=user, dbname=dbname, password=password) as conn:
30+
with conn.cursor() as cur:
31+
cur.execute("INSERT INTO schema_table (name) VALUES ('more_data_layer');")
32+
cur.execute("CREATE TABLE more_data_table (id serial PRIMARY KEY, extra varchar);")
33+
conn.commit()
34+
35+
36+
# Chaining: proc -> noproc -> client
37+
base_proc = factories.postgresql_proc(load=[load_schema])
38+
seeded_noproc = factories.postgresql_noproc(depends_on="base_proc", load=[load_data])
39+
client_layered = factories.postgresql("seeded_noproc")
40+
41+
# Deeper chaining: proc -> noproc -> noproc -> client
42+
more_seeded_noproc = factories.postgresql_noproc(depends_on="seeded_noproc", load=[load_more_data])
43+
client_deep_layered = factories.postgresql("more_seeded_noproc")
44+
45+
46+
def test_chaining_two_layers(client_layered: psycopg.Connection) -> None:
47+
"""Test that data from both proc and noproc layers is present."""
48+
with client_layered.cursor() as cur:
49+
# From base_proc (load_schema)
50+
cur.execute("SELECT count(*) FROM information_schema.tables WHERE table_name = 'schema_table';")
51+
res = cur.fetchone()
52+
assert res
53+
assert res[0] == 1
54+
55+
# From seeded_noproc (load_data)
56+
cur.execute("SELECT count(*) FROM information_schema.tables WHERE table_name = 'data_table';")
57+
res = cur.fetchone()
58+
assert res
59+
assert res[0] == 1
60+
61+
# Data inserted in seeded_noproc
62+
cur.execute("SELECT name FROM schema_table;")
63+
res = cur.fetchone()
64+
assert res
65+
assert res[0] == "data_layer"
66+
67+
68+
def test_chaining_three_layers(client_deep_layered: psycopg.Connection) -> None:
69+
"""Test that data from all three layers is present."""
70+
with client_deep_layered.cursor() as cur:
71+
# From base_proc
72+
cur.execute("SELECT count(*) FROM information_schema.tables WHERE table_name = 'schema_table';")
73+
res = cur.fetchone()
74+
assert res
75+
assert res[0] == 1
76+
77+
# From seeded_noproc
78+
cur.execute("SELECT count(*) FROM information_schema.tables WHERE table_name = 'data_table';")
79+
res = cur.fetchone()
80+
assert res
81+
assert res[0] == 1
82+
83+
# From more_seeded_noproc
84+
cur.execute("SELECT count(*) FROM information_schema.tables WHERE table_name = 'more_data_table';")
85+
res = cur.fetchone()
86+
assert res
87+
assert res[0] == 1
88+
89+
# Data from multiple layers
90+
cur.execute("SELECT name FROM schema_table ORDER BY id;")
91+
results = cur.fetchall()
92+
assert results[0][0] == "data_layer"
93+
assert results[1][0] == "more_data_layer"
94+
95+
96+
def test_inheritance(base_proc: PostgreSQLExecutor, seeded_noproc: NoopExecutor) -> None:
97+
"""Verify that connection parameters are inherited from the base fixture."""
98+
assert seeded_noproc.host == base_proc.host
99+
assert seeded_noproc.port == base_proc.port
100+
assert seeded_noproc.user == base_proc.user
101+
assert seeded_noproc.password == base_proc.password

‎tests/test_postgres_options_plugin.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,20 +95,21 @@ def test_postgres_drop_test_database(
9595
user=postgresql_proc_to_override.user,
9696
host=postgresql_proc_to_override.host,
9797
port=postgresql_proc_to_override.port,
98-
template_dbname=template_dbname,
98+
dbname=template_dbname,
99+
as_template=True,
99100
version=postgresql_proc_to_override.version,
100101
password=postgresql_proc_to_override.password,
101102
connection_timeout=5,
102103
)
103104
template_janitor.init()
104105
template_janitor.load(load_database)
105-
assert template_janitor.template_dbname
106+
assert template_janitor.dbname
106107
janitor = DatabaseJanitor(
107108
user=postgresql_proc_to_override.user,
108109
host=postgresql_proc_to_override.host,
109110
port=postgresql_proc_to_override.port,
110111
dbname=dbname,
111-
template_dbname=template_janitor.template_dbname,
112+
template_dbname=template_janitor.dbname,
112113
version=postgresql_proc_to_override.version,
113114
password=postgresql_proc_to_override.password,
114115
connection_timeout=5,
@@ -137,7 +138,7 @@ def test_postgres_drop_test_database(
137138
assert hasattr(excinfo.value, "__cause__")
138139
assert f'FATAL: database "{janitor.dbname}" does not exist' in str(excinfo.value.__cause__)
139140
with pytest.raises(TimeoutError) as excinfo:
140-
with template_janitor.cursor(template_janitor.template_dbname):
141+
with template_janitor.cursor(template_janitor.dbname):
141142
pass
142143
assert hasattr(excinfo.value, "__cause__")
143-
assert f'FATAL: database "{template_janitor.template_dbname}" does not exist' in str(excinfo.value.__cause__)
144+
assert f'FATAL: database "{template_janitor.dbname}" does not exist' in str(excinfo.value.__cause__)

0 commit comments

Comments
 (0)