apitest

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2024 License: Apache-2.0 Imports: 38 Imported by: 0

README

apitest

API test for Go.

在测试的同时生成接口文档。

确保代码和文档的一致。

省心又省力。

如何使用

  1. 添加接口

1.1. 定义接口、参数和结果

POST /book

type BookParam struct {
    Name string `json:"name"` // 名称
    Author string `json:"author"` // 作者
}

type BookResult struct {
    Id uint64 `json:"id"` // 新记录id
}

func CreateBook(c *gin.Context) {
    // use BookParam receive param
    var p BookParam

    // return BookResult as API's result
    var r BookResult
    c.JSON(http.StatusOK, r)
}

1.2. 注册路由,启动服务:

func main() {
	buf := new(bytes.Buffer)
	gin.DefaultWriter = io.MultiWriter(buf, os.Stdout)
	engine := gin.Default()
    engine.POST("/book", CreateBook)

	if err := engine.Run(":8888"); err != nil {
        panic(err)
    }
}
  1. 添加测试
func TestAPI(t *testing.T) {
    w := new(bytes.Buffer)

    var r BookResult

    // 调用请求的同时生成文档
    if err := NewAT("/book", http.MethodPost, "新建图书信息", nil, nil). // 新建测试,指定接口路径和方法
        SetParam(&BookParam{ // 设置参数
            Name: "test",
            Author: "jd",
        }).
        FakeRun().  // 虚假执行;若要真正执行,请使用`Run()`
        Result(&r). // 获取结果
        WriteFile(w). // 输出文档到文件
        Err(); err != nil {
        t.Fatal(err)
    }
}
  1. 执行测试并生成文档

go test .

将生成文档:

## 新建图书信息

`POST /book`

Param - Query

* name (*string*) 名称
* author (*string*) 作者

Return

* id (*uint64*) 新记录id

其中,参数和返回的字段信息来源于结构体的定义。

如此,在接口和测试完成的同时,文档也随之完成。

Documentation

Overview

Package apitest Usage:

NewAT(xxx).
	SetParam(xxx).
	Debug().
	Run().
	EqualCode(xxx).
	Result(xxx).
	Equal(...).
	WriteFile(xxx).
	Err()

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilParam 参数为nil
	ErrNilParam = errors.New("please input param, param is nil now")
)

Predefined error

Functions

func ApiKey added in v1.8.0

func ApiKey(method, path string, i ...int) string

func CookieMapToSlice

func CookieMapToSlice(cm map[string]string) []*http.Cookie

CookieMapToSlice map转为slice

func GenParamResult added in v1.4.0

func GenParamResult(key string, param, result reflect.Type, resultWrapper ...func(v any) any) (p, r any)

func GinHandlerAPIDoc

func GinHandlerAPIDoc(doc *gin.RouterGroup, dir string, brand string)

GinHandlerAPIDoc 针对指定目录下的md接口文档,生成对应的html文件,并注册到gin路由上

func HandleRoutes added in v1.4.0

func HandleRoutes(group *gin.RouterGroup, routes []*Route, h func(group *gin.RouterGroup, route *Route))

func JSONIndent

func JSONIndent(w io.Writer, v any)

JSONIndent json格式化后输出

func MakeCatalog

func MakeCatalog(entries []CatalogEntry) (string, error)

func MakeDoc added in v1.8.0

func MakeDoc(t DocHelper, dir, file, title, pathPrefix string)

func OpenFile

func OpenFile(file, title string) (*os.File, error)

OpenFile 打开文件

func RegisterTagName

func RegisterTagName(tagName string)

func XMLIndent

func XMLIndent(w io.Writer, v any)

Types

type APIError

type APIError interface {
	Code() string
	Msg() string
}

type AT

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

AT api test

func NewAT

func NewAT(
	path,
	method,
	comment string,
	h http.Header,
	cookies []*http.Cookie,
) *AT

NewAT 新建

func (*AT) CatalogEntry

func (at *AT) CatalogEntry() CatalogEntry

