Example #1
0
// AdvanceTicks advances the raft state machine fake clock
func AdvanceTicks(clockSource *fakeclock.FakeClock, ticks int) {
	// A FakeClock timer won't fire multiple times if time is advanced
	// more than its interval.
	for i := 0; i != ticks; i++ {
		clockSource.Increment(time.Second)
	}
}
func incrementSleepInBackground(fakeTimeService *fakeclock.FakeClock, delay time.Duration) chan struct{} {
	doneChan := make(chan struct{})
	go func() {
		for {
			select {
			case <-doneChan:
				return
			default:
				if fakeTimeService.WatcherCount() > 0 {
					fakeTimeService.Increment(delay)
				}
			}
		}
	}()
	return doneChan
}
Example #3
0
// PollFuncWithTimeout is used to periodically execute a check function, it
// returns error after timeout.
func PollFuncWithTimeout(clockSource *fakeclock.FakeClock, f func() error, timeout time.Duration) error {
	if f() == nil {
		return nil
	}
	timer := time.After(timeout)
	for i := 0; ; i++ {
		if i%5 == 0 && clockSource != nil {
			clockSource.Increment(time.Second)
		}
		err := f()
		if err == nil {
			return nil
		}
		select {
		case <-timer:
			return fmt.Errorf("polling failed: %v", err)
		case <-time.After(50 * time.Millisecond):
		}
	}
}
Example #4
0
// PollFuncWithTimeout is used to periodically execute a check function, it
// returns error after timeout.
func PollFuncWithTimeout(clockSource *fakeclock.FakeClock, f func() error, timeout time.Duration) error {
	if f() == nil {
		return nil
	}
	timer := time.NewTimer(timeout)
	defer timer.Stop()
	for i := 0; ; i++ {
		if i%5 == 0 && clockSource != nil {
			clockSource.Increment(time.Second)
		}
		err := f()
		if err == nil {
			return nil
		}
		select {
		case <-timer.C:
			return errors.Wrap(err, "polling failed")
		case <-time.After(50 * time.Millisecond):
		}
	}
}
Example #5
0
package fakeclock_test

import (
	"time"

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

	. "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())
	"github.com/pivotal-golang/clock/fakeclock"

	"github.com/cloudfoundry-incubator/converger/converger_process"
)

const aBit = 100 * time.Millisecond

