Search code examples
pythonpytestpython-unittestpytest-mock

How do i mock _asdict() method for sqlalchemy row in Pytest and MagicMock?


Below is my actual code

    results = session.execute(query)
    for row in results:
        final.append(row._asdict())
    return final

I am able to mock session.execute to return me list of tuples. But after that in the code when _asdict() is called i get an execption saying tuple as no attribute _asdict(). Below is the code i have used for pytest mocking. I want to know how to mock _asdict() here.

mock_session.execute.return_value = [tup1,
                                     tup2]

Solution

  • I finally found a way to mock it usinng MagicMock() I am mocking the return type for session.execute() i.e; CursorResult() object like shown below.

    CursorResult = MagicMock()
    mock_session.execute.return_value = [CursorResult(tup1),
                                         CursorResult(tup2)]
    CursorResult.return_value._asdict.side_effect = [tup1, tup2]