py.test:会话范围的临时文件夹

Thi*_*ter 17 python pytest

tmpdirpy.test中的夹具使用function示波器,因此在具有更广范围的夹具中不可用session.但是,这对于某些情况很有用,例如设置临时PostgreSQL服务器(当然不应该为每个测试重新创建).

是否有任何干净的方法来获得更广泛的范围的临时文件夹,不涉及编写我自己的夹具和访问py.test的内部API?

its*_*ire 24

由于pytest版本2.8及更高版本,会话范围的tmpdir_factory夹具可用.请参阅文档中的以下示例.

# contents of conftest.py
import pytest

@pytest.fixture(scope='session')
def image_file(tmpdir_factory):
    img = compute_expensive_image()
    fn = tmpdir_factory.mktemp('data').join('img.png')
    img.save(str(fn))
    return fn

# contents of test_image.py
def test_histogram(image_file):
    img = load_image(image_file)
    # compute and test histogram
Run Code Online (Sandbox Code Playgroud)


flu*_*lub 14

不幸的是,目前还没有办法做得很好.在未来,py.test将为此引入一个新的"任何"范围或类似的东西,但那是未来.

现在你必须自己手动完成.然而,正如你注意到你松散了一些不错的功能:/ tmp到最后一次测试的符号链接,几次测试运行后的自动清理,合理命名的目录等.如果目录不是太贵我通常会结合会话和功能范围的夹具以下列方式:

@pytest.fixture(scope='session')
def sessiondir(request):
    dir = py.path.local(tempfile.mkdtemp())
    request.addfinalizer(lambda: dir.remove(rec=1))
    # Any extra setup here
    return dir

@pytest.fixture
def dir(sessiondir, tmpdir):
    sessiondir.copy(tmpdir)
    return tmpdir
Run Code Online (Sandbox Code Playgroud)

这会创建一个临时目录,在测试运行后会对其进行清理,但对于实际需要它的每个测试(通过请求dir)都会获得一个使用tmpdir语义保存的副本.

如果测试实际上需要通过此目录共享状态,则终结器dir必须将事物复制回sessiondir.然而,这不是一个好主意,因为它使测试依赖于执行顺序,并且在使用pytest-xdist时也会导致问题.

  • 从 2.8 开始,情况不再如此。请参阅 /sf/answers/2663518301/。 (2认同)