github.com/stolowski/snapd@v0.0.0-20210407085831-115137ce5a22/osutil/sys_linux_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2018 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_test 21 22 import ( 23 "os" 24 "path/filepath" 25 "syscall" 26 27 . "gopkg.in/check.v1" 28 29 "github.com/snapcore/snapd/osutil" 30 ) 31 32 type sysSuite struct{} 33 34 var _ = Suite(&sysSuite{}) 35 36 func (s *sysSuite) TestSymlinkatAndReadlinkat(c *C) { 37 // Create and open a temporary directory. 38 d := c.MkDir() 39 fd, err := syscall.Open(d, syscall.O_DIRECTORY, 0) 40 c.Assert(err, IsNil) 41 defer syscall.Close(fd) 42 43 // Create a symlink relative to the directory file descriptor. 44 err = osutil.Symlinkat("target", fd, "linkpath") 45 c.Assert(err, IsNil) 46 47 // Ensure that the created file is a symlink. 48 fname := filepath.Join(d, "linkpath") 49 fi, err := os.Lstat(fname) 50 c.Assert(err, IsNil) 51 c.Assert(fi.Name(), Equals, "linkpath") 52 c.Assert(fi.Mode()&os.ModeSymlink, Equals, os.ModeSymlink) 53 54 // Ensure that the symlink target is correct. 55 target, err := os.Readlink(fname) 56 c.Assert(err, IsNil) 57 c.Assert(target, Equals, "target") 58 59 // Use readlinkat with a buffer that fits only part of the target path. 60 buf := make([]byte, 2) 61 n, err := osutil.Readlinkat(fd, "linkpath", buf) 62 c.Assert(err, IsNil) 63 c.Assert(n, Equals, 2) 64 c.Assert(buf, DeepEquals, []byte{'t', 'a'}) 65 66 // Use a buffer that fits all of the target path. 67 buf = make([]byte, 100) 68 n, err = osutil.Readlinkat(fd, "linkpath", buf) 69 c.Assert(err, IsNil) 70 c.Assert(n, Equals, len("target")) 71 c.Assert(buf[:n], DeepEquals, []byte{'t', 'a', 'r', 'g', 'e', 't'}) 72 }