django-mock-queries icon indicating copy to clipboard operation
django-mock-queries copied to clipboard

how can we mock a model instance?

Open AdrienLemaire opened this issue 4 years ago • 2 comments

Hi. I'd like to test a model method, while mocking the data of a test instance. Using django wagtail and pytest.

models.py

class BlockPage(Page):  # A wagtail model
    title = models.CharField(max_length=100)
    block = models.ForeignKey()

   def get_context(self, request):
        context = super().get_context(request, *args, **kwargs)
        current_category = self.block.category
        context['category'] = current_category
        return context

conftest.py

@pytest.fixture(scope="class")
def make_block_page(request: _pytest.fixtures.FixtureRequest) -> None:
    def _make_block_page(cls: TestCase, title: str) -> dict:
        block = MockModel(mocktitle=title, category=MockModel())
        return MockModel(mock_name="BlockPage", title=title, block=block)

    # Make the method available from TestCase
    request.cls.make_block_page = _make_block_page

test_models.py

@pytest.mark.usefixtures("make_block_page")
class BlockPageTestCase(WagtailPageTests):
    def setUp(self) -> None:
        super().setUp()
        self.block_page = self.make_block_page("ブロック1")

    def test_context(self) -> None:
        fake_request = HttpRequest()
        context = BlockPage.get_context(self.block_page, fake_request)
        self.assertListEqual()

pytest traceback

============================== FAILURES ===============================
___________________ BlockPageTestCase.test_context ____________________

self = <models_test.BlockPageTestCase testMethod=test_context>

    def test_context(self) -> None:
        fake_request = HttpRequest()
>       context = BlockPage.get_context(self.block_page, fake_request)

gopart/tests/models_test.py:20:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = BlockPage, request = <HttpRequest>, args = (), kwargs = {}

    def get_context(self, request: HttpRequest, *args: list, **kwargs: dict) -> dict:
>       context = super().get_context(request, *args, **kwargs)
E       TypeError: super(type, obj): obj must be an instance or subtype of type

gopart/models.py:259: TypeError
===================== 1 failed, 1 passed in 0.27s =====================

I was hoping that passing mock_name="BlockPage" as parameter to MockModel would do the trick and the model would accept the mock as being an instance of itself, but it doesn't.

How would you go about fixing this issue?

AdrienLemaire avatar Jun 16 '20 10:06 AdrienLemaire

Hy @AdrienLemaire , did you find a fix for this?

luisiacc avatar Jun 04 '21 02:06 luisiacc

Sorry, that was a while ago, and I've changed my tech stack since, I don't remember.

AdrienLemaire avatar Jun 04 '21 03:06 AdrienLemaire