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.
赞(3) 打赏
欢迎转载,注明出处:刘世明的博客 » create temp file and clean up in go test

评论 4

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.

  2. #2

    Your article helped me a lot, is there any more related content? Thanks! https://www.binance.bh/register?ref=QCGZMHR6

    打开Binance账户1个月前 (05-25)回复
  3. #3

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  4. #4

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

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

支付宝扫一扫打赏

微信扫一扫打赏