PyTest teardown_class 运行得太快了 [英] PyTest teardown_class is being run too soon
问题描述
Pythonteardown_class"的行为不像我期望的那样.以下是我的代码摘要:
The Python "teardown_class" is not behaving as I expect it to. Below is a summary of my code:
@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"""
我相信它的执行方式是:
- create_table 正在使用第一个参数 (table1) 从设置中调用
- create_table 中的代码执行
- teardown_class 中的代码执行
- 使用第二个参数再次执行上面的 1-3
- 使用第三个参数再次执行上面的 1-3
- test_foo 中的代码执行
我期望它的表现:
- create_table 使用第一个参数 (table1) 调用
- create_table 中的代码执行
- create_table 使用第二个参数(表 2)调用
- create_table 中的代码执行
- create_table 使用第三个参数(表 3)调用
- create_table 中的代码执行
- test_foo 中的代码执行
- teardown_class 中的代码执行
Python 2.7.10、pytest-3.6.2、py-1.5.3、pluggy-0.6.0
Python 2.7.10, pytest-3.6.2, py-1.5.3, pluggy-0.6.0
推荐答案
我找到了解决方案.我在 setup
函数内部重新创建了 create_table
函数作为 inner 函数.
I was able to find the solution. I recreated the create_table
function as an inner function, inside of the setup
function.
@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"""
现在它按照我的预期运行,按以下顺序:
And now it runs as I expect it to, in this sequence:
- 为 table1 参数运行一次
create_table
- 为 table2 参数运行一次
create_table
- 为 table3 参数运行一次
create_table
- 运行
test_foo
- 运行
teardown_class
似乎任何/每次从 setup
调用 setup
之外的函数时,都会导致 teardown
函数运行直接在外部函数中的代码运行之后,这就是我面临的问题.
It seems that any/every time a function that is outside of setup
is called from setup
, it causes the teardown
function to run directly after the code in the outer function runs, and that was the issue I was facing.
这篇关于PyTest teardown_class 运行得太快了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!