path_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2013 Julien Schmidt. All rights reserved.
  2. // Based on the path package, Copyright 2009 The Go Authors.
  3. // Use of this source code is governed by a BSD-style license that can be found
  4. // in the LICENSE file.
  5. package httprouter
  6. import (
  7. "runtime"
  8. "testing"
  9. )
  10. var cleanTests = []struct {
  11. path, result string
  12. }{
  13. // Already clean
  14. {"/", "/"},
  15. {"/abc", "/abc"},
  16. {"/a/b/c", "/a/b/c"},
  17. {"/abc/", "/abc/"},
  18. {"/a/b/c/", "/a/b/c/"},
  19. // missing root
  20. {"", "/"},
  21. {"abc", "/abc"},
  22. {"abc/def", "/abc/def"},
  23. {"a/b/c", "/a/b/c"},
  24. // Remove doubled slash
  25. {"//", "/"},
  26. {"/abc//", "/abc/"},
  27. {"/abc/def//", "/abc/def/"},
  28. {"/a/b/c//", "/a/b/c/"},
  29. {"/abc//def//ghi", "/abc/def/ghi"},
  30. {"//abc", "/abc"},
  31. {"///abc", "/abc"},
  32. {"//abc//", "/abc/"},
  33. // Remove . elements
  34. {".", "/"},
  35. {"./", "/"},
  36. {"/abc/./def", "/abc/def"},
  37. {"/./abc/def", "/abc/def"},
  38. {"/abc/.", "/abc/"},
  39. // Remove .. elements
  40. {"..", "/"},
  41. {"../", "/"},
  42. {"../../", "/"},
  43. {"../..", "/"},
  44. {"../../abc", "/abc"},
  45. {"/abc/def/ghi/../jkl", "/abc/def/jkl"},
  46. {"/abc/def/../ghi/../jkl", "/abc/jkl"},
  47. {"/abc/def/..", "/abc"},
  48. {"/abc/def/../..", "/"},
  49. {"/abc/def/../../..", "/"},
  50. {"/abc/def/../../..", "/"},
  51. {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"},
  52. // Combinations
  53. {"abc/./../def", "/def"},
  54. {"abc//./../def", "/def"},
  55. {"abc/../../././../def", "/def"},
  56. }
  57. func TestPathClean(t *testing.T) {
  58. for _, test := range cleanTests {
  59. if s := CleanPath(test.path); s != test.result {
  60. t.Errorf("CleanPath(%q) = %q, want %q", test.path, s, test.result)
  61. }
  62. if s := CleanPath(test.result); s != test.result {
  63. t.Errorf("CleanPath(%q) = %q, want %q", test.result, s, test.result)
  64. }
  65. }
  66. }
  67. func TestPathCleanMallocs(t *testing.T) {
  68. if testing.Short() {
  69. t.Skip("skipping malloc count in short mode")
  70. }
  71. if runtime.GOMAXPROCS(0) > 1 {
  72. t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
  73. return
  74. }
  75. for _, test := range cleanTests {
  76. allocs := testing.AllocsPerRun(100, func() { CleanPath(test.result) })
  77. if allocs > 0 {
  78. t.Errorf("CleanPath(%q): %v allocs, want zero", test.result, allocs)
  79. }
  80. }
  81. }