github.com/kaiya/goutils@v1.0.1-0.20230226104005-4ae4a4dc3688/tinyrpc/rpc/packet_test.go (about)

     1  package rpc
     2  
     3  import (
     4  	"bufio"
     5  	"compress/zlib"
     6  	"fmt"
     7  	"net"
     8  	"sync"
     9  	"testing"
    10  	"unsafe"
    11  )
    12  
    13  func Test_Encode(t *testing.T) {
    14  	testStr := "hello"
    15  	var wg sync.WaitGroup
    16  	server, client := net.Pipe()
    17  	// server side
    18  	wg.Add(1)
    19  	go func() {
    20  		defer wg.Done()
    21  		defer server.Close()
    22  		zipR, err := zlib.NewReader(server)
    23  		if err != nil {
    24  			t.Errorf("init zlib reader failed:%s", err)
    25  		}
    26  		bufconn := bufio.NewReader(zipR)
    27  		msg, err := DecodePacket(bufconn)
    28  		if err != nil {
    29  			fmt.Printf("decode packet error:%s\n", err)
    30  			return
    31  		}
    32  		fmt.Printf("got msg len:%d, %s ", len(msg), string(msg))
    33  		if res := string(msg); res != testStr {
    34  			t.Errorf("res:%s, want:%s", res, testStr)
    35  		}
    36  	}()
    37  
    38  	// client side
    39  	zip := zlib.NewWriter(client)
    40  	bufconn := bufio.NewWriter(zip)
    41  	err := EncodePacket(bufconn, []byte(testStr))
    42  	if err != nil {
    43  		fmt.Printf("encode error:%s", err)
    44  	}
    45  	bufconn.Flush()
    46  	zip.Flush()
    47  	client.Close()
    48  	wg.Wait()
    49  }
    50  
    51  func TestByte(t *testing.T) {
    52  	// abc
    53  	a := []byte{97, 98, 99}
    54  	// 65 66 67
    55  	b := "ABCD"
    56  	b = *(*string)(unsafe.Pointer(&a))
    57  	// b: 65 98 99 -> Abc
    58  	a[0] = 65
    59  	t.Logf("byte of b: %v, str of b:%s", []byte(b), b)
    60  }