单元测试unnittest——tornado AsyncHTTPTestCase

最近有一个单元测试的任务,要对tornado实现的服务进行测试,初始考虑Test_Main类继承unittest.TestCase,然后使用多进程起服务,再在服务里面测试

import unittest
from multiprocessing import Process
def func():
    #起服务的函数

class TestMain(unittest.TestCase):
    def test_server(self):
        p_server = Process(target=func,args=())
        p_server.start()
        time.sleep(10)
        sun = p_server.pid
        data = json.dumps(data)
        r = requests.post(url,data=data)
        self.assertEqual(r.json(), "hello world!")
if __name__ == '__main__':
    unittest.main()

后来发现这样写有问题,nosetests无法对多进程给出测试结果。

经过查阅资料,发现tornado自带有单元测试的方法,并且这个方法是继承unittest.TestCase的,所以问题迎刃而解。

参考文档:https://www.tornadoweb.org/en/stable/testing.html ; https://www.jianshu.com/p/fb7e583cb6dd

具体代码如下:

from tornado.testing import AsyncHTTPTestCase
import unittest
class TestTornado(AsyncHTTPTestCase):
    def get_app(self):
        app = MyApplication([
            (r'/test', BaseHandler(需要启的服务)),
        ])
        return app
     def test_BaseHandler(self):
        # 测试正常输入文本
        data = json.dumps({"text": ""})
        response = self.fetch("/test",method="POST",body=data)
        self.assertEqual(eval(response.body)["data"], "test")
        self.assertEqual(eval(response.body)["code"], 200)
if __name__ == '__main__':
    unittest.main()

附上nosetest的脚本写法

首先要安装 pip install nose-cov
脚本:
#!/bin/bash
nosetests --with-cov --cov-report term --cov-report html --cov . test/

这样运行脚本就把test目录下所有的单元测试文件全部测试一遍,生成测试结果在htmlcov目录下,从htmlcov/index.html进入

原文地址:https://www.cnblogs.com/peng-yuan/p/15181974.html