[Python] unit testing in DRF, Error mock.patch transaction.atomic with unittest.mock.patch

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    @transaction.atomic
    def deposit(user: User, account_number: str, amount: float) -> None:
    account = get_object_or_404(
    Account.objects.select_for_update(), account_number=account_number, user=user
    )

    account.balance += amount
    account.save()

    AccountTransaction.objects.create(~~~~~)


    class TestDepositUnit(TestCase):

    @patch("django.db.transaction.atomic", return_value = MagicMock())
    @patch("account.services.AccountTransaction.objects.create")
    @patch("account.services.get_object_or_404")
    def test_deposit(self, mock_get_object_or_404, mock_create, mock_atomic):

    mock_user = MagicMock()
    mock_user.username = "testuser"

    mock_account = MagicMock()
    mock_account.balance = 0
    mock_account.save = MagicMock()

    mock_get_object_or_404.return_value = mock_account

    deposit(user=mock_user, account_number="123", amount=100)

    asset mock_account.balance == 100


    I want to patch the djagno ORM because I want to do unit testing without a database. It seems like transaction.atomic has been patched, but I'm getting a database runtime error. or is there another problem?

    fully unit testing without db

    error message:

    def get_autocommit(self):
    """Get the autocommit state."""
    > self.ensure_connection()
    E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

    /lib/python3.13/site-packages/django/db/backends/base/base.py:454: RuntimeError
    ====== short test summary info =======
    FAILED tests/account/test_deposit.py::TestDepositUnit::test_deposit_unit - RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
    1 failed in 0.08s

    Continue reading...

Compartilhe esta Página