3

在 python 测试函数中

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

我期待p并且os.getcwd()会给出相同的结果。但实际上,p指向测试文件的目录,而os.getcwd()指向预期的临时文件。

这是预期的行为吗?

4

2 回答 2

4

查看以下文档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在您的示例中,您更改的不是“新”当前目录,而是您更改的“旧”目录。

于 2019-04-12T20:52:03.133 回答
0

从文档中:

您可以使用 tmpdir 固定装置,它将为测试调用提供一个唯一的临时目录,该目录是在基本临时目录中创建的。

而,getcwd代表获取当前工作目录,并返回您的 python 进程已启动的目录。

于 2019-04-12T20:38:23.570 回答