github.com/kat-co/cmd@v0.0.0-20140616103059-5da365f9d57e/util_test.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package cmd_test
     5  
     6  import (
     7  	"bytes"
     8  	"errors"
     9  	"fmt"
    10  	"io"
    11  
    12  	"launchpad.net/gnuflag"
    13  
    14  	"github.com/juju/cmd"
    15  )
    16  
    17  func bufferString(stream io.Writer) string {
    18  	return stream.(*bytes.Buffer).String()
    19  }
    20  
    21  // TestCommand is used by several different tests.
    22  type TestCommand struct {
    23  	cmd.CommandBase
    24  	Name    string
    25  	Option  string
    26  	Minimal bool
    27  	Aliases []string
    28  }
    29  
    30  func (c *TestCommand) Info() *cmd.Info {
    31  	if c.Minimal {
    32  		return &cmd.Info{Name: c.Name}
    33  	}
    34  	return &cmd.Info{
    35  		Name:    c.Name,
    36  		Args:    "<something>",
    37  		Purpose: c.Name + " the juju",
    38  		Doc:     c.Name + "-doc",
    39  		Aliases: c.Aliases,
    40  	}
    41  }
    42  
    43  func (c *TestCommand) SetFlags(f *gnuflag.FlagSet) {
    44  	if !c.Minimal {
    45  		f.StringVar(&c.Option, "option", "", "option-doc")
    46  	}
    47  }
    48  
    49  func (c *TestCommand) Init(args []string) error {
    50  	return cmd.CheckEmpty(args)
    51  }
    52  
    53  func (c *TestCommand) Run(ctx *cmd.Context) error {
    54  	switch c.Option {
    55  	case "error":
    56  		return errors.New("BAM!")
    57  	case "silent-error":
    58  		return cmd.ErrSilent
    59  	case "echo":
    60  		_, err := io.Copy(ctx.Stdout, ctx.Stdin)
    61  		return err
    62  	default:
    63  		fmt.Fprintln(ctx.Stdout, c.Option)
    64  	}
    65  	return nil
    66  }
    67  
    68  // minimalHelp and fullHelp are the expected help strings for a TestCommand
    69  // with Name "verb", with and without Minimal set.
    70  var minimalHelp = "usage: verb\n"
    71  var optionHelp = `usage: verb [options] <something>
    72  purpose: verb the juju
    73  
    74  options:
    75  --option (= "")
    76      option-doc
    77  `
    78  var fullHelp = `usage: verb [options] <something>
    79  purpose: verb the juju
    80  
    81  options:
    82  --option (= "")
    83      option-doc
    84  
    85  verb-doc
    86  `