gopkg.in/goose.v2@v2.0.1/testservices/hook/service_test.go (about) 1 package hook 2 3 import ( 4 "fmt" 5 "testing" 6 7 gc "gopkg.in/check.v1" 8 ) 9 10 func Test(t *testing.T) { 11 gc.TestingT(t) 12 } 13 14 var _ = gc.Suite(&ServiceSuite{}) 15 16 type ServiceSuite struct { 17 ts *testService 18 } 19 20 func (s *ServiceSuite) SetUpTest(c *gc.C) { 21 s.ts = newTestService() 22 // This hook is called based on the function name. 23 s.ts.RegisterControlPoint("foo", functionControlHook) 24 // This hook is called based on a user specified hook name. 25 s.ts.RegisterControlPoint("foobar", namedControlHook) 26 } 27 28 type testService struct { 29 TestService 30 label string 31 } 32 33 func newTestService() *testService { 34 return &testService{ 35 TestService: TestService{ 36 ControlHooks: make(map[string]ControlProcessor), 37 }, 38 } 39 } 40 41 func functionControlHook(s ServiceControl, args ...interface{}) error { 42 label := args[0].(string) 43 returnError := args[1].(bool) 44 if returnError { 45 return fmt.Errorf("An error occurred") 46 } 47 s.(*testService).label = label 48 return nil 49 } 50 51 func namedControlHook(s ServiceControl, args ...interface{}) error { 52 s.(*testService).label = "foobar" 53 return nil 54 } 55 56 func (s *testService) foo(label string, returnError bool) error { 57 if err := s.ProcessFunctionHook(s, label, returnError); err != nil { 58 return err 59 } 60 return nil 61 } 62 63 func (s *testService) bar() error { 64 if err := s.ProcessControlHook("foobar", s); err != nil { 65 return err 66 } 67 return nil 68 } 69 70 func (s *ServiceSuite) TestFunctionHookNoError(c *gc.C) { 71 err := s.ts.foo("success", false) 72 c.Assert(err, gc.IsNil) 73 c.Assert(s.ts.label, gc.Equals, "success") 74 } 75 76 func (s *ServiceSuite) TestHookWithError(c *gc.C) { 77 err := s.ts.foo("success", true) 78 c.Assert(err, gc.Not(gc.IsNil)) 79 c.Assert(s.ts.label, gc.Equals, "") 80 } 81 82 func (s *ServiceSuite) TestNamedHook(c *gc.C) { 83 err := s.ts.bar() 84 c.Assert(err, gc.IsNil) 85 c.Assert(s.ts.label, gc.Equals, "foobar") 86 } 87 88 func (s *ServiceSuite) TestHookCleanup(c *gc.C) { 89 // Manually delete the existing control point. 90 s.ts.RegisterControlPoint("foo", nil) 91 // Register a new hook and ensure it works. 92 cleanup := s.ts.RegisterControlPoint("foo", functionControlHook) 93 err := s.ts.foo("cleanuptest", false) 94 c.Assert(err, gc.IsNil) 95 c.Assert(s.ts.label, gc.Equals, "cleanuptest") 96 // Use the cleanup func to remove the hook and check the result. 97 cleanup() 98 err = s.ts.foo("again", false) 99 c.Assert(err, gc.IsNil) 100 c.Assert(s.ts.label, gc.Equals, "cleanuptest") 101 // Ensure that only the specified hook was removed and the other remaining one still works. 102 err = s.ts.bar() 103 c.Assert(err, gc.IsNil) 104 c.Assert(s.ts.label, gc.Equals, "foobar") 105 106 }