功能测试

微服务项目的功能测试是:通过发送的http请求并断言http响应,所有的测试与发布的api进行交互。

开发者主要关注两类最重要的功能测试:

  • 验证应用的行为和期望一致的测试
  • 确保异常行为已被修复且不再发生的测试

Flask中的FlaskClient类构建请求:

import unittest
import json
from flask_basic import app as tested_app

class TestApp(unittest.TestCase):
    def test_help(self):
        # creating a client to interact with the app
        app = tested_app.test_client()

        # calling /api/ endpoint
        hello = app.get('/api')

        # asserting the body
        body = json.loads(str(hello.data, 'utf8'))
        self.assertEqual(body['Hello'], 'World!')

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

FlaskClient类对每个http动词都有一个方法,方法会返回响应对象,然后这些对象可以被测试用来对结果进行验证。再上例中,我妈使用的是.get()方法获得响应对象。

在Flask类中有一个testing标志,可用它将异常传递到测试中,但有时倾向于不按照默认方式从应用得到返回值。比如为让api保持一致,要确保把返回体中的5xx和4xx错误的转换成json格式。

下面的例子:调用/api/会产生一个异类,通过结构化的json返回体,测试要确保客户端在test_raise()中获取正确的500信息。

test_proper_404()测试方法对一个不存在的路径进行了相似的校验:

import unittest
import json
from flask_error import app as tested_app

_404 = ('The requested URL was not found on the server. ' 'If you entered the URL manually please check your ' 'spelling and try again.')

class TestApp(unittest.TestCase):
    def setUp(self):
        # creating a client to interact with the app
        self.app = tested_app.test_client()

    def test_raise(self):
        # this won't raise a Python exception but return a 500
        hello = self.app.get('/api')
        body = json.loads(str(hello.data, 'utf8'))
        self.assertEqual(body['code'], 500)

    def test_proper_404(self):
        # calling a non existing endpoint
        hello = self.app.get('/dwdwqqwdwqd')

        # yeah it's not there
        self.assertEqual(hello.status_code, 404)

        # but we still get a nice JSON body
        body = json.loads(str(hello.data, 'utf8'))
        self.assertEqual(body['code'], 404)
        self.assertEqual(body['message'], '404: Not Found')
        self.assertEqual(body['description'], _404)

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

 

posted @ 2022-11-16 14:25  乔小生1221  阅读(21)  评论(0编辑  收藏  举报