gRPC Mock Server

article/2025/9/18 3:45:34

powermock

PowerMock是一个Mock Server的实现,它同时支持HTTP与gRPC协议接口的Mock,并提供了灵活的插件功能。
这个工具面向于前后端、测试等对有接口Mock需求的开发人员,也可以作为一个通用的Mock服务,部署在网关架构或API管理平台中,实现降级、接口Mock等功能。

  • PowerMock
    • 功能
    • 示例
      • 一、较为高级的用法
        • 1. 条件场景一
        • 2. 条件场景二
      • 二、从Hello World开始吧
        • 1. 先Mock一个HTTP接口
        • 2. 再mock一个gRPC接口
    • 安装
      • 通过Go安装
      • 开箱即用版本
      • 通过Makefile编译

项目地址

项目地址:PowerMock

功能

作为一个Mock Server,PowerMock具有以下的核心功能:

  1. 支持 HTTP协议gRPC协议 接口的Mock。
  2. 支持配置 Javascript 等脚本语言来动态生成响应。
  3. 支持对一个接口配置多种响应,并按照条件进行区分。
  4. 匹配条件支持多种运算符(AND/OR/>/</=等)。
  5. 支持返回静态数据以及 特定领域的随机数据
  6. 支持 插件 功能,可以通过编写插件实现其他匹配或Mock引擎。
  7. 同时提供HTTP与gRPC接口,可以动态对MockAPI进行 增删改查
  8. 开箱即用的Redis存储,并支持自由拓展其他存储引擎,比如MySQL、etcd。
  9. 同时支持 windows / darwin / linux 的 32 位 与 64 位。
  10. 语言无关,任何使用HTTP协议或gRPC协议的项目均可以使用本工具。

示例

一、较为高级的用法

本示例可以在 示例代码 找到对应资料
本示例必须使用v8版本的powermock,才能完整支持Javascript的功能

以下面这份配置为示例:

uniqueKey: "advanced_example"
path: "/examples.greeter.api.Greeter/Hello"
method: "POST"
cases:- condition:simple:items:- operandX: "$request.header.uid"operator: "<="operandY: "1000"response:simple:header:x-unit-id: "3"x-unit-region: "sh"trailer:x-api-version: "1.3.2"body: |{"timestamp": "1111", "message": "This message will only be returned when uid <= 1000", "amount": "{{ $mock.price }}"}- condition:simple:items:- operandX: "$request.header.uid"operator: ">"operandY: "1000"response:script:lang: "javascript"content: |(function(){function random(min, max){return parseInt(Math.random()*(max-min+1)+min,10);}return {code: 0,header: {"x-unit-id": (request.header["uid"] % 5).toString(),"x-unit-region": "bj",},trailer: {"x-api-version": "1.3.2",},body: {timestamp: Math.ceil(new Date().getTime() / 1000),message: "this message is generated by javascript, your uid is: " + request.header["uid"],amount: random(0, 5000),},}})()

这份配置定义了一个MockAPI,用于匹配所有路径为 /examples.greeter.api.Greeter/Hello,方法为 POST 的请求,它包含了两个场景,能够实现这样的效果:

1. 条件场景一

当请求 Header 中的 uid <= 1000 时:

  • Response Header 中写入:
x-unit-id: "3"
x-unit-region: "sh"
  • Response Trailer 中写入:
x-api-version: "1.3.2"
  • Response Body 中写入:
{"timestamp": "1111", "message": "This message will only be returned when uid <= 1000", "amount": "{{ $mock.price }}"}

其中的 {{ $mock.price }} 是魔法变量,用于返回一个随机的价格数据。最终,客户端收到的 Response Body 类似于:

{"timestamp": "1111","message": "This message will only be returned when uid <= 1000","amount": 7308.4
}

2. 条件场景二

当请求 Header 中的 uid > 1000 时,通过执行以下Javascript脚本返回响应:

