本文整理匯總了Golang中github.com/cloudfoundry/bosh-utils/system/fakes.FakeFileSystem.ReadFileString方法的典型用法代碼示例。如果您正苦於以下問題:Golang FakeFileSystem.ReadFileString方法的具體用法?Golang FakeFileSystem.ReadFileString怎麽用?Golang FakeFileSystem.ReadFileString使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/cloudfoundry/bosh-utils/system/fakes.FakeFileSystem
的用法示例。
在下文中一共展示了FakeFileSystem.ReadFileString方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1:
err = logFile.Close()
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
logFile.Close()
fs.RemoveAll(logFile.Name())
})
It("logs the formatted DEBUG message to the file", func() {
logger, logFile, err := New(boshlog.LevelDebug, logFile.Name(), DefaultLogFileMode, fs)
Expect(err).ToNot(HaveOccurred())
logger.Debug("TAG", "some %s info to log", "awesome")
contents, err := fs.ReadFileString(logFile.Name())
Expect(err).ToNot(HaveOccurred())
expectedContent := expectedLogFormat("TAG", "DEBUG - some awesome info to log")
Expect(contents).To(MatchRegexp(expectedContent))
})
It("logs the formatted INFO message to the file", func() {
logger, logFile, err := New(boshlog.LevelDebug, logFile.Name(), DefaultLogFileMode, fs)
Expect(err).ToNot(HaveOccurred())
logger.Info("TAG", "some %s info to log", "awesome")
contents, err := fs.ReadFileString(logFile.Name())
Expect(err).ToNot(HaveOccurred())
示例2:
configPath = filepath.Join("/etc/", "blobstore-fake-provider.json")
blobstore = NewExternalBlobstore("fake-provider", map[string]interface{}{}, fs, runner, uuidGen, configPath)
})
Describe("Validate", func() {
It("external validate writes config file", func() {
options := map[string]interface{}{"fake-key": "fake-value"}
blobstore := NewExternalBlobstore("fake-provider", options, fs, runner, uuidGen, configPath)
runner.CommandExistsValue = true
err := blobstore.Validate()
Expect(err).ToNot(HaveOccurred())
s3CliConfig, err := fs.ReadFileString(configPath)
Expect(err).ToNot(HaveOccurred())
expectedJSON := map[string]string{"fake-key": "fake-value"}
boshassert.MatchesJSONString(GinkgoT(), expectedJSON, s3CliConfig)
})
It("external validate errors when command not in path", func() {
options := map[string]interface{}{}
blobstore := NewExternalBlobstore("fake-provider", options, fs, runner, uuidGen, configPath)
err := blobstore.Validate()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("not found in PATH"))
})
示例3: 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"))
//.........這裏部分代碼省略.........
示例4:
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"))
})
})
Context("when writing job configuration fails", func() {
It("returns error", func() {
fs.WriteFileError = errors.New("fake-write-error")
err := monit.AddJob("router", 0, "/some/config/path")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-write-error"))
})
})
})
示例5:
cmdRunner.AddCmdResult("/path-to-script", fakesys.FakeCmdResult{
Stdout: "fake-stdout",
Stderr: "fake-stderr",
ExitStatus: 0,
Error: nil,
})
})
It("saves stdout/stderr to log file", func() {
err := genericScript.Run()
Expect(err).ToNot(HaveOccurred())
Expect(fs.FileExists(stdoutLogPath)).To(BeTrue())
Expect(fs.FileExists(stderrLogPath)).To(BeTrue())
stdout, err := fs.ReadFileString(stdoutLogPath)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal("fake-stdout"))
stderr, err := fs.ReadFileString(stderrLogPath)
Expect(err).ToNot(HaveOccurred())
Expect(stderr).To(Equal("fake-stderr"))
})
})
Context("when command fails", func() {
BeforeEach(func() {
cmdRunner.AddCmdResult("/path-to-script", fakesys.FakeCmdResult{
Stdout: "fake-stdout",
Stderr: "fake-stderr",
ExitStatus: 1,
示例6:
Stderr: []byte("fake-stderr"),
ExitStatus: 0,
}
result, err := runner.RunCommand("fake-log-dir-name", "fake-log-file-name", cmd)
Expect(err).ToNot(HaveOccurred())
Expect(result).To(Equal(expectedResult))
})
It("saves stdout to log file", func() {
_, err := runner.RunCommand("fake-log-dir-name", "fake-log-file-name", cmd)
Expect(err).ToNot(HaveOccurred())
Expect(fs.FileExists("/fake-base-dir/fake-log-dir-name/fake-log-file-name.stdout.log")).To(BeTrue())
stdout, err := fs.ReadFileString("/fake-base-dir/fake-log-dir-name/fake-log-file-name.stdout.log")
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal("fake-stdout"))
})
It("saves stderr to log file", func() {
_, err := runner.RunCommand("fake-log-dir-name", "fake-log-file-name", cmd)
Expect(err).ToNot(HaveOccurred())
Expect(fs.FileExists("/fake-base-dir/fake-log-dir-name/fake-log-file-name.stderr.log")).To(BeTrue())
stdout, err := fs.ReadFileString("/fake-base-dir/fake-log-dir-name/fake-log-file-name.stderr.log")
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal("fake-stderr"))
})
})
示例7:
err := fs.MkdirAll("fake-device-path", os.FileMode(0750))
Expect(err).ToNot(HaveOccurred())
err = fs.Symlink("fake-device-path", "/dev/disk/by-id/scsi-3"+id)
Expect(err).ToNot(HaveOccurred())
})
It("returns the path", func() {
path, timeout, err := pathResolver.GetRealDevicePath(diskSettings)
Expect(err).ToNot(HaveOccurred())
Expect(path).To(Equal("fake-device-path"))
Expect(timeout).To(BeFalse())
for _, host := range hosts {
str, _ := fs.ReadFileString(host)
Expect(str).To(Equal("- - -"))
}
})
})
Context("when path does not exist", func() {
BeforeEach(func() {
err := fs.Symlink("fake-device-path", "/dev/disk/by-id/scsi-3"+id)
Expect(err).ToNot(HaveOccurred())
})
It("returns an error", func() {
_, _, err := pathResolver.GetRealDevicePath(diskSettings)
Expect(err).To(HaveOccurred())
})
示例8:
It("runs a successful script command and doesnt return an error", func() {
script := `
Write-Output stdout
[Console]::Error.WriteLine('stderr')
`
cmdRunner.AddCmdResult("/fake-temp-file.fake-ext", fakesys.FakeCmdResult{
Stdout: "stdout",
Stderr: "stderr",
ExitStatus: 0,
})
var scriptContent string
cmdCallback := func() {
var err error
scriptContent, err = fs.ReadFileString("/fake-temp-file.fake-ext")
Expect(err).NotTo(HaveOccurred())
}
cmdRunner.SetCmdCallback("/fake-temp-file.fake-ext", cmdCallback)
stdout, stderr, err := scriptRunner.Run(script)
Expect(err).NotTo(HaveOccurred())
Expect(stdout).To(Equal("stdout"))
Expect(stderr).To(Equal("stderr"))
Expect(scriptContent).To(Equal(script))
})
It("runs a failing Powershell command and returns error", func() {
cmdRunner.AddCmdResult("/fake-temp-file.fake-ext", fakesys.FakeCmdResult{
Error: errors.New("failed"),
示例9:
})
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",
})
diskSettings = boshsettings.DiskSettings{
VolumeID: "fake-disk-id",
}
})
Describe("GetRealDevicePath", func() {
It("rescans the devices attached to the root disks scsi controller", func() {
resolver.GetRealDevicePath(diskSettings)
scanContents, err := fs.ReadFileString("/sys/class/scsi_host/hostfake-host-id/scan")
Expect(err).NotTo(HaveOccurred())
Expect(scanContents).To(Equal("- - -"))
})
It("detects device", func() {
devicePath, timedOut, err := resolver.GetRealDevicePath(diskSettings)
Expect(err).NotTo(HaveOccurred())
Expect(timedOut).To(BeFalse())
Expect(devicePath).To(Equal("/dev/sdf"))
})
Context("when device does not immediately appear", func() {
It("retries detection of device", func() {
fs.SetGlob("/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/*",
[]string{},
示例10:
It("updates the blob on the file system", func() {
fs.WriteFileString("/var/vcap/micro_bosh/data/cache/123-456-789", "Some data")
putBody := `Updated data`
putPayload := strings.NewReader(putBody)
request, err := http.NewRequest("PUT", serverURL+"/blobs/a5/123-456-789", putPayload)
Expect(err).ToNot(HaveOccurred())
httpResponse, err := httpClient.Do(request)
Expect(err).ToNot(HaveOccurred())
defer httpResponse.Body.Close()
Expect(httpResponse.StatusCode).To(Equal(201))
contents, err := fs.ReadFileString("/var/vcap/micro_bosh/data/cache/123-456-789")
Expect(err).ToNot(HaveOccurred())
Expect(contents).To(Equal("Updated data"))
})
Context("when manager errors", func() {
It("returns a 500 because of openfile error", func() {
fs.OpenFileErr = errors.New("oops")
putBody := `Updated data`
putPayload := strings.NewReader(putBody)
request, err := http.NewRequest("PUT", serverURL+"/blobs/a5/123-456-789", putPayload)
Expect(err).ToNot(HaveOccurred())
httpResponse, err := httpClient.Do(request)
示例11:
oldLocation = "/path/to/old_file"
newLocation = "/path/to/new_file"
fs.WriteFileString(oldLocation, "some content")
})
It("renames the file", func() {
Expect(fs.FileExists(oldLocation)).To(BeTrue())
Expect(fs.FileExists(newLocation)).To(BeFalse())
err := mover.Move(oldLocation, newLocation)
Expect(err).ToNot(HaveOccurred())
Expect(fs.FileExists(oldLocation)).To(BeFalse())
contents, err := fs.ReadFileString(newLocation)
Expect(err).ToNot(HaveOccurred())
Expect(contents).To(Equal("some content"))
})
Context("when Rename fails due to EXDEV error", func() {
BeforeEach(func() {
fs.RenameError = &os.LinkError{
Err: syscall.Errno(0x12),
}
})
It("moves the file", func() {
Expect(fs.FileExists(oldLocation)).To(BeTrue())
Expect(fs.FileExists(newLocation)).To(BeFalse())
示例12:
stemcell: default
migrated_from:
- name: baz-job
az: z5
azs:
- z3
- z4
templates:
- name: simple
release: foo-release
networks:
- name: default
default: [dns, gateway]
`
manifestContents, err := fs.ReadFileString(manifestPath)
Expect(err).ToNot(HaveOccurred())
Expect(manifestContents).To(Equal(expectedManifestContents))
expectedCloudConfigContents := `---
azs:
- name: z1
cloud_properties:
baz: qux
foo: bar
- name: z2
cloud_properties: {}
- name: z3
cloud_properties: {}
- name: z4
cloud_properties: {}
示例13: 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("returns a dummy cert manager", func() {
certManager := platform.GetCertManager()
Expect(certManager.UpdateCertificates("")).Should(BeNil())
})
})
Describe("MountPersistentDisk", func() {
var diskSettings boshsettings.DiskSettings
var mountsPath, managedSettingsPath, formattedDisksPath string
BeforeEach(func() {
diskSettings = boshsettings.DiskSettings{ID: "somediskid"}
mountsPath = filepath.Join(dirProvider.BoshDir(), "mounts.json")
managedSettingsPath = filepath.Join(dirProvider.BoshDir(), "managed_disk_settings.json")
formattedDisksPath = filepath.Join(dirProvider.BoshDir(), "formatted_disks.json")
})
It("Mounts a persistent disk", func() {
mountsContent, _ := fs.ReadFileString(mountsPath)
Expect(mountsContent).To(Equal(""))
err := platform.MountPersistentDisk(diskSettings, "/dev/potato")
Expect(err).NotTo(HaveOccurred())
mountsContent, _ = fs.ReadFileString(mountsPath)
Expect(mountsContent).To(Equal(`[{"MountDir":"/dev/potato","DiskCid":"somediskid"}]`))
})
It("Updates the managed disk settings", func() {
lastMountedCid, _ := fs.ReadFileString(managedSettingsPath)
Expect(lastMountedCid).To(Equal(""))
err := platform.MountPersistentDisk(diskSettings, "/dev/potato")
Expect(err).NotTo(HaveOccurred())
lastMountedCid, _ = fs.ReadFileString(managedSettingsPath)
Expect(lastMountedCid).To(Equal("somediskid"))
})
It("Updates the formatted disks", func() {
formattedDisks, _ := fs.ReadFileString(formattedDisksPath)
Expect(formattedDisks).To(Equal(""))
err := platform.MountPersistentDisk(diskSettings, "/dev/potato")
Expect(err).NotTo(HaveOccurred())
formattedDisks, _ = fs.ReadFileString(formattedDisksPath)
Expect(formattedDisks).To(Equal(`[{"DiskCid":"somediskid"}]`))
})
Context("Device has already been mounted as expected", func() {
BeforeEach(func() {
fs.WriteFileString(managedSettingsPath, "somediskid")
fs.WriteFileString(mountsPath, `[{"MountDir":"/dev/potato","DiskCid":"somediskid"}]`)
})
//.........這裏部分代碼省略.........
示例14:
})
It("deletes the legacy deployment state file", func() {
migrated, err := migrator.MigrateIfExists(legacyDeploymentStateFilePath)
Expect(migrated).To(BeTrue())
Expect(err).ToNot(HaveOccurred())
Expect(fakeFs.FileExists(legacyDeploymentStateFilePath)).To(BeFalse())
})
It("uses the legacy UUID as the director_uuid in the new deployment manifest", func() {
migrated, err := migrator.MigrateIfExists(legacyDeploymentStateFilePath)
Expect(migrated).To(BeTrue())
Expect(err).ToNot(HaveOccurred())
content, err := fakeFs.ReadFileString(modernDeploymentStateFilePath)
Expect(err).ToNot(HaveOccurred())
Expect(content).To(MatchRegexp(`{
"director_id": "bm-5480c6bb-3ba8-449a-a262-a2e75fbe5daf",
"installation_id": "",
"current_vm_cid": "",
"current_stemcell_id": "",
"current_disk_id": "",
"current_release_ids": null,
"current_manifest_sha1": "",
"disks": \[\],
"stemcells": \[\],
"releases": \[\]
}`))
})
示例15:
Expect(fakeDavClient.GetPath).To(Equal("fake-blob-id"))
})
It("saves the blob to the destination path", func() {
fakeDavClient.GetContents = ioutil.NopCloser(strings.NewReader("fake-content"))
localBlob, err := blobstore.Get("fake-blob-id")
Expect(err).ToNot(HaveOccurred())
defer func() {
err := localBlob.Delete()
Expect(err).ToNot(HaveOccurred())
}()
Expect(localBlob.Path()).To(Equal("fake-destination-path"))
contents, err := fs.ReadFileString("fake-destination-path")
Expect(err).ToNot(HaveOccurred())
Expect(contents).To(Equal("fake-content"))
})
Context("when getting from blobstore fails", func() {
It("returns an error", func() {
fakeDavClient.GetErr = errors.New("fake-get-error")
_, err := blobstore.Get("fake-blob-id")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("fake-get-error"))
})
})
})