github.com/rigado/snapd@v2.42.5-go-mod+incompatible/strutil/map_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2017 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package strutil_test 21 22 import ( 23 "gopkg.in/yaml.v2" 24 25 . "gopkg.in/check.v1" 26 27 "github.com/snapcore/snapd/strutil" 28 ) 29 30 type orderedMapSuite struct{} 31 32 var _ = Suite(&orderedMapSuite{}) 33 34 func (s *orderedMapSuite) TestBasic(c *C) { 35 om := strutil.NewOrderedMap( 36 "K1", "bar", 37 "K2", "baz", 38 "K0", "foo", 39 ) 40 41 for i := 0; i < 100; i++ { 42 c.Assert(om.Keys(), DeepEquals, []string{"K1", "K2", "K0"}) 43 } 44 45 c.Check(om.Get("K1"), Equals, "bar") 46 c.Check(om.Get("K2"), Equals, "baz") 47 c.Check(om.Get("K0"), Equals, "foo") 48 49 om.Del("K2") 50 c.Assert(om.Keys(), DeepEquals, []string{"K1", "K0"}) 51 52 om.Set("K9", "foobar") 53 c.Assert(om.Keys(), DeepEquals, []string{"K1", "K0", "K9"}) 54 c.Check(om.Get("K9"), Equals, "foobar") 55 56 om2 := om.Copy() 57 c.Assert(om2.Keys(), DeepEquals, []string{"K1", "K0", "K9"}) 58 59 // replaces existing value, inserted at the end 60 om.Set("K1", "newbar") 61 c.Assert(om.Keys(), DeepEquals, []string{"K0", "K9", "K1"}) 62 c.Check(om.Get("K1"), Equals, "newbar") 63 } 64 65 func (s *orderedMapSuite) TestYamlTrivial(c *C) { 66 yamlStr := []byte(` 67 k: v 68 k2: v2 69 k0: v0 70 `) 71 var om strutil.OrderedMap 72 err := yaml.Unmarshal(yamlStr, &om) 73 c.Assert(err, IsNil) 74 c.Check(om.Keys(), DeepEquals, []string{"k", "k2", "k0"}) 75 } 76 77 func (s *orderedMapSuite) TestYamlDupe(c *C) { 78 yamlStr := []byte(` 79 k: v 80 k0: v0 81 k: v 82 `) 83 var om strutil.OrderedMap 84 err := yaml.Unmarshal(yamlStr, &om) 85 c.Assert(err, ErrorMatches, `found duplicate key "k"`) 86 } 87 88 func (s *orderedMapSuite) TestYamlErr(c *C) { 89 yamlStr := []byte(` 90 k: 91 nested: var 92 `) 93 var om strutil.OrderedMap 94 err := yaml.Unmarshal(yamlStr, &om) 95 c.Assert(err, ErrorMatches, "(?m)yaml: unmarshal error.*") 96 }