(function(){function random(min, max){return parseInt(Math.random()*(max-min+1)+min,10);}return {code: 0,header: {"x-unit-id": (request.header["uid"] % 5).toString(),"x-unit-region": "bj",},trailer: {"x-api-version": "1.3.2",},body: {timestamp: Math.ceil(new Date().getTime() / 1000),message: "this message is generated by javascript, your uid is: " + request.header["uid"],amount: random(0, 5000),},}
})()

在这个脚本中,根据请求的 Header,以及一些内置或自定义函数来生成了响应的code、header、trailer与body。
最终客户端收到的响应体类似于:

{"timestamp": 1622093545,"message": "this message is generated by javascript, your uid is: 2233","amount": 314
}

它描述了一个相对复杂的场景,当然可能你的需求比较简单,实战的话,我们先从Hello World开始吧!

二、从Hello World开始吧

本示例可以在 示例代码 找到对应资料

首先,创建一个配置文件:

log:pretty: truelevel: debug
grpcmockserver:enable: trueaddress: 0.0.0.0:30002protomanager:protoimportpaths: [ ]protodir: ./apis
httpmockserver:enable: trueaddress: 0.0.0.0:30003
apimanager:grpcaddress: 0.0.0.0:30000httpaddress: 0.0.0.0:30001
pluginregistry: { }
plugin:simple: { }grpc: { }http: { }script: { }redis:enable: falseaddr: 127.0.0.1:6379password: ""db: 0prefix: /powermock/

将编译好的PowerMock与上面创建好的配置文件放到同一个目录中,像下面这样:

➜ ls -alh
total 45M
drwxrwxrwx 1 storyicon storyicon 4.0K May 27 14:18 .
drwxrwxrwx 1 storyicon storyicon 4.0K May 24 11:43 ..
-rwxrwxrwx 1 storyicon storyicon  546 May 27 14:16 config.yaml
-rwxrwxrwx 1 storyicon storyicon  45M May 27 14:18 powermock

然后执行

➜ ./powermock serve --config.file config.yaml

如果没有端口冲突的话,你应该已经可以看到服务运行起来了!

1. 先Mock一个HTTP接口

在上面的目录下,创建一个名为 apis.yaml 的文件:

uniqueKey: "hello_example_http"
path: "/hello"
method: "GET"
cases:- response:simple:header:x-unit-id: "3"x-unit-region: "sh"trailer:x-api-version: "1.3.2"body: |hello world!

然后运行:

➜ ./powermock load --address=127.0.0.1:30000 apis.yaml
2:32PM INF start to load file component=main file=load.go:59
2:32PM INF mock apis loaded from file component=main count=1 file=load.go:64
2:32PM INF start to save api component=main file=load.go:76 host= method=GET path=/hello uniqueKey=hello
2:32PM INF succeed! component=main file=load.go:89

这样,我们描述的MockAPI就创建起来了。

通过 curl 或者你的浏览器请求 http://127.0.0.1:30003/hello,可以看到返回给我们 hello world 了!

➜ curl http://127.0.0.1:30003/hello -i
HTTP/1.1 200 OK
Content-Type: application/json
X-Unit-Id: 3
X-Unit-Region: sh
Date: Thu, 27 May 2021 06:36:28 GMT
Content-Length: 12hello world!

2. 再mock一个gRPC接口

在上面的目录中,创建一个 apis 目录,使整个目录结构像下面这样:

➜  ls -alh
total 45M
drwxrwxrwx 1 storyicon storyicon 4.0K May 27 14:42 .
drwxrwxrwx 1 storyicon storyicon 4.0K May 27 14:37 ..
drwxrwxrwx 1 storyicon storyicon 4.0K May 27 14:23 apis
-rwxrwxrwx 1 storyicon storyicon 1.8K May 27 14:32 apis.yaml
-rwxrwxrwx 1 storyicon storyicon  546 May 27 14:16 config.yaml
-rwxrwxrwx 1 storyicon storyicon  45M May 27 14:18 powermock

在 apis 目录中创建我们的 greeter.proto:

syntax = "proto3";package examples.greeter.api;
option go_package = "github.com/bilibili-base/powermock/examples/helloWorld/apis;apis";service Greeter {rpc Hello(HelloRequest) returns (HelloResponse);
}message HelloRequest {string message = 2;
}message HelloResponse {string message = 2;
}

现在整个目录结构像这样:

.
├── apis
│   └── greeter.proto
├── apis.yaml
├── config.yaml
└── powermock

重新运行我们的 powermock 来加载我们新写的proto文件:

➜ ./powermock serve --config.file config.yaml
2:55PM INF starting load proto from: ./apis component=main.gRPCMockServer.protoManager file=service.go:102
2:55PM INF api loaded component=main.gRPCMockServer.protoManager file=service.go:131 name=/examples.greeter.api.Greeter/Hello

在启动日志中可以看到我们新创建的 proto 文件已经被加载到 PowerMock 中了。

将我们的 apis.yaml 文件修改成下面的内容:

uniqueKey: "hello_example_http"
path: "/hello"
method: "GET"
cases:- response:simple:header:x-unit-id: "3"x-unit-region: "sh"trailer:x-api-version: "1.3.2"body: |hello world!---uniqueKey: "hello_example_gRPC"
path: "/examples.greeter.api.Greeter/Hello"
method: "POST"
cases:- response:simple:header:x-unit-id: "3"x-unit-region: "sh"trailer:x-api-version: "1.3.2"body: |{"message": "hello world!"}

可以看到,里面添加了一个名为 “hello_example_gRPC” 的 MockAPI,我们通过下面的命令装载它:

➜ powermock load --address=127.0.0.1:30000  apis.yaml
3:06PM INF start to load file component=main file=load.go:59
3:06PM INF mock apis loaded from file component=main count=2 file=load.go:64
3:06PM INF start to save api component=main file=load.go:76 host= method=GET path=/hello uniqueKey=hello_example_http
3:06PM INF start to save api component=main file=load.go:76 host= method=POST path=/examples.greeter.api.Greeter/Hello uniqueKey=hello_example_gRPC
3:06PM INF succeed! component=main file=load.go:89

这样,我们的MockAPI就被添加到PowerMock中了。

如果你的环境中有BloomRPC之类的工具的话,可以先通过BloomRPC加载 greeter.proto,然后调用 127.0.0.1:30002

在这里插入图片描述

可以看到,调用成功返回了 “hello world”。
如果使用编程语言进行调用的话,以 golang 为例,通过下面的代码调用 PowerMock:

func main() {fmt.Println("starting call mock server")conn, err := grpc.Dial("127.0.0.1:30002", grpc.WithInsecure())if err != nil {panic(err)}client := apis.NewGreeterClient(conn)var header, trailer metadata.MDstartTime := time.Now()resp, err := client.Hello(context.TODO(), &apis.HelloRequest{Message: "hi",}, grpc.Header(&header), grpc.Trailer(&trailer))if err != nil {panic(err)}fmt.Printf("[elapsed] %d ms \r\n", time.Since(startTime).Milliseconds())fmt.Printf("[headers] %+v \r\n", header)fmt.Printf("[trailer] %+v \r\n", trailer)fmt.Printf("[response] %+v \r\n", resp.String())
}

日志输出是这样的:

starting call mock server
[elapsed] 2 ms
[headers] map[content-type:[application/grpc] x-unit-id:[3] x-unit-region:[sh]]
[trailer] map[x-api-version:[1.3.2]]
[response] message:"This message will only be returned when uid <= 1000"

可以看到,我们的接口被成功Mock出来了!

安装

通过Go安装

安装普通版本,无Javascript支持:

go install github.com/bilibili-base/powermock/cmd/powermock

安装V8版本,支持Javascript:

go install github.com/bilibili-base/powermock/cmd/powermock-v8

开箱即用版本

如果你没有定制插件的需求,开箱即用版本 非常适合你。

通过Makefile编译

如果你是 linux/darwin/wsl 的用户,推荐使用 makefile 来进行安装:

➜ git clone https://github.com/bilibili-base/powermock
➜ cd powermock
➜ make build_linux_v8
➜ make build_linux
➜ make build_darwin
➜ make build_windows

当然也可以直接进行编译:

➜ cd ./cmd/powermock
➜ go install
➜ go build .

