簡體   English   中英

如何使用 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())

我期待pos.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 進程的目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM