我正在构建一个构建在sqlAlchemy顶部的Pyramid Web应用程序,并且只依赖Postgresql作为其数据库后端.
什么是单元测试结构的方法
>每次测试运行时都会构建一次数据库 – 而不是每个测试setUp(),因为这对于复杂的应用程序来说太慢了
>(重新)创建数据库表,因为它们将在生产中创建(例如,从Alembic运行迁移).任何不干净的数据库都会在测试运行开始时被销毁.
>如果标准库unittest框架之外的特定功能使编写测试用例更容易,则可以选择自定义测试运行程序.
解决方法:
Nose测试运行器支持setup_package()和teardown_package()方法.以下是文档的摘录:
07001
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.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(),它看起来大致如下:
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方法:
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 – 通过回滚事务,它确保下一个测试将在完全干净的数据库上启动.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。