当前位置: 首页>>代码示例>>Golang>>正文


Golang clockwork.NewFakeClock函数代码示例

本文整理汇总了Golang中github.com/jonboulle/clockwork.NewFakeClock函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFakeClock函数的具体用法?Golang NewFakeClock怎么用?Golang NewFakeClock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewFakeClock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestNewDirExpirationTTL

func TestNewDirExpirationTTL(t *testing.T) {
	nd, _ := newTestNodeDir()

	if _, ttl := nd.expirationAndTTL(clockwork.NewFakeClock()); ttl > expiration.Nanoseconds() {
		t.Errorf("ttl = %d, want %d < %d", ttl, ttl, expiration.Nanoseconds())
	}

	newExpiration := time.Hour
	nd.UpdateTTL(time.Now().Add(newExpiration))
	if _, ttl := nd.expirationAndTTL(clockwork.NewFakeClock()); ttl > newExpiration.Nanoseconds() {
		t.Errorf("ttl = %d, want %d < %d", ttl, ttl, newExpiration.Nanoseconds())
	}
}
开发者ID:RomainVabre,项目名称:origin,代码行数:13,代码来源:node_test.go

示例2: TestNewDirReadWriteListReprClone

func TestNewDirReadWriteListReprClone(t *testing.T) {
	nd, _ := newTestNodeDir()

	if _, err := nd.Read(); err == nil {
		t.Errorf("err = %v, want err != nil", err)
	}

	if err := nd.Write(val, nd.CreatedIndex+1); err == nil {
		t.Errorf("err = %v, want err != nil", err)
	}

	if ns, err := nd.List(); ns == nil && err != nil {
		t.Errorf("nodes = %v and err = %v, want nodes = nil and err == nil", ns, err)
	}

	en := nd.Repr(false, false, clockwork.NewFakeClock())
	if en.Key != nd.Path {
		t.Errorf("en.Key = %s, want = %s", en.Key, nd.Path)
	}

	cn := nd.Clone()
	if cn.Path != nd.Path {
		t.Errorf("cn.Path = %s, want = %s", cn.Path, nd.Path)
	}
}
开发者ID:RomainVabre,项目名称:origin,代码行数:25,代码来源:node_test.go

示例3: TestWaitForProviderConfigImmediateSuccess

func TestWaitForProviderConfigImmediateSuccess(t *testing.T) {
	cfg := newValidProviderConfig()
	b, err := json.Marshal(&cfg)
	if err != nil {
		t.Fatalf("Failed marshaling provider config")
	}

	resp := http.Response{Body: ioutil.NopCloser(bytes.NewBuffer(b))}
	hc := &fakeClient{&resp}
	fc := clockwork.NewFakeClock()

	reschan := make(chan ProviderConfig)
	go func() {
		reschan <- waitForProviderConfig(hc, cfg.Issuer.String(), fc)
	}()

	var got ProviderConfig
	select {
	case got = <-reschan:
	case <-time.After(time.Second):
		t.Fatalf("Did not receive result within 1s")
	}

	if !reflect.DeepEqual(cfg, got) {
		t.Fatalf("Received incorrect provider config: want=%#v got=%#v", cfg, got)
	}
}
开发者ID:GamerockSA,项目名称:dex,代码行数:27,代码来源:provider_test.go

示例4: TestPrivateKeyManagerExpiresAt

func TestPrivateKeyManagerExpiresAt(t *testing.T) {
	fc := clockwork.NewFakeClock()
	now := fc.Now().UTC()

	k := generatePrivateKeyStatic(t, 17)
	km := &privateKeyManager{
		clock: fc,
	}

	want := fc.Now().UTC()
	got := km.ExpiresAt()
	if want != got {
		t.Fatalf("Incorrect expiration time: want=%v got=%v", want, got)
	}

	err := km.Set(&PrivateKeySet{
		keys:        []*PrivateKey{k},
		ActiveKeyID: k.KeyID,
		expiresAt:   now.Add(2 * time.Minute),
	})
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	want = fc.Now().UTC().Add(2 * time.Minute)
	got = km.ExpiresAt()
	if want != got {
		t.Fatalf("Incorrect expiration time: want=%v got=%v", want, got)
	}
}
开发者ID:RomainVabre,项目名称:origin,代码行数:30,代码来源:manager_test.go

示例5: makeTestSessionKeyRepoDB

func makeTestSessionKeyRepoDB(dsn string) func() (session.SessionKeyRepo, clockwork.FakeClock) {
	return func() (session.SessionKeyRepo, clockwork.FakeClock) {
		c := initDB(dsn)
		fc := clockwork.NewFakeClock()
		return db.NewSessionKeyRepoWithClock(c, fc), fc
	}
}
开发者ID:adrianlop,项目名称:dex,代码行数:7,代码来源:session_repo_test.go

示例6: TestPeriodic

func TestPeriodic(t *testing.T) {
	fc := clockwork.NewFakeClock()
	rg := &fakeRevGetter{testutil.NewRecorderStream(), 0}
	compactable := &fakeCompactable{testutil.NewRecorderStream()}
	tb := &Periodic{
		clock:        fc,
		periodInHour: 1,
		rg:           rg,
		c:            compactable,
	}

	tb.Run()
	defer tb.Stop()

	n := int(time.Hour / checkCompactionInterval)
	// collect 3 hours of revisions
	for i := 0; i < 3; i++ {
		// advance one hour, one revision for each interval
		for j := 0; j < n; j++ {
			fc.Advance(checkCompactionInterval)
			rg.Wait(1)
		}
		// ready to acknowledge hour "i"; unblock clock
		fc.Advance(checkCompactionInterval)
		a, err := compactable.Wait(1)
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(a[0].Params[0], &pb.CompactionRequest{Revision: int64(i*n) + 1}) {
			t.Errorf("compact request = %v, want %v", a[0].Params[0], &pb.CompactionRequest{Revision: int64(i*n) + 1})
		}
	}
}
开发者ID:mgurevin,项目名称:etcd,代码行数:33,代码来源:compactor_test.go

示例7: TestPeriodic

func TestPeriodic(t *testing.T) {
	fc := clockwork.NewFakeClock()
	compactable := &fakeCompactable{testutil.NewRecorderStream()}
	tb := &Periodic{
		clock:        fc,
		periodInHour: 1,
		rg:           &fakeRevGetter{},
		c:            compactable,
	}

	tb.Run()
	defer tb.Stop()

	n := int(time.Hour / checkCompactionInterval)
	for i := 0; i < 3; i++ {
		for j := 0; j < n; j++ {
			time.Sleep(5 * time.Millisecond)
			fc.Advance(checkCompactionInterval)
		}

		a, err := compactable.Wait(1)
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(a[0].Params[0], &pb.CompactionRequest{Revision: int64(i*n) + 1}) {
			t.Errorf("compact request = %v, want %v", a[0].Params[0], &pb.CompactionRequest{Revision: int64(i*n) + 1})
		}
	}
}
开发者ID:achanda,项目名称:etcd,代码行数:29,代码来源:compactor_test.go

示例8: newFakeClock

// newFakeClock creates a new FakeClock that has been advanced to at least minExpireTime
func newFakeClock() clockwork.FakeClock {
	fc := clockwork.NewFakeClock()
	for minExpireTime.After(fc.Now()) {
		fc.Advance((0x1 << 62) * time.Nanosecond)
	}
	return fc
}
开发者ID:CliffYuan,项目名称:etcd,代码行数:8,代码来源:store_test.go

示例9: TestNewPasswordReset

func TestNewPasswordReset(t *testing.T) {
	clock = clockwork.NewFakeClock()
	defer func() {
		clock = clockwork.NewRealClock()
	}()

	now := clock.Now()

	issuer, _ := url.Parse("http://example.com")
	clientID := "myclient"
	usr := User{ID: "123456", Email: "[email protected]"}
	callback := "http://client.example.com/callback"
	expires := time.Hour * 3
	password := Password("passy")

	tests := []struct {
		user     User
		password Password
		issuer   url.URL
		clientID string
		callback string
		expires  time.Duration
		want     jose.Claims
	}{
		{
			issuer:   *issuer,
			clientID: clientID,
			user:     usr,
			callback: callback,
			expires:  expires,
			password: password,
			want: map[string]interface{}{
				"iss": issuer.String(),
				"aud": clientID,
				ClaimPasswordResetCallback: callback,
				ClaimPasswordResetPassword: string(password),
				"exp": float64(now.Add(expires).Unix()),
				"sub": usr.ID,
				"iat": float64(now.Unix()),
			},
		},
	}

	for i, tt := range tests {
		cbURL, err := url.Parse(tt.callback)
		if err != nil {
			t.Fatalf("case %d: non-nil err: %q", i, err)
		}
		ev := NewPasswordReset(tt.user, tt.password, tt.issuer, tt.clientID, *cbURL, tt.expires)

		if diff := pretty.Compare(tt.want, ev.claims); diff != "" {
			t.Errorf("case %d: Compare(want, got): %v", i, diff)
		}

		if diff := pretty.Compare(ev.Password(), password); diff != "" {
			t.Errorf("case %d: Compare(want, got): %v", i, diff)
		}
	}
}
开发者ID:no2key,项目名称:dex,代码行数:59,代码来源:password_test.go

示例10: TestRekeyNeededUserClose

