[英]Python mock.patch is not mocking my function?
So I wrote a pretty simple test case and function.所以我写了一个非常简单的测试用例和函数。 I can't seem to figure out the problem.我似乎无法弄清楚问题所在。 Anyone have an idea?有人有想法吗? I feel like it should work.我觉得它应该工作。
import pandas
import unittest
from unittest import mock
from unittest.mock import MagicMock, Mock
def my_func():
temp = pandas.ExcelFile('temp.xlsx')
return temp.parse()
@mock.patch('pandas.ExcelFile')
def test_func(pd):
pd.parse.return_value = 10
print(pd.parse())
print(my_func())
Output just gives this:输出只是给出了这个:
10
<MagicMock name='ExcelFile().parse()' id='140620591125360'>
Provide a completed unit test solution based on @MrBean Bremen's comment.根据@MrBean Bremen 的评论提供完整的单元测试解决方案。
index_63929989.py
: index_63929989.py
:
import pandas
def my_func():
temp = pandas.ExcelFile('temp.xlsx')
return temp.parse()
test_index_63929989.py
: test_index_63929989.py
:
import unittest
from unittest import mock
from index_63929989 import my_func
class TestIndex(unittest.TestCase):
@mock.patch('pandas.ExcelFile')
def test_func(self, mock_pd_excelFile):
mock_pd_excelFile.return_value.parse.return_value = 10
actual = my_func()
mock_pd_excelFile.assert_called_with('temp.xlsx')
self.assertEqual(actual, 10)
if __name__ == '__main__':
unittest.main()
unit test result with coverage report:带有覆盖率报告的单元测试结果:
coverage run /Users/ldu020/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/63929989/test_index_63929989.py && coverage report -m --include="src/*"
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
---------------------------------------------------------------------------------
src/stackoverflow/63929989/index_63929989.py 4 0 100%
src/stackoverflow/63929989/test_index_63929989.py 11 0 100%
---------------------------------------------------------------------------------
TOTAL 15 0 100%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.