jeudi 28 janvier 2016

Mock side_effect fails in function under test, works inside unit test function

I want to mock out the worksheet.cell_value call in the function below...

/excelplanning/scraper.py

VERIFICATION_DATA = [{ 'row': 9, 'col': colnum('AE'), 'expected_value': 'fake_data1'},
                    { 'row': 19, 'col': colnum('AG'), 'expected_value': 'fake_data2'}
                    ]

def verifySheetOK():
    passed = True
    for vset in VERIFICATION_DATA:
        val = worksheet.cell_value(vset['row'], vset['col'])
        if val != vset['expected_value']:
            passed = False
            break
    return passed  

...in the following test case (slightly modified from the original to explain the issue better)

import mock
import excelplanning
from excelplanning.scraper import verifySheetOK

def test(self):
    with mock.patch('excelplanning.scraper.worksheet') as mock_sheet:
        mock_sheet = mock.Mock()
        conf = {'cell_value.side_effect':['fake_data1','fake_data2']}
        mock_sheet.configure_mock(**conf)

        #print(mock_sheet.cell_value(1,1)=='fake_data1')  #result: True
        #print(mock_sheet.cell_value(1,1)=='fake_data2')  #result: True

        self.assertEqual(verifySheetOK(), True)

As a test result I get a AssertionError: False != True. If I debug the testcase I see that

val = worksheet.cell_value(vset['row'], vset['col'])

in verifySheetOK() get assigned to <MagicMock name='worksheet.cell_value()' id='70465232'> instead of to string fake_data1, and then the if val != vset['expected_value'] fails.

What surprises me is that the 2 commented out prints statements in the test case do give the expected result.

What could be going wrong here?

PS: the function verifySheetOK() works as intended in normal operation.

Aucun commentaire:

Enregistrer un commentaire