go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/clock/systemclock_test.go (about)

     1  // Copyright 2016 The LUCI Authors.
     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  package clock
    16  
    17  import (
    18  	"context"
    19  	"testing"
    20  	"time"
    21  
    22  	. "github.com/smartystreets/goconvey/convey"
    23  )
    24  
    25  // timeBase is the amount of time where short-response goroutine events "should
    26  // happen". This isn't a great measure, since scheduling can take longer. Making
    27  // this short will make the test run faster at the possible expense of increased
    28  // raciness. Making this longer will increase test time, but will potentially
    29  // reduce the change of race-related errors.
    30  //
    31  // This should be kept >60ms which is a fairly gratuitous RTC-based scheduler
    32  // delay (1 hr / 2^16) that some older OSes may be subject to.
    33  const timeBase = 60 * time.Millisecond
    34  
    35  // veryLongTime is a time long enough that it won't feasably happen during the
    36  // course of test execution.
    37  const veryLongTime = 1000 * timeBase
    38  
    39  // TestSystemClock tests the non-trivial system clock methods.
    40  func TestSystemClock(t *testing.T) {
    41  	t.Parallel()
    42  
    43  	Convey(`A cancelable Context`, t, func() {
    44  		c, cancelFunc := context.WithCancel(context.Background())
    45  		sc := GetSystemClock()
    46  
    47  		Convey(`Will perform a full sleep if the Context isn't canceled.`, func() {
    48  			So(sc.Sleep(c, timeBase).Incomplete(), ShouldBeFalse)
    49  		})
    50  
    51  		Convey(`Will terminate the Sleep prematurely if the Context is canceled.`, func() {
    52  			cancelFunc()
    53  			So(sc.Sleep(c, veryLongTime).Incomplete(), ShouldBeTrue)
    54  			So(sc.Sleep(c, veryLongTime).Err, ShouldEqual, context.Canceled)
    55  		})
    56  	})
    57  }