gmock

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2023 License: Apache-2.0 Imports: 8 Imported by: 0

README

说明

gmock主要是为了简化单元测试而设计。

原理

对常用的服务本地内存实现。

目标

不改变现有代码的情况下,能快速对原有代码进行单元测试。

示例

package main

import (
	"context"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/sjqzhang/gmock"
	"github.com/sjqzhang/gmock/mockdb"
	"github.com/sjqzhang/gmock/mockdocker"
	_ "gorm.io/driver/mysql"
	gormv2 "gorm.io/gorm"
	"io/ioutil"
	"net/http"
	"time"
	"xorm.io/xorm"
)

type User struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	testMockGORM()
	testMockGORMV2()
	testMockXORM()
	testMockRedis()
	testMockHttpServer()
	testMockDocker()
	testDBUtil()

}

func testMockGORM() {
	var db *gorm.DB
	mockdb.DBType = "mysql"
	mock := gmock.NewMockGORM("example", func(gorm *mockdb.MockGORM) {
		db = gorm.GetGormDB()
	})
	fmt.Println(mock.GetDSN())
	//mock.RegisterModels(&User{})
	mock.InitSchemas(`CREATE TABLE user (
                           id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                           age int(3) DEFAULT NULL,
                           name varchar(255) DEFAULT NULL COMMENT '名称',
                           PRIMARY KEY (id)
) ENGINE=InnoDB ;`)
	mock.ResetAndInit()

	var user User
	err := db.Where("id=?", 1).Find(&user).Error
	if err != nil {
		panic(err)
	}
	if user.Id != 1 {
		panic(fmt.Errorf("testMockGORM error"))
	}

}

func testDBUtil() {
	util := gmock.NewDBUtil()
	util.RunMySQLServer("test", 33333, false)
	db, err := gorm.Open("mysql", "user:pass@tcp(127.0.0.1:33333)/test?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		panic(err)
	}
	sqlText := util.ReadFile("./example/ddl.txt")
	for _, s := range util.ParseSQLText(sqlText) {
		fmt.Println(db.Exec(s))
	}
	fmt.Println(util.QueryListBySQL(db.DB(), "select * from project"))
}

func testMockGORMV2() {
	mockdb.DBType = "mysql"
	var db *gormv2.DB
	mock := gmock.NewMockGORMV2("example", func(orm *mockdb.MockGORMV2) {
		db = orm.GetGormDB()
	})
	//注册模型
	mock.RegisterModels(&User{})
	//初始化数据库及表数据
	mock.ResetAndInit()
	mock.ResetAndInit()
	//db := mock.GetGormDB()
	var user User
	err := db.Where("id=?", 1).Find(&user).Error
	if err != nil {
		panic(err)
	}
	if user.Id != 1 {
		panic(fmt.Errorf("testMockGORMV2 error"))
	}

}

func testMockRedis() {
	server := gmock.NewMockRedisServer(63790)
	client := server.GetRedisClient()
	ctx := context.Background()
	key := "aa"
	value := "aa value"
	pool := server.GetRedigoPool()
	conn := pool.Get()
	defer conn.Close()
	rep, err := conn.Do("set", key, value)
	if err != nil {
		panic(err)
	}
	fmt.Println(rep)
	//client.Set(ctx, key, value, time.Second*10)
	cmd := client.Get(ctx, key)
	if cmd.Val() != value {
		panic("testMockRedis error")
	}

}

func testMockHttpServer() {
	// 只支持 http 不支持 https
	server := gmock.NewMockHttpServer("./", []string{"www.baidu.com", "www.jenkins.org"})
	server.InitMockHttpServer()
	//server.SetReqRspHandler(func(req *mockhttp.Request, rsp *mockhttp.Response) {
	//	req.Method = "GET"
	//	req.Endpoint = "/HelloWorld"
	//	req.Host = "www.baidu.com"
	//	rsp.Body = "xxxxxxxxx bbbb"
	//})
	resp, err := http.Get("http://www.baidu.com/hello/xxx")
	if err != nil {
		panic(err)
	}
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	if string(data) != "hello baidu" {
		panic(fmt.Errorf("testMockHttpServer error"))
	}
}