// A rekey is needed, but the user closes the rekey status window.
func TestRekeyNeededUserClose(t *testing.T) {
	tc := libkb.SetupTest(t, "gregor", 1)
	defer tc.Cleanup()

	rkeyui := &fakeRekeyUI{}
	rkeyui.notifyRefresh = make(chan bool, 10)
	router := fakeUIRouter{
		rekeyUI: rkeyui,
	}
	tc.G.SetUIRouter(&router)

	clock := clockwork.NewFakeClock()
	tc.G.SetClock(clock)

	gUID, h, rekeyHandler := rekeySetup(tc)

	rekeyBroadcast(tc, gUID, h, problemSet)

	select {
	case <-rekeyHandler.notifyStart:
	case <-time.After(20 * time.Second):
		t.Fatal("timeout waiting for rekeyHandler.notifyStart")
	}

	// since this is testing that the user closes a rekey status window,
	// wait for the refresh call:
	select {
	case <-rkeyui.notifyRefresh:
	case <-time.After(20 * time.Second):
		t.Fatal("timeout waiting for rekeyui.notifyRefresh")
	}

	// now call finish
	outcome, err := h.RekeyStatusFinish(context.Background(), rkeyui.sessionID)
	if err != nil {
		t.Fatal(err)
	}
	if outcome != keybase1.Outcome_IGNORED {
		t.Fatalf("RekeyStatusFinish outcome: %v, expected %v", outcome, keybase1.Outcome_IGNORED)
	}

	clock.Advance(3 * time.Second)

	select {
	case <-rekeyHandler.notifyComplete:
	case <-time.After(20 * time.Second):
		t.Fatal("timeout waiting for rekeyHandler.notifyComplete")
	}

	// there should be one call to refresh to bring the window up, but then the RekeyStatusFinish call above
	// should close the window and stop the loop.
	if len(rkeyui.refreshArgs) != 1 {
		t.Fatalf("rkeyui refresh calls: %d, expected 1", len(rkeyui.refreshArgs))
	}

	if len(rkeyui.refreshArgs[0].ProblemSetDevices.ProblemSet.Tlfs) != 1 {
		t.Errorf("first refresh call, tlf count = %d, expected 1", len(rkeyui.refreshArgs[0].ProblemSetDevices.ProblemSet.Tlfs))
	}
}
开发者ID:qbit,项目名称:client,代码行数:60,代码来源:rekey_test.go

示例11: newSessionKeyRepo

func newSessionKeyRepo(t *testing.T) (session.SessionKeyRepo, clockwork.FakeClock) {
	clock := clockwork.NewFakeClock()
	if os.Getenv("DEX_TEST_DSN") == "" {
		return db.NewSessionKeyRepoWithClock(db.NewMemDB(), clock), clock
	}
	dbMap := connect(t)
	return db.NewSessionKeyRepoWithClock(dbMap, clock), clock
}
开发者ID:GamerockSA,项目名称:dex,代码行数:8,代码来源:session_repo_test.go

示例12: TestPrivateKeyRotatorRun

func TestPrivateKeyRotatorRun(t *testing.T) {
	fc := clockwork.NewFakeClock()
	now := fc.Now().UTC()

	k1 := generatePrivateKeyStatic(t, 1)
	k2 := generatePrivateKeyStatic(t, 2)
	k3 := generatePrivateKeyStatic(t, 3)
	k4 := generatePrivateKeyStatic(t, 4)

	kRepo := NewPrivateKeySetRepo()
	krot := NewPrivateKeyRotator(kRepo, 4*time.Second)
	krot.clock = fc
	krot.generateKey = generatePrivateKeySerialFunc(t)

	steps := []*PrivateKeySet{
		&PrivateKeySet{
			keys:        []*PrivateKey{k1},
			ActiveKeyID: k1.KeyID,
			expiresAt:   now.Add(4 * time.Second),
		},
		&PrivateKeySet{
			keys:        []*PrivateKey{k2, k1},
			ActiveKeyID: k2.KeyID,
			expiresAt:   now.Add(6 * time.Second),
		},
		&PrivateKeySet{
			keys:        []*PrivateKey{k3, k2},
			ActiveKeyID: k3.KeyID,
			expiresAt:   now.Add(8 * time.Second),
		},
		&PrivateKeySet{
			keys:        []*PrivateKey{k4, k3},
			ActiveKeyID: k4.KeyID,
			expiresAt:   now.Add(10 * time.Second),
		},
	}

	stop := krot.Run()
	defer close(stop)

	for i, st := range steps {
		// wait for the rotater to get sleepy
		fc.BlockUntil(1)

		got, err := kRepo.Get()
		if err != nil {
			t.Fatalf("step %d: unexpected error: %v", i, err)
		}
		if !reflect.DeepEqual(st, got) {
			t.Fatalf("step %d: unexpected state: want=%#v got=%#v", i, st, got)
		}
		fc.Advance(2 * time.Second)
	}
}
开发者ID:GamerockSA,项目名称:dex,代码行数:54,代码来源:rotate_test.go

