本文介紹了Python mock 修補(bǔ)另一個(gè)函數(shù)調(diào)用的函數(shù)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
def f1():
return 10, True
def f2():
num, stat = f1()
return 2*num, stat
如何使用 python 的模擬庫(kù)修補(bǔ) f1()
并返回自定義結(jié)果以便我可以測(cè)試 f2()
?
How do I use python's mock library to patch f1()
and return a custom result so I could test f2()
?
已我的測(cè)試有問(wèn)題嗎?這似乎不起作用,所有測(cè)試都因 AssertionError 而失敗
Edited: Is there something wrong with my test? This doesn't seem to be working, all the tests failed with AssertionError
from foo.bar import f2
from mock import patch
class MyTest(TestCase):
def test_f2_1(self):
with patch('project.module.f1') as some_func:
some_func.return_value = (20, False)
num, stat = f2()
self.assertEqual((num, stat), (40, False))
@patch('project.module.f1')
def test_f2_2(self, some_func):
some_func.return_value = (20, False)
num, stat = f2()
self.assertEqual((num, stat), (40, False))
推薦答案
第一個(gè)例子表明 f1() 和 f2() 定義在同一個(gè)模塊中.因此,以下應(yīng)該有效:
First example suggests that f1() and f2() defined in the same module. Hence the following should work:
from foo.bar import f2
from mock import patch
class MyTest(TestCase):
@patch('foo.bar.f1')
def test_f2_2(self, some_func):
some_func.return_value = (20, False)
num, stat = f2()
self.assertEqual((num, stat), (40, False))
補(bǔ)丁與導(dǎo)入相同:@patch('foo.bar.f1')
這是一個(gè)很好的答案:
http://bhfsteve.blogspot.nl/2012/06/patching-tip-using-mocks-in-python-unit.html
這篇關(guān)于Python mock 修補(bǔ)另一個(gè)函數(shù)調(diào)用的函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!