Rollback database transactions in SQLAlchemy tests using PostgreSQL

I am creating a Pyramid web application that is built on top of SQLAlchemy and uses only PostgreSQL as the database.

What is the way to have a unit test structure so that

  • To speed up the tests, database transactions will be rolled back on teardown()or another cleaning of the test package

  • You can use other ways to speed up tests, for example. if SQLAlchemy and PostgreSQL have any corresponding SQLite :in:memory:database

  • You can choose your own á la test runner py.testif specific functions outside the unittest framework make it easier to write test cases.

+1
source share
2 answers

Since this question is a bit like your other question , I will copy the corresponding part of my answer here:

All test classes must be subclassed from the base class, which defines the general tearDown method:

class BaseTest(unittest.TestCase):

    def setUp(self):
        # This makes things nicer if the previous test fails
        # - without this all subsequent tests fail
        self.tearDown()

        self.config = testing.setUp()

    def tearDown(self):
        testing.tearDown()
        session.expunge_all()
        session.rollback()
+1
source

For tests, you can initialize the PostgreSQL data directory in RAMdisk (you can create a directory under /dev/shm/, which is installed as tmpfsin modern Linux distributions). You can run Postgres on a non-standard port.

PGTEMP=`mktemp -d /dev/shm/pgtemp.XXXXXX`
initdb -D "$PGTEMP"
postgres -D "$PGTEMP" -k "$PGTEMP" -p 54321
+1
source

All Articles