微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 如何通过测试正确设置和拆除我的pytest类?

我正在使用selenium进行端到端测试,我无法获得如何使用setup_class和teardown_class方法.

我需要在setup_class方法中设置浏览器,然后执行一系列定义为类方法的测试,最后在teardown_class方法退出浏览器.

但从逻辑上讲,这似乎是一个糟糕的解决方案,因为实际上我的测试不是用于类,而是用于对象.我在每个测试方法中传递自我参数,所以我可以访问对象的变量:

class TestClass:

    def setup_class(cls):
        pass

    def test_buttons(self, data):
        # self.$attribute can be used, but not cls.$attribute?  
        pass

    def test_buttons2(self, data):
        # self.$attribute can be used, but not cls.$attribute?
        pass

    def teardown_class(cls):
        pass

甚至为类创建浏览器实例似乎也不正确..它应该分别为每个对象创建,对吧?

那么,我需要使用__init__和__del__方法而不是setup_class和teardown_class?

解决方法:

根据Fixture finalization / executing teardown code使用addfinalizer是“历史的”.

As historical note, another way to write teardown code is by accepting a request object into your fixture function and can call its request.addfinalizer one or multiple times:

设置和拆卸的当前最佳实践是使用产量

import pytest

@pytest.fixture()
def resource():
    print("setup")
    yield "resource"
    print("teardown")

class TestResource(object):
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

运行它会导致

$py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items

pytest_yield.py setup
testing resource
.teardown


=== 1 passed in 0.01 seconds ===

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