Files
book-comic-library/backend/cmd/webui/handlers/internal_test.go

50 lines
1.4 KiB
Go

package handlers
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"syscall"
"testing"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/puddle/v2"
"booklib/internal/store"
)
func TestAbsBookPathTraversalRejected(t *testing.T) {
root := "/data/books/lib" // 纯路径逻辑,不碰文件系统,无需 DB
for _, bad := range []string{"../../etc/passwd", "a/../../../etc/x", "../sibling"} {
if _, e := absBookPath(root, store.Book{Path: bad}); e == nil {
t.Fatalf("must reject %q", bad)
}
}
if p, e := absBookPath(root, store.Book{Path: "series-a/vol.cbz"}); e != nil || p != filepath.Join(root, "series-a", "vol.cbz") {
t.Fatalf("must accept relative path: %q %v", p, e)
}
}
func TestDBErrStatus(t *testing.T) {
for _, tc := range []struct {
e error
want int
}{
{&pgconn.PgError{Code: "57P01"}, http.StatusServiceUnavailable}, // PG 停机:池内连接被服务端断
{&pgconn.PgError{Code: "08006"}, http.StatusServiceUnavailable},
{fmt.Errorf("dial: %w", syscall.ECONNREFUSED), http.StatusServiceUnavailable},
{puddle.ErrClosedPool, http.StatusServiceUnavailable},
{errors.New("boom"), http.StatusInternalServerError},
} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
dbErr(c, tc.e)
if w.Code != tc.want {
t.Errorf("dbErr(%v) = %d, want %d", tc.e, w.Code, tc.want)
}
}
}