psycopg-toolkit 0.2.2__tar.gz → 0.3.1__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 (21) hide show
  1. psycopg_toolkit-0.3.1/PKG-INFO +720 -0
  2. psycopg_toolkit-0.3.1/README.md +687 -0
  3. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/pyproject.toml +2 -2
  4. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/core/database.py +3 -1
  5. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/repositories/base.py +62 -5
  6. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/utils/type_inspector.py +102 -0
  7. psycopg_toolkit-0.2.2/PKG-INFO +0 -335
  8. psycopg_toolkit-0.2.2/README.md +0 -302
  9. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/.gitignore +0 -0
  10. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/.vscode/settings.json +0 -0
  11. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/LICENSE +0 -0
  12. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/__init__.py +0 -0
  13. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/core/__init__.py +0 -0
  14. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/core/config.py +0 -0
  15. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/core/factory.py +0 -0
  16. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/core/transaction.py +0 -0
  17. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/exceptions.py +0 -0
  18. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/repositories/__init__.py +0 -0
  19. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/utils/__init__.py +0 -0
  20. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/utils/json_handler.py +0 -0
  21. {psycopg_toolkit-0.2.2 → psycopg_toolkit-0.3.1}/src/psycopg_toolkit/utils/psychopg_helper.py +0 -0
