pytest 获得了很大的吸引力,它可以使用tmpdir 和monkeypatching 完成所有这些工作(嘲笑)。
您可以使用tmpdir 函数参数,该参数将提供一个对测试调用唯一的临时目录,在基本临时目录中创建(默认情况下创建为系统临时目录的子目录)。
import os
def test_create_file(tmpdir):
p = tmpdir.mkdir("sub").join("hello.txt")
p.write("content")
assert p.read() == "content"
assert len(tmpdir.listdir()) == 1
monkeypatch 函数参数可帮助您安全地设置/删除属性、字典项或环境变量,或修改 sys.path 以进行导入。
import os
def test_some_interaction(monkeypatch):
monkeypatch.setattr(os, "getcwd", lambda: "/")
你也可以传递一个函数而不是使用 lambda。
import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')
def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
x = getssh()
assert x == '/abc/.ssh'
# You can still use lambda when passing arguments, e.g.
# monkeypatch.setattr(os.path, 'expanduser', lambda x: '/abc')
如果您的应用程序与文件系统有很多交互,那么使用 pyfakefs 之类的东西可能会更容易,因为模拟会变得乏味和重复。