vendredi 4 août 2017

Mocking file reads using patch decorator and side_effect

I am testing a function that reads a file, does operations to the contents and returns a value depending on what it sees. The function testme I test lives in module.py. I am running python 2.7. I know I can accomplish this with

import unittest
import module
from mock import patch, mock_open

TestTestMe(unittest.TestCase):
    ...
    def test_test_me(self):
        with patch('module.open', mock_open(read_data='1 2')) as _:
          self.assertRaises(IndexError, module.testme, 'foo')
        with patch('module.open', mock_open(read_data='1 2 3')) as _:
          self.assertEquals(module.testme('foo'), 3)

etc.

However, I would like to (mostly to prevent repeated use of with statement, and also to be able to dynamically generate various read_data) be able to do this using the @patch as decorator defining my read_data with a function. Something like this. I will not repeat the class definition and imports.

def give_contents(x):
    if x == 'correct':
        return mock_open(read_data='1 2 3')
    else:
        return mock_open(read_data='a b c')

and then using the test function like:

@patch(module.open, side_effect=give_contents)
def test_test_me(self):
    self.assertEquals(module.testme('correct'), 3)

I keep running into TypeErrors such as

TypeError: test_testme() takes exactly 1 argument (2 given)

however I try to get around this. This is driving me crazy. Guidance would be greatly appreciated. If you want some additional details I may have omitted, please ask for specifics, and I will provide those.

Aucun commentaire:

Enregistrer un commentaire