本文整理汇总了Golang中github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/system/fakes.NewFakeFileSystem函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFakeFileSystem函数的具体用法?Golang NewFakeFileSystem怎么用?Golang NewFakeFileSystem使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewFakeFileSystem函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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())
})
})
}
示例2: init
func init() {
Describe("Testing with Ginkgo", func() {
It("new drain script", func() {
runner := fakesys.NewFakeCmdRunner()
fs := fakesys.NewFakeFileSystem()
dirProvider := boshdir.NewProvider("/var/vcap")
scriptProvider := NewConcreteScriptProvider(runner, fs, dirProvider)
script := scriptProvider.NewScript("foo")
Expect(script.Path()).To(Equal("/var/vcap/jobs/foo/bin/drain"))
})
})
}
示例3: init
func init() {
Describe("GenericScriptProvider", func() {
It("produces script paths relative to the base directory", func() {
runner := fakesys.NewFakeCmdRunner()
fs := fakesys.NewFakeFileSystem()
dirProvider := boshdir.NewProvider("/the/base/dir")
scriptProvider := scriptrunner.NewJobScriptProvider(runner, fs, dirProvider)
script := scriptProvider.Get("myjob", "the-best-hook-ever")
Expect(script.Path()).To(Equal("/the/base/dir/jobs/myjob/bin/the-best-hook-ever"))
})
})
}
示例4: NewFakePlatform
func NewFakePlatform() (platform *FakePlatform) {
platform = new(FakePlatform)
platform.Fs = fakesys.NewFakeFileSystem()
platform.Runner = fakesys.NewFakeCmdRunner()
platform.FakeCompressor = fakecmd.NewFakeCompressor()
platform.FakeCopier = fakecmd.NewFakeCopier()
platform.FakeVitalsService = fakevitals.NewFakeService()
platform.DevicePathResolver = fakedpresolv.NewFakeDevicePathResolver()
platform.AddUserToGroupsGroups = make(map[string][]string)
platform.SetupSSHPublicKeys = make(map[string]string)
platform.UserPasswords = make(map[string]string)
platform.ScsiDiskMap = make(map[string]string)
platform.GetFileContentsFromDiskDiskPaths = []string{}
platform.GetFileContentsFromDiskFileNames = [][]string{}
platform.GetFileContentsFromDiskContents = map[string][]byte{}
platform.GetFileContentsFromDiskErrs = map[string]error{}
platform.certManager = new(fakecert.FakeManager)
return
}
示例5: init
func init() {
Describe("prepareNetworkChange", func() {
var (
action PrepareNetworkChangeAction
fs *fakesys.FakeFileSystem
settingsService *fakesettings.FakeSettingsService
)
BeforeEach(func() {
fs = fakesys.NewFakeFileSystem()
settingsService = &fakesettings.FakeSettingsService{}
action = NewPrepareNetworkChange(fs, settingsService, fakeactions.NewFakeAgentKiller())
})
It("is synchronous", func() {
Expect(action.IsAsynchronous()).To(BeFalse())
})
It("is not persistent", func() {
Expect(action.IsPersistent()).To(BeFalse())
})
It("invalidates settings so that load settings cannot fall back on old settings", func() {
resp, err := action.Run()
Expect(err).NotTo(HaveOccurred())
Expect(resp).To(Equal("ok"))
Expect(settingsService.SettingsWereInvalidated).To(BeTrue())
})
Context("when settings invalidation succeeds", func() {
Context("when the network rules file can be removed", func() {
It("removes the network rules file", func() {
fs.WriteFile("/etc/udev/rules.d/70-persistent-net.rules", []byte{})
resp, err := action.Run()
Expect(err).NotTo(HaveOccurred())
Expect(resp).To(Equal("ok"))
Expect(fs.FileExists("/etc/udev/rules.d/70-persistent-net.rules")).To(BeFalse())
})
})
Context("when the network rules file cannot be removed", func() {
BeforeEach(func() {
fs.RemoveAllError = errors.New("fake-remove-all-error")
})
It("returns error from removing the network rules file", func() {
resp, err := action.Run()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-remove-all-error"))
Expect(resp).To(BeNil())
})
})
})
Context("when settings invalidation fails", func() {
BeforeEach(func() {
settingsService.InvalidateSettingsError = errors.New("fake-invalidate-error")
})
It("returns error early if settings err invalidating", func() {
resp, err := action.Run()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-invalidate-error"))
Expect(resp).To(BeNil())
})
It("does not remove the network rules file", func() {
fs.WriteFile("/etc/udev/rules.d/70-persistent-net.rules", []byte{})
action.Run()
Expect(fs.FileExists("/etc/udev/rules.d/70-persistent-net.rules")).To(BeTrue())
})
})
})
}
示例6: describeLinuxPlatform
func describeLinuxPlatform() {
var (
collector *fakestats.FakeCollector
fs *fakesys.FakeFileSystem
cmdRunner *fakesys.FakeCmdRunner
diskManager *fakedisk.FakeDiskManager
dirProvider boshdirs.Provider
devicePathResolver *fakedpresolv.FakeDevicePathResolver
platform Platform
cdutil *fakedevutil.FakeDeviceUtil
compressor boshcmd.Compressor
copier boshcmd.Copier
vitalsService boshvitals.Service
netManager *fakenet.FakeManager
certManager *fakecert.FakeManager
monitRetryStrategy *fakeretry.FakeRetryStrategy
fakeDefaultNetworkResolver *fakenet.FakeDefaultNetworkResolver
options LinuxOptions
logger boshlog.Logger
)
BeforeEach(func() {
logger = boshlog.NewLogger(boshlog.LevelNone)
collector = &fakestats.FakeCollector{}
fs = fakesys.NewFakeFileSystem()
cmdRunner = fakesys.NewFakeCmdRunner()
diskManager = fakedisk.NewFakeDiskManager()
dirProvider = boshdirs.NewProvider("/fake-dir")
cdutil = fakedevutil.NewFakeDeviceUtil()
compressor = boshcmd.NewTarballCompressor(cmdRunner, fs)
copier = boshcmd.NewCpCopier(cmdRunner, fs, logger)
vitalsService = boshvitals.NewService(collector, dirProvider)
netManager = &fakenet.FakeManager{}
certManager = new(fakecert.FakeManager)
monitRetryStrategy = fakeretry.NewFakeRetryStrategy()
devicePathResolver = fakedpresolv.NewFakeDevicePathResolver()
fakeDefaultNetworkResolver = &fakenet.FakeDefaultNetworkResolver{}
options = LinuxOptions{}
fs.SetGlob("/sys/bus/scsi/devices/*:0:0:0/block/*", []string{
"/sys/bus/scsi/devices/0:0:0:0/block/sr0",
"/sys/bus/scsi/devices/6:0:0:0/block/sdd",
"/sys/bus/scsi/devices/fake-host-id:0:0:0/block/sda",
})
fs.SetGlob("/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/*", []string{
"/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/sdf",
})
})
JustBeforeEach(func() {
platform = NewLinuxPlatform(
fs,
cmdRunner,
collector,
compressor,
copier,
dirProvider,
vitalsService,
cdutil,
diskManager,
netManager,
certManager,
monitRetryStrategy,
devicePathResolver,
5*time.Millisecond,
options,
logger,
fakeDefaultNetworkResolver,
)
})
Describe("SetupRuntimeConfiguration", func() {
It("setups runtime configuration", func() {
err := platform.SetupRuntimeConfiguration()
Expect(err).NotTo(HaveOccurred())
Expect(len(cmdRunner.RunCommands)).To(Equal(1))
Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"bosh-agent-rc"}))
})
})
Describe("CreateUser", func() {
It("creates user", func() {
expectedUseradd := []string{
"useradd",
"-m",
"-b", "/some/path/to/home",
"-s", "/bin/bash",
"-p", "bar-pwd",
"foo-user",
}
err := platform.CreateUser("foo-user", "bar-pwd", "/some/path/to/home")
Expect(err).NotTo(HaveOccurred())
basePathStat := fs.GetFileTestStat("/some/path/to/home")
Expect(basePathStat.FileType).To(Equal(fakesys.FakeFileTypeDir))
//.........这里部分代码省略.........
示例7: init
func init() {
Describe("execCmdRunner", func() {
var (
runner CmdRunner
)
BeforeEach(func() {
runner = NewExecCmdRunner(boshlog.NewLogger(boshlog.LevelNone))
})
Describe("RunComplexCommand", func() {
It("run complex command with working directory", func() {
cmd := Command{
Name: "ls",
Args: []string{"-l"},
WorkingDir: ".",
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(ContainSubstring("exec_cmd_runner_fixtures"))
Expect(stdout).To(ContainSubstring("total"))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("run complex command with env", func() {
cmd := Command{
Name: "env",
Env: map[string]string{
"FOO": "BAR",
},
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(ContainSubstring("FOO=BAR"))
Expect(stdout).To(ContainSubstring("PATH="))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("runs complex command with specific env", func() {
cmd := Command{
Name: "env",
Env: map[string]string{
"FOO": "BAR",
},
UseIsolatedEnv: true,
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(ContainSubstring("FOO=BAR"))
Expect(stdout).ToNot(ContainSubstring("PATH="))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("run complex command with stdin", func() {
input := "This is STDIN\nWith another line."
cmd := Command{
Name: "cat",
Args: []string{"/dev/stdin"},
Stdin: strings.NewReader(input),
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal(input))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("prints stdout/stderr to provided I/O object", func() {
fs := fakesys.NewFakeFileSystem()
stdoutFile, err := fs.OpenFile("/fake-stdout-path", os.O_RDWR, os.FileMode(0644))
Expect(err).ToNot(HaveOccurred())
stderrFile, err := fs.OpenFile("/fake-stderr-path", os.O_RDWR, os.FileMode(0644))
Expect(err).ToNot(HaveOccurred())
cmd := Command{
Name: "bash",
Args: []string{"-c", "echo fake-out >&1; echo fake-err >&2"},
Stdout: stdoutFile,
Stderr: stderrFile,
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(BeEmpty())
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
stdoutContents := make([]byte, 1024)
_, err = stdoutFile.Read(stdoutContents)
Expect(err).ToNot(HaveOccurred())
Expect(string(stdoutContents)).To(ContainSubstring("fake-out"))
stderrContents := make([]byte, 1024)
_, err = stderrFile.Read(stderrContents)
Expect(err).ToNot(HaveOccurred())
//.........这里部分代码省略.........
示例8: init
func init() {
Describe("concreteCompiler", func() {
var (
compiler Compiler
compressor *fakecmd.FakeCompressor
blobstore *fakeblobstore.FakeBlobstore
fs *fakesys.FakeFileSystem
runner *fakecmdrunner.FakeFileLoggingCmdRunner
packageApplier *fakepackages.FakeApplier
packagesBc *fakebc.FakeBundleCollection
)
BeforeEach(func() {
compressor = fakecmd.NewFakeCompressor()
blobstore = &fakeblobstore.FakeBlobstore{}
fs = fakesys.NewFakeFileSystem()
runner = fakecmdrunner.NewFakeFileLoggingCmdRunner()
packageApplier = fakepackages.NewFakeApplier()
packagesBc = fakebc.NewFakeBundleCollection()
compiler = NewConcreteCompiler(
compressor,
blobstore,
fs,
runner,
FakeCompileDirProvider{Dir: "/fake-compile-dir"},
packageApplier,
packagesBc,
)
})
BeforeEach(func() {
fs.MkdirAll("/fake-compile-dir", os.ModePerm)
})
Describe("Compile", func() {
var (
bundle *fakebc.FakeBundle
pkg Package
pkgDeps []boshmodels.Package
)
BeforeEach(func() {
bundle = packagesBc.FakeGet(boshmodels.Package{
Name: "pkg_name",
Version: "pkg_version",
})
bundle.InstallPath = "/fake-dir/data/packages/pkg_name/pkg_version"
bundle.EnablePath = "/fake-dir/packages/pkg_name"
compressor.CompressFilesInDirTarballPath = "/tmp/compressed-compiled-package"
pkg, pkgDeps = getCompileArgs()
})
It("returns blob id and sha1 of created compiled package", func() {
blobstore.CreateBlobID = "fake-blob-id"
blobstore.CreateFingerprint = "fake-blob-sha1"
blobID, sha1, err := compiler.Compile(pkg, pkgDeps)
Expect(err).ToNot(HaveOccurred())
Expect(blobID).To(Equal("fake-blob-id"))
Expect(sha1).To(Equal("fake-blob-sha1"))
})
It("cleans up all packages before and after applying dependent packages", func() {
_, _, err := compiler.Compile(pkg, pkgDeps)
Expect(err).ToNot(HaveOccurred())
Expect(packageApplier.ActionsCalled).To(Equal([]string{"KeepOnly", "Apply", "Apply", "KeepOnly"}))
Expect(packageApplier.KeptOnlyPackages).To(BeEmpty())
})
It("returns an error if cleaning up packages fails", func() {
packageApplier.KeepOnlyErr = errors.New("fake-keep-only-error")
_, _, err := compiler.Compile(pkg, pkgDeps)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-keep-only-error"))
})
It("fetches source package from blobstore without checking SHA1 by default because of Director bug", func() {
_, _, err := compiler.Compile(pkg, pkgDeps)
Expect(err).ToNot(HaveOccurred())
Expect(blobstore.GetBlobIDs[0]).To(Equal("blobstore_id"))
Expect(blobstore.GetFingerprints[0]).To(Equal(""))
})
PIt("(Pending Tracker Story: <https://www.pivotaltracker.com/story/show/94524232>) fetches source package from blobstore and checks SHA1 by default in future", func() {
_, _, err := compiler.Compile(pkg, pkgDeps)
Expect(err).ToNot(HaveOccurred())
Expect(blobstore.GetBlobIDs[0]).To(Equal("blobstore_id"))
Expect(blobstore.GetFingerprints[0]).To(Equal("sha1"))
})
It("returns an error if removing compile target directory during uncompression fails", func() {
fs.RegisterRemoveAllError("/fake-compile-dir/pkg_name", errors.New("fake-remove-error"))
//.........这里部分代码省略.........
示例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:
It("writes", func() {
blobManager := NewBlobManager(fs, basePath)
fs.WriteFileString(blobPath, "some data")
defer fs.RemoveAll(blobPath)
err := blobManager.Write(blobId, toWrite)
Expect(err).ToNot(HaveOccurred())
contents, err := fs.ReadFileString(blobPath)
Expect(err).ToNot(HaveOccurred())
Expect(contents).To(Equal("new data"))
})
Context("when it writes", func() {
It("creates and closes the file", func() {
fs_ := boshsysfake.NewFakeFileSystem()
blobManager := NewBlobManager(fs_, basePath)
err := blobManager.Write(blobId, toWrite)
Expect(err).ToNot(HaveOccurred())
fileStats, err := fs_.FindFileStats(blobPath)
Expect(err).ToNot(HaveOccurred())
Expect(fileStats.Open).To(BeFalse())
})
It("creates file with correct permissions", func() {
fs_ := boshsysfake.NewFakeFileSystem()
blobManager := NewBlobManager(fs_, basePath)
err := blobManager.Write(blobId, toWrite)
fileStats, err := fs_.FindFileStats(blobPath)
Expect(err).ToNot(HaveOccurred())
Expect(fileStats.FileMode).To(Equal(os.FileMode(0666)))
Expect(fileStats.Flags).To(Equal(os.O_WRONLY | os.O_CREATE | os.O_TRUNC))
示例11: createBlobManager
func createBlobManager() (blobManager BlobManager, fs *fakesys.FakeFileSystem) {
fs = fakesys.NewFakeFileSystem()
blobManager = NewBlobManager(fs, "/var/vcap/micro_bosh/data/cache")
return
}
示例12: describeCentosNetManager
func describeCentosNetManager() {
var (
fs *fakesys.FakeFileSystem
cmdRunner *fakesys.FakeCmdRunner
ipResolver *fakeip.FakeResolver
addressBroadcaster *fakearp.FakeAddressBroadcaster
netManager Manager
interfaceConfigurationCreator InterfaceConfigurationCreator
)
BeforeEach(func() {
fs = fakesys.NewFakeFileSystem()
cmdRunner = fakesys.NewFakeCmdRunner()
ipResolver = &fakeip.FakeResolver{}
logger := boshlog.NewLogger(boshlog.LevelNone)
interfaceConfigurationCreator = NewInterfaceConfigurationCreator(logger)
addressBroadcaster = &fakearp.FakeAddressBroadcaster{}
netManager = NewCentosNetManager(
fs,
cmdRunner,
ipResolver,
interfaceConfigurationCreator,
addressBroadcaster,
logger,
)
})
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
}
Describe("SetupNetworking", func() {
var (
dhcpNetwork boshsettings.Network
staticNetwork boshsettings.Network
expectedNetworkConfigurationForStatic string
expectedNetworkConfigurationForDHCP string
expectedDhclientConfiguration string
)
BeforeEach(func() {
dhcpNetwork = boshsettings.Network{
Type: "dynamic",
Default: []string{"dns"},
DNS: []string{"8.8.8.8", "9.9.9.9"},
Mac: "fake-dhcp-mac-address",
}
staticNetwork = boshsettings.Network{
Type: "manual",
IP: "1.2.3.4",
Netmask: "255.255.255.0",
Gateway: "3.4.5.6",
Mac: "fake-static-mac-address",
}
expectedNetworkConfigurationForStatic = `DEVICE=ethstatic
BOOTPROTO=static
IPADDR=1.2.3.4
NETMASK=255.255.255.0
BROADCAST=1.2.3.255
GATEWAY=3.4.5.6
ONBOOT=yes
PEERDNS=no
DNS1=8.8.8.8
DNS2=9.9.9.9
`
expectedNetworkConfigurationForDHCP = `DEVICE=ethdhcp
BOOTPROTO=dhcp
ONBOOT=yes
PEERDNS=yes
`
expectedDhclientConfiguration = `# Generated by bosh-agent
option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
send host-name "<hostname>";
request subnet-mask, broadcast-address, time-offset, routers,
domain-name, domain-name-servers, domain-search, host-name,
netbios-name-servers, netbios-scope, interface-mtu,
rfc3442-classless-static-routes, ntp-servers;
prepend domain-name-servers 8.8.8.8, 9.9.9.9;
`
})
stubInterfacesWithVirtual := func(physicalInterfaces map[string]boshsettings.Network, virtualInterfaces []string) {
interfacePaths := []string{}
for iface, networkSettings := range physicalInterfaces {
interfacePaths = append(interfacePaths, writeNetworkDevice(iface, networkSettings.Mac, true))
//.........这里部分代码省略.........
示例13: JobChange
func (p fakeParams) JobChange() (change string) { return p.jobChange }
func (p fakeParams) HashChange() (change string) { return p.hashChange }
func (p fakeParams) UpdatedPackages() (pkgs []string) { return p.updatedPackages }
func (p fakeParams) JobState() (string, error) { return p.jobState, p.jobStateErr }
func (p fakeParams) JobNextState() (string, error) { return p.jobNextState, p.jobNextStateErr }
var _ = Describe("ConcreteScript", func() {
var (
runner *fakesys.FakeCmdRunner
fs *fakesys.FakeFileSystem
script ConcreteScript
)
BeforeEach(func() {
fs = fakesys.NewFakeFileSystem()
runner = fakesys.NewFakeCmdRunner()
script = NewConcreteScript(fs, runner, "/fake/script")
})
Describe("Run", func() {
var (
params fakeParams
)
BeforeEach(func() {
params = fakeParams{
jobChange: "job_shutdown",
hashChange: "hash_unchanged",
updatedPackages: []string{"foo", "bar"},
}
示例14: init
func init() {
Describe("compiledPackageApplier", func() {
var (
packagesBc *fakebc.FakeBundleCollection
blobstore *fakeblob.FakeBlobstore
compressor *fakecmd.FakeCompressor
fs *fakesys.FakeFileSystem
logger boshlog.Logger
applier Applier
)
BeforeEach(func() {
packagesBc = fakebc.NewFakeBundleCollection()
blobstore = fakeblob.NewFakeBlobstore()
compressor = fakecmd.NewFakeCompressor()
fs = fakesys.NewFakeFileSystem()
logger = boshlog.NewLogger(boshlog.LevelNone)
applier = NewCompiledPackageApplier(packagesBc, true, blobstore, compressor, fs, logger)
})
Describe("Prepare & Apply", func() {
var (
pkg models.Package
bundle *fakebc.FakeBundle
)
BeforeEach(func() {
pkg, bundle = buildPkg(packagesBc)
})
ItInstallsPkg := func(act func() error) {
It("returns error when installing package 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 package 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 package 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 package blob to tmp path and later cleans it up", func() {
fs.TempDirDir = "/fake-tmp-dir"
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")
err := act()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-filesystem-tempdir-error"))
})
It("returns error when decompressing package blob fails", func() {
compressor.DecompressFileToDirErr = errors.New("fake-decompress-error")
err := act()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-decompress-error"))
})
It("installs bundle from decompressed tmp path of a package blob", func() {
fs.TempDirDir = "/fake-tmp-dir"
//.........这里部分代码省略.........
示例15: 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()
//.........这里部分代码省略.........