Files
deb-python-sqlalchemy-utils/tests/functions/test_get_class_by_table.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

101 lines
2.8 KiB
Python

import pytest
import sqlalchemy as sa
from sqlalchemy_utils import get_class_by_table
class TestGetClassByTableWithJoinedTableInheritance(object):
@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(object):
@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'}
)