TestTx starts a test transaction that's rolled back automatically as the test case is cleaning itself up. The function invokes TestSchema to create a single schema where this test transaction and all future test transactions for this package test run will run. `search_path` is set to the name of t
(ctx context.Context, tb testing.TB, driver riverdriver.Driver[TTx], opts *TestTxOpts)
| 534 | // The included driver determines what migrations are run to prepare the test |
| 535 | // transaction schema. |
| 536 | func TestTx[TTx any](ctx context.Context, tb testing.TB, driver riverdriver.Driver[TTx], opts *TestTxOpts) (TTx, string) { |
| 537 | tb.Helper() |
| 538 | |
| 539 | schema := testTxSchemaForDatabaseAndMigrationLines(ctx, tb, driver, opts) |
| 540 | tb.Logf("TestTx using %s schema: %s", driver.DatabaseName(), schema) |
| 541 | |
| 542 | execTx, err := driver.GetExecutor().Begin(ctx) |
| 543 | require.NoError(tb, err) |
| 544 | |
| 545 | tb.Cleanup(func() { |
| 546 | // Tests may inerit context from `t.Context()` which is cancelled after |
| 547 | // tests run and before calling clean up. We need a non-cancelled |
| 548 | // context to issue rollback here, so use a bit of a bludgeon to do so |
| 549 | // with `context.WithoutCancel()`. |
| 550 | ctx := context.WithoutCancel(ctx) |
| 551 | |
| 552 | err := execTx.Rollback(ctx) |
| 553 | |
| 554 | if err == nil { |
| 555 | return |
| 556 | } |
| 557 | |
| 558 | // Try to look for an error on rollback because it does occasionally |
| 559 | // reveal a real problem in the way a test is written. However, allow |
| 560 | // tests to roll back their transaction early if they like, so ignore |
| 561 | // `ErrTxClosed`. |
| 562 | if errors.Is(err, pgx.ErrTxClosed) { |
| 563 | return |
| 564 | } |
| 565 | |
| 566 | // In case of a cancelled context during a database operation, which |
| 567 | // happens in many tests, pgx seems to not only roll back the |
| 568 | // transaction, but closes the connection, and returns this error on |
| 569 | // rollback. Allow this error since it's hard to prevent it in our flows |
| 570 | // that use contexts heavily. |
| 571 | if err.Error() == "conn closed" { |
| 572 | return |
| 573 | } |
| 574 | |
| 575 | // Cancelled context again, but this one from libpq. |
| 576 | if err.Error() == "driver: bad connection" { |
| 577 | return |
| 578 | } |
| 579 | |
| 580 | // Similar to the above, but a newly appeared error that wraps the |
| 581 | // above. As far as I can tell, no error variables are available to use |
| 582 | // with `errors.Is`. |
| 583 | if err.Error() == "failed to deallocate cached statement(s): conn closed" { |
| 584 | return |
| 585 | } |
| 586 | |
| 587 | require.NoError(tb, err) |
| 588 | }) |
| 589 | |
| 590 | return driver.UnwrapTx(execTx), schema |
| 591 | } |
| 592 | |
| 593 | var ( |
no test coverage detected
searching dependent graphs…