简介:微服务是一种云原生架构方法,其中单个应用程序由许多松散耦合且可独立部署的较小组件或服务组成。这些服务通常有自己的堆栈,包括数据库和数据模型;通过REST API,事件流和消息代理的组合相互通信;它们是按业务能力组织的,分隔服务的线通常称为有界上下文。
微服务的优势:简言之方便高扩展,方便部署
1、可以更轻松地更新代码。
2、团队可以为不同的组件使用不同的堆栈。
3、组件可以彼此独立地进行缩放,从而减少了因必须缩放整个应用程序而产生的浪费和成本,因为单个功能可能面临过多的负载。
怎么测:细分为测试的内容和测试的方法。
微服务的测试内容:
服务独立测试:功能、数据检查、性能
服务间一致性测试:正常场景、异常场景
系统集成测试:功能、数据检查、性能
服务幂等测试:一个服务、服务之间
测试微服务的方法:
1、间接测试:各服务提供虚拟的http接口,使服务测试转为http接口测试,
一般通过web框架进行转发。
2、直接测试:针对每个服务,专门写一个client进行访问测试,python中可以通过使用grpc的ProtoBuf来辅助生成client进行访问。
微服务搭建范例:
间接测试范例:
对应的微服务:
from nameko.rpc import rpc
import datetime
class HelloService:
name = "hello_service"
@rpc
def hello(self, name):
return "hello.{}.{}".format(name, str(datetime.datetime.now())[:-7])
微服务封装转http接口:
from sanic import Sanic
from nameko.standalone.rpc import ClusterRpcProxy
from sanic.response import json
app = Sanic(__name__)
config_mq = {'AMQP_URI': "amqp://guest:guest@127.0.0.1"}
@app.get('/hello')
async def hello_world(request):
with ClusterRpcProxy(config_mq) as rpc:
data = request.args
result = rpc.hello_service.hello(name=data["name"][0])
return json({"code": 200, "result": result})
if __name__ == '__main__':
app.run(host="127.0.0.1", port=3033, auto_reload=True)
微服务转http接口的单元测试用例:
# -*-coding:utf-8 -*-
import unittest
import requests
from logger import log
class TestHello(unittest.TestCase):
def test_hello_cn(self):
# 中文
name = "冰墩墩"
res = requests.get(url=f"http://127.0.0.1:3033/hello?name={name}")
log.info(f"cn - res.text:{res.text}")
self.assertIn(f"hello.{name}.", res.text)
def test_hello_en(self):
# 英文
name = "lily"
res = requests.get(url=f"http://127.0.0.1:3033/hello?name={name}")
log.info(f"en - res.text:{res.text}")
self.assertIn(f"hello.{name}.", res.text)
def test_hello_punctuation(self):
# 标点符号
name = "$%^"
res = requests.get(url=f"http://127.0.0.1:3033/hello?name={name}")
log.info(f"punctuation - res.text:{res.text}")
self.assertIn(f"hello.{name}.", res.text)
if __name__ == "__main__":
unittest.main()
执行结果:
图形化展示:
如按范例Sanic:JSON - 中文ASCII,请参考:
https://www.jianshu.com/p/0369b4c74bba
这样我们通过测试http接口实现了对 hello_service 这个微服务的间接测试。post,put,delete接口同理。
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!