gotest

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2024 License: MIT Imports: 18 Imported by: 0

README

gotest

gotest is a library that simulates the testing of cache, dao and handler.


Example of use

mock test cache

Example of a cache interface.

// UserExampleCache cache interface
type UserExampleCache interface {
	Set(ctx context.Context, id uint64, data *model.UserExample, duration time.Duration) error
	Get(ctx context.Context, id uint64) (ret *model.UserExample, err error)
}

// userExampleCache define a cache struct
type userExampleCache struct {
	cache cache.Cache
}

// NewUserExampleCache new a cache
func NewUserExampleCache(rdb *redis.Client) UserExampleCache {
	return &userExampleCache{
		// ...
	}
}

Test cache example

func newUserExampleCache() *gotest.RedisCache {
	testData := map[string]interface{}{
		"1": &model.UserExample{ID:1},
	}

	rc := gotest.NewRedisCache(testData)
	rc.ICache = NewUserExampleCache(rc.RedisClient)
	return rc
}

func Test_userExampleCache_Set(t *testing.T) {
	c := newUserExampleCache()
	defer c.Close()

	record := c.TestDataSlice[0].(*model.UserExample)
	err := c.ICache.(UserExampleCache).Set(c.Ctx, record.ID, record, time.Hour)
	if err != nil {
		t.Fatal(err)
	}
}

func Test_userExampleCache_Get(t *testing.T) {
	c := newUserExampleCache()
	defer c.Close()

	record := c.TestDataSlice[0].(*model.UserExample)
	err := c.ICache.(UserExampleCache).Set(c.Ctx, record.ID, record, time.Hour)
	if err != nil {
		t.Fatal(err)
	}

	got, err := c.ICache.(UserExampleCache).Get(c.Ctx, record.ID)
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, record, got)
}

Simulation test dao

Click to see the specific example.


Mock Test Handler

func newHandler() *Handler {
	now := time.Now()
	testData := &User{
		ID:        1,
		Name:      "foo",
		CreatedAt: now,
		UpdatedAt: now,
	}

	// init mock cache
	c := gotest.NewCache(map[string]interface{}{"no cache": testData})
	c.ICache = struct{}{} // instantiated cache interface

	// init mock dao
	d := gotest.NewDao(c, testData)
	d.IDao = struct{}{} // instantiated dao interface

	// init mock handler
	h := gotest.NewHandler(d, testData)
	h.IHandler = struct{}{} // instantiated handler interface

	h := newHandler()
	defer h.Close()

	h.GoRunHttpServer([]gotest.RouterInfo{
		{
			FuncName: "GetByID",
			Method:   http.MethodGet,
			Path:     "/user/:id",
			HandlerFunc: func(c *gin.Context) {
				c.String(http.StatusOK, testData.Name)
			},
		},
	})

	return h
}

func TestGetHello(t *testing.T) {
	h := newHandler()
	defer h.Close()
	testData := h.TestData.(*User)

	rows := sqlmock.NewRows([]string{"id", "created_at", "updated_at"}).
		AddRow(testData.ID, testData.CreatedAt, testData.UpdatedAt)

	h.MockDao.SqlMock.ExpectQuery("SELECT .*").
		WithArgs(testData.ID).
		WillReturnRows(rows)

	result := &gohttp.StdResult{}
	err := gohttp.Get(result, h.GetRequestURL("GetByID", testData.ID))
	if err != nil {
		t.Fatal(err)
	}
	if result.Code != 0 {
		t.Fatalf("%+v", result)
	}
}

Documentation

Overview

Package gotest is a library that simulates the testing of cache, dao and handler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	Ctx           context.Context
	TestDataSlice []interface{}
	TestDataMap   map[string]interface{}
	RedisClient   *redis.Client

	ICache interface{}
	// contains filtered or unexported fields
}

Cache redis cache

func NewCache

func NewCache(testDataMap map[string]interface{}) *Cache

NewCache instantiated redis cache

func (*Cache) Close

func (c *Cache) Close()

Close redis server

func (*Cache) GetIDs

func (c *Cache) GetIDs() []uint64

GetIDs get test data ids

func (*Cache) GetTestData

func (c *Cache) GetTestData() map[string]interface{}

GetTestData get test data

type Dao

type Dao struct {
	Ctx      context.Context
	TestData interface{}
	SQLMock  sqlmock.Sqlmock
	Cache    *Cache
	DB       *gorm.DB
	IDao     interface{}
	AnyTime  *anyTime
	// contains filtered or unexported fields
}

Dao dao info

func NewDao

func NewDao(c *Cache, testData interface{}) *Dao

NewDao instantiated dao

func (*Dao) Close

func (d *Dao) Close()

Close dao

func (*Dao) GetAnyArgs

func (d *Dao) GetAnyArgs(obj interface{}) []driver.Value

GetAnyArgs Dynamic generation of parameter types based on structures

type Handler

type Handler struct {
	TestData interface{}
	MockDao  *Dao
	IHandler interface{}

	Engine     *gin.Engine
	HTTPServer *http.Server
	// contains filtered or unexported fields
}

Handler info

func NewHandler

func NewHandler(dao *Dao, testData interface{}) *Handler

NewHandler instantiated handler

func (*Handler) Close

func (h *Handler) Close()

Close handler

func (*Handler) GetRequestURL

func (h *Handler) GetRequestURL(funcName string, pathVal ...interface{}) string

GetRequestURL get request url from name

func (*Handler) GoRunHTTPServer

func (h *Handler) GoRunHTTPServer(fns []RouterInfo)

GoRunHTTPServer run http server

type RouterInfo

type RouterInfo struct {
	FuncName    string
	Method      string
	Path        string
	HandlerFunc gin.HandlerFunc
}

RouterInfo router info

type Service

type Service struct {
	Ctx      context.Context
	TestData interface{}
	MockDao  *Dao

	Server *grpc.Server

	IServiceClient interface{}
	// contains filtered or unexported fields
}

Service info

func NewService

func NewService(dao *Dao, testData interface{}) *Service

NewService instantiated service

func (*Service) Close

func (s *Service) Close()

Close service

func (*Service) GetClientConn

func (s *Service) GetClientConn() *grpc.ClientConn

GetClientConn dial rpc server

func (*Service) GoGrpcServer

func (s *Service) GoGrpcServer()

GoGrpcServer run grpc server

Jump to

Keyboard shortcuts

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