Alchemy-Mock

0.4.3 · abandoned · verified Thu Apr 16

Alchemy-Mock (version 0.4.3) provides helpers for mocking SQLAlchemy sessions in unit tests, allowing for assertions against SQLAlchemy expressions. The project appears to be abandoned since its last release in 2019, with a community-maintained fork, `mock-alchemy`, now serving as an actively developed alternative.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `UnifiedAlchemyMagicMock` to mock a SQLAlchemy session. It includes an example of stubbing query results and asserting on method calls. It also highlights a common behavior where the mock session doesn't perform actual filtering on objects added to it, requiring different assertion strategies.

import unittest
from unittest import mock

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from alchemy_mock.mocking import UnifiedAlchemyMagicMock

# Define a simple SQLAlchemy model for demonstration
Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)

    def __repr__(self):
        return f"<User(id={self.id}, name='{self.name}', email='{self.email}')>"

# Example usage of UnifiedAlchemyMagicMock
def get_user_by_name(session, name):
    return session.query(User).filter(User.name == name).first()

def add_user(session, name, email):
    user = User(name=name, email=email)
    session.add(user)
    session.commit()
    return user

class TestUserService(unittest.TestCase):
    def test_get_user_by_name(self):
        mock_session = UnifiedAlchemyMagicMock(
            data=[([mock.call.query(User), mock.call.filter(User.name == 'Alice')], [User(id=1, name='Alice', email='alice@example.com')])]
        )
        user = get_user_by_name(mock_session, 'Alice')
        self.assertIsNotNone(user)
        self.assertEqual(user.name, 'Alice')
        mock_session.filter.assert_called_once_with(User.name == 'Alice')

    def test_add_user(self):
        mock_session = UnifiedAlchemyMagicMock()
        new_user = add_user(mock_session, 'Bob', 'bob@example.com')
        
        # In alchemy-mock, the mock session doesn't apply filters to added models, so querying them directly might not work as expected.
        # However, you can assert that the add and commit calls happened.
        mock_session.add.assert_called_once()
        mock_session.commit.assert_called_once()
        
        # To retrieve added data, you typically would configure 'data' if querying after adding.
        # Or, assert on the object passed to add.
        self.assertEqual(new_user.name, 'Bob')
        self.assertEqual(new_user.email, 'bob@example.com')

# To run the tests (example):
if __name__ == '__main__':
    unittest.main()

view raw JSON →