gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/config/default_test.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 "testing" 9 "time" 10 11 "gitee.com/liuxuezhan/go-micro-v1.18.0/config/source/env" 12 "gitee.com/liuxuezhan/go-micro-v1.18.0/config/source/file" 13 ) 14 15 var ( 16 sep = string(os.PathSeparator) 17 ) 18 19 func createFileForIssue18(t *testing.T, content string) *os.File { 20 data := []byte(content) 21 path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano())) 22 fh, err := os.Create(path) 23 if err != nil { 24 t.Error(err) 25 } 26 _, err = fh.Write(data) 27 if err != nil { 28 t.Error(err) 29 } 30 31 return fh 32 } 33 34 func createFileForTest(t *testing.T) *os.File { 35 data := []byte(`{"foo": "bar"}`) 36 path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano())) 37 fh, err := os.Create(path) 38 if err != nil { 39 t.Error(err) 40 } 41 _, err = fh.Write(data) 42 if err != nil { 43 t.Error(err) 44 } 45 46 return fh 47 } 48 49 func TestConfigLoadWithGoodFile(t *testing.T) { 50 fh := createFileForTest(t) 51 path := fh.Name() 52 defer func() { 53 fh.Close() 54 os.Remove(path) 55 }() 56 57 // Create new config 58 conf := NewConfig() 59 // Load file source 60 if err := conf.Load(file.NewSource( 61 file.WithPath(path), 62 )); err != nil { 63 t.Fatalf("Expected no error but got %v", err) 64 } 65 } 66 67 func TestConfigLoadWithInvalidFile(t *testing.T) { 68 fh := createFileForTest(t) 69 path := fh.Name() 70 defer func() { 71 fh.Close() 72 os.Remove(path) 73 }() 74 75 // Create new config 76 conf := NewConfig() 77 // Load file source 78 err := conf.Load(file.NewSource( 79 file.WithPath(path), 80 file.WithPath("/i/do/not/exists.json"), 81 )) 82 83 if err == nil { 84 t.Fatal("Expected error but none !") 85 } 86 if !strings.Contains(fmt.Sprintf("%v", err), "/i/do/not/exists.json") { 87 t.Fatalf("Expected error to contain the unexisting file but got %v", err) 88 } 89 } 90 91 func TestConfigMerge(t *testing.T) { 92 fh := createFileForIssue18(t, `{ 93 "amqp": { 94 "host": "rabbit.platform", 95 "port": 80 96 }, 97 "handler": { 98 "exchange": "springCloudBus" 99 } 100 }`) 101 path := fh.Name() 102 defer func() { 103 fh.Close() 104 os.Remove(path) 105 }() 106 os.Setenv("AMQP_HOST", "rabbit.testing.com") 107 108 conf := NewConfig() 109 conf.Load( 110 file.NewSource( 111 file.WithPath(path), 112 ), 113 env.NewSource(), 114 ) 115 116 actualHost := conf.Get("amqp", "host").String("backup") 117 if actualHost != "rabbit.testing.com" { 118 t.Fatalf("Expected %v but got %v", 119 "rabbit.testing.com", 120 actualHost) 121 } 122 }