// 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的更多相关文章

  1. Socket聊天程序——Common

    写在前面: 上一篇记录了Socket聊天程序的客户端设计,为了记录的完整性,这里还是将Socket聊天的最后一个模块--Common模块记录一下.Common的设计如下: 功能说明: Common模块 ...

  2. angularjs 1 开发简单案例(包含common.js,service.js,controller.js,page)

    common.js var app = angular.module('app', ['ngFileUpload']) .factory('SV_Common', function ($http) { ...

  3. Common Bugs in C Programming

    There are some Common Bugs in C Programming. Most of the contents are directly from or modified from ...

  4. ANSI Common Lisp Practice - My Answers - Chatper - 3

    Ok, Go ahead. 1 (a) (b) (c) (d) 2 注:union 在 Common Lisp 中的作用就是求两个集合的并集.但是这有一个前提,即给的两个列表已经满足集合的属性了.具体 ...

  5. [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 ...

  6. [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 ...

  7. [LeetCode] Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...

  8. 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

  9. 动态规划求最长公共子序列(Longest Common Subsequence, LCS)

    1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...

  10. 【leetcode】Longest Common Prefix

    题目简述: Write a function to find the longest common prefix string amongst an array of strings. 解题思路: c ...

随机推荐

  1. Android同屏、摄像头RTMP推送常用的数据接口设计探讨

    前言 好多开发者在调用Android平台RTMP推送或轻量级RTSP服务接口时,采集到的video数据类型多样化,如420sp.I420.yv12.nv21.rgb的,还有的拿到的图像是倒置的,如果开 ...

  2. UTL_FILE 包使用介绍

    Postgresql 不支持 package功能,这给oracle 向 postgresql迁移增加了很多迁移工作.人大金仓Kingbase数据库实现了类似 oracle package 功能,并提供 ...

  3. mysql_唯一索引数据重复问题总结

    CREATE TABLE `tt_transfer_assemble_diffuse_plan_info` ( `id` bigint(20) unsigned NOT NULL AUTO_INCRE ...

  4. Filebeat Nginx Module 自定义字段

    Filebeat Nginx Module 自定义字段 一.修改/usr/local/nginx/conf/nginx.conf中 log_format access '$remote_addr - ...

  5. 跟羽夏学 Ghidra ——工具

    写在前面   此系列是本人一个字一个字码出来的,包括示例和实验截图.本人非计算机专业,可能对本教程涉及的事物没有了解的足够深入,如有错误,欢迎批评指正. 如有好的建议,欢迎反馈.码字不易,如果本篇文章 ...

  6. [Python]-string-字符串

    字符串是Python中很常用的数据类型,此处记录一些典型用法并随时更新. split()方法 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串. 两个参数st ...

  7. js中new的原理

    面向对象 在了解new的原理之前,先简单地了解一下构造函数和对象. js可以通过构造函数创建对象: function Test() { } var t = new Test(); 构造函数的首字母大写 ...

  8. kindeditor获取html内容之终极大法

    请允许我哔哔两句,真是难受啊,有问题去百度,结果百了一堆乱七八糟的内容,有头没尾,有尾没头的,搞得我晕头转向,现在把kindeditor获取HTML的终极打法无偿分享出来,这可是我配置查找了一下午的成 ...

  9. 2022 CLion 中的Cygwin 配置(最全,最良心版)

    目录 前景提要 一.windows 10 安装Cygwin 1.找到官网,进入官网,百度搜索或者点击下边链接. 2.找到如图位置,双击下载 3.下载完成后,找到下载的位置,双击exe文件. 4.进入欢 ...

  10. Nginx配置中一个不起眼字符"/"的巨大作用

    文章转载自:https://mp.weixin.qq.com/s/QwsbuNIqLpxi_FhQ5pSV3w Nginx作为一个轻量级的,高性能的web服务软件,因其占有内存少,并发能力强的特点,而 ...