Cannot get openpyxl worksheet.iter_rows() work with MagicMock

58 views Asked by At

My django2.2/python3.6 server loads excel-file and uses openpyxl worksheet.iter_rows() to provide a python list based on it.
It works, but when I try to test it I cannot make use of MagicMock as seen in the examples below: the line print("ws row:", row) never get executed.

views.py:

import openpyxl

def read_excel_file_contents(filename: str, sheetname: str, cell: str) -> str:
    wb = openpyxl.load_workbook(filename, read_only=True)
    ws = wb[sheetname]
    print()
    print("ws.iter_rows():", ws.iter_rows().__dict__)
    print()
    for row in ws.iter_rows():
        print("ws row:", row)
    return ws[cell].value

test_file.py:

import views
import unittest
from unittest.mock import MagicMock, patch

class FunctionsToTest(unittest.TestCase):

    @patch('views.openpyxl')
    def test_read_mocked_excel_file(self, openpyxl_mock):
        wb = openpyxl_mock.workbook()
        wb.create_sheet("somesheet")
        ws = wb["somesheet"]
        ws["A1"].value = "Some content"

        openpyxl_mock.load_workbook = MagicMock(return_value=wb)
        self.assertEqual(
            views.read_excel_file_contents(
                "a mocked excel file",
                sheetname="somesheet",
                cell="A1"
            ),
            "Some content"
        )

output:

./test.sh
94458
/home/
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
....
ws.iter_rows(): {'_mock_return_value': sentinel.DEFAULT, '_mock_parent': None, '_mock_name': None, '_mock_new_name': '()', '_mock_new_parent': <MagicMock name='openpyxl.workbook().__getitem__().iter_rows' id='139796928280336'>, '_spec_class': None, '_spec_set': None, '_spec_signature': None, '_mock_methods': None, '_mock_children': {}, '_mock_wraps': None, '_mock_delegate': None, '_mock_called': False, '_mock_call_args': None, '_mock_call_count': 0, '_mock_call_args_list': [], '_mock_mock_calls': [], 'method_calls': [], '_mock_unsafe': False, '_mock_side_effect': None}

.
----------------------------------------------------------------------
Ran 1 test in 20.517s

OK
Destroying test database for alias 'default'...

0

There are 0 answers