Skip to main content
 首页 » 编程设计

python之flask 测试之为什么测试失败

2024年10月24日9java哥

我正在尝试为一个简单的 Flask 应用程序编写测试。项目结构如下:

app/ 
    static/ 
    templates/ 
    forms.py 
    models.py 
    views.py 
migrations/ 
config.py 
manage.py 
tests.py 

测试.py

import unittest 
from app import create_app, db 
from flask import current_app 
from flask.ext.testing import TestCase 
 
class AppTestCase(TestCase): 
    def create_app(self): 
        return create_app('test_config') 
 
    def setUp(self): 
        db.create_all() 
 
    def tearDown(self): 
        db.session.remove() 
        db.drop_all() 
 
    def test_hello(self): 
        response = self.client.get('/') 
        self.assert_200(response) 

应用/初始化.py

# app/__init__.py 
 
from flask import Flask 
from flask.ext.sqlalchemy import SQLAlchemy 
from config import config 
 
db = SQLAlchemy() 
 
def create_app(config_name): 
    app = Flask(__name__) 
    app.config.from_object(config[config_name]) 
    db.init_app(app) 
    return app 
 
app = create_app('default') 
 
from . import views 

当我启动测试时,test_hello 失败,因为 response.status_code 是 404。请告诉我,我该如何解决它?看来,该应用程序实例对 views.py 中的 View 函数一无所知。如果需要完整代码,可以找到here

请您参考如下方法:

您的 views.py 文件将路由安装在您的 __init__.py 文件中创建的 app 中。

您必须将这些路由绑定(bind)到您在 create_app 测试方法中创建的应用。

我建议你反转依赖关系。而不是 views.py 导入您的代码,您可以制作一个 init_app 从您的 __init__.py 或测试文件中导入和调用.

# views.py 
def init_app(app): 
    app.add_url_rule('/', 'index', index) 
    # repeat to each route 

你可以做得更好,使用 Blueprint .

def init_app(app): 
    app.register_blueprint(blueprint) 

这样,您的测试文件只需导入此 init_app 并将蓝图绑定(bind)到测试 app 对象。