| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- package main
- import (
- "os"
- "path/filepath"
- "testing"
- )
- func TestAppendAndReadLines(t *testing.T) {
- // TempDir 每次提供隔离目录,测试结束后由框架清理。
- path := filepath.Join(t.TempDir(), "notes.txt")
- if err := appendLine(path, "学习 Go"); err != nil {
- t.Fatal(err)
- }
- if err := appendLine(path, "学习文件"); err != nil {
- t.Fatal(err)
- }
- lines, err := readLines(path)
- if err != nil {
- t.Fatal(err)
- }
- want := []string{"学习 Go", "学习文件"}
- if len(lines) != len(want) {
- t.Fatalf("行数=%d,期望=%d", len(lines), len(want))
- }
- for index := range want {
- if lines[index] != want[index] {
- t.Errorf("第 %d 行=%q,期望=%q", index+1, lines[index], want[index])
- }
- }
- }
- func TestReadEmptyFile(t *testing.T) {
- path := filepath.Join(t.TempDir(), "empty.txt")
- if err := os.WriteFile(path, nil, 0600); err != nil {
- t.Fatal(err)
- }
- lines, err := readLines(path)
- if err != nil {
- t.Fatal(err)
- }
- if len(lines) != 0 {
- t.Fatalf("空文件行数=%d,期望=0", len(lines))
- }
- }
- func TestReadMissingFile(t *testing.T) {
- path := filepath.Join(t.TempDir(), "missing.txt")
- _, err := readLines(path)
- if err == nil {
- t.Fatal("读取不存在的文件应返回错误")
- }
- }
|