Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package lib_test
import (
"testing"

"github.com/devlights/try-golang/examples/testing/testing_short_feature/lib"
"github.com/devlights/try-golang/examples/testing/short_feature/lib"
)

func TestAdd(t *testing.T) {
Expand Down
8 changes: 8 additions & 0 deletions examples/testing/tempdir/Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# https://taskfile.dev

version: '3'

tasks:
default:
cmds:
- go test -v .
52 changes: 52 additions & 0 deletions examples/testing/tempdir/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package main

import (
"fmt"
"os"
"path/filepath"
"testing"
)

var (
tmpDir string
)

func TestMain(m *testing.M) {
ret := m.Run()

// テスト終了後に一時ディレクトリが削除されているか確認
if tmpDir != "" {
_, err := os.Stat(tmpDir)
fmt.Printf("[teardown] os.Stat() ==> %v", err)
}

os.Exit(ret)
}

func TestTempDir(t *testing.T) {
//
// t.TempDir() にてテスト時に利用できる一時ディレクトリの
// パスが取得出来る。この一時ディレクトリはテスト時に作成されて
// テスト終了後に自動的に消去される。テスト時に手動で一時ディレクトリを
// 確保しておく手間が無くなるため、とても便利。
//
tmpDir = t.TempDir()
t.Logf("tmpDir=%s", tmpDir)

fi, err := os.Stat(tmpDir)
t.Logf("IsDir=%v, Name=%s, Err=%v", fi.IsDir(), fi.Name(), err)

// ディレクトリが存在しているだけでは何なので
// 何かのファイルを書き込んでおく
p := filepath.Join(tmpDir, "hello.txt")
os.WriteFile(p, []byte("hello world"), 0777)

fi, err = os.Stat(p)
t.Logf("IsDir=%v, Name=%s, Err=%v", fi.IsDir(), fi.Name(), err)

// t.TempDir() の呼び出しは何回でも良い
// その度に、異なるディレクトリが返る
for i := 0; i < 10; i++ {
t.Logf("tmpDir=%s", t.TempDir())
}
}