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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
import pytest
import sqlalchemy as sa
from sqlalchemy_utils import get_class_by_table
class TestGetClassByTableWithJoinedTableInheritance:
@pytest.fixture
def Entity(self, Base):
class Entity(Base):
__tablename__ = 'entity'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
type = sa.Column(sa.String)
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': 'entity'
}
return Entity
@pytest.fixture
def User(self, Entity):
class User(Entity):
__tablename__ = 'user'
id = sa.Column(
sa.Integer,
sa.ForeignKey(Entity.id, ondelete='CASCADE'),
primary_key=True
)
__mapper_args__ = {
'polymorphic_identity': 'user'
}
return User
def test_returns_class(self, Base, User, Entity):
assert get_class_by_table(Base, User.__table__) == User
assert get_class_by_table(
Base,
Entity.__table__
) == Entity
def test_table_with_no_associated_class(self, Base):
table = sa.Table(
'some_table',
Base.metadata,
sa.Column('id', sa.Integer)
)
assert get_class_by_table(Base, table) is None
class TestGetClassByTableWithSingleTableInheritance:
@pytest.fixture
def Entity(self, Base):
class Entity(Base):
__tablename__ = 'entity'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
type = sa.Column(sa.String)
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': 'entity'
}
return Entity
@pytest.fixture
def User(self, Entity):
class User(Entity):
__mapper_args__ = {
'polymorphic_identity': 'user'
}
return User
def test_multiple_classes_without_data_parameter(self, Base, Entity, User):
with pytest.raises(ValueError):
assert get_class_by_table(
Base,
Entity.__table__
)
def test_multiple_classes_with_data_parameter(self, Base, Entity, User):
assert get_class_by_table(
Base,
Entity.__table__,
{'type': 'entity'}
) == Entity
assert get_class_by_table(
Base,
Entity.__table__,
{'type': 'user'}
) == User
def test_multiple_classes_with_bogus_data(self, Base, Entity, User):
with pytest.raises(ValueError):
assert get_class_by_table(
Base,
Entity.__table__,
{'type': 'unknown'}
)
|