示例13: TestHandleKeysFunc

func TestHandleKeysFunc(t *testing.T) {
	fc := clockwork.NewFakeClock()
	exp := fc.Now().Add(13 * time.Second)
	km := &StaticKeyManager{
		expiresAt: exp,
		keys: []jose.JWK{
			jose.JWK{
				ID:       "1234",
				Type:     "RSA",
				Alg:      "RS256",
				Use:      "sig",
				Exponent: 65537,
				Modulus:  big.NewInt(int64(5716758339926702)),
			},
			jose.JWK{
				ID:       "5678",
				Type:     "RSA",
				Alg:      "RS256",
				Use:      "sig",
				Exponent: 65537,
				Modulus:  big.NewInt(int64(1234294715519622)),
			},
		},
	}

	req, err := http.NewRequest("GET", "http://server.example.com", nil)
	if err != nil {
		t.Fatalf("Failed creating HTTP request: err=%v", err)
	}

	w := httptest.NewRecorder()
	hdlr := handleKeysFunc(km, fc)
	hdlr.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("Incorrect status code: want=200 got=%d", w.Code)
	}

	wantHeader := http.Header{
		"Content-Type":  []string{"application/json"},
		"Cache-Control": []string{"public, max-age=13"},
		"Expires":       []string{exp.Format(time.RFC1123)},
	}
	gotHeader := w.Header()
	if !reflect.DeepEqual(wantHeader, gotHeader) {
		t.Fatalf("Incorrect headers: want=%#v got=%#v", wantHeader, gotHeader)
	}

	wantBody := `{"keys":[{"kid":"1234","kty":"RSA","alg":"RS256","use":"sig","e":"AQAB","n":"FE9chh46rg=="},{"kid":"5678","kty":"RSA","alg":"RS256","use":"sig","e":"AQAB","n":"BGKVohEShg=="}]}`
	gotBody := w.Body.String()
	if wantBody != gotBody {
		t.Fatalf("Incorrect body: want=%s got=%s", wantBody, gotBody)
	}
}
开发者ID:no2key,项目名称:dex,代码行数:54,代码来源:http_test.go

示例14: TestPrivateKeyRotatorExpiresAt

func TestPrivateKeyRotatorExpiresAt(t *testing.T) {
	fc := clockwork.NewFakeClock()
	krot := &PrivateKeyRotator{
		clock: fc,
		ttl:   time.Minute,
	}
	got := krot.expiresAt()
	want := fc.Now().UTC().Add(time.Minute)
	if !reflect.DeepEqual(want, got) {
		t.Errorf("Incorrect expiration time: want=%v got=%v", want, got)
	}
}
开发者ID:GamerockSA,项目名称:dex,代码行数:12,代码来源:rotate_test.go

示例15: TestHealthy

func TestHealthy(t *testing.T) {
	fc := clockwork.NewFakeClock()
	now := fc.Now().UTC()

	tests := []struct {
		expiresAt time.Time
		numKeys   int
		expected  error
	}{
		{
			expiresAt: now.Add(time.Hour),
			numKeys:   2,
			expected:  nil,
		},
		{
			expiresAt: now.Add(time.Hour),
			numKeys:   -1,
			expected:  ErrorNoKeys,
		},
		{
			expiresAt: now.Add(time.Hour),
			numKeys:   0,
			expected:  ErrorNoKeys,
		},
		{
			expiresAt: now.Add(-time.Hour),
			numKeys:   2,
			expected:  ErrorPrivateKeysExpired,
		},
	}

	for i, tt := range tests {
		kRepo := NewPrivateKeySetRepo()
		krot := NewPrivateKeyRotator(kRepo, time.Hour)
		krot.clock = fc
		pks := &PrivateKeySet{
			expiresAt: tt.expiresAt,
		}
		if tt.numKeys != -1 {
			for n := 0; n < tt.numKeys; n++ {
				pks.keys = append(pks.keys, generatePrivateKeyStatic(t, n))
			}
			err := kRepo.Set(pks)
			if err != nil {
				log.Fatalf("case %d: unexpected error: %v", i, err)
			}

		}
		if err := krot.Healthy(); err != tt.expected {
			t.Errorf("case %d: got==%q, want==%q", i, err, tt.expected)
		}
	}
}
开发者ID:GamerockSA,项目名称:dex,代码行数:53,代码来源:rotate_test.go


注:本文中的github.com/jonboulle/clockwork.NewFakeClock函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。