本文整理汇总了Golang中k8s/io/kubernetes/pkg/util.NewFakeClock函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFakeClock函数的具体用法?Golang NewFakeClock怎么用?Golang NewFakeClock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewFakeClock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestTTLPolicy
func TestTTLPolicy(t *testing.T) {
fakeTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
ttl := 30 * time.Second
exactlyOnTTL := fakeTime.Add(-ttl)
expiredTime := fakeTime.Add(-(ttl + 1))
policy := TTLPolicy{ttl, util.NewFakeClock(fakeTime)}
fakeTimestampedEntry := ×tampedEntry{obj: struct{}{}, timestamp: exactlyOnTTL}
if policy.IsExpired(fakeTimestampedEntry) {
t.Errorf("TTL cache should not expire entries exactly on ttl")
}
fakeTimestampedEntry.timestamp = fakeTime
if policy.IsExpired(fakeTimestampedEntry) {
t.Errorf("TTL Cache should not expire entries before ttl")
}
fakeTimestampedEntry.timestamp = expiredTime
if !policy.IsExpired(fakeTimestampedEntry) {
t.Errorf("TTL Cache should expire entries older than ttl")
}
for _, ttl = range []time.Duration{0, -1} {
policy.Ttl = ttl
if policy.IsExpired(fakeTimestampedEntry) {
t.Errorf("TTL policy should only expire entries when initialized with a ttl > 0")
}
}
}
示例2: TestBackoffGC
func TestBackoffGC(t *testing.T) {
id := "_idGC"
tc := util.NewFakeClock(time.Now())
step := time.Second
maxDuration := 5 * step
b := NewFakeBackOff(step, maxDuration, tc)
for i := 0; i <= int(maxDuration/step); i++ {
tc.Step(step)
b.Next(id, tc.Now())
}
lastUpdate := tc.Now()
tc.Step(maxDuration + step)
b.GC()
_, found := b.perItemBackoff[id]
if !found {
t.Errorf("expected GC to skip entry, elapsed time=%s maxDuration=%s", tc.Now().Sub(lastUpdate), maxDuration)
}
tc.Step(maxDuration + step)
b.GC()
r, found := b.perItemBackoff[id]
if found {
t.Errorf("expected GC of entry after %s got entry %v", tc.Now().Sub(lastUpdate), r)
}
}
示例3: TestExpirationBasic
func TestExpirationBasic(t *testing.T) {
unexpectedVal := "bar"
expectedVal := "bar2"
testObj := testObject{
key: "foo",
val: unexpectedVal,
}
fakeClock := util.NewFakeClock(time.Now())
objectCache := NewFakeObjectCache(func() (interface{}, error) {
return expectedVal, nil
}, 1*time.Second, fakeClock)
err := objectCache.Add(testObj.key, testObj.val)
if err != nil {
t.Errorf("Unable to add obj %#v by key: %s", testObj, testObj.key)
}
// sleep 2s so cache should be expired.
fakeClock.Sleep(2 * time.Second)
value, err := objectCache.Get(testObj.key)
if err != nil {
t.Errorf("Unable to get obj %#v by key: %s", testObj, testObj.key)
}
if value.(string) != expectedVal {
t.Errorf("Expected to get cached value: %#v, but got: %s", expectedVal, value.(string))
}
}
示例4: getTestSQ
func getTestSQ(startThreads bool, config *github_util.Config, server *httptest.Server) *SubmitQueue {
// TODO: Remove this line when we fix the plumbing regarding the fake/real e2e tester.
admin.Mux = admin.NewConcurrentMux()
sq := new(SubmitQueue)
sq.RequiredStatusContexts = []string{notRequiredReTestContext1, notRequiredReTestContext2}
sq.RequiredRetestContexts = []string{requiredReTestContext1, requiredReTestContext2}
sq.BlockingJobNames = []string{"foo"}
sq.WeakStableJobNames = []string{"bar"}
sq.githubE2EQueue = map[int]*github_util.MungeObject{}
sq.githubE2EPollTime = 50 * time.Millisecond
sq.clock = util.NewFakeClock(time.Time{})
sq.lastMergeTime = sq.clock.Now()
sq.lastE2EStable = true
sq.prStatus = map[string]submitStatus{}
sq.lastPRStatus = map[string]submitStatus{}
sq.lgtmTimeCache = mungerutil.NewLabelTimeCache(lgtmLabel)
sq.startTime = sq.clock.Now()
sq.healthHistory = make([]healthRecord, 0)
sq.DoNotMergeMilestones = []string{doNotMergeMilestone}
sq.e2e = &fake_e2e.FakeE2ETester{
JobNames: sq.BlockingJobNames,
WeakStableJobNames: sq.WeakStableJobNames,
}
if startThreads {
sq.internalInitialize(config, nil, server.URL)
sq.EachLoop()
}
return sq
}
示例5: getTestSQ
func getTestSQ(startThreads bool, config *github_util.Config, server *httptest.Server) *SubmitQueue {
sq := new(SubmitQueue)
sq.RequiredStatusContexts = []string{jenkinsUnitContext}
sq.E2EStatusContext = jenkinsE2EContext
sq.UnitStatusContext = jenkinsUnitContext
if server != nil {
sq.JenkinsHost = server.URL
}
sq.JobNames = []string{"foo"}
sq.WeakStableJobNames = []string{"bar"}
sq.githubE2EQueue = map[int]*github_util.MungeObject{}
sq.githubE2EPollTime = 50 * time.Millisecond
sq.clock = util.NewFakeClock(time.Time{})
sq.lastMergeTime = sq.clock.Now()
sq.lastE2EStable = true
sq.prStatus = map[string]submitStatus{}
sq.lastPRStatus = map[string]submitStatus{}
if startThreads {
sq.internalInitialize(config, nil, server.URL)
sq.EachLoop()
sq.userWhitelist.Insert(whitelistUser)
}
return sq
}
示例6: TestBackoffReset
func TestBackoffReset(t *testing.T) {
id := "_idReset"
tc := util.NewFakeClock(time.Now())
step := time.Second
maxDuration := step * 5
b := NewFakeBackOff(step, maxDuration, tc)
startTime := tc.Now()
// get to backoff = maxDuration
for i := 0; i <= int(maxDuration/step); i++ {
tc.Step(step)
b.Next(id, tc.Now())
}
// backoff should be capped at maxDuration
if !b.IsInBackOffSince(id, tc.Now()) {
t.Errorf("expected to be in Backoff got %s", b.Get(id))
}
lastUpdate := tc.Now()
tc.Step(2*maxDuration + step) // time += 11s, 11 > 2*maxDuration
if b.IsInBackOffSince(id, lastUpdate) {
t.Errorf("now=%s lastUpdate=%s (%s) expected Backoff reset got %s b.lastUpdate=%s", tc.Now(), startTime, tc.Now().Sub(lastUpdate), b.Get(id))
}
}
示例7: TestSlowBackoff
func TestSlowBackoff(t *testing.T) {
id := "_idSlow"
tc := util.NewFakeClock(time.Now())
step := time.Second
maxDuration := 50 * step
b := NewFakeBackOff(step, maxDuration, tc)
cases := []time.Duration{0, 1, 2, 4, 8, 16, 32, 50, 50, 50}
for ix, c := range cases {
tc.Step(step)
w := b.Get(id)
if w != c*step {
t.Errorf("input: '%d': expected %s, got %s", ix, c*step, w)
}
b.Next(id, tc.Now())
}
//Now confirm that the Reset cancels backoff.
b.Next(id, tc.Now())
b.Reset(id)
if b.Get(id) != 0 {
t.Errorf("Reset didn't clear the backoff.")
}
}
示例8: NewFakeControllerExpectationsLookup
// NewFakeControllerExpectationsLookup creates a fake store for PodExpectations.
func NewFakeControllerExpectationsLookup(ttl time.Duration) (*ControllerExpectations, *util.FakeClock) {
fakeTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
fakeClock := util.NewFakeClock(fakeTime)
ttlPolicy := &cache.TTLPolicy{Ttl: ttl, Clock: fakeClock}
ttlStore := cache.NewFakeExpirationStore(
ExpKeyFunc, nil, ttlPolicy, fakeClock)
return &ControllerExpectations{ttlStore}, fakeClock
}
示例9: TestIsTunnelSyncHealthy
// TestIsTunnelSyncHealthy verifies that the 600 second lag test
// is honored.
func TestIsTunnelSyncHealthy(t *testing.T) {
tunneler := &SSHTunneler{}
master, etcdserver, _, assert := setUp(t)
defer etcdserver.Terminate(t)
master.tunneler = tunneler
// Pass case: 540 second lag
tunneler.lastSync = time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC).Unix()
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 9, 1, 1, time.UTC))
err := master.IsTunnelSyncHealthy(nil)
assert.NoError(err, "IsTunnelSyncHealthy() should not have returned an error.")
// Fail case: 720 second lag
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 12, 1, 1, time.UTC))
err = master.IsTunnelSyncHealthy(nil)
assert.Error(err, "IsTunnelSyncHealthy() should have returned an error.")
}
示例10: newTestBasicWorkQueue
func newTestBasicWorkQueue() (*basicWorkQueue, *util.FakeClock) {
fakeClock := util.NewFakeClock(time.Now())
wq := &basicWorkQueue{
clock: fakeClock,
queue: make(map[types.UID]time.Time),
}
return wq, fakeClock
}
示例11: TestDeduping
func TestDeduping(t *testing.T) {
fakeClock := util.NewFakeClock(time.Now())
q := newDelayingQueue(fakeClock)
first := "foo"
q.AddAfter(first, 50*time.Millisecond)
if err := waitForWaitingQueueToFill(q); err != nil {
t.Fatalf("unexpected err: %v", err)
}
q.AddAfter(first, 70*time.Millisecond)
if err := waitForWaitingQueueToFill(q); err != nil {
t.Fatalf("unexpected err: %v", err)
}
if q.Len() != 0 {
t.Errorf("should not have added")
}
// step past the first block, we should receive now
fakeClock.Step(60 * time.Millisecond)
if err := waitForAdded(q, 1); err != nil {
t.Errorf("should have added")
}
item, _ := q.Get()
q.Done(item)
// step past the second add
fakeClock.Step(20 * time.Millisecond)
if q.Len() != 0 {
t.Errorf("should not have added")
}
// test again, but this time the earlier should override
q.AddAfter(first, 50*time.Millisecond)
q.AddAfter(first, 30*time.Millisecond)
if err := waitForWaitingQueueToFill(q); err != nil {
t.Fatalf("unexpected err: %v", err)
}
if q.Len() != 0 {
t.Errorf("should not have added")
}
fakeClock.Step(40 * time.Millisecond)
if err := waitForAdded(q, 1); err != nil {
t.Errorf("should have added")
}
item, _ = q.Get()
q.Done(item)
// step past the second add
fakeClock.Step(20 * time.Millisecond)
if q.Len() != 0 {
t.Errorf("should not have added")
}
if q.Len() != 0 {
t.Errorf("should not have added")
}
}
示例12: TestSecondsSinceSync
// TestSecondsSinceSync verifies that proper results are returned
// when checking the time between syncs
func TestSecondsSinceSync(t *testing.T) {
tunneler := &SSHTunneler{}
assert := assert.New(t)
tunneler.lastSync = time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC).Unix()
// Nano Second. No difference.
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 1, 1, 2, time.UTC))
assert.Equal(int64(0), tunneler.SecondsSinceSync())
// Second
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 1, 2, 1, time.UTC))
assert.Equal(int64(1), tunneler.SecondsSinceSync())
// Minute
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 2, 1, 1, time.UTC))
assert.Equal(int64(60), tunneler.SecondsSinceSync())
// Hour
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 2, 1, 1, 1, time.UTC))
assert.Equal(int64(3600), tunneler.SecondsSinceSync())
// Day
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 2, 1, 1, 1, 1, time.UTC))
assert.Equal(int64(86400), tunneler.SecondsSinceSync())
// Month
tunneler.clock = util.NewFakeClock(time.Date(2015, time.February, 1, 1, 1, 1, 1, time.UTC))
assert.Equal(int64(2678400), tunneler.SecondsSinceSync())
// Future Month. Should be -Month.
tunneler.lastSync = time.Date(2015, time.February, 1, 1, 1, 1, 1, time.UTC).Unix()
tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC))
assert.Equal(int64(-2678400), tunneler.SecondsSinceSync())
}
示例13: TestRepositoryBucketAddOversize
func TestRepositoryBucketAddOversize(t *testing.T) {
clock := util.NewFakeClock(time.Now())
b := repositoryBucket{
clock: clock,
}
i := 0
for ; i < bucketSize; i++ {
ttl := time.Duration(uint64(ttl5m) * uint64(i))
b.Add(ttl, fmt.Sprintf("%d", i))
}
if len(b.list) != bucketSize {
t.Fatalf("unexpected number of items: %d != %d", len(b.list), bucketSize)
}
// make first three stale
clock.Step(ttl5m * 3)
if !b.Has("3") {
t.Fatalf("bucket does not contain repository 3")
}
if len(b.list) != bucketSize-3 {
t.Fatalf("unexpected number of items: %d != %d", len(b.list), bucketSize-3)
}
// add few repos one by one
for ; i < bucketSize+5; i++ {
ttl := time.Duration(uint64(ttl5m) * uint64(i))
b.Add(ttl, fmt.Sprintf("%d", i))
}
if len(b.list) != bucketSize {
t.Fatalf("unexpected number of items: %d != %d", len(b.list), bucketSize)
}
// add few repos at once
newRepos := []string{}
for ; i < bucketSize+10; i++ {
newRepos = append(newRepos, fmt.Sprintf("%d", i))
}
b.Add(ttl5m, newRepos...)
if len(b.list) != bucketSize {
t.Fatalf("unexpected number of items: %d != %d", len(b.list), bucketSize)
}
for j := 0; j < bucketSize; j++ {
expected := fmt.Sprintf("%d", i-bucketSize+j)
if b.list[j].repository != expected {
t.Fatalf("unexpected repository on index %d: %s != %s", j, b.list[j].repository, expected)
}
}
}
示例14: TestRepositoryBucketCopy
func TestRepositoryBucketCopy(t *testing.T) {
now := time.Now()
clock := util.NewFakeClock(now)
ttl5m := time.Minute * 5
for _, tc := range []struct {
name string
entries []bucketEntry
expectedRepos []string
}{
{
name: "no entry",
expectedRepos: []string{},
},
{
name: "one stale entry",
entries: []bucketEntry{
{
repository: "1",
},
},
expectedRepos: []string{},
},
{
name: "two entries",
entries: []bucketEntry{
{
repository: "a",
evictOn: now.Add(ttl5m),
},
{
repository: "b",
evictOn: now.Add(ttl5m),
},
},
expectedRepos: []string{"a", "b"},
},
} {
b := repositoryBucket{
clock: clock,
list: tc.entries,
}
result := b.Copy()
if !reflect.DeepEqual(result, tc.expectedRepos) {
t.Errorf("[%s] got unexpected repo list: %s", tc.name, diff.ObjectGoPrintDiff(result, tc.expectedRepos))
}
}
}
示例15: TestActiveDeadlineHandler
// TestActiveDeadlineHandler verifies the active deadline handler functions as expected.
func TestActiveDeadlineHandler(t *testing.T) {
pods := newTestPods(4)
fakeClock := util.NewFakeClock(time.Now())
podStatusProvider := &mockPodStatusProvider{pods: pods}
fakeRecorder := &record.FakeRecorder{}
handler, err := newActiveDeadlineHandler(podStatusProvider, fakeRecorder, fakeClock)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
now := unversioned.Now()
startTime := unversioned.NewTime(now.Time.Add(-1 * time.Minute))
// this pod has exceeded its active deadline
exceededActiveDeadlineSeconds := int64(30)
pods[0].Status.StartTime = &startTime
pods[0].Spec.ActiveDeadlineSeconds = &exceededActiveDeadlineSeconds
// this pod has not exceeded its active deadline
notYetActiveDeadlineSeconds := int64(120)
pods[1].Status.StartTime = &startTime
pods[1].Spec.ActiveDeadlineSeconds = ¬YetActiveDeadlineSeconds
// this pod has no deadline
pods[2].Status.StartTime = &startTime
pods[2].Spec.ActiveDeadlineSeconds = nil
testCases := []struct {
pod *api.Pod
expected bool
}{{pods[0], true}, {pods[1], false}, {pods[2], false}, {pods[3], false}}
for i, testCase := range testCases {
if actual := handler.ShouldSync(testCase.pod); actual != testCase.expected {
t.Errorf("[%d] ShouldSync expected %#v, got %#v", i, testCase.expected, actual)
}
actual := handler.ShouldEvict(testCase.pod)
if actual.Evict != testCase.expected {
t.Errorf("[%d] ShouldEvict.Evict expected %#v, got %#v", i, testCase.expected, actual.Evict)
}
if testCase.expected {
if actual.Reason != reason {
t.Errorf("[%d] ShouldEvict.Reason expected %#v, got %#v", i, message, actual.Reason)
}
if actual.Message != message {
t.Errorf("[%d] ShouldEvict.Message expected %#v, got %#v", i, message, actual.Message)
}
}
}
}