github.com/dahs81/otto@v0.2.1-0.20160126165905-6400716cf085/helper/compile/app_testing.go (about) 1 package compile 2 3 import ( 4 "fmt" 5 "reflect" 6 "sync" 7 8 "github.com/hashicorp/otto/otto" 9 ) 10 11 var testLock sync.RWMutex 12 var testOn bool 13 var testAppOpts *AppOptions 14 15 // AppTest enables/disables test mode for the compilation package. When 16 // test mode is enabled, the test steps can be used to make assertions about 17 // the compilation process. 18 // 19 // Always be sure to defer and disable this. 20 // 21 // This should not be used outside of tests. Within tests, this cannot 22 // be parallelized since it uses global state. 23 func AppTest(on bool) { 24 testLock.Lock() 25 defer testLock.Unlock() 26 27 testOn = on 28 } 29 30 // AppTestStepContext is an otto.TestStep that tests the value of something 31 // in the template context. 32 type AppTestStepContext struct { 33 Key string 34 Value interface{} 35 } 36 37 func (s *AppTestStepContext) Run(c *otto.Core) error { 38 testLock.RLock() 39 defer testLock.RUnlock() 40 41 if testAppOpts == nil { 42 return fmt.Errorf("no context") 43 } 44 45 ctx := testAppOpts.Bindata.Context 46 if ctx == nil { 47 return fmt.Errorf("no context") 48 } 49 50 value, ok := ctx[s.Key] 51 if !ok || !reflect.DeepEqual(value, s.Value) { 52 return fmt.Errorf("bad value for '%s': %#v", s.Key, value) 53 } 54 55 return nil 56 }