func defaultConf() HandlerConf { return HandlerConf{ StoreAdapter: fakestoreadapter.New(), Clock: fakeclock.NewFakeClock(time.Unix(100, 0)), Logger: fakelogger.NewFakeLogger(), } }
// NewInitNode creates a new raft node initiating the cluster // for other members to join func NewInitNode(t *testing.T, tc *cautils.TestCA, raftConfig *api.RaftConfig, opts ...raft.NewNodeOptions) (*TestNode, *fakeclock.FakeClock) { ctx := context.Background() clockSource := fakeclock.NewFakeClock(time.Now()) n := NewNode(t, clockSource, tc, opts...) err := n.Node.JoinAndStart() require.NoError(t, err, "can't join cluster") leadershipCh, cancel := n.SubscribeLeadership() defer cancel() go n.Run(ctx) // Wait for the node to become the leader. <-leadershipCh if raftConfig != nil { assert.NoError(t, n.MemoryStore().Update(func(tx store.Tx) error { return store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ Annotations: api.Annotations{ Name: store.DefaultClusterName, }, Raft: *raftConfig, }, }) })) } return n, clockSource }
. "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"), },
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)
. "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())
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"}}, } It("sends initial heartbeat", func() { // Configure periodic heartbeat every 5 hours // so that we are sure that we will not receive it agent = New( logger, handler, platform, actionDispatcher, jobSupervisor, specService, syslogServer, 5*time.Hour, settingsService, uuidGenerator, timeService, ) // Immediately exit after sending initial heartbeat handler.SendErr = errors.New("stop") err := agent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) Expect(handler.SendInputs()).To(Equal([]fakembus.SendInput{ { Target: boshhandler.HealthMonitor, Topic: boshhandler.Heartbeat, Message: expectedHb, }, })) }) It("sends periodic heartbeats", func() { sentRequests := 0 handler.SendCallback = func(_ fakembus.SendInput) { sentRequests++ if sentRequests == 3 { handler.SendErr = errors.New("stop") } } err := agent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) Expect(handler.SendInputs()).To(Equal([]fakembus.SendInput{ { Target: boshhandler.HealthMonitor, Topic: boshhandler.Heartbeat, Message: expectedHb, }, { Target: boshhandler.HealthMonitor, Topic: boshhandler.Heartbeat, Message: expectedHb, }, { Target: boshhandler.HealthMonitor, Topic: boshhandler.Heartbeat, Message: expectedHb, }, })) }) }) Context("when the agent fails to get job spec for a heartbeat", func() { BeforeEach(func() { specService.GetErr = errors.New("fake-spec-service-error") handler.KeepOnRunning() }) It("returns the error", func() { err := agent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-spec-service-error")) }) }) Context("when the agent fails to get vitals for a heartbeat", func() { BeforeEach(func() { platform.FakeVitalsService.GetErr = errors.New("fake-vitals-service-error") handler.KeepOnRunning() }) It("returns the error", func() { err := agent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-vitals-service-error")) }) }) It("sends job monitoring alerts to health manager", func() { handler.KeepOnRunning() monitAlert := boshalert.MonitAlert{ ID: "fake-monit-alert", Service: "fake-service", Event: "fake-event", Action: "fake-action", Date: "Sun, 22 May 2011 20:07:41 +0500", Description: "fake-description", } jobSupervisor.JobFailureAlert = &monitAlert // Fail the first time handler.Send is called for an alert (ignore heartbeats) handler.SendCallback = func(input fakembus.SendInput) { if input.Topic == boshhandler.Alert { handler.SendErr = errors.New("stop") } } err := agent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) expectedAlert := boshalert.Alert{ ID: "fake-monit-alert", Severity: boshalert.SeverityDefault, Title: "fake-service - fake-event - fake-action", Summary: "fake-description", CreatedAt: int64(1306076861), } Expect(handler.SendInputs()).To(ContainElement(fakembus.SendInput{ Target: boshhandler.HealthMonitor, Topic: boshhandler.Alert, Message: expectedAlert, })) }) It("sends ssh alerts to health manager", func() { handler.KeepOnRunning() syslogMsg := boshsyslog.Msg{Content: "disconnected by user"} syslogServer.StartFirstSyslogMsg = &syslogMsg uuidGenerator.GeneratedUUID = "fake-uuid" // Fail the first time handler.Send is called for an alert (ignore heartbeats) handler.SendCallback = func(input fakembus.SendInput) { if input.Topic == boshhandler.Alert { handler.SendErr = errors.New("stop") } } err := agent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) expectedAlert := boshalert.Alert{ ID: "fake-uuid", Severity: boshalert.SeverityWarning, Title: "SSH Logout", Summary: "disconnected by user", CreatedAt: timeService.Now().Unix(), } Expect(handler.SendInputs()).To(ContainElement(fakembus.SendInput{ Target: boshhandler.HealthMonitor, Topic: boshhandler.Alert, Message: expectedAlert, })) }) }) }) }
. "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))))
"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() {
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{
) 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() {
. "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()) })
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 }
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)
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,
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)
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()
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)) })