本文整理匯總了Golang中github.com/cloudfoundry/bosh-utils/system/fakes.FakeFileSystem.WriteFileString方法的典型用法代碼示例。如果您正苦於以下問題:Golang FakeFileSystem.WriteFileString方法的具體用法?Golang FakeFileSystem.WriteFileString怎麽用?Golang FakeFileSystem.WriteFileString使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/cloudfoundry/bosh-utils/system/fakes.FakeFileSystem
的用法示例。
在下文中一共展示了FakeFileSystem.WriteFileString方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1:
BeforeEach(func() {
compressor = fakecmd.NewFakeCompressor()
fs = fakesys.NewFakeFileSystem()
stemcellReader = NewReader(compressor, fs)
manifestContents := `
---
name: fake-stemcell-name
version: '2690'
cloud_properties:
infrastructure: aws
ami:
us-east-1: fake-ami-version
`
fs.WriteFileString("fake-extracted-path/stemcell.MF", manifestContents)
})
It("extracts the stemcells from a stemcell path", func() {
_, err := stemcellReader.Read("fake-stemcell-path", "fake-extracted-path")
Expect(err).ToNot(HaveOccurred())
Expect(compressor.DecompressFileToDirTarballPaths).To(ContainElement("fake-stemcell-path"))
Expect(compressor.DecompressFileToDirDirs).To(ContainElement("fake-extracted-path"))
})
It("generates correct stemcell", func() {
stemcell, err := stemcellReader.Read("fake-stemcell-path", "fake-extracted-path")
Expect(err).ToNot(HaveOccurred())
expectedStemcell := NewExtractedStemcell(
Manifest{
Name: "fake-stemcell-name",
示例2:
result := cert.SplitCerts("abcdefghij")
Expect(len(result)).To(Equal(0))
})
})
Describe("DeleteFile()", func() {
var (
fakeFs *fakesys.FakeFileSystem
)
BeforeEach(func() {
fakeFs = fakesys.NewFakeFileSystem()
})
It("only deletes the files with the given prefix", func() {
fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye")
fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye")
fakeFs.WriteFileString("/path/to/delete/stuff/in/different_file_1.bar", "goodbye")
fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{
"/path/to/delete/stuff/in/delete_me_1.foo",
"/path/to/delete/stuff/in/delete_me_2.foo",
})
count, err := cert.DeleteFiles(fakeFs, "/path/to/delete/stuff/in/", "delete_me_")
Expect(err).ToNot(HaveOccurred())
Expect(count).To(Equal(2))
Expect(countFiles(fakeFs, "/path/to/delete/stuff/in/")).To(Equal(1))
})
It("only deletes the files in the given path", func() {
fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye")
fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye")
示例3:
fs = fakesys.NewFakeFileSystem()
logger := boshlog.NewLogger(boshlog.LevelNone)
metadataService = NewFileMetadataService(
"fake-metadata-file-path",
"fake-userdata-file-path",
"fake-settings-file-path",
fs,
logger,
)
})
Describe("GetInstanceID", func() {
Context("when metadata service file exists", func() {
BeforeEach(func() {
metadataContents := `{"instance-id":"fake-instance-id"}`
fs.WriteFileString("fake-metadata-file-path", metadataContents)
})
It("returns instance id", func() {
instanceID, err := metadataService.GetInstanceID()
Expect(err).NotTo(HaveOccurred())
Expect(instanceID).To(Equal("fake-instance-id"))
})
})
Context("when metadata service file does not exist", func() {
It("returns an error", func() {
_, err := metadataService.GetInstanceID()
Expect(err).To(HaveOccurred())
})
})
示例4:
fs.WriteFileString("/fake-config.conf", `{
"Platform": {
"Linux": {
"UseDefaultTmpDir": true,
"UsePreformattedPersistentDisk": true,
"BindMountPersistentDisk": true,
"DevicePathResolutionType": "virtio"
}
},
"Infrastructure": {
"Settings": {
"Sources": [
{
"Type": "HTTP",
"URI": "http://fake-uri"
},
{
"Type": "ConfigDrive",
"DiskPaths": ["/fake-disk-path1", "/fake-disk-path2"],
"MetaDataPath": "/fake-metadata-path",
"UserDataPath": "/fake-userdata-path",
"SettingsPath": "/fake-settings-path"
},
{
"Type": "File",
"MetaDataPath": "/fake-metadata-path",
"UserDataPath": "/fake-userdata-path",
"SettingsPath": "/fake-settings-path"
},
{
"Type": "CDROM",
"FileName": "/fake-file-name"
}
],
"UseServerName": true,
"UseRegistry": true
}
}
}`)
示例5:
Expect(disks).To(HaveLen(1))
Expect(disks[0].CID()).To(Equal("fake-existing-disk-cid"))
})
})
Context("when disk does not exists in disk repo", func() {
It("returns an empty array", func() {
disks, err := manager.FindCurrent()
Expect(err).ToNot(HaveOccurred())
Expect(disks).To(BeEmpty())
})
})
Context("when reading disk repo fails", func() {
BeforeEach(func() {
fakeFs.WriteFileString("/fake/path", "{}")
fakeFs.ReadFileError = errors.New("fake-read-error")
})
It("returns an error", func() {
_, err := manager.FindCurrent()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-read-error"))
})
})
})
Describe("FindUnused", func() {
var (
firstDisk bidisk.Disk
thirdDisk bidisk.Disk
示例6:
Describe("Start", func() {
It("start starts each monit service in group vcap", func() {
client.ServicesInGroupServices = []string{"fake-service"}
err := monit.Start()
Expect(err).ToNot(HaveOccurred())
Expect(client.ServicesInGroupName).To(Equal("vcap"))
Expect(len(client.StartServiceNames)).To(Equal(1))
Expect(client.StartServiceNames[0]).To(Equal("fake-service"))
})
It("deletes stopped file", func() {
fs.MkdirAll("/var/vcap/monit/stopped", os.FileMode(0755))
fs.WriteFileString("/var/vcap/monit/stopped", "")
err := monit.Start()
Expect(err).ToNot(HaveOccurred())
Expect(fs.FileExists("/var/vcap/monit/stopped")).ToNot(BeTrue())
})
It("does not fail if stopped file is not present", func() {
err := monit.Start()
Expect(err).ToNot(HaveOccurred())
})
})
Describe("Stop", func() {
It("stop stops each monit service in group vcap", func() {
client.ServicesInGroupServices = []string{"fake-service"}
示例7:
})
})
})
})
Describe("ChmodExecutables", func() {
var (
binGlob string
filePath string
)
BeforeEach(func() {
binGlob = "fake-glob/*"
filePath = "fake-glob/file"
fs.SetGlob("fake-glob/*", []string{filePath})
fs.WriteFileString(filePath, "content")
})
It("fetches the files", func() {
fileMode := fs.GetFileTestStat(filePath).FileMode
Expect(fileMode).To(Equal(os.FileMode(0)))
err := extractor.ChmodExecutables(binGlob)
Expect(err).ToNot(HaveOccurred())
fileMode = fs.GetFileTestStat(filePath).FileMode
Expect(fileMode).To(Equal(os.FileMode(0755)))
})
})
})
示例8:
BeforeEach(func() {
compressor = fakecmd.NewFakeCompressor()
fakeFs = fakesys.NewFakeFileSystem()
reader = NewReader("/some/job/archive", "/extracted/job", compressor, fakeFs)
})
Context("when the job archive is a valid tar", func() {
Context("when the job manifest is valid", func() {
BeforeEach(func() {
fakeFs.WriteFileString(
"/extracted/job/job.MF",
`---
name: fake-job
templates:
some_template: some_file
packages:
- fake-package
properties:
fake-property:
description: "Fake description"
default: "fake-default"
`,
)
})
It("returns a job with the details from the manifest", func() {
job, err := reader.Read()
Expect(err).NotTo(HaveOccurred())
Expect(job).To(Equal(
Job{
Name: "fake-job",
Templates: map[string]string{"some_template": "some_file"},
示例9: describeDummyPlatform
func describeDummyPlatform() {
var (
platform Platform
collector boshstats.Collector
fs *fakesys.FakeFileSystem
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())
})
})
Describe("UnmountPersistentDisk", func() {
Context("when there are two mounted persistent disks in the mounts json", func() {
BeforeEach(func() {
var mounts []mount
mounts = append(mounts, mount{MountDir: "dir1", DiskCid: "cid1"})
mounts = append(mounts, mount{MountDir: "dir2", DiskCid: "cid2"})
mountsJSON, _ := json.Marshal(mounts)
mountsPath := path.Join(dirProvider.BoshDir(), "mounts.json")
fs.WriteFile(mountsPath, mountsJSON)
})
It("removes one of the disks from the mounts json", func() {
unmounted, err := platform.UnmountPersistentDisk(settings.DiskSettings{ID: "cid1"})
Expect(err).NotTo(HaveOccurred())
Expect(unmounted).To(Equal(true))
_, isMountPoint, err := platform.IsMountPoint("dir1")
Expect(isMountPoint).To(Equal(false))
_, isMountPoint, err = platform.IsMountPoint("dir2")
Expect(isMountPoint).To(Equal(true))
})
})
})
Describe("SetUserPassword", func() {
It("writes the password to a file", func() {
err := platform.SetUserPassword("user-name", "fake-password")
Expect(err).NotTo(HaveOccurred())
userPasswordsPath := path.Join(dirProvider.BoshDir(), "user-name", CredentialFileName)
password, err := fs.ReadFileString(userPasswordsPath)
Expect(err).NotTo(HaveOccurred())
Expect(password).To(Equal("fake-password"))
})
It("writes the passwords to different files for each user", func() {
err := platform.SetUserPassword("user-name1", "fake-password1")
Expect(err).NotTo(HaveOccurred())
err = platform.SetUserPassword("user-name2", "fake-password2")
Expect(err).NotTo(HaveOccurred())
userPasswordsPath := path.Join(dirProvider.BoshDir(), "user-name1", CredentialFileName)
password, err := fs.ReadFileString(userPasswordsPath)
Expect(err).NotTo(HaveOccurred())
Expect(password).To(Equal("fake-password1"))
//.........這裏部分代碼省略.........
示例10:
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Not supported"))
})
Context("when sync_dns is recieved", func() {
Context("when blobstore contains DNS records", func() {
BeforeEach(func() {
fakeDNSRecordsString := `
{
"records": [
["fake-ip0", "fake-name0"],
["fake-ip1", "fake-name1"]
]
}`
err := fakeFileSystem.WriteFileString("fake-blobstore-file-path", fakeDNSRecordsString)
Expect(err).ToNot(HaveOccurred())
fakeBlobstore.GetFileName = "fake-blobstore-file-path"
})
It("accesses the blobstore and fetches DNS records", func() {
response, err := syncDNS.Run("fake-blobstore-id", "fake-fingerprint")
Expect(err).ToNot(HaveOccurred())
Expect(response).To(Equal("synced"))
Expect(fakeBlobstore.GetBlobIDs).To(ContainElement("fake-blobstore-id"))
Expect(fakeBlobstore.GetFingerprints).To(ContainElement("fake-fingerprint"))
Expect(fakeBlobstore.GetError).ToNot(HaveOccurred())
Expect(fakeBlobstore.GetFileName).ToNot(Equal(""))
示例11:
cache Cache
fs *fakesys.FakeFileSystem
)
BeforeEach(func() {
logger := boshlog.NewLogger(boshlog.LevelNone)
fs = fakesys.NewFakeFileSystem()
cache = NewCache(
"/fake-base-path",
fs,
logger,
)
})
It("is a cache hit when the tarball with that url and sha1 has been downloaded", func() {
fs.WriteFileString("source-path", "")
err := cache.Save("source-path", &fakeSource{
sha1: "fake-sha1",
url: "http://foo.bar.com",
description: "some tarball",
})
Expect(err).ToNot(HaveOccurred())
path, found := cache.Get(&fakeSource{
sha1: "fake-sha1",
url: "http://foo.bar.com",
description: "some tarball",
})
Expect(found).To(BeTrue())
Expect(fs.FileExists(path)).To(BeTrue())
示例12: describeUbuntuNetManager
func describeUbuntuNetManager() {
var (
fs *fakesys.FakeFileSystem
cmdRunner *fakesys.FakeCmdRunner
ipResolver *fakeip.FakeResolver
addressBroadcaster *fakearp.FakeAddressBroadcaster
interfaceAddrsProvider *fakeip.FakeInterfaceAddressesProvider
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{}
interfaceAddrsProvider = &fakeip.FakeInterfaceAddressesProvider{}
interfaceAddrsValidator := boship.NewInterfaceAddressesValidator(interfaceAddrsProvider)
dnsValidator := NewDNSValidator(fs)
netManager = NewUbuntuNetManager(
fs,
cmdRunner,
ipResolver,
interfaceConfigurationCreator,
interfaceAddrsValidator,
dnsValidator,
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"}))
})
})
//.........這裏部分代碼省略.........
示例13:
fakeFs = fakesys.NewFakeFileSystem()
logger := boshlog.NewLogger(boshlog.LevelNone)
fakeValidator = fakes.NewFakeValidator()
fakeValidator.SetValidateBehavior([]fakes.ValidateOutput{
{Err: nil},
})
parser = manifest.NewParser(fakeFs, logger, fakeValidator)
fakeFs.WriteFileString(comboManifestPath, `
---
releases:
- name: fake-release-name-1
url: file://~/absolute-path/fake-release-1.tgz
sha1: fake-sha1
- name: fake-release-name-2
url: file:///absolute-path/fake-release-2.tgz
sha1: fake-sha2
- name: fake-release-name-3
url: file://relative-path/fake-release-3.tgz
sha1: fake-sha3
- name: fake-release-name-4
url: http://fake-url/fake-release-4.tgz
sha1: fake-sha4
name: unknown-keys-are-ignored
`)
})
Context("when combo manifest path does not exist", func() {
BeforeEach(func() {
err := fakeFs.RemoveAll(comboManifestPath)
Expect(err).ToNot(HaveOccurred())
})
示例14:
failureHandler := func(alert boshalert.MonitAlert) (err error) {
didHandleAlert = true
return
}
go monit.MonitorJobFailures(failureHandler)
err := doJobFailureEmail(`fake-other-email`, jobFailuresServerPort)
Expect(err).ToNot(HaveOccurred())
Expect(didHandleAlert).To(BeFalse())
})
})
Describe("AddJob", func() {
BeforeEach(func() {
fs.WriteFileString("/some/config/path", "fake-config")
})
Context("when reading configuration from config path succeeds", func() {
Context("when writing job configuration succeeds", func() {
It("returns no error because monit can track added job in jobs directory", func() {
err := monit.AddJob("router", 0, "/some/config/path")
Expect(err).ToNot(HaveOccurred())
writtenConfig, err := fs.ReadFileString(
dirProvider.MonitJobsDir() + "/0000_router.monitrc")
Expect(err).ToNot(HaveOccurred())
Expect(writtenConfig).To(Equal("fake-config"))
})
})
示例15:
Expect(err.Error()).To(ContainSubstring("missing blobstore_path"))
})
It("returns error when blobstore path is not a string", func() {
options := map[string]interface{}{"blobstore_path": 443}
blobstore = NewLocalBlobstore(fs, uuidGen, options)
err := blobstore.Validate()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("blobstore_path must be a string"))
})
})
Describe("Get", func() {
It("fetches the local blob contents", func() {
fs.WriteFileString(fakeBlobstorePath+"/fake-blob-id", "fake contents")
tempFile, err := fs.TempFile("bosh-blobstore-local-TestLocalGet")
Expect(err).ToNot(HaveOccurred())
fs.ReturnTempFile = tempFile
defer fs.RemoveAll(tempFile.Name())
_, err = blobstore.Get("fake-blob-id", "")
Expect(err).ToNot(HaveOccurred())
fileStats := fs.GetFileTestStat(tempFile.Name())
Expect(fileStats).ToNot(BeNil())
Expect("fake contents").To(Equal(fileStats.StringContents()))
})