main_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. )
  7. func TestAppendAndReadLines(t *testing.T) {
  8. // TempDir 每次提供隔离目录,测试结束后由框架清理。
  9. path := filepath.Join(t.TempDir(), "notes.txt")
  10. if err := appendLine(path, "学习 Go"); err != nil {
  11. t.Fatal(err)
  12. }
  13. if err := appendLine(path, "学习文件"); err != nil {
  14. t.Fatal(err)
  15. }
  16. lines, err := readLines(path)
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. want := []string{"学习 Go", "学习文件"}
  21. if len(lines) != len(want) {
  22. t.Fatalf("行数=%d,期望=%d", len(lines), len(want))
  23. }
  24. for index := range want {
  25. if lines[index] != want[index] {
  26. t.Errorf("第 %d 行=%q,期望=%q", index+1, lines[index], want[index])
  27. }
  28. }
  29. }
  30. func TestReadEmptyFile(t *testing.T) {
  31. path := filepath.Join(t.TempDir(), "empty.txt")
  32. if err := os.WriteFile(path, nil, 0600); err != nil {
  33. t.Fatal(err)
  34. }
  35. lines, err := readLines(path)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. if len(lines) != 0 {
  40. t.Fatalf("空文件行数=%d,期望=0", len(lines))
  41. }
  42. }
  43. func TestReadMissingFile(t *testing.T) {
  44. path := filepath.Join(t.TempDir(), "missing.txt")
  45. _, err := readLines(path)
  46. if err == nil {
  47. t.Fatal("读取不存在的文件应返回错误")
  48. }
  49. }