Skip to content
Advertisement

Pytest create multiple files with tmp_path fixture

I have a simple function which counts the files in a directory.

def count_files(path):
    return len(os.listdir(path))

I want to test this the following way. This works, but is of course very repetetive:

def test_count_files(tmp_path):
    f1 = tmp_path / "hello1.txt"
    f1.touch()
    f2 = tmp_path / "hello2.txt"
    f2.touch()
    f3 = tmp_path / "hello3.txt"
    f3.touch()
    f4 = tmp_path / "hello4.txt"
    f4.touch()
    assert count_files(tmp_path) == 4

Is there an easier way to write this?

Desired:

def test_count_files(tmp_path):
    f1 = tmp_path / ["hello1.txt", "hello2.txt", "hello3.txt"]
    f1.touch()
    assert count_files(tmp_path) == 3

Advertisement

Answer

Try just a simple for loop like

n_files = 4
for i in range(n_files):
    (tmp_path / f"hello{i}.txt").touch()
assert count_files(tmp_path) == n_files
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement