简体   繁体   English

适用于Sanic应用程序的python unitests

[英]python unitests for sanic app

I'm building CRUD REST APIs using peewee ORM and sanic(sanic-crud) as app server. 我正在使用peewee ORM和sanic(sanic-crud)作为应用程序服务器来构建CRUD REST API。 Things are working fine. 一切正常。 And I wrote couple of unittest cases for the same. 我也写了几个单元测试用例。

But, I'm facing problem running unittests. 但是,我在运行单元测试时遇到了问题。 The problem is that unittests starts sanic app server and stalled there. 问题在于,单元测试会启动sanic应用服务器并停在那里。 Its not running unittest cases at all. 它根本没有运行单元测试用例。 But when I press Ctrl+C manually then the sanic server gets terminated and unittests execution starts. 但是,当我手动按Ctrl + C时,sanic服务器将终止并开始执行单元测试。 So, it means there should be a way to start sanic server and continue unittests run and terminate server at the end. 因此,这意味着应该有一种方法可以启动sanic服务器并继续运行单元测试,最后结束服务器。

Can someone please me the correct way writting unittest cases for sanic app? 有人可以请我为Sanic应用编写单元测试案例的正确方法吗?

I followed official docs too but no luck. 我也关注官方文档,但没有运气。 http://sanic.readthedocs.io/en/latest/sanic/testing.html http://sanic.readthedocs.io/en/latest/sanic/testing.html

I tried following 我尝试了以下

from restapi import app # the execution stalled here i guess
import unittest
import asyncio
import aiohttp

class AutoRestTests(unittest.TestCase):
    ''' Unit testcases for REST APIs '''

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

    def test_get_metrics_all(self):
        @asyncio.coroutine
        def get_all():
            res = app.test_client.get('/metrics')
            assert res.status == 201
        self.loop.run_until_complete(get_all())

from restapi.py 来自restapi.py

app = Sanic(__name__)
generate_crud(app, [Metrics, ...])
app.run(host='0.0.0.0', port=1337, workers=4, debug=True)

Finally managed to run unittests by moving app.run statement to main block 最终通过将app.run语句移至主块来运行单元测试

# tiny app server starts here
app = Sanic(__name__)
generate_crud(app, [Metrics, ...])
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1337, debug=True)
        # workers=4, log_config=LOGGING)

and

from restapi import app
import json
import unittest

class AutoRestTests(unittest.TestCase):
    ''' Unit testcases for REST APIs '''

    def test_get_metrics_all(self):
        request, response = app.test_client.get('/metrics')
        self.assertEqual(response.status, 200)
        data = json.loads(response.text)
        self.assertEqual(data['metric_name'], 'vCPU')

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM