@@ -16,13 +16,19 @@ package log
1616
1717import (
1818 "os"
19+ "path/filepath"
1920 "testing"
2021
2122 "github.com/stretchr/testify/require"
2223)
2324
2425func TestInitLogNoPermission (t * testing.T ) {
26+ if os .Geteuid () == 0 {
27+ t .Skip ("Skip test when running as root user" )
28+ }
29+
2530 tmpDir := t .TempDir ()
31+
2632 conf := & Config {
2733 Level : "debug" ,
2834 File : tmpDir + "/test.log" ,
@@ -33,9 +39,44 @@ func TestInitLogNoPermission(t *testing.T) {
3339 require .NoError (t , err )
3440 require .NotNil (t , logger )
3541
36- err = os .Chmod (tmpDir , 0 )
37- require .NoError (t , err )
42+ // Directory permission denied
43+ require .NoError (t , os .Chmod (tmpDir , 0 ))
44+ _ , _ , err = InitAppLogger (conf )
45+ require .Contains (t , err .Error (), "permission denied" )
46+ require .NoError (t , os .Chmod (tmpDir , 0755 ))
3847
48+ // Directory exists but doesn't allow file creation
49+ readOnlyDirPath := filepath .Join (tmpDir , "readonly-dir" )
50+ require .NoError (t , os .Mkdir (readOnlyDirPath , 0755 ))
51+ require .NoError (t , os .Chmod (readOnlyDirPath , 0555 )) // Read-only directory
52+ conf .File = readOnlyDirPath + "/test.log"
3953 _ , _ , err = InitAppLogger (conf )
4054 require .ErrorContains (t , err , "permission denied" )
55+ require .NoError (t , os .Chmod (readOnlyDirPath , 0755 ))
56+
57+ // Using a directory as log file
58+ dirLogPath := filepath .Join (tmpDir , "dir-as-log" )
59+ require .NoError (t , os .Mkdir (dirLogPath , 0755 ))
60+ conf .File = dirLogPath
61+ _ , _ , err = InitAppLogger (conf )
62+ require .ErrorContains (t , err , "can't use directory as log file name" )
63+
64+ // File exists but is not writable
65+ filePath := filepath .Join (tmpDir , "readonly.log" )
66+ file , err := os .Create (filePath )
67+ require .NoError (t , err )
68+ file .Close ()
69+ require .NoError (t , os .Chmod (filePath , 0444 ))
70+ conf .File = filePath
71+ _ , _ , err = InitAppLogger (conf )
72+ require .ErrorContains (t , err , "permission denied" )
73+ require .NoError (t , os .Chmod (filePath , 0644 ))
74+
75+ // Ensure parent directory is created successfully
76+ nestedPath := filepath .Join (tmpDir , "nested/path/to" )
77+ conf .File = nestedPath + "/test.log"
78+ _ , _ , err = InitAppLogger (conf )
79+ require .NoError (t , err )
80+ _ , err = os .Stat (nestedPath )
81+ require .NoError (t , err )
4182}
0 commit comments