Skip to content

Commit

Permalink
Add file creation handling and tests in SampleUpdater #67
Browse files Browse the repository at this point in the history
The code now checks if the specified file exists before appending a message. If it doesn't exist, it tries to create it, handling related errors accordingly. Corresponding tests to verify the new functionality have also been added, effectively ensuring its correct operation.

The failure to update spam for non-existing file was a side effect from duplication check #63

fix test typo from prev commit
  • Loading branch information
umputun committed Mar 31, 2024
1 parent 457e748 commit d3cd103
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app/bot/sample_updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ func (s *SampleUpdater) Reader() (io.ReadCloser, error) {

// Append a message to the file, preventing duplicates
func (s *SampleUpdater) Append(msg string) error {
// if file does not exist, create it
if _, err := os.Stat(s.fileName); os.IsNotExist(err) {
if _, err = os.Create(s.fileName); err != nil {
return fmt.Errorf("failed to create %s: %w", s.fileName, err)
}
}

// check if the message is already in the file
fh, err := os.Open(s.fileName)
if err != nil {
return fmt.Errorf("failed to open %s: %w", s.fileName, err)
Expand All @@ -44,6 +52,7 @@ func (s *SampleUpdater) Append(msg string) error {
}
}

// append the message to the file
fh, err = os.OpenFile(s.fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644) //nolint:gosec // keep it readable by all
if err != nil {
return fmt.Errorf("failed to open %s: %w", s.fileName, err)
Expand Down
19 changes: 19 additions & 0 deletions app/bot/sample_updater_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bot
import (
"io"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -72,6 +73,24 @@ func TestSampleUpdater(t *testing.T) {
assert.Equal(t, "Test message second line third line\n", string(content))
})

t.Run("no file", func(t *testing.T) {
dir := os.TempDir()
file := filepath.Join(dir, "non-existent-samples.txt")
defer os.Remove(file)

updater := NewSampleUpdater(file)
err := updater.Append("Test message")
assert.NoError(t, err)

reader, err := updater.Reader()
require.NoError(t, err)
defer reader.Close()

content, err := io.ReadAll(reader)
assert.NoError(t, err)
assert.Equal(t, "Test message\n", string(content))
})

t.Run("unhappy path", func(t *testing.T) {
updater := NewSampleUpdater("/tmp/non-existent/samples.txt")
err := updater.Append("Test message")
Expand Down

0 comments on commit d3cd103

Please sign in to comment.