Function-scoped fixture with transaction rollback cleanup. Each test runs inside a transaction that gets rolled back at the end, providing isolation without the overhead of schema recreation. For databases that don't support transactions (e.g., MySQL MyISAM), falls back to tru
(db_module)
| 66 | |
| 67 | @pytest_asyncio.fixture(scope="function") |
| 68 | async def db(db_module): |
| 69 | """ |
| 70 | Function-scoped fixture with transaction rollback cleanup. |
| 71 | |
| 72 | Each test runs inside a transaction that gets rolled back at the end, |
| 73 | providing isolation without the overhead of schema recreation. |
| 74 | |
| 75 | For databases that don't support transactions (e.g., MySQL MyISAM), |
| 76 | falls back to truncation cleanup. |
| 77 | |
| 78 | This is the FASTEST isolation method - use for most tests. |
| 79 | |
| 80 | Usage: |
| 81 | @pytest.mark.asyncio |
| 82 | async def test_something(db): |
| 83 | obj = await Model.create(name="test") |
| 84 | assert obj.id is not None |
| 85 | # Changes are rolled back after test |
| 86 | """ |
| 87 | # Get connection from the context using its default connection |
| 88 | conn = db_module.db() |
| 89 | |
| 90 | # Check if the database supports transactions |
| 91 | if conn.capabilities.supports_transactions: |
| 92 | # Start a savepoint/transaction |
| 93 | transaction = conn._in_transaction() |
| 94 | await transaction.__aenter__() |
| 95 | |
| 96 | try: |
| 97 | yield db_module |
| 98 | finally: |
| 99 | # Rollback the transaction (discards all changes made during test) |
| 100 | class _RollbackException(Exception): |
| 101 | pass |
| 102 | |
| 103 | await transaction.__aexit__(_RollbackException, _RollbackException(), None) |
| 104 | else: |
| 105 | # For databases without transaction support (e.g., MyISAM), |
| 106 | # fall back to truncation cleanup |
| 107 | yield db_module |
| 108 | await _truncate_all_tables(db_module) |
| 109 | |
| 110 | |
| 111 | @pytest_asyncio.fixture(scope="function") |
nothing calls this directly
no test coverage detected