launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/utils/file_test.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package utils_test 5 6 import ( 7 "io/ioutil" 8 gc "launchpad.net/gocheck" 9 "os/user" 10 "path/filepath" 11 12 "launchpad.net/juju-core/juju/osenv" 13 "launchpad.net/juju-core/utils" 14 ) 15 16 type fileSuite struct { 17 oldHome string 18 } 19 20 var _ = gc.Suite(&fileSuite{}) 21 22 func (s *fileSuite) SetUpTest(c *gc.C) { 23 s.oldHome = osenv.Home() 24 err := osenv.SetHome("/home/test-user") 25 c.Assert(err, gc.IsNil) 26 } 27 28 func (s *fileSuite) TearDownTest(c *gc.C) { 29 err := osenv.SetHome(s.oldHome) 30 c.Assert(err, gc.IsNil) 31 } 32 33 func (*fileSuite) TestNormalizePath(c *gc.C) { 34 currentUser, err := user.Current() 35 c.Assert(err, gc.IsNil) 36 for _, test := range []struct { 37 path string 38 expected string 39 err string 40 }{{ 41 path: "/var/lib/juju", 42 expected: "/var/lib/juju", 43 }, { 44 path: "~/foo", 45 expected: "/home/test-user/foo", 46 }, { 47 path: "~/foo//../bar", 48 expected: "/home/test-user/bar", 49 }, { 50 path: "~", 51 expected: "/home/test-user", 52 }, { 53 path: "~" + currentUser.Username, 54 expected: currentUser.HomeDir, 55 }, { 56 path: "~" + currentUser.Username + "/foo", 57 expected: currentUser.HomeDir + "/foo", 58 }, { 59 path: "~" + currentUser.Username + "/foo//../bar", 60 expected: currentUser.HomeDir + "/bar", 61 }, { 62 path: "~foobar/path", 63 err: "user: unknown user foobar", 64 }} { 65 actual, err := utils.NormalizePath(test.path) 66 if test.err != "" { 67 c.Check(err, gc.ErrorMatches, test.err) 68 } else { 69 c.Check(err, gc.IsNil) 70 c.Check(actual, gc.Equals, test.expected) 71 } 72 } 73 } 74 75 func (*fileSuite) TestCopyFile(c *gc.C) { 76 dir := c.MkDir() 77 f, err := ioutil.TempFile(dir, "source") 78 c.Assert(err, gc.IsNil) 79 defer f.Close() 80 _, err = f.Write([]byte("hello world")) 81 c.Assert(err, gc.IsNil) 82 dest := filepath.Join(dir, "dest") 83 84 err = utils.CopyFile(dest, f.Name()) 85 c.Assert(err, gc.IsNil) 86 data, err := ioutil.ReadFile(dest) 87 c.Assert(err, gc.IsNil) 88 c.Assert(string(data), gc.Equals, "hello world") 89 }