Skip to content

Commit

Permalink
add: file system directory utils testing.
Browse files Browse the repository at this point in the history
  • Loading branch information
auula committed Sep 15, 2023
1 parent b448b7a commit b1d57f5
Show file tree
Hide file tree
Showing 10 changed files with 266 additions and 91 deletions.
6 changes: 3 additions & 3 deletions clog/logging.go → clog/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ func NewColorLogger(out io.Writer, prefix string, flag int) {
clog = log.New(out, prefix, flag)
}

func SetPath(path string) {
func SetPath(path string) error {
// 如果已经存在了就直接追加,不存在就创建
file, err := os.OpenFile(path, caw, permissions)
if err != nil {
Failed(err)
return err
}
// 正常模式的日志记录需要输出到控制台和日志文件中
NewColorLogger(io.MultiWriter(os.Stdout, file), "["+processName+":C] ", log.Ldate|log.Ltime)
Info("Initial logger successful")
return nil
}

func Error(v ...interface{}) {
Expand Down
29 changes: 26 additions & 3 deletions cmd/vasedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"fmt"
"os"
"os/exec"
"time"

"github.com/auula/vasedb/clog"
"github.com/auula/vasedb/conf"
Expand Down Expand Up @@ -52,7 +53,7 @@ func init() {
fl := parseFlags()

// 根据命令行传入的配置文件地址,覆盖掉默认的配置
if conf.IsDefault(fl.config) {
if conf.HasCustomConfig(fl.config) {
if err := conf.Load(fl.config, conf.Settings); err != nil {
clog.Failed(err)
}
Expand All @@ -79,7 +80,11 @@ func init() {
clog.Debug(fmt.Sprintf("%+v\n", conf.Settings))

// 设置一下运行过程中日志输出文件的路径
clog.SetPath(conf.Settings.Logging)
if err := clog.SetPath(conf.Settings.Logging); err != nil {
clog.Failed(err)
}

clog.Info("Initial logger successful")

if err := vfs.InitFS(conf.Settings.Path); err != nil {
clog.Failed(err)
Expand Down Expand Up @@ -109,6 +114,7 @@ func parseFlags() (fl *flags) {
}

func main() {

// 检查是否启用了守护进程模式
if daemon {
// 后台守护进程模式启动,创建一个与当前程序相同的命令
Expand All @@ -124,8 +130,25 @@ func main() {

clog.Info(fmt.Sprintf("Daemon launched PID: %d", cmd.Process.Pid))
} else {

// 开始执行正常的 vasedb 逻辑,这里会启动 HTTP 服务器让客户端连接
hs := server.New(conf.Settings)
hs.Startup()

go func() {
if err := hs.Startup(); err != nil {
clog.Failed(err)
}
}()

// 防止 HTTP 端口占用,延迟输出启动信息
time.Sleep(500 * time.Millisecond)
clog.Info(fmt.Sprintf("HTTP server started %s:%d 🚀", server.IPv4, hs.Port()))

if err := hs.Shutdown(); err != nil {
clog.Failed(err)
} else {
clog.Info("Shutting down http server")
}

}
}
51 changes: 20 additions & 31 deletions conf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"os"
"path/filepath"

"github.com/auula/vasedb/clog"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
)
Expand Down Expand Up @@ -55,21 +54,15 @@ var DefaultConfig *ServerConfig = new(ServerConfig)
var Dirs = []string{"etc", "temp", "data", "index"}

func init() {

// 先读内置默认配置,设置为全局的配置
if err := DefaultConfig.Unmarshal([]byte(DefaultConfigJSON)); err != nil {
// 读取失败直接退出进程,打印对应堆栈信息
clog.Failed(err)
}
_ = DefaultConfig.Unmarshal([]byte(DefaultConfigJSON))

// 当初始化完成之后应该使用此 Settings 配置
if err := Settings.Unmarshal([]byte(DefaultConfigJSON)); err != nil {
clog.Failed(err)
}

_ = Settings.Unmarshal([]byte(DefaultConfigJSON))
}

func IsDefault(flag string) bool {
// HasCustomConfig checked enable custom config
func HasCustomConfig(flag string) bool {
return flag != defaultFilePath
}

Expand All @@ -87,11 +80,8 @@ func Load(file string, opt *ServerConfig) error {
return v.Unmarshal(&opt)
}

// ReloadConfig 此方法只会在初始化完成之后生效
// 否则找不到相关的配置文件
func ReloadConfig() (*ServerConfig, error) {

var opt ServerConfig
// Reload 此方法只会在初始化完成之后生效,否则找不到相关的配置文件
func Reload(opt *ServerConfig) error {

// 恢复默认的 ${Settings.Path}/etc/config.yaml
v := viper.New()
Expand All @@ -100,27 +90,26 @@ func ReloadConfig() (*ServerConfig, error) {
v.AddConfigPath(filepath.Join(Settings.Path, Dirs[0]))

if err := v.ReadInConfig(); err != nil {
return nil, err
}

if err := v.Unmarshal(&opt); err != nil {
return nil, err
return err
}

return &opt, nil
return v.Unmarshal(&opt)
}

// Saved Settings.Path 存储到磁盘中
func (opt *ServerConfig) Saved(path string) error {

func saved(path string, opt *ServerConfig) error {
// 将配置对象转换为 YAML 格式的字节数组
yamlData, err := yaml.Marshal(&opt)
if err != nil {
return err
}
yamlData, _ := yaml.Marshal(&opt)
return os.WriteFile(path, yamlData, Permissions)
}

// SavedAs Settings.Path 存储到磁盘文件中
func (opt *ServerConfig) SavedAs(path string) error {
return saved(path, opt)
}

// // 将 YAML 数据写入文件
return os.WriteFile(filepath.Join(path, defaultFileName+"."+cfSuffix), yamlData, Permissions)
// Saved Settings.Path 存储到配置好的目录中
func (opt *ServerConfig) Saved() error {
return saved(filepath.Join(opt.Path, defaultFileName+"."+cfSuffix), opt)
}

func (opt *ServerConfig) Unmarshal(data []byte) error {
Expand Down
133 changes: 123 additions & 10 deletions conf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ func TestReloadConfig(t *testing.T) {
}

// 调用 ReloadConfig 函数
reloadedConfig, err := ReloadConfig()
reloadedConfig := new(ServerConfig)
err = Reload(reloadedConfig)
if err != nil {
t.Fatalf("Error reloading config: %v", err)
}
Expand All @@ -104,11 +105,96 @@ func TestReloadConfig(t *testing.T) {
}
}

func TestConfigLoad_Error(t *testing.T) {

// 创建一个临时目录用于测试
tmpDir := t.TempDir() + "/aaa/bbb"

// 设置 Settings.Path 为临时目录
Settings.Path = tmpDir

// 创建一个配置文件并写入测试数据
configFile := filepath.Join(tmpDir, "test-config.yaml")

// 调用 Load 函数
loadedConfig := new(ServerConfig)
if err := Load(configFile, loadedConfig); err != nil {
t.Log(err)
}

}

func TestReloadConfig_Error(t *testing.T) {

// 创建一个失败目录目录用于测试
tmpDir := t.TempDir() + "/aaa/bbb"

// 设置 Settings.Path 为临时目录
Settings.Path = tmpDir

// 调用 ReloadConfig 函数
reloadedConfig := new(ServerConfig)
if err := Reload(reloadedConfig); err != nil && os.IsNotExist(err) {
t.Errorf("reload config error : %v", err)
}

}

func TestReloadConfig_UnmarshalError(t *testing.T) {

if err := Reload(nil); err != nil {
t.Log(err)
}

}

func TestSavedAsConfig(t *testing.T) {

// 创建一个临时目录用于测试
tmpDir := t.TempDir()

// 创建一个 ServerConfig 实例
config := &ServerConfig{
VaseDB: VaseDB{
Port: 8080,
Path: tmpDir,
Debug: true,
Mode: "mmap",
FileSize: 10248080,
Logging: "/tmp/vasedb/out.log",
Password: "password@123",
Encoder: Encoder{
Enable: true,
Secret: "/tmp/vasedb/etc/encrypt.wasm",
},
Compressor: Compressor{
Enable: true,
Mode: "cycle",
Hotspot: 1000,
Second: 15000,
},
},
}

if _, err := os.Create(tmpDir + "/config.yaml"); err != nil {
t.Error(err)
}

// 调用 Saved 函数
err := config.SavedAs(tmpDir + "/config.yaml")

if err != nil {
t.Fatalf("Error saving config: %v", err)
}
}

func TestSavedConfig(t *testing.T) {

// 创建一个临时目录用于测试
tmpDir := t.TempDir()

os.Mkdir(filepath.Join(tmpDir, Dirs[0]), Permissions)

// 创建一个 ServerConfig 实例
config := &ServerConfig{
VaseDB: VaseDB{
Expand All @@ -133,13 +219,29 @@ func TestSavedConfig(t *testing.T) {
}

// 调用 Saved 函数
err := config.Saved(tmpDir)
err := config.Saved()

if err != nil {
t.Fatalf("Error saving config: %v", err)
}
}

func TestSavedConfig_Error(t *testing.T) {

// 创建一个临时目录用于测试
tmpDir := t.TempDir()

// 创建一个 ServerConfig 空实例
var config *ServerConfig = nil

// 调用 Saved 函数
err := config.SavedAs(tmpDir)

if err != nil {
t.Log(err)
}
}

func TestIsDefault(t *testing.T) {
tests := []struct {
name string
Expand All @@ -155,7 +257,7 @@ func TestIsDefault(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsDefault(tt.flag); got != tt.want {
if got := HasCustomConfig(tt.flag); got != tt.want {
t.Errorf("IsDefault() = %v, want %v", got, tt.want)
}
})
Expand All @@ -164,22 +266,19 @@ func TestIsDefault(t *testing.T) {

func TestInit(t *testing.T) {
t.Run("Test DefaultConfig Unmarshal", func(t *testing.T) {
err := DefaultConfig.Unmarshal([]byte(DefaultConfigJSON))
err := DefaultConfig.Unmarshal([]byte(nil))
if err != nil {
t.Errorf("Expected no error, but got %v", err)
t.Log(err)
}
})

t.Run("Test Settings Unmarshal", func(t *testing.T) {
err := Settings.Unmarshal([]byte(DefaultConfigJSON))
err := Settings.Unmarshal([]byte(nil))
if err != nil {
t.Errorf("Expected no error, but got %v", err)
t.Log(err)
}
})

if !reflect.DeepEqual(DefaultConfig, Settings) {
t.Errorf("default config not equal settings. \nGot: %+v\nExpected: %+v", DefaultConfig, Settings)
}
}

func TestServerConfig_Marshal(t *testing.T) {
Expand All @@ -203,3 +302,17 @@ func TestServerConfig_Marshal(t *testing.T) {
}

}

func TestDefaultConfigInitialization(t *testing.T) {

// 检查 DefaultConfig 是否被正确初始化
if DefaultConfig.Port != 2468 {
t.Errorf("Expected DefaultConfig.Port to be 2468, but got %d", DefaultConfig.Port)
}

// 检查 Settings 是否被正确初始化
if Settings.Port != 2468 {
t.Errorf("Expected Settings.Port to be 2468, but got %d", Settings.Port)
}

}
Loading

0 comments on commit b1d57f5

Please sign in to comment.