func testMockXORM() {
	var engine *xorm.Engine
	mockdb.DBType = "mysql"
	mock := gmock.NewMockXORM("example", func(orm *mockdb.MockXORM) {
		engine = orm.GetXORMEngine()
	})
	mock.RegisterModels(&User{})

	mock.ResetAndInit()
	db := mock.GetXORMEngine()
	var user User
	_, err := db.Where("id=?", 1).Get(&user)
	if err != nil {
		panic(err)
	}
	if user.Id != 1 {
		panic(fmt.Errorf("testMockXORM error"))
	}
}

func testMockDocker() {
	mock := mockdocker.NewMockDockerService()
	defer mock.Destroy()
	err := mock.InitContainerWithCmd(func(cmd *string) {
		//  注意:容器必须后台运行,否则会挂起,程序不会继续执行,所以要保证你的容器后台运行不退出
		*cmd = "docker run --name some-mysql  -p 3308:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7"
	})
	fmt.Println(err)
	if !mock.WaitForReady("wget 127.0.0.1:3308 -O -", time.Second*50) {
		panic(fmt.Errorf("mysql start fail"))
	}
	fmt.Println("mysql start success")

}

生成覆盖率及测试报告


go test -timeout 0 -covermode=count -coverprofile=coverage.out  -run="^Test" -coverpkg=package1,package2  

go tool cover -html=coverage.out -o coverage.html

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(origurl string, args ...interface{}) (resp *requests.Response, err error)

func NewDBUtil

func NewDBUtil() *util.DBUtil

func NewGORMFromDSN

func NewGORMFromDSN(pathToSqlFileName string, dbType string, dsn string) *mockdb.MockGORM

func NewGORMV2FromDSN

func NewGORMV2FromDSN(pathToSqlFileName string, dbType string, dsn string) *mockdb.MockGORMV2

func NewMockGORM

func NewMockGORM(pathToSqlFileName string, dbName string) *mockdb.MockGORM

func NewMockGORMV2

func NewMockGORMV2(pathToSqlFileName string, dbName string) *mockdb.MockGORMV2

func NewMockGRPC

func NewMockGRPC(opts ...mockgrpc.OptionGRPC) *mockgrpc.MockGRPC

func NewMockHttpServer

func NewMockHttpServer(httpServerPort int, mockJSONDir string, allowProxyHosts []string) *mockhttp.MockHttpServer

func NewMockRedisServer

func NewMockRedisServer(port int) *mockredis.MockRedisServer

func NewMockXORM

func NewMockXORM(pathToSqlFileName string, resetHandler func(orm *mockdb.MockXORM)) *mockdb.MockXORM

func NewRecorder

func NewRecorder() *httptest.ResponseRecorder

func NewRequestForTest

func NewRequestForTest(method, origurl string, args ...interface{}) (*http.Request, error)

func NewXORMFromDSN

func NewXORMFromDSN(pathToSqlFileName string, dbType string, dsn string) *mockdb.MockXORM

func Post

func Post(origurl string, args ...interface{}) (resp *requests.Response, err error)

Types

This section is empty.

Directories

