github.com/v2fly/v2ray-core/v4@v4.45.2/proxy/trojan/protocol_test.go (about) 1 package trojan_test 2 3 import ( 4 "testing" 5 6 "github.com/google/go-cmp/cmp" 7 8 "github.com/v2fly/v2ray-core/v4/common" 9 "github.com/v2fly/v2ray-core/v4/common/buf" 10 "github.com/v2fly/v2ray-core/v4/common/net" 11 "github.com/v2fly/v2ray-core/v4/common/protocol" 12 . "github.com/v2fly/v2ray-core/v4/proxy/trojan" 13 ) 14 15 func toAccount(a *Account) protocol.Account { 16 account, err := a.AsAccount() 17 common.Must(err) 18 return account 19 } 20 21 func TestTCPRequest(t *testing.T) { 22 user := &protocol.MemoryUser{ 23 Email: "love@v2fly.org", 24 Account: toAccount(&Account{ 25 Password: "password", 26 }), 27 } 28 payload := []byte("test string") 29 data := buf.New() 30 common.Must2(data.Write(payload)) 31 32 buffer := buf.New() 33 defer buffer.Release() 34 35 destination := net.Destination{Network: net.Network_TCP, Address: net.LocalHostIP, Port: 1234} 36 writer := &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)} 37 common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data})) 38 39 reader := &ConnReader{Reader: buffer} 40 common.Must(reader.ParseHeader()) 41 42 if r := cmp.Diff(reader.Target, destination); r != "" { 43 t.Error("destination: ", r) 44 } 45 46 decodedData, err := reader.ReadMultiBuffer() 47 common.Must(err) 48 if r := cmp.Diff(decodedData[0].Bytes(), payload); r != "" { 49 t.Error("data: ", r) 50 } 51 } 52 53 func TestUDPRequest(t *testing.T) { 54 user := &protocol.MemoryUser{ 55 Email: "love@v2fly.org", 56 Account: toAccount(&Account{ 57 Password: "password", 58 }), 59 } 60 payload := []byte("test string") 61 data := buf.New() 62 common.Must2(data.Write(payload)) 63 64 buffer := buf.New() 65 defer buffer.Release() 66 67 destination := net.Destination{Network: net.Network_UDP, Address: net.LocalHostIP, Port: 1234} 68 writer := &PacketWriter{Writer: &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)}, Target: destination} 69 common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data})) 70 71 connReader := &ConnReader{Reader: buffer} 72 common.Must(connReader.ParseHeader()) 73 74 packetReader := &PacketReader{Reader: connReader} 75 p, err := packetReader.ReadMultiBufferWithMetadata() 76 common.Must(err) 77 78 if p.Buffer.IsEmpty() { 79 t.Error("no request data") 80 } 81 82 if r := cmp.Diff(p.Target, destination); r != "" { 83 t.Error("destination: ", r) 84 } 85 86 mb, decoded := buf.SplitFirst(p.Buffer) 87 buf.ReleaseMulti(mb) 88 89 if r := cmp.Diff(decoded.Bytes(), payload); r != "" { 90 t.Error("data: ", r) 91 } 92 }