Skip to content

Commit ba398db

Browse files
committed
Add NewReader unit tests
1 parent 1f60f82 commit ba398db

File tree

4 files changed

+47
-6
lines changed

4 files changed

+47
-6
lines changed

storage/filestorage.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package storage
33
import (
44
"crypto"
55
"io"
6-
"log"
76
"os"
87
"path"
98

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

2322
// NewReader returns a Reader for a file in a location, returns ErrFileNotFound
2423
// if the requested path was not found at all
25-
func (s *FileStorage) NewReader(filename string, location Location) (reader io.ReadCloser, err error) {
24+
func (s *FileStorage) NewReader(filename string, location Location) (io.ReadCloser, error) {
2625
var prefix string
2726
if location == Permanent {
2827
prefix = ""
2928
} else {
3029
prefix = "-in-progress"
3130
}
31+
3232
fullPath := path.Join(s.directory+prefix, filename)
3333
stat, err := os.Stat(fullPath)
3434
if os.IsNotExist(err) || stat == nil {
35-
err = ErrFileNotFound
36-
return
35+
return nil, ErrFileNotFound
3736
}
3837

3938
f, err := os.Open(fullPath)
4039
if err != nil {
41-
log.Fatal(err)
40+
return nil, err
4241
}
43-
4442
return f, err
4543
}
4644

storage/filestorage_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package storage
2+
3+
import (
4+
"io"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
const (
11+
testdataDir = "testdata/testrepo"
12+
inProgressDir = "testdata/testrepo-in-progress"
13+
testFile = "test.txt"
14+
)
15+
16+
func TestNewReader(t *testing.T) {
17+
tests := []struct {
18+
name string
19+
directory string
20+
filename string
21+
location Location
22+
wantErr bool
23+
}{
24+
{"Permanent location", testdataDir, testFile, Permanent, false},
25+
{"Temporary location", testdataDir, testFile, Temporary, false},
26+
{"Not existing file", testdataDir, "does-not-exist.txt", Permanent, true},
27+
}
28+
for _, tt := range tests {
29+
t.Run(tt.name, func(t *testing.T) {
30+
storage := NewFileStorage(tt.directory)
31+
32+
r, err := storage.NewReader(tt.filename, tt.location)
33+
assert.EqualValues(t, tt.wantErr, (err != nil))
34+
if r != nil {
35+
content, err := io.ReadAll(r)
36+
assert.Nil(t, err)
37+
assert.EqualValues(t, "Hello World", string(content))
38+
}
39+
})
40+
}
41+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hello World

storage/testdata/testrepo/test.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hello World

0 commit comments

Comments
 (0)