Debian Codegraph @

tests/tcp_server_test.go

raw symbols SCIP
1 /*
2 Copyright 2022 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package tests
18
19 import (
20 "context"
21 "net"
22 "testing"
23
24 "k8s.io/klog/v2"
25 )
26
27 func echo(conn net.Conn) {
28 var data [256]byte
29
30 for {
31 n, err := conn.Read(data[:])
32 if err != nil {
33 klog.Info(err)
34 return
35 }
36
37 _, err = conn.Write(data[:n])
38 if err != nil {
39 klog.Info(err)
40 return
41 }
42 }
43 }
44
45 func TestEchoServer(t *testing.T) {
46 ctx := context.Background()
47 ln, err := net.Listen("tcp", "")
48 if err != nil {
49 t.Error(err)
50 }
51
52 go func() {
53 for {
54 conn, err := ln.Accept()
55 if err != nil {
56 klog.Info(err)
57 break
58 }
59 go echo(conn)
60 }
61 }()
62
63 ps := runGRPCProxyServer(t)
64 defer ps.Stop()
65
66 a := runAgent(t, ps.AgentAddr())
67 defer a.Stop()
68 waitForConnectedServerCount(t, 1, a)
69
70 // run test client
71 tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
72 if err != nil {
73 t.Fatal(err)
74 }
75
76 conn, err := tunnel.DialContext(ctx, "tcp", ln.Addr().String())
77 if err != nil {
78 t.Error(err)
79 }
80
81 msg := "1234567890123456789012345"
82 n, err := conn.Write([]byte(msg))
83 if err != nil {
84 t.Error(err)
85 }
86 if n != len(msg) {
87 t.Errorf("expect write %d; got %d", len(msg), n)
88 }
89
90 var data [10]byte
91
92 n, err = conn.Read(data[:])
93 if err != nil {
94 t.Error(err)
95 }
96 if string(data[:n]) != msg[:10] {
97 t.Errorf("expect %s; got %s", msg[:10], string(data[:n]))
98 }
99
100 n, err = conn.Read(data[:])
101 if err != nil {
102 t.Error(err)
103 }
104 if string(data[:n]) != msg[10:20] {
105 t.Errorf("expect %s; got %s", msg[10:20], string(data[:n]))
106 }
107
108 msg2 := "1234567"
109 n, err = conn.Write([]byte(msg2))
110 if err != nil {
111 t.Error(err)
112 }
113 if n != len(msg2) {
114 t.Errorf("expect write %d; got %d", len(msg2), n)
115 }
116
117 n, err = conn.Read(data[:])
118 if err != nil {
119 t.Error(err)
120 }
121 if string(data[:n]) != msg[20:] {
122 t.Errorf("expect %s; got %s", msg[20:], string(data[:n]))
123 }
124
125 n, err = conn.Read(data[:])
126 if err != nil {
127 t.Error(err)
128 }
129 if string(data[:n]) != msg2 {
130 t.Errorf("expect %s; got %s", msg, string(data[:n]))
131 }
132
133 if err := conn.Close(); err != nil {
134 t.Error(err)
135 }
136 }