http://chatgpt.dhexx.cn/article/TDw9TPGs.shtml

相关文章

mock server java_1分钟搭建极简mock server

1、无聊的背景、起源&#xff1a; 如今的业务系统越来越复杂庞大&#xff0c;各个功能直接的调用也是多如牛毛&#xff0c;但如果在联调的时候&#xff0c;恰好被调的接口正在开发&#xff0c;怎么办&#xff1f;傻傻的等么&#xff0c;不存在的&#xff01;这时会搭建一些serv…

Mock Server入门及实践

分享一个大牛的人工智能教程。零基础&#xff01;通俗易懂&#xff01;风趣幽默&#xff01;希望你也加入到人工智能的队伍中来&#xff01;请轻击人工智能教程 什么是Mock Server&#xff1f; Mock测试&#xff1a;就是在测试过程中&#xff0c;对于某些不容易构造或者不容易…

用 java 安装 mockserver,Mock Server实践

背景 在美团服务端测试中&#xff0c;被测服务通常依赖于一系列的外部模块&#xff0c;被测服务与外部模块间通过REST API或是Thrift调用来进行通信。要对被测服务进行系统测试&#xff0c;一般做法是&#xff0c;部署好所有外部依赖模块&#xff0c;由被测服务直接调用。然而有…

Mock-- Server的使用

近日项目需求 使用mock-server来提供虚拟数据(API)&#xff0c;方便在服务被调用方没有开发好的情况下&#xff0c;服务调用方能不被耽误的继续进行开发 。 我们的情况大概是这样&#xff1a; 我们的服务去调用 另一方提供的服务&#xff0c;另一方的服务可能还没有开发好&…

前端调试,模拟数据利器之Mock Server使用教程来啦~

文章目录 1 MockServer是什么2 为什么要使用MockServer3 MockServer的作用4 搭建MockServer服务4.1 部署MockServer服务详细步骤4.1.1 第一种方式&#xff08;推荐&#xff09;4.1.2 第二种方式 4.2 启动Shell脚本4.3 访问MockServer UI界面 5 MockServer服务的基础使用5.1 项目…

浅谈 Mock Server

What&#xff1f;什么是 Mock Server Mock 是模拟的意思。在测试中&#xff0c;通常表述为&#xff1a;对测试过程中不容易构造或者不容易获取的物件&#xff0c;用一个虚拟的物件来进行模拟的一个过程。能够提供 Mock 功能的服务就叫作 Mock Server。 Mock Server 通过模拟真…

Mock Server 入门

Mock Server介绍 什么是mock ? 我在去年的时候介绍一篇幅 python mock的基本使用&#xff0c;http://www.cnblogs.com/fnng/p/5648247.html 主要是针对单元测试的应用&#xff0c;它可以很方便的解除单元测试中各种依赖&#xff0c;大大的降低了编写单元测试的难度。 什么是Mo…

Matlab解决脚本中中文乱码问题

首先下载字体yahei consolas hybrid。百度网盘地址&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1Zv2FMt3uow7DZix2rtAbrA 提取码&#xff1a;am4d 然后将下载的字体保存在C:\Windows\Fonts中&#xff0c;启动Matlab2018a这里使用的是2018a版本&#xff0c;其他版…

WEB UI自动化测试之AutoMagic自动化测试

AutoMagic自动化测试平台 AutoMagic 是一个基于WebUI的自动化管理平台。为什么叫AutoMagic呢&#xff1f;因为自动化&#xff08;Automation&#xff09;在执行起来的时候是一个很神奇的事情&#xff0c;它可以无人值守的模拟人的操作&#xff0c;就像魔术&#xff08;Magic&a…

Jupyter Notebook从入门到精通

下载 本课程练习完整代码 Jupyter Notebook&#xff1a; https://gist.github.com/zgpeace/8d3eb8c803a54d1ca797fa26cb68bd4c 财富500强 csv下载 https://github.com/zgpeace/fortune500.git 1. 什么是 Jupyter 笔记本&#xff1f; Jupyter Notebook 是一个非常强大的工具&…

dev shm mysql_新特性:/dev/shm对Oracle 11g的影响

