58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
package api
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestDBFileBytes(t *testing.T) {
|
|
dir := t.TempDir()
|
|
dbPath := filepath.Join(dir, "app.db")
|
|
mustWrite := func(p string, n int) {
|
|
t.Helper()
|
|
if err := os.WriteFile(p, make([]byte, n), 0o600); err != nil {
|
|
t.Fatalf("write %s: %v", p, err)
|
|
}
|
|
}
|
|
mustWrite(dbPath, 100)
|
|
mustWrite(dbPath+"-wal", 30)
|
|
|
|
cases := []struct {
|
|
name string
|
|
driver string
|
|
path string
|
|
want int64
|
|
}{
|
|
{name: "sqlite 主文件加 wal", driver: "sqlite", path: dbPath, want: 130},
|
|
{name: "sqlite 文件不存在计 0", driver: "sqlite", path: filepath.Join(dir, "none.db"), want: 0},
|
|
{name: "外部数据库不可度量", driver: "postgres", path: "", want: -1},
|
|
{name: "路径为空不可度量", driver: "sqlite", path: "", want: -1},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
if got := dbFileBytes(tc.driver, tc.path); got != tc.want {
|
|
t.Fatalf("dbFileBytes(%q, %q) = %d, want %d", tc.driver, tc.path, got, tc.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestResourcesSnapshot(t *testing.T) {
|
|
SetAboutRuntime("sqlite", filepath.Join(t.TempDir(), "absent.db"))
|
|
got := resourcesSnapshot()
|
|
|
|
if got["numCpu"].(int) < 1 || got["goroutines"].(int) < 1 {
|
|
t.Fatalf("numCpu / goroutines 应为正数: %+v", got)
|
|
}
|
|
if got["memHeapBytes"].(uint64) == 0 || got["memSysBytes"].(uint64) == 0 {
|
|
t.Fatalf("内存指标应为正数: %+v", got)
|
|
}
|
|
if got["cpuAvgPercent"].(float64) < 0 {
|
|
t.Fatalf("cpuAvgPercent 不应为负: %+v", got)
|
|
}
|
|
if got["dbEngine"].(string) != "sqlite" || got["dbBytes"].(int64) != 0 {
|
|
t.Fatalf("存储指标不符: %+v", got)
|
|
}
|
|
}
|