diff --git a/sf/context.go b/sf/context.go new file mode 100644 index 0000000..d8ae8e9 --- /dev/null +++ b/sf/context.go @@ -0,0 +1,13 @@ +package sf + +import ( + "context" + "github.com/rekby/fixenv" +) + +func Context(e fixenv.Env) context.Context { + return e.CacheWithCleanup(nil, nil, func() (res interface{}, _ fixenv.FixtureCleanupFunc, _ error) { + ctx, ctxCancel := context.WithCancel(context.Background()) + return ctx, fixenv.FixtureCleanupFunc(ctxCancel), nil + }).(context.Context) +} diff --git a/sf/context_test.go b/sf/context_test.go new file mode 100644 index 0000000..ce0d882 --- /dev/null +++ b/sf/context_test.go @@ -0,0 +1,23 @@ +package sf + +import ( + "context" + "github.com/rekby/fixenv" + "github.com/rekby/fixenv/internal" + "testing" +) + +func TestContext(t *testing.T) { + tm := &internal.TestMock{} + + e := fixenv.New(tm) + ctx := Context(e) + if ctx.Err() != nil { + t.Fatal(ctx.Err()) + } + + tm.CallCleanup() + if ctx.Err() != context.Canceled { + t.Fatal(ctx.Err()) + } +} diff --git a/sf/filesystem.go b/sf/filesystem.go index 1bae1f4..f844afd 100644 --- a/sf/filesystem.go +++ b/sf/filesystem.go @@ -5,9 +5,11 @@ import ( "os" ) +// TempDir return path for existet temporary folder +// the folder will remove after test finish with all contents func TempDir(e fixenv.Env) string { return e.CacheWithCleanup(nil, nil, func() (res interface{}, cleanup fixenv.FixtureCleanupFunc, err error) { - dir, err := os.MkdirTemp("", "") + dir, err := os.MkdirTemp("", "fixenv-auto-") mustNoErr(e, err, "failed to create temp dir: %v", err) e.T().Logf("Temp dir created: %v", dir) clean := func() { @@ -17,3 +19,20 @@ func TempDir(e fixenv.Env) string { return dir, clean, nil }).(string) } + +// TempFile return path to empty existed file in TempDir +func TempFile(e fixenv.Env) string { + return TempFileNamed(e, "fixenv-auto-") +} + +// TempFileNamed return path to empty file in TempDir +// pattern is pattern for os.CreateTemp +func TempFileNamed(e fixenv.Env, pattern string) string { + return e.Cache(nil, nil, func() (res interface{}, err error) { + dir := TempDir(e) + f, err := os.CreateTemp(dir, pattern) + mustNoErr(e, err, "failed to create temp file: %w", err) + fName := f.Name() + return fName, f.Close() + }).(string) +} diff --git a/sf/filesystem_test.go b/sf/filesystem_test.go index 1c38976..d473569 100644 --- a/sf/filesystem_test.go +++ b/sf/filesystem_test.go @@ -20,3 +20,19 @@ func TestTempDir(t *testing.T) { t.Fatalf("Directory must be removed after test finished, have err: %v", err) } } + +func TestTempFile(t *testing.T) { + var file string + t.Run("subtest", func(t *testing.T) { + e := fixenv.New(t) + file := TempFile(e) + if _, err := os.Stat(file); err != nil { + t.Fatal(err) + } + }) + + _, err := os.Stat(file) + if !os.IsNotExist(err) { + t.Fatal("File must be removed with temp directory") + } +}