pytest - 有没有办法忽略一个autouse夹具?

时间:2016-09-18 14:36:36

标签: selenium selenium-webdriver pytest fixtures

我有这个autouse fixture,它将为每个测试创建一个webdriver实例:

@pytest.fixture(autouse=True)
def use_phantomjs(self):
    self.wd = webdriver.PhantomJS()
    yield
    self.close_wd()

但是,由于我们的某个API存在错误,我们的某些测试无法在PhantomJS上运行。这些测试只能在Chrome(或Firefox)上运行,因此我使用Chrome为webdriver实例创建了另一种方法:

def use_chrome(self):
    self.wd = webdriver.Chrome()

我计划在那些测试中使用,但我无法绕过上面的autouse灯具。

有没有办法以某种方式覆盖我们的一些测试的autouse灯具?我已经尝试过对每个测试使用pytest.mark.usefixtures但是看起来不太理想,必须在每个测试中放置装饰器。有人提到使用元类,但我还没有完全理解它们是如何工作的,所以我想知道是否还有其他方法可能会错过。

2 个答案:

答案 0 :(得分:4)

您可以通过多种方式实现此目的,一种方法是使用请求夹具以及pytest标记修复。 您需要做的就是创建一个新的通用夹具

@pytest.fixture(autouse=True)
def browser(request):
    _browser = request.node.get_marker('browser')
    if _browser:
       if _browser.kwargs.get("use") == "chrome" :
            # Do chrome related setup
       elif _browser.kwargs.get("use") == "phantom" :
            # Do Phantom.js related setup
   else:
       # No mark up ,use default setup

并按此标记您的测试

@pytest.mark.browser(use="chrome")
def test_some_chrome_test():
    # browser here would return chrome driver

@pytest.mark.browser(use="phantom")
def test_some_phantomjs_test():
    # browser here would return phantom driver

答案 1 :(得分:0)

有一种方法可以按需使用这些功能而无需使用下面的usefixtures装饰器。 如果您已经使用autouse=True,那么它将根据其范围自动调用,我认为在任何测试中都没有办法跳过它。

@pytest.fixture(autouse=False)
def use_phantomjs(self):
    self.wd = webdriver.PhantomJS()
    yield
    self.close_wd()

def test_my_test(use_phantomjs):
 ...
 ...
相关问题