I am using Flask and Flask SQLAlchemy and Flask Test. I define an example model with a string column with max length of 100. I thought I should get an exception if I try to insert a string with a length bigger than 100. SQLAlchemy even allows me to insert other data types like an int. Even if I have defined this column to be of type string. Or if I try to insert an empty string I also do not raise an Exception. Although I have set the column not to be nullable.
Why does SQLAlchemy just accepts everything. Shouldn't there be at least one exception raised?
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_testing import TestCase
db = SQLAlchemy()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
db.init_app(app)
return app
class Example(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
class MyTest(TestCase):
def create_app(self):
return create_app(self)
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_example_that_should_work(self):
example = Example(name="ABC")
db.session.add(example)
db.session.commit()
self.assertEqual(Example.query.count(), 1)
def test_example__do_not_insert_strings_of_bigger_size(self):
example = Example(name="ABC"*100)
db.session.add(example)
db.session.commit()
self.assertEqual(Example.query.count(), 0) # AssertionError: 1 != 0
def test_example_do_not_insert_different_data_type(self):
example = Example(name=42)
db.session.add(example)
db.session.commit()
self.assertEqual(Example.query.count(), 0) # AssertionError: 1 != 0
def test_example_do_not_insert_nullable(self):
example = Example(name="")
db.session.add(example)
db.session.commit()
self.assertEqual(Example.query.count(), 0) # AssertionError: 1 != 0