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


Golang clock.NewMock函数代码示例

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


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

示例1: TestMock_Ticker_Stop

// Ensure that the mock's Ticker can be stopped.
func TestMock_Ticker_Stop(t *testing.T) {
	var n int32
	clock := clock.NewMock()

	// Create a channel to increment every second.
	ticker := clock.Ticker(1 * time.Second)
	go func() {
		for {
			<-ticker.C
			atomic.AddInt32(&n, 1)
		}
	}()
	gosched()

	// Move clock forward.
	clock.Add(5 * time.Second)
	if atomic.LoadInt32(&n) != 5 {
		t.Fatalf("expected 5, got: %d", n)
	}

	ticker.Stop()

	// Move clock forward again.
	clock.Add(5 * time.Second)
	if atomic.LoadInt32(&n) != 5 {
		t.Fatalf("still expected 5, got: %d", n)
	}
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:29,代码来源:clock_test.go

示例2: TestMock_Ticker_Multi

// Ensure that multiple tickers can be used together.
func TestMock_Ticker_Multi(t *testing.T) {
	var n int32
	clock := clock.NewMock()

	go func() {
		a := clock.Ticker(1 * time.Microsecond)
		b := clock.Ticker(3 * time.Microsecond)

		for {
			select {
			case <-a.C:
				atomic.AddInt32(&n, 1)
			case <-b.C:
				atomic.AddInt32(&n, 100)
			}
		}
	}()
	gosched()

	// Move clock forward.
	clock.Add(10 * time.Microsecond)
	gosched()
	if atomic.LoadInt32(&n) != 310 {
		t.Fatalf("unexpected: %d", n)
	}
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:27,代码来源:clock_test.go

示例3: TestBreakerEvents

func TestBreakerEvents(t *testing.T) {
	c := clock.NewMock()
	cb := NewBreaker()
	cb.Clock = c
	events := cb.Subscribe()

	cb.Trip()
	if e := <-events; e != BreakerTripped {
		t.Fatalf("expected to receive a trip event, got %d", e)
	}

	c.Add(cb.nextBackOff + 1)
	cb.Ready()
	if e := <-events; e != BreakerReady {
		t.Fatalf("expected to receive a breaker ready event, got %d", e)
	}

	cb.Reset()
	if e := <-events; e != BreakerReset {
		t.Fatalf("expected to receive a reset event, got %d", e)
	}

	cb.Fail()
	if e := <-events; e != BreakerFail {
		t.Fatalf("expected to receive a fail event, got %d", e)
	}
}
开发者ID:rubyist,项目名称:circuitbreaker,代码行数:27,代码来源:circuitbreaker_test.go

示例4: ExampleMock_Ticker

func ExampleMock_Ticker() {
	// Create a new mock clock.
	clock := clock.NewMock()
	count := 0

	// Increment count every mock second.
	go func() {
		ticker := clock.Ticker(1 * time.Second)
		for {
			<-ticker.C
			count++
		}
	}()
	runtime.Gosched()

	// Move the clock forward 10 seconds and print the new value.
	clock.Add(10 * time.Second)
	fmt.Printf("Count is %d after 10 seconds\n", count)

	// Move the clock forward 5 more seconds and print the new value.
	clock.Add(5 * time.Second)
	fmt.Printf("Count is %d after 15 seconds\n", count)

	// Output:
	// Count is 10 after 10 seconds
	// Count is 15 after 15 seconds
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:27,代码来源:clock_test.go

示例5: ExampleMock_After

func ExampleMock_After() {
	// Create a new mock clock.
	clock := clock.NewMock()
	count := 0

	// Create a channel to execute after 10 mock seconds.
	go func() {
		<-clock.After(10 * time.Second)
		count = 100
	}()
	runtime.Gosched()

	// Print the starting value.
	fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

	// Move the clock forward 5 seconds and print the value again.
	clock.Add(5 * time.Second)
	fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

	// Move the clock forward 5 seconds to the tick time and check the value.
	clock.Add(5 * time.Second)
	fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

	// Output:
	// 1970-01-01 00:00:00 +0000 UTC: 0
	// 1970-01-01 00:00:05 +0000 UTC: 0
	// 1970-01-01 00:00:10 +0000 UTC: 100
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:28,代码来源:clock_test.go

示例6: TestThresholdBreakerResets

func TestThresholdBreakerResets(t *testing.T) {
	called := 0
	success := false
	circuit := func() error {
		if called == 0 {
			called++
			return fmt.Errorf("error")
		}
		success = true
		return nil
	}

	c := clock.NewMock()
	cb := NewThresholdBreaker(1)
	cb.Clock = c
	err := cb.Call(circuit, 0)
	if err == nil {
		t.Fatal("Expected cb to return an error")
	}

	c.Add(cb.nextBackOff + 1)
	for i := 0; i < 4; i++ {
		err = cb.Call(circuit, 0)
		if err != nil {
			t.Fatal("Expected cb to be successful")
		}

		if !success {
			t.Fatal("Expected cb to have been reset")
		}
	}
}
开发者ID:rubyist,项目名称:circuitbreaker,代码行数:32,代码来源:circuitbreaker_test.go

示例7: ExamplePerSecondHasher

// The following example shows how to create mock hashers for testing the rate
// limiter in your code:
func ExamplePerSecondHasher() {
	// Create a mock clock.
	mock := clock.NewMock()

	// Create a new per second hasher with the mock clock.
	hasher := PerMinuteHasher{
		Clock: mock,
	}

	// Generate two consecutive hashes. On most systems, the following should
	// generate two identical hashes.
	hashOne := hasher.Hash("127.0.0.1")
	hashTwo := hasher.Hash("127.0.0.1")

	// Now we push the clock forward by a minute (time travel).
	mock.Add(time.Minute)

	// The third hash should be different now.
	hashThree := hasher.Hash("127.0.0.1")

	fmt.Println(hashOne == hashTwo)
	fmt.Println(hashOne == hashThree)
	// Output: true
	// false
}
开发者ID:vially,项目名称:speedbump,代码行数:27,代码来源:hashers_test.go

示例8: Test_PerMinute_Hash

func Test_PerMinute_Hash(t *testing.T) {
	mock := clock.NewMock()
	hasher := PerMinuteHasher{
		Clock: mock,
	}

	resultOne := hasher.Hash("127.0.0.1")

	mock.Add(time.Minute)

	resultTwo := hasher.Hash("127.0.0.1")

	assert.NotEqual(t, resultOne, resultTwo)

	resultThree := hasher.Hash("127.0.0.1")
	resultFour := hasher.Hash("127.0.0.1")
	resultFive := hasher.Hash("127.0.0.2")

	assert.Equal(t, resultThree, resultFour)
	assert.NotEqual(t, resultFour, resultFive)

	// Test that it can create a new clock
	hasher = PerMinuteHasher{}
	hasher.Hash("127.0.0.1")
}
开发者ID:vially,项目名称:speedbump,代码行数:25,代码来源:hashers_test.go

示例9: TestMock_Tick

// Ensure that the mock's Tick channel sends at the correct time.
func TestMock_Tick(t *testing.T) {
	var n int32
	clock := clock.NewMock()

	// Create a channel to increment every 10 seconds.
	go func() {
		tick := clock.Tick(10 * time.Second)
		for {
			<-tick
			atomic.AddInt32(&n, 1)
		}
	}()
	gosched()

	// Move clock forward to just before the first tick.
	clock.Add(9 * time.Second)
	if atomic.LoadInt32(&n) != 0 {
		t.Fatalf("expected 0, got %d", n)
	}

	// Move clock forward to the start of the first tick.
	clock.Add(1 * time.Second)
	if atomic.LoadInt32(&n) != 1 {
		t.Fatalf("expected 1, got %d", n)
	}

	// Move clock forward over several ticks.
	clock.Add(30 * time.Second)
	if atomic.LoadInt32(&n) != 4 {
		t.Fatalf("expected 4, got %d", n)
	}
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:33,代码来源:clock_test.go

示例10: TestMock_Now

// Ensure that the mock's current time can be changed.
func TestMock_Now(t *testing.T) {
	clock := clock.NewMock()
	if now := clock.Now(); !now.Equal(time.Unix(0, 0)) {
		t.Fatalf("expected epoch, got: ", now)
	}

	// Add 10 seconds and check the time.
	clock.Add(10 * time.Second)
	if now := clock.Now(); !now.Equal(time.Unix(10, 0)) {
		t.Fatalf("expected epoch, got: ", now)
	}
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:13,代码来源:clock_test.go

示例11: NewHarness

func NewHarness(t testing.TB) *Harness {
	te := Harness{
		T:     t,
		Clock: clock.NewMock(),
	}
	te.Env = &Env{
		Out:            &te.Out,
		Err:            &te.Err,
		Clock:          te.Clock,
		ParseAPIClient: &ParseAPIClient{APIClient: &parse.Client{}},
	}
	return &te
}
开发者ID:swhitley,项目名称:parse-cli,代码行数:13,代码来源:main.go

示例12: TestMock_AfterFunc_Stop

// Ensure that the mock's AfterFunc doesn't execute if stopped.
func TestMock_AfterFunc_Stop(t *testing.T) {
	// Execute function after duration.
	clock := clock.NewMock()
	timer := clock.AfterFunc(10*time.Second, func() {
		t.Fatal("unexpected function execution")
	})
	gosched()

	// Stop timer & move clock forward.
	timer.Stop()
	clock.Add(10 * time.Second)
	gosched()
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:14,代码来源:clock_test.go

示例13: newHarness

func newHarness(t testing.TB) *Harness {
	te := Harness{
		T:     t,
		Clock: clock.NewMock(),
	}
	te.env = &env{
		Out:    &te.Out,
		Err:    &te.Err,
		Clock:  te.Clock,
		Client: &Client{client: &parse.Client{}},
	}
	return &te
}
开发者ID:huamichaelchen,项目名称:parse-cli,代码行数:13,代码来源:main_test.go

示例14: TestHTTPStopTimeoutMissed

func TestHTTPStopTimeoutMissed(t *testing.T) {
	t.Parallel()

	klock := clock.NewMock()

	const count = 10000
	hello := []byte("hello")
	finOkHandler := make(chan struct{})
	unblockOkHandler := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(finOkHandler)
		w.Header().Set("Content-Length", fmt.Sprint(len(hello)*count))
		w.WriteHeader(200)
		for i := 0; i < count/2; i++ {
			w.Write(hello)
		}
		<-unblockOkHandler
		for i := 0; i < count/2; i++ {
			w.Write(hello)
		}
	}

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	ensure.Nil(t, err)
	server := &http.Server{Handler: http.HandlerFunc(okHandler)}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{
		StopTimeout: time.Minute,
		Clock:       klock,
	}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)

	finStop := make(chan struct{})
	go func() {
		defer close(finStop)
		ensure.Nil(t, s.Stop())
	}()

	klock.Wait(clock.Calls{After: 1}) // wait for Stop to call After
	klock.Add(down.StopTimeout)

	_, err = ioutil.ReadAll(res.Body)
	ensure.Err(t, err, regexp.MustCompile("^unexpected EOF$"))
	ensure.Nil(t, res.Body.Close())
	close(unblockOkHandler)
	<-finOkHandler
	<-finStop
}
开发者ID:fwessels,项目名称:minio-xl,代码行数:51,代码来源:httpdown_test.go

示例15: TestStatsTicker

func TestStatsTicker(t *testing.T) {
	t.Parallel()

	klock := clock.NewMock()
	expected := []string{"alive", "idle", "out", "waiting"}

	statsDone := make(chan string, 4)
	hc := &stats.HookClient{
		BumpAvgHook: func(key string, val float64) {
			if contains(expected, key) {
				statsDone <- key
			}
		},
	}

	var cm resourceMaker
	p := Pool{
		New:           cm.New,
		Stats:         hc,
		Max:           4,
		MinIdle:       2,
		IdleTimeout:   time.Second,
		ClosePoolSize: 2,
		Clock:         klock,
	}

	// acquire and release some resources to make them idle
	var resources []io.Closer
	for i := p.Max; i > 0; i-- {
		r, err := p.Acquire()
		ensure.Nil(t, err)
		resources = append(resources, r)
	}
	for _, r := range resources {
		p.Release(r)
	}

	// tick IdleTimeout to make them eligible
	klock.Add(p.IdleTimeout)

	// tick Minute to trigger stats
	klock.Add(time.Minute)

	// stats should soon show idle closed
	ensure.SameElements(
		t,
		[]string{<-statsDone, <-statsDone, <-statsDone, <-statsDone},
		expected,
	)
}
开发者ID:intercom,项目名称:dvara,代码行数:50,代码来源:rpool_test.go


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