github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/testing/cmdblockhelper.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package testing
     5  
     6  import (
     7  	"strings"
     8  
     9  	"github.com/juju/errors"
    10  	jc "github.com/juju/testing/checkers"
    11  	gc "gopkg.in/check.v1"
    12  
    13  	"github.com/juju/juju/api/base"
    14  	"github.com/juju/juju/api/client/block"
    15  )
    16  
    17  // CmdBlockHelper is a helper struct used to block commands.
    18  type CmdBlockHelper struct {
    19  	blockClient *block.Client
    20  }
    21  
    22  // NewCmdBlockHelper creates a block switch used in testing
    23  // to manage desired juju blocks.
    24  func NewCmdBlockHelper(api base.APICallCloser) CmdBlockHelper {
    25  	return CmdBlockHelper{
    26  		blockClient: block.NewClient(api),
    27  	}
    28  }
    29  
    30  // on switches on desired block and
    31  // asserts that no errors were encountered.
    32  func (s *CmdBlockHelper) on(c *gc.C, blockType, msg string) {
    33  	c.Assert(s.blockClient.SwitchBlockOn(blockType, msg), gc.IsNil)
    34  }
    35  
    36  // BlockAllChanges switches changes block on.
    37  // This prevents all changes to juju environment.
    38  func (s *CmdBlockHelper) BlockAllChanges(c *gc.C, msg string) {
    39  	s.on(c, "BlockChange", msg)
    40  }
    41  
    42  // BlockRemoveObject switches remove block on.
    43  // This prevents any object/entity removal on juju environment
    44  func (s *CmdBlockHelper) BlockRemoveObject(c *gc.C, msg string) {
    45  	s.on(c, "BlockRemove", msg)
    46  }
    47  
    48  // BlockDestroyModel switches destroy block on.
    49  // This prevents juju environment destruction.
    50  func (s *CmdBlockHelper) BlockDestroyModel(c *gc.C, msg string) {
    51  	s.on(c, "BlockDestroy", msg)
    52  }
    53  
    54  func (s *CmdBlockHelper) Close() {
    55  	s.blockClient.Close()
    56  }
    57  
    58  // AssertBlocked is going to be removed as soon as all cmd tests mock out API.
    59  // the corect method to call will become AssertOperationWasBlocked.
    60  func (s *CmdBlockHelper) AssertBlocked(c *gc.C, err error, msg string) {
    61  	if err == nil {
    62  		c.Fail()
    63  	}
    64  	c.Assert(err.Error(), jc.Contains, "disabled")
    65  	stripped := strings.Replace(c.GetTestLog(), "\n", "", -1)
    66  	c.Check(stripped, gc.Matches, msg)
    67  }
    68  
    69  func AssertOperationWasBlocked(c *gc.C, err error, msg string) {
    70  	c.Assert(err.Error(), jc.Contains, "disabled", gc.Commentf("%s", errors.Details(err)))
    71  	// msg is logged
    72  	stripped := strings.Replace(c.GetTestLog(), "\n", "", -1)
    73  	c.Check(stripped, gc.Matches, msg)
    74  	c.Check(stripped, jc.Contains, "disabled")
    75  }