@@ -72,6 +72,69 @@ func TestNewFileRefreshable(t *testing.T) {
7272 }, time .Second , 10 * time .Millisecond )
7373}
7474
75+ func TestNewFileRefreshableWithReaderFunc (t * testing.T ) {
76+ ctx := t .Context ()
77+
78+ dir := t .TempDir ()
79+ filename := filepath .Join (dir , "file.txt" )
80+ ticker := make (chan time.Time , 1 )
81+
82+ // Custom reader that uppercases the content
83+ uppercaseReader := func (path string ) ([]byte , error ) {
84+ content , err := os .ReadFile (path )
85+ if err != nil {
86+ return nil , err
87+ }
88+ // Convert to uppercase
89+ for i := range content {
90+ if content [i ] >= 'a' && content [i ] <= 'z' {
91+ content [i ] = content [i ] - 'a' + 'A'
92+ }
93+ }
94+ return content , nil
95+ }
96+
97+ refreshableFile := NewFileRefreshableWithReaderFunc (ctx , filename , ticker , uppercaseReader )
98+
99+ // Assert we start with IsNotExist error.
100+ curr , err := refreshableFile .Validation ()
101+ require .Error (t , err )
102+ require .True (t , os .IsNotExist (err ))
103+ require .Empty (t , curr )
104+ require .Empty (t , refreshableFile .Current ())
105+
106+ // Create file with lowercase content.
107+ require .NoError (t , os .WriteFile (filename , []byte ("test" ), 0644 ))
108+ ticker <- time .Now ()
109+ require .EventuallyWithT (t , func (t * assert.CollectT ) {
110+ curr , err := refreshableFile .Validation ()
111+ require .NoError (t , err )
112+ require .Equal (t , "TEST" , string (curr )) // Should be uppercased
113+ require .Equal (t , "TEST" , string (refreshableFile .Current ()))
114+ }, time .Second , 10 * time .Millisecond )
115+
116+ // Update file.
117+ require .NoError (t , os .WriteFile (filename , []byte ("hello world" ), 0644 ))
118+ ticker <- time .Now ()
119+ require .EventuallyWithT (t , func (t * assert.CollectT ) {
120+ curr , err := refreshableFile .Validation ()
121+ require .NoError (t , err )
122+ require .Equal (t , "HELLO WORLD" , string (curr )) // Should be uppercased
123+ require .Equal (t , "HELLO WORLD" , string (refreshableFile .Current ()))
124+ }, time .Second , 10 * time .Millisecond )
125+
126+ // Delete file - Current() should retain last valid value.
127+ require .NoError (t , os .Remove (filename ))
128+ ticker <- time .Now ()
129+ require .EventuallyWithT (t , func (t * assert.CollectT ) {
130+ curr , err := refreshableFile .Validation ()
131+ require .Error (t , err )
132+ require .True (t , os .IsNotExist (err ))
133+ require .Empty (t , curr )
134+ require .Equal (t , "HELLO WORLD" , string (refreshableFile .Current ()))
135+ }, time .Second , 10 * time .Millisecond )
136+ }
137+
75138func TestNewMultiFileRefreshable (t * testing.T ) {
76139 ctx := t .Context ()
77140 dir := t .TempDir ()
0 commit comments