コード例 #1
0
ファイル: etcd_helper.go プロジェクト: cfibmers/bbs
func NewETCDHelper(serializationFormat *format.Format, cryptor encryption.Cryptor, client etcd.StoreClient, clock clock.Clock) *ETCDHelper {
	logger := lagertest.NewTestLogger("etcd-helper")

	return &ETCDHelper{
		client:     client,
		format:     serializationFormat,
		serializer: format.NewSerializer(cryptor),
		logger:     logger,
		clock:      clock,
	}
}
コード例 #2
0
ファイル: runner.go プロジェクト: cloudfoundry/guardian
func Start(bin, initBin, nstarBin, dadooBin, grootfsBin, rootfs, tarBin string, argv ...string) *RunningGarden {
	runner := NewGardenRunner(bin, initBin, nstarBin, dadooBin, grootfsBin, rootfs, tarBin, "unix", fmt.Sprintf("/tmp/garden_%d.sock", GinkgoParallelNode()), argv...)

	r := &RunningGarden{
		runner:   runner,
		DepotDir: runner.DepotDir,

		DataDir:   DataDir,
		GraphPath: runner.GraphPath,
		Tmpdir:    runner.TmpDir,
		logger:    lagertest.NewTestLogger("garden-runner"),

		debugIP:   runner.DebugIp,
		debugPort: runner.DebugPort,

		Client: client.New(connection.New(runner.Network, runner.Addr)),
	}

	r.process = ifrit.Invoke(r.runner)
	r.Pid = runner.Cmd.Process.Pid

	return r
}
コード例 #3
0
	BeforeEach(func() {
		fakeSpecParser = new(fakes.FakeSpecParser)
		fakeSubnetPool = new(fake_subnet_pool.FakePool)
		fakeConfigCreator = new(fakes.FakeConfigCreator)
		fakeConfigStore = new(fakes.FakeConfigStore)
		fakePortForwarder = new(fakes.FakePortForwarder)
		fakePortPool = new(fakes.FakePortPool)
		fakeFirewallOpener = new(fakes.FakeFirewallOpener)
		fakeConfigurer = new(fakes.FakeConfigurer)

		containerSpec = garden.ContainerSpec{
			Handle:  "some-handle",
			Network: "1.2.3.4/30",
		}

		logger = lagertest.NewTestLogger("test")
		networker = kawasaki.New(
			fakeSpecParser,
			fakeSubnetPool,
			fakeConfigCreator,
			fakeConfigStore,
			fakeConfigurer,
			fakePortPool,
			fakePortForwarder,
			fakeFirewallOpener,
		)

		ip, subnet, err := net.ParseCIDR("123.123.123.12/24")
		Expect(err).NotTo(HaveOccurred())
		networkConfig = kawasaki.NetworkConfig{
			HostIntf:        "banana-iface",
コード例 #4
0
		mountDir               string
		backingFile            *os.File
		logger                 lager.Logger
	)

	Describe("DiffSize", func() {
		const quotaMB = 10

		BeforeEach(func() {
			fakeAUFSDiffPathFinder = new(fakes.FakeAUFSDiffPathFinder)

			diffSizer = &quota_manager.AUFSDiffSizer{
				fakeAUFSDiffPathFinder,
			}

			logger = lagertest.NewTestLogger("AUFSQuotaManager-test")

			var err error
			mountDir, err = ioutil.TempDir("", "quota_manager_test")
			Expect(err).NotTo(HaveOccurred())

			backingFile, err = ioutil.TempFile("", "quota_manager_backing_store")
			Expect(err).NotTo(HaveOccurred())

			cmd := exec.Command("truncate", "-s", fmt.Sprintf("%dM", quotaMB), backingFile.Name())
			cmd.Stdout = GinkgoWriter
			cmd.Stderr = GinkgoWriter
			Expect(cmd.Run()).To(Succeed())

			cmd = exec.Command("mkfs.ext4", "-F", backingFile.Name())
			cmd.Stdout = GinkgoWriter
コード例 #5
0
ファイル: headers_test.go プロジェクト: cloudfoundry/gorouter
	"github.com/onsi/gomega/gbytes"
)

const uuid_regex = `^[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}$`

// 64-bit random hexadecimal string
const b3_id_regex = `^[[:xdigit:]]{16}$`

var _ = Describe("Headers", func() {
	Describe("SetVcapRequestIdHeader", func() {
		var (
			logger lager.Logger
			req    *http.Request
		)
		BeforeEach(func() {
			logger = lagertest.NewTestLogger("headers-test")
			var err error
			req, err = http.NewRequest("GET", "test.endpoint", nil)
			Expect(err).ToNot(HaveOccurred())
		})
		JustBeforeEach(func() {
			commonhttp.SetVcapRequestIdHeader(req, logger)
		})

		Context("when X-Vcap-Request-Id is not set", func() {
			It("sets the X-Vcap-Request-Id header", func() {
				reqID := req.Header.Get(commonhttp.VcapRequestIdHeader)
				Expect(reqID).ToNot(BeEmpty())
				Expect(reqID).To(MatchRegexp(uuid_regex))
			})
コード例 #6
0
		natsClient   *nats.Conn
		startMsgChan chan struct{}

		logger lager.Logger
	)

	BeforeEach(func() {
		natsPort = test_util.NextAvailPort()

		natsRunner = test_util.NewNATSRunner(int(natsPort))
		natsRunner.Start()
		natsClient = natsRunner.MessageBus

		registry = new(fakes.FakeRegistryInterface)

		logger = lagertest.NewTestLogger("mbus-test")

		startMsgChan = make(chan struct{})

		subOpts = &mbus.SubscriberOpts{
			ID: "Fake-Subscriber-ID",
			MinimumRegisterIntervalInSeconds: 60,
			PruneThresholdInSeconds:          120,
		}

		sub = mbus.NewSubscriber(logger, natsClient, registry, startMsgChan, subOpts)
	})

	AfterEach(func() {
		if natsRunner != nil {
			natsRunner.Stop()
コード例 #7
0
	"code.cloudfoundry.org/voldriver"
	"code.cloudfoundry.org/volman/vollocal"
	"code.cloudfoundry.org/volman/volmanfakes"

	"code.cloudfoundry.org/clock/fakeclock"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"code.cloudfoundry.org/voldriver/voldriverfakes"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/ginkgomon"
)

var _ = Describe("Volman", func() {
	var (
		logger = lagertest.NewTestLogger("client-test")

		fakeDriverFactory *volmanfakes.FakeDriverFactory
		fakeDriver        *voldriverfakes.FakeDriver
		fakeClock         *fakeclock.FakeClock

		scanInterval time.Duration

		driverRegistry vollocal.DriverRegistry
		driverSyncer   vollocal.DriverSyncer

		process ifrit.Process
	)

	BeforeEach(func() {
		fakeDriverFactory = new(volmanfakes.FakeDriverFactory)
コード例 #8
0
			pollErrChan chan error

			pollURL                *url.URL
			originalUploadResponse *http.Response
			closeChan              chan struct{}
		)

		BeforeEach(func() {
			closeChan = make(chan struct{})
		})

		JustBeforeEach(func() {
			httpClient := &http.Client{
				Transport: transport,
			}
			u = ccclient.NewPoller(lagertest.NewTestLogger("test"), httpClient, 10*time.Millisecond)
			pollErrChan = make(chan error, 1)
			go func(pec chan error) {
				defer GinkgoRecover()
				pec <- u.Poll(pollURL, originalUploadResponse, closeChan)
			}(pollErrChan)
		})

		Context("when the initial response is invalid", func() {
			BeforeEach(func() {
				originalUploadResponse = responseWithBody("garbage")
			})

			It("returns an error", func() {
				Eventually(pollErrChan).Should(Receive(HaveOccurred()))
			})
コード例 #9
0
ファイル: aufs_test.go プロジェクト: cloudfoundry/garden-shed
		fakeBackingStoreMgr = new(fakes.FakeBackingStoreMgr)
		fakeRetrier = new(fakes.FakeRetrier)
		fakeUnmount = func(path string) error {
			return nil
		}
	})

	JustBeforeEach(func() {
		driver = &aufs.QuotaedDriver{
			GraphDriver:     fakeGraphDriver,
			Unmount:         fakeUnmount,
			BackingStoreMgr: fakeBackingStoreMgr,
			LoopMounter:     fakeLoopMounter,
			Retrier:         fakeRetrier,
			RootPath:        rootPath,
			Logger:          lagertest.NewTestLogger("test"),
		}
	})

	Describe("GetQuotaed", func() {
		It("should create a backing store file", func() {
			id := "banana-id"
			quota := int64(12 * 1024)

			_, err := driver.GetQuotaed(id, "", quota)
			Expect(err).NotTo(HaveOccurred())

			Expect(fakeBackingStoreMgr.CreateCallCount()).To(Equal(1))
			gottenId, gottenQuota := fakeBackingStoreMgr.CreateArgsForCall(0)
			Expect(gottenId).To(Equal(id))
			Expect(gottenQuota).To(Equal(quota))
コード例 #10
0
			return nil
		}

		namespacer = &rootfs_provider.UidNamespacer{
			Translator: translator,
		}
	})

	It("returns a cache key describing the namespacer", func() {
		translator.CacheKeyReturns("namespaced-2")
		Expect(namespacer.CacheKey()).To(Equal("namespaced-2"))
	})

	It("translate the root directory", func() {
		err := namespacer.Namespace(lagertest.NewTestLogger("test"), rootfs)

		info, err := os.Stat(rootfs)
		Expect(err).NotTo(HaveOccurred())

		Expect(translated).To(ContainElement(translation{
			path:    rootfs,
			size:    info.Size(),
			mode:    info.Mode(),
			modTime: info.ModTime(),
			err:     nil,
		}))
	})

	It("translates all of the uids", func() {
		err := namespacer.Namespace(lagertest.NewTestLogger("test"), rootfs)
コード例 #11
0
ファイル: exec_test.go プロジェクト: cloudfoundry/guardian
	. "github.com/onsi/gomega"
	"github.com/opencontainers/runc/libcontainer/user"
	"github.com/opencontainers/runtime-spec/specs-go"
)

var _ = Describe("Execer", func() {
	var (
		logger *lagertest.TestLogger

		execPreparer *fakes.FakeExecPreparer
		execRunner   *fakes.FakeExecRunner
		execer       *runrunc.Execer
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		execRunner = new(fakes.FakeExecRunner)
		execPreparer = new(fakes.FakeExecPreparer)

		execer = runrunc.NewExecer(
			execPreparer,
			execRunner,
		)
	})

	It("runs the execRunner with the prepared process spec", func() {
		execPreparer.PrepareStub = func(log lager.Logger, bundlePath string, spec garden.ProcessSpec) (*runrunc.PreparedSpec, error) {
			return &runrunc.PreparedSpec{
				Process: specs.Process{
					Args: []string{spec.Path, bundlePath},
				},
コード例 #12
0
			filename        string
			incomingRequest *http.Request
		)

		BeforeEach(func() {
			uploadURL, _ = url.Parse("http://example.com")
			filename = "filename"
			incomingRequest = createValidRequest()
		})

		Context("when not cancelling", func() {
			JustBeforeEach(func() {
				httpClient := &http.Client{
					Transport: transport,
				}
				u = ccclient.NewUploader(lagertest.NewTestLogger("test"), httpClient)
				response, uploadErr = u.Upload(uploadURL, filename, incomingRequest, make(chan struct{}))
			})

			Context("Validating the content length of the request", func() {
				BeforeEach(func() {
					transport = http.DefaultTransport
					filename = "filename"
					incomingRequest = &http.Request{}
				})

				It("fails early if the content length is 0", func() {
					Expect(response.StatusCode).To(Equal(http.StatusLengthRequired))

					Expect(uploadErr).To(HaveOccurred())
				})
コード例 #13
0
		driverRegistry vollocal.DriverRegistry
		driverSyncer   vollocal.DriverSyncer
		purger         vollocal.MountPurger

		fakeDriverFactory *volmanfakes.FakeDriverFactory
		fakeDriver        *voldriverfakes.FakeDriver
		fakeClock         clock.Clock

		scanInterval time.Duration

		process ifrit.Process
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("mount-purger")

		driverRegistry = vollocal.NewDriverRegistry()

		purger = vollocal.NewMountPurger(logger, driverRegistry)
	})

	It("should succeed when there are no drivers", func() {
		err := purger.PurgeMounts(logger)
		Expect(err).NotTo(HaveOccurred())
	})

	Context("when there is a driver", func() {
		BeforeEach(func() {
			err := voldriver.WriteDriverSpec(logger, defaultPluginsDirectory, "fakedriver", "spec", []byte("http://0.0.0.0:8080"))
			Expect(err).NotTo(HaveOccurred())
コード例 #14
0
			return filepath.Join(fakeCgroupDir, name, subsystem), nil
		}

		fakeRetrier.RunStub = func(fn func() error) error {
			return fn()
		}

		subject = stopper.New(fakeCgroupResolver, fakeKiller, fakeRetrier)
	})

	AfterEach(func() {
		os.RemoveAll(fakeCgroupDir)
	})

	It("does not send any signal to processes in the exceptions list", func() {
		Expect(subject.StopAll(lagertest.NewTestLogger("test"), "foo", []int{3, 5}, false)).To(Succeed())
		Expect(fakeKiller).To(HaveKilled(0, syscall.SIGTERM, 1, 9))
		Expect(fakeKiller).To(HaveKilled(1, syscall.SIGKILL, 1, 9))
	})

	Context("when the kill flag is true", func() {
		It("sends a KILL to all processes found in the cgroup", func() {
			Expect(subject.StopAll(lagertest.NewTestLogger("test"), "foo", nil, true)).To(Succeed())
			Expect(fakeKiller).To(HaveKilled(0, syscall.SIGKILL, 1, 3, 5, 9))
		})

		It("does not send TERM to processes found in the cgroup", func() {
			Expect(subject.StopAll(lagertest.NewTestLogger("test"), "foo", nil, true)).To(Succeed())
			Expect(fakeKiller).NotTo(HaveKilled(0, syscall.SIGTERM, 1, 3, 5, 9))
		})
	})
コード例 #15
0
		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() {
		pmn = ifrit.Invoke(metrics.NewPeriodicMetronNotifier(lagertest.NewTestLogger("test")))
	})

	AfterEach(func() {
		pmn.Signal(os.Interrupt)
		Eventually(pmn.Wait(), 2*time.Second).Should(Receive())
	})

	Context("when the metron notifier starts up", func() {
		It("should emit an event that BBS has started", func() {
			Eventually(func() uint64 {
				return sender.GetCounter("BBSMasterElected")
			}).Should(Equal(uint64(1)))
		})
	})
})
コード例 #16
0
		scanInterval time.Duration

		fakeClock         *fakeclock.FakeClock
		fakeDriverFactory *volmanfakes.FakeDriverFactory

		registry vollocal.DriverRegistry
		syncer   vollocal.DriverSyncer
		process  ifrit.Process

		fakeDriver *voldriverfakes.FakeDriver

		driverName string
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("driver-syncer-test")

		fakeClock = fakeclock.NewFakeClock(time.Unix(123, 456))
		fakeDriverFactory = new(volmanfakes.FakeDriverFactory)

		scanInterval = 10 * time.Second

		registry = vollocal.NewDriverRegistry()
		syncer = vollocal.NewDriverSyncerWithDriverFactory(logger, registry, []string{defaultPluginsDirectory}, scanInterval, fakeClock, fakeDriverFactory)

		fakeDriver = new(voldriverfakes.FakeDriver)
		fakeDriver.ActivateReturns(voldriver.ActivateResponse{
			Implements: []string{"VolumeDriver"},
		})

		fakeDriverFactory.DriverReturns(fakeDriver, nil)
コード例 #17
0
	Context("when configuration is invalid", func() {
		BeforeEach(func() {
			forceUpdate = false
			cfg = &config.Config{
				UaaEndpoint:           "http://not.needed.endpoint",
				MaxNumberOfRetries:    DefaultMaxNumberOfRetries,
				RetryInterval:         DefaultRetryInterval,
				ExpirationBufferInSec: DefaultExpirationBufferTime,
			}
		})
		JustBeforeEach(func() {
			var err error

			clock = fakeclock.NewFakeClock(time.Now())
			logger = lagertest.NewTestLogger("test")
			client, err = uaa_go_client.NewClient(logger, cfg, clock)
			Expect(err).NotTo(HaveOccurred())
			Expect(client).NotTo(BeNil())

		})

		Context("when clientId is missing from config", func() {
			BeforeEach(func() {
				cfg.ClientName = ""
				cfg.ClientSecret = "client-secret"
			})

			It("returns an error", func() {
				_, err := client.FetchToken(forceUpdate)
				Expect(err).To(HaveOccurred())
コード例 #18
0
	"code.cloudfoundry.org/goshims/os/os_fake"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"code.cloudfoundry.org/voldriver"
	"code.cloudfoundry.org/voldriver/voldriverfakes"
	"code.cloudfoundry.org/volman/vollocal"
)

var _ = Describe("DriverFactory", func() {
	var (
		testLogger lager.Logger
		driverName string
	)
	BeforeEach(func() {
		testLogger = lagertest.NewTestLogger("ClientTest")
	})

	Context("when a valid driver spec is discovered", func() {
		var (
			fakeRemoteClientFactory *voldriverfakes.FakeRemoteClientFactory
			localDriver             *voldriverfakes.FakeDriver
			driver                  voldriver.Driver
			driverFactory           vollocal.DriverFactory
		)
		BeforeEach(func() {
			driverName = "some-driver-name"
			fakeRemoteClientFactory = new(voldriverfakes.FakeRemoteClientFactory)
			localDriver = new(voldriverfakes.FakeDriver)
			fakeRemoteClientFactory.NewRemoteClientReturns(localDriver, nil)
			driverFactory = vollocal.NewDriverFactoryWithRemoteClientFactory(fakeRemoteClientFactory)
コード例 #19
0
)

var _ = Describe("Oven cleaner", func() {
	var (
		retainer      cleaner.RetainChecker
		gc            *cleaner.OvenCleaner
		fakeCake      *fake_cake.FakeCake
		child2parent  map[layercake.ID]layercake.ID // child -> parent
		size          map[layercake.ID]int64
		fakeThreshold *fakes.FakeThreshold
		logger        lager.Logger
	)

	BeforeEach(func() {
		fakeThreshold = new(fakes.FakeThreshold)
		logger = lagertest.NewTestLogger("test")

		retainer = cleaner.NewRetainer()

		fakeCake = new(fake_cake.FakeCake)
		fakeCake.GetStub = func(id layercake.ID) (*image.Image, error) {
			if parent, ok := child2parent[id]; ok {
				return &image.Image{
					ID:     id.GraphID(),
					Parent: parent.GraphID(),
					Size:   size[id],
				}, nil
			}

			return &image.Image{
				Size: size[id],
コード例 #20
0
ファイル: presence_test.go プロジェクト: cloudfoundry/locket
		if kvPair == nil || kvPair.Session == "" {
			return nil, consuladapter.NewKeyNotFoundError(presenceKey)
		}

		return kvPair.Value, nil
	}

	BeforeEach(func() {
		consulClient = consulRunner.NewClient()

		presenceKey = "some-key"
		presenceValue = []byte("some-value")

		retryInterval = 500 * time.Millisecond
		logger = lagertest.NewTestLogger("locket")

		presenceTTL = 5 * time.Second
	})

	JustBeforeEach(func() {
		clock = fakeclock.NewFakeClock(time.Now())
		presenceRunner = locket.NewPresence(logger, consulClient, presenceKey, presenceValue, clock, retryInterval, presenceTTL)
	})

	AfterEach(func() {
		ginkgomon.Kill(presenceProcess)
	})

	Context("When consul is running", func() {
		Context("an error occurs while acquiring the presence", func() {
コード例 #21
0
ファイル: nstar_test.go プロジェクト: cloudfoundry/guardian
			"path-to-nstar",
			"path-to-tar",
			fakeCommandRunner,
		)
	})

	Describe("StreamIn", func() {
		var someStream io.Reader

		BeforeEach(func() {
			someStream = gbytes.NewBuffer()
		})

		Context("when it executes succesfully", func() {
			BeforeEach(func() {
				Expect(nstar.StreamIn(lagertest.NewTestLogger("test"), 12, "some-path", "some-user", someStream)).To(Succeed())
			})

			It("executes the nstar command with the right arguments", func() {
				Expect(fakeCommandRunner).To(HaveExecutedSerially(fake_command_runner.CommandSpec{
					Path: "path-to-nstar",
					Args: []string{
						"path-to-tar",
						"12",
						"some-user",
						"some-path",
					},
				}))
			})

			It("attaches the tarStream reader to stdin", func() {
コード例 #22
0
ファイル: middleware_test.go プロジェクト: cloudfoundry/bbs
			handler.ServeHTTP(nil, nil)
			handler.ServeHTTP(nil, nil)
			handler.ServeHTTP(nil, nil)

			Expect(sender.GetCounter("RequestCount")).To(Equal(uint64(3)))
		})
	})

	Describe("LogWrap", func() {
		var (
			logger              *lagertest.TestLogger
			loggableHandlerFunc middleware.LoggableHandlerFunc
		)

		BeforeEach(func() {
			logger = lagertest.NewTestLogger("test-session")
			logger.RegisterSink(lager.NewWriterSink(GinkgoWriter, lager.DEBUG))
			loggableHandlerFunc = func(logger lager.Logger, w http.ResponseWriter, r *http.Request) {
				logger = logger.Session("logger-group")
				logger.Info("written-in-loggable-handler")
			}
		})

		It("creates \"request\" session and passes it to LoggableHandlerFunc", func() {
			handler := middleware.LogWrap(logger, nil, loggableHandlerFunc)
			req, err := http.NewRequest("GET", "http://example.com", nil)
			Expect(err).NotTo(HaveOccurred())
			handler.ServeHTTP(nil, req)
			Expect(logger.Buffer()).To(gbytes.Say("test-session.request.serving"))
			Expect(logger.Buffer()).To(gbytes.Say("\"session\":\"1\""))
			Expect(logger.Buffer()).To(gbytes.Say("test-session.request.logger-group.written-in-loggable-handler"))
コード例 #23
0
var _ = Describe("Bootstrap", func() {
	node_manager.GetShutDownTimeout = func() int {
		return 10
	}

	BeforeEach(func() {

		rootConfig = &config.Config{
			ShutDownMysql:             "stop_mysql",
			MysqlStatus:               "mysql_status",
			GetSeqNumber:              "sequence_number",
			StartMysqlInJoinMode:      "start_mysql_join",
			StartMysqlInBootstrapMode: "start_mysql_bootstrap",
		}

		rootConfig.Logger = lagertest.NewTestLogger("nodeManager test")

		endpointHandlers = []*test_helpers.EndpointHandler{}
		for i := 0; i < ServerCount; i++ {
			endpointHandlers = append(endpointHandlers, test_helpers.NewEndpointHandler())
		}
	})

	JustBeforeEach(func() {
		testServers = []*httptest.Server{}
		for i := 0; i < ServerCount; i++ {
			newServer := httptest.NewServer(endpointHandlers[i])
			testServers = append(testServers, newServer)

			rootConfig.HealthcheckURLs = append(rootConfig.HealthcheckURLs, newServer.URL)
		}
コード例 #24
0
ファイル: sqldb_suite_test.go プロジェクト: cloudfoundry/bbs
	migrationProcess                     ifrit.Process
	dbDriverName, dbBaseConnectionString string
	dbFlavor                             string
)

func TestSql(t *testing.T) {
	RegisterFailHandler(Fail)

	RunSpecs(t, "SQL DB Suite")
}

var _ = BeforeSuite(func() {
	var err error
	fakeClock = fakeclock.NewFakeClock(time.Now())
	fakeGUIDProvider = &guidproviderfakes.FakeGUIDProvider{}
	logger = lagertest.NewTestLogger("sql-db")

	if test_helpers.UsePostgres() {
		dbDriverName = "postgres"
		dbBaseConnectionString = "postgres://*****:*****@localhost/"
		dbFlavor = sqldb.Postgres
	} else if test_helpers.UseMySQL() {
		dbDriverName = "mysql"
		dbBaseConnectionString = "diego:diego_password@/"
		dbFlavor = sqldb.MySQL
	} else {
		panic("Unsupported driver")
	}

	// mysql must be set up on localhost as described in the CONTRIBUTING.md doc
	// in diego-release.
コード例 #25
0
ファイル: zipkin_test.go プロジェクト: cloudfoundry/gorouter
	var (
		handler      negroni.Handler
		headersToLog *[]string
		logger       lager.Logger
		resp         http.ResponseWriter
		req          *http.Request
		nextCalled   bool
	)

	nextHandler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		nextCalled = true
	})

	BeforeEach(func() {
		headersToLog = &[]string{}
		logger = lagertest.NewTestLogger("zipkin")
		req = test_util.NewRequest("GET", "example.com", "/", nil)
		resp = httptest.NewRecorder()
		nextCalled = false
	})

	AfterEach(func() {
		Expect(nextCalled).To(BeTrue(), "Expected the next handler to be called.")
	})

	Context("with Zipkin enabled", func() {
		BeforeEach(func() {
			handler = handlers.NewZipkin(true, headersToLog, logger)
		})

		It("sets zipkin headers", func() {
コード例 #26
0
ファイル: api_test.go プロジェクト: pivotal-cf/brokerapi
	lastLogLine := func() lager.LogFormat {
		noOfLogLines := len(brokerLogger.Logs())
		if noOfLogLines == 0 {
			// better way to raise error?
			err := errors.New("expected some log lines but there were none")
			Expect(err).NotTo(HaveOccurred())
		}

		return brokerLogger.Logs()[noOfLogLines-1]
	}

	BeforeEach(func() {
		fakeServiceBroker = &fakes.FakeServiceBroker{
			InstanceLimit: 3,
		}
		brokerLogger = lagertest.NewTestLogger("broker-api")
		brokerAPI = brokerapi.New(fakeServiceBroker, brokerLogger, credentials)
	})

	Describe("response headers", func() {
		makeRequest := func() *httptest.ResponseRecorder {
			recorder := httptest.NewRecorder()
			request, _ := http.NewRequest("GET", "/v2/catalog", nil)
			request.SetBasicAuth(credentials.Username, credentials.Password)
			brokerAPI.ServeHTTP(recorder, request)
			return recorder
		}

		It("has a Content-Type header", func() {
			response := makeRequest()
コード例 #27
0
		resourceLimits garden.ResourceLimits
		server         *ghttp.Server
		hijacker       HijackStreamer
		network        string
		address        string
	)

	BeforeEach(func() {
		server = ghttp.NewServer()
		network = "tcp"
		address = server.HTTPTestServer.Listener.Addr().String()
		hijacker = NewHijackStreamer(network, address)
	})

	JustBeforeEach(func() {
		connection = NewWithHijacker(hijacker, lagertest.NewTestLogger("test-connection"))
	})

	BeforeEach(func() {
		rlimits := &garden.ResourceLimits{
			As:         uint64ptr(1),
			Core:       uint64ptr(2),
			Cpu:        uint64ptr(4),
			Data:       uint64ptr(5),
			Fsize:      uint64ptr(6),
			Locks:      uint64ptr(7),
			Memlock:    uint64ptr(8),
			Msgqueue:   uint64ptr(9),
			Nice:       uint64ptr(10),
			Nofile:     uint64ptr(11),
			Nproc:      uint64ptr(12),
コード例 #28
0
		sess, err = gexec.Start(exec.Command("ip", "link", "add", linkName, "type", "dummy"), GinkgoWriter, GinkgoWriter)
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess).Should(gexec.Exit(0))

		sess, err = gexec.Start(exec.Command("ip", "link", "set", linkName, "netns", netNsName), GinkgoWriter, GinkgoWriter)
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess).Should(gexec.Exit(0))

		configurer = &configure.Container{
			FileOpener: netns.Opener(func(path string) (*os.File, error) {
				return netNsFd, nil
			}),
		}

		logger = lagertest.NewTestLogger("container")

		containerIP, subnet, err := net.ParseCIDR("192.0.2.20/24")
		Expect(err).NotTo(HaveOccurred())
		networkConfig = kawasaki.NetworkConfig{
			ContainerIntf: linkName,
			ContainerIP:   containerIP,
			BridgeIP:      net.ParseIP("192.0.2.1"),
			Subnet:        subnet,
			Mtu:           1600,
		}
	})

	AfterEach(func() {
		sess, err := gexec.Start(exec.Command("ip", "netns", "delete", netNsName), GinkgoWriter, GinkgoWriter)
		Expect(err).NotTo(HaveOccurred())
コード例 #29
0
ファイル: perf_test.go プロジェクト: cloudfoundry/gorouter
	"code.cloudfoundry.org/gorouter/route"
	"code.cloudfoundry.org/gorouter/varz"
	"code.cloudfoundry.org/lager/lagertest"
	"code.cloudfoundry.org/routing-api/models"

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

	"strconv"

	"code.cloudfoundry.org/gorouter/metrics/reporter/fakes"
)

var _ = Describe("AccessLogRecord", func() {
	Measure("Register", func(b Benchmarker) {
		logger := lagertest.NewTestLogger("test")
		c := config.DefaultConfig()
		r := registry.NewRouteRegistry(logger, c, new(fakes.FakeRouteRegistryReporter))

		accesslog, err := access_log.CreateRunningAccessLogger(logger, c)
		Expect(err).ToNot(HaveOccurred())

		proxy.NewProxy(proxy.ProxyArgs{
			EndpointTimeout: c.EndpointTimeout,
			Ip:              c.Ip,
			TraceKey:        c.TraceKey,
			Registry:        r,
			Reporter:        varz.NewVarz(r),
			AccessLogger:    accesslog,
		})
コード例 #30
0
import (
	"errors"

	"code.cloudfoundry.org/garden"
	"code.cloudfoundry.org/garden-shed/layercake"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Metrics Adapter", func() {
	It("converts metrics calls using ID on to GetUsage calls using path", func() {
		mAdapter := MetricsAdapter{
			fn: func(logger lager.Logger, rootfsPath string) (garden.ContainerDiskStat, error) {
				Expect(rootfsPath).To(Equal("/foo/bar/banana"))
				return garden.ContainerDiskStat{
					TotalBytesUsed: 12,
				}, errors.New("potato")
			},
			id2path: func(id layercake.ID) string {
				return "/foo/bar/" + id.GraphID()
			},
		}

		stat, err := mAdapter.Metrics(lagertest.NewTestLogger("test"), layercake.DockerImageID("banana"))
		Expect(err).To(MatchError("potato"))
		Expect(stat.TotalBytesUsed).To(BeEquivalentTo(12))
	})
})