github.com/astaxie/beego@v1.12.3/config/yaml/yaml_test.go (about) 1 // Copyright 2014 beego Author. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package yaml 16 17 import ( 18 "fmt" 19 "os" 20 "testing" 21 22 "github.com/astaxie/beego/config" 23 ) 24 25 func TestYaml(t *testing.T) { 26 27 var ( 28 yamlcontext = ` 29 "appname": beeapi 30 "httpport": 8080 31 "mysqlport": 3600 32 "PI": 3.1415976 33 "runmode": dev 34 "autorender": false 35 "copyrequestbody": true 36 "PATH": GOPATH 37 "path1": ${GOPATH} 38 "path2": ${GOPATH||/home/go} 39 "empty": "" 40 ` 41 42 keyValue = map[string]interface{}{ 43 "appname": "beeapi", 44 "httpport": 8080, 45 "mysqlport": int64(3600), 46 "PI": 3.1415976, 47 "runmode": "dev", 48 "autorender": false, 49 "copyrequestbody": true, 50 "PATH": "GOPATH", 51 "path1": os.Getenv("GOPATH"), 52 "path2": os.Getenv("GOPATH"), 53 "error": "", 54 "emptystrings": []string{}, 55 } 56 ) 57 f, err := os.Create("testyaml.conf") 58 if err != nil { 59 t.Fatal(err) 60 } 61 _, err = f.WriteString(yamlcontext) 62 if err != nil { 63 f.Close() 64 t.Fatal(err) 65 } 66 f.Close() 67 defer os.Remove("testyaml.conf") 68 yamlconf, err := config.NewConfig("yaml", "testyaml.conf") 69 if err != nil { 70 t.Fatal(err) 71 } 72 73 if yamlconf.String("appname") != "beeapi" { 74 t.Fatal("appname not equal to beeapi") 75 } 76 77 for k, v := range keyValue { 78 79 var ( 80 value interface{} 81 err error 82 ) 83 84 switch v.(type) { 85 case int: 86 value, err = yamlconf.Int(k) 87 case int64: 88 value, err = yamlconf.Int64(k) 89 case float64: 90 value, err = yamlconf.Float(k) 91 case bool: 92 value, err = yamlconf.Bool(k) 93 case []string: 94 value = yamlconf.Strings(k) 95 case string: 96 value = yamlconf.String(k) 97 default: 98 value, err = yamlconf.DIY(k) 99 } 100 if err != nil { 101 t.Errorf("get key %q value fatal,%v err %s", k, v, err) 102 } else if fmt.Sprintf("%v", v) != fmt.Sprintf("%v", value) { 103 t.Errorf("get key %q value, want %v got %v .", k, v, value) 104 } 105 106 } 107 108 if err = yamlconf.Set("name", "astaxie"); err != nil { 109 t.Fatal(err) 110 } 111 if yamlconf.String("name") != "astaxie" { 112 t.Fatal("get name error") 113 } 114 115 }