404运行FlaskClient测试方法时的响应 [英] 404 Response when running FlaskClient test method

查看:407
本文介绍了404运行FlaskClient测试方法时的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑。我在一个Flask应用程序中使用应用程序工厂,在测试配置下,我的路线总是返回404s。

然而,当我使用Flask-Script并从解释器一切正常,响应回到200.



使用浏览器浏览网址可以正常工作



app / __ init __。py
$ b

  def create_app():
app = Flask (__name__)
返回应用程序

sever1.py p>

  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():
运行单元测试
import unittest
$ unit unit.TestLoader()。discover('tests')
unittest.TextTestRunner(verbosity = 2).run(tests)


if __name__ ==' __main__':
manager.run()

tests / test.py

  #import 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只是它的一个例子


解决方案

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



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



相反,用蓝图注册路由,然后注册蓝图在工厂的应用程序。在测试过程中使用工厂创建一个应用程序。将工厂传给Flask-Script管理器。

  bp =蓝图('myapp',__name__)

@ bp.route('/')
def index():
return'Hello,World!'
$ b $ create_app(config ='dev'):
app = Flask(__ name__)
#config在这里

app.register_blueprint(bp)

返回应用程序

类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()


I'm baffled by this. I'm using an application factory in a Flask application and under the test configuration my routes always return 404s.

However when I use Flask-Script and load the app from the interpreter everything works as expected, the response comes back as 200.

Navigating to the URL with the browser works fine

app/__init__.py

def create_app():
 app = Flask(__name__)
return app

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()

tests/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

解决方案

You're not using the factory pattern correctly. You should use blueprints to collect routes and register them with the app in the factory. (Or use app.add_url_rule in the factory.) Nothing outside the factory should affect the app.

Right now you create an instance of the app and then use that instance to register routes. Then you create a different instance in your tests, which doesn't have the routes registered. Since that instance doesn't have any registered routes, it returns 404 for requests to those urls.

Instead, register your routes with a blueprint, then register the blueprint with the app in the factory. Use the factory to create an app during tests. Pass the factory to the Flask-Script manager. You should not need to push the app context manually.

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()

这篇关于404运行FlaskClient测试方法时的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