當前位置: 首頁>>代碼示例>>Golang>>正文


Golang os.TempDir函數代碼示例

本文整理匯總了Golang中os.TempDir函數的典型用法代碼示例。如果您正苦於以下問題:Golang TempDir函數的具體用法?Golang TempDir怎麽用?Golang TempDir使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了TempDir函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: SetUpSuite

func (s *MyAPIFSCacheSuite) SetUpSuite(c *C) {
	root, e := ioutil.TempDir(os.TempDir(), "api-")
	c.Assert(e, IsNil)
	s.root = root

	fsroot, e := ioutil.TempDir(os.TempDir(), "api-")
	c.Assert(e, IsNil)

	accessKeyID, err := generateAccessKeyID()
	c.Assert(err, IsNil)
	secretAccessKey, err := generateSecretAccessKey()
	c.Assert(err, IsNil)

	conf := newConfigV2()
	conf.Credentials.AccessKeyID = string(accessKeyID)
	conf.Credentials.SecretAccessKey = string(secretAccessKey)
	s.accessKeyID = string(accessKeyID)
	s.secretAccessKey = string(secretAccessKey)

	// do this only once here
	setGlobalConfigPath(root)

	c.Assert(saveConfig(conf), IsNil)

	cloudServer := cloudServerConfig{
		Address:         ":" + strconv.Itoa(getFreePort()),
		Path:            fsroot,
		MinFreeDisk:     0,
		AccessKeyID:     s.accessKeyID,
		SecretAccessKey: s.secretAccessKey,
		Region:          "us-east-1",
	}
	httpHandler := serverHandler(cloudServer)
	testAPIFSCacheServer = httptest.NewServer(httpHandler)
}
開發者ID:alexex,項目名稱:minio,代碼行數:35,代碼來源:server_fs_test.go

示例2: TestExists

func TestExists(t *testing.T) {
	zeroSizedFile, _ := createZeroSizedFileInTempDir()
	defer deleteFileInTempDir(zeroSizedFile)
	nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
	defer deleteFileInTempDir(nonZeroSizedFile)
	emptyDirectory, _ := createEmptyTempDir()
	defer deleteTempDir(emptyDirectory)
	nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
	nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"

	type test struct {
		input          string
		expectedResult bool
		expectedErr    error
	}

	data := []test{
		{zeroSizedFile.Name(), true, nil},
		{nonZeroSizedFile.Name(), true, nil},
		{emptyDirectory, true, nil},
		{nonExistentFile, false, nil},
		{nonExistentDir, false, nil},
	}
	for i, d := range data {
		exists, err := Exists(d.input, new(afero.OsFs))
		if d.expectedResult != exists {
			t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
		}
		if d.expectedErr != err {
			t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
		}
	}

}
開發者ID:jaden,項目名稱:hugo,代碼行數:34,代碼來源:path_test.go

示例3: SetUpSuite

func (s *MyAPIFSCacheSuite) SetUpSuite(c *C) {
	root, err := ioutil.TempDir(os.TempDir(), "api-")
	c.Assert(err, IsNil)
	s.root = root

	fsroot, err := ioutil.TempDir(os.TempDir(), "api-")
	c.Assert(err, IsNil)

	fs.SetFSMultipartsConfigPath(filepath.Join(root, "multiparts.json"))
	multiparts := &fs.Multiparts{}
	multiparts.ActiveSession = make(map[string]*fs.MultipartSession)
	perr := fs.SaveMultipartsSession(multiparts)
	c.Assert(perr, IsNil)

	accessKeyID, perr := generateAccessKeyID()
	c.Assert(perr, IsNil)
	secretAccessKey, perr := generateSecretAccessKey()
	c.Assert(perr, IsNil)

	authConf := &AuthConfig{}
	authConf.AccessKeyID = string(accessKeyID)
	authConf.SecretAccessKey = string(secretAccessKey)
	s.accessKeyID = string(accessKeyID)
	s.secretAccessKey = string(secretAccessKey)

	// do this only once here
	customConfigPath = root

	perr = saveAuthConfig(authConf)
	c.Assert(perr, IsNil)

	minioAPI := getNewAPI(fsroot, false)
	httpHandler := getAPIHandler(false, minioAPI)
	testAPIFSCacheServer = httptest.NewServer(httpHandler)
}
開發者ID:krishnasrinivas,項目名稱:minio-fs,代碼行數:35,代碼來源:server_fs_test.go

示例4: testConfig

func testConfig() *config.Config {
	conf := config.DefaultConfig()
	conf.StateDir = os.TempDir()
	conf.AllocDir = os.TempDir()
	conf.MaxKillTimeout = 10 * time.Second
	return conf
}
開發者ID:PagerDuty,項目名稱:nomad,代碼行數:7,代碼來源:driver_test.go

示例5: TestCreateTimestampFile

func TestCreateTimestampFile(t *testing.T) {
	realDir := filepath.Join(os.TempDir(), "util_test")
	util.Mkdir(realDir, 0755)
	defer util.RemoveAll(realDir)
	timestampFilePath := filepath.Join(realDir, TIMESTAMP_FILE_NAME)
	if err := CreateTimestampFile(realDir); err != nil {
		t.Errorf("Unexpected error: %s", err)
	}
	// Assert timestamp file exists.
	if _, err := os.Stat(timestampFilePath); err != nil {
		t.Errorf("Timestamp file %s was not created!", timestampFilePath)
	}
	// Assert timestamp file contains int64.
	fileContent, err := ioutil.ReadFile(timestampFilePath)
	if err != nil {
		t.Errorf("Unexpected error: %s", err)
	}
	if _, err := strconv.ParseInt(string(fileContent), 10, 64); err != nil {
		t.Errorf("Unexpected value in %s: %s", timestampFilePath, err)
	}

	// Assert error returned when specified dir does not exist.
	nonexistantDir := filepath.Join(os.TempDir(), "util_test_nonexistant")
	util.RemoveAll(nonexistantDir)
	if err := CreateTimestampFile(nonexistantDir); err != nil {
		// Expected error
	} else {
		t.Error("Unexpected lack of error")
	}
}
開發者ID:kleopatra999,項目名稱:skia-buildbot,代碼行數:30,代碼來源:util_test.go

示例6: TestPackTo

func TestPackTo(t *testing.T) {
	Convey("Pack a dir or file to tar.gz file", t, func() {
		Convey("Pack a dir that does exist and includir root dir", func() {
			So(PackTo("testdata/testdir",
				path.Join(os.TempDir(), "testdata/testdir1.tar.gz"), true), ShouldBeNil)
		})

		Convey("Pack a dir that does exist and does not includir root dir", func() {
			So(PackTo("testdata/testdir",
				path.Join(os.TempDir(), "testdata/testdir2.tar.gz")), ShouldBeNil)
		})

		Convey("Pack a dir that does not exist and does not includir root dir", func() {
			So(PackTo("testdata/testdir404",
				path.Join(os.TempDir(), "testdata/testdir3.tar.gz")), ShouldNotBeNil)
		})

		Convey("Pack a file that does exist", func() {
			So(PackTo("testdata/README.txt",
				path.Join(os.TempDir(), "testdata/testdir4.tar.gz")), ShouldBeNil)
		})

		Convey("Pack a file that does not exist", func() {
			So(PackTo("testdata/README404.txt",
				path.Join(os.TempDir(), "testdata/testdir5.tar.gz")), ShouldNotBeNil)
		})
	})
}
開發者ID:xuewuhen,項目名稱:cae,代碼行數:28,代碼來源:tz_test.go

示例7: TestDiffObjects

func (s *TestSuite) TestDiffObjects(c *C) {
	/// filesystem
	root1, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(root1)

	root2, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(root2)

	objectPath1 := filepath.Join(root1, "object1")
	data := "hello"
	dataLen := len(data)
	perr := putTarget(objectPath1, int64(dataLen), bytes.NewReader([]byte(data)))
	c.Assert(perr, IsNil)

	objectPath2 := filepath.Join(root2, "object1")
	data = "hello"
	dataLen = len(data)
	perr = putTarget(objectPath2, int64(dataLen), bytes.NewReader([]byte(data)))
	c.Assert(perr, IsNil)

	for diff := range doDiffMain(objectPath1, objectPath2, false) {
		c.Assert(diff.Error, IsNil)
	}
}
開發者ID:koolhead17,項目名稱:mc,代碼行數:26,代碼來源:diff_test.go

示例8: TestLuaScriptExecuteWithAggregator

func TestLuaScriptExecuteWithAggregator(t *testing.T) {
	task := pendingLuaScriptTaskWithAggregator()
	mockRun := exec.CommandCollector{}
	exec.SetRunForTesting(mockRun.Run)
	defer exec.SetRunForTesting(exec.DefaultRun)
	mockRun.SetDelegateRun(func(cmd *exec.Command) error {
		runId := getRunId(t, cmd)
		assertFileContents(t, filepath.Join(os.TempDir(), runId+".lua"),
			`print("lualualua")`)
		assertFileContents(t, filepath.Join(os.TempDir(), runId+".aggregator"),
			`print("aaallluuu")`)
		return nil
	})
	err := task.Execute()
	assert.NoError(t, err)
	assert.Len(t, mockRun.Commands(), 1)
	cmd := mockRun.Commands()[0]
	expect.Equal(t, "run_lua_on_workers", cmd.Name)
	expect.Contains(t, cmd.Args, "--gae_task_id=42")
	expect.Contains(t, cmd.Args, "--description=description")
	expect.Contains(t, cmd.Args, "[email protected]")
	expect.Contains(t, cmd.Args, "--pageset_type=All")
	expect.Contains(t, cmd.Args, "--chromium_build=c14d891-586101c")
	runId := getRunId(t, cmd)
	expect.Contains(t, cmd.Args, "--log_id="+runId)
	expect.NotNil(t, cmd.Timeout)
}
開發者ID:saltmueller,項目名稱:skia-buildbot,代碼行數:27,代碼來源:poller_test.go

示例9: TestChromiumPerfExecute

func TestChromiumPerfExecute(t *testing.T) {
	task := pendingChromiumPerfTask()
	mockRun := exec.CommandCollector{}
	exec.SetRunForTesting(mockRun.Run)
	defer exec.SetRunForTesting(exec.DefaultRun)
	mockRun.SetDelegateRun(func(cmd *exec.Command) error {
		runId := getRunId(t, cmd)
		assertFileContents(t, filepath.Join(os.TempDir(), runId+".chromium.patch"),
			"chromiumpatch\n")
		assertFileContents(t, filepath.Join(os.TempDir(), runId+".skia.patch"),
			"skiapatch\n")
		return nil
	})
	err := task.Execute()
	assert.NoError(t, err)
	assert.Len(t, mockRun.Commands(), 1)
	cmd := mockRun.Commands()[0]
	expect.Equal(t, "run_chromium_perf_on_workers", cmd.Name)
	expect.Contains(t, cmd.Args, "--gae_task_id=42")
	expect.Contains(t, cmd.Args, "--description=description")
	expect.Contains(t, cmd.Args, "[email protected]")
	expect.Contains(t, cmd.Args, "--benchmark_name=benchmark")
	expect.Contains(t, cmd.Args, "--target_platform=Linux")
	expect.Contains(t, cmd.Args, "--pageset_type=All")
	expect.Contains(t, cmd.Args, "--repeat_benchmark=1")
	expect.Contains(t, cmd.Args, "--benchmark_extra_args=benchmarkargs")
	expect.Contains(t, cmd.Args, "--browser_extra_args_nopatch=banp")
	expect.Contains(t, cmd.Args, "--browser_extra_args_withpatch=bawp")
	runId := getRunId(t, cmd)
	expect.Contains(t, cmd.Args, "--log_id="+runId)
	expect.NotNil(t, cmd.Timeout)
}
開發者ID:saltmueller,項目名稱:skia-buildbot,代碼行數:32,代碼來源:poller_test.go

示例10: TestCpTypeB

func (s *CmdTestSuite) TestCpTypeB(c *C) {
	/// filesystem
	source, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(source)

	sourcePath := filepath.Join(source, "object1")
	data := "hello"
	dataLen := len(data)
	err = putTarget(sourcePath, int64(dataLen), bytes.NewReader([]byte(data)))
	c.Assert(err, IsNil)

	target, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(target)

	cps, err := newSession()
	c.Assert(err, IsNil)

	cps.URLs = append(cps.URLs, sourcePath)
	cps.URLs = append(cps.URLs, target)
	for err := range doCopyCmdSession(barCp, cps) {
		c.Assert(err, IsNil)
	}

	cps, err = newSession()
	c.Assert(err, IsNil)

	targetURL := server.URL + "/bucket"
	cps.URLs = append(cps.URLs, sourcePath)
	cps.URLs = append(cps.URLs, targetURL)
	for err := range doCopyCmdSession(barCp, cps) {
		c.Assert(err, IsNil)
	}
}
開發者ID:bosky101,項目名稱:mc,代碼行數:35,代碼來源:cp_test.go

示例11: sign

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
}
開發者ID:RobotsAndPencils,項目名稱:go-saml,代碼行數:35,代碼來源:xmlsec.go

示例12: Execute

func (task *LuaScriptTask) Execute() error {
	runId := runId(task)
	chromiumBuildDir := ctutil.ChromiumBuildDir(task.ChromiumRev, task.SkiaRev, "")
	// TODO(benjaminwagner): Since run_lua_on_workers only reads the lua script in order to
	// upload to Google Storage, eventually we should move the upload step here to avoid writing
	// to disk. Not sure if we can/should do the same for the aggregator script.
	luaScriptName := runId + ".lua"
	luaScriptPath := filepath.Join(os.TempDir(), luaScriptName)
	if err := ioutil.WriteFile(luaScriptPath, []byte(task.LuaScript), 0666); err != nil {
		return err
	}
	defer skutil.Remove(luaScriptPath)
	if task.LuaAggregatorScript != "" {
		luaAggregatorName := runId + ".aggregator"
		luaAggregatorPath := filepath.Join(os.TempDir(), luaAggregatorName)
		if err := ioutil.WriteFile(luaAggregatorPath, []byte(task.LuaAggregatorScript), 0666); err != nil {
			return err
		}
		defer skutil.Remove(luaAggregatorPath)
	}
	return exec.Run(&exec.Command{
		Name: "run_lua_on_workers",
		Args: []string{
			"--emails=" + task.Username,
			"--description=" + task.Description,
			"--gae_task_id=" + strconv.FormatInt(task.Id, 10),
			"--pageset_type=" + task.PageSets,
			"--chromium_build=" + chromiumBuildDir,
			"--run_id=" + runId,
			"--log_dir=" + logDir,
			"--log_id=" + runId,
		},
		Timeout: ctutil.MASTER_SCRIPT_RUN_LUA_TIMEOUT,
	})
}
開發者ID:Tiger66639,項目名稱:skia-buildbot,代碼行數:35,代碼來源:main.go

示例13: getNormalConfig

func getNormalConfig() *Config {
	//!TODO: split into different test case composable builders
	c := new(Config)
	c.System = SystemSection{Pidfile: filepath.Join(os.TempDir(), "nedomi.pid")}
	c.Logger = LoggerSection{Type: "nillogger"}

	cz := &CacheZoneSection{
		ID:             "test1",
		Type:           "disk",
		Path:           os.TempDir(),
		StorageObjects: 20,
		PartSize:       1024,
		Algorithm:      "lru",
	}
	c.CacheZones = map[string]*CacheZoneSection{"test1": cz}

	c.HTTP = new(HTTP)
	c.HTTP.Listen = ":5435"
	c.HTTP.Logger = c.Logger
	c.HTTP.Servers = []*VirtualHost{&VirtualHost{
		BaseVirtualHost: BaseVirtualHost{
			Name:         "localhost",
			UpstreamType: "simple",
			CacheKey:     "test",
			HandlerType:  "proxy",
			Logger:       &c.Logger,
		},
		CacheZone: cz,
	}}
	c.HTTP.Servers[0].UpstreamAddress, _ = url.Parse("http://www.google.com")

	return c
}
開發者ID:gitter-badger,項目名稱:nedomi,代碼行數:33,代碼來源:config_test.go

示例14: InitializeEnvironment

// InitializeEnvironment creates new transaction for the test
func (env *Environment) InitializeEnvironment() error {
	var err error
	_, file := filepath.Split(env.testFileName)
	env.dbFile, err = ioutil.TempFile(os.TempDir(), file)
	if err != nil {
		return fmt.Errorf("Failed to create a temporary file in %s: %s", os.TempDir(), err.Error())
	}
	env.dbConnection, err = newDBConnection(env.dbFile.Name())
	if err != nil {
		return fmt.Errorf("Failed to connect to database: %s", err.Error())
	}
	env.Environment = gohan_otto.NewEnvironment(env.dbConnection, &middleware.FakeIdentity{}, 30*time.Second)
	env.SetUp()
	env.addTestingAPI()

	script, err := env.VM.Compile(env.testFileName, env.testSource)
	if err != nil {
		return fmt.Errorf("Failed to compile the file '%s': %s", env.testFileName, err.Error())
	}

	env.VM.Run(script)
	err = env.loadSchemas()
	if err != nil {
		schema.ClearManager()
		return fmt.Errorf("Failed to load schema for '%s': %s", env.testFileName, err.Error())
	}

	err = db.InitDBWithSchemas("sqlite3", env.dbFile.Name(), true, false)
	if err != nil {
		schema.ClearManager()
		return fmt.Errorf("Failed to init DB: %s", err.Error())
	}

	return nil
}
開發者ID:masaki-saeki,項目名稱:gohan,代碼行數:36,代碼來源:environment.go

示例15: saveHosts

func saveHosts(newHosts []string) {
	var newHostsBytes []byte
	for _, newHost := range newHosts {
		newHostsBytes = append(newHostsBytes, []byte(newHost+"\n")...)
	}

	err := ioutil.WriteFile(os.TempDir()+"/newhosts.tmp", newHostsBytes, 0644)
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err,
			"file":  os.TempDir() + "/newhosts.tmp",
		}).Fatal("Error writing to file")
	}

	_, err = exec.Command(
		"sudo",
		"mv",
		os.TempDir()+"/newhosts.tmp",
		"/etc/hosts").CombinedOutput()
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"from":  os.TempDir() + "/newhosts.tmp",
			"to":    "etc/hosts",
			"error": err,
		}).Fatal("File to move file")
	}
}
開發者ID:alecdwm,項目名稱:svboxctl,代碼行數:27,代碼來源:hostsiface.go


注:本文中的os.TempDir函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。