initial commit
[govpp.git] / vendor / github.com / onsi / gomega / matchers / be_temporally_matcher.go
1 package matchers
2
3 import (
4         "fmt"
5         "github.com/onsi/gomega/format"
6         "time"
7 )
8
9 type BeTemporallyMatcher struct {
10         Comparator string
11         CompareTo  time.Time
12         Threshold  []time.Duration
13 }
14
15 func (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) {
16         return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo)
17 }
18
19 func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
20         return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo)
21 }
22
23 func (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) {
24         // predicate to test for time.Time type
25         isTime := func(t interface{}) bool {
26                 _, ok := t.(time.Time)
27                 return ok
28         }
29
30         if !isTime(actual) {
31                 return false, fmt.Errorf("Expected a time.Time.  Got:\n%s", format.Object(actual, 1))
32         }
33
34         switch matcher.Comparator {
35         case "==", "~", ">", ">=", "<", "<=":
36         default:
37                 return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator)
38         }
39
40         var threshold = time.Millisecond
41         if len(matcher.Threshold) == 1 {
42                 threshold = matcher.Threshold[0]
43         }
44
45         return matcher.matchTimes(actual.(time.Time), matcher.CompareTo, threshold), nil
46 }
47
48 func (matcher *BeTemporallyMatcher) matchTimes(actual, compareTo time.Time, threshold time.Duration) (success bool) {
49         switch matcher.Comparator {
50         case "==":
51                 return actual.Equal(compareTo)
52         case "~":
53                 diff := actual.Sub(compareTo)
54                 return -threshold <= diff && diff <= threshold
55         case ">":
56                 return actual.After(compareTo)
57         case ">=":
58                 return !actual.Before(compareTo)
59         case "<":
60                 return actual.Before(compareTo)
61         case "<=":
62                 return !actual.After(compareTo)
63         }
64         return false
65 }