本文整理匯總了Golang中io/ioutil.TempDir函數的典型用法代碼示例。如果您正苦於以下問題:Golang TempDir函數的具體用法?Golang TempDir怎麽用?Golang TempDir使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了TempDir函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: BenchmarkTarUntarWithLinks
func BenchmarkTarUntarWithLinks(b *testing.B) {
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, true)
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(origin)
defer os.RemoveAll(tempDir)
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := TarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
示例2: TestProvisionerPrepare_cookbookPaths
func TestProvisionerPrepare_cookbookPaths(t *testing.T) {
var p Provisioner
path1, err := ioutil.TempDir("", "cookbooks_one")
if err != nil {
t.Fatalf("err: %s", err)
}
path2, err := ioutil.TempDir("", "cookbooks_two")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(path1)
defer os.Remove(path2)
config := testConfig()
config["cookbook_paths"] = []string{path1, path2}
err = p.Prepare(config)
if err != nil {
t.Fatalf("err: %s", err)
}
if len(p.config.CookbookPaths) != 2 {
t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
}
if p.config.CookbookPaths[0] != path1 || p.config.CookbookPaths[1] != path2 {
t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
}
}
示例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: TestFileSS_CreateSnapshotMissingParentDir
func TestFileSS_CreateSnapshotMissingParentDir(t *testing.T) {
parent, err := ioutil.TempDir("", "raft")
if err != nil {
t.Fatalf("err: %v ", err)
}
defer os.RemoveAll(parent)
dir, err := ioutil.TempDir(parent, "raft")
if err != nil {
t.Fatalf("err: %v ", err)
}
snap, err := NewFileSnapshotStore(dir, 3, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
os.RemoveAll(parent)
peers := []byte("all my lovely friends")
_, err = snap.Create(10, 3, peers)
if err != nil {
t.Fatalf("should not fail when using non existing parent")
}
}
示例5: 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)
}
}
示例6: init
// init is used to initialize the client and perform any setup
// needed before we begin starting its various components.
func (c *Client) init() error {
// Ensure the state dir exists if we have one
if c.config.StateDir != "" {
if err := os.MkdirAll(c.config.StateDir, 0700); err != nil {
return fmt.Errorf("failed creating state dir: %s", err)
}
} else {
// Othewise make a temp directory to use.
p, err := ioutil.TempDir("", "NomadClient")
if err != nil {
return fmt.Errorf("failed creating temporary directory for the StateDir: %v", err)
}
c.config.StateDir = p
}
c.logger.Printf("[INFO] client: using state directory %v", c.config.StateDir)
// Ensure the alloc dir exists if we have one
if c.config.AllocDir != "" {
if err := os.MkdirAll(c.config.AllocDir, 0755); err != nil {
return fmt.Errorf("failed creating alloc dir: %s", err)
}
} else {
// Othewise make a temp directory to use.
p, err := ioutil.TempDir("", "NomadClient")
if err != nil {
return fmt.Errorf("failed creating temporary directory for the AllocDir: %v", err)
}
c.config.AllocDir = p
}
c.logger.Printf("[INFO] client: using alloc directory %v", c.config.AllocDir)
return nil
}
示例7: 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)
}
示例8: TestRootTempDir
func TestRootTempDir(t *testing.T) {
d, err := ioutil.TempDir("", "testroottempdir")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(d)
old := os.Getenv("TMPDIR")
cleanup, err := RootTempDir(d)
if err != nil {
t.Fatal(err)
}
testDir, err := ioutil.TempDir("", "testroottempsubdir")
if err != nil {
t.Fatal(err)
}
_, err = os.Stat(testDir)
if err != nil {
t.Fatal(err)
}
cleanup()
_, err = os.Stat(testDir)
if err == nil || !os.IsNotExist(err) {
os.RemoveAll(testDir)
t.Errorf("Cleanup did not delete sub temp dir %v", testDir)
}
if os.Getenv("TMPDIR") != old {
t.Error("Failed to restore TMPDIR")
}
}
示例9: TestUninstall
func TestUninstall(t *testing.T) {
serviceBuilder := runit.FakeServiceBuilder()
serviceBuilderDir, err := ioutil.TempDir("", "servicebuilderDir")
Assert(t).IsNil(err, "Got an unexpected error creating a temp directory")
serviceBuilder.ConfigRoot = serviceBuilderDir
testPodDir, err := ioutil.TempDir("", "testPodDir")
Assert(t).IsNil(err, "Got an unexpected error creating a temp directory")
pod := Pod{
Id: "testPod",
path: testPodDir,
ServiceBuilder: serviceBuilder,
}
manifest := getTestPodManifest(t)
manifestContent, err := manifest.OriginalBytes()
Assert(t).IsNil(err, "couldn't get manifest bytes")
err = ioutil.WriteFile(pod.currentPodManifestPath(), manifestContent, 0744)
Assert(t).IsNil(err, "should have written current manifest")
serviceBuilderFilePath := filepath.Join(serviceBuilder.ConfigRoot, "testPod.yaml")
err = ioutil.WriteFile(serviceBuilderFilePath, []byte("stuff"), 0744)
Assert(t).IsNil(err, "Error writing fake servicebuilder file")
err = pod.Uninstall()
Assert(t).IsNil(err, "Error uninstalling pod")
_, err = os.Stat(serviceBuilderFilePath)
Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
_, err = os.Stat(pod.currentPodManifestPath())
Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
}
示例10: TestSizeFileAndNestedDirectoryNonempty
// Test directory with 1 file and 1 non-empty directory
func TestSizeFileAndNestedDirectoryNonempty(t *testing.T) {
var dir, dirNested string
var err error
if dir, err = ioutil.TempDir(os.TempDir(), "TestSizeFileAndNestedDirectoryNonempty"); err != nil {
t.Fatalf("failed to create directory: %s", err)
}
if dirNested, err = ioutil.TempDir(dir, "nested"); err != nil {
t.Fatalf("failed to create nested directory: %s", err)
}
var file *os.File
if file, err = ioutil.TempFile(dir, "file"); err != nil {
t.Fatalf("failed to create file: %s", err)
}
data := []byte{100, 111, 99, 107, 101, 114}
file.Write(data)
var nestedFile *os.File
if nestedFile, err = ioutil.TempFile(dirNested, "file"); err != nil {
t.Fatalf("failed to create file in nested directory: %s", err)
}
nestedData := []byte{100, 111, 99, 107, 101, 114}
nestedFile.Write(nestedData)
var size int64
if size, _ = Size(dir); size != 12 {
t.Fatalf("directory with 6-byte file and nested directory with 6-byte file has size: %d", size)
}
}
示例11: TestManifestType
func TestManifestType(t *testing.T) {
pth, _ := ioutil.TempDir("", "_GOTEST_MANIFEST_TYPE")
defer os.RemoveAll(pth)
m, err := bagins.NewManifest(pth, "sha512", bagins.PayloadManifest)
if err != nil {
t.Error("Manifest could not be created!", err)
}
if m.Type() != bagins.PayloadManifest {
t.Errorf("Type() expected '%s', got '%s'", bagins.PayloadManifest, m.Type())
}
pth, _ = ioutil.TempDir("", "_GOTEST_MANIFEST_TYPE/tagmanifest-sha512.txt")
defer os.RemoveAll(pth)
m, err = bagins.NewManifest(pth, "sha512", bagins.TagManifest)
if err != nil {
t.Error("Manifest could not be created!", err)
}
if m.Type() != bagins.TagManifest {
t.Errorf("Type() expected '%s', got '%s'", bagins.TagManifest, m.Type())
}
}
示例12: TestScanPath
func TestScanPath(t *testing.T) {
dir1, _ := ioutil.TempDir("", "yegonesh_dir1")
dir2, _ := ioutil.TempDir("", "yegonesh_dir2")
defer os.RemoveAll(dir1)
defer os.RemoveAll(dir2)
files := []struct {
name string
dir string
}{
{"vim", dir1},
{"emacs", dir2},
{"nano", dir2},
}
for _, f := range files {
ioutil.WriteFile(f.dir+"/"+f.name, nil, 0744)
}
out := scanPath(dir1 + ":" + dir2)
expected := []string{"emacs", "nano", "vim"}
var result []string
for c := range out {
result = append(result, c)
}
if !reflect.DeepEqual(expected, result) {
t.Errorf("Expected executables to eq %v, got %v", expected, result)
}
}
示例13: TestCollectDirectoryRecursive
func TestCollectDirectoryRecursive(t *testing.T) {
file1, _ := ioutil.TempFile("", "mvshaker")
defer os.Remove(file1.Name())
file2, _ := ioutil.TempFile("", "mvshaker")
defer os.Remove(file2.Name())
dir, _ := ioutil.TempDir("", "mvshaker")
defer os.Remove(dir)
file3, _ := ioutil.TempFile(dir, "mvshaker")
defer os.Remove(file3.Name())
dir2, _ := ioutil.TempDir(dir, "mvshaker")
defer os.Remove(dir2)
file4, _ := ioutil.TempFile(dir2, "mvshaker")
defer os.Remove(file4.Name())
filesToCollect := []string{file1.Name(), file2.Name(), dir}
paths := collect(filesToCollect, []string{}, true)
sort.Sort(ByPath(paths))
expected := []shakableFile{
shakableFile{filepath: file1.Name(), isShaked: false},
shakableFile{filepath: file2.Name(), isShaked: false},
shakableFile{filepath: file3.Name(), isShaked: false},
shakableFile{filepath: file4.Name(), isShaked: false}}
sort.Sort(ByPath(expected))
assert.Equal(t, paths, expected)
}
示例14: TestWriteDHParam
func TestWriteDHParam(t *testing.T) {
// Ensure sslPath/dhparam.pem exists with the contents of routerConfig.SSLConfig.DHParam and is 0644
sslPath, err := ioutil.TempDir("", "test")
if err != nil {
t.Error(err)
}
defer os.RemoveAll(sslPath)
dhParamPath := filepath.Join(sslPath, "dhparam.pem")
expectedDHParam := "bizbar"
routerConfig := model.RouterConfig{
SSLConfig: &model.SSLConfig{
DHParam: expectedDHParam,
},
}
err = WriteDHParam(&routerConfig, sslPath)
if err != nil {
t.Error(err)
}
actualDHParam, err := ioutil.ReadFile(dhParamPath)
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(expectedDHParam, string(actualDHParam)) {
t.Errorf("Expected dhparam.pem contents, %s, does not match actual contents, %s.", expectedDHParam, string(actualDHParam))
}
expectedPerm := "-rw-r--r--" // 0644
info, _ := os.Stat(dhParamPath)
actualPerm := info.Mode().String()
if !reflect.DeepEqual(expectedPerm, actualPerm) {
t.Errorf("Expected permission on dhparam.pem, %s, does not match actual, %s.", expectedPerm, actualPerm)
}
// Ensure dhparam.pem is erased when routerConfig.SSLConfig.DHParam is empty
sslPath, err = ioutil.TempDir("", "test-empty")
if err != nil {
t.Error(err)
}
defer os.RemoveAll(sslPath)
dhParamPath = filepath.Join(sslPath, "dhparam.pem")
routerConfig = model.RouterConfig{
SSLConfig: &model.SSLConfig{
DHParam: "",
},
}
err = WriteDHParam(&routerConfig, sslPath)
if err != nil {
t.Error(err)
}
if _, err := os.Stat(dhParamPath); err == nil {
t.Errorf("Expected dhparam.pem to be erased when DHParam was an empty string, but the file was found.")
}
}
示例15: newLightningNode
// newLightningNode creates a new test lightning node instance from the passed
// rpc config and slice of extra arguments.
func newLightningNode(rpcConfig *btcrpcclient.ConnConfig, lndArgs []string) (*lightningNode, error) {
var err error
cfg := &config{
RPCHost: "127.0.0.1",
RPCUser: rpcConfig.User,
RPCPass: rpcConfig.Pass,
}
nodeNum := numActiveNodes
cfg.DataDir, err = ioutil.TempDir("", "lndtest-data")
if err != nil {
return nil, err
}
cfg.LogDir, err = ioutil.TempDir("", "lndtest-log")
if err != nil {
return nil, err
}
cfg.PeerPort, cfg.RPCPort = generateListeningPorts()
numActiveNodes++
return &lightningNode{
cfg: cfg,
p2pAddr: net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.PeerPort)),
rpcAddr: net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.RPCPort)),
rpcCert: rpcConfig.Certificates,
nodeId: nodeNum,
extraArgs: lndArgs,
}, nil
}