server_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. "net"
  16. "sync"
  17. "testing"
  18. )
  19. var testport = "localhost:9090"
  20. type TestDebugLogger struct {
  21. DebugOutput bool
  22. LogPrint func(v ...interface{})
  23. }
  24. func (ds *TestDebugLogger) IsDebugOutputEnabled() bool {
  25. return ds.DebugOutput
  26. }
  27. func (ds *TestDebugLogger) PrintDebug(v ...interface{}) {
  28. if ds.DebugOutput {
  29. ds.LogPrint(v...)
  30. }
  31. }
  32. func TestServer(t *testing.T) {
  33. // Collect the print output
  34. var out bytes.Buffer
  35. debugLogger := &TestDebugLogger{true, func(v ...interface{}) {
  36. out.WriteString(fmt.Sprint(v...))
  37. out.WriteString("\n")
  38. }}
  39. dds := NewServer(func(c net.Conn, err net.Error) {
  40. if err != nil {
  41. t.Error(err)
  42. return
  43. }
  44. c.Write([]byte("Hello"))
  45. c.Close()
  46. })
  47. dds.DebugOutput = debugLogger.DebugOutput
  48. dds.LogPrint = debugLogger.LogPrint
  49. var wg sync.WaitGroup
  50. wg.Add(1)
  51. err := dds.Run(":abc", &wg)
  52. if err == nil {
  53. t.Error("Unexpected error return:", err)
  54. return
  55. }
  56. wg.Add(1)
  57. go func() {
  58. err := dds.Run(testport, &wg)
  59. if err != nil {
  60. t.Error(err)
  61. return
  62. }
  63. }()
  64. wg.Wait()
  65. // Server is now running
  66. ret, err := readSocket()
  67. if err != nil {
  68. t.Error(err)
  69. return
  70. }
  71. if ret != "Hello" {
  72. t.Error("Unexpected server response:", ret)
  73. return
  74. }
  75. wg.Add(1)
  76. dds.Shutdown()
  77. wg.Wait()
  78. }
  79. func readSocket() (string, error) {
  80. conn, err := net.Dial("tcp", testport)
  81. if err != nil {
  82. return "", err
  83. }
  84. defer conn.Close()
  85. var buf bytes.Buffer
  86. io.Copy(&buf, conn)
  87. return buf.String(), nil
  88. }