github.com/rigado/snapd@v2.42.5-go-mod+incompatible/osutil/cmp_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2014-2015 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 osutil 21 22 import ( 23 "io/ioutil" 24 "os" 25 "path/filepath" 26 "strings" 27 28 . "gopkg.in/check.v1" 29 ) 30 31 type CmpTestSuite struct{} 32 33 var _ = Suite(&CmpTestSuite{}) 34 35 func (ts *CmpTestSuite) TestCmp(c *C) { 36 tmpdir := c.MkDir() 37 38 foo := filepath.Join(tmpdir, "foo") 39 f, err := os.Create(foo) 40 c.Assert(err, IsNil) 41 defer f.Close() 42 43 // pick a smaller bufsize so that the test can complete quicker 44 defer func() { 45 bufsz = defaultBufsz 46 }() 47 bufsz = 128 48 49 // test FilesAreEqual for various sizes: 50 // - bufsz not exceeded 51 // - bufsz matches file size 52 // - bufsz exceeds file size 53 canary := "1234567890123456" 54 for _, n := range []int{1, bufsz / len(canary), (bufsz / len(canary)) + 1} { 55 for i := 0; i < n; i++ { 56 c.Assert(FilesAreEqual(foo, foo), Equals, true) 57 _, err := f.WriteString(canary) 58 c.Assert(err, IsNil) 59 f.Sync() 60 } 61 } 62 } 63 64 func (ts *CmpTestSuite) TestCmpEmptyNeqMissing(c *C) { 65 tmpdir := c.MkDir() 66 67 foo := filepath.Join(tmpdir, "foo") 68 bar := filepath.Join(tmpdir, "bar") 69 f, err := os.Create(foo) 70 c.Assert(err, IsNil) 71 defer f.Close() 72 c.Assert(FilesAreEqual(foo, bar), Equals, false) 73 c.Assert(FilesAreEqual(bar, foo), Equals, false) 74 } 75 76 func (ts *CmpTestSuite) TestCmpEmptyNeqNonEmpty(c *C) { 77 tmpdir := c.MkDir() 78 79 foo := filepath.Join(tmpdir, "foo") 80 bar := filepath.Join(tmpdir, "bar") 81 f, err := os.Create(foo) 82 c.Assert(err, IsNil) 83 defer f.Close() 84 c.Assert(ioutil.WriteFile(bar, []byte("x"), 0644), IsNil) 85 c.Assert(FilesAreEqual(foo, bar), Equals, false) 86 c.Assert(FilesAreEqual(bar, foo), Equals, false) 87 } 88 89 func (ts *CmpTestSuite) TestCmpStreams(c *C) { 90 for _, x := range []struct { 91 a string 92 b string 93 r bool 94 }{ 95 {"hello", "hello", true}, 96 {"hello", "world", false}, 97 {"hello", "hell", false}, 98 } { 99 c.Assert(StreamsEqual(strings.NewReader(x.a), strings.NewReader(x.b)), Equals, x.r) 100 } 101 }