github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/jsonutil/json_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 jsonutil_test 21 22 import ( 23 "encoding/json" 24 "strings" 25 "testing" 26 27 . "gopkg.in/check.v1" 28 29 "github.com/snapcore/snapd/jsonutil" 30 ) 31 32 func Test(t *testing.T) { TestingT(t) } 33 34 type utilSuite struct{} 35 36 var _ = Suite(&utilSuite{}) 37 38 func (s *utilSuite) TestDecodeError(c *C) { 39 input := "{]" 40 var output interface{} 41 err := jsonutil.DecodeWithNumber(strings.NewReader(input), &output) 42 c.Assert(err, NotNil) 43 c.Assert(err, ErrorMatches, `invalid character ']' looking for beginning of object key string`) 44 } 45 46 func (s *utilSuite) TestDecodeErrorOnExcessData(c *C) { 47 input := "1000000000[1,2]" 48 var output interface{} 49 err := jsonutil.DecodeWithNumber(strings.NewReader(input), &output) 50 c.Assert(err, NotNil) 51 c.Assert(err, ErrorMatches, `cannot parse json value`) 52 } 53 54 func (s *utilSuite) TestDecodeSuccess(c *C) { 55 input := `{"a":1000000000, "b": 1.2, "c": "foo", "d":null}` 56 var output interface{} 57 err := jsonutil.DecodeWithNumber(strings.NewReader(input), &output) 58 c.Assert(err, IsNil) 59 c.Assert(output, DeepEquals, map[string]interface{}{ 60 "a": json.Number("1000000000"), 61 "b": json.Number("1.2"), 62 "c": "foo", 63 "d": nil, 64 }) 65 } 66 67 func (utilSuite) TestStructFields(c *C) { 68 type aStruct struct { 69 Foo int `json:"hello"` 70 Bar int `json:"potato,stuff"` 71 } 72 c.Assert(jsonutil.StructFields((*aStruct)(nil)), DeepEquals, []string{"hello", "potato"}) 73 } 74 75 func (utilSuite) TestStructFieldsExcept(c *C) { 76 type aStruct struct { 77 Foo int `json:"hello"` 78 Bar int `json:"potato,stuff"` 79 } 80 c.Assert(jsonutil.StructFields((*aStruct)(nil), "potato"), DeepEquals, []string{"hello"}) 81 c.Assert(jsonutil.StructFields((*aStruct)(nil), "hello"), DeepEquals, []string{"potato"}) 82 } 83 84 func (utilSuite) TestStructFieldsSurvivesNoTag(c *C) { 85 type aStruct struct { 86 Foo int `json:"hello"` 87 Bar int 88 } 89 c.Assert(jsonutil.StructFields((*aStruct)(nil)), DeepEquals, []string{"hello"}) 90 }