github.com/deemoprobe/k8s-first-commit@v0.0.0-20230430165612-a541f1982be3/pkg/proxy/proxier_test.go (about) 1 /* 2 Copyright 2014 Google Inc. All rights reserved. 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 proxy 18 19 import ( 20 "fmt" 21 "io" 22 "net" 23 "testing" 24 25 "github.com/GoogleCloudPlatform/kubernetes/pkg/api" 26 ) 27 28 // a simple echoServer that only accept one connection 29 func echoServer(addr string) error { 30 l, err := net.Listen("tcp", addr) 31 if err != nil { 32 return fmt.Errorf("failed to start echo service: %v", err) 33 } 34 defer l.Close() 35 conn, err := l.Accept() 36 if err != nil { 37 return fmt.Errorf("failed to accept new conn to echo service: %v", err) 38 } 39 io.Copy(conn, conn) 40 conn.Close() 41 return nil 42 } 43 44 func TestProxy(t *testing.T) { 45 go func() { 46 if err := echoServer("127.0.0.1:2222"); err != nil { 47 t.Fatal(err) 48 } 49 }() 50 51 lb := NewLoadBalancerRR() 52 lb.OnUpdate([]api.Endpoints{{"echo", []string{"127.0.0.1:2222"}}}) 53 54 p := NewProxier(lb) 55 if err := p.AddService("echo", 2223); err != nil { 56 t.Fatalf("error adding new service: %v", err) 57 } 58 conn, err := net.Dial("tcp", "127.0.0.1:2223") 59 if err != nil { 60 t.Fatalf("error connecting to proxy: %v", err) 61 } 62 magic := "aaaaa" 63 if _, err := conn.Write([]byte(magic)); err != nil { 64 t.Fatalf("error writing to proxy: %v", err) 65 } 66 buf := make([]byte, 5) 67 if _, err := conn.Read(buf); err != nil { 68 t.Fatalf("error reading from proxy: %v", err) 69 } 70 if string(buf) != magic { 71 t.Fatalf("bad echo from proxy: got: %q, expected %q", string(buf), magic) 72 } 73 }