fasthttpunit

package module
v0.0.0-...-960584e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2022 License: MIT Imports: 20 Imported by: 0

README

fasthttpunit

fasthttp单元测试框架

示例

1.运行单元测试

./example/path/unit.sh

./example/file/unit.sh

2.用例结果及覆盖率

case cover cover-html

使用

1.配置用例列表,用例支持yml、yaml、json扩展名的文件,配置用例目录后,框架会自动扫描目录下是用例文件

  • yaml文件示例
desc: '等于'
path: '/equal'
caseList:
  - desc: '1'
    params: 'a=e&c=1'
    expected: 'Hello World'

  - desc: '2'
    params: 'a=1&b=c'
    expected: 'Ok'
  • json文件示例
{
  "desc": "包含",
  "path": "/contains",
  "method": "POST",
  "caseList": [
    {
      "desc": "1",
      "params": "num=1&sign=1",
      "expected": "Hello",
      "expectedType": "contains"
    },
    {
      "desc": "2",
      "params": "num=2&sign=2",
      "expected": "hello",
      "expectedType": "contains"
    }
  ]
}

2.fasthttp程序代码

package main

import (
	"log"

	"github.com/buaazp/fasthttprouter"
	"github.com/valyala/fasthttp"
)

func Equal(ctx *fasthttp.RequestCtx) {
	_, _ = ctx.WriteString(`Hello World`)
}

func Contains(ctx *fasthttp.RequestCtx) {
	_, _ = ctx.WriteString(`24sdfq23rwasdfasdfHelloadfasdf23sadfasdfef2`)
}

func Pattern(ctx *fasthttp.RequestCtx) {
	_, _ = ctx.WriteString(`{"code": 200, "msg": "ok", "data":{}}`)
}

func loadRouter() *fasthttprouter.Router {
	r := fasthttprouter.New()
	r.GET("/equal", Equal)
	r.POST("/contains", Contains)
	r.GET("/pattern", Pattern)

	return r
}

func main() {
	r := loadRouter()

	server := fasthttp.Server{
		Handler: r.Handler,
	}

	err := server.ListenAndServe(":8080")
	if err != nil {
		log.Fatalf("server start error:%s\n", err.Error())
	}
}

3.单元测试代码

package main

import (
	"fmt"
	"testing"

	"github.com/jhq0113/fasthttpunit"
)

func mockA() {
	fmt.Printf("mock:a\n")
}

func mockB() {
	fmt.Printf("mock:b\n")
}

func TestUnit(t *testing.T) {
	r := loadRouter()

	casePath := fasthttpunit.BinPath() + "/case"

	conf, err := fasthttpunit.LoadConf(casePath)
	if err != nil {
		t.Fatal(fasthttpunit.Red("load conf err: %s", err.Error()))
	}

	conf.Delay = 3

	u := fasthttpunit.NewUnitWithRouter(conf, t, r)
	u.Test(mockA, mockB)
}

4.单元测试执行脚本

#!/bin/bash
SCRIPTPATH=$(cd "$(dirname "$0")"; pwd)

cd $SCRIPTPATH

go test . -v -coverpkg=... -coverprofile=$SCRIPTPATH/unitout/app.out
go tool cover -func=$SCRIPTPATH/unitout/app.out -o $SCRIPTPATH/unitout/coverage.txt
go tool cover -html=$SCRIPTPATH/unitout/app.out -o $SCRIPTPATH/unitout/coverage.html

Documentation

Index

Constants

View Source
const (
	Equal    = `equal`
	Contains = `contains`
	Pattern  = `pattern`
)

Variables

View Source
var (
	ErrUnsupportedFileType = errors.New(`unsupported file type`)
	ErrNotFoundApi         = errors.New("not found api")
)

Functions

func BinPath

func BinPath() string

func CaseToRequest

func CaseToRequest(api *Api, c Case) *fasthttp.Request

func Green

func Green(format string, args ...interface{}) string

Green 成功

func IsExpected

func IsExpected(expectedType, value string, resp *fasthttp.Response) bool

func Red

func Red(format string, args ...interface{}) string

Red 错误

func Yellow

func Yellow(format string, args ...interface{}) string

Yellow 警告

Types

type Api

type Api struct {
	Desc        string            `json:"desc" yaml:"desc"`
	Host        string            `json:"host" yaml:"host"`
	Method      string            `json:"method" yaml:"method"`
	Path        string            `json:"path" yaml:"path"`
	ContentType string            `json:"contentType" yaml:"contentType"`
	Header      map[string]string `json:"header" yaml:"header"`
	CaseList    []Case            `json:"caseList" yaml:"caseList"`
}

type Case

type Case struct {
	Desc         string            `json:"desc" yaml:"desc"`
	Params       string            `json:"params" yaml:"params"`
	Header       map[string]string `json:"header" yaml:"header"`
	Expected     string            `json:"expected" yaml:"expected"`
	ExpectedType string            `json:"expectedType" yaml:"expectedType"`
}

type Conf

type Conf struct {
	ApiList []*Api `json:"apiList" yaml:"apiList"`
	Delay   uint64 `json:"delay" yaml:"delay"`
}

func LoadConf

func LoadConf(fileName string) (c *Conf, err error)

func LoadConfByPath

func LoadConfByPath(basePath string) (c *Conf, err error)

type ReadWriter

type ReadWriter struct {
	net.Conn
	// contains filtered or unexported fields
}

func NewReadWriter

func NewReadWriter(server *fasthttp.Server) *ReadWriter

func (*ReadWriter) Close

func (rw *ReadWriter) Close() error

func (*ReadWriter) LocalAddr

func (rw *ReadWriter) LocalAddr() net.Addr

func (*ReadWriter) Read

func (rw *ReadWriter) Read(b []byte) (int, error)

func (*ReadWriter) RemoteAddr

func (rw *ReadWriter) RemoteAddr() net.Addr

func (*ReadWriter) Request

func (rw *ReadWriter) Request(req *fasthttp.Request, resp *fasthttp.Response) (err error)

func (*ReadWriter) SetDeadline

func (rw *ReadWriter) SetDeadline(t time.Time) error

func (*ReadWriter) SetReadDeadline

func (rw *ReadWriter) SetReadDeadline(t time.Time) error

func (*ReadWriter) SetWriteDeadline

func (rw *ReadWriter) SetWriteDeadline(t time.Time) error

func (*ReadWriter) Write

func (rw *ReadWriter) Write(b []byte) (int, error)

type Unit

type Unit struct {
	// contains filtered or unexported fields
}

func NewUnit

func NewUnit(conf *Conf, t *testing.T, s *fasthttp.Server) *Unit

func NewUnitWithHandler

func NewUnitWithHandler(conf *Conf, t *testing.T, handler fasthttp.RequestHandler) *Unit

func NewUnitWithRouter

func NewUnitWithRouter(conf *Conf, t *testing.T, r *fasthttprouter.Router) *Unit

func (*Unit) Fatal

func (u *Unit) Fatal(format string, args ...interface{})

func (*Unit) Green

func (u *Unit) Green(format string, args ...interface{})

func (*Unit) Red

func (u *Unit) Red(format string, args ...interface{})

func (*Unit) Test

func (u *Unit) Test(mockList ...func())

func (*Unit) Yellow

func (u *Unit) Yellow(format string, args ...interface{})

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL