Skip to content

Document how to perform Live DB test support with savepointsΒ #6604

Open
@revmischa

Description

@revmischa

Problem

I don't have a good solution for writing unit tests for the queries I'm writing with Prisma. I would like to be able to write tests that run real queries, each in an isolated transaction.

Suggested solution

There is a very stable and awesome implementation of this for flask-SQLAlchemy - see https://pypi.org/project/pytest-flask-sqlalchemy/#motivation

The actual implementation in there is only about 20-30 lines of python: https://github.com/jeancochrane/pytest-flask-sqlalchemy/blob/master/pytest_flask_sqlalchemy/fixtures.py#L40

The approach is pretty simple. Create a test DB and run migrations if one doesn't exist already. Then for each test:

  • Begin a transaction
  • Intercept all new transaction calls to create a SAVEPOINT (a nested transaction) instead
  • At the end of the test, roll back the transaction

This is simple, elegant, fast, and works amazingly well. You can run tests in parallel and because they are all in uncommitted transactions they don't step on each others' toes. The actual state of the database is never affected.

Alternatives

Creating a database for each test?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions