Python 事务管理器还原/回滚上次提交
我试图通过将测试数据从测试用例Python 事务管理器还原/回滚上次提交,python,sqlalchemy,pyramid,Python,Sqlalchemy,Pyramid,我试图通过将测试数据从测试用例setUp()放入setUpClass()/teardownClassclass方法来加速测试,因此它不会为测试用例中的每个测试重新创建相同的仅选择夹具 @classmethod def setUpClass(cls): plant.StuffFactory() #plant stuff with FactoryBoy transaction.commit() @classmethod def tearDownClass(cls): ses
setUp()
放入setUpClass()/teardownClass
class方法来加速测试,因此它不会为测试用例中的每个测试重新创建相同的仅选择夹具
@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()
,就像我没有植入任何东西一样
我尝试使用嵌套事务和保存点,但它们仅在数据尚未提交时才起作用
有任何指针吗?在setUpClass()
中,您可以将保存点创建为:
sp = transaction.savepoint()
然后在tearDownClass()
中,您可以简单地使用:
sp.rollback()
希望这对您有所帮助。如果您不希望提交内容,请不要调用
transaction.commit()
:)
这将要求您的测试代码中没有一个执行显式事务管理(
transaction.commit()
\transaction.rollback()
,在应用程序代码中),但这无论如何都是一种不好的做法 你看,sp
将在事务处理后变得无效。commit()
,因此如果我尝试执行sp.rollback()
它将抛出InvalidSavepointRollbackError:InvalidSavePoint被稍后的保存点失效
,可能是事务。commit()
创建新的保存点,但是如何重新获取它呢?我需要回滚到预提交状态,然后再进行所有植入。您可以将其声明为类变量我知道的用法,如cls.sp
请尝试以下操作:sp=transaction.savepoint();commit();sp.回滚()
@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()