0

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'>
JobHunter69
  • 1,706
  • 5
  • 25
  • 49

1 Answers1

0

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%
Lin Du
  • 88,126
  • 95
  • 281
  • 483