package microservice import ( "context" "log" "net" "testing" "time" "git.ali33.ru/fcg-xvii/go-tools/json" ) func TestProtoData(t *testing.T) { work := func(u *ProtocolData, name string) { for data := range u.Receiver() { t.Logf("%v data: %v", name, data) time.Sleep(time.Second / 3) u.Send(data) } } c1, c2 := net.Pipe() u1 := MakeProtocolData(c1, context.Background()) u2 := MakeProtocolData(c2, context.Background()) go work(u1, "u1") go work(u2, "u2") time.Sleep(time.Second * 2) u1.Send([]byte{1, 2, 3, 4, 5}) time.Sleep(time.Second * 100) u1.Close() time.Sleep(time.Second * 10) } func TestProtoJSON(t *testing.T) { work := func(u *ProtocolJSON, name string) { for m := range u.Receiver() { t.Logf("%v data: %v", name, m) time.Sleep(time.Second * 3) u.Send(m) } } c1, c2 := net.Pipe() u1 := MakeProtocolJSON(c1, context.Background(), 1000) u2 := MakeProtocolJSON(c2, context.Background(), 1000) go work(u1, "u1") go work(u2, "u2") u1.Send(json.Map{ "one": 1, "two": 2, }) time.Sleep(time.Second * 20) u1.Close() time.Sleep(time.Second * 10) } func TestSocket(t *testing.T) { work := func(s *Socket, name string) { for { select { case <-s.Context().Done(): log.Println("DONE....") return case q, ok := <-s.RecvQuestion(): if ok { log.Println("Question", name, q.Data()) } q.Answer(json.Map{ "answer": true, "ts": time.Now().Unix(), }) time.Sleep(time.Second) s.SendQuestion( NewQuestion( json.Map{ "ts": time.Now().Unix(), }, 0, ), ) case e, ok := <-s.RecvEvent(): if ok { log.Println("Event", e.Data()) q := NewQuestion( json.Map{ "r-answer": "OK", }, 0, ) time.Sleep(time.Second) s.SendQuestion(q) } } } } c1, c2 := net.Pipe() s1 := NewSocket(c1, 10, context.Background(), 1000) s2 := NewSocket(c2, 10, context.Background(), 1000) go work(s1, "s1") go work(s2, "s2") log.Println(s1, s2) time.Sleep(time.Second * 2) s1.SendEvent(NewEvent(json.Map{ "one": 1, })) time.Sleep(time.Second * 2) q := NewQuestion( json.Map{ "ok": true, }, time.Second*5, ) s1.SendQuestion(q) time.Sleep(time.Second * 20) c1.Close() time.Sleep(time.Second * 30) } func TestServer(t *testing.T) { host, port := "127.0.0.1", uint16(4500) newServer := func() *Server { serv := NewServer(host, port, 10, context.Background(), 1000) log.Println(serv) go func() { socket, ok := <-serv.NewConnection() if !ok { log.Println("connection error") } for { select { case e := <-socket.RecvEvent(): log.Println("event", e) case q := <-socket.RecvQuestion(): log.Println("question", q) } } }() return serv } serv := newServer() log.Println(serv) cl := NewSocketClient(host, port, 10, context.Background(), 1000) log.Println(cl) time.Sleep(time.Second * 20) serv.Close() //cl.Close() log.Println("serv closed") time.Sleep(time.Second * 30) serv = newServer() time.Sleep(time.Second * 30) serv.Close() log.Println("serv-closed-2") time.Sleep(time.Second * 50) cl.Close() time.Sleep(time.Second * 50) }