簡體   English   中英

Python mock.patch 不是在嘲笑我的函數嗎?

[英]Python mock.patch is not mocking my function?

所以我寫了一個非常簡單的測試用例和函數。 我似乎無法弄清楚問題所在。 有人有想法嗎? 我覺得它應該工作。

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())

輸出只是給出了這個:

10
<MagicMock name='ExcelFile().parse()' id='140620591125360'>

根據@MrBean Bremen 的評論提供完整的單元測試解決方案。

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()

帶有覆蓋率報告的單元測試結果:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM