1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
import pytest
import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
@pytest.fixture
def Thread(Base):
class Thread(Base):
__tablename__ = 'thread'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
@aggregated('comments', sa.Column(sa.Integer, default=0))
def comment_count(self):
return sa.func.count('1')
comments = sa.orm.relationship('Comment', backref='thread')
return Thread
@pytest.fixture
def Comment(Base):
class Comment(Base):
__tablename__ = 'comment'
id = sa.Column(sa.Integer, primary_key=True)
content = sa.Column(sa.Unicode(255))
thread_id = sa.Column(sa.Integer, sa.ForeignKey('thread.id'))
return Comment
@pytest.fixture
def init_models(Thread, Comment):
pass
class TestAggregateValueGenerationForSimpleModelPaths:
def test_assigns_aggregates_on_insert(self, session, Thread, Comment):
thread = Thread()
thread.name = 'some article name'
session.add(thread)
comment = Comment(content='Some content', thread=thread)
session.add(comment)
session.commit()
session.refresh(thread)
assert thread.comment_count == 1
def test_assigns_aggregates_on_separate_insert(
self,
session,
Thread,
Comment
):
thread = Thread()
thread.name = 'some article name'
session.add(thread)
session.commit()
comment = Comment(content='Some content', thread=thread)
session.add(comment)
session.commit()
session.refresh(thread)
assert thread.comment_count == 1
def test_assigns_aggregates_on_delete(self, session, Thread, Comment):
thread = Thread()
thread.name = 'some article name'
session.add(thread)
session.commit()
comment = Comment(content='Some content', thread=thread)
session.add(comment)
session.commit()
session.delete(comment)
session.commit()
session.refresh(thread)
assert thread.comment_count == 0
|