相关疑难解决方法(0)

使用 url_for 函数为 Flask 测试客户端生成 URL

我正在尝试使用 pytest 为 Flask 应用程序编写单元测试。我有一个应用工厂:

def create_app():
    from flask import Flask
    app = Flask(__name__)
    app.config.from_object('config')
    import os
    app.secret_key = os.urandom(24)
    from models import db
    db.init_app(app)
    return app
Run Code Online (Sandbox Code Playgroud)

和一个测试类:

class TestViews(object):

    @classmethod
    def setup_class(cls):
        cls.app = create_app()
        cls.app.testing = True
        cls.client = cls.app.test_client()

    @classmethod
    def teardown_class(cls):
        cls.app_context.pop()

    def test_create_user(self):
        """
        Tests the creation of a new user.
        """
        view = TestViews.client.get(url_for('create_users')).status_code == 200
Run Code Online (Sandbox Code Playgroud)

但是当我运行我的测试时,我收到以下错误:

RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed …
Run Code Online (Sandbox Code Playgroud)

python unit-testing pytest flask

7
推荐指数
2
解决办法
4176
查看次数

标签 统计

flask ×1

pytest ×1

python ×1

unit-testing ×1