Tests for book catalog experiment.
This commit is contained in:
parent
ee42f7267e
commit
6034d8faa7
2 changed files with 57 additions and 0 deletions
51
code_to_optimize/User_post.py
Normal file
51
code_to_optimize/User_post.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
from __future__ import annotations
|
||||
from sqlalchemy import create_engine, Integer, String, ForeignKey
|
||||
from sqlalchemy.orm import sessionmaker, relationship, Relationship, Session as SessionType, DeclarativeBase
|
||||
from sqlalchemy.engine.base import Engine
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
# Custom base class
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
# Setup
|
||||
engine: Engine = create_engine('sqlite:///example.db')
|
||||
|
||||
# Typing for sessionmaker
|
||||
Session = sessionmaker(bind=engine)
|
||||
session: SessionType = Session()
|
||||
|
||||
|
||||
# Models
|
||||
class User(Base): # Base now properly recognized
|
||||
__tablename__ = 'users'
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String)
|
||||
posts: Relationship[list[Post]] = relationship("Post", order_by="Post.id", back_populates="user")
|
||||
|
||||
|
||||
class Post(Base): # Base now properly recognized
|
||||
__tablename__ = 'posts'
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String)
|
||||
user_id: Mapped[int] = mapped_column(Integer, ForeignKey('users.id'))
|
||||
user: Relationship[User] = relationship("User", back_populates="posts")
|
||||
|
||||
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
|
||||
# Inefficient query
|
||||
def get_user_posts() -> dict[User, list[Post]]:
|
||||
users: list[User] = session.query(User).all() # Query all users
|
||||
user_posts: dict[User, list[Post]] = {}
|
||||
for u in users:
|
||||
user_posts[u] = session.query(Post).filter(Post.user_id == u.id).all()
|
||||
return user_posts
|
||||
|
||||
|
||||
# Example usage
|
||||
for user, posts in get_user_posts().items():
|
||||
print(f"User: {user.name}, Posts: {[post.title for post in posts]}")
|
||||
6
code_to_optimize/tests/pytest/test_book_catalog_2.py
Normal file
6
code_to_optimize/tests/pytest/test_book_catalog_2.py
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
from code_to_optimize.book_catalog import get_authors2
|
||||
|
||||
|
||||
def test_get_authors_basic() -> None:
|
||||
authors = get_authors2(num_authors=10)
|
||||
assert len(authors) == 10, "Should return 10 authors"
|
||||
Loading…
Reference in a new issue