func (s *hookManagerSuite) TestHookTask(c *C) { // Register a handler generator for the "test-hook" hook var calledContext *hookstate.Context mockHandler := hooktest.NewMockHandler() mockHandlerGenerator := func(context *hookstate.Context) hookstate.Handler { calledContext = context return mockHandler } s.manager.Register(regexp.MustCompile("test-hook"), mockHandlerGenerator) s.manager.Ensure() s.manager.Wait() s.state.Lock() defer s.state.Unlock() c.Assert(calledContext, NotNil, Commentf("Expected handler generator to be called with a valid context")) c.Check(calledContext.SnapName(), Equals, "test-snap") c.Check(calledContext.SnapRevision(), Equals, snap.R(1)) c.Check(calledContext.HookName(), Equals, "test-hook") c.Check(s.command.Calls(), DeepEquals, [][]string{{ "snap", "run", "--hook", "test-hook", "-r", "1", "test-snap", }}) c.Check(mockHandler.BeforeCalled, Equals, true) c.Check(mockHandler.DoneCalled, Equals, true) c.Check(mockHandler.ErrorCalled, Equals, false) c.Check(s.task.Kind(), Equals, "run-hook") c.Check(s.task.Status(), Equals, state.DoneStatus) c.Check(s.change.Status(), Equals, state.DoneStatus) }
// ContextTransaction retrieves the transaction cached within the context (and // creates one if it hasn't already been cached). func ContextTransaction(context *hookstate.Context) *Transaction { // Check for one already cached transaction, ok := context.Cached(cachedTransaction{}).(*Transaction) if ok { return transaction } // It wasn't already cached, so create and cache a new one transaction = NewTransaction(context.State()) context.OnDone(func() error { transaction.Commit() return nil }) context.Cache(cachedTransaction{}, transaction) return transaction }
func getTransaction(context *hookstate.Context) (*configstate.Transaction, error) { context.Lock() defer context.Unlock() // Extract the transaction from the context. If none, make one and cache it // in the context. transaction, ok := context.Cached(cachedTransaction{}).(*configstate.Transaction) if !ok { var err error transaction, err = configstate.NewTransaction(context.State()) if err != nil { return nil, fmt.Errorf("cannot create transaction: %s", err) } context.OnDone(func() error { transaction.Commit() return nil }) context.Cache(cachedTransaction{}, transaction) } return transaction, nil }