base_test.go 2.8 KB
package controllers

import (
	"fmt"
	redigo "github.com/gomodule/redigo/redis"
	"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
	"log"
	"opp/protocol"
	"opp/tests"
	"reflect"
	"testing"
	"time"
)

func init() {
	tests.Init()
}

func Test_GenMessage(t *testing.T) {
	input := []struct {
		Rsp     interface{}
		Error   error
		Exceprt *protocol.ResponseMessage
	}{
		{Rsp: "test", Error: fmt.Errorf("test"), Exceprt: protocol.NewErrWithMessage(1, fmt.Errorf("test")).ParseToMessage()},
		{Rsp: "test-A", Error: protocol.NewErrWithMessage(100, fmt.Errorf("test-A")), Exceprt: protocol.NewErrWithMessage(100, fmt.Errorf("test-A")).ParseToMessage()},
	}
	for i := range input {
		o := input[i]
		out := protocol.NewReturnResponse(o.Rsp, o.Error)
		if !reflect.DeepEqual(out, o.Exceprt) {
			log.Fatal("not equal ", out, o.Exceprt)
		}
	}
}

func Benchmark_GenMessage(b *testing.B) {
	o := struct {
		Rsp     interface{}
		Error   error
		Exceprt *protocol.ResponseMessage
	}{Rsp: "test", Error: fmt.Errorf("test"), Exceprt: protocol.NewErrWithMessage(1, fmt.Errorf("test-A")).ParseToMessage()}
	for i := 0; i < b.N; i++ {
		out := protocol.NewReturnResponse(o.Rsp, o.Error)
		if out.Errmsg != o.Exceprt.Errmsg || out.Errno != o.Exceprt.Errno {
			log.Fatal("not equal ", out, o.Exceprt)
		}
	}
}

func Test_Valid(t *testing.T) {
	/*修改手机号*/
	type ChangePhoneRequest struct {
		Phone   string `json:"phone" valid:"Mobile"`
		Captcha string `json:"captcha" valid:"Required"`
	}
	req := &ChangePhoneRequest{
		"1886018",
		"123",
	}
	DefaultController.Valid(req)
}

func Test_RedisSubPub(t *testing.T) {
	c := redis.NewClient()
	defer c.Close()
	/*redis 订阅*/
	go subscribe()
	go subscribe()
	go subscribe()

	for {
		var s string
		s = time.Now().String()
		_, err := c.Do("PUBLISH", "chat", s)
		if err != nil {
			fmt.Println("pub err: ", err)
			return
		}
		time.Sleep(time.Second * 5)
	}
}

func subscribe() {
	psc := redis.NewPubsubClient()
	defer func() {
		psc.Conn.Close()
		psc.Unsubscribe("chat")
	}()

	psc.Subscribe("chat")

	for {
		switch v := psc.Receive().(type) {
		case redigo.Message:
			log.Println(fmt.Printf("%s: message: %s\n", v.Channel, v.Data))
		case redigo.Subscription:
			log.Println(fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count))
		case error:
			log.Println("error:", v)
			return
		}
	}
}

//redis lock
func Test_RedisLock(t *testing.T) {
	//key :="opp:chance:1456872"
	//go func(){
	//	mutext :=redis.NewMutex(key)
	//	mutext.Lock()
	//	defer mutext.UnLock()
	//	time.Sleep(time.Second*10)
	//}()
	//time.Sleep(time.Second*1)
	//go func(){
	//	mutext :=redis.NewMutex(key)
	//	defer mutext.UnLock()
	//	if !mutext.TryLock(3){
	//		t.Log("fail to get lock",key)
	//		return
	//	}
	//	t.Log("get lock...")
	//	time.Sleep(time.Second*3)
	//	t.Log("release lock...")
	//}()
	//time.Sleep(11*time.Second)
}