Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.6 KiB

7 years ago
  1. package wrouter
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "git.aiterp.net/gisle/wrouter/auth"
  8. )
  9. type testRoute struct {
  10. Name string
  11. }
  12. func (tr *testRoute) Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
  13. w.WriteHeader(200)
  14. w.Write([]byte(tr.Name))
  15. return true
  16. }
  17. func TestPaths(t *testing.T) {
  18. tr1 := testRoute{"Test Route 1"}
  19. tr2 := testRoute{"Test Route 2"}
  20. router := Router{}
  21. router.Route("/test1", &tr1)
  22. router.Route("/test2", &tr2)
  23. t.Run("It finds /test1", func(t *testing.T) {
  24. req := httptest.NewRequest("GET", "http://test.aiterp.net/test1", nil)
  25. w := httptest.NewRecorder()
  26. router.ServeHTTP(w, req)
  27. data, _ := ioutil.ReadAll(w.Body)
  28. if string(data) != "Test Route 1" {
  29. t.Error("Wrong content:", string(data))
  30. t.Fail()
  31. }
  32. if w.Code != 200 {
  33. t.Error("Wrong code:", w.Code)
  34. t.Fail()
  35. }
  36. })
  37. t.Run("It finds /test2", func(t *testing.T) {
  38. req := httptest.NewRequest("GET", "http://test.aiterp.net/test2", nil)
  39. w := httptest.NewRecorder()
  40. router.ServeHTTP(w, req)
  41. data, _ := ioutil.ReadAll(w.Body)
  42. if string(data) != "Test Route 2" {
  43. t.Error("Wrong content:", string(data))
  44. t.Fail()
  45. }
  46. if w.Header().Get("X-Route-Index") != "1" {
  47. t.Error("Wrong index:", w.Code)
  48. t.Fail()
  49. }
  50. if w.Code != 200 {
  51. t.Error("Wrong code:", w.Code)
  52. t.Fail()
  53. }
  54. })
  55. t.Run("It does not find /test3", func(t *testing.T) {
  56. req := httptest.NewRequest("GET", "http://test.aiterp.net/test3", nil)
  57. w := httptest.NewRecorder()
  58. router.ServeHTTP(w, req)
  59. if w.Code != 404 {
  60. t.Error("Wrong code:", w.Code)
  61. t.Fail()
  62. }
  63. })
  64. }