我想做的是.
x = MagicMock()
x.iter_values = [1, 2, 3]
for i in x:
i.method()我试图为这个函数编写一个单元测试,但是我不确定如何在不调用外部资源的情况下模拟所有调用的方法.
def wiktionary_lookup(self):
"""Looks up the word in wiktionary with urllib2, only to be used for inputting data"""
wiktionary_page = urllib2.urlopen(
"http://%s.wiktionary.org/wiki/%s" % (self.language.wiktionary_prefix, self.name))
wiktionary_page = fromstring(wiktionary_page.read())
definitions = wiktionary_page.xpath("//h3/following-sibling::ol/li")
print definitions.text_content()
defs_list = []
for i in definitions:
print i
i = i.text_content()
i = i.split('\n')
for j in i:
# Takes out an annoying "[quotations]" in the end of the string, sometimes.
j = re.sub(ur'\u2003\[quotations \u25bc\]', '', j)
if len(j) > 0:
defs_list.append(j)
return defs_list编辑:
我可能是在滥用嘲弄,我不确定。我试图在不调用外部wiktionary_lookup的情况下对这个services...so方法进行单元测试,我模拟urlopen.我模拟fromstring.xpath(),但据我所见,我还需要迭代xpath()的返回值,并调用一个方法"text_contents()“,所以这就是我在这里要做的。
如果我完全误解了如何统一这个方法,那么请告诉我哪里出了问题.
编辑(添加当前单元代码)
@patch("lang_api.models.urllib2.urlopen")
@patch("lang_api.models.fromstring")
def test_wiktionary_lookup_2(self, fromstring, urlopen):
"""Looking up a real word in wiktionary, should return a list"""
fromstring().xpath.return_value = MagicMock(
content=["test", "test"], return_value='test\ntest2')
# A real word should give an output of definitions
output = self.things.model['word'].wiktionary_lookup()
self.assertEqual(len(output), 2)发布于 2016-10-01 21:27:16
实际上,您要做的是不返回带有Mock的return_value=[]。实际上,您希望返回一个list of Mock对象。下面是包含正确组件的测试代码片段和一个小示例,演示如何测试循环中的一个迭代:
@patch('d.fromstring')
@patch('d.urlopen')
def test_wiktionary(self, urlopen_mock, fromstring_mock):
urlopen_mock.return_value = Mock()
urlopen_mock.return_value.read.return_value = "some_string_of_stuff"
mocked_xpath_results = [Mock()]
fromstring_mock.return_value.xpath.return_value = mocked_xpath_results
mocked_xpath_results[0].text_content.return_value = "some string"因此,要剖析上述代码以解释为纠正您的问题所做的工作:
帮助我们测试for循环中的代码的第一件事是按照以下步骤创建一个模拟对象列表:
mocked_xpath_results = [Mock()]然后,你可以从
fromstring_mock.return_value.xpath.return_value = mocked_xpath_results我们将return_value的xpath调用设置为每个mocked_xpath_results的模拟列表。
作为如何在列表中进行操作的示例,我添加了如何在循环中进行模拟,如下所示:
mocked_xpath_results[0].text_content.return_value = "some string"在单元测试中(这可能是一个意见问题),我喜欢显式,所以我显式地访问列表项,并决定应该发生什么。
希望这能有所帮助。
https://stackoverflow.com/questions/39783460
复制相似问题