File: test_with_column_alias.py

package info (click to toggle)
python-sqlalchemy-utils 0.30.12-2~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,056 kB
  • sloc: python: 10,350; makefile: 160
file content (59 lines) | stat: -rw-r--r-- 1,902 bytes parent folder | download | duplicates (2)
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
import sqlalchemy as sa

from sqlalchemy_utils.aggregates import aggregated
from tests import TestCase


class TestAggregatedWithColumnAlias(TestCase):
    def create_models(self):
        class Thread(self.Base):
            __tablename__ = 'thread'
            id = sa.Column(sa.Integer, primary_key=True)

            @aggregated(
                'comments',
                sa.Column('_comment_count', sa.Integer, default=0)
            )
            def comment_count(self):
                return sa.func.count('1')

            comments = sa.orm.relationship('Comment', backref='thread')

        class Comment(self.Base):
            __tablename__ = 'comment'
            id = sa.Column(sa.Integer, primary_key=True)
            thread_id = sa.Column(sa.Integer, sa.ForeignKey('thread.id'))

        self.Thread = Thread
        self.Comment = Comment

    def test_assigns_aggregates_on_insert(self):
        thread = self.Thread()
        self.session.add(thread)
        comment = self.Comment(thread=thread)
        self.session.add(comment)
        self.session.commit()
        self.session.refresh(thread)
        assert thread.comment_count == 1

    def test_assigns_aggregates_on_separate_insert(self):
        thread = self.Thread()
        self.session.add(thread)
        self.session.commit()
        comment = self.Comment(thread=thread)
        self.session.add(comment)
        self.session.commit()
        self.session.refresh(thread)
        assert thread.comment_count == 1

    def test_assigns_aggregates_on_delete(self):
        thread = self.Thread()
        self.session.add(thread)
        self.session.commit()
        comment = self.Comment(thread=thread)
        self.session.add(comment)
        self.session.commit()
        self.session.delete(comment)
        self.session.commit()
        self.session.refresh(thread)
        assert thread.comment_count == 0