github.com/sleungcy/cli@v7.1.0+incompatible/util/configv3/write_config_test.go (about)

     1  package configv3_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"path/filepath"
     7  	"sort"
     8  	"strings"
     9  
    10  	"code.cloudfoundry.org/cli/util/configv3"
    11  	"gopkg.in/yaml.v2"
    12  
    13  	. "github.com/onsi/ginkgo"
    14  	. "github.com/onsi/gomega"
    15  )
    16  
    17  var _ = Describe("Config", func() {
    18  	var homeDir string
    19  
    20  	BeforeEach(func() {
    21  		homeDir = setup()
    22  	})
    23  
    24  	AfterEach(func() {
    25  		teardown(homeDir)
    26  	})
    27  
    28  	Describe("WriteConfig", func() {
    29  		var (
    30  			config *configv3.Config
    31  			file   []byte
    32  		)
    33  
    34  		BeforeEach(func() {
    35  			config = &configv3.Config{
    36  				ConfigFile: configv3.JSONConfig{
    37  					ConfigVersion: 3,
    38  					Target:        "foo.com",
    39  					ColorEnabled:  "true",
    40  				},
    41  				ENV: configv3.EnvOverride{
    42  					CFColor: "false",
    43  				},
    44  			}
    45  			err := config.WriteConfig()
    46  			Expect(err).ToNot(HaveOccurred())
    47  
    48  			file, err = ioutil.ReadFile(filepath.Join(homeDir, ".cf", "config.json"))
    49  			Expect(err).ToNot(HaveOccurred())
    50  		})
    51  
    52  		It("writes ConfigFile to homeDir/.cf/config.json", func() {
    53  			var writtenCFConfig configv3.JSONConfig
    54  			err := json.Unmarshal(file, &writtenCFConfig)
    55  			Expect(err).ToNot(HaveOccurred())
    56  
    57  			Expect(writtenCFConfig.ConfigVersion).To(Equal(config.ConfigFile.ConfigVersion))
    58  			Expect(writtenCFConfig.Target).To(Equal(config.ConfigFile.Target))
    59  			Expect(writtenCFConfig.ColorEnabled).To(Equal(config.ConfigFile.ColorEnabled))
    60  		})
    61  
    62  		It("writes the top-level keys in alphabetical order", func() {
    63  			// we use yaml.MapSlice here to preserve the original order
    64  			// https://github.com/golang/go/issues/27179
    65  			var ms yaml.MapSlice
    66  			err := yaml.Unmarshal(file, &ms)
    67  			Expect(err).ToNot(HaveOccurred())
    68  
    69  			keys := make([]string, len(ms))
    70  			for i, item := range ms {
    71  				keys[i] = item.Key.(string)
    72  			}
    73  			caseInsensitive := func(i, j int) bool { return strings.ToLower(keys[i]) < strings.ToLower(keys[j]) }
    74  			Expect(sort.SliceIsSorted(keys, caseInsensitive)).To(BeTrue())
    75  		})
    76  	})
    77  })