0
# Configuration Options
1
2
Comprehensive configuration system supporting command-line options, pytest.ini settings, and programmatic configuration for all aspects of PostgreSQL testing setup and behavior.
3
4
## Capabilities
5
6
### Configuration Dictionary
7
8
Type-safe configuration dictionary containing all PostgreSQL testing options.
9
10
```python { .api }
11
class PostgresqlConfigDict(TypedDict):
12
"""
13
Typed configuration dictionary for PostgreSQL testing options.
14
15
Contains all configuration parameters with proper type annotations
16
for IDE support and type checking.
17
"""
18
exec: str # PostgreSQL executable path
19
host: str # Host address
20
port: Optional[str] # Port number
21
port_search_count: int # Port search attempts
22
user: str # Username
23
password: str # Password
24
options: str # Connection options
25
startparams: str # Server start parameters
26
unixsocketdir: str # Unix socket directory
27
dbname: str # Database name
28
load: List[Union[Path, str]] # Data loading paths
29
postgres_options: str # Postgres executable options
30
drop_test_database: bool # Drop database flag
31
```
32
33
### Configuration Functions
34
35
```python { .api }
36
def get_config(request: FixtureRequest) -> PostgresqlConfigDict:
37
"""
38
Retrieve configuration from pytest options and ini settings.
39
40
Combines command-line options and pytest.ini values to create
41
a complete configuration dictionary.
42
43
Parameters:
44
- request: pytest fixture request object
45
46
Returns:
47
Complete configuration dictionary with all PostgreSQL options
48
"""
49
50
def detect_paths(load_paths: List[Union[LocalPath, str]]) -> List[Union[Path, str]]:
51
"""
52
Convert load paths to proper Path instances.
53
54
Handles path conversion from pytest's LocalPath objects
55
to standard pathlib.Path objects.
56
57
Parameters:
58
- load_paths: List of paths in various formats
59
60
Returns:
61
List of normalized Path objects and strings
62
"""
63
```
64
65
## Configuration Options
66
67
### Server Configuration
68
69
#### PostgreSQL Executable
70
- **Option**: `--postgresql-exec` / `postgresql_exec`
71
- **Type**: `str`
72
- **Default**: `/usr/lib/postgresql/13/bin/pg_ctl`
73
- **Description**: Path to PostgreSQL pg_ctl executable
74
75
#### Host Configuration
76
- **Option**: `--postgresql-host` / `postgresql_host`
77
- **Type**: `str`
78
- **Default**: `127.0.0.1`
79
- **Description**: Host address for PostgreSQL connections
80
81
#### Port Configuration
82
- **Option**: `--postgresql-port` / `postgresql_port`
83
- **Type**: `Optional[str]`
84
- **Default**: `None` (auto-detect)
85
- **Description**: Port number for PostgreSQL server
86
87
#### Port Search Count
88
- **Option**: `--postgresql-port-search-count` / `postgresql_port_search_count`
89
- **Type**: `int`
90
- **Default**: `5`
91
- **Description**: Number of attempts to find free port
92
93
### Authentication Configuration
94
95
#### Username
96
- **Option**: `--postgresql-user` / `postgresql_user`
97
- **Type**: `str`
98
- **Default**: `postgres`
99
- **Description**: PostgreSQL username for connections
100
101
#### Password
102
- **Option**: `--postgresql-password` / `postgresql_password`
103
- **Type**: `Optional[str]`
104
- **Default**: `None`
105
- **Description**: PostgreSQL password for connections
106
107
### Connection Configuration
108
109
#### Connection Options
110
- **Option**: `--postgresql-options` / `postgresql_options`
111
- **Type**: `str`
112
- **Default**: `""`
113
- **Description**: Additional PostgreSQL connection options
114
115
#### Unix Socket Directory
116
- **Option**: `--postgresql-unixsocketdir` / `postgresql_unixsocketdir`
117
- **Type**: `str`
118
- **Default**: System temp directory
119
- **Description**: Directory for Unix domain sockets
120
121
### Process Configuration
122
123
#### Start Parameters
124
- **Option**: `--postgresql-startparams` / `postgresql_startparams`
125
- **Type**: `str`
126
- **Default**: `"-w"`
127
- **Description**: Parameters passed to PostgreSQL on startup
128
129
#### Postgres Options
130
- **Option**: `--postgresql-postgres-options` / `postgresql_postgres_options`
131
- **Type**: `str`
132
- **Default**: `""`
133
- **Description**: Additional options passed to postgres executable via -o
134
135
### Database Configuration
136
137
#### Database Name
138
- **Option**: `--postgresql-dbname` / `postgresql_dbname`
139
- **Type**: `str`
140
- **Default**: `tests`
141
- **Description**: Default database name for test databases
142
143
#### Data Loading
144
- **Option**: `--postgresql-load` / `postgresql_load`
145
- **Type**: `pathlist`
146
- **Default**: `[]`
147
- **Description**: List of SQL files or Python callables for database initialization
148
149
#### Drop Test Database
150
- **Option**: `--postgresql-drop-test-database` / `postgresql_drop_test_database`
151
- **Type**: `bool`
152
- **Default**: `False`
153
- **Description**: Drop test database if it exists (use cautiously)
154
155
## Configuration Examples
156
157
### Command Line Configuration
158
159
```bash
160
# Basic configuration via command line
161
pytest --postgresql-host=localhost \
162
--postgresql-port=5432 \
163
--postgresql-user=test_user \
164
--postgresql-dbname=test_db
165
166
# Advanced configuration
167
pytest --postgresql-exec=/usr/local/bin/pg_ctl \
168
--postgresql-startparams="-w -t 30" \
169
--postgresql-options="sslmode=disable" \
170
--postgresql-load=/path/to/schema.sql \
171
--postgresql-load=/path/to/data.sql
172
```
173
174
### pytest.ini Configuration
175
176
```ini
177
[tool:pytest]
178
postgresql_exec = /usr/local/bin/pg_ctl
179
postgresql_host = 127.0.0.1
180
postgresql_port = 5433
181
postgresql_user = test_user
182
postgresql_password = test_pass
183
postgresql_dbname = pytest_db
184
postgresql_options = sslmode=disable application_name=pytest
185
postgresql_startparams = -w -t 30
186
postgresql_unixsocketdir = /tmp/postgresql
187
postgresql_load =
188
/path/to/schema.sql
189
/path/to/fixtures.sql
190
postgresql_postgres_options = -c shared_preload_libraries=pg_stat_statements
191
postgresql_drop_test_database = false
192
```
193
194
### Programmatic Configuration
195
196
```python
197
import pytest
198
from pytest_postgresql.config import get_config
199
200
def test_configuration_access(request):
201
"""Test accessing configuration programmatically."""
202
config = get_config(request)
203
204
assert config['host'] == '127.0.0.1'
205
assert config['user'] == 'postgres'
206
assert config['dbname'] == 'tests'
207
assert isinstance(config['port_search_count'], int)
208
```
209
210
### Environment-Based Configuration
211
212
```python
213
import os
214
from pytest_postgresql import factories
215
216
# Use environment variables for dynamic configuration
217
postgresql_proc = factories.postgresql_proc(
218
host=os.getenv('POSTGRES_HOST', '127.0.0.1'),
219
port=int(os.getenv('POSTGRES_PORT', '0')), # 0 for auto-detect
220
user=os.getenv('POSTGRES_USER', 'postgres'),
221
password=os.getenv('POSTGRES_PASSWORD'),
222
dbname=os.getenv('POSTGRES_DB', 'tests')
223
)
224
```
225
226
### Configuration Override
227
228
```python
229
from pytest_postgresql import factories
230
231
# Override specific configuration options
232
postgresql_custom = factories.postgresql_proc(
233
# Override defaults with custom values
234
executable='/opt/postgresql/bin/pg_ctl',
235
host='custom.host.com',
236
port=5433,
237
user='custom_user',
238
password='custom_password',
239
dbname='custom_db',
240
options='sslmode=require connect_timeout=10',
241
startparams='-w -t 60',
242
unixsocketdir='/custom/socket/dir',
243
postgres_options='-c log_statement=all -c log_min_duration_statement=0'
244
)
245
```
246
247
### Multiple Configuration Profiles
248
249
```python
250
from pytest_postgresql import factories
251
252
# Development configuration
253
postgresql_dev = factories.postgresql_proc(
254
port=5432,
255
dbname='dev_tests',
256
startparams='-w',
257
postgres_options='-c log_statement=none'
258
)
259
260
# CI configuration
261
postgresql_ci = factories.postgresql_proc(
262
port=5433,
263
dbname='ci_tests',
264
startparams='-w -t 120',
265
postgres_options='-c fsync=off -c synchronous_commit=off' # Faster for CI
266
)
267
268
# Debug configuration
269
postgresql_debug = factories.postgresql_proc(
270
port=5434,
271
dbname='debug_tests',
272
startparams='-w -t 30',
273
postgres_options=(
274
'-c log_statement=all '
275
'-c log_min_duration_statement=0 '
276
'-c log_line_prefix="%t [%p]: [%l-1] "'
277
)
278
)
279
```
280
281
### Configuration Validation
282
283
```python
284
from pytest_postgresql.config import get_config
285
from pytest_postgresql.exceptions import ExecutableMissingException
286
import os
287
288
def test_config_validation(request):
289
"""Test configuration validation."""
290
config = get_config(request)
291
292
# Validate executable exists
293
if not os.path.exists(config['exec']):
294
raise ExecutableMissingException(f"PostgreSQL executable not found: {config['exec']}")
295
296
# Validate port range
297
if config['port'] and not (1024 <= int(config['port']) <= 65535):
298
raise ValueError(f"Invalid port number: {config['port']}")
299
300
# Validate directory exists
301
if not os.path.exists(config['unixsocketdir']):
302
os.makedirs(config['unixsocketdir'], exist_ok=True)
303
```
304
305
## Configuration Precedence
306
307
Configuration values are resolved in the following order (highest to lowest precedence):
308
309
1. **Factory function parameters** - Direct parameters to `postgresql_proc()`, etc.
310
2. **Command-line options** - `--postgresql-*` flags
311
3. **pytest.ini settings** - `postgresql_*` options in pytest.ini
312
4. **Default values** - Built-in defaults
313
314
### Configuration Resolution Example
315
316
```python
317
# pytest.ini has: postgresql_port = 5432
318
# Command line has: --postgresql-port=5433
319
# Factory has: postgresql_proc(port=5434)
320
321
# Result: port=5434 (factory parameter wins)
322
postgresql_proc = factories.postgresql_proc(port=5434)
323
```
324
325
## Advanced Configuration
326
327
### Custom Configuration Classes
328
329
```python
330
from pytest_postgresql.config import PostgresqlConfigDict
331
from typing import Optional
332
333
class CustomPostgresConfig(PostgresqlConfigDict):
334
"""Extended configuration with custom options."""
335
custom_option: str
336
debug_mode: bool
337
338
def get_custom_config(request) -> CustomPostgresConfig:
339
"""Get configuration with custom extensions."""
340
base_config = get_config(request)
341
return CustomPostgresConfig(
342
**base_config,
343
custom_option='custom_value',
344
debug_mode=True
345
)
346
```
347
348
### Configuration Hooks
349
350
```python
351
def pytest_configure(config):
352
"""Customize pytest-postgresql configuration."""
353
# Add custom defaults
354
if not config.getoption('postgresql_port'):
355
config.option.postgresql_port = '5555'
356
357
# Environment-based overrides
358
if os.getenv('CI'):
359
config.option.postgresql_startparams = '-w -t 120'
360
```