本文整理匯總了Golang中github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/logger.NewLogger函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewLogger函數的具體用法?Golang NewLogger怎麽用?Golang NewLogger使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewLogger函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: newRealClient
func newRealClient(url string) Client {
logger := boshlog.NewLogger(boshlog.LevelNone)
return NewHTTPClient(
url,
"fake-user",
"fake-pass",
http.DefaultClient,
http.DefaultClient,
logger,
)
}
示例2: newFakeClient
func newFakeClient(shortClient, longClient *fakehttp.FakeClient) Client {
logger := boshlog.NewLogger(boshlog.LevelNone)
return NewHTTPClient(
"agent.example.com",
"fake-user",
"fake-pass",
shortClient,
longClient,
logger,
)
}
示例3: describeDummyPlatform
func describeDummyPlatform() {
var (
platform Platform
collector boshstats.Collector
fs boshsys.FileSystem
cmdRunner boshsys.CmdRunner
dirProvider boshdirs.Provider
devicePathResolver boshdpresolv.DevicePathResolver
logger boshlog.Logger
)
BeforeEach(func() {
collector = &fakestats.FakeCollector{}
fs = fakesys.NewFakeFileSystem()
cmdRunner = fakesys.NewFakeCmdRunner()
dirProvider = boshdirs.NewProvider("/fake-dir")
devicePathResolver = fakedpresolv.NewFakeDevicePathResolver()
logger = boshlog.NewLogger(boshlog.LevelNone)
})
JustBeforeEach(func() {
platform = NewDummyPlatform(
collector,
fs,
cmdRunner,
dirProvider,
devicePathResolver,
logger,
)
})
Describe("GetDefaultNetwork", func() {
It("returns the contents of dummy-defaults-network-settings.json since that's what the dummy cpi writes", func() {
settingsFilePath := "/fake-dir/bosh/dummy-default-network-settings.json"
fs.WriteFileString(settingsFilePath, `{"IP": "1.2.3.4"}`)
network, err := platform.GetDefaultNetwork()
Expect(err).NotTo(HaveOccurred())
Expect(network.IP).To(Equal("1.2.3.4"))
})
})
Describe("GetCertManager", func() {
It("returs a dummy cert manager", func() {
certManager := platform.GetCertManager()
Expect(certManager.UpdateCertificates("")).Should(BeNil())
})
})
}
示例4: TestIntegration
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
logger := boshlog.NewLogger(boshlog.LevelDebug)
cmdRunner := boshsys.NewExecCmdRunner(logger)
testEnvironment = NewTestEnvironment(cmdRunner)
// Required for reverse-compatibility with older bosh-lite
// (remove once a new warden stemcell is built).
err := testEnvironment.ConfigureAgentForGenericInfrastructure()
Expect(err).ToNot(HaveOccurred())
})
RunSpecs(t, "Integration Suite")
}
示例5: init
func init() {
Describe("ListDisk", func() {
var (
settingsService *fakesettings.FakeSettingsService
platform *fakeplatform.FakePlatform
logger boshlog.Logger
action ListDiskAction
)
BeforeEach(func() {
settingsService = &fakesettings.FakeSettingsService{}
platform = fakeplatform.NewFakePlatform()
logger = boshlog.NewLogger(boshlog.LevelNone)
action = NewListDisk(settingsService, platform, logger)
})
It("list disk should be synchronous", func() {
Expect(action.IsAsynchronous()).To(BeFalse())
})
It("is not persistent", func() {
Expect(action.IsPersistent()).To(BeFalse())
})
It("list disk run", func() {
platform.MountedDevicePaths = []string{"/dev/sdb", "/dev/sdc"}
settingsService.Settings.Disks = boshsettings.Disks{
Persistent: map[string]interface{}{
"volume-1": "/dev/sda",
"volume-2": "/dev/sdb",
"volume-3": "/dev/sdc",
},
}
value, err := action.Run()
Expect(err).ToNot(HaveOccurred())
values, ok := value.([]string)
Expect(ok).To(BeTrue())
Expect(values).To(ContainElement("volume-2"))
Expect(values).To(ContainElement("volume-3"))
Expect(len(values)).To(Equal(2))
})
})
}
示例6: main
func main() {
logger := boshlog.NewLogger(boshlog.LevelDebug)
defer logger.HandlePanic("Main")
logger.Debug(mainLogTag, "Starting agent")
app := boshapp.New(logger)
err := app.Setup(os.Args)
if err != nil {
logger.Error(mainLogTag, "App setup %s", err.Error())
os.Exit(1)
}
err = app.Run()
if err != nil {
logger.Error(mainLogTag, "App run %s", err.Error())
os.Exit(1)
}
}
示例7: main
func main() {
logger := newSignalableLogger(boshlog.NewLogger(boshlog.LevelDebug))
defer logger.HandlePanic("Main")
logger.Debug(mainLogTag, "Starting agent")
fs := boshsys.NewOsFileSystem(logger)
app := boshapp.New(logger, fs)
err := app.Setup(os.Args)
if err != nil {
logger.Error(mainLogTag, "App setup %s", err.Error())
os.Exit(1)
}
err = app.Run()
if err != nil {
logger.Error(mainLogTag, "App run %s", err.Error())
os.Exit(1)
}
}
示例8: main
func main() {
user := flag.String("user", "user", "User")
password := flag.String("password", "password", "Password")
host := flag.String("host", "127.0.0.1", "Host")
port := flag.Int("port", 8080, "Port")
instance := flag.String("instance", "", "Instance ID")
settings := flag.String("settings", "", "Instance Settings")
flag.Parse()
logger := boshlog.NewLogger(boshlog.LevelDebug)
serverManager := bmregistry.NewServerManager(logger)
_, err := serverManager.Start(*user, *password, *host, *port)
if err != nil {
panic("Error starting registry")
}
if *instance != "" && *settings != "" {
request, err := http.NewRequest(
"PUT",
fmt.Sprintf("http://%s:%[email protected]%s:%d/instances/%s/settings", *user, *password, *host, *port, *instance),
strings.NewReader(*settings),
)
if err != nil {
panic("Couldn't create request")
}
client := http.DefaultClient
_, err = client.Do(request)
if err != nil {
panic(fmt.Sprintf("Error sending request: %s", err.Error()))
}
}
select {}
}
示例9: describeUbuntuNetManager
func describeUbuntuNetManager() {
var (
fs *fakesys.FakeFileSystem
cmdRunner *fakesys.FakeCmdRunner
ipResolver *fakeip.FakeResolver
addressBroadcaster *fakearp.FakeAddressBroadcaster
netManager UbuntuNetManager
interfaceConfigurationCreator InterfaceConfigurationCreator
)
writeNetworkDevice := func(iface string, macAddress string, isPhysical bool) string {
interfacePath := fmt.Sprintf("/sys/class/net/%s", iface)
fs.WriteFile(interfacePath, []byte{})
if isPhysical {
fs.WriteFile(fmt.Sprintf("/sys/class/net/%s/device", iface), []byte{})
}
fs.WriteFileString(fmt.Sprintf("/sys/class/net/%s/address", iface), fmt.Sprintf("%s\n", macAddress))
return interfacePath
}
stubInterfacesWithVirtual := func(physicalInterfaces map[string]boshsettings.Network, virtualInterfaces []string) {
interfacePaths := []string{}
for iface, networkSettings := range physicalInterfaces {
interfacePaths = append(interfacePaths, writeNetworkDevice(iface, networkSettings.Mac, true))
}
for _, iface := range virtualInterfaces {
interfacePaths = append(interfacePaths, writeNetworkDevice(iface, "virtual", false))
}
fs.SetGlob("/sys/class/net/*", interfacePaths)
}
stubInterfaces := func(physicalInterfaces map[string]boshsettings.Network) {
stubInterfacesWithVirtual(physicalInterfaces, nil)
}
BeforeEach(func() {
fs = fakesys.NewFakeFileSystem()
cmdRunner = fakesys.NewFakeCmdRunner()
ipResolver = &fakeip.FakeResolver{}
logger := boshlog.NewLogger(boshlog.LevelNone)
interfaceConfigurationCreator = NewInterfaceConfigurationCreator(logger)
addressBroadcaster = &fakearp.FakeAddressBroadcaster{}
netManager = NewUbuntuNetManager(
fs,
cmdRunner,
ipResolver,
interfaceConfigurationCreator,
addressBroadcaster,
logger,
).(UbuntuNetManager)
})
Describe("ComputeNetworkConfig", func() {
Context("when there is one manual network and neither is marked as default for DNS", func() {
It("should use the manual network for DNS", func() {
networks := boshsettings.Networks{
"manual": factory.Network{DNS: &[]string{"8.8.8.8"}}.Build(),
}
stubInterfaces(networks)
_, _, dnsServers, err := netManager.ComputeNetworkConfig(networks)
Expect(err).ToNot(HaveOccurred())
Expect(dnsServers).To(Equal([]string{"8.8.8.8"}))
})
})
Context("when there is a vip network and a manual network and neither is marked as default for DNS", func() {
It("should use the manual network for DNS", func() {
networks := boshsettings.Networks{
"vip": boshsettings.Network{Type: "vip"},
"manual": factory.Network{Type: "manual", DNS: &[]string{"8.8.8.8"}}.Build(),
}
stubInterfaces(networks)
_, _, dnsServers, err := netManager.ComputeNetworkConfig(networks)
Expect(err).ToNot(HaveOccurred())
Expect(dnsServers).To(Equal([]string{"8.8.8.8"}))
})
})
Context("when there is a vip network and a manual network and the manual network is marked as default for DNS", func() {
It("should use the manual network for DNS", func() {
networks := boshsettings.Networks{
"vip": boshsettings.Network{Type: "vip"},
"manual": factory.Network{Type: "manual", DNS: &[]string{"8.8.8.8"}, Default: []string{"dns"}}.Build(),
}
stubInterfaces(networks)
_, _, dnsServers, err := netManager.ComputeNetworkConfig(networks)
Expect(err).ToNot(HaveOccurred())
Expect(dnsServers).To(Equal([]string{"8.8.8.8"}))
})
})
Context("when specified more than one DNS", func() {
It("extracts all DNS servers from the network configured as default DNS", func() {
networks := boshsettings.Networks{
"default": factory.Network{
IP: "10.10.0.32",
Netmask: "255.255.255.0",
//.........這裏部分代碼省略.........
示例10: init
func init() {
Describe("actionDispatcher", func() {
var (
logger boshlog.Logger
taskService *faketask.FakeService
taskManager *faketask.FakeManager
actionFactory *fakeaction.FakeFactory
actionRunner *fakeaction.FakeRunner
dispatcher ActionDispatcher
)
BeforeEach(func() {
logger = boshlog.NewLogger(boshlog.LevelNone)
taskService = faketask.NewFakeService()
taskManager = faketask.NewFakeManager()
actionFactory = fakeaction.NewFakeFactory()
actionRunner = &fakeaction.FakeRunner{}
dispatcher = NewActionDispatcher(logger, taskService, taskManager, actionFactory, actionRunner)
})
It("responds with exception when the method is unknown", func() {
actionFactory.RegisterActionErr("fake-action", errors.New("fake-create-error"))
req := boshhandler.NewRequest("fake-reply", "fake-action", []byte{})
resp := dispatcher.Dispatch(req)
boshassert.MatchesJSONString(GinkgoT(), resp, `{"exception":{"message":"unknown message fake-action"}}`)
})
Context("when action is synchronous", func() {
var (
req boshhandler.Request
)
BeforeEach(func() {
req = boshhandler.NewRequest("fake-reply", "fake-action", []byte("fake-payload"))
actionFactory.RegisterAction("fake-action", &fakeaction.TestAction{Asynchronous: false})
})
It("handles synchronous action", func() {
actionRunner.RunValue = "fake-value"
resp := dispatcher.Dispatch(req)
Expect(req.GetPayload()).To(Equal(actionRunner.RunPayload))
Expect(boshhandler.NewValueResponse("fake-value")).To(Equal(resp))
})
It("handles synchronous action when err", func() {
actionRunner.RunErr = errors.New("fake-run-error")
resp := dispatcher.Dispatch(req)
expectedJSON := fmt.Sprintf("{\"exception\":{\"message\":\"Action Failed %s: fake-run-error\"}}", req.Method)
boshassert.MatchesJSONString(GinkgoT(), resp, expectedJSON)
})
})
Context("when action is asynchronous", func() {
var (
req boshhandler.Request
action *fakeaction.TestAction
)
BeforeEach(func() {
req = boshhandler.NewRequest("fake-reply", "fake-action", []byte("fake-payload"))
action = &fakeaction.TestAction{Asynchronous: true}
actionFactory.RegisterAction("fake-action", action)
})
ItAllowsToCancelTask := func() {
It("allows task to be cancelled", func() {
dispatcher.Dispatch(req)
err := taskService.StartedTasks["fake-generated-task-id"].Cancel()
Expect(err).ToNot(HaveOccurred())
Expect(action.Canceled).To(BeTrue())
})
It("returns error from cancelling task if canceling task fails", func() {
action.CancelErr = errors.New("fake-cancel-err")
dispatcher.Dispatch(req)
err := taskService.StartedTasks["fake-generated-task-id"].Cancel()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-cancel-err"))
})
}
Context("when action is not persistent", func() {
BeforeEach(func() {
action.Persistent = false
})
It("responds with task id and state", func() {
resp := dispatcher.Dispatch(req)
boshassert.MatchesJSONString(GinkgoT(), resp,
`{"value":{"agent_task_id":"fake-generated-task-id","state":"running"}}`)
})
It("starts running created task", func() {
dispatcher.Dispatch(req)
//.........這裏部分代碼省略.........
示例11: init
func init() {
Describe("App", func() {
var (
baseDir string
agentConfPath string
agentConfJSON string
app App
)
BeforeEach(func() {
var err error
baseDir, err = ioutil.TempDir("", "go-agent-test")
Expect(err).ToNot(HaveOccurred())
err = os.Mkdir(filepath.Join(baseDir, "bosh"), os.ModePerm)
Expect(err).ToNot(HaveOccurred())
})
BeforeEach(func() {
agentConfPath = filepath.Join(baseDir, "bosh", "agent.json")
agentConfJSON = `{
"Infrastructure": { "Settings": { "Sources": [{ "Type": "CDROM", "FileName": "/fake-file-name" }] } }
}`
settingsPath := filepath.Join(baseDir, "bosh", "settings.json")
settingsJSON := `{
"agent_id": "my-agent-id",
"blobstore": {
"options": {
"bucket_name": "george",
"encryption_key": "optional encryption key",
"access_key_id": "optional access key id",
"secret_access_key": "optional secret access key"
},
"provider": "dummy"
},
"disks": {
"ephemeral": "/dev/sdb",
"persistent": {
"vol-xxxxxx": "/dev/sdf"
},
"system": "/dev/sda1"
},
"env": {
"bosh": {
"password": "some encrypted password"
}
},
"networks": {
"netA": {
"default": ["dns", "gateway"],
"ip": "ww.ww.ww.ww",
"dns": [
"xx.xx.xx.xx",
"yy.yy.yy.yy"
]
},
"netB": {
"dns": [
"zz.zz.zz.zz"
]
}
},
"Mbus": "https://vcap:[email protected]:6868",
"ntp": [
"0.north-america.pool.ntp.org",
"1.north-america.pool.ntp.org"
],
"vm": {
"name": "vm-abc-def"
}
}`
err := ioutil.WriteFile(settingsPath, []byte(settingsJSON), 0640)
Expect(err).ToNot(HaveOccurred())
})
JustBeforeEach(func() {
err := ioutil.WriteFile(agentConfPath, []byte(agentConfJSON), 0640)
Expect(err).ToNot(HaveOccurred())
logger := boshlog.NewLogger(boshlog.LevelNone)
fakefs := boshsys.NewOsFileSystem(logger)
app = New(logger, fakefs)
})
AfterEach(func() {
os.RemoveAll(baseDir)
})
It("Sets up device path resolver on platform specific to infrastructure", func() {
err := app.Setup([]string{"bosh-agent", "-P", "dummy", "-C", agentConfPath, "-b", baseDir})
Expect(err).ToNot(HaveOccurred())
Expect(app.GetPlatform().GetDevicePathResolver()).To(Equal(devicepathresolver.NewIdentityDevicePathResolver()))
})
//.........這裏部分代碼省略.........
示例12: init
func init() {
Describe("bootstrap", func() {
Describe("Run", func() {
var (
platform *fakeplatform.FakePlatform
dirProvider boshdir.Provider
settingsSource *fakeinf.FakeSettingsSource
settingsService *fakesettings.FakeSettingsService
)
BeforeEach(func() {
platform = fakeplatform.NewFakePlatform()
dirProvider = boshdir.NewProvider("/var/vcap")
settingsSource = &fakeinf.FakeSettingsSource{}
settingsService = &fakesettings.FakeSettingsService{}
})
bootstrap := func() error {
logger := boshlog.NewLogger(boshlog.LevelNone)
return NewBootstrap(platform, dirProvider, settingsService, logger).Run()
}
It("sets up runtime configuration", func() {
err := bootstrap()
Expect(err).NotTo(HaveOccurred())
Expect(platform.SetupRuntimeConfigurationWasInvoked).To(BeTrue())
})
Describe("SSH tunnel setup for registry", func() {
It("returns error without configuring ssh on the platform if getting public key fails", func() {
settingsService.PublicKeyErr = errors.New("fake-get-public-key-err")
err := bootstrap()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-get-public-key-err"))
Expect(platform.SetupSSHCalled).To(BeFalse())
})
Context("when public key is not empty", func() {
BeforeEach(func() {
settingsService.PublicKey = "fake-public-key"
})
It("gets the public key and sets up ssh via the platform", func() {
err := bootstrap()
Expect(err).NotTo(HaveOccurred())
Expect(platform.SetupSSHPublicKey).To(Equal("fake-public-key"))
Expect(platform.SetupSSHUsername).To(Equal("vcap"))
})
It("returns error if configuring ssh on the platform fails", func() {
platform.SetupSSHErr = errors.New("fake-setup-ssh-err")
err := bootstrap()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-setup-ssh-err"))
})
})
Context("when public key key is empty", func() {
BeforeEach(func() {
settingsSource.PublicKey = ""
})
It("gets the public key and does not setup SSH", func() {
err := bootstrap()
Expect(err).NotTo(HaveOccurred())
Expect(platform.SetupSSHCalled).To(BeFalse())
})
})
})
It("sets up hostname", func() {
settingsService.Settings.AgentID = "foo-bar-baz-123"
err := bootstrap()
Expect(err).NotTo(HaveOccurred())
Expect(platform.SetupHostnameHostname).To(Equal("foo-bar-baz-123"))
})
It("fetches initial settings", func() {
err := bootstrap()
Expect(err).NotTo(HaveOccurred())
Expect(settingsService.SettingsWereLoaded).To(BeTrue())
})
It("returns error from loading initial settings", func() {
settingsService.LoadSettingsError = errors.New("fake-load-error")
err := bootstrap()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-load-error"))
})
It("sets up networking", func() {
//.........這裏部分代碼省略.........
示例13: init
func init() {
Describe("asyncTaskService", func() {
var (
uuidGen *fakeuuid.FakeGenerator
service Service
)
BeforeEach(func() {
uuidGen = &fakeuuid.FakeGenerator{}
service = NewAsyncTaskService(uuidGen, boshlog.NewLogger(boshlog.LevelNone))
})
Describe("StartTask", func() {
startAndWaitForTaskCompletion := func(task Task) Task {
service.StartTask(task)
for task.State == StateRunning {
time.Sleep(time.Nanosecond)
task, _ = service.FindTaskWithID(task.ID)
}
return task
}
It("sets return value on a successful task", func() {
runFunc := func() (interface{}, error) { return 123, nil }
task, err := service.CreateTask(runFunc, nil, nil)
Expect(err).ToNot(HaveOccurred())
task = startAndWaitForTaskCompletion(task)
Expect(task.State).To(BeEquivalentTo(StateDone))
Expect(task.Value).To(Equal(123))
Expect(task.Error).To(BeNil())
})
It("sets task error on a failing task", func() {
err := errors.New("fake-error")
runFunc := func() (interface{}, error) { return nil, err }
task, createErr := service.CreateTask(runFunc, nil, nil)
Expect(createErr).ToNot(HaveOccurred())
task = startAndWaitForTaskCompletion(task)
Expect(task.State).To(BeEquivalentTo(StateFailed))
Expect(task.Value).To(BeNil())
Expect(task.Error).To(Equal(err))
})
Describe("CreateTask", func() {
It("can run task created with CreateTask which does not have end func", func() {
ranFunc := false
runFunc := func() (interface{}, error) { ranFunc = true; return nil, nil }
task, err := service.CreateTask(runFunc, nil, nil)
Expect(err).ToNot(HaveOccurred())
startAndWaitForTaskCompletion(task)
Expect(ranFunc).To(BeTrue())
})
It("can run task created with CreateTask which has end func", func() {
ranFunc := false
runFunc := func() (interface{}, error) { ranFunc = true; return nil, nil }
ranEndFunc := false
endFunc := func(Task) { ranEndFunc = true }
task, err := service.CreateTask(runFunc, nil, endFunc)
Expect(err).ToNot(HaveOccurred())
startAndWaitForTaskCompletion(task)
Expect(ranFunc).To(BeTrue())
Expect(ranEndFunc).To(BeTrue())
})
It("returns an error if generate uuid fails", func() {
uuidGen.GenerateError = errors.New("fake-generate-uuid-error")
_, err := service.CreateTask(nil, nil, nil)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-generate-uuid-error"))
})
})
Describe("CreateTaskWithID", func() {
It("can run task created with CreateTaskWithID which does not have end func", func() {
ranFunc := false
runFunc := func() (interface{}, error) { ranFunc = true; return nil, nil }
task := service.CreateTaskWithID("fake-task-id", runFunc, nil, nil)
startAndWaitForTaskCompletion(task)
Expect(ranFunc).To(BeTrue())
})
It("can run task created with CreateTaskWithID which has end func", func() {
ranFunc := false
runFunc := func() (interface{}, error) { ranFunc = true; return nil, nil }
ranEndFunc := false
endFunc := func(Task) { ranEndFunc = true }
//.........這裏部分代碼省略.........
示例14: init
func init() {
Describe("settingsService", func() {
var (
fs *fakesys.FakeFileSystem
fakeDefaultNetworkResolver *fakenet.FakeDefaultNetworkResolver
fakeSettingsSource *fakes.FakeSettingsSource
)
BeforeEach(func() {
fs = fakesys.NewFakeFileSystem()
fakeDefaultNetworkResolver = &fakenet.FakeDefaultNetworkResolver{}
fakeSettingsSource = &fakes.FakeSettingsSource{}
})
buildService := func() (Service, *fakesys.FakeFileSystem) {
logger := boshlog.NewLogger(boshlog.LevelNone)
service := NewService(fs, "/setting/path.json", fakeSettingsSource, fakeDefaultNetworkResolver, logger)
return service, fs
}
Describe("LoadSettings", func() {
var (
fetchedSettings Settings
fetcherFuncErr error
service Service
)
BeforeEach(func() {
fetchedSettings = Settings{}
fetcherFuncErr = nil
})
JustBeforeEach(func() {
fakeSettingsSource.SettingsValue = fetchedSettings
fakeSettingsSource.SettingsErr = fetcherFuncErr
service, fs = buildService()
})
Context("when settings fetcher succeeds fetching settings", func() {
BeforeEach(func() {
fetchedSettings = Settings{AgentID: "some-new-agent-id"}
})
Context("when settings contain at most one dynamic network", func() {
BeforeEach(func() {
fetchedSettings.Networks = Networks{
"fake-net-1": Network{Type: NetworkTypeDynamic},
}
})
It("updates the service with settings from the fetcher", func() {
err := service.LoadSettings()
Expect(err).NotTo(HaveOccurred())
Expect(service.GetSettings().AgentID).To(Equal("some-new-agent-id"))
})
It("persists settings to the settings file", func() {
err := service.LoadSettings()
Expect(err).NotTo(HaveOccurred())
json, err := json.Marshal(fetchedSettings)
Expect(err).NotTo(HaveOccurred())
fileContent, err := fs.ReadFile("/setting/path.json")
Expect(err).NotTo(HaveOccurred())
Expect(fileContent).To(Equal(json))
})
It("returns any error from writing to the setting file", func() {
fs.WriteFileError = errors.New("fs-write-file-error")
err := service.LoadSettings()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fs-write-file-error"))
})
})
})
Context("when settings fetcher fails fetching settings", func() {
BeforeEach(func() {
fetcherFuncErr = errors.New("fake-fetch-error")
})
Context("when a settings file exists", func() {
Context("when settings contain at most one dynamic network", func() {
BeforeEach(func() {
fs.WriteFile("/setting/path.json", []byte(`{
"agent_id":"some-agent-id",
"networks": {"fake-net-1": {"type": "dynamic"}}
}`))
fakeDefaultNetworkResolver.GetDefaultNetworkNetwork = Network{
IP: "fake-resolved-ip",
Netmask: "fake-resolved-netmask",
Gateway: "fake-resolved-gateway",
}
})
It("returns settings from the settings file with resolved network", func() {
err := service.LoadSettings()
//.........這裏部分代碼省略.........
示例15: init
func init() {
Describe("renderedJobApplier", func() {
var (
jobsBc *fakebc.FakeBundleCollection
jobSupervisor *fakejobsuper.FakeJobSupervisor
packageApplierProvider *fakepackages.FakeApplierProvider
blobstore *fakeblob.FakeBlobstore
compressor *fakecmd.FakeCompressor
fs *fakesys.FakeFileSystem
applier Applier
)
BeforeEach(func() {
jobsBc = fakebc.NewFakeBundleCollection()
jobSupervisor = fakejobsuper.NewFakeJobSupervisor()
packageApplierProvider = fakepackages.NewFakeApplierProvider()
blobstore = fakeblob.NewFakeBlobstore()
fs = fakesys.NewFakeFileSystem()
compressor = fakecmd.NewFakeCompressor()
logger := boshlog.NewLogger(boshlog.LevelNone)
applier = NewRenderedJobApplier(
jobsBc,
jobSupervisor,
packageApplierProvider,
blobstore,
compressor,
fs,
logger,
)
})
Describe("Prepare & Apply", func() {
var (
job models.Job
bundle *fakebc.FakeBundle
)
BeforeEach(func() {
job, bundle = buildJob(jobsBc)
})
ItInstallsJob := func(act func() error) {
BeforeEach(func() {
fs.TempDirDir = "/fake-tmp-dir"
})
It("returns error when installing job fails", func() {
bundle.InstallError = errors.New("fake-install-error")
err := act()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-install-error"))
})
It("downloads and later cleans up downloaded job template blob", func() {
blobstore.GetFileName = "/fake-blobstore-file-name"
err := act()
Expect(err).ToNot(HaveOccurred())
Expect(blobstore.GetBlobIDs[0]).To(Equal("fake-blobstore-id"))
Expect(blobstore.GetFingerprints[0]).To(Equal("fake-blob-sha1"))
// downloaded file is cleaned up
Expect(blobstore.CleanUpFileName).To(Equal("/fake-blobstore-file-name"))
})
It("returns error when downloading job template blob fails", func() {
blobstore.GetError = errors.New("fake-get-error")
err := act()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-get-error"))
})
It("decompresses job template blob to tmp path and later cleans it up", func() {
blobstore.GetFileName = "/fake-blobstore-file-name"
var tmpDirExistsBeforeInstall bool
bundle.InstallCallBack = func() {
tmpDirExistsBeforeInstall = true
}
err := act()
Expect(err).ToNot(HaveOccurred())
Expect(compressor.DecompressFileToDirTarballPaths[0]).To(Equal("/fake-blobstore-file-name"))
Expect(compressor.DecompressFileToDirDirs[0]).To(Equal("/fake-tmp-dir"))
// tmp dir exists before bundle install
Expect(tmpDirExistsBeforeInstall).To(BeTrue())
// tmp dir is cleaned up after install
Expect(fs.FileExists(fs.TempDirDir)).To(BeFalse())
})
It("returns error when temporary directory creation fails", func() {
fs.TempDirError = errors.New("fake-filesystem-tempdir-error")
//.........這裏部分代碼省略.........