本文整理汇总了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)
}
示例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)
}
}
}
示例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)
}
示例4: testConfig
func testConfig() *config.Config {
conf := config.DefaultConfig()
conf.StateDir = os.TempDir()
conf.AllocDir = os.TempDir()
conf.MaxKillTimeout = 10 * time.Second
return conf
}
示例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")
}
}
示例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)
})
})
}
示例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)
}
}
示例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)
}
示例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)
}
示例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)
}
}
示例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
}
示例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,
})
}
示例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
}
示例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
}
示例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")
}
}