github.com/fafucoder/cilium@v1.6.11/pkg/safetime/safetime_test.go (about) 1 // Copyright 2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // +build !privileged_tests 16 17 package safetime 18 19 import ( 20 "bytes" 21 "fmt" 22 "strings" 23 "testing" 24 "time" 25 26 log "github.com/sirupsen/logrus" 27 . "gopkg.in/check.v1" 28 ) 29 30 // Hook up gocheck into the "go test" runner. 31 func Test(t *testing.T) { 32 TestingT(t) 33 } 34 35 type SafetimeSuite struct { 36 out *bytes.Buffer // stores log output 37 logger *log.Entry 38 } 39 40 var _ = Suite(&SafetimeSuite{}) 41 42 func (s *SafetimeSuite) SetUpTest(c *C) { 43 s.out = &bytes.Buffer{} 44 logger := log.New() 45 logger.Out = s.out 46 s.logger = log.NewEntry(logger) 47 } 48 49 func (s *SafetimeSuite) TestNegativeDuration(c *C) { 50 future := time.Now().Add(time.Second) 51 d, ok := TimeSinceSafe(future, s.logger) 52 53 c.Assert(ok, Equals, false) 54 c.Assert(d, Equals, time.Duration(0)) 55 fmt.Println(s.out.String()) 56 c.Assert(strings.Contains(s.out.String(), "BUG: negative duration"), Equals, true) 57 } 58 59 func (s *SafetimeSuite) TestNonNegativeDuration(c *C) { 60 // To prevent the test case from being flaky on machines with invalid 61 // CLOCK_MONOTONIC: 62 past := time.Now().Add(-10 * time.Second) 63 d, ok := TimeSinceSafe(past, s.logger) 64 65 c.Assert(ok, Equals, true) 66 c.Assert(d > time.Duration(0), Equals, true) 67 c.Assert(len(s.out.String()) == 0, Equals, true) 68 }