os_unix_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  5. package os_test
  6. import (
  7. . "os"
  8. "runtime"
  9. "syscall"
  10. "testing"
  11. )
  12. func checkUidGid(t *testing.T, path string, uid, gid int) {
  13. dir, err := Stat(path)
  14. if err != nil {
  15. t.Fatalf("Stat %q (looking for uid/gid %d/%d): %s", path, uid, gid, err)
  16. }
  17. sys := dir.Sys().(*syscall.Stat_t)
  18. if int(sys.Uid) != uid {
  19. t.Errorf("Stat %q: uid %d want %d", path, sys.Uid, uid)
  20. }
  21. if int(sys.Gid) != gid {
  22. t.Errorf("Stat %q: gid %d want %d", path, sys.Gid, gid)
  23. }
  24. }
  25. func TestChown(t *testing.T) {
  26. // Chown is not supported under windows os Plan 9.
  27. // Plan9 provides a native ChownPlan9 version instead.
  28. if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
  29. return
  30. }
  31. // Use TempDir() to make sure we're on a local file system,
  32. // so that the group ids returned by Getgroups will be allowed
  33. // on the file. On NFS, the Getgroups groups are
  34. // basically useless.
  35. f := newFile("TestChown", t)
  36. defer Remove(f.Name())
  37. defer f.Close()
  38. dir, err := f.Stat()
  39. if err != nil {
  40. t.Fatalf("stat %s: %s", f.Name(), err)
  41. }
  42. // Can't change uid unless root, but can try
  43. // changing the group id. First try our current group.
  44. gid := Getgid()
  45. t.Log("gid:", gid)
  46. if err = Chown(f.Name(), -1, gid); err != nil {
  47. t.Fatalf("chown %s -1 %d: %s", f.Name(), gid, err)
  48. }
  49. sys := dir.Sys().(*syscall.Stat_t)
  50. checkUidGid(t, f.Name(), int(sys.Uid), gid)
  51. // Then try all the auxiliary groups.
  52. groups, err := Getgroups()
  53. if err != nil {
  54. t.Fatalf("getgroups: %s", err)
  55. }
  56. t.Log("groups: ", groups)
  57. for _, g := range groups {
  58. if err = Chown(f.Name(), -1, g); err != nil {
  59. t.Fatalf("chown %s -1 %d: %s", f.Name(), g, err)
  60. }
  61. checkUidGid(t, f.Name(), int(sys.Uid), g)
  62. // change back to gid to test fd.Chown
  63. if err = f.Chown(-1, gid); err != nil {
  64. t.Fatalf("fchown %s -1 %d: %s", f.Name(), gid, err)
  65. }
  66. checkUidGid(t, f.Name(), int(sys.Uid), gid)
  67. }
  68. }