Files
deb-python-sqlalchemy-utils/tests/aggregate/test_multiple_aggregates_per_class.py
Jacob Magnusson 815f07d6c1 Use pytest fixtures to reduce complexity and repetition
Also:

Allow override of database name and user in tests (important for me as I would have to mess with my PSQL and MySQL database users otherwise)
Use dict.items instead of six.iteritems as it sporadically caused RuntimeError: dictionary changed size during iteration in Python 2.6 tests.
Fix typo DNS to DSN
Adds Python 3.5 to tox.ini
Added an .editorconfig
Import babel.dates in sqlalchemy_utils.i18n as an exception would be raised when using the latest versions of babel.
2016-01-19 10:52:30 +01:00

97 lines
2.7 KiB
Python

import pytest
import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
@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 Thread(Base, Comment):
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')
@aggregated('comments', sa.Column(sa.Integer))
def last_comment_id(self):
return sa.func.max(Comment.id)
comments = sa.orm.relationship(
'Comment',
backref='thread'
)
Thread.last_comment = sa.orm.relationship(
'Comment',
primaryjoin='Thread.last_comment_id == Comment.id',
foreign_keys=[Thread.last_comment_id],
viewonly=True
)
return Thread
@pytest.fixture
def init_models(Comment, Thread):
pass
class TestAggregateValueGenerationForSimpleModelPaths(object):
def test_assigns_aggregates_on_insert(self, session, Thread, Comment):
thread = Thread()
thread.name = u'some article name'
session.add(thread)
comment = Comment(content=u'Some content', thread=thread)
session.add(comment)
session.commit()
session.refresh(thread)
assert thread.comment_count == 1
assert thread.last_comment_id == comment.id
def test_assigns_aggregates_on_separate_insert(
self,
session,
Thread,
Comment
):
thread = Thread()
thread.name = u'some article name'
session.add(thread)
session.commit()
comment = Comment(content=u'Some content', thread=thread)
session.add(comment)
session.commit()
session.refresh(thread)
assert thread.comment_count == 1
assert thread.last_comment_id == 1
def test_assigns_aggregates_on_delete(self, session, Thread, Comment):
thread = Thread()
thread.name = u'some article name'
session.add(thread)
session.commit()
comment = Comment(content=u'Some content', thread=thread)
session.add(comment)
session.commit()
session.delete(comment)
session.commit()
session.refresh(thread)
assert thread.comment_count == 0
assert thread.last_comment_id is None