timestruct_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2017 The Go Authors. All right reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
  5. package unix_test
  6. import (
  7. "testing"
  8. "time"
  9. "unsafe"
  10. "golang.org/x/sys/unix"
  11. )
  12. func TestTimeToTimespec(t *testing.T) {
  13. timeTests := []struct {
  14. time time.Time
  15. valid bool
  16. }{
  17. {time.Unix(0, 0), true},
  18. {time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), true},
  19. {time.Date(2262, time.December, 31, 23, 0, 0, 0, time.UTC), false},
  20. {time.Unix(0x7FFFFFFF, 0), true},
  21. {time.Unix(0x80000000, 0), false},
  22. {time.Unix(0x7FFFFFFF, 1000000000), false},
  23. {time.Unix(0x7FFFFFFF, 999999999), true},
  24. {time.Unix(-0x80000000, 0), true},
  25. {time.Unix(-0x80000001, 0), false},
  26. {time.Date(2038, time.January, 19, 3, 14, 7, 0, time.UTC), true},
  27. {time.Date(2038, time.January, 19, 3, 14, 8, 0, time.UTC), false},
  28. {time.Date(1901, time.December, 13, 20, 45, 52, 0, time.UTC), true},
  29. {time.Date(1901, time.December, 13, 20, 45, 51, 0, time.UTC), false},
  30. }
  31. // Currently all targets have either int32 or int64 for Timespec.Sec.
  32. // If there were a new target with unsigned or floating point type for
  33. // it, this test must be adjusted.
  34. have64BitTime := (unsafe.Sizeof(unix.Timespec{}.Sec) == 8)
  35. for _, tt := range timeTests {
  36. ts, err := unix.TimeToTimespec(tt.time)
  37. tt.valid = tt.valid || have64BitTime
  38. if tt.valid && err != nil {
  39. t.Errorf("TimeToTimespec(%v): %v", tt.time, err)
  40. }
  41. if err == nil {
  42. tstime := time.Unix(int64(ts.Sec), int64(ts.Nsec))
  43. if !tstime.Equal(tt.time) {
  44. t.Errorf("TimeToTimespec(%v) is the time %v", tt.time, tstime)
  45. }
  46. }
  47. }
  48. }