0

I am trying to write a unit test for SQLAlchemy's Limit Offset functions. I am new to Python unit testing and I am not sure how to mock the session.query(table).limit(20).offset(20) part. I use unittest.mock.patch to mock the load_session function. Any help would be appreciated. Thanks in advance. I have tried a few syntaxes but none of them worked. Example:

Source code:

    def execute():
        ...
        db2_engine = get_db2_engine()
        session = load_session(db2_engine)
        result_set = session.query(Table).limit(20).offset(20)
        db2_session.close()
        ...
    

Test code:

    import unittest
    from unittest.mock import MagicMock, patch

    def setUp(self):
        self.worker = MyClass(
            ...
        )

    @patch("source_class.load_session")
    def test_execute(self, mock_load_session):
        ...
        mock_session = MagicMock()
        mock_session.query.return_value = MagicMock()
        mock_session.query.return_value.limit.return_value = MagicMock()
        mock_session.query.return_value.limit.return_value.offset.return_value = [...]
        mock_load_session.return_value = mock_session
        ...

        self.worker.execute()
        ...
user3595026
  • 560
  • 2
  • 9
  • 26
  • can you explain what you mean by *"none of them worked"*? can you show the imports and how you call `execute` in `test_execute`? – python_user Jul 05 '23 at 19:17
  • Updated the post. I have tried different mock syntaxes none of those syntaxes worked e.g., `session_mock.query.return_value.limit.return_value.offset.return_value = [...]` @python_user – user3595026 Jul 05 '23 at 20:37
  • thanks for adding the info, might be obvious, but have you checked if you are patching the right namespace? what are you asserting based on? – python_user Jul 05 '23 at 20:43
  • Yes, I have checked the patching namespace looks correct to me. I am asserting the subsequent method calls based on the result set. – user3595026 Jul 05 '23 at 23:31

0 Answers0