github.com/cloudwego/hertz@v0.9.3/pkg/network/netpoll/dial_test.go (about)

     1  // Copyright 2023 CloudWeGo 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  
    16  //go:build !windows
    17  // +build !windows
    18  
    19  package netpoll
    20  
    21  import (
    22  	"context"
    23  	"crypto/tls"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/cloudwego/hertz/pkg/common/config"
    28  	"github.com/cloudwego/hertz/pkg/common/test/assert"
    29  	"github.com/cloudwego/hertz/pkg/common/test/mock"
    30  )
    31  
    32  func TestDial(t *testing.T) {
    33  	t.Run("NetpollDial", func(t *testing.T) {
    34  		const nw = "tcp"
    35  		const addr = "localhost:10100"
    36  		transporter := NewTransporter(&config.Options{
    37  			Addr:    addr,
    38  			Network: nw,
    39  		})
    40  		go transporter.ListenAndServe(func(ctx context.Context, conn interface{}) error {
    41  			return nil
    42  		})
    43  		defer transporter.Close()
    44  		time.Sleep(100 * time.Millisecond)
    45  
    46  		dial := NewDialer()
    47  		// DialConnection
    48  		_, err := dial.DialConnection("tcp", "localhost:10101", time.Second, nil) // wrong addr
    49  		assert.NotNil(t, err)
    50  
    51  		nwConn, err := dial.DialConnection(nw, addr, time.Second, nil)
    52  		assert.Nil(t, err)
    53  		defer nwConn.Close()
    54  		_, err = nwConn.Write([]byte("abcdef"))
    55  		assert.Nil(t, err)
    56  		// DialTimeout
    57  		nConn, err := dial.DialTimeout(nw, addr, time.Second, nil)
    58  		assert.Nil(t, err)
    59  		defer nConn.Close()
    60  	})
    61  
    62  	t.Run("NotSupportTLS", func(t *testing.T) {
    63  		dial := NewDialer()
    64  		_, err := dial.AddTLS(mock.NewConn(""), nil)
    65  		assert.DeepEqual(t, errNotSupportTLS, err)
    66  		_, err = dial.DialConnection("tcp", "localhost:10102", time.Microsecond, &tls.Config{})
    67  		assert.DeepEqual(t, errNotSupportTLS, err)
    68  		_, err = dial.DialTimeout("tcp", "localhost:10102", time.Microsecond, &tls.Config{})
    69  		assert.DeepEqual(t, errNotSupportTLS, err)
    70  	})
    71  }