gpt4 book ai didi

python - 编写集成测试的新手

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:41 25 4
gpt4 key购买 nike

这是我的测试文件:

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

这是完整的堆栈跟踪:

$ nosetests tests/api/client/test_init_views.py
F
======================================================================
FAIL: test_root_route (tests.api.client.test_init_views.TestInitViews)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/dmonsewicz/dev/autoresponders/tests/api/client/test_init_views.py", line 17, in test_root_route
self.assert_template_used('index.html')
File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/flask_testing.py", line 120, in assertTemplateUsed
raise AssertionError("template %s not used" % name)
AssertionError: template index.html not used

----------------------------------------------------------------------
Ran 1 test in 0.012s

FAILED (failures=1)

我是 Python 新手,似乎无法弄清楚这个问题。我想做的就是编写一个简单的测试,命中 / (根路由)端点,并 断言 使用的模板实际上是 index.html

尝试使用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')

最佳答案

您必须运行 pip install flasher 并确保您的 Flask 版本大于 0.6。

看起来您省略了设置 app.config['TESTING'] = True

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

#!/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()

关于python - 编写集成测试的新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24215880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com