// 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. mysql_varchar与中英文关系总结

    mysql 4.0版本以下,varchar(50), 指的是50字节,如果存放utf8汉字时,只能存放16个(每个汉字3字节) mysql 5.0版本以上,varchar(50), 指的是50字符,无 ...

  2. MySQL到底有没有解决幻读问题?这篇文章彻底给你解答

    MySQL InnoDB引擎在Repeatable Read(可重复读)隔离级别下,到底有没有解决幻读的问题? 网上众说纷纭,有的说解决了,有的说没解决,甚至有些大v的意见都无法达成统一. 今天就深入 ...

  3. 2021年1月-第02阶段-前端基础-HTML+CSS阶段-Day01

    HTML5 第一天 一.什么是 HTML5 1.HTML5 的概念与定义 定义:HTML5 定义了 HTML 标准的最新版本,是对 HTML 的第五次重大修改,号称下一代的 HTML 两个概念: 是一 ...

  4. 【学习笔记】Vin-Mono论文阅读笔记(一)

    VINS-Mono 概述 VINS-Mono VINS-Mono是由一个单目相机和一个低成本IMU组成的鲁棒通用的单目视觉惯性系统.通过融合预积分的IMU测量值和特征观测值来获得高精度的视觉惯性里程计 ...

  5. 使用kubeoperator安装的k8s集群以及采用的containerd容器运行时,关于采用的是cgroup 驱动还是systemd 驱动的说明

    使用kubeoperator安装的k8s集群,默认使用的是systemd驱动 # kubectl get cm -n kube-system NAME DATA AGE calico-config 4 ...

  6. 9. Ceph 基础篇 - Crush Maps

    文章转载自:https://mp.weixin.qq.com/s?__biz=MzI1MDgwNzQ1MQ==&mid=2247485302&idx=1&sn=00a3a204 ...

  7. 5.监控MySQL

    prometheus监控MySQL需要用到mysql_exporter. mysql_exporter 项目地址:https://github.com/prometheus/mysqld_export ...

  8. a除于b

    a=eval(input()) b=eval(input()) if b!=0: print("{}".format(round(a/b,2))) else: print(&quo ...

  9. 原生Redis跨数据中心双向同步优化实践

    一.背景 公司基于业务发展以及战略部署,需要实现在多个数据中心单元化部署,一方面可以实现多数据中心容灾,另外可以提升用户请求访问速度.需要保证多数据中心容灾或者实现用户就近访问的话,需要各个数据中心拥 ...

  10. DirectX 使用 Vortice 从零开始控制台创建 Direct2D1 窗口修改颜色

    本文将告诉大家如何使用 Vortice 底层库从零开始,从一个控制台项目,开始搭建一个最简单的使用 Direct2D1 的 DirectX 应用.本文属于入门级博客,期望本文能让大家了解 Vortic ...