問題描述
我有一個專有的存儲庫格式,我正在嘗試開發一個 Python 模塊來處理這些存儲庫.回購格式如下:
I have a proprietary repository format and I'm trying to develop a Python module to process these repositories. Repo format goes as:
/home/X/
|
+ alpha/
|
+ beta/
|
+ project.conf
這里,X
是一個項目.alpha
和 beta
是本項目中的文件夾,它們代表本項目中的組.group 是這個 repo 中的一個容器,它所代表的內容實際上與這個問題無關.repo X
在其根級別也有文件;project.conf
就是此類文件的一個示例.
Here, X
is a project. alpha
and beta
are folders inside this project and they represent groups in this project. A group is a container in this repo and what it represents is really not relevant for this question. The repo X
also has files in its root level; project.conf
is an example of such a file.
我有一個名為Project
的類,它抽象出X
等項目.Project
類有一個 load()
方法,用于構建內存中的表示.
I have a class called Project
that abstracts projects such as X
. The Project
class has a method load()
that builds an in-memory representation.
class Project(object):
def load(self):
for entry in os.listdir(self.root):
path = os.path.join(self.root, entry)
if os.path.isdir(path):
group = Group(path)
self.groups.append(group)
group.load()
else:
# process files ...
要通過模擬文件系統對 load()
方法進行單元測試,我有:
To unit test the load()
method by mocking the file system, I have:
import unittest
from unittest import mock
import Project
class TestRepo(unittest.TestCase):
def test_load_project(self):
project = Project("X")
with mock.patch('os.listdir') as mocked_listdir:
mocked_listdir.return_value = ['alpha', 'beta', 'project.conf']
project.load()
self.assertEqual(len(project.groups), 2)
這確實模擬了 os.listdir
成功.但我無法欺騙 Python 將 mocked_listdir.return_value
視為由文件和目錄組成.
This does mock os.listdir
successfully. But I can't trick Python to treat mocked_listdir.return_value
as consisting of files and directories.
我如何模擬 os.listdir
或 os.path.isdir
,在同一個測試中,這樣測試就會看到alpha
和 beta
作為目錄,project.conf
作為文件?
How do I mock either os.listdir
or os.path.isdir
, in the same test, such that the test will see alpha
and beta
as directories and project.conf
as a file?
推薦答案
我設法通過將一個可迭代對象傳遞給模擬的 isdir
的 side_effect
屬性來實現所需的行為對象.
I managed to achieve the desired behavior by passing an iterable to the side_effect
attribute of the mocked isdir
object.
import unittest
from unittest import mock
import Project
class TestRepo(unittest.TestCase):
def test_load_project(self):
project = Project("X")
with mock.patch('os.listdir') as mocked_listdir:
with mock.patch('os.path.isdir') as mocked_isdir:
mocked_listdir.return_value = ['alpha', 'beta', 'project.conf']
mocked_isdir.side_effect = [True, True, False]
project.load()
self.assertEqual(len(project.groups), 2)
關鍵是 mocked_isdir.side_effect = [True, True, False]
行.可迭代對象中的布爾值應與傳遞給 mocked_listdir.return_value
屬性的目錄和文件條目的順序相匹配.
The key is the mocked_isdir.side_effect = [True, True, False]
line. The boolean values in the iterable should match the order of directory and file entries passed to the mocked_listdir.return_value
attribute.
這篇關于如何在 Python 中模擬 os.listdir 來假裝文件和目錄?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!