github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/utils/ssh/testing/fakessh.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package testing
     5  
     6  import (
     7  	"fmt"
     8  	"io/ioutil"
     9  	"path/filepath"
    10  
    11  	gc "launchpad.net/gocheck"
    12  
    13  	"launchpad.net/juju-core/testing/testbase"
    14  )
    15  
    16  // sshscript should only print the result on the first execution,
    17  // to handle the case where it's called multiple times. On
    18  // subsequent executions, it should find the next 'ssh' in $PATH
    19  // and exec that.
    20  var sshscript = `#!/bin/bash --norc
    21  if [ ! -e "$0.run" ]; then
    22      touch "$0.run"
    23      if [ -e "$0.expected-input" ]; then
    24          diff "$0.expected-input" -
    25          exitcode=$?
    26          if [ $exitcode -ne 0 ]; then
    27              echo "ERROR: did not match expected input" >&2
    28              exit $exitcode
    29          fi
    30          else
    31              head >/dev/null
    32          fi
    33      # stdout
    34      %s
    35      # stderr
    36      %s
    37      exit %d
    38  else
    39      export PATH=${PATH#*:}
    40      exec ssh $*
    41  fi`
    42  
    43  // InstallFakeSSH creates a fake "ssh" command in a new $PATH,
    44  // updates $PATH, and returns a function to reset $PATH to its
    45  // original value when called.
    46  //
    47  // input may be:
    48  //    - nil (ignore input)
    49  //    - a string (match input exactly)
    50  // output may be:
    51  //    - nil (no output)
    52  //    - a string (stdout)
    53  //    - a slice of strings, of length two (stdout, stderr)
    54  func InstallFakeSSH(c *gc.C, input, output interface{}, rc int) testbase.Restorer {
    55  	fakebin := c.MkDir()
    56  	ssh := filepath.Join(fakebin, "ssh")
    57  	switch input := input.(type) {
    58  	case nil:
    59  	case string:
    60  		sshexpectedinput := ssh + ".expected-input"
    61  		err := ioutil.WriteFile(sshexpectedinput, []byte(input), 0644)
    62  		c.Assert(err, gc.IsNil)
    63  	default:
    64  		c.Errorf("input has invalid type: %T", input)
    65  	}
    66  	var stdout, stderr string
    67  	switch output := output.(type) {
    68  	case nil:
    69  	case string:
    70  		stdout = fmt.Sprintf("cat<<EOF\n%s\nEOF", output)
    71  	case []string:
    72  		c.Assert(output, gc.HasLen, 2)
    73  		stdout = fmt.Sprintf("cat<<EOF\n%s\nEOF", output[0])
    74  		stderr = fmt.Sprintf("cat>&2<<EOF\n%s\nEOF", output[1])
    75  	}
    76  	script := fmt.Sprintf(sshscript, stdout, stderr, rc)
    77  	err := ioutil.WriteFile(ssh, []byte(script), 0777)
    78  	c.Assert(err, gc.IsNil)
    79  	return testbase.PatchEnvPathPrepend(fakebin)
    80  }