使用PostgreSQL在SQLAlchemy测试中创建数据库 [英] Creating databases in SQLAlchemy tests with PostgreSQL

查看:218
本文介绍了使用PostgreSQL在SQLAlchemy测试中创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Pyramid Web应用程序,该应用程序建立在SQLAlchemy的顶部,并且仅将PostgreSQL作为其数据库后端。

I am building a Pyramid web application which is built on the top of SQLAlchemy and solely relies PostgreSQL as its database backend.

单元测试结构,这样


  • 数据库每次测试运行一次,而不是每次测试 setUp( ),因为这对于复杂的应用程序来说太慢了

  • Database is built once per test run - not on every test setUp() as this is too slow for a complex application

数据库表的创建(重新)过程与在生产环境中创建数据库表一样(例如从Alembic运行迁移)。在测试开始时,所有不干净的数据库都会被销毁。

Database tables are (re)created as they would be created in production (e.g. run migrations from Alembic). Any unclean databases are destroyed at the start of the test run.

可以选择自定义测试运行器ala py。测试,如果标准库unittest框架之外的特定功能使其更容易编写测试用例。

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.

推荐答案

Nose 测试运行程序支持 setup_package() teardown_package()方法。以下是这些文档的摘录:

Nose test runner supports setup_package() and teardown_package() methods. Here's an excerpt from the docs:


测试包

nose允许将测试分组为测试包。这允许
包级别的设置;例如,如果您需要为测试创建测试
数据库或其他数据夹具,则可以在
软件包设置中创建它,并在每次测试运行一次的软件包拆解中将其删除,而宁可使用

nose allows tests to be grouped into test packages. This allows package-level setup; for instance, if you need to create a test database or other data fixture for your tests, you may create it in package setup and remove it in package teardown once per test run, rather than having to create and tear it down once per test module or test case.

要创建包级安装和拆卸方法,请定义安装
和/或拆解功能位于测试包的 init .py中。设置
方法可以命名为setup,setup_package,setUp或setUpPackage;
拆解可以命名为teardown,teardown_package,tearDown或
tearDownPackage。在从测试包中加载第一个测试模块开始
开始执行测试包中的测试。

To create package-level setup and teardown methods, define setup and/or teardown functions in the init.py of a test package. Setup methods may be named setup, setup_package, setUp, or setUpPackage; teardown may be named teardown, teardown_package, tearDown or tearDownPackage. Execution of tests in a test package begins as soon as the first test module is loaded from the test package.

我的应用程序中有 setup_package(),其外观大致如下:

In my application I have setup_package() which looks roughly like the following:

def _create_database():

    template_engine = sa.create_engine("postgres://postgres@/postgres", echo=False)

    conn = template_engine.connect()
    conn = conn.execution_options(autocommit=False)
    conn.execute("ROLLBACK")
    try:
        conn.execute("DROP DATABASE %s" % DB_NAME)
    except sa.exc.ProgrammingError as e:
        # Could not drop the database, probably does not exist
        conn.execute("ROLLBACK")
    except sa.exc.OperationalError as e:
        # Could not drop database because it's being accessed by other users (psql prompt open?)
        conn.execute("ROLLBACK")

    conn.execute("CREATE DATABASE %s" % DB_NAME)
    conn.close()

    template_engine.dispose()


def setup_package():
    _create_database()

    engine = sa.create_engine("postgres://postgres@/%s" % DB_NAME, echo=False)

    session = sa.orm.scoped_session(sa.orm.sessionmaker())
    session.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all()


def teardown_package():
    # no need to do anything as the old database is dropped at the start of every run

此外,所有测试用例类都从基类中继承,该基类重要地定义了常见的 tearDown 方法:

In addition, all test case classes are subclassed from a base class, which, importantly, 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()

子类通常会覆盖基础 setUp ,但通常无需覆盖 tearDown -通过回滚事务来确保下一次测试将在完全干净的数据库上开始。

Subclasses often override base setUp, but there usually no need to override tearDown - by rolling back the transaction it ensures that the next test will start on a completely clean database.

这篇关于使用PostgreSQL在SQLAlchemy测试中创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