99package os_test
1010
1111import (
12+ "errors"
13+ "io/fs"
1214 . "os"
1315 "runtime"
1416 "testing"
1517)
1618
1719func TestChmod (t * testing.T ) {
20+ // Chmod
1821 f := newFile ("TestChmod" , t )
1922 defer Remove (f .Name ())
2023 defer f .Close ()
@@ -28,4 +31,42 @@ func TestChmod(t *testing.T) {
2831 t .Fatalf ("chmod %s %#o: %s" , f .Name (), fm , err )
2932 }
3033 checkMode (t , f .Name (), fm )
34+
35+ }
36+
37+ // Since testing syscalls requires a static, predictable environment that has to be controlled
38+ // by the CI, we don't test for success but for failures and verify that the error messages are as expected.
39+ // EACCES is returned when the user does not have the required permissions to change the ownership of the file
40+ // ENOENT is returned when the file does not exist
41+ // ENOTDIR is returned when the file is not a directory
42+ func TestChownErr (t * testing.T ) {
43+ if runtime .GOOS == "windows" || runtime .GOOS == "plan9" {
44+ t .Log ("skipping on " + runtime .GOOS )
45+ return
46+ }
47+
48+ var (
49+ TEST_UID_ROOT = 0
50+ TEST_GID_ROOT = 0
51+ )
52+
53+ f := newFile ("TestChown" , t )
54+ defer Remove (f .Name ())
55+ defer f .Close ()
56+
57+ // EACCES
58+ if err := Chown (f .Name (), TEST_UID_ROOT , TEST_GID_ROOT ); err != nil {
59+ errCmp := fs.PathError {Op : "chown" , Path : f .Name (), Err : errors .New ("operation not permitted" )}
60+ if errors .Is (err , & errCmp ) {
61+ t .Fatalf ("chown(%s, uid=%v, gid=%v): got '%v', want 'operation not permitted'" , f .Name (), TEST_UID_ROOT , TEST_GID_ROOT , err )
62+ }
63+ }
64+
65+ // ENOENT
66+ if err := Chown ("invalid" , Geteuid (), Getgid ()); err != nil {
67+ errCmp := fs.PathError {Op : "chown" , Path : "invalid" , Err : errors .New ("no such file or directory" )}
68+ if errors .Is (err , & errCmp ) {
69+ t .Fatalf ("chown(%s, uid=%v, gid=%v): got '%v', want 'no such file or directory'" , f .Name (), Geteuid (), Getegid (), err )
70+ }
71+ }
3172}
0 commit comments