@@ -0,0 +1,720 @@
1
+ Metadata-Version: 2.4
2
+ Name: psycopg-toolkit
3
+ Version: 0.3.1
4
+ Summary: A Python PostgreSQL database utility with connection pooling
5
+ Project-URL: Homepage, https://github.com/descoped/psycopg-toolkit
6
+ Project-URL: Repository, https://github.com/descoped/psycopg-toolkit
7
+ Project-URL: Documentation, https://github.com/descoped/psycopg-toolkit/tree/master/docs
8
+ Project-URL: Issues, https://github.com/descoped/psycopg-toolkit/issues
9
+ Author-email: Ove Ranheim <oranheim@gmail.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: async,database,jsonb,pgvector,pool,postgresql,psycopg,repository-pattern
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Framework :: Pydantic :: 2
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Database
24
+ Classifier: Topic :: Database :: Database Engines/Servers
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
28
+ Requires-Dist: psycopg-pool>=3.2.4
29
+ Requires-Dist: psycopg>=3.2.3
30
+ Requires-Dist: pydantic>=2.10.5
31
+ Requires-Dist: tenacity>=9.0.0
32
+ Description-Content-Type: text/markdown
33
+
34
+ # Psycopg Toolkit
35
+
36
+ [![Build Status](https://github.com/descoped/psycopg-toolkit/actions/workflows/build-test.yml/badge.svg)](https://github.com/descoped/psycopg-toolkit/actions/workflows/build-test-native.yml)
37
+ [![Coverage](https://codecov.io/gh/descoped/psycopg-toolkit/branch/master/graph/badge.svg)](https://codecov.io/gh/descoped/psycopg-toolkit)
38
+ [![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
39
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
40
+ [![Release](https://img.shields.io/github/v/release/descoped/psycopg-toolkit)](https://github.com/descoped/psycopg-toolkit/releases)
41
+
42
+ A robust PostgreSQL database toolkit providing enterprise-grade connection pooling and database management capabilities for Python applications.
43
+
44
+ ## Features
45
+
46
+ - Async-first design with connection pooling via `psycopg-pool`
47
+ - Comprehensive transaction management with savepoint support
48
+ - Type-safe repository pattern with Pydantic model validation
49
+ - **JSONB support with automatic field detection and psycopg JSON adapters**
50
+ - **Native pgvector support with automatic vector field detection**
51
+ - PostgreSQL array field preservation (TEXT[], INTEGER[])
52
+ - Automatic date/timestamp conversion for Pydantic models
53
+ - SQL query builder with SQL injection protection
54
+ - Database schema and test data lifecycle management
55
+ - Automatic retry mechanism with exponential backoff
56
+ - Granular exception hierarchy for error handling
57
+ - Connection health monitoring and validation
58
+ - Database initialization callback system
59
+ - Statement timeout configuration
60
+ - Fully typed with modern Python type hints
61
+
62
+ ## Installation
63
+
64
+ ```bash
65
+ pip install psycopg-toolkit
66
+ ```
67
+
68
+ ## Quick Start
69
+
70
+ ```python
71
+ from psycopg_toolkit import Database, DatabaseSettings
72
+ from uuid import uuid4
73
+
74
+ # Configure database
75
+ settings = DatabaseSettings(
76
+ host="localhost",
77
+ port=5432,
78
+ dbname="your_database",
79
+ user="your_user",
80
+ password="your_password"
81
+ )
82
+
83
+ async def main():
84
+ # Initialize database
85
+ db = Database(settings)
86
+ await db.init_db()
87
+
88
+ # Get transaction manager
89
+ tm = await db.get_transaction_manager()
90
+
91
+ # Execute in transaction
92
+ async with tm.transaction() as conn:
93
+ async with conn.cursor() as cur:
94
+ user_id = uuid4()
95
+ await cur.execute(
96
+ "INSERT INTO users (id, email) VALUES (%s, %s)",
97
+ (user_id, "user@example.com")
98
+ )
99
+
100
+ # Clean up
101
+ await db.cleanup()
102
+ ```
103
+
104
+ ## Core Components
105
+
106
+ ### Database Management
107
+
108
+ ```python
109
+ # Health check
110
+ is_healthy = await db.check_pool_health()
111
+
112
+ # Connection management
113
+ async with db.connection() as conn:
114
+ async with conn.cursor() as cur:
115
+ await cur.execute("SELECT version()")
116
+ ```
117
+
118
+ ### Transaction Management
119
+
120
+ ```python
121
+ # Basic transaction
122
+ async with tm.transaction() as conn:
123
+ # Operations automatically rolled back on error
124
+ pass
125
+
126
+ # With savepoint
127
+ async with tm.transaction(savepoint="user_creation") as conn:
128
+ # Nested transaction using savepoint
129
+ pass
130
+ ```
131
+
132
+ ### Repository Pattern
133
+
134
+ ```python
135
+ from pydantic import BaseModel
136
+ from psycopg_toolkit import BaseRepository
137
+
138
+ class User(BaseModel):
139
+ id: UUID
140
+ email: str
141
+
142
+ class UserRepository(BaseRepository[User]):
143
+ def __init__(self, conn: AsyncConnection):
144
+ super().__init__(
145
+ db_connection=conn,
146
+ table_name="users",
147
+ model_class=User,
148
+ primary_key="id"
149
+ )
150
+
151
+ # Usage
152
+ async with tm.transaction() as conn:
153
+ repo = UserRepository(conn)
154
+ user = await repo.get_by_id(user_id)
155
+ ```
156
+
157
+ ### JSONB Support
158
+
159
+ ```python
160
+ from typing import Dict, List, Any
161
+ from pydantic import BaseModel
162
+ from psycopg_toolkit import BaseRepository
163
+
164
+ class UserProfile(BaseModel):
165
+ id: int
166
+ name: str
167
+ # These fields are automatically detected as JSONB
168
+ metadata: Dict[str, Any]
169
+ preferences: Dict[str, str]
170
+ tags: List[str]
171
+
172
+ class UserRepository(BaseRepository[UserProfile, int]):
173
+ def __init__(self, conn):
174
+ super().__init__(
175
+ db_connection=conn,
176
+ table_name="user_profiles",
177
+ model_class=UserProfile,
178
+ primary_key="id"
179
+ # auto_detect_json=True by default
180
+ )
181
+
182
+ # Usage - JSON fields handled automatically
183
+ user = UserProfile(
184
+ id=1,
185
+ name="John Doe",
186
+ metadata={"created_at": "2024-01-01", "source": "web"},
187
+ preferences={"theme": "dark", "language": "en"},
188
+ tags=["premium", "beta_tester"]
189
+ )
190
+
191
+ # JSONB fields automatically serialized/deserialized
192
+ created_user = await repo.create(user)
193
+ retrieved_user = await repo.get_by_id(1)
194
+ ```
195
+
196
+ ### PostgreSQL Arrays and Date Fields
197
+
198
+ ```python
199
+ from typing import List
200
+ from datetime import date
201
+ from pydantic import BaseModel
202
+ from psycopg_toolkit import BaseRepository
203
+
204
+ class User(BaseModel):
205
+ id: UUID
206
+ username: str
207
+ roles: List[str] # PostgreSQL TEXT[] array
208
+ permissions: List[str] # PostgreSQL TEXT[] array
209
+ metadata: Dict[str, Any] # JSONB field
210
+ birthdate: str # ISO date string (from DATE)
211
+ created_at: str # ISO datetime string (from TIMESTAMP)
212
+ updated_at: str # ISO datetime string (from TIMESTAMPTZ)
213
+ last_login: str | None # Optional timestamp field
214
+
215
+ class UserRepository(BaseRepository[User, UUID]):
216
+ def __init__(self, conn):
217
+ super().__init__(
218
+ db_connection=conn,
219
+ table_name="users",
220
+ model_class=User,
221
+ primary_key="id",
222
+ # Preserve PostgreSQL arrays instead of JSONB
223
+ array_fields={"roles", "permissions"},
224
+ # Auto-convert ALL date/timestamp fields to/from strings
225
+ date_fields={"birthdate", "created_at", "updated_at", "last_login"}
226
+ )
227
+
228
+ # PostgreSQL arrays are preserved, dates are auto-converted
229
+ user = User(
230
+ id=uuid4(),
231
+ username="john",
232
+ roles=["admin", "user"], # Stored as TEXT[]
233
+ permissions=["read", "write"], # Stored as TEXT[]
234
+ metadata={"dept": "IT"}, # Stored as JSONB
235
+ birthdate="1990-01-01", # Converts to/from PostgreSQL DATE
236
+ created_at="2024-01-01T12:00:00", # Converts to/from TIMESTAMP
237
+ updated_at="2024-01-01T12:00:00", # Converts to/from TIMESTAMPTZ
238
+ last_login=None # Nullable timestamp field
239
+ )
240
+ ```
241
+
242
+ ### Schema Management
243
+
244
+ ```python
245
+ from psycopg_toolkit.core.transaction import SchemaManager
246
+
247
+ class UserSchemaManager(SchemaManager[None]):
248
+ async def create_schema(self, conn: AsyncConnection) -> None:
249
+ await conn.execute("""
250
+ CREATE TABLE IF NOT EXISTS users (
251
+ id UUID PRIMARY KEY,
252
+ email TEXT UNIQUE NOT NULL
253
+ )
254
+ """)
255
+
256
+ async def drop_schema(self, conn: AsyncConnection) -> None:
257
+ await conn.execute("DROP TABLE IF EXISTS users")
258
+
259
+ # Usage
260
+ async with tm.with_schema(UserSchemaManager()) as _:
261
+ # Schema available here
262
+ pass # Automatically dropped after
263
+ ```
264
+
265
+ ## Error Handling
266
+
267
+ ```python
268
+ from psycopg_toolkit import (
269
+ DatabaseConnectionError,
270
+ DatabasePoolError,
271
+ DatabaseNotAvailable,
272
+ RecordNotFoundError
273
+ )
274
+
275
+ try:
276
+ async with tm.transaction() as conn:
277
+ repo = UserRepository(conn)
278
+ user = await repo.get_by_id(user_id)
279
+ except DatabaseConnectionError as e:
280
+ print(f"Connection error: {e.original_error}")
281
+ except RecordNotFoundError:
282
+ print(f"User {user_id} not found")
283
+ ```
284
+
285
+
286
+ ## Testing with Async Libraries
287
+
288
+ ### Understanding the pytest and Async Boundary
289
+
290
+ When testing async libraries like `async-task-worker` or database libraries (e.g., `psycopg-toolkit`), you'll encounter a fundamental challenge: pytest's session-scoped fixtures are synchronous, while modern libraries are increasingly async. This section explains the problem and provides the recommended patterns for handling this boundary.
291
+
292
+ #### The Core Problem
293
+
294
+ pytest's fixture system was designed before async became prevalent in Python:
295
+ - **Session fixtures are synchronous**: They run once per test session and must be sync functions
296
+ - **Modern libraries are async**: Database pools, task workers, and connections require `await`
297
+ - **Resource efficiency matters**: You want to reuse expensive resources (containers, pools) across tests
298
+
299
+ This creates an awkward boundary where you need async resources in sync fixture setup.
300
+
301
+ #### The Standard Solution: `asyncio.run()`
302
+
303
+ The accepted pattern in the Python testing community is using `asyncio.run()` in session fixtures. While it may feel inelegant, this is the recommended approach documented in pytest-asyncio's own examples.
304
+
305
+ ```python
306
+ import pytest
307
+ import asyncio
308
+ from async_task_worker import AsyncTaskWorker
309
+
310
+ @pytest.fixture(scope="session")
311
+ def worker():
312
+ """Session-scoped worker for test efficiency.
313
+
314
+ This uses asyncio.run() to bridge the sync/async boundary.
315
+ This is the standard pattern for async resources in session fixtures.
316
+ """
317
+ # Create the worker
318
+ worker = AsyncTaskWorker(max_workers=5)
319
+
320
+ # Start it using asyncio.run() - the standard workaround
321
+ asyncio.run(worker.start())
322
+
323
+ yield worker
324
+
325
+ # Cleanup
326
+ asyncio.run(worker.stop())
327
+
328
+ # Your async tests can then use the worker normally
329
+ @pytest.mark.asyncio
330
+ async def test_task_execution(worker):
331
+ task_id = await worker.add_task(my_task, data)
332
+ result = await worker.get_task_future(task_id)
333
+ assert result == expected
334
+ ```
335
+
336
+ ### Complete Testing Pattern
337
+
338
+ Here's a comprehensive example showing best practices for testing async-task-worker:
339
+
340
+ ```python
341
+ import pytest
342
+ import pytest_asyncio
343
+ import asyncio
344
+ from datetime import datetime
345
+ from async_task_worker import AsyncTaskWorker, task, TaskStatus
346
+
347
+ # ============================================================
348
+ # Session Fixtures (Synchronous with asyncio.run())
349
+ # ============================================================
350
+
351
+ @pytest.fixture(scope="session")
352
+ def event_loop_policy():
353
+ """Use a specific event loop policy for tests."""
354
+ return asyncio.get_event_loop_policy()
355
+
356
+ @pytest.fixture(scope="session")
357
+ def worker():
358
+ """Create a session-scoped worker instance.
359
+
360
+ Note: We use asyncio.run() here because session fixtures
361
+ must be synchronous. This is the standard pattern.
362
+ """
363
+ worker = AsyncTaskWorker(
364
+ max_workers=3,
365
+ task_timeout=10,
366
+ cache_enabled=True,
367
+ cache_ttl=60
368
+ )
369
+
370
+ # Start the worker using asyncio.run()
371
+ asyncio.run(worker.start())
372
+
373
+ yield worker
374
+
375
+ # Cleanup
376
+ asyncio.run(worker.stop())
377
+
378
+ # ============================================================
379
+ # Function-Scoped Async Fixtures (Can use async/await)
380
+ # ============================================================
381
+
382
+ @pytest_asyncio.fixture
383
+ async def clean_worker(worker):
384
+ """Provides a clean worker state for each test."""
385
+ # Clear any existing tasks
386
+ tasks = worker.get_all_tasks()
387
+ for task in tasks:
388
+ if task.status in ("pending", "running"):
389
+ await worker.cancel_task(task.id)
390
+
391
+ # Clear cache if enabled
392
+ if worker.cache:
393
+ await worker.clear_cache()
394
+
395
+ yield worker
396
+
397
+ # Post-test cleanup if needed
398
+ # ...
399
+
400
+ # ============================================================
401
+ # Test Task Definitions
402
+ # ============================================================
403
+
404
+ @task("test_computation")
405
+ async def test_computation(value, delay=0.1, progress_callback=None):
406
+ """A test task that simulates computation."""
407
+ steps = 5
408
+ result = value
409
+
410
+ for i in range(steps):
411
+ await asyncio.sleep(delay)
412
+ result = result * 2
413
+
414
+ if progress_callback:
415
+ progress_callback((i + 1) / steps)
416
+
417
+ return result
418
+
419
+ @task("test_failing_task")
420
+ async def test_failing_task(should_fail=True):
421
+ """A task that can be configured to fail."""
422
+ if should_fail:
423
+ raise ValueError("Task failed as expected")
424
+ return "success"
425
+
426
+ # ============================================================
427
+ # Test Cases
428
+ # ============================================================
429
+
430
+ @pytest.mark.asyncio
431
+ async def test_basic_task_execution(clean_worker):
432
+ """Test basic task execution flow."""
433
+ # Add a task
434
+ task_id = await clean_worker.add_task(
435
+ test_computation,
436
+ value=2,
437
+ delay=0.01
438
+ )
439
+
440
+ # Wait for completion
441
+ result = await clean_worker.get_task_future(task_id)
442
+
443
+ # Verify result (2 * 2^5 = 64)
444
+ assert result == 64
445
+
446
+ # Check task info
447
+ info = clean_worker.get_task_info(task_id)
448
+ assert info.status == TaskStatus.COMPLETED
449
+ assert info.progress == 1.0
450
+
451
+ @pytest.mark.asyncio
452
+ async def test_task_cancellation(clean_worker):
453
+ """Test task cancellation."""
454
+ # Start a long-running task
455
+ task_id = await clean_worker.add_task(
456
+ test_computation,
457
+ value=1,
458
+ delay=1.0 # Long delay
459
+ )
460
+
461
+ # Cancel it
462
+ cancelled = await clean_worker.cancel_task(task_id)
463
+ assert cancelled
464
+
465
+ # Verify status
466
+ info = clean_worker.get_task_info(task_id)
467
+ assert info.status == TaskStatus.CANCELLED
468
+
469
+ @pytest.mark.asyncio
470
+ async def test_cache_functionality(clean_worker):
471
+ """Test caching of task results."""
472
+ # First execution
473
+ task_id1 = await clean_worker.add_task(
474
+ test_computation,
475
+ value=3,
476
+ delay=0.01,
477
+ use_cache=True
478
+ )
479
+ result1 = await clean_worker.get_task_future(task_id1)
480
+
481
+ # Second execution with same args (should hit cache)
482
+ start_time = datetime.now()
483
+ task_id2 = await clean_worker.add_task(
484
+ test_computation,
485
+ value=3,
486
+ delay=0.01, # This delay won't happen due to cache
487
+ use_cache=True
488
+ )
489
+ result2 = await clean_worker.get_task_future(task_id2)
490
+ elapsed = (datetime.now() - start_time).total_seconds()
491
+
492
+ # Results should match
493
+ assert result1 == result2
494
+
495
+ # Second execution should be much faster (cache hit)
496
+ assert elapsed < 0.05 # Much less than the task delay
497
+
498
+ @pytest.mark.asyncio
499
+ async def test_concurrent_tasks(clean_worker):
500
+ """Test concurrent task execution."""
501
+ # Add multiple tasks
502
+ task_ids = []
503
+ for i in range(5):
504
+ task_id = await clean_worker.add_task(
505
+ test_computation,
506
+ value=i,
507
+ delay=0.01
508
+ )
509
+ task_ids.append(task_id)
510
+
511
+ # Wait for all to complete
512
+ futures = clean_worker.get_task_futures(task_ids)
513
+ results = await asyncio.gather(*futures)
514
+
515
+ # Verify all completed
516
+ assert len(results) == 5
517
+ for i, result in enumerate(results):
518
+ assert result == i * (2 ** 5)
519
+
520
+ # ============================================================
521
+ # Testing Utilities
522
+ # ============================================================
523
+
524
+ class TaskMonitor:
525
+ """Utility class for monitoring task execution in tests."""
526
+
527
+ def __init__(self, worker: AsyncTaskWorker):
528
+ self.worker = worker
529
+ self.events = []
530
+
531
+ async def monitor_task(self, task_id: str, timeout: float = 5.0):
532
+ """Monitor a task until completion or timeout."""
533
+ start_time = asyncio.get_event_loop().time()
534
+
535
+ while asyncio.get_event_loop().time() - start_time < timeout:
536
+ info = self.worker.get_task_info(task_id)
537
+ self.events.append({
538
+ "time": asyncio.get_event_loop().time() - start_time,
539
+ "status": info.status,
540
+ "progress": info.progress
541
+ })
542
+
543
+ if info.status not in ("pending", "running"):
544
+ return info
545
+
546
+ await asyncio.sleep(0.1)
547
+
548
+ raise TimeoutError(f"Task {task_id} did not complete within {timeout}s")
549
+
550
+ @pytest.mark.asyncio
551
+ async def test_with_monitor(clean_worker):
552
+ """Example of using the TaskMonitor utility."""
553
+ monitor = TaskMonitor(clean_worker)
554
+
555
+ task_id = await clean_worker.add_task(
556
+ test_computation,
557
+ value=5,
558
+ delay=0.1
559
+ )
560
+
561
+ # Monitor the task
562
+ final_info = await monitor.monitor_task(task_id)
563
+
564
+ # Check the monitoring captured progress
565
+ assert len(monitor.events) > 0
566
+ assert final_info.status == TaskStatus.COMPLETED
567
+
568
+ # Verify progress increased over time
569
+ progresses = [e["progress"] for e in monitor.events]
570
+ assert progresses[-1] == 1.0
571
+ ```
572
+
573
+ ### Testing with Database Libraries (e.g., psycopg-toolkit)
574
+
575
+ The same pattern applies when testing with async database libraries:
576
+
577
+ ```python
578
+ import pytest
579
+ import asyncio
580
+ from psycopg_toolkit import Database
581
+
582
+ @pytest.fixture(scope="session")
583
+ def db():
584
+ """Session-scoped database connection.
585
+
586
+ Uses asyncio.run() to handle async operations in sync fixture.
587
+ This is the standard pattern for pytest with async resources.
588
+ """
589
+ db = Database("postgresql://user:pass@localhost/test")
590
+
591
+ # Create the pool synchronously using asyncio.run()
592
+ asyncio.run(db.get_pool())
593
+
594
+ yield db
595
+
596
+ # Cleanup
597
+ asyncio.run(db.cleanup())
598
+
599
+ @pytest.fixture(scope="function")
600
+ async def db_connection(db):
601
+ """Function-scoped connection from the session pool."""
602
+ async with db.connection() as conn:
603
+ yield conn
604
+ # Automatic cleanup via context manager
605
+ ```
606
+
607
+ ### Key Takeaways
608
+
609
+ 1. **The `asyncio.run()` pattern is correct**: Don't feel bad about using it in session fixtures - it's the standard solution
610
+ 2. **Session vs Function Scope**: Use session fixtures for expensive resources (pools, workers) and function fixtures for cleanup
611
+ 3. **The awkwardness is pytest's limitation, not your design**: Your async library doesn't need sync wrappers
612
+ 4. **Document the pattern**: Help users understand why `asyncio.run()` appears in test fixtures
613
+
614
+ ### Additional Testing Resources
615
+
616
+ - **pytest-asyncio**: The standard pytest plugin for async testing
617
+ - **pytest-timeout**: Useful for preventing hanging async tests
618
+ - **asyncio-test**: Utilities for testing asyncio code
619
+ - **Testing async generators**: Use `async for` in tests or `aioitertools` for utilities
620
+
621
+ ### Common Pitfalls and Solutions
622
+
623
+ #### Pitfall 1: Event Loop Conflicts
624
+ ```python
625
+ # Wrong - Creates new event loop
626
+ def test_something():
627
+ loop = asyncio.new_event_loop()
628
+ loop.run_until_complete(my_async_func())
629
+
630
+ # Right - Use pytest-asyncio
631
+ @pytest.mark.asyncio
632
+ async def test_something():
633
+ await my_async_func()
634
+ ```
635
+
636
+ #### Pitfall 2: Forgetting Cleanup
637
+ ```python
638
+ # Wrong - No cleanup
639
+ @pytest.fixture
640
+ def worker():
641
+ w = AsyncTaskWorker()
642
+ asyncio.run(w.start())
643
+ return w
644
+
645
+ # Right - Proper cleanup
646
+ @pytest.fixture
647
+ def worker():
648
+ w = AsyncTaskWorker()
649
+ asyncio.run(w.start())
650
+ yield w
651
+ asyncio.run(w.stop())
652
+ ```
653
+
654
+ #### Pitfall 3: Mixing Sync and Async Incorrectly
655
+ ```python
656
+ # Wrong - Can't await in sync function
657
+ def test_task(worker):
658
+ result = await worker.add_task(...) # SyntaxError
659
+
660
+ # Right - Mark as async test
661
+ @pytest.mark.asyncio
662
+ async def test_task(worker):
663
+ result = await worker.add_task(...)
664
+ ```
665
+
666
+ By following these patterns, you can effectively test async-task-worker and similar async libraries while maintaining clean, efficient test suites.
667
+
668
+
669
+ ## Documentation
670
+
671
+ - [Database Management](docs/database.md)
672
+ - [Transaction Management](docs/transaction_manager.md)
673
+ - [Base Repository](docs/base_repository.md)
674
+ - [JSONB Support](docs/jsonb_support.md)
675
+ - [PsycopgHelper](docs/psycopg_helper.md)
676
+
677
+ ## Running Tests
678
+
679
+ ```bash
680
+ # Install dependencies
681
+ uv sync --all-groups
682
+
683
+ # Run all tests except performance tests (default)
684
+ uv run pytest
685
+
686
+ # Run only performance tests
687
+ uv run pytest -m performance
688
+
689
+ # Run all tests including performance
690
+ uv run pytest -m ""
691
+
692
+ # Run specific test categories
693
+ uv run pytest tests/unit/ # Only unit tests
694
+ uv run pytest -m performance # Only performance tests
695
+
696
+ # Run with coverage
697
+ uv run pytest --cov=src/psycopg_toolkit --cov-report=html
698
+ ```
699
+
700
+ ### Test Categories
701
+
702
+ The test suite is organized into three categories:
703
+
704
+ - **Unit tests**: Fast, isolated tests that don't require a database (in `tests/unit/`)
705
+ - **Integration tests**: Tests that require a real PostgreSQL database (in `tests/` root)
706
+ - **Performance tests**: Benchmarks and performance measurements (marked with `@pytest.mark.performance`)
707
+
708
+ Performance tests are excluded by default to keep the regular test runs fast. Use the `-m performance` flag to run them explicitly.
709
+
710
+ ## Contributing
711
+
712
+ 1. Fork the repository
713
+ 2. Create a feature branch
714
+ 3. Add tests for new features
715
+ 4. Ensure all tests pass
716
+ 5. Submit a pull request
717
+
718
+ ## License
719
+
720
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.