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