TestContextFile tests the Context.File() method
(t *testing.T)
| 78 | |
| 79 | // TestContextFile tests the Context.File() method |
| 80 | func TestContextFile(t *testing.T) { |
| 81 | // Test serving an existing file |
| 82 | t.Run("serve existing file", func(t *testing.T) { |
| 83 | // Create a temporary test file |
| 84 | testFile := "testdata/test_file.txt" |
| 85 | |
| 86 | w := httptest.NewRecorder() |
| 87 | c, _ := CreateTestContext(w) |
| 88 | c.Request = httptest.NewRequest(http.MethodGet, "/test", nil) |
| 89 | |
| 90 | c.File(testFile) |
| 91 | |
| 92 | assert.Equal(t, http.StatusOK, w.Code) |
| 93 | assert.Contains(t, w.Body.String(), "This is a test file") |
| 94 | assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) |
| 95 | }) |
| 96 | |
| 97 | // Test serving a non-existent file |
| 98 | t.Run("serve non-existent file", func(t *testing.T) { |
| 99 | w := httptest.NewRecorder() |
| 100 | c, _ := CreateTestContext(w) |
| 101 | c.Request = httptest.NewRequest(http.MethodGet, "/test", nil) |
| 102 | |
| 103 | c.File("non_existent_file.txt") |
| 104 | |
| 105 | assert.Equal(t, http.StatusNotFound, w.Code) |
| 106 | }) |
| 107 | |
| 108 | // Test serving a directory (should return 200 with directory listing or 403 Forbidden) |
| 109 | t.Run("serve directory", func(t *testing.T) { |
| 110 | w := httptest.NewRecorder() |
| 111 | c, _ := CreateTestContext(w) |
| 112 | c.Request = httptest.NewRequest(http.MethodGet, "/test", nil) |
| 113 | |
| 114 | c.File(".") |
| 115 | |
| 116 | // Directory serving can return either 200 (with listing) or 403 (forbidden) |
| 117 | assert.True(t, w.Code == http.StatusOK || w.Code == http.StatusForbidden) |
| 118 | }) |
| 119 | |
| 120 | // Test with HEAD request |
| 121 | t.Run("HEAD request", func(t *testing.T) { |
| 122 | testFile := "testdata/test_file.txt" |
| 123 | |
| 124 | w := httptest.NewRecorder() |
| 125 | c, _ := CreateTestContext(w) |
| 126 | c.Request = httptest.NewRequest(http.MethodHead, "/test", nil) |
| 127 | |
| 128 | c.File(testFile) |
| 129 | |
| 130 | assert.Equal(t, http.StatusOK, w.Code) |
| 131 | assert.Empty(t, w.Body.String()) // HEAD request should not return body |
| 132 | assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) |
| 133 | }) |
| 134 | |
| 135 | // Test with Range request |
| 136 | t.Run("Range request", func(t *testing.T) { |
| 137 | testFile := "testdata/test_file.txt" |