如何测试自定义Flask错误页面?

bro*_*oox 6 python flask

我正在尝试在flask中测试自定义错误页面(404在本例中).

我已经定义了我的自定义404页面:

@app.errorhandler(404)
def page_not_found(e):
    print "Custom 404!"
    return render_template('404.html'), 404
Run Code Online (Sandbox Code Playgroud)

当在浏览器中访问未知页面时,这非常有效(我Custom 404!在stdout中看到并且我的自定义内容可见).但是,当尝试触发404 via unittestnose,标准/服务器404页面呈现.我没有收到日志消息或我试图测试的自定义内容.

我的测试用例定义如下:

class MyTestCase(TestCase):
    def setUp(self):
        self.app = create_app()
        self.app_context = self.app.app_context()
        self.app.config.from_object('config.TestConfiguration')
        self.app.debug = False # being explicit to debug what's going on...
        self.app_context.push()
        self.client = self.app.test_client()

    def tearDown(self):
        self.app_context.pop()

    def test_custom_404(self):
        path = '/non_existent_endpoint'
        response = self.client.get(path)
        self.assertEqual(response.status_code, 404)
        self.assertIn(path, response.data)
Run Code Online (Sandbox Code Playgroud)

app.debug明确设置了False我的测试应用程序.还有其他我必须明确设置的东西吗?

bro*_*oox 6

在用新鲜的眼睛重新审视之后,很明显问题出在我的应用程序初始化而不是我的测试/配置中.我的应用程序__init__.py基本上是这样的:

def create_app():
    app = Flask(__name__)
    app.config.from_object('config.BaseConfiguration')
    app.secret_key = app.config.get('SECRET_KEY')
    app.register_blueprint(main.bp)
    return app

app = create_app()

# Custom error pages

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
Run Code Online (Sandbox Code Playgroud)

请注意,错误处理程序连接到@app外面create_app(),我打电话我的方法TestCase.setUp()的方法.

如果我只是将错误处理程序移动到create_app()方法中,一切正常......但感觉有点粗糙?也许?

def create_app():
    app = Flask(__name__)
    app.config.from_object('config.BaseConfiguration')
    app.secret_key = app.config.get('SECRET_KEY')
    app.register_blueprint(main.bp)

    # Custom error pages
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    return app
Run Code Online (Sandbox Code Playgroud)

这最终回答了我的问题,并解决了我的问题,但我喜欢关于如何不同地注册这些错误处理程序的其他想法.