如何使用 pytest tmpdir.as_cwd 获取临时路径
How to get the temporary path using pytest tmpdir.as_cwd
在一个python测试函数中
def test_something(tmpdir):
with tmpdir.as_cwd() as p:
print('here', p)
print(os.getcwd())
我原以为 p
而 os.getcwd()
会给出相同的结果。但实际上,p
指向测试文件的目录,而 os.getcwd()
指向预期的临时文件。
这是预期的行为吗?
You can use the tmpdir fixture which will provide a temporary
directory unique to the test invocation, created in the base temporary
directory.
然而,getcwd
代表获取当前工作目录,returns 代表您的 python 进程已启动的目录。
看看py.path.as_cwd
的文档:
return context manager which changes to current dir during the managed "with" context. On __enter__
it returns the old dir.
因此您观察到的行为是正确的:
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
不是您要更改到的 "new" 当前目录,而是您更改前的 "old" 目录。
在一个python测试函数中
def test_something(tmpdir):
with tmpdir.as_cwd() as p:
print('here', p)
print(os.getcwd())
我原以为 p
而 os.getcwd()
会给出相同的结果。但实际上,p
指向测试文件的目录,而 os.getcwd()
指向预期的临时文件。
这是预期的行为吗?
You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.
然而,getcwd
代表获取当前工作目录,returns 代表您的 python 进程已启动的目录。
看看py.path.as_cwd
的文档:
return context manager which changes to current dir during the managed "with" context. On
__enter__
it returns the old dir.
因此您观察到的行为是正确的:
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
不是您要更改到的 "new" 当前目录,而是您更改前的 "old" 目录。