11package stringutils_test
22
33import (
4+ "errors"
45 "net/http"
56 "net/url"
67 "testing"
@@ -136,6 +137,17 @@ func parseDateWithNanoseconds(dateString string) *time.Time {
136137}
137138
138139func TestGetFormattedFilename (t * testing.T ) {
140+ fixedTime := time .Date (2024 , time .December , 26 , 15 , 0 , 0 , 0 , time .UTC )
141+ originalNowFunc := stringutils .NowFunc
142+ stringutils .NowFunc = func () time.Time { return fixedTime }
143+ defer func () { stringutils .NowFunc = originalNowFunc }()
144+
145+ originalHomeDirFunc := stringutils .UserHomeDirFunc
146+ stringutils .UserHomeDirFunc = func () (string , error ) {
147+ return "/home/testuser" , nil
148+ }
149+ defer func () { stringutils .UserHomeDirFunc = originalHomeDirFunc }()
150+
139151 tests := []struct {
140152 name string
141153 format string
@@ -151,6 +163,15 @@ func TestGetFormattedFilename(t *testing.T) {
151163 },
152164 expected : "2024-12-26-localhost_9000-_example_path.raw" ,
153165 },
166+ {
167+ name : "Basic formatting with sanitized hostname and URL under home" ,
168+ format : "~/%Y-%m-%d-{hostname}-{url}.raw" ,
169+ req : & http.Request {
170+ Host : "localhost:9000" ,
171+ URL : & url.URL {Path : "/example/path" },
172+ },
173+ expected : "/home/testuser/2024-12-26-localhost_9000-_example_path.raw" ,
174+ },
154175 {
155176 name : "Special characters in hostname and URL" ,
156177 format : "%Y-%m-%d-%F-{hostname}-{url}.raw" ,
@@ -196,3 +217,26 @@ func TestGetFormattedFilename(t *testing.T) {
196217 })
197218 }
198219}
220+
221+ func TestGetFormattedFilename_HomeErr (t * testing.T ) {
222+ fixedTime := time .Date (2024 , time .December , 26 , 15 , 0 , 0 , 0 , time .UTC )
223+ originalNowFunc := stringutils .NowFunc
224+ stringutils .NowFunc = func () time.Time { return fixedTime }
225+ defer func () { stringutils .NowFunc = originalNowFunc }()
226+
227+ originalHomeDirFunc := stringutils .UserHomeDirFunc
228+ stringutils .UserHomeDirFunc = func () (string , error ) {
229+ return "" , errors .New ("error" )
230+ }
231+ defer func () { stringutils .UserHomeDirFunc = originalHomeDirFunc }()
232+
233+ format := "~/%Y-%m-%d-{hostname}-{url}.raw"
234+ req := & http.Request {
235+ Host : "localhost:9000" ,
236+ URL : & url.URL {Path : "/example/path" },
237+ }
238+ expected := "/2024-12-26-localhost_9000-_example_path.raw"
239+
240+ result := stringutils .GetFormattedFilename (format , req )
241+ assert .Equal (t , expected , result )
242+ }
0 commit comments