Path Synopsis
vendor2
github.com/alicebob/gopher-json
Package json is a simple JSON encoder/decoder for gopher-lua.
Package json is a simple JSON encoder/decoder for gopher-lua.
github.com/davecgh/go-spew/spew
Package spew implements a deep pretty printer for Go data structures to aid in debugging.
Package spew implements a deep pretty printer for Go data structures to aid in debugging.
github.com/docker/docker/api/types/filters
Package filters provides tools for encoding a mapping of keys to a set of multiple values.
Package filters provides tools for encoding a mapping of keys to a set of multiple values.
github.com/docker/docker/api/types/swarm/runtime
Package runtime is a generated protocol buffer package.
Package runtime is a generated protocol buffer package.
github.com/docker/docker/pkg/pools
Package pools provides a collection of pools which provide various data types with buffers.
Package pools provides a collection of pools which provide various data types with buffers.
github.com/docker/go-connections/nat
Package nat is a convenience package for manipulation of strings describing network ports.
Package nat is a convenience package for manipulation of strings describing network ports.
github.com/docker/go-units
Package units provides helper function to parse and print size and time units in human-readable format.
Package units provides helper function to parse and print size and time units in human-readable format.
github.com/dolthub/vitess/go/cache
Package cache implements a LRU cache.
Package cache implements a LRU cache.
github.com/dolthub/vitess/go/event
Package event provides a reflect-based framework for low-frequency global dispatching of events, which are values of any arbitrary type, to a set of listener functions, which are usually registered by plugin packages during init().
Package event provides a reflect-based framework for low-frequency global dispatching of events, which are values of any arbitrary type, to a set of listener functions, which are usually registered by plugin packages during init().
github.com/dolthub/vitess/go/hack
Package hack gives you some efficient functionality at the cost of breaking some Go rules.
Package hack gives you some efficient functionality at the cost of breaking some Go rules.
github.com/dolthub/vitess/go/mysql
Package mysql is a library to support MySQL binary protocol, both client and server sides.
Package mysql is a library to support MySQL binary protocol, both client and server sides.
github.com/dolthub/vitess/go/netutil
Package netutil contains network-related utility functions.
Package netutil contains network-related utility functions.
github.com/dolthub/vitess/go/sqltypes
Package sqltypes implements interfaces and types that represent SQL values.
Package sqltypes implements interfaces and types that represent SQL values.
github.com/dolthub/vitess/go/stats
Package stats is a wrapper for expvar.
Package stats is a wrapper for expvar.
github.com/dolthub/vitess/go/sync2
Package sync2 provides extra functionality along the same lines as sync.
Package sync2 provides extra functionality along the same lines as sync.
github.com/dolthub/vitess/go/tb
Package tb exposes some handy traceback functionality buried in the runtime.
Package tb exposes some handy traceback functionality buried in the runtime.
github.com/dolthub/vitess/go/vt/vterrors
Package vterrors provides simple error handling primitives for Vitess
Package vterrors provides simple error handling primitives for Vitess
github.com/go-kit/kit/metrics
Package metrics provides a framework for application instrumentation.
Package metrics provides a framework for application instrumentation.
github.com/go-kit/kit/metrics/discard
Package discard provides a no-op metrics backend.
Package discard provides a no-op metrics backend.
github.com/gogo/protobuf/proto
Package proto converts data structures to and from the wire format of protocol buffers.
Package proto converts data structures to and from the wire format of protocol buffers.
github.com/golang/glog
Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
github.com/golang/protobuf/proto
Package proto provides functionality for handling protocol buffer messages.
Package proto provides functionality for handling protocol buffer messages.
github.com/golang/protobuf/ptypes
Package ptypes provides functionality for interacting with well-known types.
Package ptypes provides functionality for interacting with well-known types.
github.com/gomodule/redigo/redis
Package redis is a client for the Redis database.
Package redis is a client for the Redis database.
github.com/klauspost/compress/fse
Package fse provides Finite State Entropy encoding and decoding.
Package fse provides Finite State Entropy encoding and decoding.
github.com/klauspost/compress/huff0
Package huff0 provides fast huffman encoding as used in zstd.
Package huff0 provides fast huffman encoding as used in zstd.
github.com/klauspost/compress/snappy
Package snappy implements the Snappy compression format.
Package snappy implements the Snappy compression format.
github.com/klauspost/compress/zstd
Package zstd provides decompression of zstandard files.
Package zstd provides decompression of zstandard files.
github.com/pkg/errors
Package errors provides simple error handling primitives.
Package errors provides simple error handling primitives.
github.com/pmezard/go-difflib/difflib
Package difflib is a partial port of Python difflib module.
Package difflib is a partial port of Python difflib module.
github.com/stretchr/testify/assert
Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.
Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.
github.com/stretchr/testify/require
Package require implements the same assertions as the `assert` package but stops test execution when a test fails.
Package require implements the same assertions as the `assert` package but stops test execution when a test fails.
github.com/syndtr/goleveldb/leveldb
Package leveldb provides implementation of LevelDB key/value database.
Package leveldb provides implementation of LevelDB key/value database.
github.com/syndtr/goleveldb/leveldb/cache
Package cache provides interface and implementation of a cache algorithms.
Package cache provides interface and implementation of a cache algorithms.
github.com/syndtr/goleveldb/leveldb/comparer
Package comparer provides interface and implementation for ordering sets of data.
Package comparer provides interface and implementation for ordering sets of data.
github.com/syndtr/goleveldb/leveldb/errors
Package errors provides common error types used throughout leveldb.
Package errors provides common error types used throughout leveldb.
github.com/syndtr/goleveldb/leveldb/filter
Package filter provides interface and implementation of probabilistic data structure.
Package filter provides interface and implementation of probabilistic data structure.
github.com/syndtr/goleveldb/leveldb/iterator
Package iterator provides interface and implementation to traverse over contents of a database.
Package iterator provides interface and implementation to traverse over contents of a database.
github.com/syndtr/goleveldb/leveldb/journal
Package journal reads and writes sequences of journals.
Package journal reads and writes sequences of journals.
github.com/syndtr/goleveldb/leveldb/memdb
Package memdb provides in-memory key/value database implementation.
Package memdb provides in-memory key/value database implementation.
github.com/syndtr/goleveldb/leveldb/opt
Package opt provides sets of options used by LevelDB.
Package opt provides sets of options used by LevelDB.
github.com/syndtr/goleveldb/leveldb/storage
Package storage provides storage abstraction for LevelDB.
Package storage provides storage abstraction for LevelDB.
github.com/syndtr/goleveldb/leveldb/table
Package table allows read and write sorted key/value.
Package table allows read and write sorted key/value.
github.com/syndtr/goleveldb/leveldb/util
Package util provides utilities used throughout leveldb.
Package util provides utilities used throughout leveldb.
golang.org/x/net/context
Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes.
golang.org/x/sync/errgroup
Package errgroup provides synchronization, error propagation, and Context cancelation for groups of goroutines working on subtasks of a common task.
Package errgroup provides synchronization, error propagation, and Context cancelation for groups of goroutines working on subtasks of a common task.
golang.org/x/sys/execabs
Package execabs is a drop-in replacement for os/exec that requires PATH lookups to find absolute paths.
Package execabs is a drop-in replacement for os/exec that requires PATH lookups to find absolute paths.
golang.org/x/sys/internal/unsafeheader
Package unsafeheader contains header declarations for the Go runtime's slice and string implementations.
Package unsafeheader contains header declarations for the Go runtime's slice and string implementations.
golang.org/x/sys/unix
Package unix contains an interface to the low-level operating system primitives.
Package unix contains an interface to the low-level operating system primitives.
golang.org/x/sys/windows
Package windows contains an interface to the low-level operating system primitives.
Package windows contains an interface to the low-level operating system primitives.
google.golang.org/grpc/codes
Package codes defines the canonical error codes used by gRPC.
Package codes defines the canonical error codes used by gRPC.
google.golang.org/grpc/internal/status
Package status implements errors returned by gRPC.
Package status implements errors returned by gRPC.
google.golang.org/grpc/status
Package status implements errors returned by gRPC.
Package status implements errors returned by gRPC.
google.golang.org/protobuf/encoding/prototext
Package prototext marshals and unmarshals protocol buffer messages as the textproto format.
Package prototext marshals and unmarshals protocol buffer messages as the textproto format.
google.golang.org/protobuf/encoding/protowire
Package protowire parses and formats the raw wire encoding.
Package protowire parses and formats the raw wire encoding.
google.golang.org/protobuf/internal/descfmt
Package descfmt provides functionality to format descriptors.
Package descfmt provides functionality to format descriptors.
google.golang.org/protobuf/internal/descopts
Package descopts contains the nil pointers to concrete descriptor options.
Package descopts contains the nil pointers to concrete descriptor options.
google.golang.org/protobuf/internal/detrand
Package detrand provides deterministically random functionality.
Package detrand provides deterministically random functionality.
google.golang.org/protobuf/internal/encoding/defval
Package defval marshals and unmarshals textual forms of default values.
Package defval marshals and unmarshals textual forms of default values.
google.golang.org/protobuf/internal/encoding/messageset
Package messageset encodes and decodes the obsolete MessageSet wire format.
Package messageset encodes and decodes the obsolete MessageSet wire format.
google.golang.org/protobuf/internal/encoding/tag
Package tag marshals and unmarshals the legacy struct tags as generated by historical versions of protoc-gen-go.
Package tag marshals and unmarshals the legacy struct tags as generated by historical versions of protoc-gen-go.
google.golang.org/protobuf/internal/encoding/text
Package text implements the text format for protocol buffers.
Package text implements the text format for protocol buffers.
google.golang.org/protobuf/internal/errors
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors.
google.golang.org/protobuf/internal/filedesc
Package filedesc provides functionality for constructing descriptors.
Package filedesc provides functionality for constructing descriptors.
google.golang.org/protobuf/internal/filetype
Package filetype provides functionality for wrapping descriptors with Go type information.
Package filetype provides functionality for wrapping descriptors with Go type information.
google.golang.org/protobuf/internal/flags
Package flags provides a set of flags controlled by build tags.
Package flags provides a set of flags controlled by build tags.
google.golang.org/protobuf/internal/genid
Package genid contains constants for declarations in descriptor.proto and the well-known types.
Package genid contains constants for declarations in descriptor.proto and the well-known types.
google.golang.org/protobuf/internal/order
Package order provides ordered access to messages and maps.
Package order provides ordered access to messages and maps.
google.golang.org/protobuf/internal/pragma
Package pragma provides types that can be embedded into a struct to statically enforce or prevent certain language properties.
Package pragma provides types that can be embedded into a struct to statically enforce or prevent certain language properties.
google.golang.org/protobuf/internal/set
Package set provides simple set data structures for uint64s.
Package set provides simple set data structures for uint64s.
google.golang.org/protobuf/internal/strs
Package strs provides string manipulation functionality specific to protobuf.
Package strs provides string manipulation functionality specific to protobuf.
google.golang.org/protobuf/internal/version
Package version records versioning information about this module.
Package version records versioning information about this module.
google.golang.org/protobuf/proto
Package proto provides functions operating on protocol buffer messages.
Package proto provides functions operating on protocol buffer messages.
google.golang.org/protobuf/reflect/protodesc
Package protodesc provides functionality for converting FileDescriptorProto messages to/from protoreflect.FileDescriptor values.
Package protodesc provides functionality for converting FileDescriptorProto messages to/from protoreflect.FileDescriptor values.
google.golang.org/protobuf/reflect/protoreflect
Package protoreflect provides interfaces to dynamically manipulate messages.
Package protoreflect provides interfaces to dynamically manipulate messages.
google.golang.org/protobuf/reflect/protoregistry
Package protoregistry provides data structures to register and lookup protobuf descriptor types.
Package protoregistry provides data structures to register and lookup protobuf descriptor types.
google.golang.org/protobuf/runtime/protoiface
Package protoiface contains types referenced or implemented by messages.
Package protoiface contains types referenced or implemented by messages.
google.golang.org/protobuf/runtime/protoimpl
Package protoimpl contains the default implementation for messages generated by protoc-gen-go.
Package protoimpl contains the default implementation for messages generated by protoc-gen-go.
google.golang.org/protobuf/types/known/anypb
Package anypb contains generated types for google/protobuf/any.proto.
Package anypb contains generated types for google/protobuf/any.proto.
google.golang.org/protobuf/types/known/durationpb
Package durationpb contains generated types for google/protobuf/duration.proto.
Package durationpb contains generated types for google/protobuf/duration.proto.
google.golang.org/protobuf/types/known/timestamppb
Package timestamppb contains generated types for google/protobuf/timestamp.proto.
Package timestamppb contains generated types for google/protobuf/timestamp.proto.
gopkg.in/src-d/go-errors.v1
Yet another `errors` package, implementing errors handling primitives, allowing error wrapping and error tracing.
Yet another `errors` package, implementing errors handling primitives, allowing error wrapping and error tracing.

Jump to

Keyboard shortcuts

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