filecreationtime_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package filesystem
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. "time"
  7. )
  8. // GetFileCreationTime is platform dependent: it must never report a bogus
  9. // timestamp, and must always report "unknown" as (0, false).
  10. func TestGetFileCreationTime(t *testing.T) {
  11. tmpDir := t.TempDir()
  12. filePath := filepath.Join(tmpDir, "sample.txt")
  13. if err := os.WriteFile(filePath, []byte("hello arozos"), 0644); err != nil {
  14. t.Fatalf("unable to write test file: %v", err)
  15. }
  16. fileStat, err := os.Stat(filePath)
  17. if err != nil {
  18. t.Fatalf("unable to stat test file: %v", err)
  19. }
  20. dirStat, err := os.Stat(tmpDir)
  21. if err != nil {
  22. t.Fatalf("unable to stat test folder: %v", err)
  23. }
  24. tests := []struct {
  25. name string
  26. fileInfo os.FileInfo
  27. expectNil bool
  28. }{
  29. {name: "nil file info", fileInfo: nil, expectNil: true},
  30. {name: "regular file", fileInfo: fileStat, expectNil: false},
  31. {name: "directory", fileInfo: dirStat, expectNil: false},
  32. }
  33. //Anything created during this test must sit inside this window
  34. lowerBound := time.Now().Add(-24 * time.Hour).Unix()
  35. upperBound := time.Now().Add(24 * time.Hour).Unix()
  36. for _, test := range tests {
  37. t.Run(test.name, func(t *testing.T) {
  38. creationTime, ok := GetFileCreationTime(test.fileInfo)
  39. if test.expectNil && ok {
  40. t.Errorf("expected no creation time for %s, got %d", test.name, creationTime)
  41. }
  42. if !ok {
  43. if creationTime != 0 {
  44. t.Errorf("unsupported creation time should be reported as 0, got %d", creationTime)
  45. }
  46. return
  47. }
  48. if creationTime < lowerBound || creationTime > upperBound {
  49. t.Errorf("creation time %d is outside the expected range %d - %d", creationTime, lowerBound, upperBound)
  50. }
  51. })
  52. }
  53. }