Python“ teardown_class”的行为不符合我的预期。以下是我的代码摘要:
@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"""
Python 2.7.10,pytest-3.6.2,py-1.5.3,pluggy-0.6.0
答案 0 :(得分:1)
您的课堂方法错过了cls参数:
@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_class,创建表(共3个),运行测试方法,然后启动teardown_class。
如果添加函数test_bar(),则会得到:
test.py Setting up
Creating: table1
Creating: table2
Creating: table3
Running test_foo
.Running test_bar
.Tearing down
似乎对我也没问题。
您是否有其他提示来做些假设?
答案 1 :(得分:0)
我能够找到解决方案。我在create_table
函数内部将setup
函数重新创建为内部函数。
@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_foo
teardown_class
似乎每次setup
调用setup
之外的函数时,都会导致teardown
函数在之后直接运行外部函数中的代码运行,这就是我面临的问题。