[Python] Mocking in pony orm

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am looking for a way to mock db_session in pony. An example I have now is the following test method:

    import unittest
    from unittest.mock import MagicMock
    from mock import patch

    from fireguard.service.usr_service import _create_user, _find_user

    @patch('mymodule.Database')
    @patch('mymodule.db_session')
    def test_find_user(self, mock_db, mock_db_session):
    mock_db_session.return_value.__enter__.return_value = MagicMock()
    mock_db_session.return_value.__exit__.return_value = None
    mock_db_instance = MagicMock()
    mock_db.return_value = mock_db_instance

    mock_another_user = MagicMock()
    mock_another_user.name = "John Doe"
    mock_another_user.username = "johndoe"
    mock_another_user.email = "johndoe@example.com"
    mock_another_user.phone = 99887766

    mock_db.get.return_value = mock_another_user
    with mock_db_session:
    user = _find_user(email='johndoe@example.com')


    self.assertEqual(user.name, "John Doe")
    self.assertEqual(user.username, "johndoe")
    self.assertEqual(user.email, "johndoe@example.com")


    This does work however, in debug mode, but not otherwise, and I am not sure why.

    I am also providing the code for the _find_user function.

    @db_session
    def find_user_by_email (email: str) -> User:
    return _find_user(email=email)

    def _find_user(email: str) -> User:
    return db.get("select * from schema.usr_tbl where email = $email")

    Continue reading...

Compartilhe esta Página