From 1e1bbcd3d9c54948de640845918cfd04a79d36e8 Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Mon, 27 Jul 2020 13:46:24 +0000 Subject: [PATCH] env uses layers --- doc.go | 7 +++++++ env.go | 32 +++++++++++++++++++------------- env_test.go | 9 +++++---- runner.go | 1 - 4 files changed, 31 insertions(+), 18 deletions(-) create mode 100644 doc.go delete mode 100644 runner.go diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..d90115d --- /dev/null +++ b/doc.go @@ -0,0 +1,7 @@ +/* + + Package tea provides a tree structure for writing stateful tests, such that + child tests may utilize the side-effects of their ancestors. + +*/ +package tea diff --git a/env.go b/env.go index 7c857c9..33cdf43 100644 --- a/env.go +++ b/env.go @@ -6,8 +6,7 @@ import ( ) type env struct { - key string - value interface{} + data map[string]interface{} parent *env } @@ -17,7 +16,8 @@ func mkenv(test Test) *env { } // save looks at the Test t and saves the values of its fields marked with a -// save tag +// save tag. All of the fields for that tests are stored together as a data +// layer. func (e *env) save(test Test) *env { V := reflect.ValueOf(test) if V.Type().Kind() == reflect.Ptr { @@ -25,6 +25,7 @@ func (e *env) save(test Test) *env { } T := V.Type() + saved := make(map[string]interface{}) for i := 0; i < T.NumField(); i++ { f := T.Field(i) if !isSaveField(f) { @@ -32,9 +33,11 @@ func (e *env) save(test Test) *env { } fv := V.Field(i) - e = &env{ - key: f.Name, - value: fv.Interface(), + saved[f.Name] = fv.Interface() + } + if len(saved) > 0 { + return &env{ + data: saved, parent: e, } } @@ -55,13 +58,16 @@ func (e *env) load(dest Test) error { set := false for e := e; e != nil; e = e.parent { - if e.key == f.Name { - ev := reflect.ValueOf(e.value) - if ev.Type().AssignableTo(fv.Type()) { - set = true - fv.Set(ev) - break - } + v, ok := e.data[f.Name] + if !ok { + continue + } + + ev := reflect.ValueOf(v) + if ev.Type().AssignableTo(fv.Type()) { + set = true + fv.Set(ev) + break } } diff --git a/env_test.go b/env_test.go index 433b707..0f01526 100644 --- a/env_test.go +++ b/env_test.go @@ -41,12 +41,13 @@ func TestSave(t *testing.T) { t.Fatalf("saw nil env when expecting a valid env") } - if e.key != "Foo" { - t.Errorf("expected key %q but saw %q instead", "Foo", e.key) + foo, ok := e.data["Foo"] + if !ok { + t.Errorf("expected field Foo to be saved but was not saved") } - if e.value != 5 { - t.Errorf("expected value %v but saw %v instead", 5, e.value) + if foo != 5 { + t.Errorf("expected value %v but saw %v instead", 5, foo) } }) diff --git a/runner.go b/runner.go deleted file mode 100644 index f9164ac..0000000 --- a/runner.go +++ /dev/null @@ -1 +0,0 @@ -package tea