首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建自定义“test”命令以运行Flask应用程序的测试套件

创建自定义“test”命令以运行Flask应用程序的测试套件
EN

Stack Overflow用户
提问于 2018-09-06 21:38:23
回答 1查看 1.4K关注 0票数 1

我们正在使用一些自定义命令扩展Flask-cli。命令test就是其中之一:

代码语言:javascript
复制
# run.py: specified by FLASK_APP
# This is the Flask application object
app = create_app(os.getenv('FLASK_ENV') or 'default')

@app.cli.command()
def test():
    """Run the unit tests."""
        
    tests = unittest.TestLoader().discover('tests')

    test_runner = unittest.TextTestRunner()
    test_runner.run(tests)

然而,一个典型的测试(使用Python的内置单元测试模块)如下所示,它基于描述的here样式。

代码语言:javascript
复制
# some-tests.py: unittest-based test case.
class SomeTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

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

    def test_load(self):
        pass

我在这里显然遇到了一个反模式:我用缺省(development)配置初始化了一个flask对象,因为我需要它用于@app.cli.command()装饰器,这一切都发生在run.py中。然而,一旦我在some-tests.py中运行测试setUp函数,我就必须以某种方式利用testing配置来获取Flask对象,例如,通过使用testing配置重新创建Flask应用程序,就像现在发生的那样。

我希望有一个关于如何实现flask-cli测试命令的指针,在该命令中,只创建一个Flask对象,该对象在各种测试用例中重用,而无需在命令行上运行testing之前明确地将环境设置为flask test

EN

回答 1

Stack Overflow用户

发布于 2019-02-19 01:46:27

我不确定这个答案是否适合你的要求,但这就是我尝试解决这个问题的方式。不幸的是,如果你想在Flask中使用默认的命令行界面,那么你需要调用create_app来调用flask test命令。你能做的就是尝试使用pytest。它允许您创建可跨多个测试用例使用的fixture。例如,在您的tests包中创建名为conftest.py的文件,并声明一些默认的fixture,如下所示:

代码语言:javascript
复制
@pytest.fixture
def app():
    return create_app('testing')


@pytest.fixture
def client(app):
    return app.test_client()


@pytest.fixture
def database(app):
    _db.app = app

    with app.app_context():
        _db.create_all()

    yield _db

    _db.session.close()
    _db.drop_all()

然后在您的测试用例文件中(例如:test_login.py)您可以像这样使用这些装置:

代码语言:javascript
复制
# Notice argument names are the same as name of our fixtures
# You don't need to import fixtures to this file - pytest will  
# automatically recognize fixtures for you
def test_registration(app, client):
    response = client.post(
        '/api/auth/login',
        json={
            'username': 'user1',
            'password': '$dwq3&jNYGu'
        })
    assert response.status_code == 200
    json_data = response.get_json()
    assert json_data['access_token']
    assert json_data['refresh_token']

这种方法最好的地方是您不需要创建setUptearDown方法。然后,您可以为您的应用程序创建test cli命令:

代码语言:javascript
复制
import pytest

@app.cli.command()
def test():
    '''
    Run tests.
    '''
    pytest.main(['--rootdir', './tests'])

并将其命名为flask test

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52205378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档