pytest - 有没有办法忽略自动装置?

pytest - is there a way to ignore an autouse fixture?

我有这个 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()

我打算在这些测试中使用它,但我无法绕过上面的自动装置。

有没有办法以某种方式覆盖我们某些测试的自动夹具?我尝试过对每个测试使用 pytest.mark.usefixtures,但在每个测试中都使用该装饰器似乎并不理想。有人提到使用元类,但我还没有完全理解它们是如何工作的,所以我想知道是否还有其他我可能错过的方法。

有一种方法可以按需使用这些功能,而无需像下面这样使用 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):
 ...
 ...

-----更新最新版本的pytest----- 使用 request.node.get_closest_marker() 获取标记。参考 get_closest_marker


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

@pytest.fixture(autouse=True)
def browser(request):
    # _browser = request.node.get_marker('browser')
    _browser = request.node.get_closest_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