istio.io/istio@v0.0.0-20240520182934-d79c90f27776/samples/tcp-echo/src/main_test.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "bufio" 19 "net" 20 "os" 21 "strings" 22 "testing" 23 "time" 24 ) 25 26 // TestTcpEchoServer tests the behavior of the TCP Echo Server. 27 func TestTcpEchoServer(t *testing.T) { 28 // set up test parameters 29 prefix := "hello" 30 request := "world" 31 want := prefix + " " + request 32 33 // start the TCP Echo Server 34 os.Args = []string{"main", "9000,9001", prefix} 35 go main() 36 37 // wait for the TCP Echo Server to start 38 time.Sleep(500 * time.Millisecond) 39 40 for _, addr := range []string{":9000", ":9001"} { 41 // connect to the TCP Echo Server 42 conn, err := net.Dial("tcp", addr) 43 if err != nil { 44 t.Fatalf("couldn't connect to the server: %v", err) 45 } 46 defer conn.Close() 47 48 // test the TCP Echo Server output 49 if _, err := conn.Write([]byte(request + "\n")); err != nil { 50 t.Fatalf("couldn't send request: %v", err) 51 } else { 52 reader := bufio.NewReader(conn) 53 if response, err := reader.ReadBytes(byte('\n')); err != nil { 54 t.Fatalf("couldn't read server response: %v", err) 55 } else if !strings.HasPrefix(string(response), want) { 56 t.Errorf("output doesn't match, wanted: %s, got: %s", want, response) 57 } 58 } 59 } 60 }