gitlab.com/postgres-ai/database-lab/v3@v3.0.3/pkg/config/config_test.go (about) 1 package config 2 3 import ( 4 "bytes" 5 "os" 6 "path" 7 "path/filepath" 8 "testing" 9 10 "github.com/rs/xid" 11 "github.com/stretchr/testify/require" 12 "github.com/stretchr/testify/suite" 13 14 "gitlab.com/postgres-ai/database-lab/v3/pkg/util" 15 ) 16 17 func TestLoadConfig(t *testing.T) { 18 suite.Run(t, &ConfigSuite{}) 19 } 20 21 func copyFile(src, dst string, process func([]byte) []byte) error { 22 data, err := os.ReadFile(src) 23 if err != nil { 24 return err 25 } 26 27 return os.WriteFile(dst, process(data), 0600) 28 } 29 30 type ConfigSuite struct { 31 suite.Suite 32 oldCwd string 33 mountDir string 34 } 35 36 func (s *ConfigSuite) SetupTest() { 37 t := s.T() 38 39 s.mountDir = t.TempDir() 40 41 t.Log(s.mountDir) 42 43 cwd, err := os.Getwd() 44 require.NoError(t, err) 45 s.oldCwd = cwd 46 require.NoError(t, os.Chdir(s.mountDir)) 47 48 require.NoError(t, os.Mkdir("configs", 0700)) 49 require.NoError(t, os.Mkdir("data", 0700)) 50 51 exampleSrc := filepath.Join(cwd, "../../configs/config.example.logical_generic.yml") 52 testConfig := filepath.Join(s.mountDir, "configs/server.yml") 53 54 err = copyFile(exampleSrc, testConfig, func(data []byte) []byte { 55 return bytes.ReplaceAll(data, []byte("/var/lib/dblab"), []byte(s.mountDir)) 56 }) 57 require.NoError(t, err) 58 } 59 60 func (s *ConfigSuite) TearDownTest() { 61 s.Require().NoError(os.Chdir(s.oldCwd)) 62 } 63 64 func (s *ConfigSuite) TestGenerateNewID() { 65 instanceID, err := LoadInstanceID() 66 s.Require().NoError(err) 67 s.NotEmpty(instanceID) 68 69 instanceIDPath, err := util.GetMetaPath("instance_id") 70 s.Require().NoError(err) 71 data, err := os.ReadFile(instanceIDPath) 72 s.Require().NoError(err) 73 s.Equal(instanceID, string(data)) 74 } 75 76 func (s *ConfigSuite) TestLoadInstanceID() { 77 instanceID := xid.New().String() 78 79 instanceIDPath, err := util.GetMetaPath("instance_id") 80 s.Require().NoError(err) 81 err = os.MkdirAll(path.Dir(instanceIDPath), 0755) 82 s.Require().NoError(err) 83 err = os.WriteFile(instanceIDPath, []byte(instanceID), 0600) 84 s.Require().NoError(err) 85 86 instanceID, err = LoadInstanceID() 87 s.Require().NoError(err) 88 s.Equal(instanceID, instanceID) 89 }