Skip to content

Commit

Permalink
Add NewReader unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
NamelessOne91 committed Oct 8, 2024
1 parent 38e36ef commit 0950285
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 6 deletions.
10 changes: 4 additions & 6 deletions storage/filestorage.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package storage
import (
"crypto"
"io"
"log"
"os"
"path"

Expand All @@ -22,25 +21,24 @@ func NewFileStorage(directory string) Storage {

// NewReader returns a Reader for a file in a location, returns ErrFileNotFound
// if the requested path was not found at all
func (s *FileStorage) NewReader(filename string, location Location) (reader io.ReadCloser, err error) {
func (s *FileStorage) NewReader(filename string, location Location) (io.ReadCloser, error) {
var prefix string
if location == Permanent {
prefix = ""
} else {
prefix = "-in-progress"
}

fullPath := path.Join(s.directory+prefix, filename)
stat, err := os.Stat(fullPath)
if os.IsNotExist(err) || stat == nil {
err = ErrFileNotFound
return
return nil, ErrFileNotFound
}

f, err := os.Open(fullPath)
if err != nil {
log.Fatal(err)
return nil, err
}

return f, err
}

Expand Down
41 changes: 41 additions & 0 deletions storage/filestorage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package storage

import (
"io"
"testing"

"github.com/stretchr/testify/assert"
)

const (
testdataDir = "testdata/testrepo"
inProgressDir = "testdata/testrepo-in-progress"
testFile = "test.txt"
)

func TestNewReader(t *testing.T) {
tests := []struct {
name string
directory string
filename string
location Location
wantErr bool
}{
{"Permanent location", testdataDir, testFile, Permanent, false},
{"Temporary location", testdataDir, testFile, Temporary, false},
{"Not existing file", testdataDir, "does-not-exist.txt", Permanent, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
storage := NewFileStorage(tt.directory)

r, err := storage.NewReader(tt.filename, tt.location)
assert.EqualValues(t, tt.wantErr, (err != nil))
if r != nil {
content, err := io.ReadAll(r)
assert.Nil(t, err)
assert.EqualValues(t, "Hello World", string(content))
}
})
}
}
1 change: 1 addition & 0 deletions storage/testdata/testrepo-in-progress/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello World
1 change: 1 addition & 0 deletions storage/testdata/testrepo/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello World

0 comments on commit 0950285

Please sign in to comment.