github.com/paketo-buildpacks/packit@v1.3.2-0.20211206231111-86b75c657449/chronos/clock_test.go (about)

     1  package chronos_test
     2  
     3  import (
     4  	"errors"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/paketo-buildpacks/packit/chronos"
     9  	"github.com/sclevine/spec"
    10  
    11  	. "github.com/onsi/gomega"
    12  )
    13  
    14  func testClock(t *testing.T, context spec.G, it spec.S) {
    15  	var Expect = NewWithT(t).Expect
    16  
    17  	context("Now", func() {
    18  		it("returns the value from the given Now function", func() {
    19  			now := time.Now()
    20  
    21  			clock := chronos.NewClock(func() time.Time {
    22  				return now
    23  			})
    24  
    25  			Expect(clock.Now()).To(Equal(now))
    26  		})
    27  	})
    28  
    29  	context("Measure", func() {
    30  		var clock chronos.Clock
    31  
    32  		it.Before(func() {
    33  			now := time.Now()
    34  			times := []time.Time{now, now.Add(20 * time.Second)}
    35  
    36  			clock = chronos.NewClock(func() time.Time {
    37  				t := time.Now()
    38  
    39  				if len(times) > 0 {
    40  					t = times[0]
    41  					times = times[1:]
    42  				}
    43  
    44  				return t
    45  			})
    46  		})
    47  
    48  		it("returns the duration taken to perform the operation", func() {
    49  			duration, err := clock.Measure(func() error {
    50  				return nil
    51  			})
    52  			Expect(err).NotTo(HaveOccurred())
    53  			Expect(duration).To(Equal(20 * time.Second))
    54  		})
    55  
    56  		context("when the operation errors", func() {
    57  			it("returns that error", func() {
    58  				_, err := clock.Measure(func() error {
    59  					return errors.New("operation failed")
    60  				})
    61  				Expect(err).To(MatchError("operation failed"))
    62  			})
    63  		})
    64  	})
    65  }