Python PyTest teardown_类运行得太快
Python“teardown_类”的行为与我预期的不同。以下是我的代码摘要:Python PyTest teardown_类运行得太快,python,google-bigquery,pytest,teardown,Python,Google Bigquery,Pytest,Teardown,Python“teardown_类”的行为与我预期的不同。以下是我的代码摘要: @classmethod def setup_class(cls): cls.create_table(table1) cls.create_table(table2) cls.create_table(table3) @classmethod def create_table(cls, some_arg_here): """Some code here that creates t
@classmethod
def setup_class(cls):
cls.create_table(table1)
cls.create_table(table2)
cls.create_table(table3)
@classmethod
def create_table(cls, some_arg_here):
"""Some code here that creates the table"""
def test_foo(self):
"""Some test code here"""
@classmethod
def teardown_class(cls):
"""Perform teardown things"""
我认为它的执行方式是:
Python2.7.10、pytest-3.6.2、py-1.5.3、pluggy-0.6.0
@classmethod
def create_table(some_arg_here):
"""Some code here that creates the table"""
换成
@classmethod
def create_table(cls, some_arg_here):
我修改了您的代码并添加了一些打印:
class TestClass:
@classmethod
def setup_class(cls):
print("Setting up")
cls.create_table('table1')
cls.create_table('table2')
cls.create_table('table3')
@classmethod
def create_table(cls, some_arg_here):
print("Creating:", some_arg_here)
"""Some code here that creates the table"""
def test_foo(self):
print('Running test_foo')
"""Some test code here"""
@classmethod
def teardown_class(cls):
print("Tearing down")
"""Perform teardown things"""
如果使用-s运行,将得到以下结果:
test.py Setting up
Creating: table1
Creating: table2
Creating: table3
Running test_foo
.Tearing down
正如您所看到的,一切都按预期进行。调用setup_类,创建表(全部3个),运行测试方法,然后启动teardown_类
如果添加一个函数test_bar(),您将得到:
test.py Setting up
Creating: table1
Creating: table2
Creating: table3
Running test_foo
.Running test_bar
.Tearing down
对我来说似乎也很好
对于你的假设,你还有什么提示吗?我找到了解决办法。我将
create_table
函数重新创建为内部函数,位于设置
函数内部
@classmethod
def setup_class(cls):
def create_table(some_arg_here):
"""Some code here that creates the table"""
create_table(table1)
create_table(table2)
create_table(table3)
def test_foo(self):
"""Some test code here"""
@classmethod
def teardown_class(cls):
"""Perform teardown things"""
现在,它按照我预期的顺序运行:
create_table
create_table
create_table
test\u foo
teardown\u类
似乎每次从
setup
调用setup
之外的函数时,都会导致teardown
函数在外部函数中的代码运行后直接运行,这就是我所面临的问题 我发现当我从setup方法调用另一个方法时,问题就出现了。如果我将create_table中的代码直接放入setup方法中,它会按预期工作:setup方法中的所有代码都会运行,然后是测试,然后是拆卸。但如果我从安装程序调用create_table(多次),那么每次调用之后,它都会运行teardown。这真的是预期的表现吗?如果是这样,我需要一个解决办法。。。