material_manage_system/cmd/server/main_test.go

70 lines
1.7 KiB
Go

package main
import (
"io/fs"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/wmms/wmms/internal/web"
)
func TestFrontendRoutesServeBuiltAssetsAtRootPath(t *testing.T) {
gin.SetMode(gin.TestMode)
dist, err := web.DistFS()
if err != nil {
t.Fatal(err)
}
assetPath := ""
if err := fs.WalkDir(dist, ".", func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if !entry.IsDir() && strings.HasPrefix(path, "assets/") {
assetPath = path
return fs.SkipAll
}
return nil
}); err != nil {
t.Fatal(err)
}
if assetPath == "" {
t.Fatal("embedded frontend has no assets")
}
router := gin.New()
registerFrontendRoutes(router)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/"+assetPath, nil))
if response.Code != http.StatusOK {
t.Fatalf("asset status = %d, want %d", response.Code, http.StatusOK)
}
}
func TestFrontendRefreshFallsBackWithoutMaskingAPIOrAssets(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
registerFrontendRoutes(r)
for _, path := range []string{"/stock", "/login", "/master-data/settings", "/api/missing", "/ws", "/uploads/missing", "/assets/missing.js"} {
t.Run(path, func(t *testing.T) {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
want := 200
if path == "/api/missing" || path == "/ws" || path == "/uploads/missing" || path == "/assets/missing.js" {
want = 404
}
if w.Code != want {
t.Fatalf("status=%d want=%d", w.Code, want)
}
})
}
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/stock", nil))
if w.Code != 404 {
t.Fatalf("POST status=%d", w.Code)
}
}