File: test_hybrid_properties.py

package info (click to toggle)
python-sqlalchemy-utils 0.41.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,252 kB
  • sloc: python: 13,566; makefile: 141
file content (78 lines) | stat: -rw-r--r-- 1,954 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import pytest
import sqlalchemy as sa
from sqlalchemy.ext.hybrid import hybrid_property

from sqlalchemy_utils import generic_relationship


@pytest.fixture
def User(Base):
    class User(Base):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)
    return User


@pytest.fixture
def UserHistory(Base):
    class UserHistory(Base):
        __tablename__ = 'user_history'
        id = sa.Column(sa.Integer, primary_key=True)

        transaction_id = sa.Column(sa.Integer, primary_key=True)
    return UserHistory


@pytest.fixture
def Event(Base):
    class Event(Base):
        __tablename__ = 'event'
        id = sa.Column(sa.Integer, primary_key=True)

        transaction_id = sa.Column(sa.Integer)

        object_type = sa.Column(sa.Unicode(255))
        object_id = sa.Column(sa.Integer, nullable=False)

        object = generic_relationship(
            object_type, object_id
        )

        @hybrid_property
        def object_version_type(self):
            return self.object_type + 'History'

        @object_version_type.expression
        def object_version_type(cls):
            return sa.func.concat(cls.object_type, 'History')

        object_version = generic_relationship(
            object_version_type, (object_id, transaction_id)
        )
    return Event


@pytest.fixture
def init_models(User, UserHistory, Event):
    pass


class TestGenericRelationship:

    def test_set_manual_and_get(self, session, User, UserHistory, Event):
        user = User(id=1)
        history = UserHistory(id=1, transaction_id=1)
        session.add(user)
        session.add(history)
        session.commit()

        event = Event(transaction_id=1)
        event.object_id = user.id
        event.object_type = type(user).__name__
        assert event.object is None

        session.add(event)
        session.commit()

        assert event.object == user
        assert event.object_version == history