to be
a problem slover

create temp file and clean up in go test

import (
    "fmt"
    "io/ioutil"
    "os"
    "testing"
)

func tempdir(patten string) string{
    dir, _ := ioutil.TempDir("/tmp", patten)
    fmt.Println(dir + ": created")
    return dir
}

func TestTempDir(t *testing.T) {
    dir := tempdir("dir-prefix*suffix")
    cleanUp := func() { os.RemoveAll(dir)}
    // test logic...
    cleanUp()
    fmt.Println(dir + ": deleted")
}

output:

=== RUN   TestTempDir
/tmp/dir-prefix400328188suffix: created
/tmp/dir-prefix400328188suffix: deleted

note

ioutil.TempDir

  • create temp file with patten, the first param can be space, if not specified, it will use os.TempDir() to put the temp dir
  • the second param use ‘*’ to split prefix and suffix

os.RemoveAll

  • removes path and any children it contains.
赞(0) 打赏
欢迎转载,注明出处:刘世明的博客 » create temp file and clean up in go test

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下作者

支付宝扫一扫打赏

微信扫一扫打赏