Flask-testing 数据库在提交时不保存

Flask-testing database not saving on commit

我有以下 flask 工厂目录设置:

server/
    __init__.py
    .env
    wsgi.py
    app/
        __init__.py
        config/
            __init__.py
            config.py
            test_config.py
        models/
            __init__.py
            sku.py
        views/
            __init__.py
            sku_bp.py
    tests/
        __init__.py
        test_sku_view.py

create_app方法定义在server/app/__init__.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app(config):
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object(config)
    db.init_app(app)
    with app.app_context()
        from app.views.sku_bp import sku_bp
        app.register_blueprint(sku_bp, url_prefix='/api/sku/')
        return app

而模型(server/app/models/sku.py)和蓝图(server/app/views/sku_bp.py)由:

from app import db

class SKU(db.Model):
    __tablename__ = 'sku'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    def to_dict(self):
        return {'id': self.id, 'name': self.name}

from flask import Blueprint, jsonify
from app.models.sku import SKU

sku_bp = Blueprint('sku_bp', __name__)

@sku_bp.route('/get/')
@sku_bp.route('/get/<string:sku_name>')
def get(sku_name: str):
    try:
        sku = SKU.query.filter_by(name=sku_name).first()
    except Exception as e:
        return jsonify({'Error': f'{e}'}), 404
    else:
        return jsonify(sku.to_dict()), 200

分别

我正在尝试 server/tests/test_sku_view.py 中的计算单元测试,如下所示:

import unittest
import sys
sys.path.append('./')
from flask_testing import TestCase
import pandas as pd
from app.models.sku import SKU
from app.config.test_config import TestConfig
from app import create_app, db

class TestSKUView(TestConfig, TestCase):

    def create_app(self):
        return create_app(TestConfig)

    def setUp(self):
        db.create_all()
        df_sku = pd.read_csv('tests/io/test.sku.csv')
        for index, row in df_sku.iterrows():
            sku = SKU(**row)
        db.session.commit()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_sku_view(self):
        skus = SKU.query.all()
        print(f'skus = {skus}')

def main():
    unittest.main()

if __name__ == '__main__':
    main()

server/tests/io/test.sku.csv 文件如下所示:

id,name
1,'A'
2,'B'

并且 server/app/config/test_config.py 文件如下所示:

class TestConfig():
    DEBUG = True
    TESTING = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'

我使用 python3.7 tests/test_sku_view.pyserver/ 目录中调用此脚本。 但是,当我打印查询数据库的 skus 列表时,没有返回任何内容,即 skus = []。请问我哪里错了?我知道 sku 正在正确生成,但它似乎没有在提交时保存在数据库中...

你需要在提交之前添加一个db.session.add(sku),显然是在for循环中:-)