• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang fakeclock.NewFakeClock函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: defaultConf

func defaultConf() HandlerConf {
	return HandlerConf{
		StoreAdapter: fakestoreadapter.New(),
		Clock:        fakeclock.NewFakeClock(time.Unix(100, 0)),
		Logger:       fakelogger.NewFakeLogger(),
	}
}
开发者ID:nagyistge,项目名称:hm9000,代码行数:7,代码来源:bulk_app_state_test.go


示例2:

	. "github.com/onsi/gomega"

	boshlog "github.com/cloudfoundry/bosh-utils/logger"
	"github.com/pivotal-golang/clock/fakeclock"

	. "github.com/cloudfoundry/bosh-utils/retrystrategy"
)

var _ = Describe("TimeoutRetryStrategy", func() {
	var (
		fakeTimeService *fakeclock.FakeClock
		logger          boshlog.Logger
	)

	BeforeEach(func() {
		fakeTimeService = fakeclock.NewFakeClock(time.Now())
		logger = boshlog.NewLogger(boshlog.LevelNone)
	})

	Describe("Try", func() {
		Context("when there are errors during a try", func() {
			It("retries until the timeout", func() {
				retryable := newSimpleRetryable([]attemptOutput{
					{
						IsRetryable: true,
						AttemptErr:  errors.New("first-error"),
					},
					{
						IsRetryable: true,
						AttemptErr:  errors.New("second-error"),
					},
开发者ID:mattcui,项目名称:bosh-agent,代码行数:31,代码来源:timeout_retry_strategy_test.go


示例3:

		fakeQueue              *fake_operationq.FakeQueue
		evacuatable            evacuation_context.Evacuatable
		evacuationNotifier     evacuation_context.EvacuationNotifier

		bulker  *harmonizer.Bulker
		process ifrit.Process
	)

	BeforeEach(func() {
		sender = fake.NewFakeMetricSender()
		metrics.Initialize(sender, nil)

		logger = lagertest.NewTestLogger("test")
		pollInterval = 30 * time.Second
		evacuationPollInterval = 10 * time.Second
		fakeClock = fakeclock.NewFakeClock(time.Unix(123, 456))
		fakeGenerator = new(fake_generator.FakeGenerator)
		fakeQueue = new(fake_operationq.FakeQueue)

		evacuatable, _, evacuationNotifier = evacuation_context.New()

		bulker = harmonizer.NewBulker(logger, pollInterval, evacuationPollInterval, evacuationNotifier, fakeClock, fakeGenerator, fakeQueue)
	})

	JustBeforeEach(func() {
		process = ifrit.Invoke(bulker)
		Eventually(fakeClock.WatcherCount).Should(Equal(1))
	})

	AfterEach(func() {
		process.Signal(os.Interrupt)
开发者ID:jiangytcn,项目名称:rep,代码行数:31,代码来源:bulker_test.go


示例4:

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/tedsuo/ifrit"
)

var _ = Describe("Pipelines Sync Runner", func() {
	var fakeSyncer *fakes.FakePipelineSyncer
	var interval = 10 * time.Second
	var fakeClock *fakeclock.FakeClock
	var runner SyncRunner
	var process ifrit.Process

	BeforeEach(func() {
		fakeSyncer = new(fakes.FakePipelineSyncer)
		fakeClock = fakeclock.NewFakeClock(time.Unix(0, 123))

		runner = SyncRunner{
			Syncer:   fakeSyncer,
			Interval: interval,
			Clock:    fakeClock,
		}
	})

	JustBeforeEach(func() {
		process = ifrit.Invoke(runner)
	})

	AfterEach(func() {
		process.Signal(os.Interrupt)
		Eventually(process.Wait()).Should(Receive())
开发者ID:utako,项目名称:atc,代码行数:31,代码来源:sync_runner_test.go


示例5: init

func init() {
	Describe("Agent", func() {
		var (
			logger           boshlog.Logger
			handler          *fakembus.FakeHandler
			platform         *fakeplatform.FakePlatform
			actionDispatcher *fakeagent.FakeActionDispatcher
			jobSupervisor    *fakejobsuper.FakeJobSupervisor
			specService      *fakeas.FakeV1Service
			syslogServer     *fakesyslog.FakeServer
			settingsService  *fakesettings.FakeSettingsService
			uuidGenerator    *fakeuuid.FakeGenerator
			timeService      *fakeclock.FakeClock
			agent            Agent
		)

		BeforeEach(func() {
			logger = boshlog.NewLogger(boshlog.LevelNone)
			handler = &fakembus.FakeHandler{}
			platform = fakeplatform.NewFakePlatform()
			actionDispatcher = &fakeagent.FakeActionDispatcher{}
			jobSupervisor = fakejobsuper.NewFakeJobSupervisor()
			specService = fakeas.NewFakeV1Service()
			syslogServer = &fakesyslog.FakeServer{}
			settingsService = &fakesettings.FakeSettingsService{}
			uuidGenerator = &fakeuuid.FakeGenerator{}
			timeService = fakeclock.NewFakeClock(time.Now())
			agent = New(
				logger,
				handler,
				platform,
				actionDispatcher,
				jobSupervisor,
				specService,
				syslogServer,
				5*time.Millisecond,
				settingsService,
				uuidGenerator,
				timeService,
			)
		})

		Describe("Run", func() {
			It("lets dispatcher handle requests arriving via handler", func() {
				err := agent.Run()
				Expect(err).ToNot(HaveOccurred())

				expectedResp := boshhandler.NewValueResponse("pong")
				actionDispatcher.DispatchResp = expectedResp

				req := boshhandler.NewRequest("fake-reply", "fake-action", []byte("fake-payload"))
				resp := handler.RunFunc(req)

				Expect(actionDispatcher.DispatchReq).To(Equal(req))
				Expect(resp).To(Equal(expectedResp))
			})

			It("resumes persistent actions *before* dispatching new requests", func() {
				resumedBeforeStartingToDispatch := false
				handler.RunCallBack = func() {
					resumedBeforeStartingToDispatch = actionDispatcher.ResumedPreviouslyDispatchedTasks
				}

				err := agent.Run()
				Expect(err).ToNot(HaveOccurred())
				Expect(resumedBeforeStartingToDispatch).To(BeTrue())
			})

			Context("when heartbeats can be sent", func() {
				BeforeEach(func() {
					handler.KeepOnRunning()
				})

				BeforeEach(func() {
					jobName := "fake-job"
					nodeID := "node-id"
					jobIndex := 1
					specService.Spec = boshas.V1ApplySpec{
						JobSpec: boshas.JobSpec{Name: &jobName},
						Index:   &jobIndex,
						NodeID:  nodeID,
					}

					jobSupervisor.StatusStatus = "fake-state"

					platform.FakeVitalsService.GetVitals = boshvitals.Vitals{
						Load: []string{"a", "b", "c"},
					}
				})

				expectedJobName := "fake-job"
				expectedJobIndex := 1
				expectedNodeID := "node-id"
				expectedHb := Heartbeat{
					Job:      &expectedJobName,
					Index:    &expectedJobIndex,
					JobState: "fake-state",
					NodeID:   expectedNodeID,
					Vitals:   boshvitals.Vitals{Load: []string{"a", "b", "c"}},
				}
//.........这里部分代码省略.........
开发者ID:nimbus-cloud,项目名称:bosh-agent,代码行数:101,代码来源:agent_test.go


示例6:

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("FakeTicker", func() {
	const Δ = 10 * time.Millisecond

	var (
		fakeClock   *fakeclock.FakeClock
		initialTime time.Time
	)

	BeforeEach(func() {
		initialTime = time.Date(2014, 1, 1, 3, 0, 30, 0, time.UTC)
		fakeClock = fakeclock.NewFakeClock(initialTime)
	})

	It("provides a channel that receives the time at each interval", func() {
		ticker := fakeClock.NewTicker(10 * time.Second)
		timeChan := ticker.C()
		Consistently(timeChan, Δ).ShouldNot(Receive())

		fakeClock.Increment(5 * time.Second)
		Consistently(timeChan, Δ).ShouldNot(Receive())

		fakeClock.Increment(4 * time.Second)
		Consistently(timeChan, Δ).ShouldNot(Receive())

		fakeClock.Increment(1 * time.Second)
		Eventually(timeChan).Should(Receive(Equal(initialTime.Add(10 * time.Second))))
开发者ID:andrew-edgar,项目名称:clock,代码行数:30,代码来源:fake_ticker_test.go


示例7:

	"github.com/pivotal-golang/clock/fakeclock"
)

var _ = Describe("SSH", func() {
	Describe("SSHRetryStrategy", func() {
		var (
			sshRetryStrategy         *SSHRetryStrategy
			fakeTimeService          *fakeclock.FakeClock
			connectionRefusedTimeout time.Duration
			authFailureTimeout       time.Duration
			startTime                time.Time
		)

		BeforeEach(func() {
			startTime = time.Now()
			fakeTimeService = fakeclock.NewFakeClock(startTime)
			connectionRefusedTimeout = 10 * time.Minute
			authFailureTimeout = 5 * time.Minute

			sshRetryStrategy = &SSHRetryStrategy{
				ConnectionRefusedTimeout: connectionRefusedTimeout,
				AuthFailureTimeout:       authFailureTimeout,
				TimeService:              fakeTimeService,
			}
		})

		Describe("IsRetryable", func() {
			refusedErr := errors.New("connection refused")
			authErr := errors.New("unable to authenticate")

			Context("when err is connection refused", func() {
开发者ID:mattcui,项目名称:bosh-init,代码行数:31,代码来源:ssh_tunnel_test.go


示例8:

		fakeExitHandler         *fake_exit_handler.FakeExitHandler
		fakeGraphicalVisualizer *fake_graphical_visualizer.FakeGraphicalVisualizer
		fakeTaskExaminer        *fake_task_examiner.FakeTaskExaminer
		systemDomain            string
	)

	BeforeEach(func() {
		fakeAppExaminer = &fake_app_examiner.FakeAppExaminer{}
		fakeTaskExaminer = &fake_task_examiner.FakeTaskExaminer{}
		outputBuffer = gbytes.NewBuffer()
		terminalUI = terminal.NewUI(nil, outputBuffer, nil)
		fakeTerm = &fake_terminal.FakeTerminal{}
		osSignalChan = make(chan os.Signal, 1)
		location, err := time.LoadLocation("Africa/Djibouti")
		Expect(err).NotTo(HaveOccurred())
		fakeClock = fakeclock.NewFakeClock(time.Date(2012, time.February, 29, 6, 45, 30, 820, location))
		fakeExitHandler = &fake_exit_handler.FakeExitHandler{}
		fakeGraphicalVisualizer = &fake_graphical_visualizer.FakeGraphicalVisualizer{}
		systemDomain = "system.domain"
	})

	Describe("ListAppsCommand", func() {
		var listAppsCommand cli.Command

		BeforeEach(func() {
			commandFactory := command_factory.NewAppExaminerCommandFactory(fakeAppExaminer, terminalUI, fakeTerm, fakeClock, fakeExitHandler, nil, fakeTaskExaminer, systemDomain)
			listAppsCommand = commandFactory.MakeListAppCommand()
		})

		It("displays all the existing apps & tasks, making sure output spacing is correct", func() {
			listApps := []app_examiner.AppInfo{
开发者ID:Klaudit,项目名称:lattice,代码行数:31,代码来源:app_examiner_command_factory_test.go


示例9:

)

var _ = Describe("Metrics Server", func() {
	var (
		store             storepackage.Store
		storeAdapter      *fakestoreadapter.FakeStoreAdapter
		timeProvider      *fakeclock.FakeClock
		metricsServer     *MetricsServer
		metricsAccountant *fakemetricsaccountant.FakeMetricsAccountant
	)

	BeforeEach(func() {
		conf, _ := config.DefaultConfig()
		storeAdapter = fakestoreadapter.New()
		store = storepackage.NewStore(conf, storeAdapter, fakelogger.NewFakeLogger())
		timeProvider = fakeclock.NewFakeClock(time.Unix(100, 0))

		metricsAccountant = &fakemetricsaccountant.FakeMetricsAccountant{}

		metricsServer = New(nil, nil, metricsAccountant, fakelogger.NewFakeLogger(), store, timeProvider, conf)
	})

	Describe("message metrics", func() {
		BeforeEach(func() {
			metricsAccountant.GetMetricsReturns(map[string]float64{
				"foo": 1,
				"bar": 2,
			}, nil)
		})

		Context("when the metrics fetch succesfully", func() {
开发者ID:nagyistge,项目名称:hm9000,代码行数:31,代码来源:metricsserver_test.go


示例10:

	. "github.com/onsi/gomega"
)

var logger = lagertest.NewTestLogger("test")

var _ = Describe("Allocation Store", func() {
	var (
		allocationStore  *allocationstore.AllocationStore
		fakeClock        *fakeclock.FakeClock
		fakeEventEmitter *fakes.FakeEventEmitter
		currentTime      time.Time
	)

	BeforeEach(func() {
		currentTime = time.Now()
		fakeClock = fakeclock.NewFakeClock(currentTime)
		fakeEventEmitter = &fakes.FakeEventEmitter{}
		allocationStore = allocationstore.NewAllocationStore(fakeClock, fakeEventEmitter)
	})

	Describe("List", func() {
		Context("when a container is allocated", func() {
			var req executor.AllocationRequest

			BeforeEach(func() {
				resource := executor.NewResource(512, 512, "")
				req = executor.NewAllocationRequest("banana", &resource, nil)
				_, err := allocationStore.Allocate(logger, &req)
				Expect(err).NotTo(HaveOccurred())
			})
开发者ID:snowsnail,项目名称:executor,代码行数:30,代码来源:allocationstore_test.go


示例11:

		radar *Radar

		resourceConfig atc.ResourceConfig
		savedResource  db.SavedResource

		fakeLease *dbfakes.FakeLease

		process ifrit.Process
	)

	BeforeEach(func() {
		epoch = time.Unix(123, 456).UTC()
		fakeTracker = new(rfakes.FakeTracker)
		fakeRadarDB = new(fakes.FakeRadarDB)
		fakeClock = fakeclock.NewFakeClock(epoch)
		interval = 1 * time.Minute

		fakeRadarDB.GetPipelineNameReturns("some-pipeline")
		radar = NewRadar(fakeTracker, interval, fakeRadarDB, fakeClock)

		resourceConfig = atc.ResourceConfig{
			Name:   "some-resource",
			Type:   "git",
			Source: atc.Source{"uri": "http://example.com"},
		}

		fakeRadarDB.ScopedNameStub = func(thing string) string {
			return "pipeline:" + thing
		}
开发者ID:pcfdev-forks,项目名称:atc,代码行数:29,代码来源:radar_test.go


示例12:

		messageBus        *fakeyagnats.FakeNATSConn
		timeProvider      *fakeclock.FakeClock
		dea               appfixture.DeaFixture
		app               appfixture.AppFixture
		conf              *config.Config
		metricsAccountant *fakemetricsaccountant.FakeMetricsAccountant
	)

	BeforeEach(func() {
		messageBus = fakeyagnats.Connect()
		dea = appfixture.NewDeaFixture()
		app = dea.GetApp(0)
		conf, _ = config.DefaultConfig()
		metricsAccountant = &fakemetricsaccountant.FakeMetricsAccountant{}

		timeProvider = fakeclock.NewFakeClock(time.Unix(int64(10+conf.ActualFreshnessTTL()), 0))

		storeAdapter = fakestoreadapter.New()
		store = storepackage.NewStore(conf, storeAdapter, fakelogger.NewFakeLogger())
		sender = New(store, metricsAccountant, conf, messageBus, fakelogger.NewFakeLogger())
		store.BumpActualFreshness(time.Unix(10, 0))
		store.BumpDesiredFreshness(time.Unix(10, 0))
	})

	Context("when the sender fails to pull messages out of the start queue", func() {
		BeforeEach(func() {
			storeAdapter.ListErrInjector = fakestoreadapter.NewFakeStoreAdapterErrorInjector("start", errors.New("oops"))
		})

		It("should return an error and not send any messages", func() {
			err := sender.Send(timeProvider)
开发者ID:nagyistge,项目名称:hm9000,代码行数:31,代码来源:sender_test.go


示例13:

		domain                        string = "192.168.11.11.xip.io"
		fakeClock                     *fakeclock.FakeClock
		fakeDockerMetadataFetcher     *fake_docker_metadata_fetcher.FakeDockerMetadataFetcher
		appRunnerCommandFactoryConfig command_factory.DockerRunnerCommandFactoryConfig
		logger                        lager.Logger
		fakeTailedLogsOutputter       *fake_tailed_logs_outputter.FakeTailedLogsOutputter
		fakeExitHandler               *fake_exit_handler.FakeExitHandler
	)

	BeforeEach(func() {
		fakeAppRunner = &fake_app_runner.FakeAppRunner{}
		fakeAppExaminer = &fake_app_examiner.FakeAppExaminer{}
		outputBuffer = gbytes.NewBuffer()
		terminalUI = terminal.NewUI(nil, outputBuffer, nil)
		fakeDockerMetadataFetcher = &fake_docker_metadata_fetcher.FakeDockerMetadataFetcher{}
		fakeClock = fakeclock.NewFakeClock(time.Now())
		logger = lager.NewLogger("ltc-test")
		fakeTailedLogsOutputter = fake_tailed_logs_outputter.NewFakeTailedLogsOutputter()
		fakeExitHandler = &fake_exit_handler.FakeExitHandler{}
	})

	Describe("CreateAppCommand", func() {
		var createCommand cli.Command

		BeforeEach(func() {
			env := []string{"SHELL=/bin/bash", "COLOR=Blue"}
			appRunnerCommandFactoryConfig = command_factory.DockerRunnerCommandFactoryConfig{
				AppRunner:   fakeAppRunner,
				AppExaminer: fakeAppExaminer,
				UI:          terminalUI,
				DockerMetadataFetcher: fakeDockerMetadataFetcher,
开发者ID:rowhit,项目名称:lattice,代码行数:31,代码来源:docker_runner_command_factory_test.go


示例14:

	var (
		analyzer     *Analyzer
		storeAdapter *fakestoreadapter.FakeStoreAdapter
		store        storepackage.Store
		clock        *fakeclock.FakeClock
		dea          appfixture.DeaFixture
		app          appfixture.AppFixture
	)

	conf, _ := config.DefaultConfig()

	BeforeEach(func() {
		storeAdapter = fakestoreadapter.New()
		store = storepackage.NewStore(conf, storeAdapter, fakelogger.NewFakeLogger())

		clock = fakeclock.NewFakeClock(time.Unix(1000, 0))

		dea = appfixture.NewDeaFixture()
		app = dea.GetApp(0)

		store.BumpActualFreshness(time.Unix(100, 0))
		store.BumpDesiredFreshness(time.Unix(100, 0))

		analyzer = New(store, clock, fakelogger.NewFakeLogger(), conf)
	})

	startMessages := func() []models.PendingStartMessage {
		messages, _ := store.GetPendingStartMessages()
		messagesArr := []models.PendingStartMessage{}
		for _, message := range messages {
			messagesArr = append(messagesArr, message)
开发者ID:nagyistge,项目名称:hm9000,代码行数:31,代码来源:analyzer_test.go


示例15: TestDB

var consulHelper *test_helpers.ConsulHelper

var serviceClient bbs.ServiceClient
var etcdDB db.DB
var etcdDBWithFakeStore db.DB
var workPoolCreateError error

var cryptor encryption.Cryptor

func TestDB(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "ETCD DB Suite")
}

var _ = BeforeSuite(func() {
	clock = fakeclock.NewFakeClock(time.Unix(0, 1138))

	etcdPort = 4001 + GinkgoParallelNode()
	etcdUrl = fmt.Sprintf("http://127.0.0.1:%d", etcdPort)
	etcdRunner = etcdstorerunner.NewETCDClusterRunner(etcdPort, 1, nil)

	consulRunner = consulrunner.NewClusterRunner(
		9001+config.GinkgoConfig.ParallelNode*consulrunner.PortOffsetLength,
		1,
		"http",
	)

	consulRunner.Start()
	consulRunner.WaitUntilReady()

	etcdRunner.Start()
开发者ID:emc-xchallenge,项目名称:bbs,代码行数:31,代码来源:etcd_suite_test.go


示例16:

		handler    http.Handler
		response   *httptest.ResponseRecorder
		request    *http.Request
		noaaClient *fakes.FakeNoaaClient
		bbsClient  *fake_bbs.FakeClient
		logger     *lagertest.TestLogger
		fakeClock  *fakeclock.FakeClock
	)

	BeforeEach(func() {
		var err error

		bbsClient = new(fake_bbs.FakeClient)
		noaaClient = &fakes.FakeNoaaClient{}
		logger = lagertest.NewTestLogger("test")
		fakeClock = fakeclock.NewFakeClock(time.Date(2008, 8, 8, 8, 8, 8, 8, time.UTC))
		handler = lrpstats.NewHandler(bbsClient, noaaClient, fakeClock, logger)
		response = httptest.NewRecorder()
		request, err = http.NewRequest("GET", "/v1/actual_lrps/:guid/stats", nil)
		Expect(err).NotTo(HaveOccurred())
	})

	JustBeforeEach(func() {
		handler.ServeHTTP(response, request)
	})

	Describe("Validation", func() {
		It("fails with a missing authorization header", func() {
			Expect(response.Code).To(Equal(http.StatusUnauthorized))
		})
开发者ID:emc-xchallenge,项目名称:tps,代码行数:30,代码来源:lrpstats_test.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang fakeclock.FakeClock类代码示例发布时间:2022-05-28
下一篇:
Golang clock.Clock类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap