Testing¶
The functions in this module can be used for testing that the constraints of your models. Each assert function runs SQL UPDATEs that check for the existence of given constraint. Consider the following model:
class User(Base):
__tablename__ = 'user'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String(200), nullable=True)
email = sa.Column(sa.String(255), nullable=False)
user = User(name='John Doe', email='john@example.com')
session.add(user)
session.commit()
We can easily test the constraints by assert_* functions:
from sqlalchemy_utils import (
assert_nullable,
assert_non_nullable,
assert_max_length
)
assert_nullable(user, 'name')
assert_non_nullable(user, 'email')
assert_max_length(user, 'name', 200)
# raises AssertionError because the max length of email is 255
assert_max_length(user, 'email', 300)
assert_min_value¶
assert_max_length¶
-
sqlalchemy_utils.asserts.
assert_max_length
(obj, column, max_length)[source]¶ Assert that the given column is of given max length. This function supports string typed columns as well as PostgreSQL array typed columns.
In the following example we add a check constraint that user can have a maximum of 5 favorite colors and then test this.:
class User(Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) favorite_colors = sa.Column(ARRAY(sa.String), nullable=False) __table_args__ = ( sa.CheckConstraint( sa.func.array_length(favorite_colors, 1) <= 5 ) ) user = User(name='John Doe', favorite_colors=['red', 'blue']) session.add(user) session.commit() assert_max_length(user, 'favorite_colors', 5)
Parameters: - obj – SQLAlchemy declarative model object
- column – Name of the column
- max_length – Maximum length of given column