| 290 | } |
| 291 | |
| 292 | func TestWriteFile(t *testing.T) { |
| 293 | t.Parallel() |
| 294 | |
| 295 | tmpdir := os.TempDir() |
| 296 | noPermsFilePath := filepath.Join(tmpdir, "no-perms-file") |
| 297 | noPermsDirPath := filepath.Join(tmpdir, "no-perms-dir") |
| 298 | logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug) |
| 299 | fs := newTestFs(afero.NewMemMapFs(), func(call, file string) error { |
| 300 | if file == noPermsFilePath || file == noPermsDirPath { |
| 301 | return os.ErrPermission |
| 302 | } |
| 303 | return nil |
| 304 | }) |
| 305 | api := agentfiles.NewAPI(logger, fs, nil) |
| 306 | |
| 307 | dirPath := filepath.Join(tmpdir, "directory") |
| 308 | err := fs.MkdirAll(dirPath, 0o755) |
| 309 | require.NoError(t, err) |
| 310 | |
| 311 | filePath := filepath.Join(tmpdir, "file") |
| 312 | err = afero.WriteFile(fs, filePath, []byte("content"), 0o644) |
| 313 | require.NoError(t, err) |
| 314 | |
| 315 | notDirErr := "not a directory" |
| 316 | if runtime.GOOS == "windows" { |
| 317 | notDirErr = "cannot find the path" |
| 318 | } |
| 319 | |
| 320 | tests := []struct { |
| 321 | name string |
| 322 | path string |
| 323 | bytes []byte |
| 324 | errCode int |
| 325 | error string |
| 326 | }{ |
| 327 | { |
| 328 | name: "NoPath", |
| 329 | path: "", |
| 330 | errCode: http.StatusBadRequest, |
| 331 | error: "\"path\" is required", |
| 332 | }, |
| 333 | { |
| 334 | name: "RelativePathDotSlash", |
| 335 | path: "./relative", |
| 336 | errCode: http.StatusBadRequest, |
| 337 | error: "file path must be absolute", |
| 338 | }, |
| 339 | { |
| 340 | name: "RelativePath", |
| 341 | path: "also-relative", |
| 342 | errCode: http.StatusBadRequest, |
| 343 | error: "file path must be absolute", |
| 344 | }, |
| 345 | { |
| 346 | name: "NonExistent", |
| 347 | path: filepath.Join(tmpdir, "/nested/does-not-exist"), |
| 348 | bytes: []byte("now it does exist"), |
| 349 | }, |