仅当文件夹尚不存在时,如何在 pytest 和 运行 方法中检查文件夹的创建?

How to check creation of folders in pytest and run method only if the folders don't already exist?

我有创建以下文件夹结构的装置:

-test-output
  -folder1
  -folder2
  -folder3
@pytest.fixture(scope="module", autouse=True)
def set_up():  
    root_path = os.getcwd()
    folders = ['folder1', 'folder2', 'folder3']

    os.mkdir(os.path.join(root_path, 'test-output'))

    for folder in folders:
        os.mkdir(os.path.join(root_path, 'test-output', folder))


def test_folders(set_up):
    print('created folders')

我如何才能 运行 创建目录,只有在之前没有创建过目录的情况下?到目前为止,方法 运行s 每次我 运行 test_folders 方法,并触发错误: FileExistsError: [WinError 183] Cannot create a file when that file already exists 如果目录 fixture 已经存在,如何不 运行 创建它们?

因为你是 运行 这个 fixture 作为 autouse=Truescope="module",我建议用一些 if/else 将函数包装在一个 try 语句中检查文件夹。

查看下面我的代码:

@pytest.fixture(scope="module", autouse=True)
def set_up():
    try:
        root_path = os.getcwd()
        folders = ['folder1', 'folder2', 'folder3']
        if os.path.isdir(os.path.join(root_path, 'test-output')):
            pass
        else:
            os.mkdir(os.path.join(root_path, 'test-output'))

        for folder in folders:
            if os.path.isdir(os.path.join(root_path, 'test-output', folder)):
                pass
            else:
                os.mkdir(os.path.join(root_path, 'test-output', folder))
    except FileExistsError as e:
        print(f'File does exist: {e}')
        pass


def test_folders(set_up):
    print('created folders')

可以在创建的最后加上yield。在 yield 之后你可以删除“test-output”文件夹。

import os.path
import pytest
import shutil


@pytest.fixture(scope="module", autouse=True)
def set_up():
    print("setup")
    root_path = os.getcwd()
    folders = ['folder1', 'folder2', 'folder3']

    output_folder = os.path.join(root_path, 'test-output')
    os.mkdir(output_folder)

    for folder in folders:
        os.mkdir(os.path.join(root_path, 'test-output', folder))

    yield output_folder
    shutil.rmtree(output_folder)


def test_folders(set_up):
    print('created folders')


def test_folders1(set_up):
    print('created folders1')


def test_folders2(set_up):
    print('created folders2')