如何使用测试正确设置和拆卸我的 pytest 类? [英] How do I correctly setup and teardown for my pytest class with tests?
问题描述
我使用 selenium 进行端到端测试,但我不知道如何使用 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
参数,所以我可以访问对象的变量:
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
?
推荐答案
根据 Fixture 终结/执行拆卸代码,目前设置和拆卸的最佳实践是使用 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 ===
另一种编写拆卸代码的方法是接受一个请求
-context object 进入你的夹具函数,并使用一个执行一次或多次拆卸的函数调用它的 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屋!