I have a simple function which counts the files in a directory.
JavaScript
x
3
1
def count_files(path):
2
return len(os.listdir(path))
3
I want to test this the following way. This works, but is of course very repetetive:
JavaScript
1
11
11
1
def test_count_files(tmp_path):
2
f1 = tmp_path / "hello1.txt"
3
f1.touch()
4
f2 = tmp_path / "hello2.txt"
5
f2.touch()
6
f3 = tmp_path / "hello3.txt"
7
f3.touch()
8
f4 = tmp_path / "hello4.txt"
9
f4.touch()
10
assert count_files(tmp_path) == 4
11
Is there an easier way to write this?
Desired:
JavaScript
1
5
1
def test_count_files(tmp_path):
2
f1 = tmp_path / ["hello1.txt", "hello2.txt", "hello3.txt"]
3
f1.touch()
4
assert count_files(tmp_path) == 3
5
Advertisement
Answer
Try just a simple for loop like
JavaScript
1
5
1
n_files = 4
2
for i in range(n_files):
3
(tmp_path / f"hello{i}.txt").touch()
4
assert count_files(tmp_path) == n_files
5