Skip to content

Decorating a class with mocked_relations does not work with setUp #110

Open
@jurrian

Description

@jurrian

I have been decorating my TestCase classes with the mocked_relations decorator. Unfortunately I found that setUp is not patched, and even if it is the scope prevents it from reaching the test methods. Therefore, I have created a mixin which can be used in TestCases to provide mocked_relations in the entire TestCase using start() and stop():

class TestCaseMockQueriesMixin:
    models = None

    def __init__(self, *args, **kwargs):
        if not self.models:
            raise ValueError(
                'No models have been supplied. Usage: '
                'class SomeTestCase(TestCaseMockQueriesMixin.mocked_relations([ModelA, ...]), TestCase)'
            )
        super().__init__(*args, **kwargs)

    @classmethod
    def mocked_relations(cls, *models):
        cls.models = models
        return cls

    def _callSetUp(self):
        self.start_mocks()
        # noinspection PyProtectedMember
        super()._callSetUp()

    def start_mocks(self):
        patcher_chain = mocked_relations(*self.models)
        patcher_chain.start()
        self.addCleanup(patcher_chain.stop)

This works when used like this:

class SomeTestCase(TestCaseMockQueriesMixin.mocked_relations([ModelA, ...]), TestCase):
     ...

This way you can mock the managers in setUp and for example add to a M2M field, what you add in setUp still exists in the test methods.

I just wanted to share my finding, maybe it's useful for others. If interested I can make a PR to integrate it in the rest of the code, let me know :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions