Pytest 使用 tmp_path fixture 创建多个文件
Pytest create multiple files with tmp_path fixture
我有一个简单的函数可以计算目录中的文件数。
def count_files(path):
return len(os.listdir(path))
我想通过以下方式进行测试。这行得通,但当然是非常重复的:
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
有没有更简单的写法?
期望:
def test_count_files(tmp_path):
f1 = tmp_path / ["hello1.txt", "hello2.txt", "hello3.txt"]
f1.touch()
assert count_files(tmp_path) == 3
尝试像
这样的简单 for 循环
n_files = 4
for i in range(n_files):
(tmp_path / f"hello{i}.txt").touch()
assert count_files(tmp_path) == n_files
我有一个简单的函数可以计算目录中的文件数。
def count_files(path):
return len(os.listdir(path))
我想通过以下方式进行测试。这行得通,但当然是非常重复的:
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
有没有更简单的写法?
期望:
def test_count_files(tmp_path):
f1 = tmp_path / ["hello1.txt", "hello2.txt", "hello3.txt"]
f1.touch()
assert count_files(tmp_path) == 3
尝试像
这样的简单 for 循环n_files = 4
for i in range(n_files):
(tmp_path / f"hello{i}.txt").touch()
assert count_files(tmp_path) == n_files