mercredi 26 octobre 2016

Python: creating a mockclass and use it as a contextmanager

I'm trying to unit test a dynamic class that is supposed to be used as an inherited object to easily add functionality to the grand scheme. But also act as a standalone package, so testing should be minimum.

This class has quite a few difficulties.

  1. NotImplemented Errors on method calls.

  2. Generic functions.

For example:

    class SomeClass(object):
        def something(a):
            raise NotImplementedError(...)

        def process(self, data, route):
            func = getattr(self, route)

            if callable(func):
                return func(data)
            else:
                return func

My question is whether it is possible to use a MockClass per such:

    class MockClass(SomeClass):
         # Patch problematic methods, I'm having difficulty 
         # finding the right patching approach
         def patched_process(self, data, route):
             return 'example'

         @patch('MockClass.process', patched_process)
         def process(self, data, route):
             return super(MockClass, self).process(data, route) 

So that in my TestCase (Django, fyi)...

    class ClassTests(TestCase):
        def test_process(self):
            with MockClass() as testee:
                 # run tests
                 result = testee.process(1, 2)
                 self.assertTrue(result == 'example')

This would result then in no failed tests?

Aucun commentaire:

Enregistrer un commentaire