0

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"""

我相信它的执行方式是:

  1. 正在使用第一个参数(table1)从设置中调用 create_table
  2. create_table 中的代码执行
  3. teardown_class 中的代码执行
  4. 上面的1-3用第二个参数再次执行
  5. 上面的1-3用第3个参数再次执行
  6. test_foo 中的代码执行

我期望它如何执行:

  1. 使用第一个参数 (table1) 调用 create_table
  2. create_table 中的代码执行
  3. 使用第二个参数调用 create_table(表 2)
  4. create_table 中的代码执行
  5. 使用第三个参数调用 create_table(表 3)
  6. create_table 中的代码执行
  7. test_foo 中的代码执行
  8. teardown_class 中的代码执行

Python 2.7.10、pytest-3.6.2、py-1.5.3、pluggy-0.6.0

4

2 回答 2

1

您的 classmethod 错过了 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

对我来说似乎也很好。。

对于您的假设,您是否有更多提示?

于 2018-06-27T20:18:14.000 回答
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"""

现在它按照我的预期运行,按以下顺序:

  1. create_table为 table1 参数运行一次
  2. create_table为 table2 参数运行一次
  3. create_table为 table3 参数运行一次
  4. test_foo
  5. teardown_class

似乎每次/每次setup调用外部函数时setup,都会导致teardown函数在外部函数中的代码运行后直接运行,这就是我面临的问题。

于 2018-06-28T18:21:03.903 回答