Skip to content

how can we mock a model instance? #114

Closed
@AdrienLemaire

Description

@AdrienLemaire

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?

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