var _ = Describe("ConvergerProcess", func() {
	var (
		fakeBBSServiceClient        *fake_bbs.FakeServiceClient
		fakeBBSClient               *fake_bbs.FakeClient
		logger                      *lagertest.TestLogger
		fakeClock                   *fakeclock.FakeClock
		convergeRepeatInterval      time.Duration
		kickTaskDuration            time.Duration
		expirePendingTaskDuration   time.Duration
		expireCompletedTaskDuration time.Duration

		process ifrit.Process

		waitEvents chan<- models.CellEvent
		waitErrs   chan<- error
	)

	BeforeEach(func() {
		fakeBBSServiceClient = new(fake_bbs.FakeServiceClient)
		fakeBBSClient = new(fake_bbs.FakeClient)
		logger = lagertest.NewTestLogger("test")
		fakeClock = fakeclock.NewFakeClock(time.Now())

		convergeRepeatInterval = 1 * time.Second
	"os"
	"time"

	"code.cloudfoundry.org/guardian/rundmc/dadoo"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-golang/clock/fakeclock"
)

var _ = Describe("PidFileReader", func() {

	var (
		clk     *fakeclock.FakeClock
		timeout time.Duration

		pdr *dadoo.PidFileReader

		pidFileContents string
		pidFilePath     string
	)

	BeforeEach(func() {
		clk = fakeclock.NewFakeClock(time.Now())
		timeout = time.Millisecond * 60

		pidFileContents = "5621"
	})

	JustBeforeEach(func() {
		pdr = &dadoo.PidFileReader{
			Clock:         clk,
Example #8
0
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
)

var _ = Describe("MonitorStep", func() {
	var (
		fakeStep1 *fakes.FakeStep
		fakeStep2 *fakes.FakeStep

		checkSteps chan *fakes.FakeStep

		checkFunc        func() steps.Step
		hasBecomeHealthy <-chan struct{}
		clock            *fakeclock.FakeClock
		fakeStreamer     *fake_log_streamer.FakeLogStreamer

		startTimeout      time.Duration
		healthyInterval   time.Duration
		unhealthyInterval time.Duration

		step   steps.Step
		logger *lagertest.TestLogger
	)

	const numOfConcurrentMonitorSteps = 3

	BeforeEach(func() {
		startTimeout = 0
		healthyInterval = 1 * time.Second
		unhealthyInterval = 500 * time.Millisecond
Example #9
0
)

var _ = Describe("Watcher", func() {
	const (
		expectedProcessGuid  = "some-process-guid"
		expectedInstanceGuid = "some-instance-guid"
		retryWaitDuration    = 50 * time.Millisecond
	)

	var (
		bbs             *fake_bbs.FakeReceptorBBS
		hub             *eventfakes.FakeHub
		clock           *fakeclock.FakeClock
		receptorWatcher watcher.Watcher
		process         ifrit.Process

		desiredLRPStop   chan bool
		desiredLRPErrors chan error

		actualLRPStop   chan bool
		actualLRPErrors chan error
	)

	BeforeEach(func() {
		bbs = new(fake_bbs.FakeReceptorBBS)
		hub = new(eventfakes.FakeHub)
		clock = fakeclock.NewFakeClock(time.Now())
		logger := lagertest.NewTestLogger("test")

		desiredLRPStop = make(chan bool, 1)
		desiredLRPErrors = make(chan error)
	"github.com/tedsuo/ifrit"

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

// a bit of grace time for eventuallys
const aBit = 50 * time.Millisecond

var _ = Describe("PeriodicMetronNotifier", func() {
	var (
		sender *fake.FakeMetricSender

		etcdOptions    etcd.ETCDOptions
		reportInterval time.Duration
		fakeClock      *fakeclock.FakeClock

		pmn ifrit.Process
	)

	BeforeEach(func() {
		reportInterval = 100 * time.Millisecond

		fakeClock = fakeclock.NewFakeClock(time.Unix(123, 456))

		sender = fake.NewFakeMetricSender()
		dropsonde_metrics.Initialize(sender, nil)
	})

	JustBeforeEach(func() {
	boshalert "github.com/cloudfoundry/bosh-agent/agent/alert"
	. "github.com/cloudfoundry/bosh-agent/jobsupervisor"
	boshmonit "github.com/cloudfoundry/bosh-agent/jobsupervisor/monit"
	fakemonit "github.com/cloudfoundry/bosh-agent/jobsupervisor/monit/fakes"
	boshdir "github.com/cloudfoundry/bosh-agent/settings/directories"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"
	fakesys "github.com/cloudfoundry/bosh-utils/system/fakes"
)

var _ = Describe("monitJobSupervisor", func() {
	var (
		fs                    *fakesys.FakeFileSystem
		runner                *fakesys.FakeCmdRunner
		client                *fakemonit.FakeMonitClient
		logger                boshlog.Logger
		dirProvider           boshdir.Provider
		jobFailuresServerPort int
		monit                 JobSupervisor
		timeService           *fakeclock.FakeClock
	)

	var jobFailureServerPort = 5000

	getJobFailureServerPort := func() int {
		jobFailureServerPort++
		return jobFailureServerPort
	}

	BeforeEach(func() {
		fs = fakesys.NewFakeFileSystem()
		runner = fakesys.NewFakeCmdRunner()
Example #12
0
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"

	"github.com/concourse/atc"
	"github.com/concourse/atc/db"
	"github.com/concourse/atc/worker"
	"github.com/concourse/atc/worker/fakes"
)

var _ = Describe("Hardcoded", func() {
	var (
		logger           lager.Logger
		workerDB         *fakes.FakeSaveWorkerDB
		gardenAddr       string
		baggageClaimAddr string
		resourceTypes    []atc.WorkerResourceType
		fakeClock        *fakeclock.FakeClock

		process ifrit.Process
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("hardcoded-worker")
		workerDB = &fakes.FakeSaveWorkerDB{}
		gardenAddr = "http://garden.example.com"
		baggageClaimAddr = "http://volumes.example.com"
		resourceTypes = []atc.WorkerResourceType{
			{
				Type:  "type",
				Image: "image",
			},
Example #13
0
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/concourse/atc/worker"
	"github.com/concourse/atc/worker/fakes"
	"github.com/concourse/baggageclaim"
	bfakes "github.com/concourse/baggageclaim/fakes"
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager/lagertest"
)

var _ = Describe("Volumes", func() {
	var (
		volumeFactory worker.VolumeFactory
		fakeVolume    *bfakes.FakeVolume
		fakeDB        *fakes.FakeVolumeFactoryDB
		fakeClock     *fakeclock.FakeClock
		logger        *lagertest.TestLogger
	)

	BeforeEach(func() {
		fakeVolume = new(bfakes.FakeVolume)
		fakeDB = new(fakes.FakeVolumeFactoryDB)
		fakeClock = fakeclock.NewFakeClock(time.Unix(123, 456))
		logger = lagertest.NewTestLogger("test")

		volumeFactory = worker.NewVolumeFactory(fakeDB, fakeClock)
	})

	Context("VolumeFactory", func() {
		Describe("Build", func() {
Example #14
0
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager"

	"github.com/cloudfoundry-incubator/auction/auctionrunner"
	"github.com/cloudfoundry-incubator/auction/auctiontypes"
	"github.com/cloudfoundry-incubator/rep"
	"github.com/cloudfoundry-incubator/rep/repfakes"

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

var _ = Describe("Scheduler", func() {
	var clients map[string]*repfakes.FakeSimClient
	var zones map[string]auctionrunner.Zone
	var clock *fakeclock.FakeClock
	var workPool *workpool.WorkPool
	var results auctiontypes.AuctionResults
	var logger lager.Logger

	BeforeEach(func() {
		clock = fakeclock.NewFakeClock(time.Now())

		var err error
		workPool, err = workpool.NewWorkPool(5)
		Expect(err).NotTo(HaveOccurred())

		clients = map[string]*repfakes.FakeSimClient{}
		zones = map[string]auctionrunner.Zone{}

		logger = lager.NewLogger("fakelogger")
Example #15
0
			}
		})

		It("should call the callback 12 times", func() {
			Expect(ret.Retry(callback)).NotTo(Succeed())
			Expect(callbackCount).To(Equal(12))
		})

		It("should return the error", func() {
			Expect(ret.Retry(callback)).To(MatchError("banana"))
		})
	})

	Context("when the callback succeeds after a while", func() {
		var (
			fakeClk *fakeclock.FakeClock
			called  chan bool
		)

		BeforeEach(func() {
			fakeClk = fakeclock.NewFakeClock(time.Now())
			clk = fakeClk
			called = make(chan bool, 12)

			callback = func() error {
				called <- true

				callbackCount++
				if callbackCount == 6 {
					return nil
				}
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager"

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

var _ = Describe("StagingCompletedHandler", func() {
	var (
		logger lager.Logger
		appId  string
		taskId string

		fakeCCClient        *fakes.FakeCcClient
		fakeBackend         *fake_backend.FakeBackend
		backendResponse     cc_messages.StagingResponseForCC
		backendError        error
		fakeClock           *fakeclock.FakeClock
		metricSender        *fake.FakeMetricSender
		stagingDurationNano time.Duration

		responseRecorder *httptest.ResponseRecorder
		handler          handlers.CompletionHandler
	)

	BeforeEach(func() {
		logger = lager.NewLogger("fakelogger")
		logger.RegisterSink(lager.NewWriterSink(GinkgoWriter, lager.DEBUG))

		appId = "my_app_id"
		taskId = "do_this"
Example #17
0
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,
				}))
			})
		})
	})
}
Example #18
0
)

func buildMonitAlert() MonitAlert {
	return MonitAlert{
		ID:          "some-random-id",
		Service:     "nats",
		Event:       "does not exist",
		Action:      "restart",
		Date:        "Sun, 22 May 2011 20:07:41 +0500",
		Description: "process is not running",
	}
}

var _ = Describe("monitAdapter", func() {
	var (
		settingsService *fakesettings.FakeSettingsService
		timeService     *fakeclock.FakeClock
	)

	BeforeEach(func() {
		settingsService = &fakesettings.FakeSettingsService{}
		timeService = fakeclock.NewFakeClock(time.Now())
	})

	Describe("IsIgnorable", func() {
		itIgnores := func(event string) {
			monitAlert := buildMonitAlert()
			monitAlert.Event = event

			monitAdapter := NewMonitAdapter(monitAlert, settingsService, timeService)
			Expect(monitAdapter.IsIgnorable()).To(BeTrue())
		}
Example #19
0
import (
	"os"
	"time"

	. "github.com/concourse/atc/pipelines"
	"github.com/concourse/atc/pipelines/fakes"
	. "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() {
Example #20
0
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"
	"github.com/pivotal-golang/operationq"
	"github.com/pivotal-golang/operationq/fake_operationq"
	"github.com/tedsuo/ifrit"
)

var _ = Describe("Bulker", func() {
	var (
		sender *fake.FakeMetricSender

		logger                 *lagertest.TestLogger
		pollInterval           time.Duration
		evacuationPollInterval time.Duration
		fakeClock              *fakeclock.FakeClock
		fakeGenerator          *fake_generator.FakeGenerator
		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
func advanceTime(timeService *fakeclock.FakeClock, duration time.Duration, watcherCount int) {
	Eventually(timeService.WatcherCount).Should(Equal(watcherCount))
	timeService.Increment(duration)
}
import (
	"errors"
	"time"

	. "github.com/onsi/ginkgo"
	. "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"),
					},
package fakeclock_test

import (
	"time"

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

var _ = Describe("FakeClock", func() {
	const Δ time.Duration = 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)
	})

	Describe("Now", func() {
		It("returns the current time, w/o race conditions", func() {
			go fakeClock.Increment(time.Minute)
			Eventually(fakeClock.Now).Should(Equal(initialTime.Add(time.Minute)))
		})
	})

	Describe("Sleep", func() {
Example #24
0
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/ginkgomon"

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

var _ = Describe("Maintain Presence", func() {
	var (
		config          maintain.Config
		fakeHeartbeater *maintain_fakes.FakeRunner
		fakeClient      *fake_client.FakeClient
		serviceClient   *fake_bbs.FakeServiceClient
		logger          *lagertest.TestLogger

		maintainer        ifrit.Runner
		maintainProcess   ifrit.Process
		heartbeaterErrors chan error
		observedSignals   chan os.Signal
		clock             *fakeclock.FakeClock
		pingErrors        chan error
	)

	BeforeEach(func() {
		pingErrors = make(chan error, 1)
		fakeClient = &fake_client.FakeClient{
			PingStub: func() error {
				return <-pingErrors
			},
		}
		resources := executor.ExecutorResources{MemoryMB: 128, DiskMB: 1024, Containers: 6}
Example #25
0
func init() {
	sender = metrics_fakes.NewFakeMetricSender()
	metrics.Initialize(sender, nil)
}

var _ = Describe("RouteFetcher", func() {
	var (
		cfg       *config.Config
		uaaClient *testUaaClient.FakeClient
		registry  *testRegistry.FakeRegistryInterface
		fetcher   *RouteFetcher
		logger    lager.Logger
		client    *fake_routing_api.FakeClient

		token *schema.Token

		response     []db.Route
		process      ifrit.Process
		eventChannel chan routing_api.Event
		errorChannel chan error

		clock *fakeclock.FakeClock
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		cfg = config.DefaultConfig()
		cfg.PruneStaleDropletsInterval = 2 * time.Second

		retryInterval := 0
Example #26
0
	. "github.com/onsi/gomega"

	"bytes"
	"time"

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

var _ = Describe("Stage", func() {
	var (
		logOutBuffer, logErrBuffer *bytes.Buffer
		logger                     boshlog.Logger

		stage           Stage
		ui              UI
		fakeTimeService *fakeclock.FakeClock

		uiOut, uiErr *bytes.Buffer
	)

	BeforeEach(func() {
		uiOut = bytes.NewBufferString("")
		uiErr = bytes.NewBufferString("")

		logOutBuffer = bytes.NewBufferString("")
		logErrBuffer = bytes.NewBufferString("")
		logger = boshlog.NewWriterLogger(boshlog.LevelDebug, logOutBuffer, logErrBuffer)

		ui = NewWriterUI(uiOut, uiErr, logger)
		fakeTimeService = fakeclock.NewFakeClock(time.Now())
	"github.com/cloudfoundry-incubator/lattice/ltc/terminal/cursor"
	"github.com/cloudfoundry-incubator/lattice/ltc/test_helpers"
	"github.com/codegangsta/cli"
	"github.com/pivotal-golang/clock/fakeclock"
)

const TerminalEsc = "\033["

var _ = Describe("CommandFactory", func() {

	var (
		fakeAppExaminer         *fake_app_examiner.FakeAppExaminer
		outputBuffer            *gbytes.Buffer
		terminalUI              terminal.UI
		fakeTerm                *fake_terminal.FakeTerminal
		fakeClock               *fakeclock.FakeClock
		osSignalChan            chan os.Signal
		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())
Example #28
0
	"errors"
	"time"

	"github.com/cloudfoundry/hm9000/config"
	"github.com/cloudfoundry/hm9000/models"
	storepackage "github.com/cloudfoundry/hm9000/store"
	"github.com/cloudfoundry/hm9000/testhelpers/appfixture"
	"github.com/cloudfoundry/hm9000/testhelpers/fakelogger"
	"github.com/cloudfoundry/storeadapter/fakestoreadapter"
)

var _ = Describe("Analyzer", func() {
	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)
	"github.com/cloudfoundry-incubator/runtime-schema/models"
	"github.com/codegangsta/cli"
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager"

	app_runner_command_factory "github.com/cloudfoundry-incubator/lattice/ltc/app_runner/command_factory"
)

var _ = Describe("CommandFactory", func() {
	var (
		fakeAppRunner                 *fake_app_runner.FakeAppRunner
		fakeAppExaminer               *fake_app_examiner.FakeAppExaminer
		outputBuffer                  *gbytes.Buffer
		terminalUI                    terminal.UI
		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")
	"github.com/cloudfoundry-incubator/executor/depot/allocationstore/fakes"
	"github.com/pivotal-golang/clock/fakeclock"
	"github.com/pivotal-golang/lager/lagertest"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/ginkgomon"

	. "github.com/onsi/ginkgo"
	. "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() {