简体   繁体   中英

How to mock an object inside main() function in python?

I am trying to mock data1 and data2 and trying to provide a return value. I have the following code:

import pandas 

def main():
    data1= pandas.read_excel('path1')
    data2= pandas.read_excel('path2')

if __name__ == '__main__':
    main()
import test1
from unittest.mock import patch
import pandas

class Testdata(unittest.TestCase):

    @patch('test1.main.data1')
    @patch('test1.main.data2')
    def test_main(self, mock_data1, mock_data2):    
        mock_data1.return_value = pandas.DataFrame([some dataframe])
        mock_data2.return_value = pandas.DataFrame([some dataframe])
        test.main()
        data1.assert_called_once()
        data2.assert_called_once()

if __name__ == '__main__':
    unittest.main()

I am getting the following error:

Error
Traceback (most recent call last):
  File "C:\apps\python\3.6.2\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "C:\apps\python\3.6.2\lib\unittest\case.py", line 605, in run
    testMethod()
  File "C:\apps\python\3.6.2\lib\unittest\mock.py", line 1171, in patched
    arg = patching.__enter__()
  File "C:\apps\python\3.6.2\lib\unittest\mock.py", line 1227, in __enter__
    self.target = self.getter()
  File "C:\apps\python\3.6.2\lib\unittest\mock.py", line 1397, in <lambda>
    getter = lambda: _importer(target)
  File "C:\apps\python\3.6.2\lib\unittest\mock.py", line 1080, in _importer
    thing = __import__(import_path)
ModuleNotFoundError: No module named 'main'

How do I resolve this issue and how to mock data1 and data2 and provide a return value to it?

Can't say much before looking at the full-code but I thing adding import unitest in the starting shall do the job.

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