Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jurrian opened this issue Apr 23, 2020 · 0 comments
Open

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

jurrian opened this issue Apr 23, 2020 · 0 comments

Comments

@jurrian
Copy link

jurrian commented Apr 23, 2020

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 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant