簡體   English   中英

是否可以模擬 os.scandir 及其屬性?

[英]Is it possible to mock os.scandir and its attributes?

for entry in os.scandir(document_dir)
    if os.path.isdir(entry):
    # some code goes here
    else:
        # else the file needs to be in a folder
        file_path = entry.path.replace(os.sep, '/')

我遇到問題 mocking os.scandir 和 else 語句中的路徑屬性。 我無法模擬我在單元測試中創建的模擬對象的屬性。

with patch("os.scandir") as mock_scandir:
    # mock_scandir.return_value = ["docs.json", ]
    # mock_scandir.side_effect = ["docs.json", ]
    # mock_scandir.return_value.path = PropertyMock(return_value="docs.json")

這些都是我嘗試過的所有選項。 任何幫助是極大的贊賞。

這取決於你真正需要模擬什么。 問題是os.scandir返回os.DirEntry類型的條目。 一種可能性是使用您自己的模擬DirEntry並僅實現您需要的方法(在您的示例中,只有path )。 對於您的示例,您還必須模擬os.path.isdir 這是一個獨立的示例,說明如何執行此操作:

import os
from unittest.mock import patch


def get_paths(document_dir):
    # example function containing your code
    paths = []
    for entry in os.scandir(document_dir):
        if os.path.isdir(entry):
            pass
        else:
            # else the file needs to be in a folder
            file_path = entry.path.replace(os.sep, '/')
            paths.append(file_path)
    return paths


class DirEntry:
    def __init__(self, path):
        self.path = path

    def path(self):
        return self.path


@patch("os.scandir")
@patch("os.path.isdir")
def test_sut(mock_isdir, mock_scandir):
    mock_isdir.return_value = False
    mock_scandir.return_value = [DirEntry("docs.json")]
    assert get_paths("anydir") == ["docs.json"]

根據您的實際代碼,您可能需要做更多的事情。

如果你想修補更多的文件系統功能,你可以考慮使用pyfakefs來代替,它會修補整個文件系統。 這對於單個測試來說是多余的,但對於依賴文件系統功能的測試套件來說可能很方便。

免責聲明:我是 pyfakefs 的貢獻者。

暫無
暫無

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

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