func (*AT) Debug

func (at *AT) Debug() *AT

Debug 开启调试模式

func (*AT) Equal

func (at *AT) Equal(args ...any) *AT

Equal 校验

func (*AT) EqualCode

func (at *AT) EqualCode(wantCode int) *AT

EqualCode 比较响应码

func (*AT) EqualThen

func (at *AT) EqualThen(f func(*AT) error, args ...any) *AT

EqualThen 相等之后

func (*AT) Err

func (at *AT) Err() error

func (*AT) Errors

func (at *AT) Errors(errs ...any) *AT

Errors 获取错误

func (*AT) FakeRun

func (at *AT) FakeRun() *AT

Run 运行

func (*AT) GetResultExtractor

func (at *AT) GetResultExtractor(format string) (re ResultExtractor, ok bool)

func (*AT) InsecureSkipVerify added in v0.3.0

func (at *AT) InsecureSkipVerify() *AT

func (*AT) MarkAuthHeader

func (at *AT) MarkAuthHeader(authHeaderKey, authHeaderValue string) *AT

func (*AT) Method

func (at *AT) Method() string

func (*AT) MonkeyRun

func (at *AT) MonkeyRun() *AT

MonkeyRun 猴子运行

func (*AT) New

func (at *AT) New() *AT

New 克隆一个新的AT

func (*AT) Path

func (at *AT) Path() string

func (*AT) PressureRun

func (at *AT) PressureRun(n, c int) *AT

PressureRun 压力运行,n: 运行次数,c: 并发数

func (*AT) PressureRunBatch

func (at *AT) PressureRunBatch(param []PressureParam) *AT

PressureRunBatch 批量压力运行

func (*AT) RegisterResultExtractor

func (at *AT) RegisterResultExtractor(format string, re ResultExtractor) *AT

func (*AT) Resp

func (at *AT) Resp() *http.Response

func (*AT) Result

func (at *AT) Result(r any) *AT

Result 获取结果

func (*AT) ResultWrapper added in v0.4.0

func (at *AT) ResultWrapper(rw ResultWrapper) *AT

ResultWrapper 指定结果包装结构

func (*AT) Run

func (at *AT) Run() *AT

Run 运行

func (*AT) SetCert added in v0.3.0

func (at *AT) SetCert(caCertPath, certFile, keyFile string) *AT

func (*AT) SetClientTimeout added in v1.3.0

func (at *AT) SetClientTimeout(timeout time.Duration) *AT

SetClientTimeout set client timeout like: 10*time.Second

func (*AT) SetCookies

func (at *AT) SetCookies(cookies []*http.Cookie) *AT

SetCookies 设置cookies

func (*AT) SetFile

func (at *AT) SetFile(file string) *AT

SetFile 设置文件

func (*AT) SetHeader

func (at *AT) SetHeader(header http.Header) *AT

SetHeader 设置header

func (*AT) SetHost

func (at *AT) SetHost(host string) *AT

SetHost 设置host

func (*AT) SetParam

func (at *AT) SetParam(param any) *AT

SetParam 设置参数

func (*AT) SetPort

func (at *AT) SetPort(port string) *AT

SetPort 设置端口,如":8080"

func (*AT) SetScheme

func (at *AT) SetScheme(scheme string) *AT

SetScheme 设置scheme

func (*AT) SetStatus

func (at *AT) SetStatus(status Status) *AT

func (*AT) Title

func (at *AT) Title() string

func (*AT) UseXMLFormat

func (at *AT) UseXMLFormat() *AT

UseXMLFormat 设置参数和结果格式为XML

func (*AT) UseXMLParamFormat

func (at *AT) UseXMLParamFormat() *AT

UseXMLParamFormat 设置参数格式为XML

func (*AT) UseXMLResultFormat

func (at *AT) UseXMLResultFormat() *AT

UseXMLResultFormat 设置结果格式为XML

func (*AT) WriteFile

func (at *AT) WriteFile(w io.Writer) *AT

