user_test.go 3.2 KB

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