Search code examples
pythontestingdirectorypytestfixtures

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


I have this fixture that creates the following folder structure:

-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')

How can I run the creation of directories, only when they haven't been created before? So far, the method runs everytime I run the test_folders method, and triggers the error: FileExistsError: [WinError 183] Cannot create a file when that file already exists How not to run the creation of directories fixture if they are already present?


Solution

  • Because you are running this fixture as autouse=True and with scope="module", I would recommend wrapping the function in a try statement with a few if/else's to check for the folders.

    See my code below:

    @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')