简体   繁体   English

使用PostgreSQL在SQLAlchemy测试中回滚数据库事务

[英]Rolling back database transactions in SQLAlchemy tests with PostgreSQL

I am building a Pyramid web application which is built on the top of SQLAlchemy and solely relies PostgreSQL as its database backend. 我正在构建一个Pyramid Web应用程序,该应用程序建立在SQLAlchemy的顶部,并且仅依赖PostgreSQL作为其数据库后端。

What would be a way to have the unit tests structure so that 什么是具有单元测试结构的方法,以便

  • To speed up tests, database transactions are rolled back at the teardown() , or other clean up hook of the test suite 为了加快测试速度,数据库事务会在teardown()或测试套件的其他清理钩子上回滚。

  • Other tricks to speed up tests could be used, eg if SQLAlchemy and PostgreSQL has anything corresponding SQLite's :in:memory: database 可以使用其他加快测试速度的技巧,例如,如果SQLAlchemy和PostgreSQL具有与SQLite相对应的:in:memory:数据库,

  • It is possible to choose a custom test runner á la py.test if a specific features outside the standard library unittest framework makes it easier to write test cases. 如果标准库unittest框架之外的特定功能使编写测试用例更加容易,则可以选择自定义测试运行器py.test

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: 所有测试用例类都应从基类的子类中定义,该基类定义了通用的tearDown方法:

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). 对于测试,您可以在RAMdisk上初始化PostgreSQL数据目录(可以在/dev/shm/下创建一个目录,该目录在现代Linux发行版中作为tmpfs挂载)。 The you can run Postgres on non-standard port. 您可以在非标准端口上运行Postgres。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM