1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright (C) 2021-2024 Simon Ruderich
15 ft "ruderich.org/simon/safcm/remote/sync/filetest"
16 "ruderich.org/simon/safcm/testutil"
19 func TestHandle(t *testing.T) {
20 cwd, err := os.Getwd()
24 defer os.Chdir(cwd) //nolint:errcheck
26 err = os.RemoveAll("testdata")
30 err = os.Mkdir("testdata", 0700)
35 // Set umask to test mode for new files
36 umask := syscall.Umask(027)
37 defer syscall.Umask(umask)
41 Mode: fs.ModeDir | 0700,
43 _, uid, _, gid := ft.CurrentUserAndGroup()
45 symlinkExists := "\"file\": too many levels of symbolic links"
46 if runtime.GOOS == "freebsd" {
47 // EMLINK instead of ELOOP
48 symlinkExists = "\"file\": too many links"
62 // TODO: Add tests for chown and run them only as root
74 fmt.Errorf("\"file\": file does not exist, use -create"),
88 Data: []byte("line\n"),
92 fmt.Sprintf(`"file": created file (%d/%d -rw-r-----)`, uid, gid),
93 `"file": added line "line"`,
98 "missing: create (empty line)",
107 fmt.Errorf("empty line"),
110 "missing: create (newline)",
119 fmt.Errorf("line must not contain newlines: \"line\\n\""),
128 ft.CreateFile("file", "line\n", 0641)
135 Data: []byte("line\n"),
148 ft.CreateFile("file", "existing\n", 0641)
155 Data: []byte("existing\nline\n"),
159 `"file": added line "line"`,
164 "exists: append (no newline in file)",
169 ft.CreateFile("file", "existing", 0641)
176 Data: []byte("existing\nline\n"),
180 `"file": added missing trailing newline`,
181 `"file": added line "line"`,
186 "exists: append (only trailing newline I)",
191 ft.CreateFile("file", "first\nline", 0641)
198 Data: []byte("first\nline\n"),
202 `"file": added missing trailing newline`,
207 "exists: append (only trailing newline II)",
212 ft.CreateFile("file", "first\nline", 0641)
219 Data: []byte("first\nline\n"),
223 `"file": added missing trailing newline`,
228 "exists: append (partial line)",
233 ft.CreateFile("file", "# line with spaces\n", 0641)
240 Data: []byte("# line with spaces\nline with spaces\n"),
244 `"file": added line "line with spaces"`,
255 ft.CreateSymlink("file", "target")
261 Mode: fs.ModeSymlink | 0777,
262 Data: []byte("target"),
266 fmt.Errorf(symlinkExists),
274 ft.CreateFifo("file", 0640)
280 Mode: fs.ModeNamedPipe | 0640,
284 fmt.Errorf("\"file\": not a regular file but p---------"),
288 for _, tc := range tests {
289 t.Run(tc.name, func(t *testing.T) {
290 // Create separate test directory for each test case
291 path := filepath.Join(cwd, "testdata", tc.name)
292 err = os.Mkdir(path, 0700)
301 if tc.prepare != nil {
305 changes, err := handle(tc.path, tc.line, tc.create)
306 testutil.AssertEqual(t, "changes",
307 changes, tc.expChanges)
308 testutil.AssertErrorEqual(t, "err", err, tc.expErr)
310 files, err := ft.WalkDir(path)
314 testutil.AssertEqual(t, "files", files, tc.expFiles)
319 err = os.RemoveAll(filepath.Join(cwd, "testdata"))