clear_logs_job_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package job
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. )
  8. // writeAccessLogConfig points bin/config.json at the given access log path (use
  9. // "none" to disable), so GetAccessLogPath resolves it the way the job does.
  10. func writeAccessLogConfig(t *testing.T, accessPath string) {
  11. t.Helper()
  12. binDir := t.TempDir()
  13. t.Setenv("XUI_BIN_FOLDER", binDir)
  14. configData, err := json.Marshal(map[string]any{
  15. "log": map[string]any{"access": accessPath},
  16. })
  17. if err != nil {
  18. t.Fatalf("marshal xray config: %v", err)
  19. }
  20. if err := os.WriteFile(filepath.Join(binDir, "config.json"), configData, 0644); err != nil {
  21. t.Fatalf("write xray config: %v", err)
  22. }
  23. }
  24. func TestWipeAccessLog_TruncatesEnabledLog(t *testing.T) {
  25. accessLog := filepath.Join(t.TempDir(), "access.log")
  26. if err := os.WriteFile(accessLog, []byte("2026/06/23 12:00:00 from tcp:203.0.113.10:443 accepted\n"), 0644); err != nil {
  27. t.Fatalf("seed access log: %v", err)
  28. }
  29. writeAccessLogConfig(t, accessLog)
  30. wipeAccessLog()
  31. info, err := os.Stat(accessLog)
  32. if err != nil {
  33. t.Fatalf("access log should still exist: %v", err)
  34. }
  35. if info.Size() != 0 {
  36. t.Fatalf("access log should be truncated to 0, got %d bytes", info.Size())
  37. }
  38. }
  39. func TestWipeAccessLog_LeavesDisabledLogAlone(t *testing.T) {
  40. writeAccessLogConfig(t, "none")
  41. // Must not panic or create a file literally named "none".
  42. wipeAccessLog()
  43. if _, err := os.Stat("none"); err == nil {
  44. os.Remove("none")
  45. t.Fatal(`wipeAccessLog must not create a file named "none"`)
  46. }
  47. }