我想测试名为 getFileAsJson 的appendRole 来读取打开的文件。 我的问题是我不知道下一个将是哪个开放。 if/elif 有很多。
def appendRole(self, hosts=None, _newrole=None, newSubroles=None, undoRole=False, config_path=None):
""" Same as changeRole but keeps subroles """
if hosts is None:
hosts = ["127.0.0.1"]
if newSubroles is None:
newSubroles = {}
if config_path is None:
config_path = self.config_path
with self._lock:
default = {}
data = self.getFileAsJson(config_path, default)
...................
...................
...................
...................
data1 = self.getFileAsJson(self.config_path_all, {"some"})
data2 = self.getFileAsJson(self.config_path_core, {"something"})
...................
...................
...................
def getFileAsJson(self, config_path, init_value):
"""
read file and return json data
if it wasn't create. Will created.
"""
self.createFile(config_path, init_value)
try:
with open(config_path, "r") as json_data:
data = json.load(json_data)
return data
except Exception as e:
self.logAndRaiseValueError(
"Can't read data from %s because %s" % (config_path, e))
最佳答案
甚至您也可以在 Python mock builtin 'open' in a class using two different files 找到问题的答案我想鼓励您改变为 getFileAsJson()
编写测试的方法,然后信任它。
要测试appendRole()
,请使用 mock.patch
修补 getFileAsJson()
,然后通过 side_effect
属性,您可以指示模拟返回测试所需的内容。
因此,在对 getFileAsJson()
进行一些测试后,您可以在其中使用 mock_open()
模拟 open
内置(也许你也需要修补 createFile()
)。您的 appendRole()
的测试如下所示:
@mock.patch('mymodule.getFileAsJson', autospec=True)
def test_appendRole(self, mock_getFileAsJson)
mock_getFileAsJson.side_effect = [m_data, m_data1,m_data2,...]
# where m_data, m_data1,m_data2, ... is what is supposed
# getFileAsJson return in your test
# Invoke appendRole() to test it
appendRole(bla, bla)
# Now you can use mock_getFileAsJson.assert* family methods to
# check how your appendRole call it.
# Moreover add what you need to test in appendRole()
关于python - 两个文件的 python 'open' 中的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471565/