编写集成测试的新手

2024-04-26 23:44:05 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的测试文件:

from flask import Flask
from flask.ext.testing import TestCase


class TestInitViews(TestCase):

    render_templates = False

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        return app

    def test_root_route(self):
        self.client.get('/')
        self.assert_template_used('index.html')

以下是完整的堆栈跟踪:

^{pr2}$

我是Python的新手,好像搞不懂这个。我所要做的就是编写一个简单的测试,它命中/(根路由)端点和{},该模板实际上是{}

尝试使用LiveServerTestCase

from flask import Flask
from flask.ext.testing import LiveServerTestCase


class TestInitViews(LiveServerTestCase):

    render_templates = False

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['LIVESERVER_PORT'] = 6765

        return app

    def setUp(self):
        self.app = self.app.test_client()

    def test_root_route(self):
        res = self.app.get('/')

        print(res)

        self.assert_template_used('index.html')

我使用的是Flask-Testing版本0.4,由于某些原因,LiveServerTestCase在我的导入中不存在

工作代码

from flask import Flask
from flask.ext.testing import TestCase
from api.client import blueprint


class TestInitViews(TestCase):

    render_templates = False

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True

        app.register_blueprint(blueprint)

        return app

    def test_root_route(self):
        res = self.client.get('/')
        self.assert_template_used('index.html')

Tags: fromtestimportselfclientconfigappflask
1条回答
网友
1楼 · 发布于 2024-04-26 23:44:05

你必须运行pip install blinker并确保你的烧瓶版本大于.6。在

看来你省略了设置应用程序配置['TESTING']=真

我能够运行以下测试来验证断言是否为真:

#!/usr/bin/python

import unittest
from flask import Flask
from flask.ext.testing import TestCase
from flask import render_template


class MyTest(TestCase):

  def create_app(self):
    app = Flask(__name__)
    app.config['TESTING'] = True

    @app.route('/')
    def hello_world():
      return render_template('index.html')
    return app

  def test_root_route(self):
    self.client.get('/')
    self.assert_template_used('index.html')

if __name__ == '__main__':
  unittest.main()

相关问题 更多 >