github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/packer/communicator_mock.go (about)

     1  package packer
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"sync"
     8  )
     9  
    10  // MockCommunicator is a valid Communicator implementation that can be
    11  // used for tests.
    12  type MockCommunicator struct {
    13  	StartCalled     bool
    14  	StartCmd        *RemoteCmd
    15  	StartStderr     string
    16  	StartStdout     string
    17  	StartStdin      string
    18  	StartExitStatus int
    19  
    20  	UploadCalled bool
    21  	UploadPath   string
    22  	UploadData   string
    23  
    24  	UploadDirDst     string
    25  	UploadDirSrc     string
    26  	UploadDirExclude []string
    27  
    28  	DownloadCalled bool
    29  	DownloadPath   string
    30  	DownloadData   string
    31  }
    32  
    33  func (c *MockCommunicator) Start(rc *RemoteCmd) error {
    34  	c.StartCalled = true
    35  	c.StartCmd = rc
    36  
    37  	go func() {
    38  		var wg sync.WaitGroup
    39  		if rc.Stdout != nil && c.StartStdout != "" {
    40  			wg.Add(1)
    41  			go func() {
    42  				rc.Stdout.Write([]byte(c.StartStdout))
    43  				wg.Done()
    44  			}()
    45  		}
    46  
    47  		if rc.Stderr != nil && c.StartStderr != "" {
    48  			wg.Add(1)
    49  			go func() {
    50  				rc.Stderr.Write([]byte(c.StartStderr))
    51  				wg.Done()
    52  			}()
    53  		}
    54  
    55  		if rc.Stdin != nil {
    56  			wg.Add(1)
    57  			go func() {
    58  				defer wg.Done()
    59  				var data bytes.Buffer
    60  				io.Copy(&data, rc.Stdin)
    61  				c.StartStdin = data.String()
    62  			}()
    63  		}
    64  
    65  		wg.Wait()
    66  		rc.SetExited(c.StartExitStatus)
    67  	}()
    68  
    69  	return nil
    70  }
    71  
    72  func (c *MockCommunicator) Upload(path string, r io.Reader, fi *os.FileInfo) error {
    73  	c.UploadCalled = true
    74  	c.UploadPath = path
    75  
    76  	var data bytes.Buffer
    77  	if _, err := io.Copy(&data, r); err != nil {
    78  		panic(err)
    79  	}
    80  
    81  	c.UploadData = data.String()
    82  
    83  	return nil
    84  }
    85  
    86  func (c *MockCommunicator) UploadDir(dst string, src string, excl []string) error {
    87  	c.UploadDirDst = dst
    88  	c.UploadDirSrc = src
    89  	c.UploadDirExclude = excl
    90  
    91  	return nil
    92  }
    93  
    94  func (c *MockCommunicator) Download(path string, w io.Writer) error {
    95  	c.DownloadCalled = true
    96  	c.DownloadPath = path
    97  	w.Write([]byte(c.DownloadData))
    98  
    99  	return nil
   100  }