Rolling back database transactions in SQLAlchemy tests with PostgreSQL

天大地大妈咪最大 提交于 2019-12-04 15:49:45
Sergey

Since this question is a bit similar to your other question, I'll copy the relevant part of my answer here:

All test case classes should be subclassed from a base class, which defines a common 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()

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

PGTEMP=`mktemp -d /dev/shm/pgtemp.XXXXXX`
initdb -D "$PGTEMP"
postgres -D "$PGTEMP" -k "$PGTEMP" -p 54321
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!