我试图通过将测试数据从测试用例setUp()
放到setUpClass()/teardownClass
类方法中来加速我的测试,因此它不会为测试用例中的每个测试重新创建相同的选择夹具。
@classmethod
def setUpClass(cls):
plant.StuffFactory() #plant stuff with FactoryBoy
transaction.commit()
@classmethod
def tearDownClass(cls):
session.query(models.Stuff).delete() # delete planted stuff
transaction.commit()
但我不喜欢自己删除session.delete的东西,因为我使用了许多模型,不想跟踪我种植的东西。我想要像这样的
@classmethod
def tearDownClass(cls):
session.clear() #delete all
transaction.commit()
但是session.close()
或session.remove()
不会影响提交的数据。所以我想办法“取消”setUpClass
transaction.commit()
,就像我什么都不种植一样。
我尝试嵌套事务和保存点,但同样,只有当数据尚未提交时,它们才能工作。
有什么指示吗?
发布于 2014-07-30 12:01:06
如果您不希望事情被提交,就不要调用transaction.commit()
:)
@classmethod
def setUpClass(cls):
plant.StuffFactory() #plant stuff with FactoryBoy
# you may possibly want to flush the session, so everything has proper IDs etc.
DBSession.flush()
# let the transaction continue for the duration of the test
@classmethod
def tearDownClass(cls):
# let the database make everything as if nothing happened
transaction.rollback()
这将要求测试中的代码中没有任何代码进行显式事务管理(应用程序代码中的transaction.commit()
\ transaction.rollback()
),但无论如何,这是一个不好的做法:
作为一般规则,应用程序应该将会话的生命周期从外部管理到处理特定数据的函数。这是一种基本的关注点分离,使特定于数据的操作不知道他们访问和操作数据的上下文。
会话基础,SQLAlchemy文档(basics.html)
发布于 2014-07-30 01:54:50
在setUpClass()
中,您可以创建一个保存点如下:
sp = transaction.savepoint()
然后,在tearDownClass()
中,您可以简单地使用:
sp.rollback()
希望这能有所帮助。
https://stackoverflow.com/questions/25032638
复制