1
1
mirror of https://github.com/walles/moar.git synced 2024-08-16 15:30:34 +03:00

Handle displaying empty files

And introduce a unit test!
This commit is contained in:
Johan Walles 2019-06-13 20:04:51 +02:00
parent f6b5755501
commit da30eaf956
5 changed files with 58 additions and 3 deletions

View File

@ -28,6 +28,7 @@ type Lines struct {
// NewReaderFromStream creates a new stream reader
func NewReaderFromStream(reader io.Reader) (*_Reader, error) {
// FIXME: Close the stream when done reading it?
scanner := bufio.NewScanner(reader)
var lines []string
for scanner.Scan() {
@ -49,7 +50,9 @@ func NewReaderFromFilename(filename string) (*_Reader, error) {
return nil, err
}
return NewReaderFromStream(stream)
reader, err := NewReaderFromStream(stream)
reader.name = filename
return reader, err
}
func (r *_Reader) LineCount() int {
@ -61,6 +64,15 @@ func (r *_Reader) GetLines(firstLineOneBased int, wantedLineCount int) *Lines {
firstLineOneBased = 1
}
if len(r.lines) == 0 {
return &Lines{
lines: r.lines,
// FIXME: What line number should we set here?
firstLineOneBased: firstLineOneBased,
}
}
firstLineZeroBased := firstLineOneBased - 1
lastLineZeroBased := firstLineZeroBased + wantedLineCount - 1

43
m/reader_test.go Normal file
View File

@ -0,0 +1,43 @@
package m
import "testing"
func _TestGetLines(t *testing.T, reader *_Reader) {
t.Logf("Testing file: %s...", reader.name)
lines := reader.GetLines(1, 10)
if len(lines.lines) > 10 {
t.Errorf("Asked for 10 lines, got too many: %d", len(lines.lines))
}
if len(lines.lines) < 10 {
// No good plan for how to test short files more
return
}
// Test clipping at the end
lineCount := reader.LineCount()
lines = reader.GetLines(lineCount, 10)
if len(lines.lines) != 10 {
t.Errorf("Asked for 10 lines, got too few: %d", len(lines.lines))
return
}
if lines.firstLineOneBased != lineCount - 9 {
t.Errorf("Expected last line to be %d, was %d", lineCount - 9, lines.firstLineOneBased)
return
}
}
func TestGetLines(t *testing.T) {
// FIXME: List all files in ../sample-files
files := []string {"../sample-files/empty.txt"}
for _, file := range files {
reader, e := NewReaderFromFilename(file)
if e != nil {
t.Errorf("Error opening file <%s>: %s", file, e.Error())
continue
}
_TestGetLines(t, reader)
}
}

View File

@ -4,7 +4,7 @@ set -e -o pipefail
rm -f moar
go test 1>&2
go test github.com/walles/moar/m 1>&2
go build 1>&2

0
sample-files/empty.txt Normal file
View File

View File

@ -7,7 +7,7 @@ GOOS=linux GOARCH=386 go build
GOOS=darwin GOARCH=amd64 go build
# Unit tests first...
go test
go test github.com/walles/moar/m
# ... then Verify sending the output to a file
go build