report_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package trace
  2. import (
  3. "bytes"
  4. "io"
  5. "log"
  6. "net"
  7. "os"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func newServer(w io.Writer, network, address string) (func() error, error) {
  12. lis, err := net.Listen(network, address)
  13. if err != nil {
  14. return nil, err
  15. }
  16. done := make(chan struct{})
  17. go func() {
  18. conn, err := lis.Accept()
  19. if err != nil {
  20. lis.Close()
  21. log.Fatal(err)
  22. }
  23. io.Copy(w, conn)
  24. conn.Close()
  25. done <- struct{}{}
  26. }()
  27. return func() error {
  28. <-done
  29. return lis.Close()
  30. }, nil
  31. }
  32. func TestReportTCP(t *testing.T) {
  33. buf := &bytes.Buffer{}
  34. cancel, err := newServer(buf, "tcp", "127.0.0.1:6077")
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. report := newReport("tcp", "127.0.0.1:6077", 0, 0).(*connReport)
  39. data := []byte("hello, world")
  40. report.writePackage(data)
  41. if err := report.Close(); err != nil {
  42. t.Error(err)
  43. }
  44. cancel()
  45. assert.Equal(t, data, buf.Bytes(), "receive data")
  46. }
  47. func newUnixgramServer(w io.Writer, address string) (func() error, error) {
  48. conn, err := net.ListenPacket("unixgram", address)
  49. if err != nil {
  50. return nil, err
  51. }
  52. done := make(chan struct{})
  53. go func() {
  54. p := make([]byte, 4096)
  55. n, _, err := conn.ReadFrom(p)
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. w.Write(p[:n])
  60. done <- struct{}{}
  61. }()
  62. return func() error {
  63. <-done
  64. return conn.Close()
  65. }, nil
  66. }
  67. func TestReportUnixgram(t *testing.T) {
  68. os.Remove("/tmp/trace.sock")
  69. buf := &bytes.Buffer{}
  70. cancel, err := newUnixgramServer(buf, "/tmp/trace.sock")
  71. if err != nil {
  72. t.Fatal(err)
  73. }
  74. report := newReport("unixgram", "/tmp/trace.sock", 0, 0).(*connReport)
  75. data := []byte("hello, world")
  76. report.writePackage(data)
  77. if err := report.Close(); err != nil {
  78. t.Error(err)
  79. }
  80. cancel()
  81. assert.Equal(t, data, buf.Bytes(), "receive data")
  82. }