如何使用pytest获取临时路径tmpdir.as_cwd公司

2024-05-23 21:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

在python测试函数中

def test_something(tmpdir):
    with tmpdir.as_cwd() as p:
        print('here', p)
        print(os.getcwd())

我希望p和{}会得到相同的结果。但实际上,p指向测试文件的目录,而os.getcwd()指向预期的临时文件。在

这是预期的行为吗?在


Tags: 文件test目录hereosdefaswith
2条回答

查看^{}的文档:

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不是您要更改到的“新”当前目录,而是您从中更改的“旧”目录。在

From the documentation:

You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.

而,getcwd代表Get Current Working directory,并返回启动python进程的目录。在

相关问题 更多 >