WriteFile 写入markdown文件

type CatalogEntry

type CatalogEntry struct {
	Title  string
	Method string
	Path   string
}

type Collector added in v1.4.0

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

func NewCollector added in v1.4.0

func NewCollector(
	obj interface {
		RegisterAPI(apiGroup *gin.RouterGroup) []*Route
	},
	routem map[string]lo.Tuple2[reflect.Value, int],
	opts ...Setter,
) *Collector

NewCollector while obj is an interface and routem is a map contains apikey and handler function

func (*Collector) FindTestAPIsByPrefix added in v1.4.0

func (c *Collector) FindTestAPIsByPrefix(prefix string) (r []*TestAPI)

func (*Collector) TestAPIKeys added in v1.4.0

func (c *Collector) TestAPIKeys() []string

func (*Collector) TestAPIs added in v1.4.0

func (c *Collector) TestAPIs() map[string]*TestAPI

type DocHelper added in v1.8.0

type DocHelper interface {
	Fatal(args ...any)
	FindTestAPIsByPrefix(prefix string) (r []*TestAPI)
	GetParamResult(key string, param reflect.Type, result reflect.Type) (p any, r any)
}

type Example added in v0.12.0

type Example struct {
	Inputs      []Input
	Method      string
	Path        string
	Token       string
	Params      string
	ResultDivId string
}

type Input added in v0.12.0

type Input struct {
	Name        string
	Login       string
	Id          string
	Placeholder string
}
type Link struct {
	Url   string
	Title string
}

type Option added in v1.5.0

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

func (*Option) Default added in v1.5.0

func (o *Option) Default()

type PressureParam

type PressureParam struct {
	N int // 运行次数
	C int // 并发数
}

PressureParam 压力测试参数

type Result added in v1.4.0

type Result[T any] struct {
	Code      int    `json:"code"`                // 业务码,0为正常,非0表示出错
	Msg       string `json:"msg"`                 // 出错信息
	Timestamp int64  `json:"timestamp,omitempty"` // 时间戳
	TraceId   string `json:"traceId"`             // 追踪id

	Data T `json:"data"` // 业务数据
}

type ResultExtractor

type ResultExtractor func(data []byte, r any) error

type ResultWrapper added in v0.4.0

type ResultWrapper interface {
	WithData(data any)
}

type Route added in v1.4.0

type Route = do.Route[*gin.Context]

type Setter added in v1.5.0

type Setter func(*Option)

func UseBasePath added in v1.7.0

func UseBasePath(withBasePath bool) Setter

func WithBasePath added in v1.5.0

func WithBasePath(basePath string) Setter

func WithParamIndex added in v1.6.0

func WithParamIndex(paramIndex int) Setter

func WithResultIndex added in v1.6.0

func WithResultIndex(resultIndex int) Setter

func WithResultWrapper added in v1.7.0

func WithResultWrapper(resultWrapper func(v any) any) Setter

func WithRouterGroup added in v1.5.0

func WithRouterGroup(group *gin.RouterGroup) Setter

type SimpleKind

type SimpleKind interface {
	~int | ~int16 | ~int32 | ~int64 | ~int8 |
		~uint | ~uint16 | ~uint32 | ~uint64 | ~uint8 |
		~string |
		~bool |
		~float32 | ~float64
}

type Status

type Status int
const (
	StatusNone           Status = 0
	StatusInDesign       Status = 1 // 设计中
	StatusNotImplemented Status = 2 // 未实现
	StatusImplementation Status = 3 // 实现中
	StatusImplemented    Status = 4 // 已实现
)

func (Status) String

func (s Status) String() string

type TestAPI added in v1.4.0

type TestAPI struct {
	*AT
	// contains filtered or unexported fields
}

func (*TestAPI) GetParamResult added in v1.4.0

func (t *TestAPI) GetParamResult(gen ...func(key string, param, result reflect.Type) (p, r any)) (p, r any)

getParamResult 获取key所对应的参数和结果

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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