server_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * DudelDu
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package dudeldu
  11. import (
  12. "bytes"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net"
  17. "sync"
  18. "testing"
  19. )
  20. var testport = "localhost:9090"
  21. func TestServer(t *testing.T) {
  22. DebugOutput = true
  23. var out bytes.Buffer
  24. // Collect the print output
  25. Print = func(v ...interface{}) {
  26. out.WriteString(fmt.Sprint(v...))
  27. out.WriteString("\n")
  28. }
  29. defer func() {
  30. Print = log.Print
  31. }()
  32. dds := NewServer(func(c net.Conn, err net.Error) {
  33. if err != nil {
  34. t.Error(err)
  35. return
  36. }
  37. c.Write([]byte("Hello"))
  38. c.Close()
  39. })
  40. var wg sync.WaitGroup
  41. wg.Add(1)
  42. err := dds.Run(":abc", &wg)
  43. if err == nil {
  44. t.Error("Unexpected error return:", err)
  45. return
  46. }
  47. wg.Add(1)
  48. go func() {
  49. err := dds.Run(testport, &wg)
  50. if err != nil {
  51. t.Error(err)
  52. return
  53. }
  54. }()
  55. wg.Wait()
  56. // Server is now running
  57. ret, err := readSocket()
  58. if err != nil {
  59. t.Error(err)
  60. return
  61. }
  62. if ret != "Hello" {
  63. t.Error("Unexpected server response:", ret)
  64. return
  65. }
  66. wg.Add(1)
  67. dds.Shutdown()
  68. wg.Wait()
  69. }
  70. func readSocket() (string, error) {
  71. conn, err := net.Dial("tcp", testport)
  72. if err != nil {
  73. return "", err
  74. }
  75. defer conn.Close()
  76. var buf bytes.Buffer
  77. io.Copy(&buf, conn)
  78. return buf.String(), nil
  79. }