简体   繁体   English

整个测试套件的py.test SetUp / TearDown

[英]py.test SetUp/TearDown for whole test suite

I have a Python package that needs access to X11. 我有一个需要访问X11的Python包。 I want to use Xvfb so that I do not have to have a real X11 installed on the build machines -- Hudson in this case. 我想使用Xvfb,这样我就不必在构建机器上安装真正的X11 - 在这种情况下是Hudson。 So, I would like to start a Xvfb server when py.test starts, use that one server for all the tests, then close it down. 因此,我想在py.test启动时启动一个Xvfb服务器,使用该服务器进行所有测试,然后将其关闭。

How can I do that? 我怎样才能做到这一点?


Note : I could start(stop) an Xvfb server in the SetUp(TearDown) in each test class but that has two problem: First, it is wasteful. 注意 :我可以在每个测试类的SetUp(TearDown)中启动(停止)Xvfb服务器,但这有两个问题:首先,它是浪费的。 Second, it does not work due to either strange Fatal IO error 0 (Success) on X server if I terminate the server correctly or I get hanging Xvfb processes that do not die. 其次,如果我正确终止服务器或者我挂起了不死的Xvfb进程,那么由于Fatal IO error 0 (Success) on X server任何奇怪的Fatal IO error 0 (Success) on X server它都不起作用。 This is using xvfbwrapper if anyone is interested. 如果有兴趣的话,这是使用xvfbwrapper

You could use pytest-xvfb instead of messing with this… It would be easier. 你可以使用pytest-xvfb而不是弄乱这个......这会更容易。


It is actually fairly simple. 它实际上相当简单。 Create a file called conftest.py in your project root which contains this: 在项目根目录中创建一个名为conftest.py的文件,其中包含:

import pytest
import os
import subprocess
import tempfile

@pytest.fixture(scope="session", autouse=True)
def start_xvfb_server (request):
    tempdir = tempfile.mkdtemp()
    xvfb_cmd = ['Xvfb',
                ':1022',
                '-screen', '0', '800x600x24',
                '-fbdir', tempdir,
                '-noreset'
    ]
    xvfb_proc = subprocess.Popen(xvfb_cmd,
            stdout=open(os.devnull),
            stderr=open(os.devnull),
            shell=False
    )
    request.addfinalizer(xvfb_proc.kill)

Now, all you have to do is to set up each tests to set the DISPLAY to 1022 which is trivial to do. 现在,您所要做的就是设置每个测试以将DISPLAY设置为1022,这是微不足道的。

Alternatively, you can simply define setUpClass / tearDownClass methods, as described in the unittest module documentation: https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass 或者,您可以简单地定义setUpClass / tearDownClass方法,如unittest模块文档中所述: httpssetUpClass

Since py.test v2.4, they are fully supported. 从py.test v2.4开始,它们完全受支持。 This official documentation page also documents all xunit-style compatible methods: https://pytest.org/latest/xunit_setup.html 此官方文档页面还记录了所有xunit风格的兼容方法: https//pytest.org/latest/xunit_setup.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM