user_test.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package user
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "devt.de/common/httputil"
  14. )
  15. const TESTPORT = ":9090"
  16. const TESTQUERYURL = "http://localhost" + TESTPORT + "/foo"
  17. var handleCallback = func(w http.ResponseWriter, r *http.Request) {}
  18. var handleFunction = func(w http.ResponseWriter, r *http.Request) {
  19. // Check if a valid session cookie is there
  20. session, _ := UserSessionManager.GetSession("", w, r, false)
  21. handleCallback(w, r)
  22. if session == nil {
  23. w.Write([]byte("Content"))
  24. } else {
  25. w.Write([]byte(fmt.Sprint("Content - User session: ", session.User())))
  26. }
  27. }
  28. func TestMain(m *testing.M) {
  29. flag.Parse()
  30. // Setup a simple webserver
  31. hs, wg := startServer()
  32. if hs == nil {
  33. return
  34. }
  35. // Make sure the webserver shuts down
  36. defer stopServer(hs, wg)
  37. // Register a simple content delivery function
  38. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  39. // Call the wrapped handle function which then adds the authentication
  40. handleFunction(w, r)
  41. })
  42. // Run the tests
  43. res := m.Run()
  44. os.Exit(res)
  45. }
  46. func TestNoAuthNoSession(t *testing.T) {
  47. // By default there is no session and no authentication
  48. res, _ := sendTestRequest(TESTQUERYURL, "GET", nil, nil, nil)
  49. if res != "Content" {
  50. t.Error("Unexpected result:", res)
  51. return
  52. }
  53. // Trying to create an anonymous session should fail
  54. r, _ := http.NewRequest("GET", "", nil)
  55. _, err := UserSessionManager.GetSession("", nil, r, true)
  56. if err.Error() != "Cannot create a session without a user" {
  57. t.Error("Unexpected error:", err)
  58. return
  59. }
  60. }
  61. /*
  62. Send a request to a HTTP test server
  63. */
  64. func sendTestRequest(url string, method string, headers map[string]string,
  65. cookies []*http.Cookie, content []byte) (string, *http.Response) {
  66. var req *http.Request
  67. var err error
  68. // Create request
  69. if content != nil {
  70. req, err = http.NewRequest(method, url, bytes.NewBuffer(content))
  71. } else {
  72. req, err = http.NewRequest(method, url, nil)
  73. }
  74. // Add headers
  75. req.Header.Set("Content-Type", "application/json")
  76. for k, v := range headers {
  77. req.Header.Set(k, v)
  78. }
  79. // Add cookies
  80. for _, v := range cookies {
  81. req.AddCookie(v)
  82. }
  83. client := &http.Client{}
  84. resp, err := client.Do(req)
  85. if err != nil {
  86. panic(err)
  87. }
  88. defer resp.Body.Close()
  89. body, _ := ioutil.ReadAll(resp.Body)
  90. bodyStr := strings.Trim(string(body), " \n")
  91. // Try json decoding first
  92. out := bytes.Buffer{}
  93. err = json.Indent(&out, []byte(bodyStr), "", " ")
  94. if err == nil {
  95. return out.String(), resp
  96. }
  97. // Just return the body
  98. return bodyStr, resp
  99. }
  100. /*
  101. Start a HTTP test server.
  102. */
  103. func startServer() (*httputil.HTTPServer, *sync.WaitGroup) {
  104. hs := &httputil.HTTPServer{}
  105. var wg sync.WaitGroup
  106. wg.Add(1)
  107. go hs.RunHTTPServer(TESTPORT, &wg)
  108. wg.Wait()
  109. // Server is started
  110. if hs.LastError != nil {
  111. panic(hs.LastError)
  112. }
  113. return hs, &wg
  114. }
  115. /*
  116. Stop a started HTTP test server.
  117. */
  118. func stopServer(hs *httputil.HTTPServer, wg *sync.WaitGroup) {
  119. if hs.Running == true {
  120. wg.Add(1)
  121. // Server is shut down
  122. hs.Shutdown()
  123. wg.Wait()
  124. } else {
  125. panic("Server was not running as expected")
  126. }
  127. }