53 lines
1.3 KiB
Go
53 lines
1.3 KiB
Go
package infra
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestFileServe(t *testing.T) {
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("hola mundo"), 0o644); err != nil {
|
|
t.Fatalf("setup: %v", err)
|
|
}
|
|
|
|
handler := FileServe(dir, "/files/", 60)
|
|
|
|
t.Run("sirve archivo existente con headers de cache", func(t *testing.T) {
|
|
req := httptest.NewRequest("GET", "/files/hello.txt", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("got %d, want 200", rec.Code)
|
|
}
|
|
if rec.Body.String() != "hola mundo" {
|
|
t.Errorf("got body %q", rec.Body.String())
|
|
}
|
|
if cc := rec.Header().Get("Cache-Control"); cc != "public, max-age=60" {
|
|
t.Errorf("got Cache-Control %q", cc)
|
|
}
|
|
})
|
|
|
|
t.Run("responde 404 para archivo inexistente", func(t *testing.T) {
|
|
req := httptest.NewRequest("GET", "/files/missing.txt", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusNotFound {
|
|
t.Errorf("got %d, want 404", rec.Code)
|
|
}
|
|
})
|
|
|
|
t.Run("rechaza path con .. con 400", func(t *testing.T) {
|
|
req := httptest.NewRequest("GET", "/files/../etc/passwd", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusBadRequest {
|
|
t.Errorf("got %d, want 400", rec.Code)
|
|
}
|
|
})
|
|
}
|