package util
import (
"io"
"io/ioutil"
"os"
"path"
"testing"
)
// readFile returns the contents of the file, or "" if it doesn't exist.
func readFile(file string) string {
content, err := ioutil.ReadFile(file)
if err != nil {
return ""
}
return string(content)
}
func TestAddLineTo(t *testing.T) {
tmp_dir := t.TempDir()
f := path.Join(tmp_dir, "file")
addLine := func(line string) {
err := AddLineTo(f, line)
if err != nil {
t.Errorf("Error adding line %s: %s", line, err)
}
}
// start with an empty file
if c := readFile(f); c != "" {
t.Errorf("Expected empty file, got %s", c)
}
// add one copy of the "foo bar" line
addLine("foo bar")
if c := readFile(f); c != "foo bar\n" {
t.Errorf("Expected 'foo bar\n', got %s", c)
}
// add another copy of the "foo bar" line (should be a no-op)
addLine("foo bar")
if c := readFile(f); c != "foo bar\n" {
t.Errorf("Expected 'foo bar\n', got %s", c)
}
// add another line: "baz"
addLine("baz")
if c := readFile(f); c != "foo bar\nbaz\n" {
t.Errorf("Expected 'foo bar\nbaz\n', got %s", c)
}
// append an unfinished line "junk", with no newline
x, _ := os.OpenFile(f, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
io.WriteString(x, "junk")
x.Close()
if c := readFile(f); c != "foo bar\nbaz\njunk" {
t.Errorf("Expected 'foo bar\nbaz\njunk', got %s", c)
}
// append another "junk" (should be a no-op)
addLine("junk")
if c := readFile(f); c != "foo bar\nbaz\njunk" {
t.Errorf("Expected 'foo bar\nbaz\njunk', got %s", c)
}
// append an entirely new line "qux" (should inject a newline)
addLine("qux")
if c := readFile(f); c != "foo bar\nbaz\njunk\nqux\n" {
t.Errorf("Expected 'foo bar\nbaz\njunk\nqux\n', got %s", c)
}
}