如何为带有测试的pytest类正确设置和拆卸? [英] How do I correctly setup and teardown for my pytest class with tests?
问题描述
我正在使用硒进行端到端测试,但无法了解如何使用 setup_class
和 teardown_class
方法。
I am using selenium for end to end testing and I can't get how to use setup_class
and teardown_class
methods.
我需要在 setup_class
方法中设置浏览器,然后执行一堆定义为类方法的测试,最后退出浏览器在 teardown_class
方法中。
I need to set up browser in setup_class
method, then perform a bunch of tests defined as class methods and finally quit browser in teardown_class
method.
但是从逻辑上讲,这似乎是一个糟糕的解决方案,因为实际上我的测试不适用于类,但可以用于目的。我在每个测试方法中都传递了 self
参数,因此我可以访问对象的vars:
But logically it seems like a bad solution, because in fact my tests will not work with class, but with object. I pass self
param inside every test method, so I can access objects' vars:
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
甚至为类创建浏览器实例似乎也不正确。应该为每个对象分别创建,对吧?
And it even seems not to be correct to create browser instance for class.. It should be created for every object separately, right?
因此,我需要使用 __ init __
和 __ del __
方法,而不是 setup_class
和 teardown_class
?
So, I need to use __init__
and __del__
methods instead of setup_class
and teardown_class
?
推荐答案
根据修复最终版本/执行拆卸代码,当前最佳的设置和拆卸方法是使用 yield
而不是 return
:
According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield
instead of return
:
import pytest
@pytest.fixture()
def resource():
print("setup")
yield "resource"
print("teardown")
class TestResource:
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 ===
另一种编写拆卸代码的方法是接受 请求
-上下文对象进入Fixture函数,并使用执行一次或多次拆卸的函数调用其 request.addfinalizer
方法:
Another way to write teardown code is by accepting a request
-context object into your fixture function and calling its request.addfinalizer
method with a function that performs the teardown one or multiple times:
import pytest
@pytest.fixture()
def resource(request):
print("setup")
def teardown():
print("teardown")
request.addfinalizer(teardown)
return "resource"
class TestResource:
def test_that_depends_on_resource(self, resource):
print("testing {}".format(resource))
这篇关于如何为带有测试的pytest类正确设置和拆卸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!