当依赖项不可用时跳过 Python 测试

Skipping Python test when dependency not available

我正在研究一个 Python 2.7 项目,但并不真正熟悉 Python。没有安装 Firefox 时有一个测试失败,因为它使用使用 Firefox 的 selenium。我希望测试在不能 运行.

时自动跳过

测试class

class SeleniumAuthTestCase(SeleniumTestCase):

我遇到的错误

Traceback (most recent call last):
  File "/mnt/vagrant/source/some/path/tests/selenium/test_auth.py", line 14, in setUpClass
    super(cls, cls).setUpClass()
  File "/mnt/vagrant/source/some/path/testcases.py", line 14, in setUpClass
    cls.driver = Firefox()
  File "/some/path/venv/local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 55, in __init__
    self.binary = firefox_binary or capabilities.get("binary", FirefoxBinary())
  File "/some/path/venv/local/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 47, in __init__
    self._start_cmd = self._get_firefox_start_cmd()
  File "/some/path/venv/local/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 163, in _get_firefox_start_cmd
    " Please specify the firefox binary location or install firefox")
RuntimeError: Could not find firefox in your system PATH. Please specify the firefox binary location or install firefox

我发现有一种方法可以让 individual test methods skipped via annotation。然而,这里的错误发生在任何测试方法被调用之前:in setUpClass in parent class。

我还发现我可以重载方法:

@classmethod
def setUpClass(cls):
    super(SeleniumAuthTestCase, cls).setUpClass()

所以我可以在那里检查是否加载了依赖项,如果没有加载,则避免调用父项 class。最重要的是,我可以设置一些标志来指示该东西是否已加载,然后为每个检查它的方法添加一个注释。虽然这很笨拙,但我更想做一些像这样的 PHPUnit 代码:

public function setUp() {
    if ( true ) {
        $this->markTestSkipped();
    }
}

这在 Python 中通常是如何完成的?

approach that sbarzowski linked 对我有用。

@classmethod
def setUpClass(cls):
    try:
        Firefox()
    except:
        raise unittest.SkipTest("Selenium webdriver needs Firefox, which is not available")

    super(SeleniumAuthTestCase, cls).setUpClass()