mindxdl---common--test_tools.go
// Copyright (c) 2021. Huawei Technologies Co., Ltd. All rights reserved.
// Package common define common utils
package common
import (
"bytes"
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"huawei.com/mindxdl/base/common/constants"
"huawei.com/npu-exporter/hwlog"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
const (
// PUT is Put method
PUT = "PUT"
// GET is Get method
GET = "GET"
// POST is Post method
POST = "POST"
// DELETE is Delete method
DELETE = "DELETE"
// PATCH is Patch method
PATCH = "PATCH"
)
var (
// RoleCode is roleRode
RoleCode = constants.NormalUserRole
)
// TestSuccess if status is ok, pass
func TestSuccess(t *testing.T, getRes []byte, successWay string) {
var response ResultMsg
if err := json.Unmarshal(getRes, &response); err != nil {
hwlog.RunLog.Errorf("Unmarshal param happen err : %v", err)
return
}
status := response.Status
assert.Equal(t, successWay, status)
}
// TestSuccessData need response.Data is right
func TestSuccessData(t *testing.T, getRes []byte, data interface{}) {
var response ResultMsg
if err := json.Unmarshal(getRes, &response); err != nil {
hwlog.RunLog.Errorf("Unmarshal param happen err : %v", err)
return
}
assert.Equal(t, response.Data, data)
}
func performRequest(r *gin.Engine, method, path string, body io.Reader) *httptest.ResponseRecorder {
req, err := http.NewRequest(method, path, body)
if err != nil {
hwlog.RunLog.Errorf("NewRequest happen err : %v", err)
return nil
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("sessionid", "123456")
req.Header.Set("userid", "654321")
req.Header.Set("groupid", "111111")
req.Header.Set("roleid", "2")
req.Header.Set("roleCode", RoleCode)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
// Get request get
func Get(router *gin.Engine, uri string) []byte {
w := performRequest(router, "GET", uri, nil)
result := w.Result()
defer result.Body.Close()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
hwlog.RunLog.Errorf("Get IOUtil readAll happen err : %v", err)
return nil
}
return body
}
// Delete request delete
func Delete(router *gin.Engine, uri string) []byte {
w := performRequest(router, "DELETE", uri, nil)
result := w.Result()
defer result.Body.Close()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
hwlog.RunLog.Errorf("Delete IOUtil readAll happen err : %v", err)
return nil
}
return body
}
// Put request put
func Put(router *gin.Engine, uri string, param map[string]interface{}) []byte {
jsonByte, err := json.Marshal(param)
if err != nil {
hwlog.RunLog.Errorf("Put Marshal param happen err : %v", err)
return nil
}
w := performRequest(router, "PUT", uri, bytes.NewReader(jsonByte))
result := w.Result()
defer result.Body.Close()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
hwlog.RunLog.Errorf("Delete IOUtil readAll happen err : %v", err)
return nil
}
return body
}
// RestfulAPI include post get put delete for ut
func RestfulAPI(router *gin.Engine, operate, uri string, param map[string]interface{}) []byte {
header := map[string]string{
"Content-Type": "application/json;charset=UTF-8",
"requestid": "123456",
"userid": "654321",
"groupid": "111111",
"roleid": "2",
"roleCode": RoleCode,
}
return RestfulAPIV2(router, operate, uri, header, param)
}
// RestfulAPIV2 RestfulAPIV2
func RestfulAPIV2(router *gin.Engine, operate, uri string, header map[string]string,
param map[string]interface{}) []byte {
var paramStr string
if len(param) != 0 {
jsonByte, err := json.Marshal(param)
if err != nil {
hwlog.RunLog.Errorf("%s Marshal param happen err : %v", operate, err)
return nil
}
paramStr = string(jsonByte)
}
handler := new(HTTPHandler)
req, err := handler.NewRequest(operate, uri, paramStr)
if err != nil {
hwlog.RunLog.Errorf("NewRequest happen err : %v", err)
return nil
}
handler.SetHeader(req, header)
res := httptest.NewRecorder()
router.ServeHTTP(res, req)
result := res.Result()
defer result.Body.Close()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
hwlog.RunLog.Errorf("%s IOUtil readAll happen err : %v", operate, err)
return nil
}
return body
}
// ParseResponseToStruct parse response to struct
func ParseResponseToStruct(rspBytes []byte) (*ResultMsg, error) {
if len(rspBytes) == 0 {
return nil, errors.New("no response")
}
var response ResultMsg
if err := json.Unmarshal(rspBytes, &response); err != nil {
hwlog.RunLog.Errorf("Unmarshal param happen err : %v", err)
return nil, err
}
return &response, nil
}
mindxdl---common--test_tools.go的更多相关文章
- Socket聊天程序——Common
写在前面: 上一篇记录了Socket聊天程序的客户端设计,为了记录的完整性,这里还是将Socket聊天的最后一个模块--Common模块记录一下.Common的设计如下: 功能说明: Common模块 ...
- angularjs 1 开发简单案例(包含common.js,service.js,controller.js,page)
common.js var app = angular.module('app', ['ngFileUpload']) .factory('SV_Common', function ($http) { ...
- Common Bugs in C Programming
There are some Common Bugs in C Programming. Most of the contents are directly from or modified from ...
- ANSI Common Lisp Practice - My Answers - Chatper - 3
Ok, Go ahead. 1 (a) (b) (c) (d) 2 注:union 在 Common Lisp 中的作用就是求两个集合的并集.但是这有一个前提,即给的两个列表已经满足集合的属性了.具体 ...
- [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- [LeetCode] Longest Common Prefix 最长共同前缀
Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...
- 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]
[题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下: C++ Code 123456 struct BinaryTreeNode { int ...
- 动态规划求最长公共子序列(Longest Common Subsequence, LCS)
1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...
- 【leetcode】Longest Common Prefix
题目简述: Write a function to find the longest common prefix string amongst an array of strings. 解题思路: c ...
随机推荐
- HC32L110(五) Ubuntu20.04 VSCode的Debug环境配置
目录 HC32L110(一) HC32L110芯片介绍和Win10下的烧录 HC32L110(二) HC32L110在Ubuntu下的烧录 HC32L110(三) HC32L110的GCC工具链和VS ...
- docker-compose入门--翻译
在这一页,你将学习到如何构建一个简单的python的web应用,并通过Docker compose来运行.这个应用程序使用的是Flask框架,并维护着一个存储在reids里的点击计数器.由于这个案例使 ...
- 新建Github仓库并上传本地代码
按照Github的教程 Adding a local repository to GitHub using Git 1. 创建空的Github仓库 创建远程仓库 ,注意不要勾选Add a README ...
- es根据关键词查看某个指定索引的内容并删除
# 根据关键词查询某个索引的内容 GET product/_search?q=title:测试商品 {"query":{"match_all":{}}} # 根 ...
- Kubernetes生态架构图
图片来源于:https://gitbook.curiouser.top/ 一.kubernetes 集群架构图 二.Openshift or Kubernetes 集群架构图 三.常见的 CI/CD ...
- CentOS7.9 yum方式安装redis最新版
yum install -y http://rpms.famillecollet.com/enterprise/remi-release-7.rpm yum --enablerepo=remi ins ...
- Fluentd部署:如何监控Fluentd
监控的目的是确保日志采集能稳定高效运行. Fluentd内部运行指标 Fluentd内部保存着一些运行指标,这些指标可通过REST api直接获取,也支持通过第三方工具,如Prometheus,来访问 ...
- Vmware虚拟机设置主机端口映射
转载自:https://blog.csdn.net/Mrqiang9001/article/details/80820321
- 华为路由器NAT基本配置命令
NAT地址转换 静态 [R1]int g0/0/0 [R1-GigabitEthernet0/0/0]nat static global 202.169.10.5 inside 172.16.1.1 ...
- python2与python区别汇总
目录 输入与输出 range使用区别 字符编码区别 输入与输出 python2与python3中两个关键字的区别 python2中 input方法需要用户自己提前指定数据类型 写什么类型就是什么类型 ...