SQLAlchemy接受所有内容,如不同的数据类型,空字符串,长度更长的字符串

时间:2018-06-09 16:08:37

标签: python sqlalchemy flask-sqlalchemy flask-testing

我正在使用Flask和Flask SQLAlchemy和Flask Test。我定义了一个带有最大长度为100的字符串列的示例模型。我认为如果我尝试插入长度大于100的字符串,我应该得到一个异常.SQLAlchemy甚至允许我插入其他数据类型,如int。即使我已将此列定义为string类型。或者,如果我尝试插入一个空字符串,我也不会引发异常。虽然我已将列设置为不可为空。

为什么SQLAlchemy只接受所有内容。难道不应该至少引发一个例外吗?

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

0 个答案:

没有答案