|
| 1 | +//go:build !windows |
| 2 | + |
| 3 | +/* |
| 4 | + * Copyright 2025 CloudWeGo Authors |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +package remote |
| 20 | + |
| 21 | +import ( |
| 22 | + "errors" |
| 23 | + "net" |
| 24 | + "strings" |
| 25 | + "sync/atomic" |
| 26 | + "syscall" |
| 27 | + "testing" |
| 28 | + "time" |
| 29 | + |
| 30 | + "github.com/cloudwego/kitex/internal/test" |
| 31 | +) |
| 32 | + |
| 33 | +var _ SetConnState = &mockConn{} |
| 34 | + |
| 35 | +type mockConn struct { |
| 36 | + net.Conn |
| 37 | + closed atomic.Bool |
| 38 | +} |
| 39 | + |
| 40 | +func (m *mockConn) SetConnState(c bool) { |
| 41 | + m.closed.Store(c) |
| 42 | +} |
| 43 | + |
| 44 | +func (m *mockConn) SyscallConn() (syscall.RawConn, error) { |
| 45 | + if sc, ok := m.Conn.(syscall.Conn); ok { |
| 46 | + return sc.SyscallConn() |
| 47 | + } |
| 48 | + return nil, errors.New("not syscall.Conn") |
| 49 | +} |
| 50 | + |
| 51 | +func TestConnectionStateCheck(t *testing.T) { |
| 52 | + // wrong connection type |
| 53 | + err := ConnectionStateCheck(net.Pipe()) |
| 54 | + test.Assert(t, err != nil) |
| 55 | + test.Assert(t, strings.Contains(err.Error(), "conn is not a syscall.Conn")) |
| 56 | + |
| 57 | + ln, err := net.Listen("tcp", "127.0.0.1:0") // 本地端口自动分配 |
| 58 | + test.Assert(t, err == nil, err) |
| 59 | + defer ln.Close() |
| 60 | + |
| 61 | + done := make(chan net.Conn) |
| 62 | + go func() { |
| 63 | + conn, e := ln.Accept() |
| 64 | + test.Assert(t, e == nil) |
| 65 | + done <- conn |
| 66 | + }() |
| 67 | + |
| 68 | + clientConn, err := net.Dial("tcp", ln.Addr().String()) |
| 69 | + test.Assert(t, err == nil, err) |
| 70 | + |
| 71 | + serverConn := <-done |
| 72 | + serverConnWithState := &mockConn{Conn: serverConn} |
| 73 | + // check, not closed |
| 74 | + err = ConnectionStateCheck(serverConnWithState) |
| 75 | + test.Assert(t, err == nil, err) |
| 76 | + test.Assert(t, !serverConnWithState.closed.Load()) |
| 77 | + |
| 78 | + // close conn |
| 79 | + clientConn.Close() |
| 80 | + time.Sleep(100 * time.Millisecond) |
| 81 | + |
| 82 | + // check, closed |
| 83 | + err = ConnectionStateCheck(serverConnWithState) |
| 84 | + test.Assert(t, err == nil, err) |
| 85 | + test.Assert(t, serverConnWithState.closed.Load()) |
| 86 | +} |
0 commit comments