我目前正在为Flask中基于连接的API编写验收测试。 作为Flask用户,我习惯于使用py.test和pip模块测试东西: pytest-flask和/或Flask_Testing
两者都有帮助程序来提供一些配置并在需要时启动实时服务器。 这似乎不适用于由Connexion创建的Flask应用。 这也使得几乎不可能使用Flask的配置系统和url_for()方法。
有没有办法使用测试插件或创建更符合Flask的应用程序?
可能与#489和#364相关
这就是我现在使用的方式:
我在启动应用程序的地方添加了一个构造,以便它可以在需要时返回flask应用程序,例如:
def run(actually_run=True):
app = connexion.App(__name__, specification_dir='./swagger/')
api = app.add_api(swagger_file)
if actually_run:
app.run(host=HOST, port=PORT, ...)
else:
return app.app
然后,可以从需要它的测试中启动实时服务器:
import requests
from flask_testing import LiveServerTestCase
from main import run_application
class MyTest(LiveServerTestCase):
def create_app(self):
app = run(False)
return app
def test_server_is_up_and_running(self):
response = requests.get(f"{self.get_server_url()}/an_endpoint_for_your_api")
self.assertEqual(response.status_code, 200)
我过去使用WebTest
库( pip install webtest
)有很好的经验: https :
它将在WSGI级别上测试您的应用程序,它具有一些优点:
connexion/Flask
并且如果您决定使用gevent
或tornado
或任何其他兼容WSGI的方法,则可以继续使用将来的后端。WebTest
的文档非常广泛,涵盖了所有主要的用例。 快速入门示例:
from webtest import TestApp
import unittest
from main import app # the connexion Flask app object
class TestEndpoints(unittest.TestCase):
# could also be set up globally outside of this class
<strong i="20">@classmethod</strong>
def setUpClass(cls):
cls.app = TestApp(app)
def test_some_endpoint(self):
response = self.app.get('/some/endpoint').json()
expected_response = dict(foo='bar', baz='buz')
self.assertDictEqual(response, expected_response)
编写控制器的单元测试是否有任何更新?
我发现此存储库对于进行测试连接非常有帮助: https :
(它也使用WebTest,如@dirkschneemann所建议)
可能有一种方法可以使用flask的内部测试客户端来进行测试。 我创建了一个PR作为示例:#957
让我知道您的想法,或者如果我缺少您想要的东西。
最有用的评论
我过去使用
WebTest
库(pip install webtest
)有很好的经验: https :它将在WSGI级别上测试您的应用程序,它具有一些优点:
connexion/Flask
并且如果您决定使用gevent
或tornado
或任何其他兼容WSGI的方法,则可以继续使用将来的后端。WebTest
的文档非常广泛,涵盖了所有主要的用例。 快速入门示例: