Reputation: 233
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]
Upvotes: -1
Views: 1066
Reputation: 233
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]
Upvotes: 0
Reputation:
Following up on the comments: you can create a small class which has a _asdict
method and use that as a stand-in for the sqlalchemy row, e.g:
class FakeRow:
def _asdict(self):
# Put whatever test data you want in the dict
return { 'some_data': 1, 'some_more_data': 2 }
Then your mock would be something like:
mock_session.execute.return_value = [FakeRow(), FakeRow()]
Upvotes: 1