github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/pkg/httputil/httputil_test.go (about) 1 // Copyright 2020 PingCAP, Inc. 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package httputil 15 16 import ( 17 "context" 18 "crypto/tls" 19 "fmt" 20 "io/ioutil" 21 "net" 22 "net/http" 23 "os" 24 "path/filepath" 25 "testing" 26 27 "github.com/pingcap/check" 28 "github.com/pingcap/ticdc/pkg/security" 29 "github.com/pingcap/ticdc/pkg/util/testleak" 30 "github.com/pingcap/tidb-tools/pkg/utils" 31 ) 32 33 func Test(t *testing.T) { check.TestingT(t) } 34 35 type httputilSuite struct{} 36 37 var _ = check.Suite(&httputilSuite{}) 38 39 var httputilServerMsg = "this is httputil test server" 40 41 func (s *httputilSuite) TestHttputilNewClient(c *check.C) { 42 defer testleak.AfterTest(c)() 43 port := 8303 44 _, cancel := context.WithCancel(context.Background()) 45 46 dir, err := os.Getwd() 47 c.Assert(err, check.IsNil) 48 certDir := "_certificates" 49 serverTLS, err := utils.ToTLSConfigWithVerify( 50 filepath.Join(dir, certDir, "ca.pem"), 51 filepath.Join(dir, certDir, "server.pem"), 52 filepath.Join(dir, certDir, "server-key.pem"), 53 []string{}, 54 ) 55 c.Assert(err, check.IsNil) 56 server := runServer(serverTLS, port, c) 57 defer func() { 58 cancel() 59 server.Close() 60 }() 61 credential := &security.Credential{ 62 CAPath: filepath.Join(dir, certDir, "ca.pem"), 63 CertPath: filepath.Join(dir, certDir, "client.pem"), 64 KeyPath: filepath.Join(dir, certDir, "client-key.pem"), 65 CertAllowedCN: []string{}, 66 } 67 cli, err := NewClient(credential) 68 c.Assert(err, check.IsNil) 69 url := fmt.Sprintf("https://127.0.0.1:%d/", port) 70 resp, err := cli.Get(url) 71 c.Assert(err, check.IsNil) 72 defer resp.Body.Close() 73 body, err := ioutil.ReadAll(resp.Body) 74 c.Assert(err, check.IsNil) 75 c.Assert(string(body), check.Equals, httputilServerMsg) 76 } 77 78 func handler(w http.ResponseWriter, req *http.Request) { 79 w.Header().Set("Content-Type", "text/plain") 80 //nolint:errcheck 81 w.Write([]byte(httputilServerMsg)) 82 } 83 84 func runServer(tlsCfg *tls.Config, port int, c *check.C) *http.Server { 85 http.HandleFunc("/", handler) 86 server := &http.Server{Addr: fmt.Sprintf(":%d", port), Handler: nil} 87 88 conn, err := net.Listen("tcp", server.Addr) 89 if err != nil { 90 c.Assert(err, check.IsNil) 91 } 92 93 tlsListener := tls.NewListener(conn, tlsCfg) 94 go func() { 95 //nolint:errcheck 96 server.Serve(tlsListener) 97 }() 98 return server 99 }