diff --git a/env.go b/env.go index e66c7ca..e1e1e7f 100644 --- a/env.go +++ b/env.go @@ -299,7 +299,10 @@ func (e *EnvT) fixtureCallWrapper(key cacheKey, f FixtureCallbackFunc, opt *Fixt e.m.Unlock() if si == nil { - e.t.Fatalf("Unexpected scope. Create env for test %q", scopeName) + if opt.Scope == ScopePackage { + e.t.Fatalf("Initialize package scope before use ", scopeName) + } + e.t.Fatalf("Unexpected scope: %q", scopeName) // not reachable return nil, nil } diff --git a/examples/simple_main_test/example_test.go b/examples/simple_main_test/example_test.go new file mode 100644 index 0000000..2cb2f0f --- /dev/null +++ b/examples/simple_main_test/example_test.go @@ -0,0 +1,38 @@ +package simple_main_test + +import ( + "github.com/rekby/fixenv" + "math/rand" + "testing" +) + +var global int = -1 + +func FSingleRandom(e fixenv.Env) int { + var f fixenv.GenericFixtureFunction[int] = func() (*fixenv.GenericResult[int], error) { + return fixenv.NewGenericResult(rand.Int()), nil + } + return fixenv.CacheResult(e, f, fixenv.CacheOptions{Scope: fixenv.ScopePackage}) +} + +func TestFirst(t *testing.T) { + e := fixenv.New(t) + if global == -1 { + global = FSingleRandom(e) + } + + if singleRnd := FSingleRandom(e); singleRnd != global { + t.Fatalf("%v != %v", singleRnd, global) + } +} + +func TestSecond(t *testing.T) { + e := fixenv.New(t) + if global == -1 { + global = FSingleRandom(e) + } + + if singleRnd := FSingleRandom(e); singleRnd != global { + t.Fatalf("%v != %v", singleRnd, global) + } +} diff --git a/examples/simple_main_test/testmain_test.go b/examples/simple_main_test/testmain_test.go new file mode 100644 index 0000000..42580a0 --- /dev/null +++ b/examples/simple_main_test/testmain_test.go @@ -0,0 +1,11 @@ +package simple_main + +import ( + "github.com/rekby/fixenv" + "os" + "testing" +) + +func TestMain(m *testing.M) { + os.Exit(fixenv.RunTests(m)) +} diff --git a/maintest.go b/maintest.go index 9c54d51..61f0cf2 100644 --- a/maintest.go +++ b/maintest.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "sync" + "testing" ) // FatalfFunction function signature of Fatalf @@ -46,6 +47,30 @@ func CreateMainTestEnv(opts *CreateMainTestEnvOpts) (env *EnvT, tearDown func()) return env, packageLevelVirtualTest.cleanup } +// RunTests runs the tests. It returns an exit code to pass to os.Exit. +// +// Usage: +// declare in _test file TestMain function: +// +// func TestMain(m *testing.M) { +// os.Exit(fixenv.RunTests(m)) +// } +func RunTests(m *testing.M, opts ...*CreateMainTestEnvOpts) int { + var options *CreateMainTestEnvOpts + switch len(opts) { + case 0: + // pass + case 1: + options = opts[0] + default: + panic("allow not more then one optional arg") + } + + _, cancel := CreateMainTestEnv(options) + defer cancel() + return m.Run() +} + // virtualTest implement T interface for global env scope type virtualTest struct { m sync.Mutex