vendredi 31 juillet 2015

In unittest, how do I assert whether the function called or not NOT using mock

I want to test the class Procedures whether some function called or not. Since I know mock and often use it, firstly I used mock. However soon it later, I noticed this test was failed because using mock is just imitating the real processing.

What I want to do is the following test is passed correctly.

Does anyone have solutions?

from unittest import TestCase, mock


class Procedures:
    x = 1

    def func_should_be_called(self):
        self.x = 'called'
        return len(self.x)

    def hoge(self):
        self.func_should_be_called()
        # Because whenever self.x != 'called', Never do some_exec(), and I want to raise Exception
        assert self.x == 'called'
        self.some_exec()

    def some_exec(self):
        pass


class HogeTest(TestCase):
    def test_hoge(self):
        with mock.patch('test_hoge.Procedures.func_should_be_called') as mock_func_should_be_called:
            p = Procedures()
            mock_func_should_be_called.return_value = 5
            p.hoge()
            mock_func_should_be_called.called()

if __name__ == '__main__':
    Procedures().hoge()
    print('yes!')

In fact, I found inspect and traceback module and used it. However the code using them in the test-function(test_hoge) didn't work because old call-stack(func_should_be_called's) had been gone.

The purpose of the codes which under if __name__ == '__main__' is only verifying Procedures works correctly.

Aucun commentaire:

Enregistrer un commentaire