github.com/meulengracht/snapd@v0.0.0-20210719210640-8bde69bcc84e/gadget/quantity/offset_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2019 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 quantity_test 21 22 import ( 23 "fmt" 24 25 . "gopkg.in/check.v1" 26 "gopkg.in/yaml.v2" 27 28 "github.com/snapcore/snapd/gadget/quantity" 29 ) 30 31 type offsetTestSuite struct{} 32 33 var _ = Suite(&offsetTestSuite{}) 34 35 func (s *offsetTestSuite) TestIECString(c *C) { 36 for _, tc := range []struct { 37 offset quantity.Offset 38 exp string 39 }{ 40 {512, "512 B"}, 41 {1000, "1000 B"}, 42 {1030, "1.01 KiB"}, 43 {quantity.OffsetKiB + 512, "1.50 KiB"}, 44 {123 * quantity.OffsetKiB, "123 KiB"}, 45 {512 * quantity.OffsetKiB, "512 KiB"}, 46 {578 * quantity.OffsetMiB, "578 MiB"}, 47 {1024*quantity.OffsetMiB + 123*quantity.OffsetMiB, "1.12 GiB"}, 48 {1024 * 1024 * quantity.OffsetMiB, "1 TiB"}, 49 {2 * 1024 * 1024 * 1024 * 1024 * quantity.OffsetMiB, "2048 PiB"}, 50 } { 51 c.Check(tc.offset.IECString(), Equals, tc.exp) 52 } 53 } 54 55 func (s *offsetTestSuite) TestUnmarshalYAMLSize(c *C) { 56 type foo struct { 57 Offset quantity.Offset `yaml:"offset"` 58 } 59 60 for i, tc := range []struct { 61 s string 62 sz quantity.Offset 63 err string 64 }{ 65 {"1234", 1234, ""}, 66 {"1234M", 1234 * quantity.OffsetMiB, ""}, 67 {"1234G", 1234 * 1024 * quantity.OffsetMiB, ""}, 68 {"0", 0, ""}, 69 {"a0M", 0, `cannot parse offset "a0M": no numerical prefix.*`}, 70 {"-123", 0, `cannot parse offset "-123": offset cannot be negative`}, 71 {"123a", 0, `cannot parse offset "123a": invalid suffix "a"`}, 72 } { 73 c.Logf("tc: %v", i) 74 75 var f foo 76 err := yaml.Unmarshal([]byte(fmt.Sprintf("offset: %s", tc.s)), &f) 77 if tc.err != "" { 78 c.Check(err, ErrorMatches, tc.err) 79 } else { 80 c.Check(err, IsNil) 81 c.Check(f.Offset, Equals, tc.sz) 82 } 83 } 84 } 85 86 func (s *offsetTestSuite) TestOffsetString(c *C) { 87 var pOffset *quantity.Offset 88 c.Check(pOffset.String(), Equals, "unspecified") 89 90 for _, tc := range []struct { 91 offset quantity.Offset 92 exp string 93 }{ 94 {512, "512"}, 95 {1030, "1030"}, 96 {quantity.OffsetKiB + 512, "1536"}, 97 {578 * quantity.OffsetMiB, "606076928"}, 98 } { 99 c.Check(tc.offset.String(), Equals, tc.exp) 100 } 101 }