ORACLE 从11g版本开始&#xff0c;引入了一个自动内存管理(Automatic Memory Management)特性&#xff0c;该特性需要更多的共享内存(/dev/shm)&#xff0c;因此如 /dev/shm对Oracle 11g的影响: ORACLE 从11g版本开始&#xff0c;引入了一个自动内存管理(Automatic Memory Mana…

Git分布式版本控制工具

Git分布式版本控制工具 文章目录 Git分布式版本控制工具1、目标 2、概述2.1、开发中的实际场景2.2、版本控制器的方式2.3、Git工作流程图 3、Git安装与常用命令3.1、Git 环境配置3.1.1 下载与安装3.1.2 基本配置3.1.3 为常用指令配置别名3.1.4 解决 GitBash 乱码问题 3.2、获取…

关于我在windows使用volatility取证这档事

官网下载地址&#xff1a;https://www.volatilityfoundation.org/releases volatility3的官方文档&#xff1a;https://volatility3.readthedocs.io/en/latest/basics.html 下载 看清有两个版本&#xff0c;用法不一样 第一次我下载了Volatility 2.6 Windows Standalone Exe…

DLNLP学习笔记03(Speech Recognition: LAS模型)

Listen, Attend, and Spell (LAS) [Chorowski. et al., NIPS’15] 论文地址&#xff1a;https://arxiv.org/pdf/1508.01211.pdf 1 模型简介&#xff1a; 2 Listen&#xff1a;其中Encoder可以为RNN&#xff0c;CNN或者RNNCNN。 Listen-down sampling&#xff1a;&#xff08;RN…

On Device Debug!IDA+GDB trace automagic.apk in s1

2019独角兽企业重金招聘Python工程师标准>>> http://forum.xda-developers.com/showthread.php?t2050393 Well... I have attached a debugger to native code, set breakpoints, analyzed registers, memory, etc. It wasnt that easy though. It took me severa…

【Jetson Nano 入门】环境配置汇总

文章目录 前言一、镜像烧写二、PWM风扇自动调速三、使用MicroUSB在电脑打开终端四、VNC实现局域网及网线直连通信五、SSH文件传输六、状态监控软件Jtop七、检查CUDA、OpenCV及cuDNN八、USB摄像头测试软件Camorama九、CSI摄像头测试十、实现Yolov4-tiny的USB摄像头实时检测 前言…

WEB UI自动化测试之AutoMagic自动化测试平台开源

作者介绍&#xff1a; 网名: Ray 介绍&#xff1a;笑起来像个孩子&#xff0c;冷起来是个迷。 博客&#xff1a;http://www.cnblogs.com/tsbc/ 2018年3月29日&#xff0c;Ray说准备把AutoMagic自动化测试管理平台开源了&#xff01;&#xff01;&#xff01; 这是个好消息&…

三星s20 android auto,Automagic一个更简单的方式来自动化您的Android手机 | MOS86

你有没有想过你的智能手机会在你回家的时候开始播放音乐&#xff1f;当你关闭社交网络的时候怎么样&#xff1f;Automagic是一种替代方案&#xff0c;通过使用易于理解的流程图执行许多相同的任务&#xff0c;向用户提供了一种更简单的自动化Android手机的方法。 Automagic如何…

AutoMagic自动化测试平台简介

PS:给想做自动化平台同学一点思路。 AutoMagic 是一个基于WebUI的自动化管理平台。为什么叫AutoMagic呢&#xff1f;因为自动化&#xff08;Automation&#xff09;在执行起来的时候是一个很神奇的事情&#xff0c;它可以无人值守的模拟人的操作&#xff0c;就像魔术&#xff0…

AutoMagic设计思路简介及新增自定义关键字实例

目录 简介 AutoMagic介绍 SeleniumKey介绍 自定义关键字 简介 AutoMagic 是一个基于WebUI的自动化管理平台。为什么叫AutoMagic呢&#xff1f;因为自动化在执行起来的时候是一个很神奇的事情&#xff0c;它可以无人值守的模拟人的操作&#xff0c;就像魔术&#xff08;Magic&am…