from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key=True)
name = Column(String)
birth_date = Column(Date)
books = relationship('Book', back_populates='author')
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String)
isbn = Column(String)
author_id = Column(Integer, ForeignKey('authors.id'))
author = relationship('Author', back_populates='books')
def find_authors_with_chocolate_books(session):
return session.query(Author).join(Book).filter(Book.title.like('%Chocolate%')).all()
# Unit test
import unittest
class TestFindAuthorsWithChocolateBooks(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(self.engine)
Session = sessionmaker(bind=self.engine)
self.session = Session()
# Setup test data
author1 = Author(name='John Doe', birth_date='1980-01-01')
author2 = Author(name='Jane Doe', birth_date='1985-01-01')
book1 = Book(title='The Chocolate Factory', isbn='1234567890', author=author1)
book2 = Book(title='A Chocolate Adventure', isbn='0987654321', author=author2)
self.session.add_all([author1, author2, book1, book2])
self.session.commit()
def test_find_authors_with_chocolate_books(self):
authors = find_authors_with_chocolate_books(self.session)
self.assertEqual(len(authors), 2)
self.assertIn(author1, authors)
self.assertIn(author2, authors)
if __name__ == '__main__':
unittest.main()