diff --git a/src/ledger/file.go b/src/ledger/file.go index 5ee9027..50881cd 100644 --- a/src/ledger/file.go +++ b/src/ledger/file.go @@ -49,7 +49,7 @@ func (files Files) TempSetLastNLines(n int, lines []string) error { } defer r.Close() - if _, err := peekLastNLines(w, r, n); err != nil { + if _, err := peekLastNLines(w, bufio.NewReader(r), n); err != nil { return err } for i := range lines { diff --git a/src/ledger/file_test.go b/src/ledger/file_test.go index 9b8b356..1628a88 100644 --- a/src/ledger/file_test.go +++ b/src/ledger/file_test.go @@ -354,6 +354,47 @@ func TestFilesTempSetLastNLines(t *testing.T) { want string }{ "empty": {}, + "append to empty": { + input: []string{"hello", "world"}, + n: 100, + want: "hello\nworld\n", + }, + "replace last 10 of 1 lines with 2": { + given: "ohno", + input: []string{"hello", "world"}, + n: 10, + want: "hello\nworld\n", + }, + "replace last 1 of 1 lines with 2": { + given: "ohno", + input: []string{"hello", "world"}, + n: 1, + want: "hello\nworld\n", + }, + "replace last 0 of 1 lines with 2": { + given: "ohno", + input: []string{"hello", "world"}, + n: 0, + want: "ohno\nhello\nworld\n", + }, + "replace last 1 of 1 lines with 0": { + given: "ohno", + input: []string{}, + n: 1, + want: "", + }, + "replace last 1 of 2 lines with 1": { + given: "ohno\nhaha", + input: []string{"replaced"}, + n: 1, + want: "ohno\nreplaced\n", + }, + "replace last 1 of 2 lines with 2": { + given: "ohno\nhaha", + input: []string{"replac", "ed"}, + n: 1, + want: "ohno\nreplac\ned\n", + }, } for name, d := range cases { @@ -363,11 +404,18 @@ func TestFilesTempSetLastNLines(t *testing.T) { os.WriteFile(p, []byte(c.given), os.ModePerm) files := Files([]string{p}) if err := files.TempSetLastNLines(c.n, c.input); err != nil { + s := err.Error() + if _, err := os.Stat(s); err == nil { + got, _ := os.ReadFile(s) + if string(got) != c.want { + t.Errorf("want\n%s, got\n%s", c.want, got) + } + } t.Fatal(err) } got, _ := os.ReadFile(p) if string(got) != c.want { - t.Errorf("want\n\t%s, got\n\t%s", c.want, got) + t.Errorf("want\n%s, got\n%s", c.want, got) } }) }