py.test方法每次运行只执行一次

时间:2016-05-08 13:39:30

标签: python python-2.7 pytest

我是pytest(和python)的新手。在我的所有测试之前只有一次要执行的事情(例如: - 启动android模拟器,创建appium驱动程序,实例化我的所有页面类,以便我可以在测试中使用它们)。顺便说一句,我在多个班级都有我的考试。经过一段时间的阅读后,我认为@pytest.yield_fixture(scope="session", autouse=True)可以做到这一点......但那不是我看到的......请看下面的例子..

import pytest

class TestBase():
    @pytest.yield_fixture(scope="session", autouse=True)
    def fixture_session(self):
        # start emulator, create driver and instantiate all page
        # classes with driver create above
        print "\n in fixture_session! @session "   
        yield
        # tear down
        print "in fixture_session after yield @session"
    @pytest.yield_fixture(scope="module", autouse=True)
    def fixture_module(request):
        print 'in fixture_module @module'
        # tear down
        yield
        print "in fixture_module after yield @module"

class TestOne(TestBase):
    def test_a(self):
        # write test with page objects created in TestBase
        print "in test_a of TestOne"  
    def test_b(self):
        print "in test_b of TestOne"

class TestTwo(TestBase):
    def test_a(self):
        print "in test_a of TestTwo"

    def test_b(self):
        print "in test_b of TestTwo"

运行此功能

test_base.py
 in fixture_session! @session
in fixture_module @module
in test_a of TestOne
.in test_b of TestOne
.
 in fixture_session! @session
in fixture_module @module
in test_a of TestTwo
.in test_b of TestTwo
.in fixture_module after yield @module
in fixture_module after yield @module
in fixture_session after yield @session
in fixture_session after yield @session

我错过了什么?为什么每个测试类执行@pytest.yield_fixture(scope="session", autouse=True)以及为什么在完成测试运行后会发生拆除?总而言之,这是在Pytest中设置测试框架的正确方法吗?

1 个答案:

答案 0 :(得分:0)

这是因为您在类中定义了灯具然后将其子类化,导致灯具被定义两次。

相反,您应该将fixture定义为普通函数,并将测试更改为函数,或者如果要使用类进行分组测试,则不要从任何基类继承。

相关问题