在 python 测试函数中
def test_something(tmpdir):
with tmpdir.as_cwd() as p:
print('here', p)
print(os.getcwd())
我期待p
并且os.getcwd()
会给出相同的结果。但实际上,p
指向测试文件的目录,而os.getcwd()
指向预期的临时文件。
这是预期的行为吗?
在 python 测试函数中
def test_something(tmpdir):
with tmpdir.as_cwd() as p:
print('here', p)
print(os.getcwd())
我期待p
并且os.getcwd()
会给出相同的结果。但实际上,p
指向测试文件的目录,而os.getcwd()
指向预期的临时文件。
这是预期的行为吗?
查看以下文档py.path.as_cwd
:
返回在托管“with”上下文期间更改为当前目录的上下文管理器。它返回
__enter__
旧目录。
因此,您观察到的行为是正确的:
def test_something(tmpdir):
print('current directory where you are before changing it:', os.getcwd())
# the current directory will be changed now
with tmpdir.as_cwd() as old_dir:
print('old directory where you were before:', old_dir)
print('current directory where you are now:', os.getcwd())
print('you now returned to the old current dir', os.getcwd())
请记住,p
在您的示例中,您更改的不是“新”当前目录,而是您更改的“旧”目录。
您可以使用 tmpdir 固定装置,它将为测试调用提供一个唯一的临时目录,该目录是在基本临时目录中创建的。
而,getcwd
代表获取当前工作目录,并返回您的 python 进程已启动的目录。