简体   繁体   中英

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.

index_63929989.py :

import pandas


def my_func():
    temp = pandas.ExcelFile('temp.xlsx')
    return temp.parse()

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM