Golang TempFile示例

说明

golang tempfile示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: io/ioutil

示例#1
文件: lzhuf.go 项目: LA3QMA/wl2k-go

//TODO:
// * Modify lzhuf.c's Encode() so we don't have to use temp files.
// * Handle go errors.
func encDec(data []byte, encode bool) []byte {
	// Create temp files
	outf, _ := ioutil.TempFile("", "lzhuf")
	inf, _ := ioutil.TempFile("", "lzhuf")
	defer func() {
		outf.Close()
		os.Remove(outf.Name())
		os.Remove(inf.Name())
	}()

	// Copy data to in file
	io.Copy(inf, bytes.NewBuffer(data))
	inf.Sync()
	inf.Close()

	// Encode/Decode the inf to outf
	lzs := C.AllocStruct()
	var retval C.int
	if encode {
		retval = C.Encode(0, C.CString(inf.Name()), C.CString(outf.Name()), lzs, 1)
	} else {
		retval = C.Decode(0, C.CString(inf.Name()), C.CString(outf.Name()), lzs, 1)
	}
	C.FreeStruct(lzs)

	if retval < 0 {
		panic("lzhuf encode/decode error")
	}

	// Read the compressed/decompressed data from outf
	b, _ := ioutil.ReadAll(outf)

	return b
}

示例#2
文件: engine_test.go 项目: jeady/lmk

func build_config(
	rules string,
	c *C) (conf string, cleanup func()) {
	var fconf, rconf *os.File
	var err error
	var conf_test Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	cleanup = func() {
		fconf.Close()
		rconf.Close()
	}

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString(
		"[Settings]\nloglevel=debug\nrules=" + rconf.Name() + "\n")
	fconf.Sync()
	rconf.WriteString(rules + "\n")
	rconf.Sync()

	conf_test, err = NewFileConfig(fconf.Name())
	c.Assert(conf_test, Not(Equals), nil)
	c.Assert(err, Equals, nil)

	conf = fconf.Name()
	return
}

示例#3
文件: loader_test.go 项目: brorhie/panamax-kubernetes-adapter-go

func TestConflictingCurrentContext(t *testing.T) {
	commandLineFile, _ := ioutil.TempFile("", "")
	defer os.Remove(commandLineFile.Name())
	envVarFile, _ := ioutil.TempFile("", "")
	defer os.Remove(envVarFile.Name())

	mockCommandLineConfig := clientcmdapi.Config{
		CurrentContext: "any-context-value",
	}
	mockEnvVarConfig := clientcmdapi.Config{
		CurrentContext: "a-different-context",
	}

	WriteToFile(mockCommandLineConfig, commandLineFile.Name())
	WriteToFile(mockEnvVarConfig, envVarFile.Name())

	loadingRules := ClientConfigLoadingRules{
		CommandLinePath: commandLineFile.Name(),
		EnvVarPath:      envVarFile.Name(),
	}

	mergedConfig, err := loadingRules.Load()
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext {
		t.Errorf("expected %v, got %v", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext)
	}
}

示例#4
文件: resource_test.go 项目: ninefive/confd

func TestSameConfigFalse(t *testing.T) {
	log.SetLevel("warn")
	src, err := ioutil.TempFile("", "src")
	defer os.Remove(src.Name())
	if err != nil {
		t.Errorf(err.Error())
	}
	_, err = src.WriteString("src")
	if err != nil {
		t.Errorf(err.Error())
	}
	dest, err := ioutil.TempFile("", "dest")
	defer os.Remove(dest.Name())
	if err != nil {
		t.Errorf(err.Error())
	}
	_, err = dest.WriteString("dest")
	if err != nil {
		t.Errorf(err.Error())
	}
	status, err := sameConfig(src.Name(), dest.Name())
	if err != nil {
		t.Errorf(err.Error())
	}
	if status != false {
		t.Errorf("Expected sameConfig(src, dest) to be %v, got %v", false, status)
	}
}

示例#5
文件: loader_test.go 项目: ttysteale/kubernetes-api

func TestMigratingFile(t *testing.T) {
	sourceFile, _ := ioutil.TempFile("", "")
	defer os.Remove(sourceFile.Name())
	destinationFile, _ := ioutil.TempFile("", "")
	// delete the file so that we'll write to it
	os.Remove(destinationFile.Name())

	WriteToFile(testConfigAlfa, sourceFile.Name())

	loadingRules := ClientConfigLoadingRules{
		MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()},
	}

	if _, err := loadingRules.Load(); err != nil {
		t.Errorf("unexpected error %v", err)
	}

	// the load should have recreated this file
	defer os.Remove(destinationFile.Name())

	sourceContent, err := ioutil.ReadFile(sourceFile.Name())
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	destinationContent, err := ioutil.ReadFile(destinationFile.Name())
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}

	if !reflect.DeepEqual(sourceContent, destinationContent) {
		t.Errorf("source and destination do not match")
	}
}

示例#6
文件: provisioner_test.go 项目: mouserage/packer-provisioner-ansible

func TestProvisionerPrepare_Defaults(t *testing.T) {
	var p Provisioner
	config := testConfig()

	err := p.Prepare(config)
	if err == nil {
		t.Fatalf("should have error")
	}

	hostkey_file, err := ioutil.TempFile("", "hostkey")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(hostkey_file.Name())

	publickey_file, err := ioutil.TempFile("", "publickey")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(publickey_file.Name())

	playbook_file, err := ioutil.TempFile("", "playbook")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(playbook_file.Name())

	config["ssh_host_key_file"] = hostkey_file.Name()
	config["ssh_authorized_key_file"] = publickey_file.Name()
	config["playbook_file"] = playbook_file.Name()
	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
}

示例#7
文件: file_config_test.go 项目: jeady/lmk

func (t *FileConfigTest) TestLoadsRelativeRulesPath(c *C) {
	var fconf, rconf *os.File
	var err error
	var conf Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	defer (func() {
		fconf.Close()
		rconf.Close()
	})()

	path, _ := filepath.Rel(filepath.Dir(fconf.Name()), rconf.Name())

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString("[Settings]\nloglevel=debug\nrules=" + path + "\n")
	fconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Assert(conf, Not(Equals), nil)
	c.Assert(err, Equals, nil)
}

示例#8
文件: serve_test.go 项目: kubernetes/kubernetes

func createTestCertFiles(dir string, spec TestCertSpec) (certFilePath, keyFilePath string, err error) {
	certPem, keyPem, err := utilcert.GenerateSelfSignedCertKey(spec.host, parseIPList(spec.ips), spec.names)
	if err != nil {
		return "", "", err
	}

	certFile, err := ioutil.TempFile(dir, "cert")
	if err != nil {
		return "", "", err
	}

	keyFile, err := ioutil.TempFile(dir, "key")
	if err != nil {
		return "", "", err
	}

	_, err = certFile.Write(certPem)
	if err != nil {
		return "", "", err
	}
	certFile.Close()

	_, err = keyFile.Write(keyPem)
	if err != nil {
		return "", "", err
	}
	keyFile.Close()

	return certFile.Name(), keyFile.Name(), nil
}

示例#9
文件: helpers_test.go 项目: Clarifai/kubernetes

func TestMinifySuccess(t *testing.T) {
	certFile, _ := ioutil.TempFile("", "")
	defer os.Remove(certFile.Name())
	keyFile, _ := ioutil.TempFile("", "")
	defer os.Remove(keyFile.Name())
	caFile, _ := ioutil.TempFile("", "")
	defer os.Remove(caFile.Name())

	mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t)

	if err := MinifyConfig(&mutatingConfig); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if len(mutatingConfig.Contexts) > 1 {
		t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts)
	}
	if _, exists := mutatingConfig.Contexts["federal-context"]; !exists {
		t.Errorf("missing context")
	}

	if len(mutatingConfig.Clusters) > 1 {
		t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters)
	}
	if _, exists := mutatingConfig.Clusters["cow-cluster"]; !exists {
		t.Errorf("missing cluster")
	}

	if len(mutatingConfig.AuthInfos) > 1 {
		t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos)
	}
	if _, exists := mutatingConfig.AuthInfos["red-user"]; !exists {
		t.Errorf("missing user")
	}
}

示例#10
文件: logs.go 项目: catalyzeio/cli

// DumpLogs dumps logs from a Backup/Restore/Import/Export job to the console
func (d *SDb) DumpLogs(taskType string, job *models.Job, service *models.Service) error {
	logrus.Printf("Retrieving %s logs for job %s...", service.Label, job.ID)
	tempURL, err := d.TempLogsURL(job.ID, service.ID)
	if err != nil {
		return err
	}
	dir, err := ioutil.TempDir("", "")
	if err != nil {
		return err
	}

	encrFile, err := ioutil.TempFile(dir, "")
	if err != nil {
		return err
	}
	resp, err := http.Get(tempURL.URL)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	io.Copy(encrFile, resp.Body)
	encrFile.Close()

	plainFile, err := ioutil.TempFile(dir, "")
	if err != nil {
		return err
	}
	// do we have to close this before calling DecryptFile?
	// or can two processes have a file open simultaneously?
	plainFile.Close()

	if taskType == "backup" {
		logsKey := job.Backup.KeyLogs
		if logsKey == "" {
			logsKey = job.Backup.Key
		}
		err := d.Crypto.DecryptFile(encrFile.Name(), logsKey, job.Backup.IV, plainFile.Name())
		if err != nil {
			return err
		}
	} else if taskType == "restore" {
		logsKey := job.Restore.KeyLogs
		if logsKey == "" {
			logsKey = job.Restore.Key
		}
		err := d.Crypto.DecryptFile(encrFile.Name(), logsKey, job.Restore.IV, plainFile.Name())
		if err != nil {
			return err
		}
	}
	logrus.Printf("-------------------------- Begin %s logs --------------------------", service.Label)
	plainFile, _ = os.Open(plainFile.Name())
	io.Copy(os.Stdout, plainFile)
	plainFile.Close()
	logrus.Printf("--------------------------- End %s logs ---------------------------", service.Label)
	os.Remove(encrFile.Name())
	os.Remove(plainFile.Name())
	os.Remove(dir)
	return nil
}

示例#11
文件: injection_test.go 项目: RomainVabre/origin

func TestExpandInjectedFiles(t *testing.T) {
	tmp, err := ioutil.TempDir("", "s2i-test-")
	tmpNested, err := ioutil.TempDir(tmp, "nested")
	if err != nil {
		t.Errorf("Unable to create temp directory: %v", err)
	}
	defer os.RemoveAll(tmp)
	list := api.VolumeList{{Source: tmp, Destination: "/foo"}}
	f1, _ := ioutil.TempFile(tmp, "foo")
	f2, _ := ioutil.TempFile(tmpNested, "bar")
	files, err := ExpandInjectedFiles(list)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	expected := []string{"/foo/" + filepath.Base(f1.Name()), filepath.Join("/foo", filepath.Base(tmpNested), filepath.Base(f2.Name()))}
	for _, exp := range expected {
		found := false
		for _, f := range files {
			if f == exp {
				found = true
			}
		}
		if !found {
			t.Errorf("Expected %q in resulting file list, got %+v", exp, files)
		}
	}
}

示例#12
文件: bundle.go 项目: kod3r/plumber

// Bundle stuff...
// BUG(echu): need to figure out how to handle conflicts in bundle names
func (ctx *Context) Bundle(bundlePath string) error {
	log.Printf("==> Creating bundle from '%s'", bundlePath)
	defer log.Printf("<== Bundling complete.")

	log.Printf(" |  Parsing bundle config.")
	bundleConfig, err := ParseBundleFromDir(bundlePath)
	if err != nil {
		return err
	}
	log.Printf("    %v", bundleConfig)

	log.Printf(" |  Making temp file for python wrapper")
	wrapper, err := ioutil.TempFile(bundlePath, "plumber")
	defer removeTempFile(wrapper)
	if err != nil {
		return err
	}
	log.Printf("    Created '%s'", wrapper.Name())

	templateCtx := templateContext{
		Wrapper: path.Base(wrapper.Name()),
		Plumber: bundleConfig,
	}

	log.Printf(" |  Writing wrapper.")
	tmpl, err := template.New("wrapper").Parse(wrapperTemplate)
	if err != nil {
		return err
	}
	if err := tmpl.Execute(wrapper, templateCtx); err != nil {
		return err
	}
	log.Printf("    Done.")

	log.Printf(" |  Making temp file for Dockerfile")
	dockerfile, err := ioutil.TempFile(bundlePath, "plumber")
	defer removeTempFile(dockerfile)
	if err != nil {
		return err
	}
	log.Printf("    Created '%s'", dockerfile.Name())

	log.Printf(" |  Writing Dockerfile.")
	tmpl, err = template.New("dockerfile").Parse(dockerfileTemplate)
	if err != nil {
		return err
	}
	if err := tmpl.Execute(dockerfile, templateCtx); err != nil {
		return err
	}
	log.Printf("    Done.")

	log.Printf(" |  Building container.")
	err = shell.RunAndLog(ctx.DockerCmd, "build", "--pull", "-t", ctx.GetImage(bundleConfig.Name), "-f", dockerfile.Name(), bundlePath)
	if err != nil {
		return err
	}
	log.Printf("    Container '%s' built.", ctx.GetImage(bundleConfig.Name))
	return nil
}

示例#13
文件: diamond.go 项目: jameslz/MICA

func makeFineDmndDB(seqBuf *bytes.Buffer) (string, error) {
	tmpSeqFile, err := ioutil.TempFile(".", "fine-sequences-")
	if err != nil {
		return "", fmt.Errorf("Could not create temporary sequence file: %s\n", err)
	}
	err = ioutil.WriteFile(tmpSeqFile.Name(), seqBuf.Bytes(), 0666)
	if err != nil {
		return "", fmt.Errorf("Could not write to temporary sequence file: %s\n", err)
	}
	tmpDmndFile, err := ioutil.TempFile(".", "fine-dmnd-db-")
	if err != nil {
		return "", fmt.Errorf("Could not create temporary diamond file: %s\n", err)
	}
	cmd := exec.Command(
		flagDmnd,
		"makedb",
		"--in", tmpSeqFile.Name(),
		"-d", tmpDmndFile.Name())

	err = mica.Exec(cmd)
	if err != nil {
		return "", fmt.Errorf("Could not create fine diamond database: %s\n", err)
	}

	err = os.RemoveAll(tmpSeqFile.Name())
	if err != nil {
		return "", fmt.Errorf("Could not remove temporary sequence file: %s\n", err)
	}

	return tmpDmndFile.Name(), nil

}

示例#14
文件: gpg.go 项目: hdonnay/aptly

// VerifyDetachedSignature verifies combination of signature and cleartext using gpgv
func (g *GpgVerifier) VerifyDetachedSignature(signature, cleartext io.Reader) error {
	args := g.argsKeyrings()

	sigf, err := ioutil.TempFile("", "aptly-gpg")
	if err != nil {
		return err
	}
	defer os.Remove(sigf.Name())
	defer sigf.Close()

	_, err = io.Copy(sigf, signature)
	if err != nil {
		return err
	}

	clearf, err := ioutil.TempFile("", "aptly-gpg")
	if err != nil {
		return err
	}
	defer os.Remove(clearf.Name())
	defer clearf.Close()

	_, err = io.Copy(clearf, cleartext)
	if err != nil {
		return err
	}

	args = append(args, sigf.Name(), clearf.Name())
	return g.runGpgv(args, "detached signature")
}

示例#15
文件: help_test.go 项目: Twisted001/gowsdl

func helpDiff(a, b string) (string, error) {
	atmp, err := ioutil.TempFile("", "help-diff")

	if err != nil {
		return "", err
	}

	btmp, err := ioutil.TempFile("", "help-diff")

	if err != nil {
		return "", err
	}

	if _, err := io.WriteString(atmp, a); err != nil {
		return "", err
	}

	if _, err := io.WriteString(btmp, b); err != nil {
		return "", err
	}

	ret, err := exec.Command("diff", "-u", "-d", "--label", "got", atmp.Name(), "--label", "expected", btmp.Name()).Output()

	os.Remove(atmp.Name())
	os.Remove(btmp.Name())

	if err.Error() == "exit status 1" {
		return string(ret), nil
	}

	return string(ret), err
}

示例#16
文件: epeg_test.go 项目: koofr/goepeg

func TestThumbnail(t *testing.T) {
	input, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(input.Name())

	input.Write(sourceInput)
	input.Close()

	output, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(output.Name())
	output.Close()

	err = Thumbnail(input.Name(), output.Name(), 4, 75, ScaleTypeFitMin)
	if err != nil {
		t.Fatal(err)
	}

	bytes, err := ioutil.ReadFile(output.Name())
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(bytes, thumbnailOutput) {
		t.Errorf("Thumbnail failed")
	}
}

示例#17
文件: output_interceptor_unix.go 项目: WIZARD-CXY/golang-devops-stuff

func (interceptor *outputInterceptor) StartInterceptingOutput() error {
	if interceptor.intercepting {
		return errors.New("Already intercepting output!")
	}
	interceptor.intercepting = true

	var err error

	interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo")
	if err != nil {
		return err
	}

	interceptor.stdoutPlaceholder, err = ioutil.TempFile("", "ginkgo")
	if err != nil {
		return err
	}

	interceptor.stderrPlaceholder, err = ioutil.TempFile("", "ginkgo")
	if err != nil {
		return err
	}

	syscall.Dup2(1, int(interceptor.stdoutPlaceholder.Fd()))
	syscall.Dup2(2, int(interceptor.stderrPlaceholder.Fd()))

	syscall.Dup2(int(interceptor.redirectFile.Fd()), 1)
	syscall.Dup2(int(interceptor.redirectFile.Fd()), 2)

	return nil
}

示例#18
文件: epeg_test.go 项目: koofr/goepeg

func TestTransform(t *testing.T) {
	input, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(input.Name())

	input.Write(sourceInput)
	input.Close()

	output, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(output.Name())
	output.Close()

	err = Transform(input.Name(), output.Name(), TransformTransverse)
	if err != nil {
		t.Fatal(err)
	}

	bytes, err := ioutil.ReadFile(output.Name())
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(bytes, transformOutput) {
		t.Errorf("TestTransform failed")
	}
}

示例#19
文件: file_config_test.go 项目: jeady/lmk

func load_config(
	config string,
	rules string,
	c *C) (conf *FileConfig, cleanup func()) {
	var fconf, rconf *os.File
	var err error

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	cleanup = func() {
		fconf.Close()
		rconf.Close()
	}

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString(
		"[Settings]\n" + config + "\n" + "rules=" + rconf.Name() + "\n")
	fconf.Sync()
	rconf.WriteString(rules + "\n")
	rconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Assert(conf, Not(Equals), nil)
	c.Assert(err, Equals, nil)
	return
}

示例#20
文件: log_test.go 项目: flyxiao2000/myide

func TestFileLogger(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "_gnatsd")
	if err != nil {
		t.Fatal("Could not create tmp dir")
	}
	defer os.RemoveAll(tmpDir)

	file, err := ioutil.TempFile(tmpDir, "gnatsd:log_")
	if err != nil {
		t.Fatalf("Could not create the temp file: %v", err)
	}
	file.Close()

	logger := NewFileLogger(file.Name(), false, false, false, false)
	logger.Noticef("foo")

	buf, err := ioutil.ReadFile(file.Name())
	if err != nil {
		t.Fatalf("Could not read logfile: %v", err)
	}
	if len(buf) <= 0 {
		t.Fatal("Expected a non-zero length logfile")
	}

	if string(buf) != "[INF] foo\n" {
		t.Fatalf("Expected '%s', received '%s'\n", "[INFO] foo", string(buf))
	}

	file, err = ioutil.TempFile(tmpDir, "gnatsd:log_")
	if err != nil {
		t.Fatalf("Could not create the temp file: %v", err)
	}
	file.Close()

	logger = NewFileLogger(file.Name(), true, true, true, true)
	logger.Errorf("foo")

	buf, err = ioutil.ReadFile(file.Name())
	if err != nil {
		t.Fatalf("Could not read logfile: %v", err)
	}
	if len(buf) <= 0 {
		t.Fatal("Expected a non-zero length logfile")
	}
	str := string(buf)
	errMsg := fmt.Sprintf("Expected '%s', received '%s'\n", "[pid] <date> [ERR] foo", str)
	pidEnd := strings.Index(str, " ")
	infoStart := strings.LastIndex(str, "[ERR]")
	if pidEnd == -1 || infoStart == -1 {
		t.Fatalf("%v", errMsg)
	}
	pid := str[0:pidEnd]
	if pid[0] != '[' || pid[len(pid)-1] != ']' {
		t.Fatalf("%v", errMsg)
	}
	//TODO: Parse date.
	if !strings.HasSuffix(str, "[ERR] foo\n") {
		t.Fatalf("%v", errMsg)
	}
}

示例#21
文件: file_config_test.go 项目: jeady/lmk

func (t *FileConfigTest) TestRulesFileDoesNotExist(c *C) {
	var fconf, rconf *os.File
	var err error
	var conf Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	defer (func() {
		fconf.Close()
		rconf.Close()
	})()

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString("[Settings]\nloglevel=debug\nrules=\n")
	fconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Check(conf, Equals, (*FileConfig)(nil))
	c.Check(err, Not(Equals), nil)
}

示例#22
文件: client_integration_test.go 项目: marete/restic

func benchmarkCopyDown(b *testing.B, fileSize int64, delay time.Duration) {
	// Create a temp file and fill it with zero's.
	src, err := ioutil.TempFile("", "sftptest")
	if err != nil {
		b.Fatal(err)
	}
	defer src.Close()
	srcFilename := src.Name()
	defer os.Remove(srcFilename)
	zero, err := os.Open("/dev/zero")
	if err != nil {
		b.Fatal(err)
	}
	n, err := io.Copy(src, io.LimitReader(zero, fileSize))
	if err != nil {
		b.Fatal(err)
	}
	if n < fileSize {
		b.Fatal("short copy")
	}
	zero.Close()
	src.Close()

	sftp, cmd := testClient(b, READONLY, delay)
	defer cmd.Wait()
	defer sftp.Close()
	b.ResetTimer()
	b.SetBytes(fileSize)

	for i := 0; i < b.N; i++ {
		dst, err := ioutil.TempFile("", "sftptest")
		if err != nil {
			b.Fatal(err)
		}
		defer os.Remove(dst.Name())

		src, err := sftp.Open(srcFilename)
		if err != nil {
			b.Fatal(err)
		}
		defer src.Close()
		n, err := io.Copy(dst, src)
		if err != nil {
			b.Fatalf("copy error: %v", err)
		}
		if n < fileSize {
			b.Fatal("unable to copy all bytes")
		}
		dst.Close()
		fi, err := os.Stat(dst.Name())
		if err != nil {
			b.Fatal(err)
		}

		if fi.Size() != fileSize {
			b.Fatalf("wrong file size: want %d, got %d", fileSize, fi.Size())
		}
		os.Remove(dst.Name())
	}
}

示例#23
文件: event_handler_test.go 项目: vjeantet/serf

// testEventScript creates an event script that can be used with the
// agent. It returns the path to the event script itself and a path to
// the file that will contain the events that that script receives.
func testEventScript(t *testing.T, script string) (string, string) {
	scriptFile, err := ioutil.TempFile("", "serf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer scriptFile.Close()

	if err := scriptFile.Chmod(0755); err != nil {
		t.Fatalf("err: %s", err)
	}

	resultFile, err := ioutil.TempFile("", "serf-result")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer resultFile.Close()

	_, err = scriptFile.Write([]byte(
		fmt.Sprintf(script, resultFile.Name())))
	if err != nil {
		t.Fatalf("err: %s")
	}

	return scriptFile.Name(), resultFile.Name()
}

示例#24
文件: xmlsec.go 项目: RobotsAndPencils/go-saml

func sign(xml string, privateKeyPath string, id string) (string, error) {

	samlXmlsecInput, err := ioutil.TempFile(os.TempDir(), "tmpgs")
	if err != nil {
		return "", err
	}
	defer deleteTempFile(samlXmlsecInput.Name())
	samlXmlsecInput.WriteString("<?xml version='1.0' encoding='UTF-8'?>\n")
	samlXmlsecInput.WriteString(xml)
	samlXmlsecInput.Close()

	samlXmlsecOutput, err := ioutil.TempFile(os.TempDir(), "tmpgs")
	if err != nil {
		return "", err
	}
	defer deleteTempFile(samlXmlsecOutput.Name())
	samlXmlsecOutput.Close()

	// fmt.Println("xmlsec1", "--sign", "--privkey-pem", privateKeyPath,
	// 	"--id-attr:ID", id,
	// 	"--output", samlXmlsecOutput.Name(), samlXmlsecInput.Name())
	output, err := exec.Command("xmlsec1", "--sign", "--privkey-pem", privateKeyPath,
		"--id-attr:ID", id,
		"--output", samlXmlsecOutput.Name(), samlXmlsecInput.Name()).CombinedOutput()
	if err != nil {
		return "", errors.New(err.Error() + " : " + string(output))
	}

	samlSignedRequest, err := ioutil.ReadFile(samlXmlsecOutput.Name())
	if err != nil {
		return "", err
	}
	samlSignedRequestXML := strings.Trim(string(samlSignedRequest), "\n")
	return samlSignedRequestXML, nil
}

示例#25
文件: loader_test.go 项目: ttysteale/kubernetes-api

func TestMigratingFileLeaveExistingFileAlone(t *testing.T) {
	sourceFile, _ := ioutil.TempFile("", "")
	defer os.Remove(sourceFile.Name())
	destinationFile, _ := ioutil.TempFile("", "")
	defer os.Remove(destinationFile.Name())

	WriteToFile(testConfigAlfa, sourceFile.Name())

	loadingRules := ClientConfigLoadingRules{
		MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()},
	}

	if _, err := loadingRules.Load(); err != nil {
		t.Errorf("unexpected error %v", err)
	}

	destinationContent, err := ioutil.ReadFile(destinationFile.Name())
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}

	if len(destinationContent) > 0 {
		t.Errorf("destination should not have been touched")
	}
}

示例#26
文件: query_test.go 项目: shyrobbiani/go.db

func TestSearchExist(t *testing.T) {
	t.Parallel()

	nodes, _ := ioutil.TempFile(os.TempDir(), "bplus_search_test")
	defer os.Remove(nodes.Name())

	values, _ := ioutil.TempFile(os.TempDir(), "bplus_search_test")
	defer os.Remove(values.Name())

	var invalid, val BPlusValue

	invalid = append(invalid, []byte("INVALID INVALID BACON INVALID")...)
	val = append(val, []byte("This is a valid value.")...)

	for i := 0; i < 5; i++ {
		Insert(nodes, values, BPlusKey(i), invalid)
	}
	Insert(nodes, values, 5, val)
	for i := 6; i < 10; i++ {
		Insert(nodes, values, BPlusKey(i), invalid)
	}

	found := Search(nodes, values, 5)
	if found == nil {
		t.Error("found == nil")
	}
	if !found.Equal(val) {
		t.Log("found  ", found)
		t.Log("wanted ", val)
		t.Fail()
	}
}

示例#27
文件: goimports.go 项目: 4honor/obdi

func diff(b1, b2 []byte) (data []byte, err error) {
	f1, err := ioutil.TempFile("", "gofmt")
	if err != nil {
		return
	}
	defer os.Remove(f1.Name())
	defer f1.Close()

	f2, err := ioutil.TempFile("", "gofmt")
	if err != nil {
		return
	}
	defer os.Remove(f2.Name())
	defer f2.Close()

	f1.Write(b1)
	f2.Write(b2)

	data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
	if len(data) > 0 {
		// diff exits with a non-zero status when the files don't match.
		// Ignore that failure as long as we get output.
		err = nil
	}
	return
}

示例#28
文件: query_test.go 项目: shyrobbiani/go.db

func BenchmarkGetAll(b *testing.B) {
	b.StopTimer()

	nodes, _ := ioutil.TempFile(os.TempDir(), "bplus_search_benchmark")
	defer os.Remove(nodes.Name())

	values, _ := ioutil.TempFile(os.TempDir(), "bplus_search_benchmark")
	defer os.Remove(values.Name())

	var val BPlusValue

	val = append(val, []byte("Test123")...)

	for i := 0; i < 1000; i++ {
		Insert(nodes, values, BPlusKey(i), val)
	}

	b.StartTimer()

	// One iteration of BenchmarkGetAll = one Search call in BenchmarkSearch. This is done so the values are comparable.
	for i := 0; i < b.N/1000+1; i++ {
		for it := GetAll(nodes, values); it.Valid(); it.Next() {
			it.Value()
		}
	}
}

示例#29
文件: lol_replay_launcher_darwin.go 项目: atuleu/go-lol

func (l *darwinLauncher) Launch(address string, region *lol.Region, id lol.GameID, encryptionKey string) error {
	cmd := exec.Command(l.launcherPath, MaestroParam1, MaestroParam2, l.clientPath,
		fmt.Sprintf(`spectator %s %s %d %s`, address, encryptionKey, id, region.PlatformID()))

	cmd.Dir = path.Dir(l.launcherPath)
	cmd.Env = append(os.Environ(), "riot_launched=true")

	now := time.Now()
	debugErr, err := ioutil.TempFile("", fmt.Sprintf("go-lol-client-debug-stderr-%d.txt", now.Unix()))
	if err != nil {
		return err
	}
	defer debugErr.Close()

	debugOut, err := ioutil.TempFile("", fmt.Sprintf("go-lol-client-debug-stdout-%d.txt", now.Unix()))
	if err != nil {
		return err
	}
	defer debugOut.Close()

	log.Printf("Connecting client output to %s and %s", debugErr.Name(), debugOut.Name())
	cmd.Stdout = debugOut
	cmd.Stderr = debugErr

	return cmd.Run()
}

示例#30
文件: edit.go 项目: niltonkummer/grind

func Diff(old, new string) []byte {
	f1, err := ioutil.TempFile("", "go-fix")
	if err != nil {
		return []byte(fmt.Sprintf("writing temp file: %v\n", err))
	}
	defer os.Remove(f1.Name())
	defer f1.Close()

	f2, err := ioutil.TempFile("", "go-fix")
	if err != nil {
		return []byte(fmt.Sprintf("writing temp file: %v\n", err))
	}
	defer os.Remove(f2.Name())
	defer f2.Close()

	f1.Write([]byte(old))
	f2.Write([]byte(new))

	// Use git diff to get consistent output and also for the context after @@ lines.
	data, err := exec.Command("git", "diff", f1.Name(), f2.Name()).CombinedOutput()
	if len(data) > 0 {
		// diff exits with a non-zero status when the files don't match.
		// Ignore that failure as long as we get output.
		err = nil
	}
	if err != nil {
		return []byte(fmt.Sprintf("invoking git diff: %v\n%s", err, data))
	}
	// skip over diff header, since it is showing temporary file names
	i := bytes.Index(data, []byte("\[email protected]@"))
	if i >= 0 {
		data = data[i+1:]
	}
	return data
}

展开阅读全文