0

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

为什么 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
4

0 回答 0