404运行FlaskClient测试方法时的响应

Ter*_*ung 10 python flask

我为此感到困惑.我在Flask应用程序中使用应用程序工厂,在测试配置下,我的路由总是返回404.

但是当我使用Flask-Script并从解释器加载应用程序时,一切都按预期工作,响应返回为200.

使用浏览器导航到URL工作正常

应用程序/ __ init__.py

def create_app():
 app = Flask(__name__)
return app
Run Code Online (Sandbox Code Playgroud)

sever1.py

from flask import Flask
from flask_script import Manager
from app import create_app  

app = create_app()
app_context = app.app_context()
app_context.push()
manager = Manager(app)


@app.route('/')
def index():
 return '<h1>Hello World!</h1>'

@app.route('/user/<name>')
def user(name):
 return '<h1>Hello, %s!</h1>' % name

@manager.command
def test():
 """Run the unit tests"""
 import unittest
 tests = unittest.TestLoader().discover('tests')
 unittest.TextTestRunner(verbosity=2).run(tests)


if __name__ == '__main__':
 manager.run()
Run Code Online (Sandbox Code Playgroud)

测试/ test.py

#imports committed 
def setUp(self):
    self.app = create_app('testing')
    self.app_context = self.app.app_context()
    self.app_context.push() 
    self.client = self.app.test_client()

def test_app_exists(self):
    response = self.client.get('/', follow_redirects=True)
    print(response) #404 :(
    self.assertTrue("Hello World!" in response.get_data()) #this is just an example of how it fails
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 13

您没有正确使用工厂模式.您应该使用蓝图来收集路线并在工厂中将其注册到应用程序中.(或app.add_url_rule在工厂使用.)工厂外的任何内容都不应影响应用程序.

现在,您创建应用程序的实例,然后使用该实例注册路由.然后在测试中创建一个不同的实例,该实例没有注册路由.由于该实例没有任何已注册的路由,因此对于那些URL的请求,它返回404.

而是使用蓝图注册您的路线,然后在工厂中使用应用程序注册蓝图.在测试期间使用工厂创建应用程序.将工厂传递给Flask-Script管理器.您不需要手动推送应用程序上下文.

from flask import Flask, Blueprint
from flask_script import Manager
from unittest import TestCase


bp = Blueprint('myapp', __name__)

@bp.route('/')
def index():
    return 'Hello, World!'

def create_app(config='dev'):
    app = Flask(__name__)
    # config goes here

    app.register_blueprint(bp)

    return app

class SomeTest(TestCase):
    def setUp(self):
        self.app = create_app(config='test')
        self.client = self.app.test_client()

    def test_index(self):
        rv = self.client.get('/')
        self.assertEqual(rv.data, b'Hello, World!')

manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)

if __name__ == '__main__':
    manager.run()
Run Code Online (Sandbox Code Playgroud)